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
|
lcnhappe/happe-master
|
test_ft_preprocessing.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_preprocessing.m
| 2,987 |
utf_8
|
b83998ddf8d5db1bb3dbea7d4905cd8f
|
function test_ft_preprocessing(datainfo, writeflag, version)
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_ft_preprocessing
% TEST ft_preprocessing ref_datasets
% writeflag determines whether the output should be saved to disk
% version determines the output directory
if nargin<1
datainfo = ref_datasets;
end
if nargin<2
writeflag = 0;
end
if nargin<3
version = 'latest';
end
for k = 1:numel(datainfo)
datanew = preprocessing10trials(datainfo(k), writeflag, version);
fname = fullfile(datainfo(k).origdir,version,'raw',datainfo(k).type,['preproc_',datainfo(k).datatype]);
load(fname);
% these are per construction different if writeflag = 0;
datanew = rmfield(datanew, 'cfg');
data = rmfield(data, 'cfg');
% these can have subtle differences eg. in hdr.orig.FID
data.hdr = [];
datanew2 = datanew;
datanew2.hdr = [];
% do the comparison with the header removed, the output argument still contains the header
assert(isequaln(data, datanew2));
end
%----------------------------------------------------------
% subfunction to read in 10 trials of data
%----------------------------------------------------------
function [data] = preprocessing10trials(dataset, writeflag, version)
% --- HISTORICAL --- attempt forward compatibility with function handles
if ~exist('ft_preprocessing') && exist('preprocessing')
eval('ft_preprocessing = @preprocessing;');
end
if ~exist('ft_read_header') && exist('read_header')
eval('ft_read_header = @read_header;');
elseif ~exist('ft_read_header') && exist('read_fcdc_header')
eval('ft_read_header = @read_fcdc_header;');
end
if ~exist('ft_read_event') && exist('read_event')
eval('ft_read_event = @read_event;');
elseif ~exist('ft_read_event') && exist('read_fcdc_event')
eval('ft_read_event = @read_fcdc_event;');
end
cfg = [];
cfg.dataset = fullfile(dataset.origdir,'original',dataset.type,dataset.datatype,'/',dataset.filename);
if writeflag,
cfg.outputfile = fullfile(dataset.origdir,version,'raw',dataset.type,['preproc_',dataset.datatype '.mat']);
end
% get header and event information
if ~isempty(dataset.dataformat)
hdr = ft_read_header(cfg.dataset, 'headerformat', dataset.dataformat);
event = ft_read_event(cfg.dataset, 'eventformat', dataset.dataformat);
cfg.dataformat = dataset.dataformat;
cfg.headerformat = dataset.dataformat;
else
hdr = ft_read_header(cfg.dataset);
event = ft_read_event(cfg.dataset);
end
% create 10 1-second trials to be used as test-case
begsample = ((1:10)-1)*round(hdr.Fs) + 1;
endsample = ((1:10) )*round(hdr.Fs);
offset = zeros(1,10);
cfg.trl = [begsample(:) endsample(:) offset(:)];
sel = cfg.trl(:,2)<=hdr.nSamples*hdr.nTrials;
cfg.trl = cfg.trl(sel,:);
cfg.continuous = 'yes';
data = ft_preprocessing(cfg);
if ~strcmp(version, 'latest') && str2num(version)<20100000
% -- HISTORICAL --- older FieldTrip versions don't support outputfile
save(cfg.outputfile, 'data');
end
|
github
|
lcnhappe/happe-master
|
test_bug2377b.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_bug2377b.m
| 3,684 |
utf_8
|
6609cf02d809a7ed643457946040bee9
|
function test_bug2377b
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_bug2377b
% TEST ft_senslabel ft_senstype ft_chantype ft_chanunit ft_datatype_sens
[pnt, tri] = icosahedron162;
pnt = pnt .* 10; % convert to cm
sel = find(pnt(:,3)>0); % take the upper hemisphere
nchan = length(sel); % there are 71 channels remaining
sens = [];
sens.elecpos = pnt(sel,:);
sens.unit = 'cm';
lab = ft_senslabel('eeg1010'); % take the channel names from this set
% perform the test sequence for a sensor array with 10-20 channel labels
sens.label = lab(1:nchan);
perform_actual_test(sens)
for i=1:nchan
lab{i} = sprintf('ch%02d', i);
end
% perform the test sequence for a sensor array with unkown labels
sens.label = lab(1:nchan);
perform_actual_test(sens)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function perform_actual_test(sens)
nchan = length(sens.label);
% without most new fields
sens0 = sens;
% with manual chantype
sens.chantype = repmat({'eeg'}, nchan, 1);
sens1 = sens;
% with automatic chantype
sens.chantype = ft_chantype(sens);
sens2 = sens;
% with manual chanunit
sens.chanunit = repmat({'V'}, nchan, 1);
sens3 = sens;
% with automatic chanunit
sens.chanunit = ft_chanunit(sens);
sens4 = sens;
% with a tra
sens.tra = eye(numel(sens.label));
sens5 = sens;
%%
sens0a = ft_datatype_sens(sens0, 'version', 'upcoming');
sens1a = ft_datatype_sens(sens1, 'version', 'upcoming');
sens2a = ft_datatype_sens(sens2, 'version', 'upcoming');
sens3a = ft_datatype_sens(sens3, 'version', 'upcoming');
sens4a = ft_datatype_sens(sens4, 'version', 'upcoming');
sens5a = ft_datatype_sens(sens5, 'version', 'upcoming');
% not all of them have the tra field
assert(isequal(tryrmfield(sens0a, 'tra'), tryrmfield(sens1a, 'tra')));
assert(isequal(tryrmfield(sens0a, 'tra'), tryrmfield(sens2a, 'tra')));
assert(isequal(tryrmfield(sens0a, 'tra'), tryrmfield(sens3a, 'tra')));
assert(isequal(tryrmfield(sens0a, 'tra'), tryrmfield(sens4a, 'tra')));
assert(isequal(tryrmfield(sens0a, 'tra'), tryrmfield(sens5a, 'tra')));
%%
montage = [];
montage.labelorg = sens.label;
montage.labelnew = montage.labelorg;
montage.tra = detrend(eye(nchan), 'constant');
sens0b = ft_apply_montage(sens0, montage);
sens1b = ft_apply_montage(sens1, montage);
sens2b = ft_apply_montage(sens2, montage);
sens3b = ft_apply_montage(sens3, montage);
sens4b = ft_apply_montage(sens4, montage);
sens5b = ft_apply_montage(sens5, montage);
%%
sens0c = ft_datatype_sens(sens0b, 'version', 'upcoming', 'amplitude', 'uV', 'distance', 'mm');
sens1c = ft_datatype_sens(sens1b, 'version', 'upcoming', 'amplitude', 'uV', 'distance', 'mm');
sens2c = ft_datatype_sens(sens2b, 'version', 'upcoming', 'amplitude', 'uV', 'distance', 'mm');
sens3c = ft_datatype_sens(sens3b, 'version', 'upcoming', 'amplitude', 'uV', 'distance', 'mm');
sens4c = ft_datatype_sens(sens4b, 'version', 'upcoming', 'amplitude', 'uV', 'distance', 'mm');
sens5c = ft_datatype_sens(sens5b, 'version', 'upcoming', 'amplitude', 'uV', 'distance', 'mm');
% they should have all fields by now
assert(isequal(sens0c, sens1c));
assert(isequal(sens0c, sens2c));
assert(isequal(sens0c, sens3c));
assert(isequal(sens0c, sens4c));
assert(isequal(sens0c, sens5c));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = tryrmfield(s, f)
if isfield(s, f)
s = rmfield(s, f);
end
|
github
|
lcnhappe/happe-master
|
test_bug1786.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_bug1786.m
| 28,790 |
utf_8
|
888eea2bc9b55eb9bbd83a5d3f474e8d
|
function test_bug1786
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_bug1786
% TEST ft_channelrepair ft_prepare_neighbours
% Original report:
% Hello,
%
% When I run sphericalSplineInterpolate.m on my data it gets stuck on line 55 at:
% "iC = pinv(C);".
%
% Thanks
% Yoel
%
% http://bugzilla.fcdonders.nl/show_bug.cgi?id=1786
% EEG bad electrode repair
% requires fieldtrip
%
% input format:
% labels - 1XN cell array
% badchans - 1XB cell array eg. {'O2', 'Fp2'}
% data - MXN array
% function fixedelec = fixelec(labels, badchans,data)
% error(nargchk(3, 3, nargin));
load /home/common/matlab/fieldtrip/data/test/bug1786.mat
labels = electrodes_names_to_keep;
badchans = interpolate_at_z;
data = z1;
% transpose data to lab style
data = data';
badchans = badchans';
eeglabels = {'Fp1','Fp2','F7','F3','Fz','F4','F8','T3','C3','Cz','C4','T4','T5','P3','Pz','P4','T6','O1','O2'};
% generating neighbours map (only locations are needed for spline)
[s,elec.elecpos] = elec_1020select(eeglabels);
elec.label = eeglabels;
elec.chanpos = elec.elecpos;
elec.tra = eye(length(eeglabels));
cfg.method = 'triangulation';
cfg.elec = elec;
%ndata = data;
ndata.label = eeglabels;
neighbours = ft_prepare_neighbours(cfg, ndata);
% converting data to proper format
% l = length(data);
% for i=1:length(eeglabels)
% trial(i,:) = data(find(cell2mat(cellfun(@ (x) strcmp(x,eeglabels(i)),labels,'UniformOutput',0))),:);
% end
% data = [];
% data.trial = {trial};
% data.elec = elec;
% data.label = eeglabels;
% data.time = {[1:l]};
ft_data.trial{1} = data;
ft_data.elec = elec;
ft_data.label = eeglabels;
ft_data.time = {[1:length(data)]};
% fixing bad channels
cfg = [];
cfg.method = 'spline';
cfg.badchannel = badchans;
cfg.neighbours = neighbours;
repaired = ft_channelrepair(cfg, ft_data);
fixedelec = cell2mat(repaired.trial);
end
function [elec] = elec_1020all_cart
% elec_1020all_cart - all 10-20 electrode Cartesian coordinates
%
% [elec] = elec_1020all_cart
%
% elec is a struct array with fields:
%
% elec.labels
% elec.X
% elec.Y
% elec.Z
%
% We gratefully acknowledge the provision of this data from
% Robert Oostenveld. The elec struct contains all channel names and
% locations for the International 10-20 electrode placement system, please
% see details in:
%
% Oostenveld, R. & Praamstra, P. (2001). The five percent electrode system
% for high-resolution EEG and ERP measurements. Clinical Neurophysiology,
% 112:713-719.
%
% $Revision$ $Date: 2009-01-30 03:49:27 $
% Copyright (C) 2005 Darren L. Weber
%
% 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 (at your option) 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 Place - Suite 330, Boston, MA 02111-1307, USA.
% Modified: 02/2004, Darren.Weber_at_radiology.ucsf.edu
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ver = '$Revision$ $Date: 2009-01-30 03:49:27 $';
fprintf('\nELEC_1020ALL_CART [v %s]\n',ver(11:15));
names = {'LPA','RPA','Nz','Fp1','Fpz','Fp2','AF9','AF7','AF5','AF3',...
'AF1','AFz','AF2','AF4','AF6','AF8','AF10','F9','F7','F5','F3','F1',...
'Fz','F2','F4','F6','F8','F10','FT9','FT7','FC5','FC3','FC1','FCz',...
'FC2','FC4','FC6','FT8','FT10','T9','T7','C5','C3','C1','Cz','C2',...
'C4','C6','T8','T10','TP9','TP7','CP5','CP3','CP1','CPz','CP2','CP4',...
'CP6','TP8','TP10','P9','P7','P5','P3','P1','Pz','P2','P4','P6','P8',...
'P10','PO9','PO7','PO5','PO3','PO1','POz','PO2','PO4','PO6','PO8',...
'PO10','O1','Oz','O2','I1','Iz','I2','AFp9h','AFp7h','AFp5h','AFp3h',...
'AFp1h','AFp2h','AFp4h','AFp6h','AFp8h','AFp10h','AFF9h','AFF7h',...
'AFF5h','AFF3h','AFF1h','AFF2h','AFF4h','AFF6h','AFF8h','AFF10h',...
'FFT9h','FFT7h','FFC5h','FFC3h','FFC1h','FFC2h','FFC4h','FFC6h',...
'FFT8h','FFT10h','FTT9h','FTT7h','FCC5h','FCC3h','FCC1h','FCC2h',...
'FCC4h','FCC6h','FTT8h','FTT10h','TTP9h','TTP7h','CCP5h','CCP3h',...
'CCP1h','CCP2h','CCP4h','CCP6h','TTP8h','TTP10h','TPP9h','TPP7h',...
'CPP5h','CPP3h','CPP1h','CPP2h','CPP4h','CPP6h','TPP8h','TPP10h',...
'PPO9h','PPO7h','PPO5h','PPO3h','PPO1h','PPO2h','PPO4h','PPO6h',...
'PPO8h','PPO10h','POO9h','POO7h','POO5h','POO3h','POO1h','POO2h',...
'POO4h','POO6h','POO8h','POO10h','OI1h','OI2h','Fp1h','Fp2h','AF9h',...
'AF7h','AF5h','AF3h','AF1h','AF2h','AF4h','AF6h','AF8h','AF10h',...
'F9h','F7h','F5h','F3h','F1h','F2h','F4h','F6h','F8h','F10h','FT9h',...
'FT7h','FC5h','FC3h','FC1h','FC2h','FC4h','FC6h','FT8h','FT10h',...
'T9h','T7h','C5h','C3h','C1h','C2h','C4h','C6h','T8h','T10h','TP9h',...
'TP7h','CP5h','CP3h','CP1h','CP2h','CP4h','CP6h','TP8h','TP10h',...
'P9h','P7h','P5h','P3h','P1h','P2h','P4h','P6h','P8h','P10h','PO9h',...
'PO7h','PO5h','PO3h','PO1h','PO2h','PO4h','PO6h','PO8h','PO10h','O1h',...
'O2h','I1h','I2h','AFp9','AFp7','AFp5','AFp3','AFp1','AFpz','AFp2',...
'AFp4','AFp6','AFp8','AFp10','AFF9','AFF7','AFF5','AFF3','AFF1',...
'AFFz','AFF2','AFF4','AFF6','AFF8','AFF10','FFT9','FFT7','FFC5',...
'FFC3','FFC1','FFCz','FFC2','FFC4','FFC6','FFT8','FFT10','FTT9',...
'FTT7','FCC5','FCC3','FCC1','FCCz','FCC2','FCC4','FCC6','FTT8',...
'FTT10','TTP9','TTP7','CCP5','CCP3','CCP1','CCPz','CCP2','CCP4',...
'CCP6','TTP8','TTP10','TPP9','TPP7','CPP5','CPP3','CPP1','CPPz',...
'CPP2','CPP4','CPP6','TPP8','TPP10','PPO9','PPO7','PPO5','PPO3',...
'PPO1','PPOz','PPO2','PPO4','PPO6','PPO8','PPO10','POO9','POO7',...
'POO5','POO3','POO1','POOz','POO2','POO4','POO6','POO8','POO10',...
'OI1','OIz','OI2','T3','T5','T4','T6'};
xyz = [ ...
0.0000 0.9237 -0.3826 ;
0.0000 -0.9237 -0.3826 ;
0.9230 0.0000 -0.3824 ;
0.9511 0.3090 0.0001 ;
1.0000 0.0000 0.0001 ;
0.9511 -0.3091 0.0000 ;
0.7467 0.5425 -0.3825 ;
0.8090 0.5878 0.0000 ;
0.8553 0.4926 0.1552 ;
0.8920 0.3554 0.2782 ;
0.9150 0.1857 0.3558 ;
0.9230 0.0000 0.3824 ;
0.9150 -0.1857 0.3558 ;
0.8919 -0.3553 0.2783 ;
0.8553 -0.4926 0.1552 ;
0.8090 -0.5878 0.0000 ;
0.7467 -0.5425 -0.3825 ;
0.5430 0.7472 -0.3826 ;
0.5878 0.8090 0.0000 ;
0.6343 0.7210 0.2764 ;
0.6726 0.5399 0.5043 ;
0.6979 0.2888 0.6542 ;
0.7067 0.0000 0.7067 ;
0.6979 -0.2888 0.6542 ;
0.6726 -0.5399 0.5043 ;
0.6343 -0.7210 0.2764 ;
0.5878 -0.8090 0.0000 ;
0.5429 -0.7472 -0.3826 ;
0.2852 0.8777 -0.3826 ;
0.3090 0.9511 0.0000 ;
0.3373 0.8709 0.3549 ;
0.3612 0.6638 0.6545 ;
0.3770 0.3581 0.8532 ;
0.3826 0.0000 0.9233 ;
0.3770 -0.3581 0.8532 ;
0.3612 -0.6638 0.6545 ;
0.3373 -0.8709 0.3549 ;
0.3090 -0.9511 0.0000 ;
0.2852 -0.8777 -0.3826 ;
-0.0001 0.9237 -0.3826 ;
0.0000 1.0000 0.0000 ;
0.0001 0.9237 0.3826 ;
0.0001 0.7066 0.7066 ;
0.0002 0.3824 0.9231 ;
0.0002 0.0000 1.0000 ;
0.0001 -0.3824 0.9231 ;
0.0001 -0.7066 0.7066 ;
0.0001 -0.9237 0.3826 ;
0.0000 -1.0000 0.0000 ;
0.0000 -0.9237 -0.3826 ;
-0.2852 0.8777 -0.3826 ;
-0.3090 0.9511 -0.0001 ;
-0.3372 0.8712 0.3552 ;
-0.3609 0.6635 0.6543 ;
-0.3767 0.3580 0.8534 ;
-0.3822 0.0000 0.9231 ;
-0.3767 -0.3580 0.8534 ;
-0.3608 -0.6635 0.6543 ;
-0.3372 -0.8712 0.3552 ;
-0.3090 -0.9511 -0.0001 ;
-0.2853 -0.8777 -0.3826 ;
-0.5429 0.7472 -0.3826 ;
-0.5878 0.8090 -0.0001 ;
-0.6342 0.7211 0.2764 ;
-0.6724 0.5401 0.5045 ;
-0.6975 0.2889 0.6545 ;
-0.7063 0.0000 0.7065 ;
-0.6975 -0.2889 0.6545 ;
-0.6724 -0.5401 0.5045 ;
-0.6342 -0.7211 0.2764 ;
-0.5878 -0.8090 -0.0001 ;
-0.5429 -0.7472 -0.3826 ;
-0.7467 0.5425 -0.3825 ;
-0.8090 0.5878 0.0000 ;
-0.8553 0.4929 0.1555 ;
-0.8918 0.3549 0.2776 ;
-0.9151 0.1858 0.3559 ;
-0.9230 0.0000 0.3824 ;
-0.9151 -0.1859 0.3559 ;
-0.8918 -0.3549 0.2776 ;
-0.8553 -0.4929 0.1555 ;
-0.8090 -0.5878 0.0000 ;
-0.7467 -0.5425 -0.3825 ;
-0.9511 0.3090 0.0000 ;
-1.0000 0.0000 0.0000 ;
-0.9511 -0.3090 0.0000 ;
-0.8785 0.2854 -0.3824 ;
-0.9230 0.0000 -0.3823 ;
-0.8785 -0.2854 -0.3824 ;
0.8732 0.4449 -0.1949 ;
0.9105 0.4093 0.0428 ;
0.9438 0.3079 0.1159 ;
0.9669 0.1910 0.1666 ;
0.9785 0.0647 0.1919 ;
0.9785 -0.0647 0.1919 ;
0.9669 -0.1910 0.1666 ;
0.9438 -0.3079 0.1159 ;
0.9105 -0.4093 0.0428 ;
0.8732 -0.4449 -0.1949 ;
0.6929 0.6929 -0.1949 ;
0.7325 0.6697 0.1137 ;
0.7777 0.5417 0.3163 ;
0.8111 0.3520 0.4658 ;
0.8289 0.1220 0.5452 ;
0.8289 -0.1220 0.5452 ;
0.8111 -0.3520 0.4658 ;
0.7777 -0.5417 0.3163 ;
0.7325 -0.6697 0.1138 ;
0.6929 -0.6929 -0.1949 ;
0.4448 0.8730 -0.1950 ;
0.4741 0.8642 0.1647 ;
0.5107 0.7218 0.4651 ;
0.5384 0.4782 0.6925 ;
0.5533 0.1672 0.8148 ;
0.5533 -0.1672 0.8148 ;
0.5384 -0.4782 0.6925 ;
0.5107 -0.7218 0.4651 ;
0.4741 -0.8642 0.1647 ;
0.4448 -0.8730 -0.1950 ;
0.1533 0.9678 -0.1950 ;
0.1640 0.9669 0.1915 ;
0.1779 0.8184 0.5448 ;
0.1887 0.5466 0.8154 ;
0.1944 0.1919 0.9615 ;
0.1944 -0.1919 0.9615 ;
0.1887 -0.5466 0.8154 ;
0.1779 -0.8184 0.5448 ;
0.1640 -0.9669 0.1915 ;
0.1533 -0.9678 -0.1950 ;
-0.1532 0.9678 -0.1950 ;
-0.1639 0.9669 0.1915 ;
-0.1778 0.8185 0.5449 ;
-0.1883 0.5465 0.8153 ;
-0.1940 0.1918 0.9611 ;
-0.1940 -0.1918 0.9611 ;
-0.1884 -0.5465 0.8153 ;
-0.1778 -0.8185 0.5449 ;
-0.1639 -0.9669 0.1915 ;
-0.1533 -0.9678 -0.1950 ;
-0.4448 0.8731 -0.1950 ;
-0.4740 0.8639 0.1646 ;
-0.5106 0.7220 0.4653 ;
-0.5384 0.4786 0.6933 ;
-0.5532 0.1673 0.8155 ;
-0.5532 -0.1673 0.8155 ;
-0.5384 -0.4786 0.6933 ;
-0.5106 -0.7220 0.4653 ;
-0.4740 -0.8638 0.1646 ;
-0.4449 -0.8731 -0.1950 ;
-0.6928 0.6928 -0.1950 ;
-0.7324 0.6700 0.1139 ;
-0.7776 0.5420 0.3167 ;
-0.8108 0.3520 0.4659 ;
-0.8284 0.1220 0.5453 ;
-0.8284 -0.1220 0.5453 ;
-0.8108 -0.3519 0.4659 ;
-0.7775 -0.5421 0.3167 ;
-0.7324 -0.6700 0.1139 ;
-0.6928 -0.6928 -0.1950 ;
-0.8730 0.4448 -0.1950 ;
-0.9106 0.4097 0.0430 ;
-0.9438 0.3080 0.1160 ;
-0.9665 0.1908 0.1657 ;
-0.9783 0.0647 0.1918 ;
-0.9783 -0.0647 0.1918 ;
-0.9665 -0.1908 0.1657 ;
-0.9438 -0.3080 0.1160 ;
-0.9106 -0.4097 0.0430 ;
-0.8730 -0.4448 -0.1950 ;
-0.9679 0.1533 -0.1950 ;
-0.9679 -0.1533 -0.1950 ;
0.9877 0.1564 0.0001 ;
0.9877 -0.1564 0.0001 ;
0.7928 0.5759 -0.1949 ;
0.8332 0.5463 0.0810 ;
0.8750 0.4284 0.2213 ;
0.9053 0.2735 0.3231 ;
0.9211 0.0939 0.3758 ;
0.9210 -0.0939 0.3758 ;
0.9053 -0.2735 0.3231 ;
0.8750 -0.4284 0.2212 ;
0.8332 -0.5463 0.0810 ;
0.7927 -0.5759 -0.1949 ;
0.5761 0.7929 -0.1949 ;
0.6117 0.7772 0.1420 ;
0.6549 0.6412 0.3987 ;
0.6872 0.4214 0.5906 ;
0.7045 0.1468 0.6933 ;
0.7045 -0.1468 0.6933 ;
0.6872 -0.4214 0.5906 ;
0.6549 -0.6412 0.3987 ;
0.6117 -0.7772 0.1420 ;
0.5761 -0.7929 -0.1949 ;
0.3027 0.9317 -0.1950 ;
0.3235 0.9280 0.1813 ;
0.3500 0.7817 0.5146 ;
0.3703 0.5207 0.7687 ;
0.3811 0.1824 0.9054 ;
0.3811 -0.1824 0.9054 ;
0.3703 -0.5207 0.7687 ;
0.3500 -0.7817 0.5146 ;
0.3235 -0.9280 0.1813 ;
0.3028 -0.9317 -0.1950 ;
0.0000 0.9801 -0.1950 ;
0.0000 0.9801 0.1949 ;
0.0001 0.8311 0.5552 ;
0.0002 0.5550 0.8306 ;
0.0001 0.1950 0.9801 ;
0.0002 -0.1950 0.9801 ;
0.0002 -0.5550 0.8306 ;
0.0001 -0.8311 0.5552 ;
0.0000 -0.9801 0.1949 ;
0.0000 -0.9801 -0.1950 ;
-0.3028 0.9319 -0.1949 ;
-0.3234 0.9278 0.1813 ;
-0.3498 0.7818 0.5148 ;
-0.3699 0.5206 0.7688 ;
-0.3808 0.1825 0.9059 ;
-0.3808 -0.1825 0.9059 ;
-0.3699 -0.5206 0.7688 ;
-0.3498 -0.7818 0.5148 ;
-0.3234 -0.9278 0.1813 ;
-0.3028 -0.9319 -0.1949 ;
-0.5761 0.7929 -0.1950 ;
-0.6116 0.7771 0.1420 ;
-0.6546 0.6411 0.3985 ;
-0.6869 0.4217 0.5912 ;
-0.7041 0.1469 0.6934 ;
-0.7041 -0.1469 0.6934 ;
-0.6870 -0.4216 0.5912 ;
-0.6546 -0.6411 0.3985 ;
-0.6116 -0.7771 0.1420 ;
-0.5761 -0.7929 -0.1950 ;
-0.7926 0.5759 -0.1950 ;
-0.8331 0.5459 0.0809 ;
-0.8752 0.4292 0.2219 ;
-0.9054 0.2737 0.3233 ;
-0.9210 0.0939 0.3757 ;
-0.9210 -0.0940 0.3757 ;
-0.9054 -0.2737 0.3233 ;
-0.8752 -0.4292 0.2219 ;
-0.8331 -0.5459 0.0809 ;
-0.7926 -0.5758 -0.1950 ;
-0.9877 0.1564 0.0000 ;
-0.9877 -0.1564 0.0000 ;
-0.9118 0.1444 -0.3824 ;
-0.9118 -0.1444 -0.3824 ;
0.8225 0.4190 -0.3825 ;
0.8910 0.4540 0.0000 ;
0.9282 0.3606 0.0817 ;
0.9565 0.2508 0.1438 ;
0.9743 0.1287 0.1828 ;
0.9799 0.0000 0.1949 ;
0.9743 -0.1287 0.1828 ;
0.9565 -0.2508 0.1437 ;
0.9282 -0.3606 0.0817 ;
0.8910 -0.4540 0.0000 ;
0.8225 -0.4191 -0.3825 ;
0.6527 0.6527 -0.3825 ;
0.7071 0.7071 0.0000 ;
0.7564 0.6149 0.2206 ;
0.7962 0.4535 0.3990 ;
0.8221 0.2404 0.5148 ;
0.8312 0.0000 0.5554 ;
0.8221 -0.2404 0.5148 ;
0.7962 -0.4535 0.3990 ;
0.7564 -0.6149 0.2206 ;
0.7071 -0.7071 0.0000 ;
0.6527 -0.6527 -0.3825 ;
0.4192 0.8226 -0.3826 ;
0.4540 0.8910 0.0000 ;
0.4932 0.8072 0.3215 ;
0.5260 0.6110 0.5905 ;
0.5477 0.3286 0.7685 ;
0.5553 0.0000 0.8310 ;
0.5477 -0.3286 0.7685 ;
0.5260 -0.6110 0.5905 ;
0.4932 -0.8072 0.3216 ;
0.4540 -0.8910 0.0000 ;
0.4192 -0.8226 -0.3826 ;
0.1444 0.9119 -0.3826 ;
0.1565 0.9877 0.0000 ;
0.1713 0.9099 0.3754 ;
0.1838 0.6957 0.6933 ;
0.1922 0.3764 0.9059 ;
0.1951 0.0000 0.9804 ;
0.1922 -0.3764 0.9059 ;
0.1838 -0.6957 0.6933 ;
0.1713 -0.9099 0.3754 ;
0.1564 -0.9877 0.0000 ;
0.1444 -0.9119 -0.3826 ;
-0.1444 0.9117 -0.3826 ;
-0.1564 0.9877 -0.0001 ;
-0.1711 0.9100 0.3754 ;
-0.1836 0.6959 0.6936 ;
-0.1918 0.3763 0.9056 ;
-0.1948 0.0000 0.9800 ;
-0.1919 -0.3763 0.9056 ;
-0.1836 -0.6959 0.6936 ;
-0.1711 -0.9100 0.3754 ;
-0.1564 -0.9877 -0.0001 ;
-0.1444 -0.9117 -0.3826 ;
-0.4191 0.8225 -0.3826 ;
-0.4540 0.8910 -0.0001 ;
-0.4931 0.8073 0.3216 ;
-0.5259 0.6109 0.5904 ;
-0.5476 0.3285 0.7685 ;
-0.5551 0.0000 0.8311 ;
-0.5475 -0.3286 0.7685 ;
-0.5258 -0.6109 0.5904 ;
-0.4931 -0.8073 0.3216 ;
-0.4540 -0.8910 -0.0001 ;
-0.4191 -0.8225 -0.3826 ;
-0.6529 0.6529 -0.3825 ;
-0.7071 0.7071 0.0000 ;
-0.7561 0.6147 0.2205 ;
-0.7960 0.4537 0.3995 ;
-0.8218 0.2405 0.5152 ;
-0.8306 0.0000 0.5551 ;
-0.8218 -0.2405 0.5152 ;
-0.7960 -0.4537 0.3995 ;
-0.7562 -0.6147 0.2205 ;
-0.7071 -0.7071 0.0000 ;
-0.6529 -0.6529 -0.3825 ;
-0.8228 0.4191 -0.3824 ;
-0.8910 0.4540 0.0000 ;
-0.9283 0.3608 0.0818 ;
-0.9567 0.2511 0.1442 ;
-0.9739 0.1285 0.1822 ;
-0.9797 0.0000 0.1949 ;
-0.9739 -0.1286 0.1822 ;
-0.9567 -0.2511 0.1442 ;
-0.9283 -0.3608 0.0818 ;
-0.8910 -0.4540 0.0000 ;
-0.8228 -0.4191 -0.3824 ;
-0.9322 0.3029 -0.1949 ;
-0.9799 0.0000 -0.1949 ;
-0.9322 -0.3029 -0.1949 ;
0.0000 1.0000 0.0000 ;
-0.5878 0.8090 -0.0001 ;
0.0000 -1.0000 0.0000 ;
-0.5878 -0.8090 -0.0001 ]';
elec = struct(...
'labels',names,...
'X',xyz(1,:),...
'Y',xyz(2,:),...
'Z',xyz(3,:));
return
% LPA 0.0000 0.9237 -0.3826
% RPA 0.0000 -0.9237 -0.3826
% Nz 0.9230 0.0000 -0.3824
% Fp1 0.9511 0.3090 0.0001
% Fpz 1.0000 -0.0000 0.0001
% Fp2 0.9511 -0.3091 0.0000
% AF9 0.7467 0.5425 -0.3825
% AF7 0.8090 0.5878 0.0000
% AF5 0.8553 0.4926 0.1552
% AF3 0.8920 0.3554 0.2782
% AF1 0.9150 0.1857 0.3558
% AFz 0.9230 0.0000 0.3824
% AF2 0.9150 -0.1857 0.3558
% AF4 0.8919 -0.3553 0.2783
% AF6 0.8553 -0.4926 0.1552
% AF8 0.8090 -0.5878 0.0000
% AF10 0.7467 -0.5425 -0.3825
% F9 0.5430 0.7472 -0.3826
% F7 0.5878 0.8090 0.0000
% F5 0.6343 0.7210 0.2764
% F3 0.6726 0.5399 0.5043
% F1 0.6979 0.2888 0.6542
% Fz 0.7067 0.0000 0.7067
% F2 0.6979 -0.2888 0.6542
% F4 0.6726 -0.5399 0.5043
% F6 0.6343 -0.7210 0.2764
% F8 0.5878 -0.8090 0.0000
% F10 0.5429 -0.7472 -0.3826
% FT9 0.2852 0.8777 -0.3826
% FT7 0.3090 0.9511 0.0000
% FC5 0.3373 0.8709 0.3549
% FC3 0.3612 0.6638 0.6545
% FC1 0.3770 0.3581 0.8532
% FCz 0.3826 0.0000 0.9233
% FC2 0.3770 -0.3581 0.8532
% FC4 0.3612 -0.6638 0.6545
% FC6 0.3373 -0.8709 0.3549
% FT8 0.3090 -0.9511 0.0000
% FT10 0.2852 -0.8777 -0.3826
% T9 -0.0001 0.9237 -0.3826
% T7 0.0000 1.0000 0.0000
% C5 0.0001 0.9237 0.3826
% C3 0.0001 0.7066 0.7066
% C1 0.0002 0.3824 0.9231
% Cz 0.0002 0.0000 1.0000
% C2 0.0001 -0.3824 0.9231
% C4 0.0001 -0.7066 0.7066
% C6 0.0001 -0.9237 0.3826
% T8 0.0000 -1.0000 0.0000
% T10 0.0000 -0.9237 -0.3826
% TP9 -0.2852 0.8777 -0.3826
% TP7 -0.3090 0.9511 -0.0001
% CP5 -0.3372 0.8712 0.3552
% CP3 -0.3609 0.6635 0.6543
% CP1 -0.3767 0.3580 0.8534
% CPz -0.3822 0.0000 0.9231
% CP2 -0.3767 -0.3580 0.8534
% CP4 -0.3608 -0.6635 0.6543
% CP6 -0.3372 -0.8712 0.3552
% TP8 -0.3090 -0.9511 -0.0001
% TP10 -0.2853 -0.8777 -0.3826
% P9 -0.5429 0.7472 -0.3826
% P7 -0.5878 0.8090 -0.0001
% P5 -0.6342 0.7211 0.2764
% P3 -0.6724 0.5401 0.5045
% P1 -0.6975 0.2889 0.6545
% Pz -0.7063 0.0000 0.7065
% P2 -0.6975 -0.2889 0.6545
% P4 -0.6724 -0.5401 0.5045
% P6 -0.6342 -0.7211 0.2764
% P8 -0.5878 -0.8090 -0.0001
% P10 -0.5429 -0.7472 -0.3826
% PO9 -0.7467 0.5425 -0.3825
% PO7 -0.8090 0.5878 0.0000
% PO5 -0.8553 0.4929 0.1555
% PO3 -0.8918 0.3549 0.2776
% PO1 -0.9151 0.1858 0.3559
% POz -0.9230 -0.0000 0.3824
% PO2 -0.9151 -0.1859 0.3559
% PO4 -0.8918 -0.3549 0.2776
% PO6 -0.8553 -0.4929 0.1555
% PO8 -0.8090 -0.5878 0.0000
% PO10 -0.7467 -0.5425 -0.3825
% O1 -0.9511 0.3090 0.0000
% Oz -1.0000 0.0000 0.0000
% O2 -0.9511 -0.3090 0.0000
% I1 -0.8785 0.2854 -0.3824
% Iz -0.9230 0.0000 -0.3823
% I2 -0.8785 -0.2854 -0.3824
% AFp9h 0.8732 0.4449 -0.1949
% AFp7h 0.9105 0.4093 0.0428
% AFp5h 0.9438 0.3079 0.1159
% AFp3h 0.9669 0.1910 0.1666
% AFp1h 0.9785 0.0647 0.1919
% AFp2h 0.9785 -0.0647 0.1919
% AFp4h 0.9669 -0.1910 0.1666
% AFp6h 0.9438 -0.3079 0.1159
% AFp8h 0.9105 -0.4093 0.0428
% AFp10h 0.8732 -0.4449 -0.1949
% AFF9h 0.6929 0.6929 -0.1949
% AFF7h 0.7325 0.6697 0.1137
% AFF5h 0.7777 0.5417 0.3163
% AFF3h 0.8111 0.3520 0.4658
% AFF1h 0.8289 0.1220 0.5452
% AFF2h 0.8289 -0.1220 0.5452
% AFF4h 0.8111 -0.3520 0.4658
% AFF6h 0.7777 -0.5417 0.3163
% AFF8h 0.7325 -0.6697 0.1138
% AFF10h 0.6929 -0.6929 -0.1949
% FFT9h 0.4448 0.8730 -0.1950
% FFT7h 0.4741 0.8642 0.1647
% FFC5h 0.5107 0.7218 0.4651
% FFC3h 0.5384 0.4782 0.6925
% FFC1h 0.5533 0.1672 0.8148
% FFC2h 0.5533 -0.1672 0.8148
% FFC4h 0.5384 -0.4782 0.6925
% FFC6h 0.5107 -0.7218 0.4651
% FFT8h 0.4741 -0.8642 0.1647
% FFT10h 0.4448 -0.8730 -0.1950
% FTT9h 0.1533 0.9678 -0.1950
% FTT7h 0.1640 0.9669 0.1915
% FCC5h 0.1779 0.8184 0.5448
% FCC3h 0.1887 0.5466 0.8154
% FCC1h 0.1944 0.1919 0.9615
% FCC2h 0.1944 -0.1919 0.9615
% FCC4h 0.1887 -0.5466 0.8154
% FCC6h 0.1779 -0.8184 0.5448
% FTT8h 0.1640 -0.9669 0.1915
% FTT10h 0.1533 -0.9678 -0.1950
% TTP9h -0.1532 0.9678 -0.1950
% TTP7h -0.1639 0.9669 0.1915
% CCP5h -0.1778 0.8185 0.5449
% CCP3h -0.1883 0.5465 0.8153
% CCP1h -0.1940 0.1918 0.9611
% CCP2h -0.1940 -0.1918 0.9611
% CCP4h -0.1884 -0.5465 0.8153
% CCP6h -0.1778 -0.8185 0.5449
% TTP8h -0.1639 -0.9669 0.1915
% TTP10h -0.1533 -0.9678 -0.1950
% TPP9h -0.4448 0.8731 -0.1950
% TPP7h -0.4740 0.8639 0.1646
% CPP5h -0.5106 0.7220 0.4653
% CPP3h -0.5384 0.4786 0.6933
% CPP1h -0.5532 0.1673 0.8155
% CPP2h -0.5532 -0.1673 0.8155
% CPP4h -0.5384 -0.4786 0.6933
% CPP6h -0.5106 -0.7220 0.4653
% TPP8h -0.4740 -0.8638 0.1646
% TPP10h -0.4449 -0.8731 -0.1950
% PPO9h -0.6928 0.6928 -0.1950
% PPO7h -0.7324 0.6700 0.1139
% PPO5h -0.7776 0.5420 0.3167
% PPO3h -0.8108 0.3520 0.4659
% PPO1h -0.8284 0.1220 0.5453
% PPO2h -0.8284 -0.1220 0.5453
% PPO4h -0.8108 -0.3519 0.4659
% PPO6h -0.7775 -0.5421 0.3167
% PPO8h -0.7324 -0.6700 0.1139
% PPO10h -0.6928 -0.6928 -0.1950
% POO9h -0.8730 0.4448 -0.1950
% POO7h -0.9106 0.4097 0.0430
% POO5h -0.9438 0.3080 0.1160
% POO3h -0.9665 0.1908 0.1657
% POO1h -0.9783 0.0647 0.1918
% POO2h -0.9783 -0.0647 0.1918
% POO4h -0.9665 -0.1908 0.1657
% POO6h -0.9438 -0.3080 0.1160
% POO8h -0.9106 -0.4097 0.0430
% POO10h -0.8730 -0.4448 -0.1950
% OI1h -0.9679 0.1533 -0.1950
% OI2h -0.9679 -0.1533 -0.1950
% Fp1h 0.9877 0.1564 0.0001
% Fp2h 0.9877 -0.1564 0.0001
% AF9h 0.7928 0.5759 -0.1949
% AF7h 0.8332 0.5463 0.0810
% AF5h 0.8750 0.4284 0.2213
% AF3h 0.9053 0.2735 0.3231
% AF1h 0.9211 0.0939 0.3758
% AF2h 0.9210 -0.0939 0.3758
% AF4h 0.9053 -0.2735 0.3231
% AF6h 0.8750 -0.4284 0.2212
% AF8h 0.8332 -0.5463 0.0810
% AF10h 0.7927 -0.5759 -0.1949
% F9h 0.5761 0.7929 -0.1949
% F7h 0.6117 0.7772 0.1420
% F5h 0.6549 0.6412 0.3987
% F3h 0.6872 0.4214 0.5906
% F1h 0.7045 0.1468 0.6933
% F2h 0.7045 -0.1468 0.6933
% F4h 0.6872 -0.4214 0.5906
% F6h 0.6549 -0.6412 0.3987
% F8h 0.6117 -0.7772 0.1420
% F10h 0.5761 -0.7929 -0.1949
% FT9h 0.3027 0.9317 -0.1950
% FT7h 0.3235 0.9280 0.1813
% FC5h 0.3500 0.7817 0.5146
% FC3h 0.3703 0.5207 0.7687
% FC1h 0.3811 0.1824 0.9054
% FC2h 0.3811 -0.1824 0.9054
% FC4h 0.3703 -0.5207 0.7687
% FC6h 0.3500 -0.7817 0.5146
% FT8h 0.3235 -0.9280 0.1813
% FT10h 0.3028 -0.9317 -0.1950
% T9h 0.0000 0.9801 -0.1950
% T7h 0.0000 0.9801 0.1949
% C5h 0.0001 0.8311 0.5552
% C3h 0.0002 0.5550 0.8306
% C1h 0.0001 0.1950 0.9801
% C2h 0.0002 -0.1950 0.9801
% C4h 0.0002 -0.5550 0.8306
% C6h 0.0001 -0.8311 0.5552
% T8h 0.0000 -0.9801 0.1949
% T10h 0.0000 -0.9801 -0.1950
% TP9h -0.3028 0.9319 -0.1949
% TP7h -0.3234 0.9278 0.1813
% CP5h -0.3498 0.7818 0.5148
% CP3h -0.3699 0.5206 0.7688
% CP1h -0.3808 0.1825 0.9059
% CP2h -0.3808 -0.1825 0.9059
% CP4h -0.3699 -0.5206 0.7688
% CP6h -0.3498 -0.7818 0.5148
% TP8h -0.3234 -0.9278 0.1813
% TP10h -0.3028 -0.9319 -0.1949
% P9h -0.5761 0.7929 -0.1950
% P7h -0.6116 0.7771 0.1420
% P5h -0.6546 0.6411 0.3985
% P3h -0.6869 0.4217 0.5912
% P1h -0.7041 0.1469 0.6934
% P2h -0.7041 -0.1469 0.6934
% P4h -0.6870 -0.4216 0.5912
% P6h -0.6546 -0.6411 0.3985
% P8h -0.6116 -0.7771 0.1420
% P10h -0.5761 -0.7929 -0.1950
% PO9h -0.7926 0.5759 -0.1950
% PO7h -0.8331 0.5459 0.0809
% PO5h -0.8752 0.4292 0.2219
% PO3h -0.9054 0.2737 0.3233
% PO1h -0.9210 0.0939 0.3757
% PO2h -0.9210 -0.0940 0.3757
% PO4h -0.9054 -0.2737 0.3233
% PO6h -0.8752 -0.4292 0.2219
% PO8h -0.8331 -0.5459 0.0809
% PO10h -0.7926 -0.5758 -0.1950
% O1h -0.9877 0.1564 0.0000
% O2h -0.9877 -0.1564 0.0000
% I1h -0.9118 0.1444 -0.3824
% I2h -0.9118 -0.1444 -0.3824
% AFp9 0.8225 0.4190 -0.3825
% AFp7 0.8910 0.4540 0.0000
% AFp5 0.9282 0.3606 0.0817
% AFp3 0.9565 0.2508 0.1438
% AFp1 0.9743 0.1287 0.1828
% AFpz 0.9799 -0.0000 0.1949
% AFp2 0.9743 -0.1287 0.1828
% AFp4 0.9565 -0.2508 0.1437
% AFp6 0.9282 -0.3606 0.0817
% AFp8 0.8910 -0.4540 0.0000
% AFp10 0.8225 -0.4191 -0.3825
% AFF9 0.6527 0.6527 -0.3825
% AFF7 0.7071 0.7071 0.0000
% AFF5 0.7564 0.6149 0.2206
% AFF3 0.7962 0.4535 0.3990
% AFF1 0.8221 0.2404 0.5148
% AFFz 0.8312 0.0000 0.5554
% AFF2 0.8221 -0.2404 0.5148
% AFF4 0.7962 -0.4535 0.3990
% AFF6 0.7564 -0.6149 0.2206
% AFF8 0.7071 -0.7071 0.0000
% AFF10 0.6527 -0.6527 -0.3825
% FFT9 0.4192 0.8226 -0.3826
% FFT7 0.4540 0.8910 0.0000
% FFC5 0.4932 0.8072 0.3215
% FFC3 0.5260 0.6110 0.5905
% FFC1 0.5477 0.3286 0.7685
% FFCz 0.5553 0.0000 0.8310
% FFC2 0.5477 -0.3286 0.7685
% FFC4 0.5260 -0.6110 0.5905
% FFC6 0.4932 -0.8072 0.3216
% FFT8 0.4540 -0.8910 0.0000
% FFT10 0.4192 -0.8226 -0.3826
% FTT9 0.1444 0.9119 -0.3826
% FTT7 0.1565 0.9877 0.0000
% FCC5 0.1713 0.9099 0.3754
% FCC3 0.1838 0.6957 0.6933
% FCC1 0.1922 0.3764 0.9059
% FCCz 0.1951 0.0000 0.9804
% FCC2 0.1922 -0.3764 0.9059
% FCC4 0.1838 -0.6957 0.6933
% FCC6 0.1713 -0.9099 0.3754
% FTT8 0.1564 -0.9877 0.0000
% FTT10 0.1444 -0.9119 -0.3826
% TTP9 -0.1444 0.9117 -0.3826
% TTP7 -0.1564 0.9877 -0.0001
% CCP5 -0.1711 0.9100 0.3754
% CCP3 -0.1836 0.6959 0.6936
% CCP1 -0.1918 0.3763 0.9056
% CCPz -0.1948 0.0000 0.9800
% CCP2 -0.1919 -0.3763 0.9056
% CCP4 -0.1836 -0.6959 0.6936
% CCP6 -0.1711 -0.9100 0.3754
% TTP8 -0.1564 -0.9877 -0.0001
% TTP10 -0.1444 -0.9117 -0.3826
% TPP9 -0.4191 0.8225 -0.3826
% TPP7 -0.4540 0.8910 -0.0001
% CPP5 -0.4931 0.8073 0.3216
% CPP3 -0.5259 0.6109 0.5904
% CPP1 -0.5476 0.3285 0.7685
% CPPz -0.5551 0.0000 0.8311
% CPP2 -0.5475 -0.3286 0.7685
% CPP4 -0.5258 -0.6109 0.5904
% CPP6 -0.4931 -0.8073 0.3216
% TPP8 -0.4540 -0.8910 -0.0001
% TPP10 -0.4191 -0.8225 -0.3826
% PPO9 -0.6529 0.6529 -0.3825
% PPO7 -0.7071 0.7071 0.0000
% PPO5 -0.7561 0.6147 0.2205
% PPO3 -0.7960 0.4537 0.3995
% PPO1 -0.8218 0.2405 0.5152
% PPOz -0.8306 0.0000 0.5551
% PPO2 -0.8218 -0.2405 0.5152
% PPO4 -0.7960 -0.4537 0.3995
% PPO6 -0.7562 -0.6147 0.2205
% PPO8 -0.7071 -0.7071 0.0000
% PPO10 -0.6529 -0.6529 -0.3825
% POO9 -0.8228 0.4191 -0.3824
% POO7 -0.8910 0.4540 0.0000
% POO5 -0.9283 0.3608 0.0818
% POO3 -0.9567 0.2511 0.1442
% POO1 -0.9739 0.1285 0.1822
% POOz -0.9797 -0.0000 0.1949
% POO2 -0.9739 -0.1286 0.1822
% POO4 -0.9567 -0.2511 0.1442
% POO6 -0.9283 -0.3608 0.0818
% POO8 -0.8910 -0.4540 0.0000
% POO10 -0.8228 -0.4191 -0.3824
% OI1 -0.9322 0.3029 -0.1949
% OIz -0.9799 0.0000 -0.1949
% OI2 -0.9322 -0.3029 -0.1949
% T3 0.0000 1.0000 0.0000
% T5 -0.5878 0.8090 -0.0001
% T4 0.0000 -1.0000 0.0000
% T6 -0.5878 -0.8090 -0.0001
end
function [CHAN1020,XYZ1020] = elec_1020select(CHAN)
% elec_1020select - select 10-20 locations
%
% [labels,xyz] = elec_1020select(CHAN)
%
% where CHAN input is a cell array of channel names from the International
% 10-20 nomenclature for EEG electrode placement. For a list of the 10-20
% electrode names, see the elec_1020all_cart function, which is based on:
%
% Oostenveld, R. & Praamstra, P. (2001). The five percent electrode system
% for high-resolution EEG and ERP measurements. Clinical Neurophysiology,
% 112:713-719.
%
% $Revision$ $Date: 2009-01-30 03:49:28 $
% Copyright (C) 2005 Darren L. Weber
%
% 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 (at your option) 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 Place - Suite 330, Boston, MA 02111-1307, USA.
% Modified: 01/2005, Darren.Weber_at_radiology.ucsf.edu
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ver = '$Revision$ $Date: 2009-01-30 03:49:28 $';
fprintf('\nELEC_1020SELECT [v %s]\n',ver(11:15));
% get the 1020 data
elec = elec_1020all_cart;
elec = struct2cell(elec);
labels = squeeze(elec(1,:,:))';
x = squeeze(elec(2,:,:)); x = x{1};
y = squeeze(elec(3,:,:)); y = y{1};
z = squeeze(elec(4,:,:)); z = z{1};
clear elec
% find all the electrode names in elec.labels that match CHAN
CHAN1020 = zeros(1,length(CHAN));
XYZ1020 = zeros(length(CHAN),3);
for c = 1:length(CHAN),
chan = CHAN{c};
index = find(strcmp(lower(chan), lower(labels)));
if ~isempty(index),
CHAN1020(c) = index;
XYZ1020(c,:) = [ x(index), y(index), z(index) ];
else
msg = sprintf('No match for channel: %s\n',chan)
error(msg)
end
end
CHAN1020 = labels(CHAN1020);
return
end
|
github
|
lcnhappe/happe-master
|
test_bug2761.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_bug2761.m
| 516 |
utf_8
|
40e8c6fcd9af682c490acf41bf40d317
|
function test_bug2761
% WALLTIME 00:10:00
% MEM 1GB
% TEST test_bug2761
% TEST ft_connectivityanalysis ft_connectivity_corr
data = [];
for i=1:5
data.label{i} = num2str(i);
end
for i=1:13
data.trial{i} = randn(5,300);
data.time{i} = (1:300)/300;
end
cfg = [];
cfg.covariance = 'yes';
timelock = ft_timelockanalysis(cfg, data);
cfg = [];
cfg.method = 'corr';
connectivity = ft_connectivityanalysis(cfg, timelock);
% this failed at the time of reporting this bug
assert(~isfield(connectivity, 'time'));
|
github
|
lcnhappe/happe-master
|
test_csp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_csp.m
| 2,280 |
utf_8
|
6749925fb2418cf2a37607668d16c4c7
|
function test_suite = test_csp
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_csp
% TEST ft_component_analysis
% Please beware of notations mistakes in [1]. For example equation (1) does not
% compute the t by t channel covariance, but an n by n time covariance matrix.
%
% [1] Zoltan J. Koles. The quantitative extraction and topographic mapping of
% the abnormal components in the clinical EEG. Electroencephalography and
% Clinical Neurophysiology, 79(6):440--447, December 1991.
% add xunit to path
ft_hastoolbox('xunit',1);
initTestSuite; % for xUnit
function test_csp_integration
% create data struct with two trials
p = 6; n = 100;
data = [];
data.label = {'c1', 'c2', 'c3', 'c4', 'c5', 'c6'};
data.trial = {randn(p, n), randn(p, n)};
data.time = {1:n, 1:n};
% HACK: prescale that data so that ft_component_analysis does not do so.
% Should add an option to disable scaling in ft_component_analysis.
scale = norm((data.trial{1}*data.trial{1}')./size(data.trial{1},2))^.5;
for trial=1:2
data.trial{trial} = data.trial{trial} ./ scale;
end
% run CSP through ft_component_analysis
cfg = [];
cfg.method = 'csp';
cfg.csp.numfilters = 4;
cfg.demean = 'false';
cfg.csp.classlabels = [1 2];
comp = ft_componentanalysis(cfg, data);
% check CSP properties
C1 = cov(data.trial{1}');
C2 = cov(data.trial{2}');
W = csp(C1, C2, cfg.csp.numfilters);
assert(norm(comp.unmixing - W) < 1e-10, ...
'CSP in ft_component_analysis does not match bare CSP.')
function test_csp_base
% Create signals with different variance. We use a degenerate covariance
% structure to stress the whitening.
p = 6; n = 100; m = 4;
S1 = diag([0 1 1 1 1 3]) * randn(p, n);
S2 = diag([0 1 1 1 1 .1]) * randn(p, n);
% randomly mix signals
A = randn(p, p);
X1 = A * S1;
X2 = A * S2;
% get covariance
C1 = cov(X1');
C2 = cov(X2');
% find unmixing matrix
W = csp(C1, C2, m);
% test CSP properties
D1 = W * C1 * W';
D2 = W * C2 * W';
assert(all(diff(diag(D1)) <= 0), ...
'CSP variance is not descending for condition 1.');
assert(norm(D1 + D2 - eye(m)) < 1e-10, ...
'CSP does not whiten correctly.');
assert(norm(diag(diag(D1)) - D1) < 1e-10, ...
'CSP does not diagonalize correctly.');
|
github
|
lcnhappe/happe-master
|
test_bug1925.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_bug1925.m
| 1,259 |
utf_8
|
3822edac5639686e3eb5ab751e54276d
|
function test_bug1925
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_bug1925
% TEST surface_nesting ft_headmodel_bemcp
[ftver, ftpath] = ft_version;
cd(fullfile(ftpath, 'forward/private')); % this is where the surface_nesting function is located
[pos, tri] = icosahedron162;
bnd10.id = 10;
bnd10.pos = pos*10;
bnd10.tri = tri;
bnd20.id = 20;
bnd20.pos = pos*20;
bnd20.tri = tri;
bnd30.id = 30;
bnd30.pos = pos*30;
bnd30.tri = tri;
bnd40.id = 40;
bnd40.pos = pos*40;
bnd40.tri = tri;
bnd50.id = 50;
bnd50.pos = pos*50;
bnd50.tri = tri;
bnd = bnd10;
bnd(2) = bnd20;
bnd(3) = bnd30;
bnd(4) = bnd40;
bnd(5) = bnd50;
assert(equalorder(surface_nesting(bnd, 'insidefirst'), 1:5));
assert(equalorder(surface_nesting(bnd, 'outsidefirst'), fliplr(1:5)));
bnd = bnd10;
bnd(3) = bnd20;
bnd(2) = bnd30;
bnd(5) = bnd40;
bnd(4) = bnd50;
assert(equalorder(surface_nesting(bnd, 'insidefirst'), [1 3 2 5 4]));
assert(equalorder(surface_nesting(bnd, 'outsidefirst'), fliplr([1 3 2 5 4])));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to deal with row and column comparisons
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function bool = equalorder(a, b)
bool = isequal(a(:), b(:));
|
github
|
lcnhappe/happe-master
|
test_ft_timelockanalysis_new.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_timelockanalysis_new.m
| 15,554 |
utf_8
|
25776f063c3317b6ed7bb48c417064d8
|
function test_ft_timelockanalysis_new(datainfo,writeflag)
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_ft_timelockanalysis_new
% ft_timelockanalysis_new ft_timelockanalysis ref_datasets
% this is a function for testing ft_timelockanalysis_new, which is not official yet
% the optional writeflag determines whether the output should be saved to
% disk
%%
% This function is testing a new ft_timelockanalysis_new which is something
% Johanna is working on and not in SVN yet.
return;
%%
if nargin<2
writeflag = 0;
end
if nargin<1
datainfo = ref_datasets;
end
% for k = 1:numel(datainfo)
for k = 1:10
datanew = timelockanalysis10trials(datainfo(k), writeflag);
fname = fullfile(datainfo(k).origdir,'latest/timelock',datainfo(k).type,'timelock_',datainfo(k).datatype);
tmp = load(fname);
if isfield(tmp, 'data')
data = tmp.data;
elseif isfield(tmp, 'datanew')
data = tmp.datanew;
else isfield(tmp, 'timelock')
data = tmp.timelock;
end
datanew = rmfield(datanew, 'cfg'); % these are per construction different if writeflag = 0;
data = rmfield(data, 'cfg');
assert(isequaln(data, datanew));
end
test_cfg_options;
function [tlck] = timelockanalysis10trials(dataset, writeflag)
cfg = [];
cfg.inputfile = fullfile(dataset.origdir,'latest/raw',dataset.type,['preproc_',dataset.datatype]);
if writeflag
cfg.outputfile = fullfile(dataset.origdir,'latest/timelock',dataset.type,'timelock_',dataset.datatype);
end
tlck = ft_timelockanalysis(cfg);
tlck1 = ft_timelockanalysis_new(cfg);
return
function test_cfg_options
load /home/common/matlab/fieldtrip/data/ftp/tutorial/eventrelatedaveraging/dataFC_LP.mat
data=dataFC_LP;
clear dataFC_LP;
data.time{2}=data.time{2}+.5; % purposely add some jitter to time window
data.time{3}=data.time{3}-.5;
cfg=[];
try
tlock=ft_timelockanalysis_new(cfg,data);
catch me
% if ~strcmp(me.message,'the option "output" was not specified or was empty');
error(me.message)
% end
end
cfg=[];
cfg.output='rubbish';
try
tlock=ft_timelockanalysis_new(cfg,data);
catch me
if ~strcmp(me.message,'the value of cfg.output is not set correctly');
error(me.message)
end
end
% no latency or covlatency given, use defaults
cfg=[];
cfg.output='avg';
cfg.feedback='none';
cfg.preproc.feedback='textbar';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
% cfg.vartrllength=1;
% tlocko=ft_timelockanalysis(cfg,data);
cfg=[];
cfg.output='cov';
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.keeptrials='no';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg=[];
cfg.output='avgandcov';
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.keeptrials='no';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
% cfg.covariance='yes';
% cfg.vartrllength=1;
% tlocko=ft_timelockanalysis(cfg,data);
cfg=[];
cfg.output='avg';
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.keeptrials='yes';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
% cfg.vartrllength=1;
% tlocko=ft_timelockanalysis(cfg,data);
cfg=[];
cfg.output='cov';
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.keeptrials='yes';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg=[];
cfg.output='avgandcov';
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.keeptrials='yes';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
% cfg.covariance='yes';
% cfg.vartrllength=1;
% tlocko=ft_timelockanalysis(cfg,data);
% options with .latency and .covlatency specified
cfg=[];
cfg.output='avg';
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.keeptrials='no';
cfg.latency=[min(data.time{1}) max(data.time{1})];
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
% cfg.vartrllength=1;
% tlocko=ft_timelockanalysis(cfg,data);
cfg.latency='maxperlength';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg.latency='minperlength';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg.latency='prestim';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg.latency='poststim';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg=[];
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.output='avg';
cfg.keeptrials='yes';
cfg.latency=[min(data.time{1}) max(data.time{1})];
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg.latency='maxperlength';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg.latency='minperlength';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg.latency='prestim';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg.latency='poststim';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg=[];
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.output='avgandcov';
cfg.keeptrials='no';
cfg.latency=[min(data.time{1}) max(data.time{1})];
cfg.covlatency=[min(data.time{1}) max(data.time{1})];
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
% cfg.covariance='yes';
% cfg.vartrllength=1;
% tlocko=ft_timelockanalysis(cfg,data);
cfg.latency='maxperlength';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg=[];
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.output='avgandcov';
cfg.keeptrials='yes';
cfg.latency=[min(data.time{1}) max(data.time{1})];
cfg.covlatency=[min(data.time{1}) max(data.time{1})];
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
% cfg.covariance='yes';
% cfg.vartrllength=1;
% tlocko=ft_timelockanalysis(cfg,data);
cfg=[];
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.output='cov';
cfg.keeptrials='no';
cfg.latency=[min(data.time{1}) max(data.time{1})];
cfg.covlatency=[min(data.time{1}) max(data.time{1})];
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg=[];
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.output='cov';
cfg.keeptrials='yes';
cfg.latency=[min(data.time{1}) max(data.time{1})];
cfg.covlatency=[min(data.time{1}) max(data.time{1})];
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
% check toi options
cfg=[];
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.output='cov';
cfg.latency=[min(data.time{1}) max(data.time{1})];
cfg.covlatency='minperlength';
cfg.toi=[-0.5 0.7];
cfg.timwin=1;
cfg.equatenumtrials='yes';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg=[];
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.output='cov';
cfg.covlatency='minperlength';
cfg.toi=[-.8:.3:0.1];
cfg.timwin=1;
cfg.equatenumtrials='no';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg=[];
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.output='cov';
cfg.covlatency='minperlength';
cfg.toi=[-.8:.3:0.1];
cfg.timwin=1;
cfg.equatenumtrials='no';
cfg.keeptrials='yes';
try
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
catch me
if ~strcmp(me.message,'sorry, if keeping trials and computing cov, cfg.equatenumtrials should be yes')
error(me.message)
end
end
cfg=[];
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.output='cov';
cfg.covlatency='minperlength';
cfg.toi=[-.8:.3:0.1];
cfg.timwin=1;
cfg.equatenumtrials='yes';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
cfg=[];
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.output='cov';
cfg.covlatency='minperlength';
cfg.toi=[-.8:.3:0.1];
cfg.timwin=1;
cfg.equatenumtrials='yes';
cfg.keeptrials='yes';
tlock=ft_timelockanalysis_new(cfg,data);
if ~strmatch(ft_datatype(tlock),'timelock'),error('datatype');end;
if ~strcmp(ft_datatype(ft_checkdata(tlock,'datatype','raw')),'raw') || ~strcmp(ft_datatype(ft_checkdata(tlock)),'timelock'),error('checkdata');end
%% ignore for svn testing, but used to test output of new function in further functions
% test ft_sourceanalysis versus MNE event related tutorial
if 0
cfg=[];
cfg.output='avg';
cfg.feedback='none';
cfg.preproc.feedback='textbar';
tlock=ft_timelockanalysis_new(cfg,data);
cfg=[];
cfg.method='lcmv';
cfg.hdmfile=['/home/common/matlab/fieldtrip/data/Subject01.hdm'];
cfg.grad=data.grad;
source=ft_sourceanalysis(cfg,tlock);
cfg = [];
cfg.covariance = 'yes';
cfg.vartrllength=1;
cfg.covariancewindow = [-inf 0]; %it will calculate the covariance matrix
% on the timepoints that are
% before the zero-time point in the trials
tlckFC = ft_timelockanalysis(cfg, data);
% tlckFIC = ft_timelockanalysis(cfg, dataFIC_LP);
save tlck tlckFC tlckFIC;
cfg=[];
cfg.method='lcmv';
cfg.hdmfile=['/home/common/matlab/fieldtrip/data/Subject01.hdm'];
cfg.grad=data.grad;
sourceFC=ft_sourceanalysis(cfg,tlckFC);
end
% spin off of beamformer tutorial but in time-domain, results won't match exactly
if 0
cfg=[];
cfg.output='cov';
cfg.feedback='none';
cfg.preproc.feedback='textbar';
cfg.covlatency=[0.8 1.3];
cfg.preproc.bpfilter='yes';
cfg.preproc.bpfreq=[16 20];
tlock=ft_timelockanalysis_new(cfg,data);
load /home/common/matlab/fieldtrip/data/ftp/tutorial/beamformer/segmentedmri.mat
cfg=[];
vol=ft_prepare_singleshell(cfg,segmentedmri);
cfg=[];
cfg.vol=vol;
cfg.reducerank = 2;
cfg.grad=tlock.grad;
cfg.grid.resolution=1;
cfg.channel={'MEG','-MLP31','-MLO12'};
grid=ft_prepare_leadfield(cfg);
cfg=[];
cfg.method='lcmv';
cfg.projectnoise='yes';
cfg.grid=grid;
cfg.vol=vol;
source=ft_sourceanalysis(cfg,tlock);
mri=ft_read_mri('/home/common/matlab/fieldtrip/data/Subject01.mri');
sourcediff=source;
% sourcediff.avg.pow=(source.avg.pow-source.avg.noise)./source.avg.noise;
sourcediff.avg.pow=(source.avg.pow)./source.avg.noise;
cfg=[];
cfg.downsample=2;
sourcediffint=ft_sourceinterpolate(cfg,sourcediff,mri);
cfg=[];
cfg.method='slice';
cfg.funparameter='avg.pow';
cfg.maskparameter=cfg.funparameter;
cfg.funcolorlim=[5 6.2];
cfg.opacitylim=[5 6.2];
cfg.opacitymap='rampup';
figure;ft_sourceplot(cfg,sourcediffint); %ok
cfg=[];
cfg.downsample=2;
sourceint=ft_sourceinterpolate(cfg,source,mri);
cfg=[];
cfg.method='slice';
cfg.funparameter='avg.pow';
% cfg.maskparameter=cfg.funparameter;
% cfg.funcolorlim=[5 6.2];
% cfg.opacitylim=[5 6.2];
% cfg.opacitymap='rampup';
figure;ft_sourceplot(cfg,sourceint); %ok
end
% test ft_timelockstatistics
if 0
cfg=[];
cfg.output='cov';
cfg.feedback='none';
cfg.keeptrials='yes';
cfg.preproc.feedback='textbar';
tlock=ft_timelockanalysis_new(cfg,data);
tlock1 = ft_selectdata(tlock, 'rpt',1:36)
tlock2 = ft_selectdata(tlock, 'rpt',37:72)
cfg=[];
cfg.method='analytic';
cfg.statistic='ft_statfun_indepsamplesT' ;
stat=ft_timelockstatistics(cfg,tlock1,tlock2);
end
|
github
|
lcnhappe/happe-master
|
test_bug2225.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_bug2225.m
| 219 |
utf_8
|
cd5a86e01c4737d10a1bf2c4f91cde09
|
function test_bug2225
% WALLTIME 00:10:00
% MEM 1gb
tic
for i=1:10000
issue_warning
end % for
toc
end % main function
function issue_warning
ft_warning('this warning should not show too often');
end % subfunction
|
github
|
lcnhappe/happe-master
|
test_tutorial_coherence.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_tutorial_coherence.m
| 7,081 |
utf_8
|
a00ebdbf1a5ecf3f6ec67bfaa67876d8
|
function test_tutorial_coherence
% MEM 4500mb
% WALLTIME 00:20:00
% TEST test_tutorial_coherence
% TEST ft_freqanalysis ft_connectivityanalysis ft_multiplotER ft_singleplotER ft_topoplotER ft_sourceanalysis ft_sourceinterpolate ft_prepare_sourcemodel headsurface
addpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/coherence');
addpath('/home/common/matlab/fieldtrip/data/');
% find the interesting epochs of data
cfg = [];
cfg.trialfun = 'trialfun_left';
cfg.dataset = '/home/common/matlab/fieldtrip/data/SubjectCMC.ds';
cfg = ft_definetrial(cfg);
% detect EOG artifacts in the MEG data
cfg.continuous = 'yes';
cfg.artfctdef.eog.padding = 0;
cfg.artfctdef.eog.bpfilter = 'no';
cfg.artfctdef.eog.detrend = 'yes';
cfg.artfctdef.eog.hilbert = 'no';
cfg.artfctdef.eog.rectify = 'yes';
cfg.artfctdef.eog.cutoff = 2.5;
cfg.artfctdef.eog.interactive = 'no';
cfg = ft_artifact_eog(cfg);
% detect jump artifacts in the MEG data
cfg.artfctdef.jump.interactive = 'no';
cfg.padding = 5;
cfg = ft_artifact_jump(cfg);
% detect muscle artifacts in the MEG data
cfg.artfctdef.muscle.cutoff = 8;
cfg.artfctdef.muscle.interactive = 'no';
cfg = ft_artifact_muscle(cfg);
% reject the epochs that contain artifacts
cfg.artfctdef.reject = 'complete';
cfg = ft_rejectartifact(cfg);
% preprocess the MEG data
cfg.demean = 'yes';
cfg.dftfilter = 'yes';
cfg.channel = {'MEG'};
cfg.continuous = 'yes';
meg = ft_preprocessing(cfg);
% preprocess the EMG data
cfg = [];
cfg.dataset = meg.cfg.dataset;
cfg.trl = meg.cfg.trl;
cfg.continuous = 'yes';
cfg.demean = 'yes';
cfg.dftfilter = 'yes';
cfg.channel = {'EMGlft' 'EMGrgt'};
cfg.hpfilter = 'yes';
cfg.hpfreq = 10;
cfg.rectify = 'yes';
emg = ft_preprocessing(cfg);
% concatenate the two data-structures into one structure
data = ft_appenddata([], meg, emg);
% visualisation
figure
subplot(2,1,1);
plot(data.time{1},data.trial{1}(77,:));
axis tight;
legend(data.label(77));
subplot(2,1,2);
plot(data.time{1},data.trial{1}(152:153,:));
axis tight;
legend(data.label(152:153));
% spectral analysis: fourier
cfg = [];
cfg.output = 'fourier';
cfg.method = 'mtmfft';
cfg.foilim = [5 100];
cfg.tapsmofrq = 5;
cfg.keeptrials = 'yes';
cfg.channel = {'MEG' 'EMGlft' 'EMGrgt'};
freqfourier = ft_freqanalysis(cfg, data);
% spectral analysis: powandcsd
cfg = [];
cfg.output = 'powandcsd';
cfg.method = 'mtmfft';
cfg.foilim = [5 100];
cfg.tapsmofrq = 5;
cfg.keeptrials = 'yes';
cfg.channel = {'MEG' 'EMGlft' 'EMGrgt'};
cfg.channelcmb = {'MEG' 'EMGlft'; 'MEG' 'EMGrgt'};
freq = ft_freqanalysis(cfg, data);
% compute coherence
cfg = [];
cfg.method = 'coh';
cfg.channelcmb = {'MEG' 'EMG'};
fd = ft_connectivityanalysis(cfg, freq);
fdfourier = ft_connectivityanalysis(cfg, freqfourier);
% visualisation
cfg = [];
cfg.parameter = 'cohspctrm';
cfg.xlim = [5 80];
cfg.refchannel = 'EMGlft';
cfg.layout = 'CTF151.lay';
cfg.showlabels = 'yes';
figure; ft_multiplotER(cfg, fd)
cfg.channel = 'MRC21';
figure; ft_singleplotER(cfg, fd);
cfg = [];
cfg.parameter = 'cohspctrm';
cfg.xlim = [15 20];
cfg.zlim = [0 0.1];
cfg.refchannel = 'EMGlft';
cfg.layout = 'CTF151.lay';
figure; ft_topoplotER(cfg, fd)
% 2 Hz smoothing
cfg = [];
cfg.output = 'powandcsd';
cfg.method = 'mtmfft';
cfg.foilim = [5 100];
cfg.tapsmofrq = 2;
cfg.keeptrials = 'yes';
cfg.channel = {'MEG' 'EMGlft'};
cfg.channelcmb = {'MEG' 'EMGlft'};
freq2 = ft_freqanalysis(cfg,data);
cfg = [];
cfg.method = 'coh';
cfg.channelcmb = {'MEG' 'EMG'};
fd2 = ft_connectivityanalysis(cfg,freq2);
cfg = [];
cfg.parameter = 'cohspctrm';
cfg.refchannel = 'EMGlft';
cfg.xlim = [5 80];
cfg.channel = 'MRC21';
figure; ft_singleplotER(cfg, fd, fd2);
% 10 Hz smoothing
cfg = [];
cfg.output = 'powandcsd';
cfg.method = 'mtmfft';
cfg.foilim = [5 100];
cfg.keeptrials = 'yes';
cfg.channel = {'MEG' 'EMGlft'};
cfg.channelcmb = {'MEG' 'EMGlft'};
cfg.tapsmofrq = 10;
freq10 = ft_freqanalysis(cfg,data);
cfg = [];
cfg.method = 'coh';
cfg.channelcmb = {'MEG' 'EMG'};
fd10 = ft_connectivityanalysis(cfg,freq10);
cfg = [];
cfg.parameter = 'cohspctrm';
cfg.xlim = [5 80];
cfg.ylim = [0 0.2];
cfg.refchannel = 'EMGlft';
cfg.channel = 'MRC21';
figure;ft_singleplotER(cfg, fd, fd2, fd10);
% 50 trials
cfg = [];
cfg.output = 'powandcsd';
cfg.method = 'mtmfft';
cfg.foilim = [5 100];
cfg.tapsmofrq = 5;
cfg.keeptrials = 'yes';
cfg.channel = {'MEG' 'EMGlft'};
cfg.channelcmb = {'MEG' 'EMGlft'};
cfg.trials = 1:50;
freq50 = ft_freqanalysis(cfg,data);
cfg = [];
cfg.method = 'coh';
cfg.channelcmb = {'MEG' 'EMG'};
fd50 = ft_connectivityanalysis(cfg,freq50);
cfg = [];
cfg.parameter = 'cohspctrm';
cfg.xlim = [5 100];
cfg.ylim = [0 0.2];
cfg.refchannel = 'EMGlft';
cfg.channel = 'MRC21';
figure; ft_singleplotER(cfg, fd, fd50);
% source reconstruction
cfg = [];
cfg.method = 'mtmfft';
cfg.output = 'powandcsd';
cfg.foilim = [18 18];
cfg.tapsmofrq = 5;
cfg.keeptrials = 'yes';
cfg.channelcmb = {'MEG' 'MEG';'MEG' 'EMGlft'};
freq = ft_freqanalysis(cfg, data);
cfg = [];
cfg.method = 'dics';
cfg.refchan = 'EMGlft';
cfg.frequency = 18;
cfg.hdmfile = 'SubjectCMC.hdm';
cfg.inwardshift = 1;
cfg.grid.resolution = 1;
cfg.grid.unit = 'cm';
source = ft_sourceanalysis(cfg, freq);
mri = ft_read_mri('SubjectCMC.mri');
mri = ft_volumereslice([], mri);
cfg = [];
cfg.parameter = 'coh';
cfg.downsample = 2;
interp = ft_sourceinterpolate(cfg, source, mri);
cfg = [];
cfg.method = 'ortho';
%cfg.interactive = 'yes';
cfg.funparameter = 'coh';
figure; ft_sourceplot(cfg, interp);
%--------------------------------
% subfunction
function trl = trialfun_left(cfg)
% read in the triggers and create a trial-matrix
% consisting of 1-second data segments, in which
% left ECR-muscle is active.
event = ft_read_event(cfg.dataset);
trig = [event(find(strcmp('backpanel trigger', {event.type}))).value];
indx = [event(find(strcmp('backpanel trigger', {event.type}))).sample];
%left-condition
sel = [find(trig==1028):find(trig==1029)];
trig = trig(sel);
indx = indx(sel);
trl = [];
for j = 1:length(trig)-1
trg1 = trig(j);
trg2 = trig(j+1);
if trg1<=100 & trg2==2080,
trlok = [[indx(j)+1:1200:indx(j+1)-1200]' [indx(j)+1200:1200:indx(j+1)]'];
trlok(:,3) = [0:-1200:-1200*(size(trlok,1)-1)]';
trl = [trl; trlok];
end
end
|
github
|
lcnhappe/happe-master
|
inspect_qsubcellfun3.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/inspect_qsubcellfun3.m
| 1,266 |
utf_8
|
34dab50806cd673f776e8cd5752e5702
|
function inspect_qsubcellfun3
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_qsubcellfun3
% TEST qsubcellfun qsubfeval qsubget
% this should not run in the automated batch, because the torque queue
% will be completely full with other jobs, causing this job to timeout
if isempty(which('qsubcellfun'))
[ftver, ftpath] = ft_version;
addpath(fullfile(ftpath, 'qsub'));
end
result1 = cellfun(@subfunction, {1, 2, 3}, 'UniformOutput', false);
result2 = qsubcellfun(@subfunction, {1, 2, 3}, 'memreq', 1e8, 'timreq', 300, 'backend', 'local');
assert(isequal(result1, result2));
% % the following does not work, which is the correct behaviour
% % the subfunction cannot be located if passed as a string
% result2 = qsubcellfun('subfunction', {1, 2, 3}, 'memreq', 1e8, 'timreq', 300, 'backend', 'local');
% assert(isequal(result1, result2));
% this section was confirmed to work on 14 October 2012
result3 = qsubcellfun(@subfunction, {1, 2, 3}, 'memreq', 1e8, 'timreq', 300);
assert(isequal(result1, result3));
% this section fails on 14 October 2012
% result4 = qsubcellfun(@subsubfunction, {1, 2, 3}, 'memreq', 1e8, 'timreq', 300);
% assert(isequal(result1, result4));
function y = subfunction(x)
y = x.^2;
function y = subsubfunction(x)
y = subfunction(x);
|
github
|
lcnhappe/happe-master
|
test_printstruct.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_printstruct.m
| 2,606 |
utf_8
|
a851c70161c6ff3f6b68993939ce7bca
|
function test_printstruct
% MEM 4096mb
% WALLTIME 00:20:00
% the above requirements are quite big, but this script is inherently
% unpredictable
numtests = 10;
fprintf('generating %d random deep nested structures to test printstruct() serialization\n', numtests);
for k = 1:numtests
% generate some deep structure
mystruct = randomval('struct');
% get string version, assign new name
% FIXME think about whether printstruct itself should contain
% initialization to empty []
newstruct = [];
printversion = printstruct('newstruct', mystruct);
% eval() it
eval(printversion);
% check equality
% use abstol here because we know all floating point numeric values are
% generated from standard normal distribution
[ok,msg] = identical(mystruct, newstruct, 'abstol', 1e-6);
if ok
fprintf('printstruct() behaves as expected for random structure %d\n', k);
else
fprintf('printstruct() DOES NOT behave as expected for random structure %d\n', k);
fprintf('%s\n', msg{:});
error('test failed, see above for details');
end
end
end
%%%%%%%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%
function myval = randomval(type, depth)
if nargin < 2
depth = 0;
end
if depth > 3 && any(strcmp(type, {'struct' 'cell'}))
% don't nest too far (unnecessarily slows down the test)
myval = [];
return;
end
% the 64-bit int/uint types are not supported by matlab's randi(), so we
% don't test them here
types = {'double' 'double_complex' 'single' 'int8' 'int16' 'int32' 'uint8' 'uint16' 'uint32' 'logical' 'struct' 'cell'};
switch(type)
case 'struct'
numfields = 5 + randi(10);
for k = 1:numfields
name = sprintf('x%d', randi(intmax));
myval.(name) = randomval(types{randi(numel(types))}, depth + 1);
end
case 'cell'
numelem = randi(200);
alldepths = repmat({depth+1}, [1 numelem]);
alltypes = types(randi(numel(types), 1, numelem));
% structs and cells cannot be within a cell as far as printstruct is concerned
alltypes(strcmp(alltypes, 'struct') | strcmp(alltypes, 'cell')) = {'double'};
myval = cellfun(@randomval, alltypes, alldepths, 'uniformoutput', false);
case 'logical'
if rand() < 0.5
myval = false(randi(100),randi(100));
else
myval = true(randi(100),randi(100));
end
case 'double_complex'
siz = [randi(100), randi(100)];
myval = randn(siz) + 1i .* randn(siz);
case {'double' 'single'}
myval = randn(randi(100), randi(100));
case {'int8' 'int16' 'int32' 'uint8' 'uint16' 'uint32' 'uint64'}
myval = randi(200, randi(100), randi(100), type);
end
end
|
github
|
lcnhappe/happe-master
|
test_bug2639.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_bug2639.m
| 5,224 |
utf_8
|
c9dcca414ad6ef237af60845013ff6f9
|
function test_bug2639
% TEST test_bug2639
% TEST ft_checkdata
% MEM 2gb
% WALLTIME 00:10:00
shufflechan = [1 3 2]';
channelcmb = {
'1' '2'
'1' '3'
'2' '3'
};
%%
freq1o = [];
freq1o.freq = 1;
freq1o.label = {'1', '2', '3'}';
freq1o.dimord = 'chan_freq';
freq1o.powspctrm = reshape([1 2 3], [3 1]);
freq1r = freq1o;
freq1r.label = freq1o.label(shufflechan);
freq1r.powspctrm = freq1o.powspctrm(shufflechan,:);
freq2o = ft_checkdata(freq1o);
freq2r = ft_checkdata(freq1r);
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.powspctrm(selo,:), freq2r.powspctrm(selr,:)));
%%
freq1o = [];
freq1o.freq = 1;
freq1o.cumtapcnt = 1;
freq1o.label = {'1', '2', '3'}';
freq1o.dimord = 'rpt_chan_freq';
freq1o.fourierspctrm = reshape([1 2 3], [1 3 1]);
freq1r = freq1o;
freq1r.label = freq1o.label(shufflechan);
freq1r.fourierspctrm = freq1o.fourierspctrm(:,shufflechan,:);
freq2o = ft_checkdata(freq1o);
freq2r = ft_checkdata(freq1r);
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.fourierspctrm(:,selo,:), freq2r.fourierspctrm(:,selr,:)));
%% full, sparse, fourier, sparsewithpow, fullfast
freq2o = ft_checkdata(freq1o, 'cmbrepresentation', 'fourier');
freq2r = ft_checkdata(freq1r, 'cmbrepresentation', 'fourier');
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.fourierspctrm(:,selo,:), freq2r.fourierspctrm(:,selr,:)));
assert( isequal(freq1r.label,freq2r.label));
assert(~isequal(freq2o.label,freq2r.label));
freq2o = ft_checkdata(freq1o, 'cmbrepresentation', 'full');
freq2r = ft_checkdata(freq1r, 'cmbrepresentation', 'full');
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.crsspctrm(selo,selo), freq2r.crsspctrm(selr,selr)));
assert( isequal(freq1r.label,freq2r.label));
assert(~isequal(freq2o.label,freq2r.label));
freq2o = ft_checkdata(freq1o, 'cmbrepresentation', 'fullfast');
freq2r = ft_checkdata(freq1r, 'cmbrepresentation', 'fullfast');
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.crsspctrm(selo,selo), freq2r.crsspctrm(selr,selr)));
assert( isequal(freq1r.label,freq2r.label));
assert(~isequal(freq2o.label,freq2r.label));
freq2o = ft_checkdata(freq1o, 'cmbrepresentation', 'sparse', 'channelcmb', channelcmb);
freq2r = ft_checkdata(freq1r, 'cmbrepresentation', 'sparse', 'channelcmb', channelcmb);
[selo, selr] = match_strcmb(freq2o.labelcmb, freq2r.labelcmb);
assert(isequal(freq2o.crsspctrm(selo,:), freq2r.crsspctrm(selr,:)));
assert( isequal(freq2o.labelcmb,freq2r.labelcmb));
freq2o = ft_checkdata(freq1o, 'cmbrepresentation', 'sparsewithpow', 'channelcmb', channelcmb);
freq2r = ft_checkdata(freq1r, 'cmbrepresentation', 'sparsewithpow', 'channelcmb', channelcmb);
[selo, selr] = match_strcmb(freq2o.labelcmb, freq2r.labelcmb);
assert(isequal(freq2o.crsspctrm(selo,:), freq2r.crsspctrm(selr,:)));
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.powspctrm(:,selo,:), freq2r.powspctrm(:,selr,:)));
assert( isequal(freq1r.label,freq2r.label));
assert(~isequal(freq2o.label,freq2r.label));
assert( isequal(freq2o.labelcmb,freq2r.labelcmb));
%%
freq1o = [];
freq1o.freq = 1;
freq1o.cumtapcnt = 1;
freq1o.dimord = 'chancmb_freq';
freq1o.label = {'1', '2', '3'}';
freq1o.powspctrm = [1 2 3]';
freq1o.labelcmb = {
'1' '2'
'1' '3'
'2' '3'
};
freq1o.crsspctrm = [
2
3
6
];
freq1r = freq1o;
freq1r.label = freq1o.label(shufflechan);
freq1r.labelcmb = freq1o.labelcmb(shufflechan,:);
freq1r.powspctrm = freq1o.powspctrm(shufflechan,:);
freq1r.crsspctrm = freq1o.crsspctrm(shufflechan,:);
freq2o = ft_checkdata(freq1o);
freq2r = ft_checkdata(freq1r);
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.powspctrm(selo,:), freq2r.powspctrm(selr,:)));
[selo, selr] = match_strcmb(freq2o.labelcmb, freq2r.labelcmb);
assert(isequal(freq2o.crsspctrm(selo,:), freq2r.crsspctrm(selr,:)));
freq2o = ft_checkdata(freq1o, 'cmbrepresentation', 'full');
freq2r = ft_checkdata(freq1r, 'cmbrepresentation', 'full');
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.crsspctrm(selo,selo), freq2r.crsspctrm(selr,selr)));
% assert( isequal(freq1r.label,freq2r.label)); % this is where the channel reordering becomes clear
% assert(~isequal(freq2o.label,freq2r.label)); % this is where the channel reordering becomes clear
freq2o = ft_checkdata(freq1o, 'cmbrepresentation', 'fullfast');
freq2r = ft_checkdata(freq1r, 'cmbrepresentation', 'fullfast');
[selo, selr] = match_str(freq2o.label, freq2r.label);
assert(isequal(freq2o.crsspctrm(selo,selo), freq2r.crsspctrm(selr,selr))); % this is where another problem appears
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [sel1, sel2] = match_strcmb(chancmb1, chancmb2)
for i=1:size(chancmb1,1)
chan1{i} = sprintf('%s_%s', chancmb1{i,:});
end
for i=1:size(chancmb2,1)
chan2{i} = sprintf('%s_%s', chancmb2{i,:});
end
[sel1, sel2] = match_str(chan1, chan2);
|
github
|
lcnhappe/happe-master
|
test_tutorial_headmodel_meg.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_tutorial_headmodel_meg.m
| 1,927 |
utf_8
|
8075bf65196420c5b808e6585988c6ee
|
function test_tutorial_headmodel_meg(datadir)
% MEM 2000mb
% WALLTIME 00:45:00
% TEST test_tutorial_headmodel_meg
% TEST ft_read_mri ft_volumesegment ft_prepare_headmodel ft_plot_vol
% TEST ft_convert_units ft_read_sens ft_plot_sens
% intial version by Lilla Magyari
if nargin==0
datadir = '/home/common/matlab/fieldtrip/data/';
end
mri = ft_read_mri([datadir,'ftp/tutorial/beamformer/Subject01.mri']);
cfg = [];
cfg.output = 'brain';
segmentedmri = ft_volumesegment(cfg, mri);
% check if segmentation is equivalent with segmentation on the ftp site
segmentedmri2 = load([datadir,'ftp/tutorial/headmodel_meg/segmentedmri']);
segmentedmri=rmfield(segmentedmri,'cfg');
segmentedmri2=rmfield(segmentedmri2.segmentedmri,'cfg');
assert(isequal(segmentedmri2,segmentedmri),'The segmentation does not match the segmentation stored on the ftp site');
%
cfg = [];
cfg.method='singleshell';
vol = ft_prepare_headmodel(cfg, segmentedmri);
% check if vol is equivalent with vol on the ftp site
vol2 = load([datadir,'ftp/tutorial/headmodel_meg/vol']);
vol2 = vol2.vol; % copy it over
vol = tryrmfield(vol, 'cfg');
vol2 = tryrmfield(vol2,'cfg');
% it is presently (Dec 2013) a bit messy where the cfg and unit are being stored after ft_prepare_mesh
vol = tryrmsubfield(vol, 'bnd.unit');
vol2 = tryrmsubfield(vol2, 'bnd.unit');
vol = tryrmsubfield(vol, 'bnd.cfg');
vol2 = tryrmsubfield(vol2, 'bnd.cfg');
vol = ft_convert_units(vol, 'mm');
vol2 = ft_convert_units(vol2,'mm');
assert(identical(vol,vol2,'abstol',0.0001),'The headmodel does not match the headmodel stored on the ftp site.');
%
sens = ft_read_sens([datadir,'/Subject01.ds']);
vol = ft_convert_units(vol,'cm');
figure
ft_plot_sens(sens, 'style', '*b');
hold on
ft_plot_vol(vol);
function s = tryrmfield(s, f)
if isfield(s, f)
s = rmfield(s, f);
end
function s = tryrmsubfield(s, f)
if issubfield(s, f)
s = rmsubfield(s, f);
end
|
github
|
lcnhappe/happe-master
|
test_ft_freqanalysis.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_freqanalysis.m
| 8,404 |
utf_8
|
1befb77d0d1d1b8a05ebc8a98d591d04
|
function test_ft_freqanalysis(datainfo, writeflag, version)
% MEM 8000mb
% WALLTIME 01:30:00
% TEST test_ft_freqanalysis
% TEST ft_freqanalysis ref_datasets
% writeflag determines whether the output should be saved to disk
% version determines the output directory
if nargin<1
datainfo = ref_datasets;
end
if nargin<2
writeflag = 0;
end
if nargin<3
version = 'latest';
end
for k = 1:numel(datainfo)
datanew = freqanalysisMtmfft(datainfo(k), writeflag, version, 'fourier', 'yes');
fname = fullfile(datainfo(k).origdir,version,'freq',datainfo(k).type,['freq_mtmfft_fourier_trl_',datainfo(k).datatype]);
load(fname); datanew = rmfield(datanew, 'cfg'); freq = rmfield(freq, 'cfg');
[ok,msg] = identical(freq, datanew, 'reltol', 1e-6);
if ~ok, error('stored and computed data not identical: %s', msg{:}); end
datanew = freqanalysisMtmfft(datainfo(k), writeflag, version, 'powandcsd', 'yes');
fname = fullfile(datainfo(k).origdir,version,'freq',datainfo(k).type,['freq_mtmfft_powandcsd_trl_',datainfo(k).datatype]);
load(fname); datanew = rmfield(datanew, 'cfg'); freq = rmfield(freq, 'cfg');
[ok,msg] = identical(freq, datanew, 'reltol', 1e-6);
if ~ok, error('stored and computed data not identical: %s', msg{:}); end
datanew = freqanalysisMtmfft(datainfo(k), writeflag, version, 'pow', 'yes');
% fname = fullfile(datainfo(k).origdir,version,'freq',datainfo(k).type,['freq_mtmfft_pow_trl_',datainfo(k).datatype]);
% load(fname); datanew = rmfield(datanew, 'cfg'); freq = rmfield(freq, 'cfg');
% [ok,msg] = identical(freq, datanew, 'reltol', 1e-6);
% if ~ok, error('stored and computed data not identical: %s', msg{:}); end
datanew = freqanalysisMtmfft(datainfo(k), writeflag, version, 'powandcsd', 'no');
fname = fullfile(datainfo(k).origdir,version,'freq',datainfo(k).type,['freq_mtmfft_powandcsd_',datainfo(k).datatype]);
load(fname); datanew = rmfield(datanew, 'cfg'); freq = rmfield(freq, 'cfg');
[ok,msg] = identical(freq, datanew, 'reltol', 1e-6);
if ~ok, error('stored and computed data not identical: %s', msg{:}); end
datanew = freqanalysisMtmfft(datainfo(k), writeflag, version, 'pow', 'no');
fname = fullfile(datainfo(k).origdir,version,'freq',datainfo(k).type,['freq_mtmfft_',datainfo(k).datatype]);
load(fname);
datanew = rmfield(datanew, 'cfg'); % these are per construction different if writeflag = 0;
freq = rmfield(freq, 'cfg');
[ok,msg] = identical(freq, datanew,'reltol',1e-6);
if ~ok
error('stored and computed data not identical: %s', msg{:});
end
end
for k = 1:numel(datainfo)
datanew = freqanalysisMtmconvol(datainfo(k), writeflag, version, 'fourier', 'yes');
fname = fullfile(datainfo(k).origdir,version,'freq',datainfo(k).type,['freq_mtmconvol_fourier_trl_',datainfo(k).datatype]);
load(fname); datanew = rmfield(datanew, 'cfg'); freq = rmfield(freq, 'cfg');
[ok,msg] = identical(freq, datanew, 'reltol', 1e-6);
if ~ok, error('stored and computed data not identical: %s', msg{:}); end
datanew = freqanalysisMtmconvol(datainfo(k), writeflag, version, 'powandcsd', 'yes');
fname = fullfile(datainfo(k).origdir,version,'freq',datainfo(k).type,['freq_mtmconvol_powandcsd_trl_',datainfo(k).datatype]);
load(fname); datanew = rmfield(datanew, 'cfg'); freq = rmfield(freq, 'cfg');
[ok,msg] = identical(freq, datanew, 'reltol', 1e-6);
if ~ok, error('stored and computed data not identical: %s', msg{:}); end
datanew = freqanalysisMtmconvol(datainfo(k), writeflag, version, 'pow', 'yes');
datanew = freqanalysisMtmconvol(datainfo(k), writeflag, version, 'powandcsd', 'no');
fname = fullfile(datainfo(k).origdir,version,'freq',datainfo(k).type,['freq_mtmconvol_powandcsd_',datainfo(k).datatype]);
load(fname); datanew = rmfield(datanew, 'cfg'); freq = rmfield(freq, 'cfg');
[ok,msg] = identical(freq, datanew, 'reltol', 1e-6);
if ~ok, error('stored and computed data not identical: %s', msg{:}); end
datanew = freqanalysisMtmconvol(datainfo(k), writeflag, version, 'pow', 'no');
fname = fullfile(datainfo(k).origdir,version,'freq',datainfo(k).type,['freq_mtmconvol_',datainfo(k).datatype]);
load(fname);
datanew = rmfield(datanew, 'cfg'); % these are per construction different if writeflag = 0;
freq = rmfield(freq, 'cfg');
[ok,msg] = identical(freq, datanew,'reltol',eps*1e6);
if ~ok
error('stored and computed data not identical: %s', msg{:});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [freq] = freqanalysisMtmconvol(dataset, writeflag, version, output, keeptrials)
if isempty(output)
output = 'pow';
% output = 'powandcsd';
% output = 'fourier';
end
if isempty(keeptrials)
output = 'no';
% output = 'yes';
end
% the file names should distinguish between the cfg.output and cfg.keeptrials option
postfix = '';
switch output
case 'pow'
% don't change
case 'powandcsd'
postfix = [postfix 'powandcsd_'];
case 'fourier'
postfix = [postfix 'fourier_'];
otherwise
error('unexpected output');
end
% the file names should distinguish between the cfg.output and cfg.keeptrials option
switch keeptrials
case 'no'
% don't change
case 'yes'
postfix = [postfix 'trl_'];
otherwise
error('unexpected keeptrials');
end
% --- HISTORICAL --- attempt forward compatibility with function handles
if ~exist('ft_freqanalysis') && exist('freqanalysis')
eval('ft_freqanalysis = @freqanalysis;');
end
fprintf('testing mtmconvol with datatype=%s, output=%s, keeptrials=%s...\n',...
dataset.datatype, output, keeptrials);
cfg = [];
cfg.method = 'mtmconvol';
cfg.output = output;
cfg.keeptrials = keeptrials;
cfg.foi = 2:2:30;
cfg.taper = 'hanning';
cfg.t_ftimwin = ones(1,numel(cfg.foi)).*0.5;
cfg.toi = (250:50:750)./1000;
cfg.polyremoval= 0;
cfg.inputfile = fullfile(dataset.origdir,version,'raw',dataset.type,['preproc_',dataset.datatype]);
if writeflag,
cfg.outputfile = fullfile(dataset.origdir,version,'freq',dataset.type,['freq_mtmconvol_',postfix,dataset.datatype]);
end
if ~strcmp(version, 'latest') && str2num(version)<20100000
% -- HISTORICAL --- older FieldTrip versions don't support inputfile and outputfile
load(cfg.inputfile, 'data');
freq = ft_freqanalysis(cfg, data);
save(cfg.outputfile, 'freq');
else
freq = ft_freqanalysis(cfg);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [freq] = freqanalysisMtmfft(dataset, writeflag, version, output, keeptrials)
% --- HISTORICAL --- attempt forward compatibility with function handles
if ~exist('ft_freqanalysis') && exist('freqanalysis')
eval('ft_freqanalysis = @freqanalysis;');
end
if isempty(output)
output = 'pow';
% output = 'powandcsd';
% output = 'fourier';
end
if isempty(keeptrials)
keeptrials = 'no';
% keeptrials = 'yes';
end
% the file names should distinguish between the cfg.output and cfg.keeptrials option
postfix = '';
switch output
case 'pow'
% don't change
case 'powandcsd'
postfix = [postfix 'powandcsd_'];
case 'fourier'
postfix = [postfix 'fourier_'];
otherwise
error('unexpected output');
end
% the file names should distinguish between the cfg.output and cfg.keeptrials option
switch keeptrials
case 'no'
% don't change
case 'yes'
postfix = [postfix 'trl_'];
otherwise
error('unexpected keeptrials');
end
fprintf('testing mtmfft with datatype=%s, output=%s, keeptrials=%s...\n',...
dataset.datatype, output, keeptrials);
cfg = [];
cfg.method = 'mtmfft';
cfg.output = output;
cfg.keeptrials = keeptrials;
cfg.foilim = [0 100];
cfg.taper = 'hanning';
cfg.polyremoval= 0;
cfg.inputfile = fullfile(dataset.origdir,version,'raw',dataset.type,['preproc_',dataset.datatype]);
if writeflag,
cfg.outputfile = fullfile(dataset.origdir,version,'freq',dataset.type,['freq_mtmfft_',postfix,dataset.datatype]);
end
if ~strcmp(version, 'latest') && str2num(version)<20100000
% -- HISTORICAL --- older FieldTrip versions don't support inputfile and outputfile
load(cfg.inputfile, 'data');
freq = ft_freqanalysis(cfg, data);
save(cfg.outputfile, 'freq');
else
freq = ft_freqanalysis(cfg);
end
|
github
|
lcnhappe/happe-master
|
test_warning_once.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_warning_once.m
| 1,458 |
utf_8
|
2b8f09a3ad31a7f8ae5279e661006211
|
function test_warning_once
% MEM 1500mb
% WALLTIME 00:10:00
ft_warning('-clear');
warning1 = 'hululu';
warning2 = 'aloah hey';
for i=1:2
[output] = evalc(['warning_caller(warning1, warning2)']);
w1size = strfind(output, warning1);
w2size = strfind(output, warning2);
if numel(w1size)~=2 || numel(w2size)~=2
error('too few warnings thrown at iteration %d', i);
end
ft_warning('-clear');
end
[output] = evalc(['warning_caller(warning1, warning2)']);
w1size = strfind(output, warning1);
w2size = strfind(output, warning2);
if numel(w1size)~=2 || numel(w2size)~=2
error('too few warnings thrown at iteration %d', i);
end
% no clearing to verify whether these warnings stay!
% check some ft_ functions, therefore get dummy data
datainfo = ref_datasets;
dataset = datainfo(1);
load(fullfile(dataset.origdir,'latest','raw',dataset.type,['preproc_',dataset.datatype]));
cfg = [];
cfg.method = 'mtmconvol';
cfg.foi = 1:.01:2;
cfg.taper = 'hanning';
cfg.t_ftimwin = ones(1,numel(cfg.foi)).*0.5;
cfg.toi = (250:50:750)./1000;
cfg.polyremoval= 0;
% one warning should be thrown
ft_freqanalysis(cfg, data);
% again!
ft_freqanalysis(cfg, data);
end
function warning_caller(warning1, warning2)
for i=1:10
ft_warning(warning1);
ft_warning('FieldTrip:TEST', warning2);
end
% these warnings should be thrown now !again!
for i=1:10
ft_warning(warning1);
ft_warning('FieldTrip:TEST', warning2);
end
end
|
github
|
lcnhappe/happe-master
|
test_ft_connectivity_powcorr_ortho.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_connectivity_powcorr_ortho.m
| 985 |
utf_8
|
ab81c598019efd18451700831a55be59
|
function test_ft_connectivity_powcorr_ortho
% MEM 1500mb
% WALLTIME 00:10:00
% TEST: test_ft_connectivity_powcorr_ortho
% TEST: ft_connectivity_powcorr_ortho
mom1 = randn(1,100)+1i*randn(1,100);
mom2 = randn(1,100)+1i*randn(1,100);
c = ft_connectivity_powcorr_ortho([mom1;mom2], 'refindx', 1);
c = c(2,:);
[c1, c2] = hipp_testfunction(mom1, mom2);
%assert(all(abs(c-[c1 c2])<10*eps));
assert(all(abs(c-(c1+c2)./2)<10*eps));
% subfunction that does the computation according to the paper
% Nat Neuro 2012 Hipp et al.
function [c1, c2] = hipp_testfunction(mom1, mom2)
% normalise the amplitudes
mom1n = mom1./abs(mom1);
mom2n = mom2./abs(mom2);
% rotate
mom12 = mom1.*conj(mom2n);
mom21 = mom2.*conj(mom1n);
% take the projection along the imaginary axis
mom12i = abs(imag(mom12));
mom21i = abs(imag(mom21));
% compute the correlation on the log transformed power values
c1 = corr(log10(mom12i.^2'), log10(abs(mom2).^2'));
c2 = corr(log10(mom21i.^2'), log10(abs(mom1).^2'));
|
github
|
lcnhappe/happe-master
|
test_ft_timelockanalysis.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_timelockanalysis.m
| 2,917 |
utf_8
|
544f3d9ad6b049dc2e929a3fd9bf8ec1
|
function test_ft_timelockanalysis(datainfo, writeflag, version)
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_ft_timelockanalysis
% ft_timelockanalysis ref_datasets
% writeflag determines whether the output should be saved to disk
% version determines the output directory
if nargin<1
datainfo = ref_datasets;
end
if nargin<2
writeflag = 0;
end
if nargin<3
version = 'latest';
end
for k = 1:numel(datainfo)
datanew = timelockanalysis10trials(datainfo(k), writeflag, version, 'yes', 'yes');
datanew = timelockanalysis10trials(datainfo(k), writeflag, version, 'yes', 'no');
datanew = timelockanalysis10trials(datainfo(k), writeflag, version, 'no', 'yes');
datanew = timelockanalysis10trials(datainfo(k), writeflag, version, 'no', 'no'); % should be the latest
fname = fullfile(datainfo(k).origdir,version,'timelock',datainfo(k).type,['timelock_',datainfo(k).datatype]);
tmp = load(fname);
if isfield(tmp, 'data')
data = tmp.data;
elseif isfield(tmp, 'datanew')
data = tmp.datanew;
else isfield(tmp, 'timelock')
data = tmp.timelock;
end
datanew = removefields(datanew, 'cfg'); % these are per construction different if writeflag = 0;
data = removefields(data, 'cfg');
[ok,msg] = identical(data, datanew,'reltol',eps*1e6);
disp(['now you are in k=' num2str(k)]);
if ~ok
error('stored and computed data not identical: %s', msg{:});
end
end
function [timelock] = timelockanalysis10trials(dataset, writeflag, version, covariance, keeptrials)
% --- HISTORICAL --- attempt forward compatibility with function handles
if ~exist('ft_timelockanalysis') && exist('timelockanalysis')
eval('ft_timelockanalysis = @timelockanalysis;');
end
if isempty(covariance)
covariance = 'no';
% covariance = 'yes';
end
if isempty(keeptrials)
keeptrials = 'no';
% keeptrials = 'yes';
end
% the file names should distinguish between the cfg.covariance and cfg.keeptrials option
postfix = '';
switch covariance
case 'no'
% don't change
case 'yes'
postfix = [postfix 'cov_'];
otherwise
error('unexpected keeptrials');
end
% the file names should distinguish between the cfg.covariance and cfg.keeptrials option
switch keeptrials
case 'no'
% don't change
case 'yes'
postfix = [postfix 'trl_'];
otherwise
error('unexpected keeptrials');
end
cfg = [];
cfg.keeptrials = keeptrials;
cfg.covariance = covariance;
cfg.inputfile = fullfile(dataset.origdir,version,'raw',dataset.type,['preproc_',dataset.datatype]);
if writeflag
cfg.outputfile = fullfile(dataset.origdir,version,'timelock',dataset.type,['timelock_',postfix,dataset.datatype]);
end
if ~strcmp(version, 'latest') && str2num(version)<20100000
% -- HISTORICAL --- older FieldTrip versions don't support inputfile and outputfile
load(cfg.inputfile, 'data');
timelock = ft_timelockanalysis(cfg, data);
save(cfg.outputfile, 'timelock');
else
timelock = ft_timelockanalysis(cfg);
end
|
github
|
lcnhappe/happe-master
|
test_ft_prepare_mesh.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_prepare_mesh.m
| 6,496 |
utf_8
|
1509c54e1eea7cffc5bf32566f1d1a85
|
function test_ft_prepare_mesh
% MEM 1500mb
% WALLTIME 00:10:00
% test ft_prepare_mesh also used for constructing SIMBIO FEM head models
% see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1815
% TEST test_ft_prepare_mesh
% TEST ft_prepare_mesh ft_datatype_segmentation ft_plot_mesh
%% segmentations
example.dim = [30 29 31]; % slightly different numbers
example.transform = eye(4);
example.coordsys = 'ctf';
example.unit = 'mm';
example.seg = zeros(example.dim);
% adjusting transformation matrix: center of the head-coordinates [0 0 0] should
% be the center of volume
% center of volume in voxel coordinates
x = round(example.dim(1)/2);
y = round(example.dim(2)/2);
z = round(example.dim(3)/2);
x = round(x);
y = round(y);
z = round(z);
origin = [x y z];
example.transform(1:4,4) = [-origin(:); 1]; % head-coordinate [0 0 0] is in the center of
% the volume (x y z in voxel-coordinates)
% compute position for each voxel in voxelspace and in headspace
[X, Y, Z] = ndgrid(1:example.dim(1), 1:example.dim(2), 1:example.dim(3));
voxelpos = [X(:) Y(:) Z(:)];
headpos = ft_warp_apply(example.transform, voxelpos);
% create 5 spheres
radius1 = 14;
radius2 = 12;
radius3 = 10;
radius4 = 8;
radius5 = 6;
for i=1:size(headpos,1)
% from small to large
if norm(headpos(i,:))<radius5
example.seg(i) = 5;
elseif norm(headpos(i,:))<radius4
example.seg(i) = 4;
elseif norm(headpos(i,:))<radius3
example.seg(i) = 3;
elseif norm(headpos(i,:))<radius2
example.seg(i) = 2;
elseif norm(headpos(i,:))<radius1
example.seg(i) = 1;
end
end
clear X Y Z headpos origin radius1 radius2 radius3 voxelpos x y z
% indexed segmentation
% 5 tissue-types
seg5 = example;
clear example;
close all;
figure; imagesc(seg5.seg(:,:,15));
% 3 tissue-types
seg3 = seg5;
seg3.seg(seg5.seg(:)==4)=3;
seg3.seg(seg5.seg(:)==5)=3;
figure; imagesc(seg3.seg(:,:,15));
% 1 tissue-types
seg1 = seg3;
seg1.seg(seg3.seg(:)==2)=1;
seg1.seg(seg3.seg(:)==3)=1;
figure; imagesc(seg1.seg(:,:,15));
% probablistic segmentations
seg5p = ft_datatype_segmentation(seg5,'segmentationstyle','probabilistic');
seg3p = ft_datatype_segmentation(seg3,'segmentationstyle','probabilistic');
seg1p = ft_datatype_segmentation(seg1,'segmentationstyle','probabilistic');
%% mesh %%%%%%%%%%%%%%%%%
%% default: triangulation
cfg=[];
cfg.numvertices = 1000;
meshA = ft_prepare_mesh(cfg,seg1p);
meshB = ft_prepare_mesh(cfg,seg1);
assert(isequalwithoutcfg(meshA,meshB),'error: 01');
assert(isfield(meshA,'pnt') && isfield(meshA,'tri') && isfield(meshA,'unit'), 'Missing field(s) in mesh structure');
assert((cfg.numvertices == size(meshA.pnt,1)) , 'Number of points is not equal to required');
cfg=[];
cfg.numvertices = 1000;
meshA = ft_prepare_mesh(cfg,seg3p);
meshB = ft_prepare_mesh(cfg,seg3);
assert(isequalwithoutcfg(meshA,meshB),'error: 02');
assert(isfield(meshA(1),'pnt') && isfield(meshA(1),'tri') && isfield(meshA(1),'unit'), 'Missing field(s) in mesh structure');
assert((cfg.numvertices == size(meshA(1).pnt,1)) && (cfg.numvertices == size(meshA(2).pnt,1)) && (cfg.numvertices == size(meshA(3).pnt,1)), 'Number of points is not equal to required');
cfg=[];
cfg.numvertices = 1000;
meshA = ft_prepare_mesh(cfg,seg5p);
meshB = ft_prepare_mesh(cfg,seg5);
assert(isequalwithoutcfg(meshA,meshB),'error: 03');
assert(isfield(meshA(1),'pnt') && isfield(meshA(1),'tri') && isfield(meshA(1),'unit'), 'Missing field(s) in mesh structure');
assert((cfg.numvertices == size(meshA(1).pnt,1)) && (cfg.numvertices == size(meshA(2).pnt,1)) && (cfg.numvertices == size(meshA(3).pnt,1)) && (cfg.numvertices == size(meshA(4).pnt,1)) && (cfg.numvertices == size(meshA(5).pnt,1)), 'Number of points is not equal to required');
figure; ft_plot_mesh(meshA,'facecolor','none');
%% method: hexahedral
cfg=[];
cfg.method = 'hexahedral';
cfg.numvertices = 1000;
meshA = ft_prepare_mesh(cfg,seg1p);
meshB = ft_prepare_mesh(cfg,seg1);
assert(isequalwithoutcfg(meshA,meshB),'error: 04');
assert(isfield(meshA,'pnt') && isfield(meshA,'hex') && isfield(meshA,'unit'), 'Missing field(s) in mesh structure');
cfg=[];
cfg.method = 'hexahedral';
cfg.numvertices = 1000;
meshA = ft_prepare_mesh(cfg,seg3p);
meshB = ft_prepare_mesh(cfg,seg3);
meshA=rmfield(meshA,'tissuelabel');
meshB=rmfield(meshB,'tissuelabel');
assert(isequalwithoutcfg(meshA,meshB),'error: 05');
assert(isfield(meshA,'pnt') && isfield(meshA,'hex') && isfield(meshA,'unit'), 'Missing field(s) in mesh structure');
cfg=[];
cfg.method = 'hexahedral';
cfg.numvertices = 1000;
meshA = ft_prepare_mesh(cfg,seg5p);
meshB = ft_prepare_mesh(cfg,seg5);
meshA=rmfield(meshA,'tissuelabel');
meshB=rmfield(meshB,'tissuelabel');
assert(isequalwithoutcfg(meshA,meshB),'error: 06');
assert(isfield(meshA,'pnt') && isfield(meshA,'hex') && isfield(meshA,'unit'), 'Missing field(s) in mesh structure');
figure; ft_plot_mesh(meshA,'surfaceonly','yes')
%% tissue specified
cfg=[];
cfg.tissue='tissue_1';
cfg.numvertices=3000;
meshA=ft_prepare_mesh(cfg,seg3)
meshB=ft_prepare_mesh(cfg,seg3p)
assert(isequalwithoutcfg(meshA,meshB),'error: 07');
assert(isfield(meshA,'pnt') && isfield(meshA,'tri') && isfield(meshA,'unit'), 'Missing field(s) in mesh structure');
cfg.method='hexahedral';
meshA=ft_prepare_mesh(cfg,seg3)
meshB=ft_prepare_mesh(cfg,seg3p)
assert(isequalwithoutcfg(meshA,meshB),'error: 08');
assert(isfield(meshA,'pnt') && isfield(meshA,'hex') && isfield(meshA,'unit'), 'Missing field(s) in mesh structure');
assert(isequalwithoutcfg(meshA.tissuelabel, {'tissue_1'}), 'error:09');
cfg.tissue='tissue_2';
meshB=ft_prepare_mesh(cfg,seg3)
assert(isequalwithoutcfg(meshB.tissuelabel, {'tissue_2'}), 'error:10');
meshA=rmfield(meshA,'tissuelabel');
meshB=rmfield(meshB,'tissuelabel');
assert(~(isequalwithoutcfg(meshA,meshB)),'error: 11');
cfg.tissue={'tissue_2' 'tissue_1'};
meshC=ft_prepare_mesh(cfg,seg3);
assert(isequalwithoutcfg(meshC.tissuelabel, cfg.tissue), 'error:12');
meshC=rmfield(meshC,'tissuelabel');
assert(~(isequalwithoutcfg(meshA,meshC)),'error: 13');
assert(~(isequalwithoutcfg(meshB,meshC)),'error: 14');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function c = isequalwithoutcfg(a, b)
if isfield(a, 'cfg')
a = rmfield(a, 'cfg');
end
if isfield(b, 'cfg')
b = rmfield(b, 'cfg');
end
c = isequal(a, b);
|
github
|
lcnhappe/happe-master
|
trialfun_affcog.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/trialfun_affcog.m
| 1,267 |
utf_8
|
559386a8dcd6b0a2b6966552240ca5f9
|
function [trl, event] = trialfun_affcog(cfg)
%% the first part is common to all trial functions
% read the header (needed for the samping rate) and the events
hdr = ft_read_header(cfg.headerfile);
event = ft_read_event(cfg.headerfile);
%% from here on it becomes specific to the experiment and the data format
% for the events of interest, find the sample numbers (these are integers)
% for the events of interest, find the trigger values (these are strings in the case of BrainVision)
EVsample = [event.sample]';
EVvalue = {event.value}';
% select the target stimuli
Word = find(strcmp('S141', EVvalue)==1);
% for each word find the condition
for w = 1:length(Word)
% code for the judgement task: 1 => Affective; 2 => Ontological;
if strcmp('S131', EVvalue{Word(w)+1}) == 1
task(w,1) = 1;
elseif strcmp('S132', EVvalue{Word(w)+1}) == 1
task(w,1) = 2;
end
end
PreTrig = round(0.2 * hdr.Fs);
PostTrig = round(1 * hdr.Fs);
begsample = EVsample(Word) - PreTrig;
endsample = EVsample(Word) + PostTrig;
offset = -PreTrig*ones(size(endsample));
%% the last part is again common to all trial functions
% return the trl matrix (required) and the event structure (optional)
trl = [begsample endsample offset task];
end % function
|
github
|
lcnhappe/happe-master
|
test_bug1397.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_bug1397.m
| 3,150 |
utf_8
|
0a032e78d8becf9f7f3c7c25f069b8b3
|
function test_bug1397
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_bug1397
% TEST ft_preprocessing ft_appenddata
% the following code was obtained from http://www.fieldtriptoolbox.org/tutorial/coherence
% on Wed Mar 28 15:36:40 CEST 2012
% find the interesting epochs of data
cfg = [];
% MODIFICATION, use trialfun handle and other path to the data
cfg.trialfun = @trialfun_left;
cfg.dataset = '/home/common/matlab/fieldtrip/data/SubjectCMC.ds';
cfg = ft_definetrial(cfg);
% MODIFICATION, use only 10 trials
cfg.trl = cfg.trl(1:10,:);
% MODIFICATION, the following should not affect the problem
%
% % detect EOG artifacts in the MEG data
% cfg.continuous = 'yes';
% cfg.artfctdef.eog.padding = 0;
% cfg.artfctdef.eog.bpfilter = 'no';
% cfg.artfctdef.eog.detrend = 'yes';
% cfg.artfctdef.eog.hilbert = 'no';
% cfg.artfctdef.eog.rectify = 'yes';
% cfg.artfctdef.eog.cutoff = 2.5;
% cfg.artfctdef.eog.interactive = 'no';
% cfg = ft_artifact_eog(cfg);
%
% % detect jump artifacts in the MEG data
% cfg.artfctdef.jump.interactive = 'no';
% cfg.padding = 5;
% cfg = ft_artifact_jump(cfg);
%
% % detect muscle artifacts in the MEG data
% cfg.artfctdef.muscle.cutoff = 8;
% cfg.artfctdef.muscle.interactive = 'no';
% cfg = ft_artifact_muscle(cfg);
%
% % reject the epochs that contain artifacts
% cfg.artfctdef.reject = 'complete';
% cfg = ft_rejectartifact(cfg);
% preprocess the MEG data
cfg.demean = 'yes';
cfg.dftfilter = 'yes';
cfg.channel = {'MEG'};
cfg.continuous = 'yes';
meg = ft_preprocessing(cfg);
cfg = [];
cfg.dataset = meg.cfg.dataset;
cfg.trl = meg.cfg.trl;
cfg.continuous = 'yes';
cfg.demean = 'yes';
cfg.dftfilter = 'yes';
cfg.channel = {'EMGlft' 'EMGrgt'};
cfg.hpfilter = 'yes';
cfg.hpfreq = 10;
cfg.rectify = 'yes';
emg = ft_preprocessing(cfg);
% see http://bugzilla.fcdonders.nl/show_bug.cgi?id=1397
% the reported problem in fieldtrip-20120302 was
%
% ??? Error using ==> ft_appenddata at 266
% there is a difference in the time axes of the input data
data = ft_appenddata([], meg, emg);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to avoid external dependencies of this test
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function trl = trialfun_left(cfg)
% read in the triggers and create a trial-matrix
% consisting of 1-second data segments, in which
% left ECR-muscle is active.
event = ft_read_event(cfg.dataset);
trig = [event(find(strcmp('backpanel trigger', {event.type}))).value];
indx = [event(find(strcmp('backpanel trigger', {event.type}))).sample];
%left-condition
sel = [find(trig==1028):find(trig==1029)];
trig = trig(sel);
indx = indx(sel);
trl = [];
for j = 1:length(trig)-1
trg1 = trig(j);
trg2 = trig(j+1);
if trg1<=100 & trg2==2080,
trlok = [[indx(j)+1:1200:indx(j+1)-1200]' [indx(j)+1200:1200:indx(j+1)]'];
trlok(:,3) = [0:-1200:-1200*(size(trlok,1)-1)]';
trl = [trl; trlok];
end
end
|
github
|
lcnhappe/happe-master
|
test_bug1618.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_bug1618.m
| 449 |
utf_8
|
76ec9df5e64a5bca83b6011dbde758b8
|
function test_suite = test_bug1618
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_bug1618
% add xunit to path
ft_hastoolbox('xunit',1);
initTestSuite; % for xUnit
function test_no_nan
% TODO: load example data, test for absence of NAN.
h = ft_read_header('data_bug1618/bug1618.dat');
h
h.chanunit
h.chantype
X = ft_read_data('data_bug1618/bug1618.dat');
assert(~any(isnan(X(:))), 'NaN values are not expected for this dataset!');
|
github
|
lcnhappe/happe-master
|
test_ft_crossfrequencyanalysis.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_crossfrequencyanalysis.m
| 6,513 |
utf_8
|
d38e768a1f5937af96f9a351237c54a5
|
function test_ft_crossfrequencyanalysis
% MEM 2gb
% WALLTIME 0:15:00
% TEST test_ft_crossfrequencyanalysis
% TEST ft_crossfrequencyanalysis
clear all;
close all;
%%%%%% generate simulation data %%%%%%%%%%%%%
% channels
N = 2;
s = zeros(N,4000);
for i = 1:N
num = 45; % number of alpha cycles
fs = 1000; % sampling frequency
hf = 70; % gamma frequency
shift ='lead'; timdiff = 10; % for directionality only
a = 10; c = 6; % a(slope)/c(threshold) : Sigmoid function parameter sigmf(x, [a, c]) = 1./(1 + exp(-a*(x-c)))
n1 = rand(1); % Gaussian white noise level
n2 = rand(1); % pink noise level
[sig,T] = inhibition(num,fs,shift,timdiff,hf,a,c,n1,n2);
s(i,:) = sig(4,1:4000);
end
% trials
M = 20;
ftdata = zeros(M,N,4000); % M trials *N Channels*times
for j = 1:M
ftdata(j,:,:) = s+rand(N,4000);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% stored in FieldTrip fashion
data = [];
data.time = cell(1,M);
data.trial = cell(1,M);
for i =1:M
data.time{1,i} = T(1:4000);
data.trial{1,i} = squeeze(ftdata(i,:,:));
end
data.fsample = 1000;
data.label = cell(N,1);
for j = 1:N
data.label{j,1} = strcat('chan',num2str(j));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
f1 = 4:1:20; % interest low frequency range of CFC
f2 = 30:10:150; % interest high frequency range of CFC
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% extract low frquency signal
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cfg = [];
cfg.output = 'fourier';
cfg.channel = 'all';
cfg.method = 'mtmconvol';
cfg.taper = 'hanning';
cfg.foi = f1;
cfg.t_ftimwin = ones(length(cfg.foi),1).*0.5;
cfg.toi = 0.5:1/data.fsample:3.5;
LFsig = ft_freqanalysis(cfg, data);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% extract high frquency evelope signal
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cfg = [];
cfg.output = 'fourier';
cfg.channel = 'all';
cfg.method = 'mtmconvol';
cfg.taper = 'hanning';
cfg.foi = f2;
cfg.t_ftimwin = 5./cfg.foi;
cfg.toi = 0.5:1/data.fsample:3.5;
HFsig = ft_freqanalysis(cfg, data);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% do the actual testing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cfg = [];
cfg.method = 'plv';
cfg.keeptrials = 'no';
CFC = ft_crossfrequencyanalysis(cfg,LFsig,HFsig);
subplot(311)
MI = squeeze(CFC.crsspctrm(1,:,:));
imagesc(f1, f2, MI');
% set(gca, 'Fontsize',20)
axis xy;
xlabel('Low frequency (Hz)');
ylabel('High frequency (Hz)');
title('Phase locking value')
axis xy; colorbar
cfg =[];
cfg.method ='mvl';
cfg.keeptrials = 'no';
CFC = ft_crossfrequencyanalysis(cfg,LFsig,HFsig);
subplot(312)
MI = squeeze(CFC.crsspctrm(1,:,:));
imagesc(f1, f2, MI');
% set(gca, 'Fontsize',20)
axis xy;
xlabel('Low frequency (Hz)');
ylabel('High frequency (Hz)');
title('mean vector length')
axis xy; colorbar
cfg =[];
cfg.method = 'mi';
cfg.keeptrials = 'no';
CFC = ft_crossfrequencyanalysis(cfg,LFsig,HFsig);
subplot(313)
MI = squeeze(CFC.crsspctrm(1,:,:));
imagesc(f1, f2, MI');
% set(gca, 'Fontsize',20)
axis xy;
xlabel('Low frequency (Hzrand(2,4000))');
ylabel('High frequency (Hz)');
title('Modulation index')
axis xy; colorbar
end % main function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [sigs, T2]=inhibition(num,fs,shift,timdiff,hf,a,c,n1,n2)
% generate simulation data
% input:
% num: number of alpha cycles
% fs: sampling frequency
% hf: gamma frequency
% shift: create directionality either alpha leads gamma or alpha lags gamma
% timdiff: alpha and gamma time lag
% a(slope)/c(threshold) : Sigmoid function parameter sigmf(x, [a, c]) = 1./(1 + exp(-a*(x-c)))
% n1 : Gaussian white noise level
% n2 : pinck noise level
% output:
% sigs: four signals {alpha0;alphas;gamma;mix} 4*T2 we are looking CFC at mix channel sigs(4,:)
% T2 time series index
% copyright @Haiteng Jiang
dt = 1/fs;
Time = 0.1 + 0.02.*randn(num,1); % alpha range cycle length 80-120 ms
amps = 2 + 0.5.*randn(num,1); % fluctuated alpha amplitude
alpha = [];
alpha2 = [];
% generate fluctuated amplitude alpha signal
for i = 1:num
T = Time(i);
t = 0:dt:T-dt;
N = length(t);
sig = (1+sin(1/T* 2*pi*t+1.5*pi));
alpha2 = [alpha2 sig];
sig = amps(i)*sig; % fluctuated alpha amplitude
alpha = [alpha sig];
end
alpha = 6* alpha; % enhanced amplitude to be more real
T1 = 0:dt:length(alpha)*dt-dt;
T2 = 0:dt:(length(alpha)-timdiff)*dt-dt;
% sigmoid threshold gamma
gammas = (1-1./(1 + exp(-a*(alpha-c)))).*(sin(2*pi*hf*T1)+1);
% shift to creat directionality not mean for CFC
switch shift
case {'lead'} % alpha leads gamma
alphastemp = zeros(1,length(alpha));
for i = 1:length(alpha)-timdiff
alphastemp(i) = alpha(i+timdiff);
end
alphas = alphastemp(1:end-timdiff);
gamma = gammas(1:end-timdiff);
case{'delay'} % alpha lags gamma
alphastemp = zeros(1,length(alpha));
for i = timdiff+1:length(alpha)
alphastemp(i) = alpha(i-timdiff);
end
alphas(1:length(T2))= alphastemp(timdiff+1:length(alpha));
gamma = gammas(timdiff+1:end);
otherwise % no directionality
alphas = alpha(1:end-timdiff);
gamma = gammas(1:end-timdiff);
end
alpha0 = alpha2(1:length(T2));
mix = alphas+gamma+n1*randn([1,length(T2)])+n2*pinknoise(numel(T2)); % signal we analysis
sigs = [alpha0;alphas;gamma;mix];
function x = pinknoise(Nx)
% pink noise
B = [0.049922035 -0.095993537 0.050612699 -0.004408786];
A = [1 -2.494956002 2.017265875 -0.522189400];
nT60 = round(log(1000)/(1-max(abs(roots(A))))); % T60 est.
v = randn(1,Nx+nT60); % Gaussian white noise: N(0,1)
x = filter(B,A,v); % Apply 1/F roll-off to PSD
x = x(nT60+1:end); % Skip transient response
end
end
|
github
|
lcnhappe/happe-master
|
test_ft_selectdata.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_selectdata.m
| 25,710 |
utf_8
|
8c3047968d7baeba558f3d6580c426e9
|
function test_ft_selectdata
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_ft_selectdata
% TEST ft_selectdata ft_selectdata_old ft_selectdata_new ft_appendfreq
timelock1 = [];
timelock1.label = {'1' '2'};
timelock1.time = 1:5;
timelock1.dimord = 'chan_time';
timelock1.avg = randn(2,5);
cfg = [];
cfg.channel = 1;
timelock1a = ft_selectdata(cfg, timelock1);
assert(isequal(size(timelock1a.avg), [1 5]));
cfg = [];
timelock2 = ft_appendtimelock(cfg, timelock1, timelock1, timelock1);
cfg = [];
cfg.channel = 1;
timelock2a = ft_selectdata(cfg, timelock2);
assert(isequal(size(timelock2a.trial), [3 1 5]));
cfg = [];
cfg.trials = [1 2];
timelock2b = ft_selectdata(cfg, timelock2);
assert(isequal(size(timelock2b.trial), [2 2 5]));
% The one that follows is a degenerate case. By selecting only one trial,
% the output is not really trial-based any more, but still contains one trial.
cfg = [];
cfg.trials = 1;
timelock2c = ft_selectdata(cfg, timelock2);
assert(isequal(size(timelock2c.trial), [1 2 5]));
% assert(isequal(size(timelock2c.trial), [2 5]));
%-------------------------------------
%generate data
data = [];
data.fsample = 1000;
data.cfg = [];
nsmp = 1000;
nchan = 80;
for k = 1:10
data.trial{k} = randn(nchan,nsmp);
data.time{k} = ((1:nsmp)-1)./data.fsample;
end
% create grad-structure and add to data
grad.pnt = randn(nchan,3);
grad.ori = randn(nchan,3);
grad.tra = eye(nchan);
for k = 1:nchan
grad.label{k,1} = ['chan',num2str(k,'%03d')];
end
data.grad = ft_datatype_sens(grad);
data.label = grad.label;
data.trialinfo = (1:10)';
data = ft_checkdata(data, 'hassampleinfo', 'yes');
%% this part of the script tests the functionality of ft_selectdata with respect
% to raw data.
compare_outputs(data, 'channel', data.label([5 8 12 38]));
% compare_outputs(data, 'channel', {}); % works neither with new nor old
compare_outputs(data, 'channel', 'all');
compare_outputs(data, 'trials', [3 4 6 9]);
compare_outputs(data, 'trials', []);
compare_outputs(data, 'trials', 'all');
% FIXME also test latency
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% this part of the script tests the functionality of ft_selectdata with respect
% to selecting the primary or a secondary dimord
freq = [];
freq.powspctrm = randn(3, 4, 5);
freq.dimord = 'chan_freq_time';
freq.crsspctrm = randn(3, 3, 4, 5);
freq.crsspctrmdimord = 'chan_chan_freq_time';
freq.label = {'1', '2', '3'};
freq.freq = 1:4;
freq.time = 1:5;
cfg = [];
freqpow = ft_selectdata(cfg, freq)
cfg = [];
cfg.parameter = 'powspctrm';
freqpow = ft_selectdata(cfg, freq)
cfg = [];
cfg.parameter = 'crsspctrm';
freqcrs = ft_selectdata(cfg, freq)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% this part of the script tests the functionality of ft_selectdata with respect
% to averaging over each dimension
% rpt_chan_freq_time
freq = [];
freq.dimord = 'rpt_chan_freq_time';
freq.label = {'1', '2', '3'};
freq.freq = 1:4;
freq.time = 1:5;
freq.powspctrm = randn(2, 3, 4, 5);
cfg = [];
cfg.avgoverrpt = 'yes';
cfg.keeprptdim = 'yes';
freq_avgoverrpt = ft_selectdata(cfg, freq)
cfg.keeprptdim = 'no';
freq_avgoverrpt = ft_selectdata(cfg, freq)
cfg = [];
cfg.avgoverchan = 'yes';
cfg.keepchandim = 'yes';
freq_avgoverchan = ft_selectdata(cfg, freq)
cfg.keepchandim = 'no';
freq_avgoverchan = ft_selectdata(cfg, freq)
cfg = [];
cfg.avgoverfreq = 'yes';
cfg.keepfreqdim = 'yes';
freq_avgoverfreq = ft_selectdata(cfg, freq)
cfg.keepfreqdim = 'no';
freq_avgoverfreq = ft_selectdata(cfg, freq)
cfg = [];
cfg.avgovertime = 'yes';
cfg.keeptimedim = 'yes';
freq_avgovertime = ft_selectdata(cfg, freq)
cfg.keeptimedim = 'no';
freq_avgovertime = ft_selectdata(cfg, freq)
cfg = [];
cfg.avgoverrpt = 'yes';
cfg.avgoverchan = 'yes';
cfg.avgoverfreq = 'yes';
cfg.avgovertime = 'yes';
freq_avgoverall = ft_selectdata(cfg, freq)
% rpt_chan_time
timelock = [];
timelock.dimord = 'rpt_chan_time';
timelock.label = {'1', '2', '3'};
timelock.time = 1:4;
timelock.avg = randn(2, 3, 4);
cfg = [];
cfg.avgoverrpt = 'yes';
timelock_avgoverrpt = ft_selectdata(cfg, timelock)
cfg = [];
cfg.avgoverchan = 'yes';
timelock_avgoverchan = ft_selectdata(cfg, timelock)
cfg = [];
cfg.avgoverrpt = 'yes';
cfg.avgoverchan = 'yes';
cfg.avgovertime = 'yes';
timelock_avgoverall = ft_selectdata(cfg, timelock)
% rpt_chan_time
cfg = [];
cfg.avgovertime = 'yes';
timelock_avgovertime = ft_selectdata(cfg, timelock)
timelock = [];
timelock.dimord = 'chan_time';
timelock.label = {'1', '2', '3'};
timelock.time = 1:4;
timelock.avg = randn(3, 4);
cfg = [];
cfg.avgoverchan = 'yes';
timelock_avgoverchan = ft_selectdata(cfg, timelock)
cfg = [];
cfg.avgovertime = 'yes';
timelock_avgovertime = ft_selectdata(cfg, timelock)
cfg = [];
cfg.avgoverchan = 'yes';
cfg.avgovertime = 'yes';
timelock_avgoverall = ft_selectdata(cfg, timelock)
source = [];
source.dim = [10 11 12];
source.transform = eye(4);
source.avg.pow = rand(10*11*12,1);
source.inside = 1:660;
source.outside = 661:1320;
cfg = [];
cfg.avgoverpos = 'yes';
output = ft_selectdata(cfg, source)
assert(output.pos(1)==5.5);
assert(output.pos(2)==6.0);
assert(output.pos(3)==6.5);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% this part of the script tests the functionality of ft_selectdata with respect
% to freqdata. it implements the (old) test_ft_selectdata_freqdata
% do spectral analysis
cfg = [];
cfg.method = 'mtmfft';
cfg.output = 'fourier';
cfg.foilim = [2 100];
cfg.pad = 1;
cfg.tapsmofrq = 3;
freq = ft_freqanalysis(cfg, data);
cfg.output = 'pow';
cfg.keeptrials = 'yes';
freqp = ft_freqanalysis(cfg, data);
cfg.output = 'powandcsd';
cfg.channelcmb = ft_channelcombination([data.label(1) {'all'};data.label(2) {'all'}], data.label);
freqc = ft_freqanalysis(cfg, data);
cfg = [];
cfg.method = 'mtmconvol';
cfg.foi = [20:20:100]; % there are 10 repetitions, so let's use 5 frequencies
cfg.toi = [0.4 0.5 0.6];
cfg.t_ftimwin = ones(1,numel(cfg.foi)).*0.2;
cfg.taper = 'hanning';
cfg.output = 'pow';
cfg.keeptrials = 'yes';
freqtf = ft_freqanalysis(cfg, data);
%% select channels, compare ft_selectdata_old with ft_selectdata_new and
% compare ft_selectdata_new with what would be expected
% make a selection of channels
[data_old, data_new] = compare_outputs(freq, 'channel', freq.label(5:10));
assert(isequal(data_old.fourierspctrm, freq.fourierspctrm(:,5:10,:)));
assert(isequal(data_new.fourierspctrm, freq.fourierspctrm(:,5:10,:)));
[data_old, data_new] = compare_outputs(freqp, 'channel', freq.label(5:10));
assert(isequal(data_old.powspctrm, freqp.powspctrm(:,5:10,:)));
assert(isequal(data_new.powspctrm, freqp.powspctrm(:,5:10,:)));
try
[data_old, data_new] = compare_outputs(freqc, 'channel', freq.label(5:10));
assert(isequal(data_old.powspctrm, freqc.powspctrm(:,5:10,:)));
assert(isequal(data_new.powspctrm, freqc.powspctrm(:,5:10,:)));
catch
fprintf('selecting channels with csd in input does not work');
end
[data_old, data_new] = compare_outputs(freqtf, 'channel', freq.label(5:10));
assert(isequal(data_old.powspctrm, freqtf.powspctrm(:,5:10,:,:)));
assert(isequal(data_new.powspctrm, freqtf.powspctrm(:,5:10,:,:)));
% make a selection of all channels
[data_old, data_new] = compare_outputs(freq, 'channel', 'all');
assert(isequal(data_old.fourierspctrm, freq.fourierspctrm));
assert(isequal(data_new.fourierspctrm, freq.fourierspctrm));
[data_old, data_new] = compare_outputs(freqp, 'channel', 'all');
assert(isequal(data_old.powspctrm, freqp.powspctrm));
assert(isequal(data_new.powspctrm, freqp.powspctrm));
try
[data_old, data_new] = compare_outputs(freqc, 'channel', 'all');
assert(isequal(data_old.powspctrm, freqc.powspctrm));
assert(isequal(data_new.powspctrm, freqc.powspctrm));
catch
fprintf('selecting channels with csd in input does not work');
end
[data_old, data_new] = compare_outputs(freqtf, 'channel', 'all');
assert(isequal(data_old.powspctrm, freqtf.powspctrm));
assert(isequal(data_new.powspctrm, freqtf.powspctrm));
% make a selection of no channels
[data_old, data_new] = compare_outputs(freq, 'channel', {});
assert(isequal(data_old.label,{}));
assert(isequal(data_new.label,{}));
[data_old, data_new] = compare_outputs(freqp, 'channel', {});
assert(isequal(data_old.label,{}));
assert(isequal(data_new.label,{}));
try
[data_old, data_new] = compare_outputs(freqc, 'channel', {});
assert(isequal(data_old.label,{}));
assert(isequal(data_new.label,{}));
catch
fprintf('selecting channels with csd in input does not work');
end
[data_old, data_new] = compare_outputs(freqtf, 'channel', {});
assert(isequal(data_old.label,{}));
assert(isequal(data_new.label,{}));
%% select frequencies
[data_old, data_new] = compare_outputs(freq, 'frequency', freq.freq([9 39]));
assert(isequal(data_old.fourierspctrm, freq.fourierspctrm(:,:,9:39)));
assert(isequal(data_new.fourierspctrm, freq.fourierspctrm(:,:,9:39)));
[data_old, data_new] = compare_outputs(freqp, 'frequency', freqp.freq([9 39]));
assert(isequal(data_old.powspctrm, freqp.powspctrm(:,:,9:39)));
assert(isequal(data_new.powspctrm, freqp.powspctrm(:,:,9:39)));
try
[data_old, data_new] = compare_outputs(freqc, 'frequency', freqc.freq([9 39]));
assert(isequal(data_old.powspctrm, freqp.powspctrm(:,5:10,:)));
assert(isequal(data_new.powspctrm, freqp.powspctrm(:,5:10,:)));
catch
fprintf('selecting channels with csd in input does not work');
end
[data_old, data_new] = compare_outputs(freqtf, 'frequency', freqtf.freq([1 4]));
assert(isequal(data_old.powspctrm, freqtf.powspctrm(:,:,1:4,:)));
assert(isequal(data_new.powspctrm, freqtf.powspctrm(:,:,1:4,:)));
% make a selection of all channels
[data_old, data_new] = compare_outputs(freq, 'frequency', 'all');
assert(isequal(data_old.fourierspctrm, freq.fourierspctrm));
assert(isequal(data_new.fourierspctrm, freq.fourierspctrm));
[data_old, data_new] = compare_outputs(freqp, 'frequency', 'all');
assert(isequal(data_old.powspctrm, freqp.powspctrm));
assert(isequal(data_new.powspctrm, freqp.powspctrm));
try
[data_old, data_new] = compare_outputs(freqp, 'frequency', 'all');
assert(isequal(data_old.powspctrm, freqp.powspctrm));
assert(isequal(data_new.powspctrm, freqp.powspctrm));
catch
fprintf('selecting channels with csd in input does not work');
end
[data_old, data_new] = compare_outputs(freqtf, 'frequency', 'all');
assert(isequal(data_old.powspctrm, freqtf.powspctrm));
assert(isequal(data_new.powspctrm, freqtf.powspctrm));
% make a selection of no channels
compare_outputs(freq, 'frequency', []);
compare_outputs(freqp, 'frequency', []);
try
compare_outputs(freqp, 'frequency', []);
catch
fprintf('selecting channels with csd in input does not work');
end
compare_outputs(freqtf, 'frequency', []);
%% select time
% subselection
[data_old, data_new] = compare_outputs(freqtf, 'latency', [0.5 0.6]);
assert(isequal(data_old.powspctrm, freqtf.powspctrm(:,:,:,[2 3])));
assert(isequal(data_new.powspctrm, freqtf.powspctrm(:,:,:,[2 3])));%
compare_outputs(freqtf, 'latency', 'all'); % all
compare_outputs(freqtf, 'latency', []); % nothing
%% select trials
% do a subselection
compare_outputs(freq, 'trials', 3:5);
compare_outputs(freqp, 'trials', 3:5);
try
compare_outputs(freqc, 'trials', 3:5);
catch
warning('assertion failed, because ft_selectdata_new cannot deal with crsspctrm in input yet');
end
compare_outputs(freqtf, 'trials', 3:5);
% do an empty selection
compare_outputs(freq, 'trials', []);
compare_outputs(freqp, 'trials', []);
try
compare_outputs(freqc, 'trials', []);
catch
warning('assertion failed, because ft_selectdata_new cannot deal with crsspctrm in input yet');
end
compare_outputs(freqtf, 'trials', []);
% select all
compare_outputs(freq, 'trials', 'all');
compare_outputs(freqp, 'trials', 'all');
try
compare_outputs(freqc, 'trials', 'all');
catch
warning('assertion failed, because ft_selectdata_new cannot deal with crsspctrm in input yet');
end
compare_outputs(freqtf, 'trials', 'all');
%% avgover channels
% Old snippet: not needed anymore
% fx4 = ft_selectdata(freq, 'avgoverchan', 'yes');
% fp4 = ft_selectdata(freqp, 'avgoverchan', 'yes');
% fc4 = ft_selectdata(freqc, 'avgoverchan', 'yes');
% ftf4 = ft_selectdata(freqtf, 'avgoverchan', 'yes');
%
% % assessing label after averaging: see bug 2191 -> this seems OK
% cfg = [];
% cfg.avgoverchan = 'yes';
% fx42 = ft_selectdata(cfg,freq);
% fp42 = ft_selectdata(cfg,freqp);
% fc42 = ft_selectdata(cfg,freqc);
% ftf42 = ft_selectdata(cfg,freqtf);
%
% if ~strcmp(fx4.label{:},fx42.label{:});error('mismatch on label field');end
% if ~strcmp(fp4.label{:},fp42.label{:});error('mismatch on label field');end
% if ~strcmp(fc4.label{:},fc42.label{:});error('mismatch on label field');end
% if ~strcmp(ftf4.label{:},ftf42.label{:});error('mismatch on label field');end
compare_outputs(freq, 'avgoverchan');
compare_outputs(freqp, 'avgoverchan');
% compare_outputs(freqc, 'avgoverchan'); % FIXME why is this commented out?
compare_outputs(freqtf, 'avgoverchan');
%% avgover frequencies
compare_outputs(freq, 'avgoverfreq');
compare_outputs(freqp, 'avgoverfreq');
% compare_outputs(freqc, 'avgoverfreq'); % FIXME why is this commented out?
compare_outputs(freqtf, 'avgoverfreq');
%% avgover trials
compare_outputs(freq, 'avgoverrpt');
compare_outputs(freqp, 'avgoverrpt');
% compare_outputs(freqc, 'avgoverrpt'); % FIXME why is this commented out?
compare_outputs(freqtf, 'avgoverrpt');
%% leaveoneout
% FIXME: to be looked into
% % fx7 = ft_selectdata(freq, 'jackknife', 'yes'); % FAILS due to 'rpttap'
% fp7 = ft_selectdata(freqp, 'jackknife', 'yes');
% fc7 = ft_selectdata(freqc, 'jackknife', 'yes');
% ftf7 = ft_selectdata(freqtf, 'jackknife', 'yes');
%% this part tests the functionality of ft_appendfreq
whos
clear freq*
% make some dummy frequency structures
freq1.label = {'1' '2'};
freq1.freq = 1:10;
freq1.time = 1:5;
freq1.dimord = 'chan_freq_time';
freq1.powspctrm = randn(2,10,5);
freq1.cfg = [];
cfg = [];
cfg.parameter = 'powspctrm';
freq2 = ft_appendfreq(cfg, freq1, freq1);
freq2 = rmfield(freq2, 'cfg');
freq2a = ft_selectdata(freq1, freq1, 'param', 'powspctrm'); % this should append the power spectrum
assert(isequal(freq2, freq2a));
freq4a = ft_selectdata(freq2, freq2, 'param', 'powspctrm');
assert(isequal(size(freq4a.powspctrm), [4 2 10 5]));
clear freq*
freq3.label = {'1' '2'};
freq3.freq = 1:10;
freq3.dimord = 'chan_freq';
freq3.powspctrm = randn(2,10);
cfg = [];
cfg.parameter = 'powspctrm';
freq4 = ft_appendfreq(cfg, freq3, freq3);
freq4 = rmfield(freq4, 'cfg');
freq4a = ft_selectdata(freq3, freq3, 'param', 'powspctrm'); % this should append the power spectrum
assert(isequal(freq4, freq4a));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% this part of the function tests the functionality of ft_selectdata with respect to timelock data
% create timelocked data
cfg = [];
cfg.keeptrials = 'yes';
tlck = ft_timelockanalysis(cfg, data);
cfg.covariance = 'yes';
tlckc = ft_timelockanalysis(cfg, data);
cfg.keeptrials = 'no';
tlckcavg = ft_timelockanalysis(cfg, data);
cfg.covariance = 'no';
tlckavg = ft_timelockanalysis(cfg, data);
%% select trials
compare_outputs(tlck, 'trials', [4 5 6]);
compare_outputs(tlckc, 'trials', [4 5 6]);
compare_outputs(tlck, 'trials', []);
compare_outputs(tlckc, 'trials', []);
compare_outputs(tlck, 'trials', 'all');
compare_outputs(tlckc, 'trials', 'all');
%% select latency
compare_outputs(tlck, 'latency', [-0.1 0.1]);
compare_outputs(tlckc, 'latency', [-0.1 0.1]);
compare_outputs(tlckavg, 'latency', [-0.1 0.1]);
compare_outputs(tlckcavg, 'latency', [-0.1 0.1]);
compare_outputs(tlck, 'latency', []);
compare_outputs(tlckc, 'latency', []);
compare_outputs(tlckavg, 'latency', []);
compare_outputs(tlckcavg, 'latency', []);
compare_outputs(tlck, 'latency', 'all');
compare_outputs(tlckc, 'latency', 'all');
compare_outputs(tlckavg, 'latency', 'all');
compare_outputs(tlckcavg, 'latency', 'all');
%% select channels
compare_outputs(tlck, 'channel', tlck.label(11:20));
compare_outputs(tlckc, 'channel', tlckc.label(11:20));
compare_outputs(tlckavg, 'channel', tlckavg.label(11:20));
% compare_outputs(tlckcavg, 'channel', tlckcavg.label(11:20));% the old and new implementation differ in the selection of channels in cov
compare_outputs(tlck, 'channel', []);
compare_outputs(tlckc, 'channel', []);
compare_outputs(tlckavg, 'channel', []);
% compare_outputs(tlckcavg, 'channel', []);% the old and new implementation differ in the selection of channels
compare_outputs(tlck, 'channel', 'all');
compare_outputs(tlckc, 'channel', 'all');
compare_outputs(tlckavg, 'channel', 'all');
compare_outputs(tlckcavg, 'channel', 'all');
%% avgoverrpt
compare_outputs(tlck, 'avgoverrpt');
compare_outputs(tlckc, 'avgoverrpt');
%% avgoverchan
compare_outputs(tlck, 'avgoverchan');
compare_outputs(tlckc, 'avgoverchan');
compare_outputs(tlckavg, 'avgoverchan');
compare_outputs(tlckcavg, 'avgoverchan');
%% avgovertime
compare_outputs(tlck, 'avgovertime');
% compare_outputs(tlckc, 'avgovertime'); % % FIXME why are the implementations inconsistent if both trials and cov are present?
compare_outputs(tlckavg, 'avgovertime');
compare_outputs(tlckcavg, 'avgovertime');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% this part of the script tests the functionality of ft_selectdata with selections
% that are made into multiple fields present in the data
if false
% this section does not yet work on 5 April 2014, so no point in testing
freq = [];
freq.powspctrm = randn(3, 4, 5);
freq.dimord = 'chan_freq_time';
freq.crsspctrm = randn(3, 3, 4, 5);
freq.crsspctrmdimord = 'chan_chan_freq_time';
freq.label = {'1', '2', '3'};
freq.freq = 1:4;
freq.time = 1:5;
cfg = [];
cfg.channel = {'1', '2'};
cfg.foilim = [1 3];
output = ft_selectdata(cfg, freq);
assert(isfield(output, 'powspctrm'), 'field missing');
assert(isfield(output, 'crsspctrm'), 'field missing');
assert(size(output.powspctrm, 1)==2, 'incorrect size'); % chan
assert(size(output.powspctrm, 2)==3, 'incorrect size'); % freq
assert(size(output.crsspctrm, 1)==2, 'incorrect size'); % chan
assert(size(output.crsspctrm, 2)==2, 'incorrect size'); % chan
assert(size(output.crsspctrm, 3)==3, 'incorrect size'); % freq
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION used for testing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data_old, data_new] = compare_outputs(data, key, value)
switch key
case 'trials'
keyold = 'rpt';
case 'frequency'
keyold = 'foilim';
case 'latency'
keyold = 'toilim';
otherwise
keyold = key;
end
if nargin>2
% there has been a key and a value
cfg = [];
cfg.(key) = value;
data_new = ft_selectdata(cfg, data);
data_old = ft_selectdata(data, keyold, value);
% don't include the cfg
data_new = rmfield(data_new, 'cfg');
data_old = rmfield(data_old, 'cfg');
% don't include the cumtapcnt if present (ft_selectdata_old might be incorrect)
if isfield(data_new, 'cumtapcnt'), data_new = rmfield(data_new, 'cumtapcnt'); end
if isfield(data_old, 'cumtapcnt'), data_old = rmfield(data_old, 'cumtapcnt'); end
if isfield(data_new, 'cov') && ~isfield(data_old, 'cov')
% skip this comparison, because ft_selectdata_old could not deal with this correctly: this is not something to be asserted here
data_new = rmfield(data_new, 'cov');
end
if isfield(data, 'trial') && isfield(data_new, 'avg') && ~isfield(data_old, 'avg')
% skip this comparison, because ft_selectdata_old could not deal with this correctly: this is not something to be asserted here
data_new = rmfield(data_new, 'avg');
end
if isfield(data, 'trial') && isfield(data_new, 'var') && ~isfield(data_old, 'var')
% skip this comparison, because ft_selectdata_old could not deal with this correctly: this is not something to be asserted here
data_new = rmfield(data_new, 'var');
end
if isfield(data, 'trial') && isfield(data_new, 'dof') && ~isfield(data_old, 'dof')
% skip this comparison, because ft_selectdata_old could not deal with this correctly: this is not something to be asserted here
data_new = rmfield(data_new, 'dof');
end
fn = {'trial', 'time', 'freq', 'trialinfo', 'sampleinfo'};
for i=1:length(fn)
if isfield(data_old, fn{i}) && isfield(data_new, fn{i}) && numel(data_old.(fn{i}))==0 && numel(data_new.(fn{i}))==0
% this is needed because these two comparisons return false
% isequal(zeros(0,0), zeros(1,0))
% isequal(cell(0,0), cell(1,0))
data_old.(fn{i}) = data_new.(fn{i});
end
end
if isfield(data_old, 'fsample') && ~isfield(data_new, 'fsample')
data_old = rmfield(data_old, 'fsample');
end
% ensure the empty fields to have the same 'size', i.e.
% assert(isequal )) chokes on comparing [] with zeros(0,1)
fnnew = fieldnames(data_new);
for k = 1:numel(fnnew)
if numel(data_new.(fnnew{k}))==0,
if iscell(data_new.(fnnew{k})),
data_new.(fnnew{k})={};
else
data_new.(fnnew{k})=[];
end
end
end
fnold = fieldnames(data_old);
for k = 1:numel(fnold)
if numel(data_old.(fnold{k}))==0,
if iscell(data_old.(fnold{k})),
data_old.(fnold{k})={};
else
data_old.(fnold{k})=[];
end
end
end
%if numel(data_old.label)==0, data_old.label = {}; end
%if numel(data_new.label)==0, data_new.label = {}; end
assert(isequal(data_old, data_new));
% check whether the output is the same as the input
if ischar(value) && strcmp(value, 'all')
dataorig = data;
try, if isfield(dataorig, 'trial'), data = rmfield(dataorig, {'avg', 'var', 'dof'}); end ; end % only remove when trial
try, if isfield(data, 'cov') && ~isfield(data_old, 'cov'), data = rmfield(data, 'cov'); end; end
data = rmfield(data, 'cfg');
if isfield(data, 'cumtapcnt'), data = rmfield(data, 'cumtapcnt'); end
assert(isequal(data, data_old));
data = dataorig;
try, if isfield(dataorig, 'trial'), data = rmfield(dataorig, {'avg', 'var', 'dof'}); end ; end % only remove when trial
try, if isfield(data, 'cov') && ~isfield(data_new, 'cov'), data = rmfield(data, 'cov'); end; end
data = rmfield(data, 'cfg');
if isfield(data, 'cumtapcnt'), data = rmfield(data, 'cumtapcnt'); end
assert(isequal(data, data_new));
end
else
% assume the avgoverXXX is tested
cfg = [];
cfg.(key) = 'yes';
data_new = ft_selectdata(cfg, data);
data_old = ft_selectdata(data, keyold, 'yes');
% don't include the cfg
data_new = rmfield(data_new, 'cfg');
data_old = rmfield(data_old, 'cfg');
if isfield(data_new, 'cov') && ~isfield(data_old, 'cov')
% skip this comparison, because ft_selectdata_old could not deal with this correctly: this is not something to be asserted here
data_new = rmfield(data_new, 'cov');
end
if isfield(data, 'trial') && isfield(data_new, 'avg') && ~isfield(data_old, 'avg')
% skip this comparison, because ft_selectdata_old could not deal with this correctly: this is not something to be asserted here
data_new = rmfield(data_new, 'avg');
end
if isfield(data, 'trial') && isfield(data_new, 'var') && ~isfield(data_old, 'var')
% skip this comparison, because ft_selectdata_old could not deal with this correctly: this is not something to be asserted here
data_new = rmfield(data_new, 'var');
end
if isfield(data, 'trial') && isfield(data_new, 'dof') && ~isfield(data_old, 'dof')
% skip this comparison, because ft_selectdata_old could not deal with this correctly: this is not something to be asserted here
data_new = rmfield(data_new, 'dof');
end
if strcmp(key, 'avgoverfreq') || strcmp(key, 'avgoverrpt')
% apparently something may be wrong with the data_old.dimord
% don't spend time on fixing this here
data_old.dimord = data_new.dimord;
% also, the cumtapcnt is inconsistent in ft_selectdata_old
if isfield(data_old, 'cumtapcnt'), data_old = rmfield(data_old, 'cumtapcnt'); end
if isfield(data_new, 'cumtapcnt'), data_new = rmfield(data_new, 'cumtapcnt'); end
end
if strcmp(key, 'avgoverrpt')
% ft_selectdata_old does something inconsistent, don't bother to fix it
if isfield(data_old, 'cumtapcnt'), data_old = rmfield(data_old, 'cumtapcnt'); end
if isfield(data_old, 'cumsumcnt'), data_old = rmfield(data_old, 'cumsumcnt'); end
if isfield(data_old, 'trialinfo'), data_old = rmfield(data_old, 'trialinfo'); end
% ft_selectdata_new tries to keep the cov, but ft_selectdata doesn't,
% don't bother to fix ft_selectdata_old
if isfield(data_new, 'cov'), data_new = rmfield(data_new, 'cov'); end
end
if strcmp(key, 'avgoverchan')
% ft_selectdata_old sometimes keeps the cov (without averaging), don't
% bother to fix it
if isfield(data_old, 'cov'), data_old = rmfield(data_old, 'cov'); end
if isfield(data_old, 'cumtapcnt'), data_old = rmfield(data_old, 'cumtapcnt'); end
if isfield(data_new, 'cumtapcnt'), data_new = rmfield(data_new, 'cumtapcnt'); end
% ft_selectdata_new tries to keep the cov, but ft_selectdata doesn't,
% don't bother to fix ft_selectdata_old
if isfield(data_new, 'cov'), data_new = rmfield(data_new, 'cov'); end
end
assert(isequal(data_old, data_new));
end
|
github
|
lcnhappe/happe-master
|
test_ft_channelcombination.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_channelcombination.m
| 7,145 |
utf_8
|
92126b1e575f43f578016080f381e561
|
function test_ft_channelcombination
% MEM 1500mb
% WALLTIME 00:10:00
% TEST test_ft_channelcombination
% TEST ft_channelcombination
% this function tests the new implementation of ft_channelcombination
load(fullfile(dccnpath('/home/common/matlab/fieldtrip/data/test/latest/raw/meg'),'preproc_ctf151.mat'));
label = data.label; clear data;
x = ft_channelcombination({'all' 'all'}, label);
y = ft_channelcombination_old({'all' 'all'}, label);
assert(isequal(x,y));
x = ft_channelcombination({'MLT' 'all'}, label);
y = ft_channelcombination_old({'MLT' 'all'}, label);
assert(isequal(x,y));
x = ft_channelcombination({'MLT' 'MRC'}, label);
y = ft_channelcombination_old({'MLT' 'MRC'}, label);
assert(isequal(x,y));
x = ft_channelcombination({{'MLC12' 'MLC13'} {'MRO11' 'MRO12' 'MRO21'}}, label);
y = ft_channelcombination_old({{'MLC12' 'MLC13'} {'MRO11' 'MRO12' 'MRO21'}}, label);
assert(isequal(x,y));
% test the new functionality
x = ft_channelcombination({'MLT' 'MRC'}, label, 0, 0);
y = ft_channelcombination({'MLT' 'MRC'}, label, 0, 1);
z = ft_channelcombination({'MLT' 'MRC'}, label, 0, 2);
assert(isequal(x, y(:,[2 1]))); % the columns should be swapped
assert(numel(z)==2*numel(x));
%%%%%%%%%%
% Below is the old code
function [collect] = ft_channelcombination_old(channelcmb, datachannel, includeauto)
% FT_CHANNELCOMBINATION creates a cell-array with combinations of EEG/MEG
% channels for subsequent cross-spectral-density and coherence analysis
%
% You should specify channel combinations as a two-column cell array,
% cfg.channelcmb = { 'EMG' 'MLF31'
% 'EMG' 'MLF32'
% 'EMG' 'MLF33' };
% to compare EMG with these three sensors, or
% cfg.channelcmb = { 'MEG' 'MEG' };
% to make all MEG combinations, or
% cfg.channelcmb = { 'EMG' 'MEG' };
% to make all combinations between the EMG and all MEG channels.
%
% For each column, you can specify a mixture of real channel labels
% and of special strings that will be replaced by the corresponding
% channel labels. Channels that are not present in the raw datafile
% are automatically removed from the channel list.
%
% Please note that the default behaviour is to exclude symetric
% pairs and auto-combinations.
%
% See also FT_CHANNELSELECTION
% Undocumented local options: optional third input argument includeauto,
% specifies to include the auto-combinations
% Copyright (C) 2003-2011, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% 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_channelcombination.m 10449 2015-06-10 18:34:02Z roboos $
if nargin==2,
includeauto = 0;
end
if ischar(channelcmb) && strcmp(channelcmb, 'all')
% make all possible combinations of all channels
channelcmb = {'all' 'all'};
end
% it should have a selection of two channels or channelgroups in each row
if size(channelcmb,1)==2 && size(channelcmb,2)~=2
warning('transposing channelcombination matrix');
channelcmb = channelcmb';
end
% this will hold the output
collect = {};
% allow for channelcmb to be a 1x2 cell-array containing cells
if numel(channelcmb)==2 && iscell(channelcmb{1}) && iscell(channelcmb{2})
channelcmb{1} = ft_channelselection(channelcmb{1}, datachannel);
channelcmb{2} = ft_channelselection(channelcmb{2}, datachannel);
n1 = numel(channelcmb{1});
n2 = numel(channelcmb{2});
tmp = cell(n1*n2+n1+n2,2);
for k = 1:n1
tmp((k-1)*n2+(1:n2), 1) = channelcmb{1}(k);
tmp((k-1)*n2+(1:n2), 2) = channelcmb{2};
tmp(n2*k+(1:n1), 1) = channelcmb{1};
tmp(n2*k+(1:n1), 2) = channelcmb{1};
tmp(n2*k+n1+(1:n2), 1) = channelcmb{2};
tmp(n2*k+n1+(1:n2), 2) = channelcmb{2};
end
collect = tmp;
return;
end
if isempty(setdiff(channelcmb(:), datachannel))
% there is nothing to do, since there are no channelgroups with special names
% each element of the input therefore already contains a proper channel name
collect = channelcmb;
if includeauto
for ch=1:numel(datachannel)
collect{end+1,1} = datachannel{ch};
collect{end, 2} = datachannel{ch};
end
end
else
% a combination is made for each row of the input selection after
% translating the channel group (such as 'all') to the proper channel names
% and within each set, double occurences and autocombinations are removed
for sel=1:size(channelcmb,1)
% translate both columns and subsequently make all combinations
channelcmb1 = ft_channelselection(channelcmb(sel,1), datachannel);
channelcmb2 = ft_channelselection(channelcmb(sel,2), datachannel);
% compute indices of channelcmb1 and channelcmb2 relative to datachannel
[dum,indx,indx1]=intersect(channelcmb1,datachannel);
[dum,indx,indx2]=intersect(channelcmb2,datachannel);
% remove double occurrences of channels in either set of signals
indx1 = unique(indx1);
indx2 = unique(indx2);
% create a matrix in which all possible combinations are set to one
cmb = zeros(length(datachannel));
for ch1=1:length(indx1)
for ch2=1:length(indx2)
cmb(indx1(ch1),indx2(ch2))=1;
end
end
% remove auto-combinations
cmb = cmb & ~eye(size(cmb));
% remove double occurences
cmb = cmb & ~tril(cmb, -1)';
[indx1,indx2] = find(cmb);
% extend the previously allocated cell-array to also hold the new
% channel combinations (this is done to prevent memory allocation and
% copying in each iteration in the for-loop below)
num = size(collect,1); % count the number of existing combinations
dum = cell(num + length(indx1), 2); % allocate space for the existing+new combinations
if num>0
dum(1:num,:) = collect(:,:); % copy the exisisting combinations into the new array
end
collect = dum;
clear dum
% convert to channel-names
for ch=1:length(indx1)
collect{num+ch,1}=datachannel{indx1(ch)};
collect{num+ch,2}=datachannel{indx2(ch)};
end
end
if includeauto
cmb = eye(length(datachannel));
[indx1,indx2] = find(cmb);
num = size(collect,1);
dum = cell(num + length(indx1), 2);
if num>0,
dum(1:num,:) = collect(:,:);
end
collect = dum;
clear dum
% convert to channel-names for the auto-combinations
for ch=1:length(indx1)
collect{num+ch,1} = datachannel{indx1(ch)};
collect{num+ch,2} = datachannel{indx2(ch)};
end
end
end
|
github
|
lcnhappe/happe-master
|
test_ft_analysispipeline.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_analysispipeline.m
| 2,685 |
utf_8
|
9466e08ec41682a2c6b7afc284babec1
|
function test_ft_analysispipeline
% MEM 1500mb
% WALLTIME 02:53:11
% TEST test_ft_analysispipeline
% TEST ft_analysispipeline
% the style of this test script is also used in test_ft_datatype and test_bug2185
global ft_default
ft_default.trackusage = 'no'; % this calls ft_analysispipeline more than 6000 times, those should not all be tracked
dirlist = {
'/home/common/matlab/fieldtrip/data/test/latest'
'/home/common/matlab/fieldtrip/data/test/20131231'
'/home/common/matlab/fieldtrip/data/test/20130630'
'/home/common/matlab/fieldtrip/data/test/20121231'
'/home/common/matlab/fieldtrip/data/test/20120630'
'/home/common/matlab/fieldtrip/data/test/20111231'
'/home/common/matlab/fieldtrip/data/test/20110630'
'/home/common/matlab/fieldtrip/data/test/20101231'
'/home/common/matlab/fieldtrip/data/test/20100630'
'/home/common/matlab/fieldtrip/data/test/20091231'
'/home/common/matlab/fieldtrip/data/test/20090630'
'/home/common/matlab/fieldtrip/data/test/20081231'
'/home/common/matlab/fieldtrip/data/test/20080630'
'/home/common/matlab/fieldtrip/data/test/20071231'
'/home/common/matlab/fieldtrip/data/test/20070630'
'/home/common/matlab/fieldtrip/data/test/20061231'
'/home/common/matlab/fieldtrip/data/test/20060630'
'/home/common/matlab/fieldtrip/data/test/20051231'
'/home/common/matlab/fieldtrip/data/test/20050630'
'/home/common/matlab/fieldtrip/data/test/20040623'
'/home/common/matlab/fieldtrip/data/test/20031128'
};
for j=1:length(dirlist)
filelist = hcp_filelist(dirlist{j});
[dummy, dummy, x] = cellfun(@fileparts, filelist, 'uniformoutput', false);
sel = strcmp(x, '.mat');
filelist = filelist(sel);
clear p f x
for i=1:length(filelist)
% skip the large files
d = dir(filelist{i});
if d.bytes>50000000
continue
end
try
fprintf('processing data structure from %s\n', filelist{i});
var = loadvar(filelist{i});
disp(var)
catch
% some of the mat files are corrupt, this should not spoil the test
disp(lasterr);
continue
end
cfg = [];
cfg.showcallinfo = 'no';
ft_analysispipeline(cfg, var);
set(gcf, 'Name', shortname(filelist{i}));
drawnow
close all
end % for filelist
end % for dirlist
end % main function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function str = shortname(str)
len = 50;
if length(str)>len
begchar = length(str)-len+4;
endchar = length(str);
str = ['...' str(begchar:endchar)];
end
end % function shortname
|
github
|
lcnhappe/happe-master
|
test_ft_componentanalysis.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_componentanalysis.m
| 3,273 |
utf_8
|
b0c2b5a3a4fc97828c4305a836bde27c
|
function test_ft_componentanalysis(datainfo, writeflag, version)
% MEM 2gb
% WALLTIME 00:10:00
% TEST test_ft_componentanalysis
% ft_componentanalysis ref_datasets
% writeflag determines whether the output should be saved to disk
% version determines the output directory
if nargin<1
datainfo = ref_datasets;
end
if nargin<2
writeflag = 0;
end
if nargin<3
version = 'latest';
end
for k = 1:numel(datainfo)
datanew = componentanalysis(datainfo(k), writeflag, version);
fname = fullfile(datainfo(k).origdir,version,'comp',datainfo(k).type,['comp_',datainfo(k).datatype]);
tmp = load(fname);
if isfield(tmp, 'comp')
data = tmp.comp;
end
datanew = rmfield(datanew, 'cfg'); % these are per construction different if writeflag = 0;
data = rmfield(data, 'cfg');
% if data is rank-deficient, the last columns of the mixing/unmixing
% matrices are arbitrary, and should thus not be compared
rankDiff = size(data.trial{1},1) - rank(data.trial{1});
if rankDiff == size(data.trial{1},1)
% massive rank deficiency (i.e., identical data in all channels)
% best to just not test the mixing matrices at all, just surrogate test
% data
data = rmfield(data, 'topo');
data = rmfield(data, 'unmixing');
datanew = rmfield(datanew, 'topo');
datanew = rmfield(datanew, 'unmixing');
elseif rankDiff > 0
data.topo(:,end-rankDiff:end) = 0;
data.unmixing(end-rankDiff:end,:) = 0;
datanew.topo(:,end-rankDiff:end) = 0;
datanew.unmixing(end-rankDiff:end,:) = 0;
end
[ok,msg] = identical(data, datanew,'abstol',1e-7,'diffabs',1);
disp(['now you are in k=' num2str(k)]);
if ~ok
disp(msg);
error('there were differences between reference and new data, see above for details');
end
end
function [comp] = componentanalysis(dataset, writeflag, version)
% --- HISTORICAL --- attempt forward compatibility with function handles
if ~exist('ft_componentanalysis') && exist('componentanalysis')
eval('ft_componentanalysis = @componentanalysis;');
end
cfg = [];
cfg.method = 'pca';
switch dataset.datatype
case {'bti148' 'bti248' 'bti248grad' 'ctf151' 'ctf275' 'ctf64' 'itab153' 'neuromag122' 'neuromag306' 'yokogawa160'}
cfg.channel = 'MEG';
otherwise
cfg.channel = 'all';
end
cfg.inputfile = fullfile(dataset.origdir,version,'raw',dataset.type,['preproc_',dataset.datatype]);
outputfile = fullfile(dataset.origdir,version,'comp',dataset.type,['comp_',dataset.datatype])
if writeflag
cfg.outputfile = outputfile;
end
if ~strcmp(version, 'latest') && str2double(version)<20100000
% -- HISTORICAL --- older FieldTrip versions don't support inputfile and outputfile
try
% use the previous random seed
load(outputfile, 'comp');
if isfield(comp.cfg.callinfo, 'randomseed')
cfg.randomseed = comp.cfg.callinfo.randomseed;
end
catch
% use a new random seed
end
load(cfg.inputfile, 'data');
comp = ft_componentanalysis(cfg, data);
save(cfg.outputfile, 'comp');
else
try
% use the previous random seed
load(outputfile, 'comp');
if isfield(comp.cfg.callinfo, 'randomseed')
cfg.randomseed = comp.cfg.callinfo.randomseed;
end
catch
% use a new random seed
end
comp = ft_componentanalysis(cfg);
end
|
github
|
lcnhappe/happe-master
|
test_prepare_freq_matrices.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_prepare_freq_matrices.m
| 15,003 |
utf_8
|
08bea5d768d5aeaaa4ad0938cac4ce3b
|
function test_prepare_freq_matrices
% WALLTIME 00:10:00
% MEM 1000mb
% TEST test_prepare_freq_matrices
% TEST prepare_freq_matrices
% TEST ft_sourceanalysis
datadir = dccnpath('/home/common/matlab/fieldtrip/data/test/latest/freq/meg');
curdir = pwd;
cd(dccnpath('/home/common/matlab/fieldtrip'));
% fourier data, multiple trials
load(fullfile(datadir,'freq_mtmfft_fourier_trl_ctf275.mat'));
cfg = [];
cfg.frequency = 5;
cfg.channel = ft_channelselection('MEG',freq.label);
[a1,a2,a3,a4] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
cfg.frequency = 5.4;
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
cfg.frequency = 10;
cfg.refchan = 'BR1';
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
assert(isequal(a2,b2));
assert(isequal(a3,b3));
cfg.frequency = 10.6;
cfg.refchan = 'BR1';
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
assert(isequal(a2,b2));
assert(isequal(a3,b3));
% powandcsd data, multiple trials
load(fullfile(datadir,'freq_mtmfft_powandcsd_trl_ctf275.mat'));
cfg = [];
cfg.frequency = 5;
cfg.channel = ft_channelselection('MEG',freq.label);
[a1,a2,a3,a4] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
cfg.frequency = 5.4;
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
cfg.frequency = 10;
cfg.refchan = 'BR1';
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
assert(isequal(a2,b2));
assert(isequal(a3,b3));
cfg.frequency = 10.6;
cfg.refchan = 'BR1';
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
assert(isequal(a2,b2));
assert(isequal(a3,b3));
% powandcsd data, multiple trials and time
load(fullfile(datadir,'freq_mtmconvol_powandcsd_trl_ctf275.mat'));
cfg = [];
cfg.frequency = 6;
cfg.latency = 0.5;
cfg.channel = ft_channelselection('MEG',freq.label);
[a1,a2,a3,a4] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
cfg.frequency = 5.5;
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
cfg.frequency = 6;
cfg.latency = 0.54;
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
cfg.frequency = 10;
cfg.refchan = 'BR1';
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
assert(isequal(a2,b2));
assert(isequal(a3,b3));
cfg.frequency = 10.6;
cfg.refchan = 'BR1';
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
assert(isequal(a2,b2));
assert(isequal(a3,b3));
% fourier data, multiple trials and time
load(fullfile(datadir,'freq_mtmconvol_fourier_trl_ctf275.mat'));
cfg = [];
cfg.frequency = 6;
cfg.latency = 0.5;
cfg.channel = ft_channelselection('MEG',freq.label);
[a1,a2,a3,a4] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
cfg.frequency = 5.5;
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
cfg.frequency = 6;
cfg.latency = 0.54;
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
cfg.frequency = 10;
cfg.refchan = 'BR1';
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
assert(isequal(a2,b2));
assert(isequal(a3,b3));
cfg.frequency = 10.6;
cfg.refchan = 'BR1';
[a1,a2,a3,a4,cfg1] = prepare_freq_matrices(cfg, freq);
[b1,b2,b3,b4,cfg2] = prepare_freq_matrices_old(cfg, freq);
assert(isequal(a1,b1));
assert(isequal(a2,b2));
assert(isequal(a3,b3));
cd(curdir);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BELOW IS THE OLD CODE
function [Cf, Cr, Pr, Ntrials, cfg] = prepare_freq_matrices_old(cfg, freq)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that converts a freq structure into Cf, Cr and Pr
% this is used in sourecanalysis
%
% This function returns data matrices with a channel order that is consistent
% with the original channel order in the data.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set the defaults
if ~isfield(cfg, 'dicsfix'), cfg.dicsfix = 'yes'; end
if ~isfield(cfg, 'quickflag'), cfg.quickflag = 0; end
if ~isfield(cfg, 'refchan'), cfg.refchan = []; end
quickflag = cfg.quickflag==1;
Cf = [];
Cr = [];
Pr = [];
% select the latency of interest for time-frequency data
if strcmp(freq.dimord, 'chan_freq_time')
tbin = nearest(freq.time, cfg.latency);
fprintf('selecting timeslice %d\n', tbin);
freq.time = freq.time(tbin);
% remove all other latencies from the data structure and reduce the number of dimensions
if isfield(freq, 'powspctrm'), freq.powspctrm = squeeze(freq.powspctrm(:,:,tbin)); end;
if isfield(freq, 'crsspctrm'), freq.crsspctrm = squeeze(freq.crsspctrm(:,:,tbin)); end;
if isfield(freq, 'fourierspctrm'), freq.fourierspctrm = squeeze(freq.fourierspctrm(:,:,tbin)); end;
freq.dimord = freq.dimord(1:(end-5)); % remove the '_time' part
elseif strcmp(freq.dimord, 'rpt_chan_freq_time') || strcmp(freq.dimord, 'rpttap_chan_freq_time')
tbin = nearest(freq.time, cfg.latency);
fprintf('selecting timeslice %d\n', tbin);
freq.time = freq.time(tbin);
% remove all other latencies from the data structure and reduce the number of dimensions
if isfield(freq, 'powspctrm'), freq.powspctrm = squeeze(freq.powspctrm(:,:,:,tbin)); end;
if isfield(freq, 'crsspctrm'), freq.crsspctrm = squeeze(freq.crsspctrm(:,:,:,tbin)); end;
if isfield(freq, 'fourierspctrm') freq.fourierspctrm = squeeze(freq.fourierspctrm(:,:,:,tbin)); end;
freq.dimord = freq.dimord(1:(end-5)); % remove the '_time' part
else
tbin = [];
end
% the time-frequency latency has already been squeezed away (see above)
if strcmp(freq.dimord, 'chan_freq') || strcmp(freq.dimord, 'chancmb_freq') || strcmp(freq.dimord, 'chan_chan_freq') || strcmp(freq.dimord, 'chan_chan_freq_time')
Ntrials = 1;
elseif strcmp(freq.dimord, 'rpt_chan_freq') || strcmp(freq.dimord, 'rpt_chancmb_freq') || strcmp(freq.dimord, 'rpt_chan_chan_freq')
Ntrials = size(freq.cumtapcnt,1);
elseif strcmp(freq.dimord, 'rpttap_chan_freq') || strcmp(freq.dimord, 'rpttap_chancmb_freq') || strcmp(freq.dimord, 'rpttap_chan_chan_freq')
Ntrials = size(freq.cumtapcnt,1);
elseif strcmp(freq.dimord, 'rpttap_chan_freq_time') || strcmp(freq.dimord, 'rpttap_chancmb_freq_time') || strcmp(freq.dimord, 'rpttap_chan_chan_freq_time')
Ntrials = size(freq.cumtapcnt,1);
else
error('unrecognized dimord for frequency data');
end
% find the frequency of interest
fbin = nearest(freq.freq, cfg.frequency);
if isfield(freq, 'powspctrm') && isfield(freq, 'crsspctrm')
% use the power and cross spectrum and construct a square matrix
% find the index of each sensor channel into powspctrm
% keep the channel order of the cfg
[dum, powspctrmindx] = match_str(cfg.channel, freq.label);
Nchans = length(powspctrmindx);
% find the index of each sensor channel combination into crsspctrm
% keep the channel order of the cfg
crsspctrmindx = zeros(Nchans);
for sgncmblop=1:size(freq.labelcmb,1)
ch1 = find(strcmp(cfg.channel, freq.labelcmb(sgncmblop,1)));
ch2 = find(strcmp(cfg.channel, freq.labelcmb(sgncmblop,2)));
if ~isempty(ch1) && ~isempty(ch2)
% this square matrix contains the indices into the signal combinations
crsspctrmindx(ch1,ch2) = sgncmblop;
end
end
% this complex rearrangement of channel indices transforms the CSDs into a square matrix
if strcmp(freq.dimord, 'chan_freq') || strcmp(freq.dimord, 'chancmb_freq')
% FIXME this fails in case dimord=rpt_chan_freq and only 1 trial
Cf = complex(nan(Nchans,Nchans));
% first use the complex conjugate for all reversed signal combinations
Cf(find(crsspctrmindx)) = freq.crsspctrm(crsspctrmindx(find(crsspctrmindx)), fbin);
Cf = ctranspose(Cf);
% and then get get the csd for all signal combinations
Cf(find(crsspctrmindx)) = freq.crsspctrm(crsspctrmindx(find(crsspctrmindx)), fbin);
% put the power on the diagonal
Cf(find(eye(Nchans))) = freq.powspctrm(powspctrmindx, fbin);
else
Cf = complex(nan(Ntrials,Nchans,Nchans));
tmp = complex(nan(Nchans,Nchans));
for trial=1:Ntrials
% first use the complex conjugate for all signal combinations reversed
tmp(find(crsspctrmindx)) = freq.crsspctrm(trial, crsspctrmindx(find(crsspctrmindx)), fbin);
tmp = ctranspose(tmp);
% and then get get the csd for all signal combinations
tmp(find(crsspctrmindx)) = freq.crsspctrm(trial, crsspctrmindx(find(crsspctrmindx)), fbin);
% put the power on the diagonal
tmp(find(eye(Nchans))) = freq.powspctrm(trial, powspctrmindx, fbin);
Cf(trial,:,:) = tmp;
end
end
% do a sanity check on the cross-spectral-density matrix
if any(isnan(Cf(:)))
error('The cross-spectral-density matrix is not complete');
end
if isfield(cfg, 'refchan') && ~isempty(cfg.refchan)
% contruct the cross-spectral-density vector of the reference channel with all MEG channels
tmpindx = match_str(freq.labelcmb(:,1), cfg.refchan);
refindx = match_str(freq.labelcmb(tmpindx,2), cfg.channel);
refindx = tmpindx(refindx);
flipref = 0;
if isempty(refindx)
% first look in the second column, then in the first
tmpindx = match_str(freq.labelcmb(:,2), cfg.refchan);
refindx = match_str(freq.labelcmb(tmpindx,1), cfg.channel);
refindx = tmpindx(refindx);
flipref = 1;
end
if length(refindx)~=Nchans
error('The cross-spectral-density with the reference channel is not complete');
end
if Ntrials==1
Cr = freq.crsspctrm(refindx, fbin);
else
for trial=1:Ntrials
Cr(trial,:) = freq.crsspctrm(trial, refindx, fbin);
end
end
if flipref
Cr = conj(Cr);
end
% obtain the power of the reference channel
refindx = match_str(freq.label, cfg.refchan);
if length(refindx)<1
error('The reference channel was not found in powspctrm');
elseif length(refindx)>1
error('Multiple occurences of the reference channel found in powspctrm');
end
if Ntrials==1
Pr = freq.powspctrm(refindx, fbin);
else
for trial=1:Ntrials
Pr(trial) = freq.powspctrm(trial, refindx, fbin);
end
Pr = Pr(:); % ensure that the first dimension contains the trials
end
end
if strcmp(cfg.dicsfix, 'yes')
Cr = conj(Cr);
end
elseif isfield(freq, 'crsspctrm')
% this is from JMs version
hastime = isfield(freq, 'time');
hasrefchan = ~isempty(cfg.refchan);
% select time-frequency window of interest
if hastime
freq = ft_selectdata(freq, 'foilim', cfg.frequency, 'toilim', cfg.latency);
fbin = 1;
tbin = 1:numel(freq.time);
else
freq = ft_selectdata(freq, 'foilim', cfg.frequency);
fbin = 1;
end
% convert to square csd matrix
% think of incorporating 'quickflag' to speed up the
% computation from fourierspectra when single trial
% estimates are not required...
freq = ft_checkdata(freq, 'cmbrepresentation', 'full');
[dum, sensindx] = match_str(cfg.channel, freq.label);
powspctrmindx = sensindx;
if isempty(strfind(freq.dimord, 'rpt'))
Ntrials = 1;
Cf = freq.crsspctrm(sensindx,sensindx,:,:);
if hasrefchan,
refindx = match_str(freq.label, cfg.refchan);
Cr = freq.crsspctrm(sensindx,refindx,:,:);
Pr = freq.crsspctrm(refindx,refindx,:,:);
else
Cr = [];
Pr = [];
end
elseif ~isempty(strfind(freq.dimord, 'rpt')),
Ntrials = length(freq.cumtapcnt);
Cf = freq.crsspctrm(:,sensindx,sensindx,:,:);
if hasrefchan,
refindx = match_str(freq.label, cfg.refchan);
Cr = freq.crsspctrm(:,sensindx,refindx,:,:);
Pr = freq.crsspctrm(:,refindx,refindx,:,:);
else
Cr = [];
Pr = [];
end
end
else
fprintf('computing cross-spectrum from fourier\n');
[dum, powspctrmindx] = match_str(cfg.channel, freq.label);
% use the fourier spectrum to compute the complete cross spectrum matrix
Nchans = length(powspctrmindx);
if strcmp(freq.dimord, 'chan_freq')
error('incompatible dimord for computing CSD matrix from fourier');
elseif strcmp(freq.dimord, 'rpt_chan_freq')
error('incompatible dimord for computing CSD matrix from fourier');
elseif strcmp(freq.dimord, 'rpttap_chan_freq'),
if quickflag,
Ntrials = 1;
end
Cf = zeros(Ntrials,Nchans,Nchans);
refindx = match_str(freq.label, cfg.refchan);
if ~isempty(refindx)
Cr = zeros(Ntrials,Nchans,1);
Pr = zeros(Ntrials,1,1);
end
if quickflag,
ntap = sum(freq.cumtapcnt);
dat = transpose(freq.fourierspctrm(:, powspctrmindx, fbin));
Cf(1,:,:) = (dat * ctranspose(dat)) ./ ntap;
if ~isempty(refindx)
ref = transpose(freq.fourierspctrm(:, refindx, fbin));
Cr(1,:,1) = dat * ctranspose(ref) ./ ntap;
Pr(1,1,1) = ref * ctranspose(ref) ./ ntap;
end
else
freq.cumtapcnt = freq.cumtapcnt(:)';
for k=1:Ntrials
tapbeg = 1 + sum([0 freq.cumtapcnt(1:(k-1))]);
tapend = sum([0 freq.cumtapcnt(1:(k ))]);
ntap = freq.cumtapcnt(k);
dat = transpose(freq.fourierspctrm(tapbeg:tapend, powspctrmindx, fbin));
Cf(k,:,:) = (dat * ctranspose(dat)) ./ ntap;
if ~isempty(refindx)
ref = transpose(freq.fourierspctrm(tapbeg:tapend, refindx, fbin));
Cr(k,:,1) = dat * ctranspose(ref) ./ ntap;
Pr(k,1,1) = ref * ctranspose(ref) ./ ntap;
end
end
end
else
error('unsupported dimord for fourier cross-spectrum computation');
end
end
% update the configuration, so that the calling function exactly knows what was selected
if ~isempty(tbin),
% a single latency was selected in the freq structure
cfg.latency = freq.time;
else
cfg.latency = [];
end
cfg.frequency = freq.freq(fbin);
cfg.channel = freq.label(powspctrmindx);
|
github
|
lcnhappe/happe-master
|
test_ft_checkdata.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/test_ft_checkdata.m
| 7,907 |
utf_8
|
342cc383141a15f393ff7aedcbb493a4
|
function test_ft_checkdata
% MEM 1500mb
% WALLTIME 00:20:00
% TEST test_ft_checkdata
% TEST ft_checkdata
%% converting raw data to timelock data
% make some raw data with unequal time-axis, excluding 0
data = [];
data.label = {'1', '2'};
for m=[eps exp(1) pi 1:20]
for n=.1:.1:m
data.time{1} = -.5:(n/m):-.1;
data.time{2} = -.5:(n/m):-.1;
fsample = mean(diff(data.time{1}));
if fsample <= 0 || isnan(fsample)
continue;
end
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
if (mean(diff(tmp.time)) - fsample > 12e-17)
error('estimation of fsample does not match!')
end
end
end
for m=[eps exp(1) pi 1:20]
for n=.1:.1:m
data.time{1} = .1:(n/m):.5;
data.time{2} = .1:(n/m):.5;
fsample = mean(diff(data.time{1}));
if fsample <= 0 || isnan(fsample)
continue;
end
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
if (mean(diff(tmp.time)) - fsample > 12e-17)
error('estimation of fsample does not match!')
end
end
end
% make some raw data with strange time-axis
data = [];
data.label = {'1', '2'};
for m=[eps exp(1) pi 1:20]
for n=.1:.1:m
data.time{1} = [-(n.^2/m) -(n/m)];
data.time{2} = [-(n.^2/m) -(n/m)];
fsample = mean(diff(data.time{1}));
if fsample <= 0 || isnan(fsample)
continue;
end
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
if (mean(diff(tmp.time)) - fsample > 12e-17)
error('estimation of fsample does not match!')
end
end
for n=eps^1.1:eps^1.1:eps
data.time{1} = [-(n.^2/m) -(n/m)];
data.time{2} = [-(n.^2/m) -(n/m)];
fsample = mean(diff(data.time{1}));
if fsample <= 0 || isnan(fsample)
continue;
end
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
if (mean(diff(tmp.time)) - fsample > 12e-17)
error('estimation of fsample does not match!')
end
end
end
for m=[eps exp(1) pi 1:20]
for n=eps:1:m
data.time{1} = [-m -n];
data.time{2} = [-m -n];
fsample = mean(diff(data.time{1}));
if fsample <= 0 || isnan(fsample)
continue;
end
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
if (n==eps)
try
tmp = ft_checkdata(data, 'datatype', 'timelock');
if (mean(diff(tmp.time)) - fsample > 12e-17)
warning('estimation of fsample does not match, but we''re near eps!')
end
catch
warning('checkdata crashed, but we''re near eps!')
end
else
tmp = ft_checkdata(data, 'datatype', 'timelock');
if (mean(diff(tmp.time)) - fsample > 12e-17)
error('estimation of fsample does not match!')
end
end
end
for n=eps^1.1:eps^1.1:eps
data.time{1} = [-(n.^2/m) -(n/m)];
data.time{2} = [-(n.^2/m) -(n/m)];
fsample = mean(diff(data.time{1}));
if fsample <= 0 || isnan(fsample)
continue;
end
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
if (mean(diff(tmp.time)) - fsample > 12e-17)
error('estimation of fsample does not match!')
end
end
end
% make some raw data with unequal time-axis, excluding 0
data = [];
data.label = {'1', '2'};
data.time{1} = [-1.5 -1.28];
data.time{2} = [2.68 2.9];
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
if sum(tmp.time-[-1.5:0.22:3]) > 12e-17 | numel(tmp.time) ~= 21
error('time axis is wrong');
end
% make some raw data with unequal time-axis, including 0 implicitly
data = [];
data.label = {'1', '2'};
data.time{1} = [-2 -1];
data.time{2} = [3 4];
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
if ~isequal(tmp.time, [-2:4])
error('time axis is wrong');
end
% make some raw data with unequal time-axis, strictly < 0
% see bug 1477
data = [];
data.label = {'1', '2'};
data.time{1} = [-5 -4];
data.time{2} = [-3 -2];
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
if ~isequal(tmp.time, [-5:-2])
error('time axis is wrong');
end
% make some raw data with unequal time-axis, strictly > 0
% related to bug 1477
data = [];
data.label = {'1', '2'};
data.time{1} = [4 5];
data.time{2} = [2 3];
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
if ~isequal(tmp.time, [2:5])
error('time axis is wrong');
end
% make some raw data with unequal time-axis, including 0, with some jitter
success = 0;
attempts = 5; % this might not work if the RNG sucks
while ~success
try
data = [];
data.label = {'1', '2'};
data.time{1} = -.5:.25:1;
data.time{2} = -.25:.25:.25;
data.time{3} = .25:.25:1;
data.time{4} = -.5:.25:-.25;
for i=1:numel(data.time)
data.time{i} = data.time{i} + (rand-0.5)/1000;
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
success = 1;
end
end
%% converting raw data to timelock data
% make some raw data with unequal time-axis, including 0
data = [];
data.label = {'1', '2'};
data.time{1} = -.5:.25:1;
data.time{2} = -.25:.25:.25;
data.time{3} = .25:.25:1;
data.time{4} = -.5:.25:-.25;
for i=1:numel(data.time)
data.trial{i} = rand(size(data.label, 2), size(data.time{i}, 2));
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
sanityCheck(tmp);
%% shift time axis to be strictly positive
for i=1:numel(data.time)
data.time{i} = data.time{i} + 0.6;
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
sanityCheck(tmp);
%% shift time axis to be strictly negative
for i=1:numel(data.time)
data.time{i} = data.time{i} - .6 - 1.1;
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
sanityCheck(tmp);
%% make time-axis incredibly small
data.time{1} = -.5:.25:1;
data.time{2} = -.25:.25:.25;
data.time{3} = .25:.25:1;
data.time{4} = -.5:.25:-.25;
for i=1:numel(data.time)
data.time{i} = (data.time{i}) ./ (10^-12);
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
sanityCheck(tmp);
%% make time-axis awesomly huge
data.time{1} = -.5:.25:1;
data.time{2} = -.25:.25:.25;
data.time{3} = .25:.25:1;
data.time{4} = -.5:.25:-.25;
for i=1:numel(data.time)
data.time{i} = data.time{i} .* (10^12);
end
tmp = ft_checkdata(data, 'datatype', 'timelock');
sanityCheck(tmp);
end
function sanityCheck(tmp)
% sanity checks
if ~isequal(size(tmp.sampleinfo), [4,2])
error('sampleinfo is wrong');
end
if ~isequal(tmp.time, [-.5:.25:1]) && ...
~isequal(tmp.time, [-.5:.25:1]+ 0.6) && ...
~isequal(tmp.time, [-.5:.25:1]- 1.1) && ...
~isequal(tmp.time, [-.5:.25:1]./ 10^-12) && ...
~isequal(tmp.time, [-.5:.25:1].* 10^-12)
error('time axis is wrong');
end
% check individual trials
% note that we handle two channels here
if any(isnan(tmp.trial(1, :))) ...
|| any(isnan(tmp.trial(2, 3:8))) || any(~isnan(tmp.trial(2, [1 2 9:14]))) ...
|| any(isnan(tmp.trial(3, 7:14))) || any(~isnan(tmp.trial(3, [1:6]))) ...
|| any(isnan(tmp.trial(4, 1:4))) || any(~isnan(tmp.trial(4, [5:14])))
error('nans are misplaced in .trial');
end
end
|
github
|
lcnhappe/happe-master
|
getdimord.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/private/getdimord.m
| 20,107 |
utf_8
|
706f4f45a5d4ae7535c204b8c010f76b
|
function dimord = getdimord(data, field, varargin)
% GETDIMORD
%
% Use as
% dimord = getdimord(data, field)
%
% See also GETDIMSIZ, GETDATFIELD
if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field)
field = ['avg.' field];
elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field)
field = ['trial.' field];
elseif ~isfield(data, field)
error('field "%s" not present in data', field);
end
if strncmp(field, 'avg.', 4)
prefix = '';
field = field(5:end); % strip the avg
data.(field) = data.avg.(field); % copy the avg into the main structure
data = rmfield(data, 'avg');
elseif strncmp(field, 'trial.', 6)
prefix = '(rpt)_';
field = field(7:end); % strip the trial
data.(field) = data.trial(1).(field); % copy the first trial into the main structure
data = rmfield(data, 'trial');
else
prefix = '';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 1: the specific dimord is simply present
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(data, [field 'dimord'])
dimord = data.([field 'dimord']);
return
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if not present, we need some additional information about the data strucure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% nan means that the value is not known and might remain unknown
% inf means that the value is not known but should be known
ntime = inf;
nfreq = inf;
nchan = inf;
nchancmb = inf;
nsubj = nan;
nrpt = nan;
nrpttap = nan;
npos = inf;
nori = nan; % this will be 3 in many cases
ntopochan = inf;
nspike = inf; % this is only for the first spike channel
nlag = nan;
ndim1 = nan;
ndim2 = nan;
ndim3 = nan;
% use an anonymous function
assign = @(var, val) assignin('caller', var, val);
% it is possible to pass additional ATTEMPTs such as nrpt, nrpttap, etc
for i=1:2:length(varargin)
assign(varargin{i}, varargin{i+1});
end
% try to determine the size of each possible dimension in the data
if isfield(data, 'label')
nchan = length(data.label);
end
if isfield(data, 'labelcmb')
nchancmb = size(data.labelcmb, 1);
end
if isfield(data, 'time')
if iscell(data.time) && ~isempty(data.time)
tmp = getdimsiz(data, 'time');
ntime = tmp(3); % raw data may contain variable length trials
else
ntime = length(data.time);
end
end
if isfield(data, 'freq')
nfreq = length(data.freq);
end
if isfield(data, 'trial') && ft_datatype(data, 'raw')
nrpt = length(data.trial);
end
if isfield(data, 'trialtime') && ft_datatype(data, 'spike')
nrpt = size(data.trialtime,1);
end
if isfield(data, 'cumtapcnt')
nrpt = size(data.cumtapcnt,1);
if numel(data.cumtapcnt)==length(data.cumtapcnt)
% it is a vector, hence it only represents repetitions
nrpttap = sum(data.cumtapcnt);
else
% it is a matrix, hence it is repetitions by frequencies
% this happens after mtmconvol with keeptrials
nrpttap = sum(data.cumtapcnt,2);
if any(nrpttap~=nrpttap(1))
warning('unexpected variation of the number of tapers over trials')
nrpttap = nan;
else
nrpttap = nrpttap(1);
end
end
end
if isfield(data, 'pos')
npos = size(data.pos,1);
elseif isfield(data, 'dim')
npos = prod(data.dim);
end
if isfield(data, 'dim')
ndim1 = data.dim(1);
ndim2 = data.dim(2);
ndim3 = data.dim(3);
end
if isfield(data, 'csdlabel')
% this is used in PCC beamformers
if length(data.csdlabel)==npos
% each position has its own labels
len = cellfun(@numel, data.csdlabel);
len = len(len~=0);
if all(len==len(1))
% they all have the same length
nori = len(1);
end
else
% one list of labels for all positions
nori = length(data.csdlabel);
end
elseif isfinite(npos)
% assume that there are three dipole orientations per source
nori = 3;
end
if isfield(data, 'topolabel')
% this is used in ICA and PCA decompositions
ntopochan = length(data.topolabel);
end
if isfield(data, 'timestamp') && iscell(data.timestamp)
nspike = length(data.timestamp{1}); % spike data: only for the first channel
end
if ft_datatype(data, 'mvar') && isfield(data, 'coeffs')
nlag = size(data.coeffs,3);
end
% determine the size of the actual data
datsiz = getdimsiz(data, field);
tok = {'subj' 'rpt' 'rpttap' 'chan' 'chancmb' 'freq' 'time' 'pos' 'ori' 'topochan' 'lag' 'dim1' 'dim2' 'dim3'};
siz = [nsubj nrpt nrpttap nchan nchancmb nfreq ntime npos nori ntopochan nlag ndim1 ndim2 ndim3];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 2: a general dimord is present and might apply
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(data, 'dimord')
dimtok = tokenize(data.dimord, '_');
if length(dimtok)>length(datsiz) && check_trailingdimsunitlength(data, dimtok((length(datsiz)+1):end))
% add the trailing singleton dimensions to datsiz, if needed
datsiz = [datsiz ones(1,max(0,length(dimtok)-length(datsiz)))];
end
if length(dimtok)==length(datsiz) || (length(dimtok)==(length(datsiz)-1) && datsiz(end)==1)
success = false(size(dimtok));
for i=1:length(dimtok)
sel = strcmp(tok, dimtok{i});
if any(sel) && datsiz(i)==siz(sel)
success(i) = true;
elseif strcmp(dimtok{i}, 'subj')
% the number of subjects cannot be determined, and will be indicated as nan
success(i) = true;
elseif strcmp(dimtok{i}, 'rpt')
% the number of trials is hard to determine, and might be indicated as nan
success(i) = true;
end
end % for
if all(success)
dimord = data.dimord;
return
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 3: look at the size of some common fields that are known
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch field
% the logic for this code is to first check whether the size of a field
% has an exact match to a potential dimensionality, if not, check for a
% partial match (ignoring nans)
% note that the case for a cell dimension (typically pos) is handled at
% the end of this section
case {'pos'}
if isequalwithoutnans(datsiz, [npos 3])
dimord = 'pos_unknown';
end
case {'individual'}
if isequalwithoutnans(datsiz, [nsubj nchan ntime])
dimord = 'subj_chan_time';
end
case {'avg' 'var' 'dof'}
if isequal(datsiz, [nrpt nchan ntime])
dimord = 'rpt_chan_time';
elseif isequal(datsiz, [nchan ntime])
dimord = 'chan_time';
elseif isequalwithoutnans(datsiz, [nrpt nchan ntime])
dimord = 'rpt_chan_time';
elseif isequalwithoutnans(datsiz, [nchan ntime])
dimord = 'chan_time';
end
case {'powspctrm' 'fourierspctrm'}
if isequal(datsiz, [nrpt nchan nfreq ntime])
dimord = 'rpt_chan_freq_time';
elseif isequal(datsiz, [nrpt nchan nfreq])
dimord = 'rpt_chan_freq';
elseif isequal(datsiz, [nchan nfreq ntime])
dimord = 'chan_freq_time';
elseif isequal(datsiz, [nchan nfreq])
dimord = 'chan_freq';
elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq ntime])
dimord = 'rpt_chan_freq_time';
elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq])
dimord = 'rpt_chan_freq';
elseif isequalwithoutnans(datsiz, [nchan nfreq ntime])
dimord = 'chan_freq_time';
elseif isequalwithoutnans(datsiz, [nchan nfreq])
dimord = 'chan_freq';
end
case {'crsspctrm' 'cohspctrm'}
if isequal(datsiz, [nrpt nchancmb nfreq ntime])
dimord = 'rpt_chancmb_freq_time';
elseif isequal(datsiz, [nrpt nchancmb nfreq])
dimord = 'rpt_chancmb_freq';
elseif isequal(datsiz, [nchancmb nfreq ntime])
dimord = 'chancmb_freq_time';
elseif isequal(datsiz, [nchancmb nfreq])
dimord = 'chancmb_freq';
elseif isequal(datsiz, [nrpt nchan nchan nfreq ntime])
dimord = 'rpt_chan_chan_freq_time';
elseif isequal(datsiz, [nrpt nchan nchan nfreq])
dimord = 'rpt_chan_chan_freq';
elseif isequal(datsiz, [nchan nchan nfreq ntime])
dimord = 'chan_chan_freq_time';
elseif isequal(datsiz, [nchan nchan nfreq])
dimord = 'chan_chan_freq';
elseif isequal(datsiz, [npos nori])
dimord = 'pos_ori';
elseif isequal(datsiz, [npos 1])
dimord = 'pos';
elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq ntime])
dimord = 'rpt_chancmb_freq_time';
elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq])
dimord = 'rpt_chancmb_freq';
elseif isequalwithoutnans(datsiz, [nchancmb nfreq ntime])
dimord = 'chancmb_freq_time';
elseif isequalwithoutnans(datsiz, [nchancmb nfreq])
dimord = 'chancmb_freq';
elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq ntime])
dimord = 'rpt_chan_chan_freq_time';
elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq])
dimord = 'rpt_chan_chan_freq';
elseif isequalwithoutnans(datsiz, [nchan nchan nfreq ntime])
dimord = 'chan_chan_freq_time';
elseif isequalwithoutnans(datsiz, [nchan nchan nfreq])
dimord = 'chan_chan_freq';
elseif isequalwithoutnans(datsiz, [npos nori])
dimord = 'pos_ori';
elseif isequalwithoutnans(datsiz, [npos 1])
dimord = 'pos';
end
case {'cov' 'coh' 'csd' 'noisecov' 'noisecsd'}
% these occur in timelock and in source structures
if isequal(datsiz, [nrpt nchan nchan])
dimord = 'rpt_chan_chan';
elseif isequal(datsiz, [nchan nchan])
dimord = 'chan_chan';
elseif isequal(datsiz, [npos nori nori])
dimord = 'pos_ori_ori';
elseif isequal(datsiz, [npos nrpt nori nori])
dimord = 'pos_rpt_ori_ori';
elseif isequalwithoutnans(datsiz, [nrpt nchan nchan])
dimord = 'rpt_chan_chan';
elseif isequalwithoutnans(datsiz, [nchan nchan])
dimord = 'chan_chan';
elseif isequalwithoutnans(datsiz, [npos nori nori])
dimord = 'pos_ori_ori';
elseif isequalwithoutnans(datsiz, [npos nrpt nori nori])
dimord = 'pos_rpt_ori_ori';
end
case {'tf'}
if isequal(datsiz, [npos nfreq ntime])
dimord = 'pos_freq_time';
end
case {'pow'}
if isequal(datsiz, [npos ntime])
dimord = 'pos_time';
elseif isequal(datsiz, [npos nfreq])
dimord = 'pos_freq';
elseif isequal(datsiz, [npos nrpt])
dimord = 'pos_rpt';
elseif isequal(datsiz, [nrpt npos ntime])
dimord = 'rpt_pos_time';
elseif isequal(datsiz, [nrpt npos nfreq])
dimord = 'rpt_pos_freq';
elseif isequal(datsiz, [npos 1]) % in case there are no repetitions
dimord = 'pos';
elseif isequalwithoutnans(datsiz, [npos ntime])
dimord = 'pos_time';
elseif isequalwithoutnans(datsiz, [npos nfreq])
dimord = 'pos_freq';
elseif isequalwithoutnans(datsiz, [npos nrpt])
dimord = 'pos_rpt';
elseif isequalwithoutnans(datsiz, [nrpt npos ntime])
dimord = 'rpt_pos_time';
elseif isequalwithoutnans(datsiz, [nrpt npos nfreq])
dimord = 'rpt_pos_freq';
end
case {'mom','itc','aa','stat','pval','statitc','pitc'}
if isequal(datsiz, [npos nori nrpt])
dimord = 'pos_ori_rpt';
elseif isequal(datsiz, [npos nori ntime])
dimord = 'pos_ori_time';
elseif isequal(datsiz, [npos nori nfreq])
dimord = 'pos_ori_nfreq';
elseif isequal(datsiz, [npos ntime])
dimord = 'pos_time';
elseif isequal(datsiz, [npos nfreq])
dimord = 'pos_freq';
elseif isequal(datsiz, [npos 3])
dimord = 'pos_ori';
elseif isequal(datsiz, [npos 1])
dimord = 'pos';
elseif isequal(datsiz, [npos nrpt])
dimord = 'pos_rpt';
elseif isequalwithoutnans(datsiz, [npos nori nrpt])
dimord = 'pos_ori_rpt';
elseif isequalwithoutnans(datsiz, [npos nori ntime])
dimord = 'pos_ori_time';
elseif isequalwithoutnans(datsiz, [npos nori nfreq])
dimord = 'pos_ori_nfreq';
elseif isequalwithoutnans(datsiz, [npos ntime])
dimord = 'pos_time';
elseif isequalwithoutnans(datsiz, [npos nfreq])
dimord = 'pos_freq';
elseif isequalwithoutnans(datsiz, [npos 3])
dimord = 'pos_ori';
elseif isequalwithoutnans(datsiz, [npos 1])
dimord = 'pos';
elseif isequalwithoutnans(datsiz, [npos nrpt])
dimord = 'pos_rpt';
elseif isequalwithoutnans(datsiz, [npos nrpt nori ntime])
dimord = 'pos_rpt_ori_time';
elseif isequalwithoutnans(datsiz, [npos nrpt 1 ntime])
dimord = 'pos_rpt_ori_time';
elseif isequal(datsiz, [npos nfreq ntime])
dimord = 'pos_freq_time';
end
case {'filter'}
if isequalwithoutnans(datsiz, [npos nori nchan]) || (isequal(datsiz([1 2]), [npos nori]) && isinf(nchan))
dimord = 'pos_ori_chan';
end
case {'leadfield'}
if isequalwithoutnans(datsiz, [npos nchan nori]) || (isequal(datsiz([1 3]), [npos nori]) && isinf(nchan))
dimord = 'pos_chan_ori';
end
case {'ori' 'eta'}
if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3])
dimord = 'pos_ori';
end
case {'csdlabel'}
if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3])
dimord = 'pos_ori';
end
case {'trial'}
if ~iscell(data.(field)) && isequalwithoutnans(datsiz, [nrpt nchan ntime])
dimord = 'rpt_chan_time';
elseif isequalwithoutnans(datsiz, [nrpt nchan ntime])
dimord = '{rpt}_chan_time';
elseif isequalwithoutnans(datsiz, [nchan nspike]) || isequalwithoutnans(datsiz, [nchan 1 nspike])
dimord = '{chan}_spike';
end
case {'sampleinfo' 'trialinfo' 'trialtime'}
if isequalwithoutnans(datsiz, [nrpt nan])
dimord = 'rpt_other';
end
case {'cumtapcnt' 'cumsumcnt'}
if isequalwithoutnans(datsiz, [nrpt nan])
dimord = 'rpt_other';
end
case {'topo'}
if isequalwithoutnans(datsiz, [ntopochan nchan])
dimord = 'topochan_chan';
end
case {'unmixing'}
if isequalwithoutnans(datsiz, [nchan ntopochan])
dimord = 'chan_topochan';
end
case {'inside'}
if isequalwithoutnans(datsiz, [npos])
dimord = 'pos';
end
case {'timestamp' 'time'}
if ft_datatype(data, 'spike') && iscell(data.(field)) && datsiz(1)==nchan
dimord = '{chan}_spike';
elseif ft_datatype(data, 'raw') && iscell(data.(field)) && datsiz(1)==nrpt
dimord = '{rpt}_time';
elseif isvector(data.(field)) && isequal(datsiz, [1 ntime ones(1,numel(datsiz)-2)])
dimord = 'time';
end
case {'freq'}
if isvector(data.(field)) && isequal(datsiz, [1 nfreq])
dimord = 'freq';
end
otherwise
if isfield(data, 'dim') && isequal(datsiz, data.dim)
dimord = 'dim1_dim2_dim3';
end
end % switch field
% deal with possible first pos which is a cell
if exist('dimord', 'var') && strcmp(dimord(1:3), 'pos') && iscell(data.(field))
dimord = ['{pos}' dimord(4:end)];
end
if ~exist('dimord', 'var')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 4: there is only one way that the dimensions can be interpreted
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dimtok = cell(size(datsiz));
for i=1:length(datsiz)
sel = find(siz==datsiz(i));
if length(sel)==1
% there is exactly one corresponding dimension
dimtok{i} = tok{sel};
else
% there are zero or multiple corresponding dimensions
dimtok{i} = [];
end
end
if all(~cellfun(@isempty, dimtok))
if iscell(data.(field))
dimtok{1} = ['{' dimtok{1} '}'];
end
dimord = sprintf('%s_', dimtok{:});
dimord = dimord(1:end-1);
return
end
end % if dimord does not exist
if ~exist('dimord', 'var')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 5: compare the size with the known size of each dimension
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sel = ~isnan(siz) & ~isinf(siz);
% nan means that the value is not known and might remain unknown
% inf means that the value is not known and but should be known
if length(unique(siz(sel)))==length(siz(sel))
% this should only be done if there is no chance of confusing dimensions
dimtok = cell(size(datsiz));
dimtok(datsiz==npos) = {'pos'};
dimtok(datsiz==nori) = {'ori'};
dimtok(datsiz==nrpttap) = {'rpttap'};
dimtok(datsiz==nrpt) = {'rpt'};
dimtok(datsiz==nsubj) = {'subj'};
dimtok(datsiz==nchancmb) = {'chancmb'};
dimtok(datsiz==nchan) = {'chan'};
dimtok(datsiz==nfreq) = {'freq'};
dimtok(datsiz==ntime) = {'time'};
dimtok(datsiz==ndim1) = {'dim1'};
dimtok(datsiz==ndim2) = {'dim2'};
dimtok(datsiz==ndim3) = {'dim3'};
if isempty(dimtok{end}) && datsiz(end)==1
% remove the unknown trailing singleton dimension
dimtok = dimtok(1:end-1);
elseif isequal(dimtok{1}, 'pos') && isempty(dimtok{2}) && datsiz(2)==1
% remove the unknown leading singleton dimension
dimtok(2) = [];
end
if all(~cellfun(@isempty, dimtok))
if iscell(data.(field))
dimtok{1} = ['{' dimtok{1} '}'];
end
dimord = sprintf('%s_', dimtok{:});
dimord = dimord(1:end-1);
return
end
end
end % if dimord does not exist
if ~exist('dimord', 'var')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 6: check whether it is a 3-D volume
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isequal(datsiz, [ndim1 ndim2 ndim3])
dimord = 'dim1_dim2_dim3';
end
end % if dimord does not exist
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% FINAL RESORT: return "unknown" for all unknown dimensions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~exist('dimord', 'var')
% this should not happen
% if it does, it might help in diagnosis to have a very informative warning message
% since there have been problems with trials not being selected correctly due to the warning going unnoticed
% it is better to throw an error than a warning
warning('could not determine dimord of "%s" in the following data', field)
disp(data);
dimtok(cellfun(@isempty, dimtok)) = {'unknown'};
if all(~cellfun(@isempty, dimtok))
if iscell(data.(field))
dimtok{1} = ['{' dimtok{1} '}'];
end
dimord = sprintf('%s_', dimtok{:});
dimord = dimord(1:end-1);
end
end
% add '(rpt)' in case of source.trial
dimord = [prefix dimord];
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ok = isequalwithoutnans(a, b)
% this is *only* used to compare matrix sizes, so we can ignore any singleton last dimension
numdiff = numel(b)-numel(a);
if numdiff > 0
% assume singleton dimensions missing in a
a = [a(:); ones(numdiff, 1)];
b = b(:);
elseif numdiff < 0
% assume singleton dimensions missing in b
b = [b(:); ones(abs(numdiff), 1)];
a = a(:);
end
c = ~isnan(a(:)) & ~isnan(b(:));
ok = isequal(a(c), b(c));
end % function isequalwithoutnans
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ok = check_trailingdimsunitlength(data, dimtok)
ok = false;
for k = 1:numel(dimtok)
switch dimtok{k}
case 'chan'
ok = numel(data.label)==1;
otherwise
if isfield(data, dimtok{k}); % check whether field exists
ok = numel(data.(dimtok{k}))==1;
end;
end
if ok,
break;
end
end
end % function check_trailingdimsunitlength
|
github
|
lcnhappe/happe-master
|
normals.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/private/normals.m
| 2,528 |
utf_8
|
96701c7ebda7e6efca8095b3adb6081c
|
function [nrm] = normals(pnt, tri, opt)
% NORMALS compute the surface normals of a triangular mesh
% for each triangle or for each vertex
%
% [nrm] = normals(pnt, tri, opt)
% where opt is either 'vertex' or 'triangle'
% Copyright (C) 2002-2007, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% 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$
if nargin<3
opt='vertex';
elseif (opt(1)=='v' | opt(1)=='V')
opt='vertex';
elseif (opt(1)=='t' | opt(1)=='T')
opt='triangle';
else
error('invalid optional argument');
end
npnt = size(pnt,1);
ntri = size(tri,1);
% shift to center
pnt(:,1) = pnt(:,1)-mean(pnt(:,1),1);
pnt(:,2) = pnt(:,2)-mean(pnt(:,2),1);
pnt(:,3) = pnt(:,3)-mean(pnt(:,3),1);
% compute triangle normals
% nrm_tri = zeros(ntri, 3);
% for i=1:ntri
% v2 = pnt(tri(i,2),:) - pnt(tri(i,1),:);
% v3 = pnt(tri(i,3),:) - pnt(tri(i,1),:);
% nrm_tri(i,:) = cross(v2, v3);
% end
% vectorized version of the previous part
v2 = pnt(tri(:,2),:) - pnt(tri(:,1),:);
v3 = pnt(tri(:,3),:) - pnt(tri(:,1),:);
nrm_tri = cross(v2, v3);
if strcmp(opt, 'vertex')
% compute vertex normals
nrm_pnt = zeros(npnt, 3);
for i=1:ntri
nrm_pnt(tri(i,1),:) = nrm_pnt(tri(i,1),:) + nrm_tri(i,:);
nrm_pnt(tri(i,2),:) = nrm_pnt(tri(i,2),:) + nrm_tri(i,:);
nrm_pnt(tri(i,3),:) = nrm_pnt(tri(i,3),:) + nrm_tri(i,:);
end
% normalise the direction vectors to have length one
nrm = nrm_pnt ./ (sqrt(sum(nrm_pnt.^2, 2)) * ones(1,3));
else
% normalise the direction vectors to have length one
nrm = nrm_tri ./ (sqrt(sum(nrm_tri.^2, 2)) * ones(1,3));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fast cross product to replace the MATLAB standard version
function [c] = cross(a,b)
c = [a(:,2).*b(:,3)-a(:,3).*b(:,2) a(:,3).*b(:,1)-a(:,1).*b(:,3) a(:,1).*b(:,2)-a(:,2).*b(:,1)];
|
github
|
lcnhappe/happe-master
|
csp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/private/csp.m
| 1,702 |
utf_8
|
3eb6c73192bc8163344c9b5e70a04877
|
function [W] = csp(C1, C2, m)
% CSP calculates the common spatial pattern (CSP) projection.
%
% Use as:
% [W] = csp(C1, C2, m)
%
% This function implements the intents of the CSP algorithm described in [1].
% Specifically, CSP finds m spatial projections that maximize the variance (or
% band power) in one condition (described by the [p x p] channel-covariance
% matrix C1), and simultaneously minimizes the variance in the other (C2):
%
% W C1 W' = D
%
% and
%
% W (C1 + C2) W' = I,
%
% Where D is a diagonal matrix with decreasing values on it's diagonal, and I
% is the identity matrix of matching shape.
% The resulting [m x p] matrix can be used to project a zero-centered [p x n]
% trial matrix X:
%
% S = W X.
%
%
% Although the CSP is the de facto standard method for feature extraction for
% motor imagery induced event-related desynchronization, it is not strictly
% necessary [2].
%
% [1] Zoltan J. Koles. The quantitative extraction and topographic mapping of
% the abnormal components in the clinical EEG. Electroencephalography and
% Clinical Neurophysiology, 79(6):440--447, December 1991.
%
% [2] Jason Farquhar. A linear feature space for simultaneous learning of
% spatio-spectral filters in BCI. Neural Networks, 22:1278--1285, 2009.
% Copyright (c) 2012, Boris Reuderink
P = whiten(C1 + C2, 1e-14); % decorrelate over conditions
[B, Lamb, B2] = svd(P * C1 * P'); % rotation to decorrelate within condition.
W = B' * P;
% keep m projections at ends
keep = circshift(1:size(W, 1) <= m, [0, -m/2]);
W = W(keep,:);
function P = whiten(C, rtol)
[U, l, U2] = svd(C);
l = diag(l);
keep = l > max(l) * rtol;
P = diag(l(keep).^(-.5)) * U(:,keep)';
|
github
|
lcnhappe/happe-master
|
hcp_dirlist.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/private/hcp_dirlist.m
| 1,228 |
utf_8
|
b0501179c448a08e78e771ff578fa072
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [list, numdirs, numfiles] = hcp_dirlist(basedir, recursive)
if nargin<2
recursive = true;
end
if ~isdir(basedir)
error('directory "%s" does not exist', basedir)
end
list = dir(basedir);
% remove all non-directories and hidden directories
list = list([list.isdir]);
hidden = false(size(list));
for i=1:length(list)
hidden(i) = list(i).name(1)=='.';
end
list = list(~hidden);
% convert to cell-array
list = {list.name};
list = list(:);
for i=1:length(list)
list{i} = fullfile(basedir, list{i});
end
list = sort(list);
numdirs = nan(size(list));
numfiles = nan(size(list));
for i=1:length(list)
content = dir(list{i});
numdirs(i) = sum([content.isdir]) - 2;
numfiles(i) = length(content) - numdirs(i) - 2;
end
if recursive
sub_list = cell(size(list));
sub_numdirs = cell(size(list));
sub_numfiles = cell(size(list));
for i=1:length(list)
[sub_list{i}, sub_numdirs{i}, sub_numfiles{i}] = hcp_dirlist(list{i}, recursive);
end
list = cat(1, list, sub_list{:});
numdirs = cat(1, numdirs, sub_numdirs{:});
numfiles = cat(1, numfiles, sub_numfiles{:});
end
|
github
|
lcnhappe/happe-master
|
ft_platform_supports.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/private/ft_platform_supports.m
| 9,557 |
utf_8
|
eb0e55d84d57e6873cce8df6cad90d96
|
function tf = ft_platform_supports(what,varargin)
% FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform
% supports a specific capability
%
% Usage:
% tf = ft_platform_supports(what)
% tf = ft_platform_supports('matlabversion', min_version, max_version)
%
% The following values are allowed for the 'what' parameter:
% value means that the following is supported:
%
% 'which-all' which(...,'all')
% 'exists-in-private-directory' exists(...) will look in the /private
% subdirectory to see if a file exists
% 'onCleanup' onCleanup(...)
% 'alim' alim(...)
% 'int32_logical_operations' bitand(a,b) with a, b of type int32
% 'graphics_objects' graphics sysem is object-oriented
% 'libmx_c_interface' libmx is supported through mex in the
% C-language (recent Matlab versions only
% support C++)
% 'stats' all statistical functions in
% FieldTrip's external/stats directory
% 'program_invocation_name' program_invocation_name() (GNU Octave)
% 'singleCompThread' start Matlab with -singleCompThread
% 'nosplash' -nosplash
% 'nodisplay' -nodisplay
% 'nojvm' -nojvm
% 'no-gui' start GNU Octave with --no-gui
% 'RandStream.setGlobalStream' RandStream.setGlobalStream(...)
% 'RandStream.setDefaultStream' RandStream.setDefaultStream(...)
% 'rng' rng(...)
% 'rand-state' rand('state')
% 'urlread-timeout' urlread(..., 'Timeout', t)
% 'griddata-vector-input' griddata(...,...,...,a,b) with a and b
% vectors
% 'griddata-v4' griddata(...,...,...,...,...,'v4'),
% that is v4 interpolation support
% 'uimenu' uimenu(...)
if ~ischar(what)
error('first argument must be a string');
end
switch what
case 'matlabversion'
tf = is_matlab() && matlabversion(varargin{:});
case 'exists-in-private-directory'
tf = is_matlab();
case 'which-all'
tf = is_matlab();
case 'onCleanup'
tf = is_octave() || matlabversion(7.8, Inf);
case 'alim'
tf = is_matlab();
case 'int32_logical_operations'
% earlier version of Matlab don't support bitand (and similar)
% operations on int32
tf = is_octave() || ~matlabversion(-inf, '2012a');
case 'graphics_objects'
% introduced in Matlab 2014b, graphics is handled through objects;
% previous versions use numeric handles
tf = is_matlab() && matlabversion('2014b', Inf);
case 'libmx_c_interface'
% removed after 2013b
tf = matlabversion(-Inf, '2013b');
case 'stats'
root_dir=fileparts(which('ft_defaults'));
external_stats_dir=fullfile(root_dir,'external','stats');
% these files are only used by other functions in the external/stats
% directory
exclude_mfiles={'common_size.m',...
'iscomplex.m',...
'lgamma.m'};
tf = has_all_functions_in_dir(external_stats_dir,exclude_mfiles);
case 'program_invocation_name'
% Octave supports program_invocation_name, which returns the path
% of the binary that was run to start Octave
tf = is_octave();
case 'singleCompThread'
tf = is_matlab() && matlabversion(7.8, inf);
case {'nosplash','nodisplay','nojvm'}
% Only on Matlab
tf = is_matlab();
case 'no-gui'
% Only on Octave
tf = is_octave();
case 'RandStream.setDefaultStream'
tf = is_matlab() && matlabversion('2008b', '2011b');
case 'RandStream.setGlobalStream'
tf = is_matlab() && matlabversion('2012a', inf);
case 'randomized_PRNG_on_startup'
tf = is_octave() || ~matlabversion(-Inf,'7.3');
case 'rng'
% recent Matlab versions
tf = is_matlab() && matlabversion('7.12',Inf);
case 'rand-state'
% GNU Octave
tf = is_octave();
case 'urlread-timeout'
tf = is_matlab() && matlabversion('2012b',Inf);
case 'griddata-vector-input'
tf = is_matlab();
case 'griddata-v4'
tf = is_matlab() && matlabversion('2009a',Inf);
case 'uimenu'
tf = is_matlab();
otherwise
error('unsupported value for first argument: %s', what);
end % switch
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function tf = is_matlab()
tf = ~is_octave();
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function tf = is_octave()
persistent cached_tf;
if isempty(cached_tf)
cached_tf = logical(exist('OCTAVE_VERSION', 'builtin'));
end
tf = cached_tf;
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function tf = has_all_functions_in_dir(in_dir, exclude_mfiles)
% returns true if all functions in in_dir are already provided by the
% platform
m_files=dir(fullfile(in_dir,'*.m'));
n=numel(m_files);
for k=1:n
m_filename=m_files(k).name;
if isempty(which(m_filename)) && ...
isempty(strmatch(m_filename,exclude_mfiles))
tf=false;
return;
end
end
tf=true;
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [inInterval] = matlabversion(min, max)
% MATLABVERSION checks if the current MATLAB version is within the interval
% specified by min and max.
%
% Use, e.g., as:
% if matlabversion(7.0, 7.9)
% % do something
% end
%
% Both strings and numbers, as well as infinities, are supported, eg.:
% matlabversion(7.1, 7.9) % is version between 7.1 and 7.9?
% matlabversion(6, '7.10') % is version between 6 and 7.10? (note: '7.10', not 7.10)
% matlabversion(-Inf, 7.6) % is version <= 7.6?
% matlabversion('2009b') % exactly 2009b
% matlabversion('2008b', '2010a') % between two versions
% matlabversion('2008b', Inf) % from a version onwards
% etc.
%
% See also VERSION, VER, VERLESSTHAN
% Copyright (C) 2006, Robert Oostenveld
% Copyright (C) 2010, Eelke Spaak
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% 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$
% this does not change over subsequent calls, making it persistent speeds it up
persistent curVer
if nargin<2
max = min;
end
if isempty(curVer)
curVer = version();
end
if ((ischar(min) && isempty(str2num(min))) || (ischar(max) && isempty(str2num(max))))
% perform comparison with respect to release string
ind = strfind(curVer, '(R');
[year, ab] = parseMatlabRelease(curVer((ind + 2):(numel(curVer) - 1)));
[minY, minAb] = parseMatlabRelease(min);
[maxY, maxAb] = parseMatlabRelease(max);
inInterval = orderedComparison(minY, minAb, maxY, maxAb, year, ab);
else % perform comparison with respect to version number
[major, minor] = parseMatlabVersion(curVer);
[minMajor, minMinor] = parseMatlabVersion(min);
[maxMajor, maxMinor] = parseMatlabVersion(max);
inInterval = orderedComparison(minMajor, minMinor, maxMajor, maxMinor, major, minor);
end
end % function
function [year, ab] = parseMatlabRelease(str)
if (str == Inf)
year = Inf; ab = Inf;
elseif (str == -Inf)
year = -Inf; ab = -Inf;
else
year = str2num(str(1:4));
ab = str(5);
end
end % function
function [major, minor] = parseMatlabVersion(ver)
if (ver == Inf)
major = Inf; minor = Inf;
elseif (ver == -Inf)
major = -Inf; minor = -Inf;
elseif (isnumeric(ver))
major = floor(ver);
minor = int8((ver - floor(ver)) * 10);
else % ver is string (e.g. '7.10'), parse accordingly
[major, rest] = strtok(ver, '.');
major = str2num(major);
minor = str2num(strtok(rest, '.'));
end
end % function
% checks if testA is in interval (lowerA,upperA); if at edges, checks if testB is in interval (lowerB,upperB).
function inInterval = orderedComparison(lowerA, lowerB, upperA, upperB, testA, testB)
if (testA < lowerA || testA > upperA)
inInterval = false;
else
inInterval = true;
if (testA == lowerA)
inInterval = inInterval && (testB >= lowerB);
end
if (testA == upperA)
inInterval = inInterval && (testB <= upperB);
end
end
end % function
|
github
|
lcnhappe/happe-master
|
ft_warning.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/private/ft_warning.m
| 7,789 |
utf_8
|
d832a7ad5e2f9bb42995e6e5d4caa198
|
function [ws, warned] = ft_warning(varargin)
% FT_WARNING will throw a warning for every unique point in the
% stacktrace only, e.g. in a for-loop a warning is thrown only once.
%
% Use as one of the following
% ft_warning(string)
% ft_warning(id, string)
% Alternatively, you can use ft_warning using a timeout
% ft_warning(string, timeout)
% ft_warning(id, string, timeout)
% where timeout should be inf if you don't want to see the warning ever
% again.
%
% Use as ft_warning('-clear') to clear old warnings from the current
% stack
%
% It can be used instead of the MATLAB built-in function WARNING, thus as
% s = ft_warning(...)
% or as
% ft_warning(s)
% where s is a structure with fields 'identifier' and 'state', storing the
% state information. In other words, ft_warning accepts as an input the
% same structure it returns as an output. This returns or restores the
% states of warnings to their previous values.
%
% It can also be used as
% [s w] = ft_warning(...)
% where w is a boolean that indicates whether a warning as been thrown or not.
%
% Please note that you can NOT use it like this
% ft_warning('the value is %d', 10)
% instead you should do
% ft_warning(sprintf('the value is %d', 10))
% Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% 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$
global ft_default
warned = false;
ws = [];
stack = dbstack;
if any(strcmp({stack(2:end).file}, 'ft_warning.m'))
% don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068
return;
end
if nargin < 1
error('You need to specify at least a warning message');
end
if isstruct(varargin{1})
warning(varargin{1});
return;
end
if ~isfield(ft_default, 'warning')
ft_default.warning = [];
end
if ~isfield(ft_default.warning, 'stopwatch')
ft_default.warning.stopwatch = [];
end
if ~isfield(ft_default.warning, 'identifier')
ft_default.warning.identifier = [];
end
if ~isfield(ft_default.warning, 'ignore')
ft_default.warning.ignore = {};
end
% put the arguments we will pass to warning() in this cell array
warningArgs = {};
if nargin==3
% calling syntax (id, msg, timeout)
warningArgs = varargin(1:2);
msg = warningArgs{2};
timeout = varargin{3};
fname = [warningArgs{1} '_' warningArgs{2}];
elseif nargin==2 && isnumeric(varargin{2})
% calling syntax (msg, timeout)
warningArgs = varargin(1);
msg = warningArgs{1};
timeout = varargin{2};
fname = warningArgs{1};
elseif nargin==2 && isequal(varargin{1}, 'off')
ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2});
return
elseif nargin==2 && isequal(varargin{1}, 'on')
ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2});
return
elseif nargin==2 && ~isnumeric(varargin{2})
% calling syntax (id, msg)
warningArgs = varargin(1:2);
msg = warningArgs{2};
timeout = inf;
fname = [warningArgs{1} '_' warningArgs{2}];
elseif nargin==1
% calling syntax (msg)
warningArgs = varargin(1);
msg = warningArgs{1};
timeout = inf; % default timeout in seconds
fname = [warningArgs{1}];
end
if ismember(msg, ft_default.warning.ignore)
% do not show this warning
return;
end
if isempty(timeout)
error('Timeout ill-specified');
end
if timeout ~= inf
fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures
line = [];
else
% here, we create the fieldname functionA.functionB.functionC...
[tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier);
if ~isempty(tmpfname),
fname = tmpfname;
clear tmpfname;
end
end
if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1})
if strcmp(fname, '-clear') % reset all fields if called outside a function
ft_default.warning.identifier = [];
ft_default.warning.stopwatch = [];
else
if issubfield(ft_default.warning.identifier, fname)
ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname);
end
end
return;
end
% and add the line number to make this unique for the last function
fname = horzcat(fname, line);
if ~issubfield('ft_default.warning.stopwatch', fname)
ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic);
end
now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call
if ~issubfield(ft_default.warning.identifier, fname) || ...
(issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout']))
% create or reset field
ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []);
% warning never given before or timed out
ws = warning(warningArgs{:});
ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout);
ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg);
warned = true;
else
% the warning has been issued before, but has not timed out yet
ws = getsubfield(ft_default.warning.identifier, [fname '.ws']);
end
end % function ft_warning
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings)
% stack(1) is this function, stack(2) is ft_warning
stack = dbstack('-completenames');
if size(stack) < 3
fname = [];
line = [];
return;
end
i0 = 3;
% ignore ft_preamble
while strfind(stack(i0).name, 'ft_preamble')
i0=i0+1;
end
fname = horzcat(fixname(stack(end).name));
if ~issubfield(ft_previous_warnings, fixname(stack(end).name))
ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields
end
for i=numel(stack)-1:-1:(i0)
% skip postamble scripts
if strncmp(stack(i).name, 'ft_postamble', 12)
break;
end
fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file
if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields
setsubfield(ft_previous_warnings, fname, []);
end
end
% line of last function call
line = ['.line', int2str(stack(i0).line)];
end
% function outcome = issubfield(strct, fname)
% substrindx = strfind(fname, '.');
% if numel(substrindx) > 0
% % separate the last fieldname from all former
% outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']);
% else
% % there is only one fieldname
% outcome = isfield(strct, fname);
% end
% end
% function strct = rmsubfield(strct, fname)
% substrindx = strfind(fname, '.');
% if numel(substrindx) > 0
% % separate the last fieldname from all former
% strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']);
% else
% % there is only one fieldname
% strct = rmfield(strct, fname);
% end
% end
|
github
|
lcnhappe/happe-master
|
benchmark.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/private/benchmark.m
| 3,925 |
utf_8
|
c57855145ed5e0e6dcce46f2eac7ad03
|
function benchmark(funname, argname, argval, m_array, n_array, niter, varargin)
% BENCHMARK a given function
%
% Use as
% benchmark(funname, argname, argval, m_array, n_array, niter, ...)
%
% Optional input arguments should come in key-value pairs and may include
% feedback = none, figure, text, table, all
% tableheader = true, false
% tabledata = true, false
% selection = 3x2 array with nchans and nsamples to be used for the table
% Copyright (C) 2009, Robert Oostenveld
%
% Subversion does not use the Log keyword, use 'svn log <filename>' or 'svn -v log | less' to get detailled information
% get the optional input arguments
feedback = keyval('feedback', varargin); % none, figure, text, table, all
tableheader = keyval('tableheader', varargin); % true, false
tabledata = keyval('tabledata', varargin); % true, false
selection = keyval('selection', varargin); % 3x2 array with nchans and nsamples to be used for the table
% set the defaults
if isempty(feedback)
feedback = 'all';
end
if isempty(tableheader)
tableheader = true;
end
if isempty(tabledata)
tabledata = true;
end
if isempty(selection)
selection = [
8 100
8 500
64 500
];
end
% convert the function from a string to a handle
funhandle = str2func(funname);
% this will hold the time that all computations took
t_array = nan(length(m_array), length(n_array));
% do the actual benchmarking
for m_indx=1:length(m_array)
for n_indx=1:length(n_array)
m = m_array(m_indx);
n = n_array(n_indx);
if strcmp(feedback, 'table')
if ~any(selection(:,1)==m & selection(:,2)==n)
continue
end
end
% create some random data
dat = randn(m, n);
elapsed = zeros(1,niter);
for iteration=1:niter
tic;
funhandle(dat, argval{:});
elapsed(iteration) = toc*1000; % convert from s into ms
end
% remember the amount of time spent on the computation for this M and N
t_array(m_indx, n_indx) = robustmean(elapsed);
% give some feedback on screen
if strcmp(feedback, 'text') || strcmp(feedback, 'all')
fprintf('nchans = %d, nsamples = %d, time = %f ms\n', m, n, t_array(m_indx, n_indx));
end
end
end
if strcmp(feedback, 'figure') || strcmp(feedback, 'all')
% give some output in a figure
figure
surf(n_array, m_array, t_array);
end
if strcmp(feedback, 'table') || strcmp(feedback, 'all')
% give some output to screen that can be copied and pasted into the wiki
m1 = find(m_array==selection(1,1)); % channels
n1 = find(n_array==selection(1,2)); % samples
m2 = find(m_array==selection(2,1)); % channels
n2 = find(n_array==selection(2,2)); % samples
m3 = find(m_array==selection(3,1)); % channels
n3 = find(n_array==selection(3,2)); % samples
if tableheader
fprintf('^function name and algorithm details ^ %dch x %dsmp ^ %dch x %dsmp ^ %dch x %dsmp ^\n', ...
m_array(m1), n_array(n1), ...
m_array(m2), n_array(n2), ...
m_array(m3), n_array(n3));
end
if tabledata
str = [];
dum = sprintf('%s;\n', funname);
str = cat(2, str, dum);
for i=1:length(argval)
dum = printstruct(argname{i}, argval{i});
str = cat(2, str, dum);
end
str(str==10) = ' ';
fprintf('|%s | %.2f ms | %.2f ms | %.2f ms |\n', str, ...
t_array(m1, n1), ...
t_array(m2, n2), ...
t_array(m3, n3));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for robust estimation of mean, removing outliers on both sides
% select the central part of the sorted vector, a quarter of the values is removed from both sides
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = robustmean(x)
x = sort(x);
n = length(x);
trim = round(0.25*n);
sel = (trim+1):(n-trim);
y = mean(x(sel));
|
github
|
lcnhappe/happe-master
|
identical.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/private/identical.m
| 6,335 |
utf_8
|
75a144da8012630d9a34dca990228677
|
function [ok, message] = identical2(a, b, varargin)
% IDENTICAL compares two input variables and returns 1/0
% and a message containing the details on the observed difference.
%
% Use as
% [ok, message] = identical(a, b)
% [ok, message] = identical(a, b, ...)
%
% This works for all possible input variables a and b, like
% numerical arrays, string arrays, cell arrays, structures
% and nested data types.
%
% Optional input arguments come in key-value pairs, supported are
% 'depth' number, for nested structures
% 'abstol' number, absolute tolerance for numerical comparison
% 'reltol' number, relative tolerance for numerical comparison
% 'diffabs' boolean, check difference between absolute values for
% numericals (useful for e.g. mixing matrices which have
% arbitrary signs)
% Copyright (C) 2004-2012, Robert Oostenveld & Markus Siegel
%
% $Id$
if nargin==3
% for backward compatibility
depth = varargin{1};
else
depth = keyval('depth', varargin);
if isempty(depth)
% set the default
depth = inf;
end
end
message = {};
location = '';
[message] = do_work(a, b, depth, location, message, varargin{:});
message = message(:);
ok = isempty(message);
if ~nargout
disp(message);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [message] = do_work(a, b, depth, location, message, varargin)
knowntypes = {
'double' % Double precision floating point numeric array
'logical' % Logical array
'char' % Character array
'cell' % Cell array
'struct' % Structure array
'numeric' % Integer or floating-point array
'single' % Single precision floating-point numeric array
'int8' % 8-bit signed integer array
'uint8' % 8-bit unsigned integer array
'int16' % 16-bit signed integer array
'uint16' % 16-bit unsigned integer array
'int32' % 32-bit signed integer array
'uint32' % 32-bit unsigned integer array
};
for type=knowntypes(:)'
if isa(a, type{:}) && ~isa(b, type{:})
message{end+1} = sprintf('different data type in %s', location);
return
end
end
if isempty(location)
location = 'array';
end
if isa(a, 'numeric') || isa(a, 'char') || isa(a, 'logical')
% perform numerical comparison
if length(size(a))~=length(size(b))
message{end+1} = sprintf('different number of dimensions in %s', location);
return;
end
if any(size(a)~=size(b))
message{end+1} = sprintf('different size in %s', location);
return;
end
if ~all(isnan(a(:)) == isnan(b(:)))
message{end+1} = sprintf('different occurence of NaNs in %s', location);
return;
end
% replace the NaNs, since we cannot compare them numerically
a = a(~isnan(a(:)));
b = b(~isnan(b(:)));
% continue with numerical comparison
if ischar(a) && any(a~=b)
message{end+1} = sprintf('different string in %s: %s ~= %s', location, a, b);
else
% use the desired tolerance
reltol = keyval('reltol', varargin{:}); % any value, relative to the mean
abstol = keyval('abstol', varargin{:}); % any value
relnormtol = keyval('relnormtol', varargin{:}); % the matrix norm, relative to the mean norm
absnormtol = keyval('absnormtol', varargin{:}); % the matrix norm
diffabs = keyval('diffabs', varargin{:});
if ~isempty(diffabs) && diffabs
a = abs(a);
b = abs(b);
end
if ~isempty(abstol) && any(abs(a-b)>abstol)
message{end+1} = sprintf('different values in %s', location);
elseif ~isempty(reltol) && any((abs(a-b)./(0.5*(a+b)))>reltol)
message{end+1} = sprintf('different values in %s', location);
elseif isempty(abstol) && isempty(reltol) && any(a~=b)
message{end+1} = sprintf('different values in %s', location);
elseif ~isempty(relnormtol) && (norm(a-b)/(0.5*(norm(a)+norm(b)))>relnormtol)
message{end+1} = sprintf('different values in %s', location);
elseif ~isempty(absnormtol) && norm(a-b)>absnormtol
message{end+1} = sprintf('different values in %s', location);
end
end
elseif isa(a, 'struct') && all(size(a)==1)
% perform recursive comparison of all fields of the structure
fna = fieldnames(a);
fnb = fieldnames(b);
if ~all(ismember(fna, fnb))
tmp = fna(~ismember(fna, fnb));
for i=1:length(tmp)
message{end+1} = sprintf('field missing in the 2nd argument in %s: {%s}', location, tmp{i});
end
end
if ~all(ismember(fnb, fna))
tmp = fnb(~ismember(fnb, fna));
for i=1:length(tmp)
message{end+1} = sprintf('field missing in the 1st argument in %s: {%s}', location, tmp{i});
end
end
fna = intersect(fna, fnb);
if depth>0
% warning, this is a recursive call to transverse nested structures
for i=1:length(fna)
fn = fna{i};
ra = getfield(a, fn);
rb = getfield(b, fn);
[message] = do_work(ra, rb, depth-1, [location '.' fn], message, varargin{:});
end
end
elseif isa(a, 'struct') && ~all(size(a)==1)
% perform recursive comparison of all array elements
if any(size(a)~=size(b))
message{end+1} = sprintf('different size of struct-array in %s', location);
return;
end
siz = size(a);
dim = ndims(a);
a = a(:);
b = b(:);
for i=1:length(a)
ra = a(i);
rb = b(i);
tmp = sprintf('%s(%s)', location, my_ind2sub(siz, i));
[message] = do_work(ra, rb, depth-1, tmp, message, varargin{:});
end
elseif isa(a, 'cell')
% perform recursive comparison of all array elements
if any(size(a)~=size(b))
message{end+1} = sprintf('different size of cell-array in %s', location);
return;
end
siz = size(a);
dim = ndims(a);
a = a(:);
b = b(:);
for i=1:length(a)
ra = a{i};
rb = b{i};
tmp = sprintf('%s{%s}', location, my_ind2sub(siz, i));
[message] = do_work(ra, rb, depth-1, tmp, message, varargin{:});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% return a string with the formatted subscript
function [str] = my_ind2sub(siz,ndx)
n = length(siz);
k = [1 cumprod(siz(1:end-1))];
ndx = ndx - 1;
for i = n:-1:1,
tmp(i) = floor(ndx/k(i))+1;
ndx = rem(ndx,k(i));
end
str = '';
for i=1:n
str = [str ',' num2str(tmp(i))];
end
str = str(2:end);
|
github
|
lcnhappe/happe-master
|
getdimsiz.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/private/getdimsiz.m
| 2,235 |
utf_8
|
340d495a654f2f6752aa1af7ac915390
|
function dimsiz = getdimsiz(data, field)
% GETDIMSIZ
%
% Use as
% dimsiz = getdimsiz(data, field)
%
% If the length of the vector that is returned is smaller than the
% number of dimensions that you would expect from GETDIMORD, you
% should assume that it has trailing singleton dimensions.
%
% Example use
% dimord = getdimord(datastructure, fieldname);
% dimtok = tokenize(dimord, '_');
% dimsiz = getdimsiz(datastructure, fieldname);
% dimsiz(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions
%
% See also GETDIMORD, GETDATFIELD
if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field)
field = ['avg.' field];
elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field)
field = ['trial.' field];
elseif ~isfield(data, field)
error('field "%s" not present in data', field);
end
if strncmp(field, 'avg.', 4)
prefix = [];
field = field(5:end); % strip the avg
data.(field) = data.avg.(field); % move the avg into the main structure
data = rmfield(data, 'avg');
elseif strncmp(field, 'trial.', 6)
prefix = numel(data.trial);
field = field(7:end); % strip the trial
data.(field) = data.trial(1).(field); % move the first trial into the main structure
data = rmfield(data, 'trial');
else
prefix = [];
end
dimsiz = cellmatsize(data.(field));
% add nrpt in case of source.trial
dimsiz = [prefix dimsiz];
end % main function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to determine the size of data representations like {pos}_ori_time
% FIXME this will fail for {xxx_yyy}_zzz
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function siz = cellmatsize(x)
if iscell(x)
if isempty(x)
siz = 0;
return % nothing else to do
elseif isvector(x)
cellsize = numel(x); % the number of elements in the cell-array
else
cellsize = size(x);
x = x(:); % convert to vector for further size detection
end
[dum, indx] = max(cellfun(@numel, x));
matsize = size(x{indx}); % the size of the content of the cell-array
siz = [cellsize matsize]; % concatenate the two
else
siz = size(x);
end
end % function cellmatsize
|
github
|
lcnhappe/happe-master
|
hcp_filelist.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/test/private/hcp_filelist.m
| 447 |
utf_8
|
71aed91ab0ef231e13aba8c62e7b1661
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function list = hcp_filelist(basedir)
dirlist = hcp_dirlist(basedir, true);
dirlist{end+1} = basedir;
list = {};
for i=1:length(dirlist)
f = dir(dirlist{i});
f = f(~[f.isdir]);
f = {f.name};
for j=1:length(f)
f{j} = fullfile(dirlist{i}, f{j});
end
list = cat(1, list, f(:));
end
list = sort(list);
|
github
|
lcnhappe/happe-master
|
beamformer_pcc.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/inverse/beamformer_pcc.m
| 13,262 |
utf_8
|
c6189828cfd87b980fb6d6c6f69ae63d
|
function [dipout] = beamformer_pcc(dip, grad, headmodel, dat, Cf, varargin)
% BEAMFORMER_PCC implements an experimental beamformer based on partial
% canonical correlations or coherences. Dipole locations that are outside
% the head will return a NaN value.
%
% Use as
% [dipout] = beamformer_pcc(dipin, grad, headmodel, dat, cov, ...)
% where
% dipin is the input dipole model
% grad is the gradiometer definition
% headmodel is the volume conductor definition
% dat is the data matrix with the ERP or ERF
% cov is the data covariance or cross-spectral density matrix
% and
% dipout is the resulting dipole model with all details
%
% The input dipole model consists of
% dipin.pos positions for dipole, e.g. regular grid, Npositions x 3
% dipin.mom dipole orientation (optional), 3 x Npositions
% and can additionally contain things like a precomputed filter.
%
% Additional options should be specified in key-value pairs and can be
% refchan
% refdip
% supchan
% supdip
% reducerank
% normalize
% normalizeparam
% feedback
% keepcsd
% keepfilter
% keepleadfield
% keepmom
% lambda
% projectnoise
% realfilter
% fixedori
% Copyright (C) 2005-2014, Robert Oostenveld & Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% 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$
if mod(nargin-5,2)
% the first 5 arguments are fixed, the other arguments should come in pairs
error('invalid number of optional arguments');
end
% these optional settings do not have defaults
refchan = ft_getopt(varargin, 'refchan', []);
refdip = ft_getopt(varargin, 'refdip', []);
supchan = ft_getopt(varargin, 'supchan', []);
supdip = ft_getopt(varargin, 'supdip', []);
% these settings pertain to the forward model, the defaults are set in compute_leadfield
reducerank = ft_getopt(varargin, 'reducerank', []);
normalize = ft_getopt(varargin, 'normalize', []);
normalizeparam = ft_getopt(varargin, 'normalizeparam', []);
% these optional settings have defaults
feedback = ft_getopt(varargin, 'feedback', 'text');
keepcsd = ft_getopt(varargin, 'keepcsd', 'no');
keepfilter = ft_getopt(varargin, 'keepfilter', 'no');
keepleadfield = ft_getopt(varargin, 'keepleadfield', 'no');
keepmom = ft_getopt(varargin, 'keepmom', 'yes');
lambda = ft_getopt(varargin, 'lambda', 0);
projectnoise = ft_getopt(varargin, 'projectnoise', 'yes');
realfilter = ft_getopt(varargin, 'realfilter', 'yes');
fixedori = ft_getopt(varargin, 'fixedori', 'no');
% convert the yes/no arguments to the corresponding logical values
fixedori = strcmp(fixedori, 'yes');
keepcsd = strcmp(keepcsd, 'yes'); % see below
keepfilter = strcmp(keepfilter, 'yes');
keepleadfield = strcmp(keepleadfield, 'yes');
keepmom = strcmp(keepmom, 'yes');
projectnoise = strcmp(projectnoise, 'yes');
realfilter = strcmp(realfilter, 'yes');
% the postprocessing of the pcc beamformer always requires the csd matrix
keepcsd = 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% find the dipole positions that are inside/outside the brain
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(dip, 'inside')
dip.inside = ft_inside_vol(dip.pos, headmodel);
end
if any(dip.inside>1)
% convert to logical representation
tmp = false(size(dip.pos,1),1);
tmp(dip.inside) = true;
dip.inside = tmp;
end
% keep the original details on inside and outside positions
originside = dip.inside;
origpos = dip.pos;
% select only the dipole positions inside the brain for scanning
dip.pos = dip.pos(originside,:);
dip.inside = true(size(dip.pos,1),1);
if isfield(dip, 'mom')
dip.mom = dip.mom(:, originside);
end
needleadfield = 1;
if isfield(dip, 'leadfield')
fprintf('using precomputed leadfields\n');
dip.leadfield = dip.leadfield(originside);
end
if isfield(dip, 'filter')
fprintf('using precomputed filters\n');
dip.filter = dip.filter(originside);
needleadfield = 0;
end
if ~isempty(refdip)
rf = ft_compute_leadfield(refdip, grad, headmodel, 'reducerank', reducerank, 'normalize', normalize);
else
rf = [];
end
if ~isempty(supdip)
sf = ft_compute_leadfield(supdip, grad, headmodel, 'reducerank', reducerank, 'normalize', normalize);
else
sf = [];
end
% sanity check
if (~isempty(rf) || ~isempty(sf)) && isfield(dip, 'filter')
error('precomputed filters cannot be used in combination with a refdip or supdip')
end
refchan = refchan; % these can be passed as optional inputs
supchan = supchan; % these can be passed as optional inputs
megchan = setdiff(1:size(Cf,1), [refchan supchan]);
Nrefchan = length(refchan);
Nsupchan = length(supchan);
Nmegchan = length(megchan);
Nchan = size(Cf,1); % should equal Nmegchan + Nrefchan + Nsupchan
Cmeg = Cf(megchan,megchan); % the filter uses the csd between all MEG channels
isrankdeficient = (rank(Cmeg)<size(Cmeg,1));
% it is difficult to give a quantitative estimate of lambda, therefore also
% support relative (percentage) measure that can be specified as string (e.g. '10%')
if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%'
ratio = sscanf(lambda, '%f%%');
ratio = ratio/100;
lambda = ratio * trace(Cmeg)/size(Cmeg,1);
end
if projectnoise
% estimate the noise power, which is further assumed to be equal and uncorrelated over channels
if isrankdeficient
% estimated noise floor is equal to or higher than lambda
noise = lambda;
else
% estimate the noise level in the covariance matrix by the smallest singular value
noise = svd(Cmeg);
noise = noise(end);
% estimated noise floor is equal to or higher than lambda
noise = max(noise, lambda);
end
end
if realfilter
% construct the filter only on the real part of the CSD matrix, i.e. filter is real
invCmeg = pinv(real(Cmeg) + lambda*eye(Nmegchan));
else
% construct the filter on the complex CSD matrix, i.e. filter contains imaginary component as well
% this results in a phase rotation of the channel data if the filter is applied to the data
invCmeg = pinv(Cmeg + lambda*eye(Nmegchan));
end
% start the scanning with the proper metric
ft_progress('init', feedback, 'beaming sources');
for i=1:size(dip.pos,1)
if needleadfield
if isfield(dip, 'leadfield') && isfield(dip, 'mom') && size(dip.mom, 1)==size(dip.leadfield{i}, 2)
% reuse the leadfield that was previously computed and project
lf = dip.leadfield{i} * dip.mom(:,i);
elseif isfield(dip, 'leadfield') && isfield(dip, 'mom')
% reuse the leadfield that was previously computed but don't project
lf = dip.leadfield{i};
elseif isfield(dip, 'leadfield') && ~isfield(dip, 'mom'),
% reuse the leadfield that was previously computed
lf = dip.leadfield{i};
elseif ~isfield(dip, 'leadfield') && isfield(dip, 'mom')
% compute the leadfield for a fixed dipole orientation
lf = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam) * dip.mom(:,i);
else
% compute the leadfield
lf = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam);
end
% concatenate scandip, refdip and supdip
lfa = [lf rf sf];
Ndip = size(lfa,2);
else
Ndip = size(dip.filter{i},1);
end
if fixedori
if isempty(refdip) && isempty(supdip) && isempty(refchan) && isempty(supchan)
% compute the leadfield for the optimal dipole orientation
% subsequently the leadfield for only that dipole orientation will
% be used for the final filter computation
if isfield(dip, 'filter') && size(dip.filter{i},1)==1
% nothing to do
ft_warning('Ignoring ''fixedori''. The fixedori option is supported only if there is ONE dipole for location.')
else
if isfield(dip, 'filter') && size(dip.filter{i},1)~=1
filt = dip.filter{i};
else
filt = pinv(lfa' * invCmeg * lfa) * lfa' * invCmeg;
end
[u, s, v] = svd(real(filt * Cmeg * ctranspose(filt)));
maxpowori = u(:,1);
if numel(s)>1,
eta = s(1,1)./s(2,2);
else
eta = nan;
end
lfa = lfa * maxpowori;
dipout.ori{i} = maxpowori;
dipout.eta(i) = eta;
% update the number of dipole components
Ndip = size(lfa,2);
end
else
ft_warning('Ignoring ''fixedori''. The fixedori option is supported only if there is ONE dipole for location.')
end
end
if isfield(dip, 'filter')
% use the provided filter
filt = dip.filter{i};
else
% construct the spatial filter
filt = pinv(lfa' * invCmeg * lfa) * lfa' * invCmeg; % use PINV/SVD to cover rank deficient leadfield
end
% concatenate the source filters with the channel filters
filtn = zeros(Ndip+Nrefchan+Nsupchan, Nmegchan+Nrefchan+Nsupchan);
% this part of the filter relates to the sources
filtn(1:Ndip,megchan) = filt;
% this part of the filter relates to the channels
filtn((Ndip+1):end,setdiff(1:(Nmegchan+Nrefchan+Nsupchan), megchan)) = eye(Nrefchan+Nsupchan);
filt = filtn;
clear filtn
if keepcsd
dipout.csd{i,1} = filt * Cf * ctranspose(filt);
end
if projectnoise
dipout.noisecsd{i,1} = noise * (filt * ctranspose(filt));
end
if keepmom && ~isempty(dat)
dipout.mom{i,1} = filt * dat;
end
if keepfilter
dipout.filter{i,1} = filt;
end
if keepleadfield && needleadfield
dipout.leadfield{i,1} = lf;
end
ft_progress(i/size(dip.pos,1), 'beaming source %d from %d\n', i, size(dip.pos,1));
% remember how all components in the output csd should be interpreted
%scandiplabel = repmat({'scandip'}, 1, size(lf, 2)); % based on last leadfield
scandiplabel = repmat({'scandip'}, 1, size(filt, 1)-size(rf, 2)-size(sf, 2)-Nrefchan-Nsupchan); % robust if lf does not exist
refdiplabel = repmat({'refdip'}, 1, size(rf, 2));
supdiplabel = repmat({'supdip'}, 1, size(sf, 2));
refchanlabel = repmat({'refchan'}, 1, Nrefchan);
supchanlabel = repmat({'supchan'}, 1, Nsupchan);
% concatenate all the labels
dipout.csdlabel{i,1} = [scandiplabel refdiplabel supdiplabel refchanlabel supchanlabel];
end % for all dipoles
ft_progress('close');
% wrap it all up, prepare the complete output
dipout.inside = originside;
dipout.pos = origpos;
% reassign the scan values over the inside and outside grid positions
if isfield(dipout, 'leadfield')
dipout.leadfield( originside) = dipout.leadfield;
dipout.leadfield(~originside) = {[]};
end
if isfield(dipout, 'filter')
dipout.filter( originside) = dipout.filter;
dipout.filter(~originside) = {[]};
end
if isfield(dipout, 'mom')
dipout.mom( originside) = dipout.mom;
dipout.mom(~originside) = {[]};
end
if isfield(dipout, 'csd')
dipout.csd( originside) = dipout.csd;
dipout.csd(~originside) = {[]};
end
if isfield(dipout, 'noisecsd')
dipout.noisecsd( originside) = dipout.noisecsd;
dipout.noisecsd(~originside) = {[]};
end
if isfield(dipout, 'csdlabel')
dipout.csdlabel( originside) = dipout.csdlabel;
dipout.csdlabel(~originside) = {[]};
end
if isfield(dipout, 'ori')
dipout.ori( originside) = dipout.ori;
dipout.ori(~originside) = {[]};
end
if isfield(dipout, 'eta')
dipout.eta( originside) = dipout.eta;
dipout.eta(~originside) = nan;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute the pseudo inverse. This is the same as the
% standard MATLAB function, except that the default tolerance is twice as
% high.
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision$ $Date: 2009/01/07 13:12:03 $
% default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = pinv(A,varargin)
[m,n] = size(A);
if n > m
X = pinv(A',varargin{:})';
else
[U,S,V] = svd(A,0);
if m > 1, s = diag(S);
elseif m == 1, s = S(1);
else s = 0;
end
if nargin == 2
tol = varargin{1};
else
tol = 10 * max(m,n) * max(s) * eps;
end
r = sum(s > tol);
if (r == 0)
X = zeros(size(A'),class(A));
else
s = diag(ones(r,1)./s(1:r));
X = V(:,1:r)*s*U(:,1:r)';
end
end
|
github
|
lcnhappe/happe-master
|
beamformer_dics.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/inverse/beamformer_dics.m
| 26,041 |
utf_8
|
d4c1f578b6725dbeb67c9a09c2ae2dd0
|
function [dipout] = beamformer_dics(dip, grad, headmodel, dat, Cf, varargin)
% BEAMFORMER_DICS scans on pre-defined dipole locations with a single dipole
% and returns the beamformer spatial filter output for a dipole on every
% location. Dipole locations that are outside the head will return a
% NaN value.
%
% Use as
% [dipout] = beamformer_dics(dipin, grad, headmodel, dat, cov, varargin)
% where
% dipin is the input dipole model
% grad is the gradiometer definition
% headmodel is the volume conductor definition
% dat is the data matrix with the ERP or ERF
% cov is the data covariance or cross-spectral density matrix
% and
% dipout is the resulting dipole model with all details
%
% The input dipole model consists of
% dipin.pos positions for dipole, e.g. regular grid, Npositions x 3
% dipin.mom dipole orientation (optional), 3 x Npositions
% and can additionally contain things like a precomputed filter.
%
% Additional options should be specified in key-value pairs and can be
% 'Pr' = power of the external reference channel
% 'Cr' = cross spectral density between all data channels and the external reference channel
% 'refdip' = location of dipole with which coherence is computed
% 'lambda' = regularisation parameter
% 'powmethod' = can be 'trace' or 'lambda1'
% 'feedback' = give ft_progress indication, can be 'text', 'gui' or 'none'
% 'fixedori' = use fixed or free orientation, can be 'yes' or 'no'
% 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no'
% 'realfilter' = construct a real-valued filter, can be 'yes' or 'no'
% 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no'
% 'keepleadfield' = remember the forward computation, can be 'yes' or 'no'
% 'keepcsd' = remember the estimated cross-spectral density, can be 'yes' or 'no'
%
% These options influence the forward computation of the leadfield
% 'reducerank' = reduce the leadfield rank, can be 'no' or a number (e.g. 2)
% 'normalize' = normalize the leadfield
% 'normalizeparam' = parameter for depth normalization (default = 0.5)
%
% If the dipole definition only specifies the dipole location, a rotating
% dipole (regional source) is assumed on each location. If a dipole moment
% is specified, its orientation will be used and only the strength will
% be fitted to the data.
% Copyright (C) 2003-2008, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% 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$
if mod(nargin-5,2)
% the first 5 arguments are fixed, the other arguments should come in pairs
error('invalid number of optional arguments');
end
% these optional settings do not have defaults
Pr = ft_getopt(varargin, 'Pr');
Cr = ft_getopt(varargin, 'Cr');
refdip = ft_getopt(varargin, 'refdip');
powmethod = ft_getopt(varargin, 'powmethod'); % the default for this is set below
realfilter = ft_getopt(varargin, 'realfilter'); % the default for this is set below
subspace = ft_getopt(varargin, 'subspace');
% these settings pertain to the forward model, the defaults are set in compute_leadfield
reducerank = ft_getopt(varargin, 'reducerank');
normalize = ft_getopt(varargin, 'normalize');
normalizeparam = ft_getopt(varargin, 'normalizeparam');
% these optional settings have defaults
feedback = ft_getopt(varargin, 'feedback', 'text');
keepcsd = ft_getopt(varargin, 'keepcsd', 'no');
keepfilter = ft_getopt(varargin, 'keepfilter', 'no');
keepleadfield = ft_getopt(varargin, 'keepleadfield', 'no');
lambda = ft_getopt(varargin, 'lambda', 0);
projectnoise = ft_getopt(varargin, 'projectnoise', 'yes');
fixedori = ft_getopt(varargin, 'fixedori', 'no');
% convert the yes/no arguments to the corresponding logical values
keepcsd = strcmp(keepcsd, 'yes');
keepfilter = strcmp(keepfilter, 'yes');
keepleadfield = strcmp(keepleadfield, 'yes');
projectnoise = strcmp(projectnoise, 'yes');
fixedori = strcmp(fixedori, 'yes');
dofeedback = ~strcmp(feedback, 'none');
% FIXME besides regular/complex lambda1, also implement a real version
% default is to use the largest singular value of the csd matrix, see Gross 2001
if isempty(powmethod)
powmethod = 'lambda1';
end
% default is to be consistent with the original description of DICS in Gross 2001
if isempty(realfilter)
realfilter = 'no';
end
% use these two logical flags instead of doing the string comparisons each time again
powtrace = strcmp(powmethod, 'trace');
powlambda1 = strcmp(powmethod, 'lambda1');
if ~isempty(Cr)
% ensure that the cross-spectral density with the reference signal is a column matrix
Cr = Cr(:);
end
if isfield(dip, 'mom') && fixedori
error('you cannot specify a dipole orientation and fixedmom simultaneously');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% find the dipole positions that are inside/outside the brain
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(dip, 'inside')
dip.inside = ft_inside_vol(dip.pos, headmodel);
end
if any(dip.inside>1)
% convert to logical representation
tmp = false(size(dip.pos,1),1);
tmp(dip.inside) = true;
dip.inside = tmp;
end
% keep the original details on inside and outside positions
originside = dip.inside;
origpos = dip.pos;
% flags to avoid calling isfield repeatedly in the loop over grid positions (saves a lot of time)
hasmom = false;
hasleadfield = false;
hasfilter = false;
hassubspace = false;
% select only the dipole positions inside the brain for scanning
dip.pos = dip.pos(originside,:);
dip.inside = true(size(dip.pos,1),1);
if isfield(dip, 'mom')
hasmom = 1;
dip.mom = dip.mom(:,originside);
end
if isfield(dip, 'leadfield')
hasleadfield = 1;
if dofeedback
fprintf('using precomputed leadfields\n');
end
dip.leadfield = dip.leadfield(originside);
end
if isfield(dip, 'filter')
hasfilter = 1;
if dofeedback
fprintf('using precomputed filters\n');
end
dip.filter = dip.filter(originside);
end
if isfield(dip, 'subspace')
hassubspace = 1;
if dofeedback
fprintf('using subspace projection\n');
end
dip.subspace = dip.subspace(originside);
end
% dics has the following sub-methods, which depend on the function input arguments
% power only, cortico-muscular coherence and cortico-cortical coherence
if ~isempty(Cr) && ~isempty(Pr) && isempty(refdip)
% compute cortico-muscular coherence, using reference cross spectral density
submethod = 'dics_refchan';
elseif isempty(Cr) && isempty(Pr) && ~isempty(refdip)
% compute cortico-cortical coherence with a dipole at the reference position
submethod = 'dics_refdip';
elseif isempty(Cr) && isempty(Pr) && isempty(refdip)
% only compute power of a dipole at the grid positions
submethod = 'dics_power';
else
error('invalid combination of input arguments for dics');
end
isrankdeficient = (rank(Cf)<size(Cf,1));
% it is difficult to give a quantitative estimate of lambda, therefore also
% support relative (percentage) measure that can be specified as string (e.g. '10%')
if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%'
ratio = sscanf(lambda, '%f%%');
ratio = ratio/100;
lambda = ratio * trace(Cf)/size(Cf,1);
end
if projectnoise
% estimate the noise power, which is further assumed to be equal and uncorrelated over channels
if isrankdeficient
% estimated noise floor is equal to or higher than lambda
noise = lambda;
else
% estimate the noise level in the covariance matrix by the smallest singular value
noise = svd(Cf);
noise = noise(end);
% estimated noise floor is equal to or higher than lambda
noise = max(noise, lambda);
end
end
% the inverse only has to be computed once for all dipoles
if strcmp(realfilter, 'yes')
% the filter is computed using only the leadfield and the inverse covariance or CSD matrix
% therefore using the real-valued part of the CSD matrix here ensures a real-valued filter
invCf = pinv(real(Cf) + lambda * eye(size(Cf)));
else
invCf = pinv(Cf + lambda * eye(size(Cf)));
end
if hassubspace
if dofeedback
fprintf('using source-specific subspace projection\n');
end
% remember the original data prior to the voxel dependent subspace projection
dat_pre_subspace = dat;
Cf_pre_subspace = Cf;
if strcmp(submethod, 'dics_refchan')
Cr_pre_subspace = Cr;
Pr_pre_subspace = Pr;
end
elseif ~isempty(subspace)
if dofeedback
fprintf('using data-specific subspace projection\n');
end
% TODO implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM
if numel(subspace)==1,
% interpret this as a truncation of the eigenvalue-spectrum
% if <1 it is a fraction of the largest eigenvalue
% if >=1 it is the number of largest eigenvalues
dat_pre_subspace = dat;
Cf_pre_subspace = Cf;
[u, s, v] = svd(real(Cf));
if subspace<1,
sel = find(diag(s)./s(1,1) > subspace);
subspace = max(sel);
end
Cf = s(1:subspace,1:subspace);
% this is equivalent to subspace*Cf*subspace' but behaves well numerically
% by construction.
invCf = diag(1./diag(Cf));
subspace = u(:,1:subspace)';
if ~isempty(dat), dat = subspace*dat; end
if strcmp(submethod, 'dics_refchan')
Cr = subspace*Cr;
end
else
Cf_pre_subspace = Cf;
Cf = subspace*Cf*subspace'; % here the subspace can be different from
% the singular vectors of Cy, so we have to do the sandwiching as opposed
% to line 216
if strcmp(realfilter, 'yes')
invCf = pinv(real(Cf));
else
invCf = pinv(Cf);
end
if strcmp(submethod, 'dics_refchan')
Cr = subspace*Cr;
end
end
end
% start the scanning with the proper metric
ft_progress('init', feedback, 'scanning grid');
switch submethod
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% dics_power
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'dics_power'
% only compute power of a dipole at the grid positions
for i=1:size(dip.pos,1)
if hasleadfield && hasmom && size(dip.mom, 1)==size(dip.leadfield{i}, 2)
% reuse the leadfield that was previously computed and project
lf = dip.leadfield{i} * dip.mom(:,i);
elseif hasleadfield && hasmom
% reuse the leadfield that was previously computed but don't project
lf = dip.leadfield{i};
elseif hasleadfield && ~hasmom
% reuse the leadfield that was previously computed
lf = dip.leadfield{i};
elseif ~hasleadfield && hasmom
% compute the leadfield for a fixed dipole orientation
lf = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam) * dip.mom(:,i);
else
% compute the leadfield
lf = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam);
end
if hassubspace
% do subspace projection of the forward model
lf = dip.subspace{i} * lf;
% the cross-spectral density becomes voxel dependent due to the projection
Cf = dip.subspace{i} * Cf_pre_subspace * dip.subspace{i}';
if strcmp(realfilter, 'yes')
invCf = pinv(dip.subspace{i} * (real(Cf_pre_subspace) + lambda * eye(size(Cf_pre_subspace))) * dip.subspace{i}');
else
invCf = pinv(dip.subspace{i} * (Cf_pre_subspace + lambda * eye(size(Cf_pre_subspace))) * dip.subspace{i}');
end
elseif ~isempty(subspace)
% do subspace projection of the forward model only
lforig = lf;
lf = subspace * lf;
% according to Kensuke's paper, the eigenspace bf boils down to projecting
% the 'traditional' filter onto the subspace
% spanned by the first k eigenvectors [u,s,v] = svd(Cy); filt = ESES*filt;
% ESES = u(:,1:k)*u(:,1:k)';
% however, even though it seems that the shape of the filter is identical to
% the shape it is obtained with the following code, the w*lf=I does not
% hold.
end
if hasfilter
% use precomputed filter
filt = dip.filter{i};
else
% compute filter
filt = pinv(lf' * invCf * lf) * lf' * invCf; % Gross eqn. 3, use PINV/SVD to cover rank deficient leadfield
end
if fixedori
% use single dipole orientation
if hasfilter && size(filt,1) == 1
% provided precomputed filter already projects to one
% orientation, nothing to be done here
else
% find out the optimal dipole orientation
[u, s, v] = svd(real(filt * Cf * ctranspose(filt)));
maxpowori = u(:,1);
eta = s(1,1)./s(2,2);
% and compute the leadfield for that orientation
lf = lf * maxpowori;
dipout.ori{i} = maxpowori;
dipout.eta(i) = eta;
if ~isempty(subspace), lforig = lforig * maxpowori; end
% recompute the filter to only use that orientation
filt = pinv(lf' * invCf * lf) * lf' * invCf;
end
elseif hasfilter && size(filt,1) == 1
error('the precomputed filter you provided projects to a single dipole orientation, but you request fixedori=''no''; this is invalid. Either provide a filter with the three orientations retained, or specify fixedori=''yes''.');
end
csd = filt * Cf * ctranspose(filt); % Gross eqn. 4 and 5
if powlambda1
if size(csd,1) == 1
% only 1 orientation, no need to do svd
dipout.pow(i,1) = real(csd);
else
dipout.pow(i,1) = lambda1(csd); % compute the power at the dipole location, Gross eqn. 8
end
elseif powtrace
dipout.pow(i,1) = real(trace(csd)); % compute the power at the dipole location
end
if keepcsd
dipout.csd{i,1} = csd;
end
if projectnoise
if powlambda1
dipout.noise(i,1) = noise * lambda1(filt * ctranspose(filt));
elseif powtrace
dipout.noise(i,1) = noise * real(trace(filt * ctranspose(filt)));
end
if keepcsd
dipout.noisecsd{i,1} = noise * filt * ctranspose(filt);
end
end
if keepfilter
if ~isempty(subspace)
dipout.filter{i,1} = filt*subspace; %FIXME should this be subspace, or pinv(subspace)?
else
dipout.filter{i,1} = filt;
end
end
if keepleadfield
if ~isempty(subspace)
dipout.leadfield{i,1} = lforig;
else
dipout.leadfield{i,1} = lf;
end
end
ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% dics_refchan
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'dics_refchan'
% compute cortico-muscular coherence, using reference cross spectral density
for i=1:size(dip.pos,1)
if hasleadfield
% reuse the leadfield that was previously computed
lf = dip.leadfield{i};
elseif hasmom
% compute the leadfield for a fixed dipole orientation
lf = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize) .* dip.mom(i,:)';
else
% compute the leadfield
lf = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize);
end
if hassubspace
% do subspace projection of the forward model
lforig = lf;
lf = dip.subspace{i} * lf;
% the cross-spectral density becomes voxel dependent due to the projection
Cf = dip.subspace{i} * Cf_pre_subspace * dip.subspace{i}';
invCf = pinv(dip.subspace{i} * (Cf_pre_subspace + lambda * eye(size(Cf))) * dip.subspace{i}');
elseif ~isempty(subspace)
% do subspace projection of the forward model only
lforig = lf;
lf = subspace * lf;
% according to Kensuke's paper, the eigenspace bf boils down to projecting
% the 'traditional' filter onto the subspace
% spanned by the first k eigenvectors [u,s,v] = svd(Cy); filt = ESES*filt;
% ESES = u(:,1:k)*u(:,1:k)';
% however, even though it seems that the shape of the filter is identical to
% the shape it is obtained with the following code, the w*lf=I does not
% hold.
end
if hasfilter
% use precomputed filter
filt = dip.filter{i};
else
% compute filter
filt = pinv(lf' * invCf * lf) * lf' * invCf; % Gross eqn. 3, use PINV/SVD to cover rank deficient leadfield
end
if fixedori
% use single dipole orientation
if hasfilter && size(filt,1) == 1
% provided precomputed filter already projects to one
% orientation, nothing to be done here
else
% find out the optimal dipole orientation
[u, s, v] = svd(real(filt * Cf * ctranspose(filt)));
maxpowori = u(:,1);
% compute the leadfield for that orientation
lf = lf * maxpowori;
dipout.ori{i,1} = maxpowori;
% recompute the filter to only use that orientation
filt = pinv(lf' * invCf * lf) * lf' * invCf;
end
elseif hasfilter && size(filt,1) == 1
error('the precomputed filter you provided projects to a single dipole orientation, but you request fixedori=''no''; this is invalid. Either provide a filter with the three orientations retained, or specify fixedori=''yes''.');
end
if powlambda1
[pow, ori] = lambda1(filt * Cf * ctranspose(filt)); % compute the power and orientation at the dipole location, Gross eqn. 4, 5 and 8
elseif powtrace
pow = real(trace(filt * Cf * ctranspose(filt))); % compute the power at the dipole location
end
csd = filt*Cr; % Gross eqn. 6
if powlambda1
% FIXME this should use the dipole orientation with maximum power
coh = lambda1(csd)^2 / (pow * Pr); % Gross eqn. 9
elseif powtrace
coh = norm(csd)^2 / (pow * Pr);
end
dipout.pow(i,1) = pow;
dipout.coh(i,1) = coh;
if keepcsd
dipout.csd{i,1} = csd;
end
if projectnoise
if powlambda1
dipout.noise(i,1) = noise * lambda1(filt * ctranspose(filt));
elseif powtrace
dipout.noise(i,1) = noise * real(trace(filt * ctranspose(filt)));
end
if keepcsd
dipout.noisecsd{i,1} = noise * filt * ctranspose(filt);
end
end
if keepfilter
dipout.filter{i,1} = filt;
end
if keepleadfield
if ~isempty(subspace)
dipout.leadfield{i,1} = lforig;
else
dipout.leadfield{i,1} = lf;
end
end
ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% dics_refdip
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'dics_refdip'
if hassubspace || ~isempty(subspace)
error('subspace projections are not supported for beaming cortico-cortical coherence');
end
if fixedori
error('fixed orientations are not supported for beaming cortico-cortical coherence');
end
% compute cortio-cortical coherence with a dipole at the reference position
lf1 = ft_compute_leadfield(refdip, grad, headmodel, 'reducerank', reducerank, 'normalize', normalize);
% construct the spatial filter for the first (reference) dipole location
filt1 = pinv(lf1' * invCf * lf1) * lf1' * invCf; % use PINV/SVD to cover rank deficient leadfield
if powlambda1
Pref = lambda1(filt1 * Cf * ctranspose(filt1)); % compute the power at the first dipole location, Gross eqn. 8
elseif powtrace
Pref = real(trace(filt1 * Cf * ctranspose(filt1))); % compute the power at the first dipole location
end
for i=1:size(dip.pos,1)
if hasleadfield
% reuse the leadfield that was previously computed
lf2 = dip.leadfield{i};
elseif hasmom
% compute the leadfield for a fixed dipole orientation
lf2 = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize) .* dip.mom(i,:)';
else
% compute the leadfield
lf2 = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize);
end
if hasfilter
% use the provided filter
filt2 = dip.filter{i};
else
% construct the spatial filter for the second dipole location
filt2 = pinv(lf2' * invCf * lf2) * lf2' * invCf; % use PINV/SVD to cover rank deficient leadfield
end
csd = filt1 * Cf * ctranspose(filt2); % compute the cross spectral density between the two dipoles, Gross eqn. 4
if powlambda1
pow = lambda1(filt2 * Cf * ctranspose(filt2)); % compute the power at the second dipole location, Gross eqn. 8
elseif powtrace
pow = real(trace(filt2 * Cf * ctranspose(filt2))); % compute the power at the second dipole location
end
if powlambda1
coh = lambda1(csd)^2 / (pow * Pref); % compute the coherence between the first and second dipole
elseif powtrace
coh = real(trace((csd)))^2 / (pow * Pref); % compute the coherence between the first and second dipole
end
dipout.pow(i,1) = pow;
dipout.coh(i,1) = coh;
if keepcsd
dipout.csd{i,1} = csd;
end
if projectnoise
if powlambda1
dipout.noise(i,1) = noise * lambda1(filt2 * ctranspose(filt2));
elseif powtrace
dipout.noise(i,1) = noise * real(trace(filt2 * ctranspose(filt2)));
end
if keepcsd
dipout.noisecsd{i,1} = noise * filt2 * ctranspose(filt2);
end
end
if keepleadfield
dipout.leadfield{i,1} = lf2;
end
ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1));
end
end % switch submethod
ft_progress('close');
% wrap it all up, prepare the complete output
dipout.inside = originside;
dipout.pos = origpos;
% reassign the scan values over the inside and outside grid positions
if isfield(dipout, 'leadfield')
dipout.leadfield( originside) = dipout.leadfield;
dipout.leadfield(~originside) = {[]};
end
if isfield(dipout, 'filter')
dipout.filter( originside) = dipout.filter;
dipout.filter(~originside) = {[]};
end
if isfield(dipout, 'ori')
dipout.ori( originside) = dipout.ori;
dipout.ori(~originside) = {[]};
end
if isfield(dipout, 'eta')
dipout.eta( originside) = dipout.eta;
dipout.eta(~originside) = nan;
end
if isfield(dipout, 'pow')
dipout.pow( originside) = dipout.pow;
dipout.pow(~originside) = nan;
end
if isfield(dipout, 'noise')
dipout.noise( originside) = dipout.noise;
dipout.noise(~originside) = nan;
end
if isfield(dipout, 'coh')
dipout.coh( originside) = dipout.coh;
dipout.coh(~originside) = nan;
end
if isfield(dipout, 'csd')
dipout.csd( originside) = dipout.csd;
dipout.csd(~originside) = {[]};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to obtain the largest singular value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [s, ori] = lambda1(x)
% determine the largest singular value, which corresponds to the power along the dominant direction
[u, s, v] = svd(x);
s = s(1);
ori = u(:,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute the pseudo inverse. This is the same as the
% standard MATLAB function, except that the default tolerance is twice as
% high.
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision$ $Date: 2009/06/17 13:40:37 $
% default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = pinv(A,varargin)
[m,n] = size(A);
if n > m
X = pinv(A',varargin{:})';
else
[U,S,V] = svd(A,0);
if m > 1, s = diag(S);
elseif m == 1, s = S(1);
else s = 0;
end
if nargin == 2
tol = varargin{1};
else
tol = 10 * max(m,n) * max(s) * eps;
end
r = sum(s > tol);
if (r == 0)
X = zeros(size(A'),class(A));
else
s = diag(ones(r,1)./s(1:r));
X = V(:,1:r)*s*U(:,1:r)';
end
end
|
github
|
lcnhappe/happe-master
|
ft_sloreta.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/inverse/ft_sloreta.m
| 16,166 |
utf_8
|
80ba97c0f6bbf9828825f37d58664d9f
|
function [dipout] = ft_sloreta(dip, grad, headmodel, dat, Cy, varargin)
% ft_sloreta scans on pre-defined dipole locations with a single dipole
% and returns the sLORETA spatial filter output for a dipole on every
% location. Dipole locations that are outside the head will return a
% NaN value. Adapted from beamformer_lcmv.m
%
% Use as
% [dipout] = beamformer_lcmv(dipin, grad, headmodel, dat, cov, varargin)
% where
% dipin is the input dipole model
% grad is the gradiometer definition
% headmodel is the volume conductor definition
% dat is the data matrix with the ERP or ERF
% cov is the data covariance or cross-spectral density matrix
% and
% dipout is the resulting dipole model with all details
%
% The input dipole model consists of
% dipin.pos positions for dipole, e.g. regular grid, Npositions x 3
% dipin.mom dipole orientation (optional), 3 x Npositions
%
% Additional options should be specified in key-value pairs and can be
% 'lambda' = regularisation parameter
% 'powmethod' = can be 'trace' or 'lambda1'
% 'feedback' = give ft_progress indication, can be 'text', 'gui' or 'none' (default)
% 'fixedori' = use fixed or free orientation, can be 'yes' or 'no'
% 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no'
% 'projectmom' = project the dipole moment timecourse on the direction of maximal power, can be 'yes' or 'no'
% 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no'
% 'keepleadfield' = remember the forward computation, can be 'yes' or 'no'
% 'keepmom' = remember the estimated dipole moment timeseries, can be 'yes' or 'no'
% 'keepcov' = remember the estimated dipole covariance, can be 'yes' or 'no'
% 'kurtosis' = compute the kurtosis of the dipole timeseries, can be 'yes' or 'no'
%
% These options influence the forward computation of the leadfield
% 'reducerank' = reduce the leadfield rank, can be 'no' or a number (e.g. 2)
% 'normalize' = normalize the leadfield
% 'normalizeparam' = parameter for depth normalization (default = 0.5)
%
% If the dipole definition only specifies the dipole location, a rotating
% dipole (regional source) is assumed on each location. If a dipole moment
% is specified, its orientation will be used and only the strength will
% be fitted to the data.
% Copyright (C) 2016, Sarang Dalal
% based on code Copyright (C) 2003-2014, 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/>.
%
if mod(nargin-5,2)
% the first 5 arguments are fixed, the other arguments should come in pairs
error('invalid number of optional arguments');
end
% these optional settings do not have defaults
powmethod = ft_getopt(varargin, 'powmethod'); % the default for this is set below
subspace = ft_getopt(varargin, 'subspace'); % used to implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM
% these settings pertain to the forward model, the defaults are set in compute_leadfield
reducerank = ft_getopt(varargin, 'reducerank');
normalize = ft_getopt(varargin, 'normalize');
normalizeparam = ft_getopt(varargin, 'normalizeparam');
% these optional settings have defaults
feedback = ft_getopt(varargin, 'feedback', 'text');
keepfilter = ft_getopt(varargin, 'keepfilter', 'no');
keepleadfield = ft_getopt(varargin, 'keepleadfield', 'no');
keepcov = ft_getopt(varargin, 'keepcov', 'no');
keepmom = ft_getopt(varargin, 'keepmom', 'yes');
lambda = ft_getopt(varargin, 'lambda', 0);
projectnoise = ft_getopt(varargin, 'projectnoise', 'yes');
projectmom = ft_getopt(varargin, 'projectmom', 'no');
fixedori = ft_getopt(varargin, 'fixedori', 'no');
computekurt = ft_getopt(varargin, 'kurtosis', 'no');
weightnorm = ft_getopt(varargin, 'weightnorm', 'no');
% convert the yes/no arguments to the corresponding logical values
keepfilter = istrue(keepfilter);
keepleadfield = istrue(keepleadfield);
keepcov = istrue(keepcov);
keepmom = istrue(keepmom);
projectnoise = istrue(projectnoise);
projectmom = istrue(projectmom);
fixedori = istrue(fixedori);
computekurt = istrue(computekurt);
% default is to use the trace of the covariance matrix, see Van Veen 1997
if isempty(powmethod)
powmethod = 'trace';
end
% use these two logical flags instead of doing the string comparisons each time again
powtrace = strcmp(powmethod, 'trace');
powlambda1 = strcmp(powmethod, 'lambda1');
if isfield(dip, 'mom') && fixedori
error('you cannot specify a dipole orientation and fixedmom simultaneously');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% find the dipole positions that are inside/outside the brain
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(dip, 'inside')
dip.inside = ft_inside_vol(dip.pos, headmodel);
end
if any(dip.inside>1)
% convert to logical representation
tmp = false(size(dip.pos,1),1);
tmp(dip.inside) = true;
dip.inside = tmp;
end
% keep the original details on inside and outside positions
originside = dip.inside;
origpos = dip.pos;
% select only the dipole positions inside the brain for scanning
dip.pos = dip.pos(originside,:);
dip.inside = true(size(dip.pos,1),1);
if isfield(dip, 'mom')
dip.mom = dip.mom(:, originside);
end
if isfield(dip, 'leadfield')
fprintf('using precomputed leadfields\n');
dip.leadfield = dip.leadfield(originside);
end
if isfield(dip, 'filter')
fprintf('using precomputed filters\n');
dip.filter = dip.filter(originside);
end
if isfield(dip, 'subspace')
fprintf('using subspace projection\n');
dip.subspace = dip.subspace(originside);
end
isrankdeficient = (rank(Cy)<size(Cy,1));
% it is difficult to give a quantitative estimate of lambda, therefore also
% support relative (percentage) measure that can be specified as string (e.g. '10%')
if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%'
ratio = sscanf(lambda, '%f%%');
ratio = ratio/100;
lambda = ratio * trace(Cy)/size(Cy,1);
end
if projectnoise
% estimate the noise power, which is further assumed to be equal and uncorrelated over channels
if isrankdeficient
% estimated noise floor is equal to or higher than lambda
noise = lambda;
else
% estimate the noise level in the covariance matrix by the smallest singular value
noise = svd(Cy);
noise = noise(end);
% estimated noise floor is equal to or higher than lambda
noise = max(noise, lambda);
end
end
% the inverse only has to be computed once for all dipoles
invCy = pinv(Cy + lambda * eye(size(Cy)));
if isfield(dip, 'subspace')
fprintf('using source-specific subspace projection\n');
% remember the original data prior to the voxel dependent subspace projection
dat_pre_subspace = dat;
Cy_pre_subspace = Cy;
elseif ~isempty(subspace)
% TODO implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM
fprintf('using data-specific subspace projection\n');
if numel(subspace)==1,
% interpret this as a truncation of the eigenvalue-spectrum
% if <1 it is a fraction of the largest eigenvalue
% if >=1 it is the number of largest eigenvalues
dat_pre_subspace = dat;
Cy_pre_subspace = Cy;
[u, s, v] = svd(real(Cy));
if subspace<1,
subspace = find(diag(s)./s(1,1) > subspace, 1, 'last');
end
Cy = s(1:subspace,1:subspace);
% this is equivalent to subspace*Cy*subspace' but behaves well numerically by construction.
invCy = diag(1./diag(Cy + lambda * eye(size(Cy))));
subspace = u(:,1:subspace)';
dat = subspace*dat;
else
dat_pre_subspace = dat;
Cy_pre_subspace = Cy;
Cy = subspace*Cy*subspace';
% here the subspace can be different from the singular vectors of Cy, so we
% have to do the sandwiching as opposed to line 216
invCy = pinv(Cy);
dat = subspace*dat;
end
end
% start the scanning with the proper metric
ft_progress('init', feedback, 'scanning grid');
for i=1:size(dip.pos,1)
if isfield(dip, 'leadfield') && isfield(dip, 'mom') && size(dip.mom, 1)==size(dip.leadfield{i}, 2)
% reuse the leadfield that was previously computed and project
lf = dip.leadfield{i} * dip.mom(:,i);
elseif isfield(dip, 'leadfield') && isfield(dip, 'mom')
% reuse the leadfield that was previously computed but don't project
lf = dip.leadfield{i};
elseif isfield(dip, 'leadfield') && ~isfield(dip, 'mom')
% reuse the leadfield that was previously computed
lf = dip.leadfield{i};
elseif ~isfield(dip, 'leadfield') && isfield(dip, 'mom')
% compute the leadfield for a fixed dipole orientation
lf = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam) * dip.mom(:,i);
else
% compute the leadfield
lf = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam);
end
if isfield(dip, 'subspace')
% do subspace projection of the forward model
lf = dip.subspace{i} * lf;
% the data and the covariance become voxel dependent due to the projection
dat = dip.subspace{i} * dat_pre_subspace;
Cy = dip.subspace{i} * (Cy_pre_subspace + lambda * eye(size(Cy_pre_subspace))) * dip.subspace{i}';
invCy = pinv(dip.subspace{i} * (Cy_pre_subspace + lambda * eye(size(Cy_pre_subspace))) * dip.subspace{i}');
elseif ~isempty(subspace)
% do subspace projection of the forward model only
lforig = lf;
lf = subspace * lf;
% according to Kensuke's paper, the eigenspace bf boils down to projecting
% the 'traditional' filter onto the subspace
% spanned by the first k eigenvectors [u,s,v] = svd(Cy); filt = ESES*filt;
% ESES = u(:,1:k)*u(:,1:k)';
% however, even though it seems that the shape of the filter is identical to
% the shape it is obtained with the following code, the w*lf=I does not hold.
end
G = lf * lf'; % Gram matrix
invG = inv(G + lambda * eye(size(G))); % regularized G^-1
if fixedori
[vv, dd] = eig(pinv(lf' * invG * lf) * lf' * invG * Cy * invG * lf); % eqn 13.22 from Sekihara & Nagarajan 2008 for sLORETA
[~,maxeig]=max(diag(dd));
eta = vv(:,maxeig);
lf = lf * eta;
if ~isempty(subspace), lforig = lforig * eta; end
dipout.ori{i} = eta;
end
if isfield(dip, 'filter')
% use the provided filter
filt = dip.filter{i};
else
% construct the spatial filter
% sLORETA: if orthogonal components are retained (i.e., fixedori = 'no')
% then weight for each lead field column must be calculated separately
for ii=1:size(lf,2)
filt(ii,:) = pinv(sqrt(lf(:,ii)' * invG * lf(:,ii))) * lf(:,ii)' * invG;
end
end
if(any(~isreal(filt)))
error('spatial filter has complex values -- did you set lambda properly?');
end
if projectmom
[u, s, v] = svd(filt * Cy * ctranspose(filt));
mom = u(:,1); % dominant dipole direction
filt = (mom') * filt;
end
if powlambda1
% dipout.pow(i) = lambda1(pinv(lf' * invCy * lf)); % this is more efficient if the filters are not present
dipout.pow(i,1) = lambda1(filt * Cy * ctranspose(filt)); % this is more efficient if the filters are present
elseif powtrace
% dipout.pow(i) = trace(pinv(lf' * invCy * lf)); % this is more efficient if the filters are not present, van Veen eqn. 24
dipout.pow(i,1) = trace(filt * Cy * ctranspose(filt)); % this is more efficient if the filters are present
end
if keepcov
% compute the source covariance matrix
dipout.cov{i,1} = filt * Cy * ctranspose(filt);
end
if keepmom && ~isempty(dat)
% estimate the instantaneous dipole moment at the current position
dipout.mom{i,1} = filt * dat;
end
if computekurt && ~isempty(dat)
% compute the kurtosis of the dipole time series
dipout.kurtosis(i,:) = kurtosis((filt*dat)');
end
if projectnoise
% estimate the power of the noise that is projected through the filter
if powlambda1
dipout.noise(i,1) = noise * lambda1(filt * ctranspose(filt));
elseif powtrace
dipout.noise(i,1) = noise * trace(filt * ctranspose(filt));
end
if keepcov
dipout.noisecov{i,1} = noise * filt * ctranspose(filt);
end
end
if keepfilter
if ~isempty(subspace)
dipout.filter{i,1} = filt*subspace;
%dipout.filter{i} = filt*pinv(subspace);
else
dipout.filter{i,1} = filt;
end
end
if keepleadfield
if ~isempty(subspace)
dipout.leadfield{i,1} = lforig;
else
dipout.leadfield{i,1} = lf;
end
end
ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1));
end
ft_progress('close');
% reassign the scan values over the inside and outside grid positions
dipout.pos = origpos;
dipout.inside = originside;
if isfield(dipout, 'leadfield')
dipout.leadfield( originside) = dipout.leadfield;
dipout.leadfield(~originside) = {[]};
end
if isfield(dipout, 'filter')
dipout.filter( originside) = dipout.filter;
dipout.filter(~originside) = {[]};
end
if isfield(dipout, 'mom')
dipout.mom( originside) = dipout.mom;
dipout.mom(~originside) = {[]};
end
if isfield(dipout, 'ori')
dipout.ori( originside) = dipout.ori;
dipout.ori(~originside) = {[]};
end
if isfield(dipout, 'cov')
dipout.cov( originside) = dipout.cov;
dipout.cov(~originside) = {[]};
end
if isfield(dipout, 'noisecov')
dipout.noisecov( originside) = dipout.noisecov;
dipout.noisecov(~originside) = {[]};
end
if isfield(dipout, 'pow')
dipout.pow( originside) = dipout.pow;
dipout.pow(~originside) = nan;
end
if isfield(dipout, 'noise')
dipout.noise( originside) = dipout.noise;
dipout.noise(~originside) = nan;
end
if isfield(dipout, 'kurtosis')
dipout.kurtosis( originside) = dipout.kurtosis;
dipout.kurtosis(~originside) = nan;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to obtain the largest singular value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = lambda1(x)
% determine the largest singular value, which corresponds to the power along the dominant direction
s = svd(x);
s = s(1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute the pseudo inverse. This is the same as the
% standard MATLAB function, except that the default tolerance is twice as
% high.
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision: 10541 $ $Date: 2009/03/23 21:14:42 $
% default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = pinv(A,varargin)
[m,n] = size(A);
if n > m
X = pinv(A',varargin{:})';
else
[U,S,V] = svd(A,0);
if m > 1, s = diag(S);
elseif m == 1, s = S(1);
else s = 0;
end
if nargin == 2
tol = varargin{1};
else
tol = 10 * max(m,n) * max(s) * eps;
end
r = sum(s > tol);
if (r == 0)
X = zeros(size(A'),class(A));
else
s = diag(ones(r,1)./s(1:r));
X = V(:,1:r)*s*U(:,1:r)';
end
end
|
github
|
lcnhappe/happe-master
|
beamformer_lcmv.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/inverse/beamformer_lcmv.m
| 17,369 |
utf_8
|
2cfd8f53b59635586786d35fb121f695
|
function [dipout] = beamformer_lcmv(dip, grad, headmodel, dat, Cy, varargin)
% BEAMFORMER_LCMV scans on pre-defined dipole locations with a single dipole
% and returns the beamformer spatial filter output for a dipole on every
% location. Dipole locations that are outside the head will return a
% NaN value.
%
% Use as
% [dipout] = beamformer_lcmv(dipin, grad, headmodel, dat, cov, varargin)
% where
% dipin is the input dipole model
% grad is the gradiometer definition
% headmodel is the volume conductor definition
% dat is the data matrix with the ERP or ERF
% cov is the data covariance or cross-spectral density matrix
% and
% dipout is the resulting dipole model with all details
%
% The input dipole model consists of
% dipin.pos positions for dipole, e.g. regular grid, Npositions x 3
% dipin.mom dipole orientation (optional), 3 x Npositions
%
% Additional options should be specified in key-value pairs and can be
% 'lambda' = regularisation parameter
% 'powmethod' = can be 'trace' or 'lambda1'
% 'feedback' = give ft_progress indication, can be 'text', 'gui' or 'none' (default)
% 'fixedori' = use fixed or free orientation, can be 'yes' or 'no'
% 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no'
% 'projectmom' = project the dipole moment timecourse on the direction of maximal power, can be 'yes' or 'no'
% 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no'
% 'keepleadfield' = remember the forward computation, can be 'yes' or 'no'
% 'keepmom' = remember the estimated dipole moment timeseries, can be 'yes' or 'no'
% 'keepcov' = remember the estimated dipole covariance, can be 'yes' or 'no'
% 'kurtosis' = compute the kurtosis of the dipole timeseries, can be 'yes' or 'no'
%
% These options influence the forward computation of the leadfield
% 'reducerank' = reduce the leadfield rank, can be 'no' or a number (e.g. 2)
% 'normalize' = normalize the leadfield
% 'normalizeparam' = parameter for depth normalization (default = 0.5)
%
% If the dipole definition only specifies the dipole location, a rotating
% dipole (regional source) is assumed on each location. If a dipole moment
% is specified, its orientation will be used and only the strength will
% be fitted to the data.
% Copyright (C) 2003-2014, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% 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$
if mod(nargin-5,2)
% the first 5 arguments are fixed, the other arguments should come in pairs
error('invalid number of optional arguments');
end
% these optional settings do not have defaults
powmethod = ft_getopt(varargin, 'powmethod'); % the default for this is set below
subspace = ft_getopt(varargin, 'subspace'); % used to implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM
% these settings pertain to the forward model, the defaults are set in compute_leadfield
reducerank = ft_getopt(varargin, 'reducerank');
normalize = ft_getopt(varargin, 'normalize');
normalizeparam = ft_getopt(varargin, 'normalizeparam');
% these optional settings have defaults
feedback = ft_getopt(varargin, 'feedback', 'text');
keepfilter = ft_getopt(varargin, 'keepfilter', 'no');
keepleadfield = ft_getopt(varargin, 'keepleadfield', 'no');
keepcov = ft_getopt(varargin, 'keepcov', 'no');
keepmom = ft_getopt(varargin, 'keepmom', 'yes');
lambda = ft_getopt(varargin, 'lambda', 0);
projectnoise = ft_getopt(varargin, 'projectnoise', 'yes');
projectmom = ft_getopt(varargin, 'projectmom', 'no');
fixedori = ft_getopt(varargin, 'fixedori', 'no');
computekurt = ft_getopt(varargin, 'kurtosis', 'no');
weightnorm = ft_getopt(varargin, 'weightnorm', 'no');
% convert the yes/no arguments to the corresponding logical values
keepfilter = istrue(keepfilter);
keepleadfield = istrue(keepleadfield);
keepcov = istrue(keepcov);
keepmom = istrue(keepmom);
projectnoise = istrue(projectnoise);
projectmom = istrue(projectmom);
fixedori = istrue(fixedori);
computekurt = istrue(computekurt);
% default is to use the trace of the covariance matrix, see Van Veen 1997
if isempty(powmethod)
powmethod = 'trace';
end
% use these two logical flags instead of doing the string comparisons each time again
powtrace = strcmp(powmethod, 'trace');
powlambda1 = strcmp(powmethod, 'lambda1');
if isfield(dip, 'mom') && fixedori
error('you cannot specify a dipole orientation and fixedmom simultaneously');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% find the dipole positions that are inside/outside the brain
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(dip, 'inside')
dip.inside = ft_inside_vol(dip.pos, headmodel);
end
if any(dip.inside>1)
% convert to logical representation
tmp = false(size(dip.pos,1),1);
tmp(dip.inside) = true;
dip.inside = tmp;
end
% keep the original details on inside and outside positions
originside = dip.inside;
origpos = dip.pos;
% select only the dipole positions inside the brain for scanning
dip.pos = dip.pos(originside,:);
dip.inside = true(size(dip.pos,1),1);
if isfield(dip, 'mom')
dip.mom = dip.mom(:, originside);
end
if isfield(dip, 'leadfield')
fprintf('using precomputed leadfields\n');
dip.leadfield = dip.leadfield(originside);
end
if isfield(dip, 'filter')
fprintf('using precomputed filters\n');
dip.filter = dip.filter(originside);
end
if isfield(dip, 'subspace')
fprintf('using subspace projection\n');
dip.subspace = dip.subspace(originside);
end
isrankdeficient = (rank(Cy)<size(Cy,1));
% it is difficult to give a quantitative estimate of lambda, therefore also
% support relative (percentage) measure that can be specified as string (e.g. '10%')
if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%'
ratio = sscanf(lambda, '%f%%');
ratio = ratio/100;
lambda = ratio * trace(Cy)/size(Cy,1);
end
if projectnoise
% estimate the noise power, which is further assumed to be equal and uncorrelated over channels
if isrankdeficient
% estimated noise floor is equal to or higher than lambda
noise = lambda;
else
% estimate the noise level in the covariance matrix by the smallest singular value
noise = svd(Cy);
noise = noise(end);
% estimated noise floor is equal to or higher than lambda
noise = max(noise, lambda);
end
end
% the inverse only has to be computed once for all dipoles
invCy = pinv(Cy + lambda * eye(size(Cy)));
if isfield(dip, 'subspace')
fprintf('using source-specific subspace projection\n');
% remember the original data prior to the voxel dependent subspace projection
dat_pre_subspace = dat;
Cy_pre_subspace = Cy;
elseif ~isempty(subspace)
% TODO implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM
fprintf('using data-specific subspace projection\n');
if numel(subspace)==1,
% interpret this as a truncation of the eigenvalue-spectrum
% if <1 it is a fraction of the largest eigenvalue
% if >=1 it is the number of largest eigenvalues
dat_pre_subspace = dat;
Cy_pre_subspace = Cy;
[u, s, v] = svd(real(Cy));
if subspace<1,
subspace = find(diag(s)./s(1,1) > subspace, 1, 'last');
end
Cy = s(1:subspace,1:subspace);
% this is equivalent to subspace*Cy*subspace' but behaves well numerically by construction.
invCy = diag(1./diag(Cy + lambda * eye(size(Cy))));
subspace = u(:,1:subspace)';
dat = subspace*dat;
else
dat_pre_subspace = dat;
Cy_pre_subspace = Cy;
Cy = subspace*Cy*subspace';
% here the subspace can be different from the singular vectors of Cy, so we
% have to do the sandwiching as opposed to line 216
invCy = pinv(Cy);
dat = subspace*dat;
end
end
% start the scanning with the proper metric
ft_progress('init', feedback, 'scanning grid');
for i=1:size(dip.pos,1)
if isfield(dip, 'leadfield') && isfield(dip, 'mom') && size(dip.mom, 1)==size(dip.leadfield{i}, 2)
% reuse the leadfield that was previously computed and project
lf = dip.leadfield{i} * dip.mom(:,i);
elseif isfield(dip, 'leadfield') && isfield(dip, 'mom')
% reuse the leadfield that was previously computed but don't project
lf = dip.leadfield{i};
elseif isfield(dip, 'leadfield') && ~isfield(dip, 'mom')
% reuse the leadfield that was previously computed
lf = dip.leadfield{i};
elseif ~isfield(dip, 'leadfield') && isfield(dip, 'mom')
% compute the leadfield for a fixed dipole orientation
lf = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam) * dip.mom(:,i);
else
% compute the leadfield
lf = ft_compute_leadfield(dip.pos(i,:), grad, headmodel, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam);
end
if isfield(dip, 'subspace')
% do subspace projection of the forward model
lf = dip.subspace{i} * lf;
% the data and the covariance become voxel dependent due to the projection
dat = dip.subspace{i} * dat_pre_subspace;
Cy = dip.subspace{i} * (Cy_pre_subspace + lambda * eye(size(Cy_pre_subspace))) * dip.subspace{i}';
invCy = pinv(dip.subspace{i} * (Cy_pre_subspace + lambda * eye(size(Cy_pre_subspace))) * dip.subspace{i}');
elseif ~isempty(subspace)
% do subspace projection of the forward model only
lforig = lf;
lf = subspace * lf;
% according to Kensuke's paper, the eigenspace bf boils down to projecting
% the 'traditional' filter onto the subspace
% spanned by the first k eigenvectors [u,s,v] = svd(Cy); filt = ESES*filt;
% ESES = u(:,1:k)*u(:,1:k)';
% however, even though it seems that the shape of the filter is identical to
% the shape it is obtained with the following code, the w*lf=I does not hold.
end
if fixedori
switch(weightnorm)
case {'unitnoisegain','nai'};
% optimal orientation calculation for unit-noise gain beamformer,
% (also applies to similar NAI), based on equation 4.47 from Sekihara & Nagarajan (2008)
[vv, dd] = eig(pinv(lf' * invCy^2 *lf)*(lf' * invCy *lf));
[~,maxeig]=max(diag(dd));
eta = vv(:,maxeig);
lf = lf * eta;
if ~isempty(subspace), lforig = lforig * eta; end
dipout.ori{i} = eta;
otherwise
% compute the leadfield for the optimal dipole orientation
% subsequently the leadfield for only that dipole orientation will be used for the final filter computation
% filt = pinv(lf' * invCy * lf) * lf' * invCy;
% [u, s, v] = svd(real(filt * Cy * ctranspose(filt)));
% in this step the filter computation is not necessary, use the quick way to compute the voxel level covariance (cf. van Veen 1997)
[u, s, v] = svd(real(pinv(lf' * invCy *lf)));
eta = u(:,1);
lf = lf * eta;
if ~isempty(subspace), lforig = lforig * eta; end
dipout.ori{i} = eta;
end
end
if isfield(dip, 'filter')
% use the provided filter
filt = dip.filter{i};
elseif strcmp(weightnorm,'nai')
% Van Veen's Neural Activity Index
% below equation is equivalent to following:
% filt = pinv(lf' * invCy * lf) * lf' * invCy;
% filt = filt/sqrt(noise*filt*filt');
filt = pinv(sqrt(noise * lf' * invCy^2 * lf)) * lf' *invCy; % based on Sekihara & Nagarajan 2008 eqn. 4.15
elseif strcmp(weightnorm,'unitnoisegain')
% Unit-noise gain minimum variance (aka Borgiotti-Kaplan) beamformer
% below equation is equivalent to following:
% filt = pinv(lf' * invCy * lf) * lf' * invCy;
% filt = filt/sqrt(filt*filt');
filt = pinv(sqrt(lf' * invCy^2 * lf)) * lf' *invCy; % Sekihara & Nagarajan 2008 eqn. 4.15
else
% construct the spatial filter
filt = pinv(lf' * invCy * lf) * lf' * invCy; % van Veen eqn. 23, use PINV/SVD to cover rank deficient leadfield
end
if projectmom
[u, s, v] = svd(filt * Cy * ctranspose(filt));
mom = u(:,1); % dominant dipole direction
filt = (mom') * filt;
end
if powlambda1
% dipout.pow(i) = lambda1(pinv(lf' * invCy * lf)); % this is more efficient if the filters are not present
dipout.pow(i,1) = lambda1(filt * Cy * ctranspose(filt)); % this is more efficient if the filters are present
elseif powtrace
% dipout.pow(i) = trace(pinv(lf' * invCy * lf)); % this is more efficient if the filters are not present, van Veen eqn. 24
dipout.pow(i,1) = trace(filt * Cy * ctranspose(filt)); % this is more efficient if the filters are present
end
if keepcov
% compute the source covariance matrix
dipout.cov{i,1} = filt * Cy * ctranspose(filt);
end
if keepmom && ~isempty(dat)
% estimate the instantaneous dipole moment at the current position
dipout.mom{i,1} = filt * dat;
end
if computekurt && ~isempty(dat)
% compute the kurtosis of the dipole time series
dipout.kurtosis(i,:) = kurtosis((filt*dat)');
end
if projectnoise
% estimate the power of the noise that is projected through the filter
if powlambda1
dipout.noise(i,1) = noise * lambda1(filt * ctranspose(filt));
elseif powtrace
dipout.noise(i,1) = noise * trace(filt * ctranspose(filt));
end
if keepcov
dipout.noisecov{i,1} = noise * filt * ctranspose(filt);
end
end
if keepfilter
if ~isempty(subspace)
dipout.filter{i,1} = filt*subspace;
%dipout.filter{i} = filt*pinv(subspace);
else
dipout.filter{i,1} = filt;
end
end
if keepleadfield
if ~isempty(subspace)
dipout.leadfield{i,1} = lforig;
else
dipout.leadfield{i,1} = lf;
end
end
ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1));
end
ft_progress('close');
% reassign the scan values over the inside and outside grid positions
dipout.pos = origpos;
dipout.inside = originside;
if isfield(dipout, 'leadfield')
dipout.leadfield( originside) = dipout.leadfield;
dipout.leadfield(~originside) = {[]};
end
if isfield(dipout, 'filter')
dipout.filter( originside) = dipout.filter;
dipout.filter(~originside) = {[]};
end
if isfield(dipout, 'mom')
dipout.mom( originside) = dipout.mom;
dipout.mom(~originside) = {[]};
end
if isfield(dipout, 'ori')
dipout.ori( originside) = dipout.ori;
dipout.ori(~originside) = {[]};
end
if isfield(dipout, 'cov')
dipout.cov( originside) = dipout.cov;
dipout.cov(~originside) = {[]};
end
if isfield(dipout, 'noisecov')
dipout.noisecov( originside) = dipout.noisecov;
dipout.noisecov(~originside) = {[]};
end
if isfield(dipout, 'pow')
dipout.pow( originside) = dipout.pow;
dipout.pow(~originside) = nan;
end
if isfield(dipout, 'noise')
dipout.noise( originside) = dipout.noise;
dipout.noise(~originside) = nan;
end
if isfield(dipout, 'kurtosis')
dipout.kurtosis( originside) = dipout.kurtosis;
dipout.kurtosis(~originside) = nan;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to obtain the largest singular value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = lambda1(x)
% determine the largest singular value, which corresponds to the power along the dominant direction
s = svd(x);
s = s(1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute the pseudo inverse. This is the same as the
% standard MATLAB function, except that the default tolerance is twice as
% high.
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision$ $Date: 2009/03/23 21:14:42 $
% default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = pinv(A,varargin)
[m,n] = size(A);
if n > m
X = pinv(A',varargin{:})';
else
[U,S,V] = svd(A,0);
if m > 1, s = diag(S);
elseif m == 1, s = S(1);
else s = 0;
end
if nargin == 2
tol = varargin{1};
else
tol = 10 * max(m,n) * max(s) * eps;
end
r = sum(s > tol);
if (r == 0)
X = zeros(size(A'),class(A));
else
s = diag(ones(r,1)./s(1:r));
X = V(:,1:r)*s*U(:,1:r)';
end
end
|
github
|
lcnhappe/happe-master
|
dipole_fit.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/inverse/dipole_fit.m
| 14,489 |
utf_8
|
b89f3d077a26265e017c4fd90d2fb7ac
|
function [dipout] = dipole_fit(dip, sens, headmodel, dat, varargin)
% DIPOLE_FIT performs an equivalent current dipole fit with a single
% or a small number of dipoles to explain an EEG or MEG scalp topography.
%
% Use as
% [dipout] = dipole_fit(dip, sens, headmodel, dat, ...)
%
% Additional input arguments should be specified as key-value pairs and can include
% 'constr' = Structure with constraints
% 'display' = Level of display [ off | iter | notify | final ]
% 'optimfun' = Function to use [fminsearch | fminunc ]
% 'maxiter' = Maximum number of function evaluations allowed [ positive integer ]
% 'metric' = Error measure to be minimised [ rv | var | abs ]
% 'checkinside' = Boolean flag to check whether dipole is inside source compartment [ 0 | 1 ]
% 'weight' = weight matrix for maximum likelihood estimation, e.g. inverse noise covariance
%
% The following optional input arguments relate to the computation of the leadfields
% 'reducerank' = 'no' or number
% 'normalize' = 'no', 'yes' or 'column'
% 'normalizeparam' = parameter for depth normalization (default = 0.5)
%
% The constraints on the source model are specified in a structure
% constr.symmetry = boolean, dipole positions are symmetrically coupled to each other
% constr.fixedori = boolean, keep dipole orientation fixed over whole data window
% constr.rigidbody = boolean, keep relative position of multiple dipoles fixed
% constr.mirror = vector, used for symmetric dipole models
% constr.reduce = vector, used for symmetric dipole models
% constr.expand = vector, used for symmetric dipole models
% constr.sequential = boolean, fit different dipoles to sequential slices of the data
%
% The maximum likelihood estimation implements
% Lutkenhoner B. "Dipole source localization by means of maximum
% likelihood estimation I. Theory and simulations" Electroencephalogr Clin
% Neurophysiol. 1998 Apr;106(4):314-21.
% Copyright (C) 2003-2016, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% 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$
% It is neccessary to provide backward compatibility support for the old function call
% in case people want to use it in conjunction with EEGLAB and the dipfit1 plugin.
% old style: function [dipout] = dipole_fit(dip, dat, sens, headmodel, constr), where constr is optional
% new style: function [dipout] = dipole_fit(dip, sens, headmodel, dat, varargin), where varargin is in key-value pairs
if nargin==4 && ~isstruct(sens) && isstruct(dat)
% looks like old style, the order of the input arguments has to be changed
warning('converting from old style input\n');
olddat = sens;
oldsens = headmodel;
oldhdm = dat;
dat = olddat;
sens = oldsens;
headmodel = oldhdm;
elseif nargin==5 && ~isstruct(sens) && isstruct(dat)
% looks like old style, the order of the input arguments has to be changed
% furthermore the additional constraint has to be fixed
warning('converting from old style input\n');
olddat = sens;
oldsens = headmodel;
oldhdm = dat;
dat = olddat;
sens = oldsens;
headmodel = oldhdm;
varargin = {'constr', varargin{1}}; % convert into a key-value pair
else
% looks like new style, i.e. with optional key-value arguments
% this is dealt with below
end
constr = ft_getopt(varargin, 'constr' ); % default is not to have constraints
metric = ft_getopt(varargin, 'metric', 'rv');
checkinside = ft_getopt(varargin, 'checkinside', false);
display = ft_getopt(varargin, 'display', 'iter');
optimfun = ft_getopt(varargin, 'optimfun' ); if isa(optimfun, 'char'), optimfun = str2func(optimfun); end
maxiter = ft_getopt(varargin, 'maxiter' );
reducerank = ft_getopt(varargin, 'reducerank' ); % for leadfield computation
normalize = ft_getopt(varargin, 'normalize' ); % for leadfield computation
normalizeparam = ft_getopt(varargin, 'normalizeparam' ); % for leadfield computation
weight = ft_getopt(varargin, 'weight' ); % for maximum likelihood estimation
if isfield(constr, 'mirror')
% for backward compatibility
constr.symmetry = true;
end
constr.symmetry = ft_getopt(constr, 'symmetry', false);
constr.fixedori = ft_getopt(constr, 'fixedori', false);
constr.rigidbody = ft_getopt(constr, 'rigidbody', false);
constr.sequential = ft_getopt(constr, 'sequential', false);
if isempty(optimfun)
% determine whether the MATLAB Optimization toolbox is available and can be used
if ft_hastoolbox('optim')
optimfun = @fminunc;
else
optimfun = @fminsearch;
end
end
if isempty(maxiter)
% set a default for the maximum number of iterations, depends on the optimization function
if isequal(optimfun, @fminunc)
maxiter = 1000;
else
maxiter = 3000;
end
end
% determine whether it is EEG or MEG
iseeg = ft_senstype(sens, 'eeg');
ismeg = ft_senstype(sens, 'meg');
if ismeg && iseeg
% this is something that I might implement in the future
error('simultaneous EEG and MEG not supported');
elseif iseeg
% ensure that the potential data is average referenced, just like the model potential
dat = avgref(dat);
end
% ensure correct dipole position and moment specification
dip = fixdipole(dip);
% convert the dipole model parameters into the non-linear parameter vector that will be optimized
[param, constr] = dipolemodel2param(dip.pos, dip.mom, constr);
% determine the scale
scale = ft_scalingfactor(sens.unit, 'cm');
% set the parameters for the optimization function
if isequal(optimfun, @fminunc)
options = optimset(...
'TolFun',1e-9,...
'TypicalX',scale*ones(size(param)),...
'LargeScale','off',...
'HessUpdate','bfgs',...
'MaxIter',maxiter,...
'MaxFunEvals',2*maxiter*length(param),...
'Display',display);
elseif isequal(optimfun, @fminsearch)
options = optimset(...
'MaxIter',maxiter,...
'MaxFunEvals',2*maxiter*length(param),...
'Display',display);
else
warning('unknown optimization function "%s", using default parameters', func2str(optimfun));
end
% perform the optimization with either the fminsearch or fminunc function
[param, fval, exitflag, output] = optimfun(@dipfit_error, param, options, dat, sens, headmodel, constr, metric, checkinside, reducerank, normalize, normalizeparam, weight);
if exitflag==0
error('Maximum number of iterations exceeded before reaching the minimum, please try with another initial guess.')
end
% do the linear optimization of the dipole moment parameters
% the error is not interesting any more, only the dipole moment is relevant
[err, mom] = dipfit_error(param, dat, sens, headmodel, constr, metric, checkinside, reducerank, normalize, normalizeparam, weight);
% convert the non-linear parameter vector into the dipole model parameters
[pos, ori] = param2dipolemodel(param, constr);
% return the optimal dipole parameters
dipout.pos = pos;
% return the optimal dipole moment and (optionally) the orientation
if ~isempty(ori)
dipout.mom = ori; % dipole orientation as vector
dipout.ampl = mom; % dipole strength
else
dipout.mom = mom; % dipole moment as vector or matrix, which represents both the orientation and strength as vector
end
% ensure correct dipole position and moment specification
dipout = fixdipole(dipout);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DIPOLEMODEL2PARAM takes the initial guess for the diople model and converts it
% to a set of parameters that needs to be optimized
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [param, constr] = dipolemodel2param(pos, ori, constr)
% reformat the position parameters in case of multiple dipoles, this
% should result in the matrix changing from [x1 y1 z1; x2 y2 z2] to
% [x1 y1 z1 x2 y2 z2] for the constraints to work
param = reshape(pos', 1, numel(pos));
% add the orientation to the nonlinear parameters
if constr.fixedori
numdip = size(pos,1);
for i=1:numdip
% add the orientation to the list of parameters
[th, phi, r] = cart2sph(ori(1,i), ori(2,i), ori(3,i));
param = [param th phi];
end
end
if constr.symmetry && constr.rigidbody
error('simultaneous symmetry and rigidbody constraints are not supported')
elseif constr.symmetry
% reduce the number of parameters to be fitted according to the constraints
% select a subset, the other sources will be re-added by the const.mirror field
param = param(constr.reduce);
elseif constr.rigidbody
constr.coilpos = param; % store the head localizer coil positions
param = [0 0 0 0 0 0]; % start with an initial translation and rotation of zero
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PARAM2DIPOLEMODEL takes the parameters and constraints and converts them into a
% diople model for which the leadfield and residual error can be computed
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [pos, ori] = param2dipolemodel(param, constr)
if constr.symmetry && constr.rigidbody
error('simultaneous symmetry and rigidbody constraints are not supported')
elseif constr.symmetry
param = constr.mirror .* param(constr.expand);
elseif constr.rigidbody
numdip = numel(constr.coilpos)/3;
pos = reshape(constr.coilpos, 3, numdip); % convert from vector into 3xN matrix
pos(4,:) = 1;
transform = rigidbody(param); % this is a 4x4 homogenous transformation matrix
pos = transform * pos; % apply the homogenous transformation matrix
param = reshape(pos(1:3,:), 1, 3*numdip);
clear pos % the actual pos will be constructed from param further down
end
if constr.fixedori
numdip = numel(param)/5;
ori = zeros(3,numdip);
for i=1:numdip
th = param(end-(2*i)+1);
phi = param(end-(2*i)+2);
[ori(1,i), ori(2,i), ori(3,i)] = sph2cart(th, phi, 1);
end
pos = reshape(param(1:(numdip*3)), 3, numdip)'; % convert into a Ndip*3 matrix
else
numdip = numel(param)/3;
pos = reshape(param, 3, numdip)'; % convert into a Ndip*3 matrix
ori = [];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DIPFIT_ERROR computes the error between measured and model data
% and can be used for non-linear fitting of dipole position
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [err, mom] = dipfit_error(param, dat, sens, headmodel, constr, metric, checkinside, reducerank, normalize, normalizeparam, weight)
% flush pending graphics events, ensure that fitting is interruptible
drawnow;
if ~isempty(get(0, 'currentfigure')) && strcmp(get(gcf, 'tag'), 'stop')
% interrupt the fitting
close;
error('USER ABORT');
end;
% convert the non-linear parameter vector into the dipole model parameters
[pos, ori] = param2dipolemodel(param, constr);
% check whether the dipole is inside the source compartment
if checkinside
inside = ft_inside_vol(pos, headmodel);
if ~all(inside)
error('Dipole is outside the source compartment');
end
end
% construct the leadfield matrix for all dipoles
lf = ft_compute_leadfield(pos, sens, headmodel, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam);
if ~isempty(ori)
lf = lf * ori;
end
% compute the optimal dipole moment and the model error
if ~isempty(weight)
% maximum likelihood estimation using the weigth matrix
if constr.sequential
error('not supported');
else
mom = pinv(lf'*weight*lf)*lf'*weight*dat; % Lutkenhoner equation 5
dif = dat - lf*mom;
end
% compute the generalized goodness-of-fit measure
switch metric
case 'rv' % relative residual variance
num = dif' * weight * dif;
denom = dat' * weight * dat;
err = sum(num(:)) ./ sum(denom(:)); % Lutkenhonner equation 7, except for the gof=1-rv
case 'var' % residual variance
num = dif' * weight * dif;
err = sum(num(:));
otherwise
error('Unsupported error metric for maximum likelihood dipole fitting');
end
else
% ordinary least squares, this is the same as MLE with weight=eye(nchans,nchans)
if constr.sequential
% the number of slices is the same as the number of dipoles
% each slice has a number of frames (time points) in it
% so the data can be nchan*ndip or nchan*(ndip*nframe)
numdip = numel(pos)/3;
numframe = size(dat,2)/numdip;
% do a sainty check on the number of frames, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3119
assert(numframe>0 && numframe==round(numframe), 'the number of frames should be a positive integer');
mom = zeros(3*numdip, numdip*numframe);
for i=1:numdip
dipsel = (1:3) + 3*(i-1); % 1:3 for the first dipole, 4:6 for the second dipole, ...
framesel = (1:numframe) + numframe*(i-1); % 1:numframe for the first, (numframe+1):(2*numframe) for the second, ...
mom(dipsel,framesel) = pinv(lf(:,dipsel))*dat(:,framesel);
end
else
mom = pinv(lf)*dat;
end
dif = dat - lf*mom;
% compute the ordinary goodness-of-fit measures
switch metric
case 'rv' % relative residual variance
err = sum(dif(:).^2) / sum(dat(:).^2);
case 'var' % residual variance
err = sum(dif(:).^2);
case 'abs' % absolute difference
err = sum(abs(dif));
otherwise
error('Unsupported error metric for dipole fitting');
end
end
if ~isreal(err)
% this happens for complex valued data, i.e. when fitting a dipole to spectrally decomposed data
% the error function should return a positive valued real number, otherwise fminunc fails
err = abs(err);
end
|
github
|
lcnhappe/happe-master
|
mesh_spectrum.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/inverse/private/mesh_spectrum.m
| 1,370 |
utf_8
|
94ec5a0ad9c740bd99c6d6a415702be9
|
% Mesh spectrum
function [L,H,d] = mesh_spectrum(S,n,varargin)
%[L,H,d] = ct_mesh_spectrum(S,n,mode)
% Compute the mesh laplace matrix and its spectrum
% input,
% S: mesh file, it has to have a pnt and a tri field
% n: number of mesh harmonic functions
% mode: 'full' for the full graph, 'half' if you want to do the first and
% the second half independently (this is useful if your graph is composed
% by two connected components)
% output,
% L: mesh laplacian matrix
% H: matrix containing a mesh harmonic functions per column
% d: spectrum of the negative Laplacian matrix, its units are 1/space^2
% (spatial frequencies are obtained as sqrt(d))
if nargin==2||varargin{1}==1
pnt{1} = S.pos;
tri{1} = S.tri;
elseif varargin{1}==2
pnt{1} = S.pos(1:end/2,:);
tri{1} = S.tri(1:end/2,:);
pnt{2} = S.pos(end/2+1:end,:);
tri{2} = S.tri(end/2+1:end,:) - size(pnt{1},1);
end
for j = 1:length(pnt)
if length(pnt)==2&&j == 1
disp('Computing the spectrum of the the first hemisphere')
elseif length(pnt)==2&&j == 2
disp('Computing the spectrum of the the second hemisphere')
end
[L{j},~] = mesh_laplacian(pnt{j},tri{j});
L{j} = (L{j} + L{j}')/2;
disp('Computing the spectrum of the negative Laplacian matrix')
[H{j},D] = eigs(L{j},n,'sm');
d{j} = diag(D);
disp('Diagonalization completed')
end
|
github
|
lcnhappe/happe-master
|
ft_hastoolbox.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/inverse/private/ft_hastoolbox.m
| 24,831 |
utf_8
|
43bae19e25ce108f013f1c401e497630
|
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-2013, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% 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$
% 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
if isdeployed
% it is not possible to check the presence of functions or change the path in a compiled application
status = 1;
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'
'SPM12' '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.besa.de/downloads/matlab/ and get the "BESA MATLAB Readers"'
'MATLAB2BESA' 'see http://www.besa.de/downloads/matlab/ and get the "MATLAB to BESA Export functions"'
'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'
'COMM' 'see http://www.mathworks.com/products/communications'
'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.fieldtriptoolbox.org'
'PREPROC' 'see http://www.fieldtriptoolbox.org'
'FORWARD' 'see http://www.fieldtriptoolbox.org'
'INVERSE' 'see http://www.fieldtriptoolbox.org'
'SPECEST' 'see http://www.fieldtriptoolbox.org'
'REALTIME' 'see http://www.fieldtriptoolbox.org'
'PLOTTING' 'see http://www.fieldtriptoolbox.org'
'SPIKE' 'see http://www.fieldtriptoolbox.org'
'CONNECTIVITY' 'see http://www.fieldtriptoolbox.org'
'PEER' 'see http://www.fieldtriptoolbox.org'
'PLOTTING' 'see http://www.fieldtriptoolbox.org'
'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://www.fieldtriptoolbox.org/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'
'MISC' 'various functions that were downloaded from http://www.mathworks.com/matlabcentral/fileexchange and elsewhere'
'35625-INFORMATION-THEORY-TOOLBOX' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox'
'29046-MUTUAL-INFORMATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox'
'14888-MUTUAL-INFORMATION-COMPUTATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/14888-mutual-information-computation'
'PLOT2SVG' 'see http://www.mathworks.com/matlabcentral/fileexchange/7401-scalable-vector-graphics-svg-export-of-figures'
'BRAINSUITE' 'see http://brainsuite.bmap.ucla.edu/processing/additional-tools/'
'BRAINVISA' 'see http://brainvisa.info'
'FILEEXCHANGE' 'see http://www.mathworks.com/matlabcentral/fileexchange/'
'NEURALYNX_V6' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Neuralynx (windows only)'
'NEURALYNX_V3' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Ueli Rutishauser'
'NPMK' 'see https://github.com/BlackrockMicrosystems/NPMK'
'VIDEOMEG' 'see https://github.com/andreyzhd/VideoMEG'
'WAVEFRONT' 'see http://mathworks.com/matlabcentral/fileexchange/27982-wavefront-obj-toolbox'
'NEURONE' 'see http://www.megaemg.com/support/unrestricted-downloads'
};
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);
% In case SPM8 or higher not available, allow to use fallback toolbox
fallback_toolbox='';
switch toolbox
case 'AFNI'
dependency={'BrikLoad', 'BrikInfo'};
case 'DSS'
dependency={'denss', 'dss_create_state'};
case 'EEGLAB'
dependency = 'runica';
case 'NWAY'
dependency = 'parafac';
case 'SPM'
dependency = 'spm'; % any version of SPM is fine
case 'SPM99'
dependency = {'spm', get_spm_version()==99};
case 'SPM2'
dependency = {'spm', get_spm_version()==2};
case 'SPM5'
dependency = {'spm', get_spm_version()==5};
case 'SPM8'
dependency = {'spm', get_spm_version()==8};
case 'SPM8UP' % version 8 or later, but not SPM 9X
dependency = {'spm', get_spm_version()>=8, get_spm_version()<95};
%This is to avoid crashes when trying to add SPM to the path
fallback_toolbox = 'SPM8';
case 'SPM12'
dependency = {'spm', get_spm_version()==12};
case 'MEG-PD'
dependency = {'rawdata', 'channames'};
case 'MEG-CALC'
dependency = {'megmodel', 'megfield', 'megtrans'};
case 'BIOSIG'
dependency = {'sopen', 'sread'};
case 'EEG'
dependency = {'ctf_read_res4', 'ctf_read_meg4'};
case 'EEGSF' % alternative name
dependency = {'ctf_read_res4', 'ctf_read_meg4'};
case 'MRI' % other functions in the mri section
dependency = {'avw_hdr_read', 'avw_img_read'};
case 'NEUROSHARE'
dependency = {'ns_OpenFile', 'ns_SetLibrary', ...
'ns_GetAnalogData'};
case 'ARTINIS'
dependency = {'read_artinis_oxy3'};
case 'BESA'
dependency = {'readBESAavr', 'readBESAelp', 'readBESAswf'};
case 'MATLAB2BESA'
dependency = {'besa_save2Avr', 'besa_save2Elp', 'besa_save2Swf'};
case 'EEPROBE'
dependency = {'read_eep_avr', 'read_eep_cnt'};
case 'YOKOGAWA'
dependency = @()hasyokogawa('16bitBeta6');
case 'YOKOGAWA12BITBETA3'
dependency = @()hasyokogawa('12bitBeta3');
case 'YOKOGAWA16BITBETA3'
dependency = @()hasyokogawa('16bitBeta3');
case 'YOKOGAWA16BITBETA6'
dependency = @()hasyokogawa('16bitBeta6');
case 'YOKOGAWA_MEG_READER'
dependency = @()hasyokogawa('1.4');
case 'BEOWULF'
dependency = {'evalwulf', 'evalwulf', 'evalwulf'};
case 'MENTAT'
dependency = {'pcompile', 'pfor', 'peval'};
case 'SON2'
dependency = {'SONFileHeader', 'SONChanList', 'SONGetChannel'};
case '4D-VERSION'
dependency = {'read4d', 'read4dhdr'};
case {'STATS', 'STATISTICS'}
dependency = has_license('statistics_toolbox'); % check the availability of a toolbox license
case {'OPTIM', 'OPTIMIZATION'}
dependency = has_license('optimization_toolbox'); % check the availability of a toolbox license
case {'SPLINES', 'CURVE_FITTING'}
dependency = has_license('curve_fitting_toolbox'); % check the availability of a toolbox license
case 'COMM'
dependency = {has_license('communication_toolbox'), 'de2bi'}; % also check the availability of a toolbox license
case 'SIGNAL'
dependency = {has_license('signal_toolbox'), 'window'}; % also check the availability of a toolbox license
case 'IMAGE'
dependency = has_license('image_toolbox'); % check the availability of a toolbox license
case {'DCT', 'DISTCOMP'}
dependency = has_license('distrib_computing_toolbox'); % check the availability of a toolbox license
case 'COMPILER'
dependency = has_license('compiler'); % check the availability of a toolbox license
case 'FASTICA'
dependency = 'fpica';
case 'BRAINSTORM'
dependency = 'bem_xfer';
case 'DENOISE'
dependency = {'tsr', 'sns'};
case 'CTF'
dependency = {'getCTFBalanceCoefs', 'getCTFdata'};
case 'BCI2000'
dependency = {'load_bcidat'};
case 'NLXNETCOM'
dependency = {'MatlabNetComClient', 'NlxConnectToServer', ...
'NlxGetNewCSCData'};
case 'DIPOLI'
dependency = {'dipoli.maci', 'file'};
case 'MNE'
dependency = {'fiff_read_meas_info', 'fiff_setup_read_raw'};
case 'TCP_UDP_IP'
dependency = {'pnet', 'pnet_getvar', 'pnet_putvar'};
case 'BEMCP'
dependency = {'bem_Cij_cog', 'bem_Cij_lin', 'bem_Cij_cst'};
case 'OPENMEEG'
dependency = {'om_save_tri'};
case 'PRTOOLS'
dependency = {'prversion', 'dataset', 'svc'};
case 'ITAB'
dependency = {'lcReadHeader', 'lcReadData'};
case 'BSMART'
dependency = 'bsmart';
case 'FREESURFER'
dependency = {'MRIread', 'vox2ras_0to1'};
case 'FNS'
dependency = 'elecsfwd';
case 'SIMBIO'
dependency = {'calc_stiff_matrix_val', 'sb_transfer'};
case 'VGRID'
dependency = 'vgrid';
case 'GIFTI'
dependency = 'gifti';
case 'XML4MAT'
dependency = {'xml2struct', 'xml2whos'};
case 'SQDPROJECT'
dependency = {'sqdread', 'sqdwrite'};
case 'BCT'
dependency = {'macaque71.mat', 'motif4funct_wei'};
case 'CCA'
dependency = {'ccabss'};
case 'EGI_MFF'
dependency = {'mff_getObject', 'mff_getSummaryInfo'};
case 'TOOLBOX_GRAPH'
dependency = 'toolbox_graph';
case 'NETCDF'
dependency = {'netcdf'};
case 'MYSQL'
% not sure if 'which' would work fine here, so use 'exist'
dependency = has_mex('mysql'); % this only consists of a single mex file
case 'ISO2MESH'
dependency = {'vol2surf', 'qmeshcut'};
case 'QSUB'
dependency = {'qsubfeval', 'qsubcellfun'};
case 'ENGINE'
dependency = {'enginefeval', 'enginecellfun'};
case 'DATAHASH'
dependency = {'DataHash'};
case 'IBTB'
dependency = {'make_ibtb','binr'};
case 'ICASSO'
dependency = {'icassoEst'};
case 'XUNIT'
dependency = {'initTestSuite', 'runtests'};
case 'PLEXON'
dependency = {'plx_adchan_gains', 'mexPlex'};
case '35625-INFORMATION-THEORY-TOOLBOX'
dependency = {'conditionalEntropy', 'entropy', 'jointEntropy',...
'mutualInformation' 'nmi' 'nvi' 'relativeEntropy'};
case '29046-MUTUAL-INFORMATION'
dependency = {'MI', 'license.txt'};
case '14888-MUTUAL-INFORMATION-COMPUTATION'
dependency = {'condentropy', 'demo_mi', 'estcondentropy.cpp',...
'estjointentropy.cpp', 'estpa.cpp', ...
'findjointstateab.cpp', 'makeosmex.m',...
'mutualinfo.m', 'condmutualinfo.m',...
'entropy.m', 'estentropy.cpp',...
'estmutualinfo.cpp', 'estpab.cpp',...
'jointentropy.m' 'mergemultivariables.m' };
case 'PLOT2SVG'
dependency = {'plot2svg.m', 'simulink2svg.m'};
case 'BRAINSUITE'
dependency = {'readdfs.m', 'writedfc.m'};
case 'BRAINVISA'
dependency = {'loadmesh.m', 'plotmesh.m', 'savemesh.m'};
case 'NEURALYNX_V6'
dependency = has_mex('Nlx2MatCSC');
case 'NEURALYNX_V3'
dependency = has_mex('Nlx2MatCSC_v3');
case 'NPMK'
dependency = {'OpenNSx' 'OpenNEV'};
case 'VIDEOMEG'
dependency = {'comp_tstamps' 'load_audio0123', 'load_video123'};
case 'WAVEFRONT'
dependency = {'write_wobj' 'read_wobj'};
case 'NEURONE'
dependency = {'readneurone' 'readneuronedata' 'readneuroneevents'};
% the following are FieldTrip modules/toolboxes
case 'FILEIO'
dependency = {'ft_read_header', 'ft_read_data', ...
'ft_read_event', 'ft_read_sens'};
case 'FORWARD'
dependency = {'ft_compute_leadfield', 'ft_prepare_vol_sens'};
case 'PLOTTING'
dependency = {'ft_plot_topo', 'ft_plot_mesh', 'ft_plot_matrix'};
case 'PEER'
dependency = {'peerslave', 'peermaster'};
case 'CONNECTIVITY'
dependency = {'ft_connectivity_corr', 'ft_connectivity_granger'};
case 'SPIKE'
dependency = {'ft_spiketriggeredaverage', 'ft_spiketriggeredspectrum'};
case 'FILEEXCHANGE'
dependency = is_subdir_in_fieldtrip_path('/external/fileexchange');
case {'INVERSE', 'REALTIME', 'SPECEST', 'PREPROC', ...
'COMPAT', 'STATFUN', 'TRIALFUN', 'UTILITIES/COMPAT', ...
'FILEIO/COMPAT', 'PREPROC/COMPAT', 'FORWARD/COMPAT', ...
'PLOTTING/COMPAT', 'TEMPLATE/LAYOUT', 'TEMPLATE/ANATOMY' ,...
'TEMPLATE/HEADMODEL', 'TEMPLATE/ELECTRODE', ...
'TEMPLATE/NEIGHBOURS', 'TEMPLATE/SOURCEMODEL'}
dependency = is_subdir_in_fieldtrip_path(toolbox);
otherwise
if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end
dependency = false;
end
status = is_present(dependency);
if ~status && ~isempty(fallback_toolbox)
% in case of SPM8UP
toolbox = fallback_toolbox;
end
% 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 && isdir(prefix)
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for windows computers in the Donders Centre for Cognitive Neuroimaging
prefix = 'h:\common\matlab';
if ~status && isdir(prefix)
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
ft_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);
status = 1;
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;
elseif (~isempty(regexp(toolbox, 'spm5$', 'once')) || ~isempty(regexp(toolbox, 'spm8$', 'once')) || ~isempty(regexp(toolbox, 'spm12$', 'once'))) && exist([toolbox 'b'], 'dir')
status = myaddpath([toolbox 'b'], silent);
else
status = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function path = unixpath(path)
%path(path=='\') = '/'; % replace backward slashes with forward slashes
path = strrep(path,'\','/');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = is_subdir_in_fieldtrip_path(toolbox_name)
fttrunkpath = unixpath(fileparts(which('ft_defaults')));
fttoolboxpath = fullfile(fttrunkpath, lower(toolbox_name));
needle=[pathsep fttoolboxpath pathsep];
haystack = [pathsep path() pathsep];
status = ~isempty(findstr(needle, haystack));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = has_mex(name)
full_name=[name '.' mexext];
status = (exist(full_name, 'file')==3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function v = get_spm_version()
if ~is_present('spm')
v=NaN;
return
end
version_str = spm('ver');
token = regexp(version_str,'(\d*)','tokens');
v = str2num([token{:}{:}]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = has_license(toolbox_name)
status = license('checkout', toolbox_name)==1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = is_present(dependency)
if iscell(dependency)
% use recursion
status = all(cellfun(@is_present,dependency));
elseif islogical(dependency)
% boolean
status = all(dependency);
elseif ischar(dependency)
% name of a function
status = is_function_present_in_search_path(dependency);
elseif isa(dependency, 'function_handle')
status = dependency();
else
assert(false,'this should not happen');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = is_function_present_in_search_path(function_name)
w = which(function_name);
% must be in path and not a variable
status = ~isempty(w) && ~isequal(w, 'variable');
|
github
|
lcnhappe/happe-master
|
ft_inverse_beamformer_dics.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/inverse/new/ft_inverse_beamformer_dics.m
| 13,353 |
utf_8
|
79c230d4fcdc8529ee9f1f03b205f5fd
|
function [estimate] = ft_inverse_beamformer_dics(leadfield, Cf, varargin)
% FT_INVERSE_BEAMFORMER_DICS estimates the source power or source
% coherence according to the Dynamic Imaging of Coherent Sources
% method.
%
% Use as
% estimate = ft_inverse_beamformer_dics(leadfield, Cf, ...)
% where
% leadfield = leadfield of the source of interest or a cell-array with leadfields for multiple sources
% Cf = cross-spectral density matrix of the data
% and
% estimate = structure with the estimated source parameters
%
% Additional options should be specified in key-value pairs and can be
% 'Pr' = power of the external reference channel
% 'Cr' = cross spectral density between all data channels and the external reference channel
% 'refdip' = location of dipole with which coherence is computed
% 'lambda' = regularisation parameter
% 'powmethod' = can be 'trace' or 'lambda1'
% 'feedback' = give ft_progress indication, can be 'text', 'gui' or 'none'
% 'fixedori' = use fixed or free orientation, can be 'yes' or 'no'
% 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no'
% 'realfilter' = construct a real-valued filter, can be 'yes' or 'no'
% 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no'
% 'keepleadfield' = remember the forward computation, can be 'yes' or 'no'
% 'keepcsd' = remember the estimated cross-spectral density, can be 'yes' or 'no'
%
% This implements Joachim Gross et al. 2001
% Copyright (C) 2003-2010, Robert Oostenveld
% these optional settings do not have defaults
Pr = keyval('Pr', varargin);
Cr = keyval('Cr', varargin);
refdip = keyval('refdip', varargin);
powmethod = keyval('powmethod', varargin); % the default for this is set below
realfilter = keyval('realfilter', varargin); % the default for this is set below
% these optional settings have defaults
feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'text'; end
keepcsd = keyval('keepcsd', varargin); if isempty(keepcsd), keepcsd = 'no'; end
keepfilter = keyval('keepfilter', varargin); if isempty(keepfilter), keepfilter = 'no'; end
keepleadfield = keyval('keepleadfield', varargin); if isempty(keepleadfield), keepleadfield = 'no'; end
lambda = keyval('lambda', varargin); if isempty(lambda ), lambda = 0; end
projectnoise = keyval('projectnoise', varargin); if isempty(projectnoise), projectnoise = 'yes'; end
fixedori = keyval('fixedori', varargin); if isempty(fixedori), fixedori = 'no'; end
% convert the yes/no arguments to the corresponding logical values
% FIXME use istrue
keepcsd = strcmp(keepcsd, 'yes');
keepfilter = strcmp(keepfilter, 'yes');
keepleadfield = strcmp(keepleadfield, 'yes');
projectnoise = strcmp(projectnoise, 'yes');
fixedori = strcmp(fixedori, 'yes');
% FIXME besides regular/complex lambda1, also implement a real version
% default is to use the largest singular value of the csd matrix, see Gross 2001
if isempty(powmethod)
powmethod = 'lambda1';
end
% default is to be consistent with the original description of DICS in Gross 2001
if isempty(realfilter)
realfilter = 'no';
end
% use these two logical flags instead of doing the string comparisons each time again
powtrace = strcmp(powmethod, 'trace');
powlambda1 = strcmp(powmethod, 'lambda1');
% dics has the following sub-methods, which depend on the additional input arguments
if ~isempty(Cr) && ~isempty(Pr) && isempty(refdip)
% compute cortico-muscular coherence, using reference cross spectral density
submethod = 'dics_refchan';
elseif isempty(Cr) && isempty(Pr) && ~isempty(refdip)
% compute cortico-cortical coherence with a dipole at the reference position
submethod = 'dics_refdip';
elseif isempty(Cr) && isempty(Pr) && isempty(refdip)
% only compute power of a dipole at the grid positions
submethod = 'dics_power';
else
error('invalid combination of input arguments for dics');
end
if ~iscell(leadfield)
% the leadfield specifies a single source
leadfield = {leadfield};
end
ndipoles = length(leadfield);
if ~isempty(Cr)
% ensure that the cross-spectral density with the reference signal is a column matrix
Cr = Cr(:);
end
isrankdeficient = (rank(Cf)<size(Cf,1));
if isrankdeficient
warning('cross-spectral density matrix is rank deficient')
end
% it is difficult to give a quantitative estimate of lambda, therefore also
% support relative (percentage) measure that can be specified as string (e.g. '10%')
if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%'
ratio = sscanf(lambda, '%f%%');
ratio = ratio/100;
lambda = ratio * trace(Cf)/size(Cf,1);
end
if projectnoise
% estimate the noise power, which is further assumed to be equal and uncorrelated over channels
if isrankdeficient
% estimated noise floor is equal to or higher than lambda
noise = lambda;
else
% estimate the noise level in the covariance matrix by the smallest singular value
noise = svd(Cf);
noise = noise(end);
% estimated noise floor is equal to or higher than lambda
noise = max(noise, lambda);
end
end
% the inverse only has to be computed once for all dipoles
if strcmp(realfilter, 'yes')
% the filter is computed using only the leadfield and the inverse covariance or CSD matrix
% therefore using the real-valued part of the CSD matrix here ensures a real-valued filter
invCf = pinv(real(Cf) + lambda * eye(size(Cf)));
else
invCf = pinv(Cf + lambda * eye(size(Cf)));
end
% start the scanning with the proper metric
ft_progress('init', feedback, 'scanning grid');
switch submethod
case 'dics_power'
% only compute power of a dipole at the grid positions
for i=1:ndipoles
lf = leadfield{i};
if fixedori
% compute the leadfield for the optimal dipole orientation
% subsequently the leadfield for only that dipole orientation will be used for the final filter computation
filt = pinv(lf' * invCf * lf) * lf' * invCf;
[u, s, v] = svd(real(filt * Cf * ctranspose(filt)));
maxpowori = u(:,1);
eta = s(1,1)./s(2,2);
lf = lf * maxpowori;
estimate.ori{i} = maxpowori;
estimate.eta{i} = eta;
end
% construct the spatial filter
filt = pinv(lf' * invCf * lf) * lf' * invCf; % Gross eqn. 3, use PINV/SVD to cover rank deficient leadfield
csd = filt * Cf * ctranspose(filt); % Gross eqn. 4 and 5
% assign the output values
if powlambda1
estimate.pow(i) = lambda1(csd); % compute the power at the dipole location, Gross eqn. 8
elseif powtrace
estimate.pow(i) = real(trace(csd)); % compute the power at the dipole location
end
if keepcsd
estimate.csd{i} = csd;
end
if projectnoise
if powlambda1
estimate.noise(i) = noise * lambda1(filt * ctranspose(filt));
elseif powtrace
estimate.noise(i) = noise * real(trace(filt * ctranspose(filt)));
end
if keepcsd
estimate.noisecsd{i} = noise * filt * ctranspose(filt);
end
end
if keepfilter
estimate.filter{i} = filt;
end
if keepleadfield
estimate.leadfield{i} = lf;
end
ft_progress(i/ndipoles, 'scanning grid %d/%d\n', i, ndipoles);
end
case 'dics_refchan'
% compute cortico-muscular coherence, using reference cross spectral density
for i=1:ndipoles
% get the leadfield for this source
lf = leadfield{i};
if fixedori
% compute the leadfield for the optimal dipole orientation
% subsequently the leadfield for only that dipole orientation will be used for the final filter computation
filt = pinv(lf' * invCf * lf) * lf' * invCf;
[u, s, v] = svd(real(filt * Cf * ctranspose(filt)));
maxpowori = u(:,1);
lf = lf * maxpowori;
estimate.ori{i} = maxpowori;
end
% construct the spatial filter
filt = pinv(lf' * invCf * lf) * lf' * invCf; % use PINV/SVD to cover rank deficient leadfield
if powlambda1
[pow, ori] = lambda1(filt * Cf * ctranspose(filt)); % compute the power and orientation at the dipole location, Gross eqn. 4, 5 and 8
elseif powtrace
pow = real(trace(filt * Cf * ctranspose(filt))); % compute the power at the dipole location
end
csd = filt*Cr; % Gross eqn. 6
if powlambda1
% FIXME this should use the dipole orientation with maximum power
coh = lambda1(csd)^2 / (pow * Pr); % Gross eqn. 9
elseif powtrace
coh = norm(csd)^2 / (pow * Pr);
end
estimate.pow(i) = pow;
estimate.coh(i) = coh;
if keepcsd
estimate.csd{i} = csd;
end
if projectnoise
if powlambda1
estimate.noise(i) = noise * lambda1(filt * ctranspose(filt));
elseif powtrace
estimate.noise(i) = noise * real(trace(filt * ctranspose(filt)));
end
if keepcsd
estimate.noisecsd{i} = noise * filt * ctranspose(filt);
end
end
if keepfilter
estimate.filter{i} = filt;
end
ft_progress(i/ndipoles, 'scanning grid %d/%d\n', i, ndipoles);
end
case 'dics_refdip'
if fixedori
error('fixed orientations are not supported for beaming cortico-cortical coherence');
end
% get the leadfield of the reference source
lf1 = refdip;
% construct the spatial filter for the first (reference) dipole location
filt1 = pinv(lf1' * invCf * lf1) * lf1' * invCf; % use PINV/SVD to cover rank deficient leadfield
if powlambda1
Pref = lambda1(filt1 * Cf * ctranspose(filt1)); % compute the power at the first dipole location, Gross eqn. 8
elseif powtrace
Pref = real(trace(filt1 * Cf * ctranspose(filt1))); % compute the power at the first dipole location
end
for i=1:ndipoles
% get the leadfield for the second source, i.e. the one that is being scanned
lf2 = leadfield{i};
% construct the spatial filter for the second source
filt2 = pinv(lf2' * invCf * lf2) * lf2' * invCf; % use PINV/SVD to cover rank deficient leadfield
csd = filt1 * Cf * ctranspose(filt2); % compute the cross spectral density between the two dipoles, Gross eqn. 4
if powlambda1
pow = lambda1(filt2 * Cf * ctranspose(filt2)); % compute the power at the second dipole location, Gross eqn. 8
elseif powtrace
pow = real(trace(filt2 * Cf * ctranspose(filt2))); % compute the power at the second dipole location
end
if powlambda1
coh = lambda1(csd)^2 / (pow * Pref); % compute the coherence between the first and second dipole
elseif powtrace
coh = real(trace((csd)))^2 / (pow * Pref); % compute the coherence between the first and second dipole
end
estimate.pow(i) = pow;
estimate.coh(i) = coh;
if keepcsd
estimate.csd{i} = csd;
end
if projectnoise
if powlambda1
estimate.noise(i) = noise * lambda1(filt2 * ctranspose(filt2));
elseif powtrace
estimate.noise(i) = noise * real(trace(filt2 * ctranspose(filt2)));
end
if keepcsd
estimate.noisecsd{i} = noise * filt2 * ctranspose(filt2);
end
end
ft_progress(i/ndipoles, 'scanning grid %d/%d\n', i, ndipoles);
end
end % switch submethod
ft_progress('close');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to obtain the largest singular value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [s, ori] = lambda1(x)
% determine the largest singular value, which corresponds to the power along the dominant direction
[u, s, v] = svd(x);
s = s(1);
ori = u(:,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute the pseudo inverse. This is the same as the
% standard Matlab function, except that the default tolerance is twice as
% high.
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision$ $Date: 2009/06/17 13:40:37 $
% default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = pinv(A,varargin)
[m,n] = size(A);
if n > m
X = pinv(A',varargin{:})';
else
[U,S,V] = svd(A,0);
if m > 1, s = diag(S);
elseif m == 1, s = S(1);
else s = 0;
end
if nargin == 2
tol = varargin{1};
else
tol = 10 * max(m,n) * max(s) * eps;
end
r = sum(s > tol);
if (r == 0)
X = zeros(size(A'),class(A));
else
s = diag(ones(r,1)./s(1:r));
X = V(:,1:r)*s*U(:,1:r)';
end
end
|
github
|
lcnhappe/happe-master
|
firfiltdcpadded.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/firfiltdcpadded.m
| 2,137 |
utf_8
|
b21b4207bf032e32cc6f0597db3cb4fe
|
% firfiltdcpadded() - Pad data with DC constant and filter
%
% Usage:
% >> data = firfiltdcpadded(data, b, causal);
%
% Inputs:
% data - raw data
% b - vector of filter coefficients
% causal - boolean perform causal filtering {default 0}
%
% Outputs:
% data - smoothed data
%
% Note:
% firfiltdcpadded always operates (pads, filters) along first dimension.
% Not memory optimized.
%
% Author: Andreas Widmann, University of Leipzig, 2013
%
% See also:
% firfiltsplit
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2013 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [ data ] = firfiltdcpadded(b, data, causal)
% Defaults
if nargin < 3 || isempty(causal)
causal = 0;
end
% Check arguments
if nargin < 2
error('Not enough input arguments.');
end
% Filter's group delay
if mod(length(b), 2) ~= 1
error('Filter order is not even.');
end
groupDelay = (length(b) - 1) / 2;
b = double(b); % Filter with double precision
% Pad data with DC constant
if causal
startPad = repmat(data(1, :), [2 * groupDelay 1]);
endPad = [];
else
startPad = repmat(data(1, :), [groupDelay 1]);
endPad = repmat(data(end, :), [groupDelay 1]);
end
% Filter data
data = filter(b, 1, double([startPad; data; endPad])); % Pad and filter with double precision
% Remove padded data
data = data(2 * groupDelay + 1:end, :);
end
|
github
|
lcnhappe/happe-master
|
minphaserceps.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/minphaserceps.m
| 1,275 |
utf_8
|
7b751637e7eed71e29f91a4ef6b586e6
|
% rcepsminphase() - Convert FIR filter coefficient to minimum phase
%
% Usage:
% >> b = minphaserceps(b);
%
% Inputs:
% b - FIR filter coefficients
%
% Outputs:
% bMinPhase - minimum phase FIR filter coefficients
%
% Author: Andreas Widmann, University of Leipzig, 2013
%
% References:
% [1] Smith III, O. J. (2007). Introduction to Digital Filters with Audio
% Applications. W3K Publishing. Retrieved Nov 11 2013, from
% https://ccrma.stanford.edu/~jos/fp/Matlab_listing_mps_m.html
% [2] Vetter, K. (2013, Nov 11). Long FIR filters with low latency.
% Retrieved Nov 11 2013, from
% http://www.katjaas.nl/minimumphase/minimumphase.html
function [bMinPhase] = minphaserceps(b)
% Line vector
b = b(:)';
n = length(b);
upsamplingFactor = 1e3; % Impulse response upsampling/zero padding to reduce time-aliasing
nFFT = 2^ceil(log2(n * upsamplingFactor)); % Power of 2
clipThresh = 1e-8; % -160 dB
% Spectrum
s = abs(fft(b, nFFT));
s(s < clipThresh) = clipThresh; % Clip spectrum to reduce time-aliasing
% Real cepstrum
c = real(ifft(log(s)));
% Fold
c = [c(1) [c(2:nFFT / 2) 0] + conj(c(nFFT:-1:nFFT / 2 + 1)) zeros(1, nFFT / 2 - 1)];
% Minimum phase
bMinPhase = real(ifft(exp(fft(c))));
% Remove zero-padding
bMinPhase = bMinPhase(1:n);
|
github
|
lcnhappe/happe-master
|
firws.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/firws.m
| 3,219 |
utf_8
|
0ab4c517238d31712ba1d97ab2497f45
|
%firws() - Designs windowed sinc type I linear phase FIR filter
%
% Usage:
% >> b = firws(m, f);
% >> b = firws(m, f, w);
% >> b = firws(m, f, t);
% >> b = firws(m, f, t, w);
%
% Inputs:
% m - filter order (mandatory even)
% f - vector or scalar of cutoff frequency/ies (-6 dB;
% pi rad / sample)
%
% Optional inputs:
% w - vector of length m + 1 defining window {default blackman}
% t - 'high' for highpass, 'stop' for bandstop filter {default low-/
% bandpass}
%
% Output:
% b - filter coefficients
%
% Example:
% fs = 500; cutoff = 0.5; tbw = 1;
% m = pop_firwsord('hamming', fs, tbw);
% b = firws(m, cutoff / (fs / 2), 'high', windows('hamming', m + 1));
%
% References:
% Smith, S. W. (1999). The scientist and engineer's guide to digital
% signal processing (2nd ed.). San Diego, CA: California Technical
% Publishing.
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% pop_firws, pop_firwsord, pop_kaiserbeta, windows
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [b a] = firws(m, f, t, w)
a = 1;
if nargin < 2
error('Not enough input arguments');
end
if length(m) > 1 || ~isnumeric(m) || ~isreal(m) || mod(m, 2) ~= 0 || m < 2
error('Filter order must be a real, even, positive integer.');
end
f = f / 2;
if any(f <= 0) || any(f >= 0.5)
error('Frequencies must fall in range between 0 and 1.');
end
if nargin < 3 || isempty(t)
t = '';
end
if nargin < 4 || isempty(w)
if ~isempty(t) && ~ischar(t)
w = t;
t = '';
else
w = windows('blackman', (m + 1));
end
end
w = w(:)'; % Make window row vector
b = fkernel(m, f(1), w);
if length(f) == 1 && strcmpi(t, 'high')
b = fspecinv(b);
end
if length(f) == 2
b = b + fspecinv(fkernel(m, f(2), w));
if isempty(t) || ~strcmpi(t, 'stop')
b = fspecinv(b);
end
end
% Compute filter kernel
function b = fkernel(m, f, w)
m = -m / 2 : m / 2;
b(m == 0) = 2 * pi * f; % No division by zero
b(m ~= 0) = sin(2 * pi * f * m(m ~= 0)) ./ m(m ~= 0); % Sinc
b = b .* w; % Window
b = b / sum(b); % Normalization to unity gain at DC
% Spectral inversion
function b = fspecinv(b)
b = -b;
b(1, (length(b) - 1) / 2 + 1) = b(1, (length(b) - 1) / 2 + 1) + 1;
|
github
|
lcnhappe/happe-master
|
pop_firma.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/pop_firma.m
| 3,356 |
utf_8
|
e6d49147b8406a5ac3fed31ab0809194
|
% pop_firma() - Filter data using moving average FIR filter
%
% Usage:
% >> [EEG, com] = pop_firma(EEG); % pop-up window mode
% >> [EEG, com] = pop_firma(EEG, 'forder', order);
%
% Inputs:
% EEG - EEGLAB EEG structure
% 'forder' - scalar filter order. Mandatory even
%
% Outputs:
% EEG - filtered EEGLAB EEG structure
% com - history string
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% firfilt, plotfresp
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com] = pop_firma(EEG, varargin)
com = '';
if nargin < 1
help pop_firma;
return;
end
if isempty(EEG.data)
error('Cannot process empty dataset');
end
if nargin < 2
drawnow;
uigeom = {[1 1 1] [1] [1 1 1]};
uilist = {{'style' 'text' 'string' 'Filter order (mandatory even):'} ...
{'style' 'edit' 'string' '' 'tag' 'forderedit'} {} ...
{} ...
{} {} {'Style' 'pushbutton' 'string' 'Plot filter responses' 'callback' {@complot, EEG.srate}}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_firma'')', 'Filter the data -- pop_firma()');
if length(result) == 0, return; end
if ~isempty(result{1})
args = [{'forder'} {str2num(result{1})}];
else
error('Not enough input arguments');
end
else
args = varargin;
end
% Convert args to structure
args = struct(args{:});
% Filter coefficients
b = ones(1, args.forder + 1) / (args.forder + 1);
% Filter
disp('pop_firma() - filtering the data');
EEG = firfilt(EEG, b);
% History string
com = sprintf('%s = pop_firma(%s', inputname(1), inputname(1));
for c = fieldnames(args)'
if ischar(args.(c{:}))
com = [com sprintf(', ''%s'', ''%s''', c{:}, args.(c{:}))];
else
com = [com sprintf(', ''%s'', %s', c{:}, mat2str(args.(c{:})))];
end
end
com = [com ');'];
% Callback plot filter properties
function complot(obj, evt, srate)
args.forder = str2num(get(findobj(gcbf, 'tag', 'forderedit'), 'string'));
if isempty(args.forder)
error('Not enough input arguments');
end
b = ones(1, args.forder + 1) / (args.forder + 1);
H = findobj('tag', 'filter responses', 'type', 'figure');
if ~isempty(H)
figure(H);
else
H = figure;
set(H, 'color', [.93 .96 1], 'tag', 'filter responses');
end
plotfresp(b, 1, [], srate);
|
github
|
lcnhappe/happe-master
|
pop_firpm.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/pop_firpm.m
| 7,885 |
utf_8
|
c7719de703135804f12c5877e899956b
|
% pop_firpm() - Filter data using Parks-McClellan FIR filter
%
% Usage:
% >> [EEG, com, b] = pop_firpm(EEG); % pop-up window mode
% >> [EEG, com, b] = pop_firpm(EEG, 'key1', value1, 'key2', ...
% value2, 'keyn', valuen);
%
% Inputs:
% EEG - EEGLAB EEG structure
% 'fcutoff' - vector or scalar of cutoff frequency/ies (~-6 dB; Hz)
% 'ftrans' - scalar transition band width
% 'ftype' - char array filter type. 'bandpass', 'highpass',
% 'lowpass', or 'bandstop'
% 'forder' - scalar filter order. Mandatory even
%
% Optional inputs:
% 'wtpass' - scalar passband weight
% 'wtstop' - scalar stopband weight
%
% Outputs:
% EEG - filtered EEGLAB EEG structure
% com - history string
% b - filter coefficients
%
% Note:
% Requires the signal processing toolbox.
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% firfilt, pop_firpmord, plotfresp, firpm, firpmord
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com, b] = pop_firpm(EEG, varargin)
if ~(exist('firpm', 'file') == 2 || exist('firpm', 'file') == 6)
error('Requires the signal processing toolbox.');
end
com = '';
if nargin < 1
help pop_firpm;
return;
end
if isempty(EEG.data)
error('Cannot process empty dataset');
end
if nargin < 2
drawnow;
ftypes = {'bandpass' 'highpass' 'lowpass' 'bandstop'};
uigeom = {[1 0.75 0.75] [1 0.75 0.75] [1 0.75 0.75] 1 [1 0.75 0.75] [1 0.75 0.75] [1 0.75 0.75] 1 [1 0.75 0.75]};
uilist = {{'Style' 'text' 'String' 'Cutoff frequency(ies) [hp lp] (~-6 dB; Hz):'} ...
{'Style' 'edit' 'String' '' 'Tag' 'fcutoffedit'} {} ...
{'Style' 'text' 'String' 'Transition band width:'} ...
{'Style' 'edit' 'String' '' 'Tag' 'ftransedit'} {} ...
{'Style' 'text' 'String' 'Filter type:'} ...
{'Style' 'popupmenu' 'String' ftypes 'Tag' 'ftypepop'} {} ...
{} ...
{'Style' 'text' 'String' 'Passband weight:'} ...
{'Style' 'edit' 'String' '' 'Tag' 'wtpassedit'} {} ...
{'Style' 'text' 'String' 'Stopband weight:'} ...
{'Style' 'edit' 'String' '' 'Tag' 'wtstopedit'} {} ...
{'Style' 'text' 'String' 'Filter order (mandatory even):'} ...
{'Style' 'edit' 'String' '' 'Tag' 'forderedit'} ...
{'Style' 'pushbutton' 'String' 'Estimate' 'Tag' 'orderpush' 'Callback' {@comcb, ftypes, EEG.srate}} ...
{} ...
{} {} {'Style' 'pushbutton' 'String', 'Plot filter responses' 'Tag' 'plotpush' 'Callback' {@comcb, ftypes, EEG.srate}}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_firpm'')', 'Filter the data -- pop_firpm()');
if isempty(result), return; end
args = {};
if ~isempty(result{1})
args = [args {'fcutoff'} {str2num(result{1})}];
end
if ~isempty(result{2})
args = [args {'ftrans'} {str2double(result{2})}];
end
args = [args {'ftype'} ftypes(result{3})];
if ~isempty(result{4})
args = [args {'wtpass'} {str2double(result{4})}];
end
if ~isempty(result{5})
args = [args {'wtstop'} {str2double(result{5})}];
end
if ~isempty(result{6})
args = [args {'forder'} {str2double(result{6})}];
end
else
args = varargin;
end
% Convert args to structure
args = struct(args{:});
c = parseargs(args, EEG.srate);
if ~isfield(args, 'forder') || isempty(args.forder)
error('Not enough input arguments');
end
b = firpm(args.forder, c{:});
% Filter
disp('pop_firpm() - filtering the data');
EEG = firfilt(EEG, b);
% History string
com = sprintf('%s = pop_firpm(%s', inputname(1), inputname(1));
for c = fieldnames(args)'
if ischar(args.(c{:}))
com = [com sprintf(', ''%s'', ''%s''', c{:}, args.(c{:}))];
else
com = [com sprintf(', ''%s'', %s', c{:}, mat2str(args.(c{:})))];
end
end
com = [com ');'];
% Convert structure args to cell array firpm parameters
function c = parseargs(args, srate)
if ~isfield(args, 'fcutoff') || ~isfield(args, 'ftype') || ~isfield(args, 'ftrans') || isempty(args.fcutoff) || isempty(args.ftype) || isempty(args.ftrans)
error('Not enough input arguments.');
end
% Cutoff frequencies
args.fcutoff = [args.fcutoff - args.ftrans / 2 args.fcutoff + args.ftrans / 2];
args.fcutoff = sort(args.fcutoff / (srate / 2)); % Sorting and normalization
if any(args.fcutoff < 0)
error('Cutoff frequencies - transition band width / 2 must not be < DC');
elseif any(args.fcutoff > 1)
error('Cutoff frequencies + transition band width / 2 must not be > Nyquist');
end
c = {[0 args.fcutoff 1]};
% Filter type
switch args.ftype
case 'bandpass'
c = [c {[0 0 1 1 0 0]}];
case 'bandstop'
c = [c {[1 1 0 0 1 1]}];
case 'highpass'
c = [c {[0 0 1 1]}];
case 'lowpass'
c = [c {[1 1 0 0]}];
end
%Filter weights
if all(isfield(args, {'wtpass', 'wtstop'})) && ~isempty(args.wtpass) && ~isempty(args.wtstop)
w = [args.wtstop args.wtpass];
c{3} = w(c{2}(1:2:end) + 1);
end
% Callback
function comcb(obj, evt, ftypes, srate)
args.fcutoff = str2num(get(findobj(gcbf, 'Tag', 'fcutoffedit'), 'String'));
args.ftype = ftypes{get(findobj(gcbf, 'Tag', 'ftypepop'), 'Value')};
args.ftrans = str2double(get(findobj(gcbf, 'Tag', 'ftransedit'), 'String'));
args.wtpass = str2double(get(findobj(gcbf, 'Tag', 'wtpassedit'), 'String'));
args.wtstop = str2double(get(findobj(gcbf, 'Tag', 'wtstopedit'), 'String'));
c = parseargs(args, srate);
switch get(obj, 'Tag')
case 'orderpush'
[args.forder, args.wtpass, args.wtstop] = pop_firpmord(c{1}(2:end - 1), c{2}(1:2:end));
if ~isempty(args.forder) || ~isempty(args.wtpass) || ~isempty(args.wtstop)
set(findobj(gcbf, 'Tag', 'forderedit'), 'String', ceil(args.forder / 2) * 2);
set(findobj(gcbf, 'Tag', 'wtpassedit'), 'String', args.wtpass);
set(findobj(gcbf, 'Tag', 'wtstopedit'), 'String', args.wtstop);
end
case 'plotpush'
args.forder = str2double(get(findobj(gcbf, 'Tag', 'forderedit'), 'String'));
if isempty(args.forder)
error('Not enough input arguments');
end
b = firpm(args.forder, c{:});
H = findobj('Tag', 'filter responses', 'Type', 'figure');
if ~isempty(H)
figure(H);
else
H = figure;
set(H, 'color', [.93 .96 1], 'Tag', 'filter responses');
end
plotfresp(b, 1, [], srate);
end
|
github
|
lcnhappe/happe-master
|
pop_eegfiltnew.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/pop_eegfiltnew.m
| 8,458 |
utf_8
|
568c652401a53a0b370d55e248775e5a
|
% pop_eegfiltnew() - Filter data using Hamming windowed sinc FIR filter
%
% Usage:
% >> [EEG, com, b] = pop_eegfiltnew(EEG); % pop-up window mode
% >> [EEG, com, b] = pop_eegfiltnew(EEG, locutoff, hicutoff, filtorder,
% revfilt, usefft, plotfreqz, minphase);
%
% Inputs:
% EEG - EEGLAB EEG structure
% locutoff - lower edge of the frequency pass band (Hz)
% {[]/0 -> lowpass}
% hicutoff - higher edge of the frequency pass band (Hz)
% {[]/0 -> highpass}
%
% Optional inputs:
% filtorder - filter order (filter length - 1). Mandatory even
% revfilt - [0|1] invert filter (from bandpass to notch filter)
% {default 0 (bandpass)}
% usefft - ignored (backward compatibility only)
% plotfreqz - [0|1] plot filter's frequency and phase response
% {default 0}
% minphase - scalar boolean minimum-phase converted causal filter
% {default false}
%
% Outputs:
% EEG - filtered EEGLAB EEG structure
% com - history string
% b - filter coefficients
%
% Note:
% pop_eegfiltnew is intended as a replacement for the deprecated
% pop_eegfilt function. Required filter order/transition band width is
% estimated with the following heuristic in default mode: transition band
% width is 25% of the lower passband edge, but not lower than 2 Hz, where
% possible (for bandpass, highpass, and bandstop) and distance from
% passband edge to critical frequency (DC, Nyquist) otherwise. Window
% type is hardcoded to Hamming. Migration to windowed sinc FIR filters
% (pop_firws) is recommended. pop_firws allows user defined window type
% and estimation of filter order by user defined transition band width.
%
% Author: Andreas Widmann, University of Leipzig, 2012
%
% See also:
% firfilt, firws, windows
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2008 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com, b] = pop_eegfiltnew(EEG, locutoff, hicutoff, filtorder, revfilt, usefft, plotfreqz, minphase)
com = '';
if nargin < 1
help pop_eegfiltnew;
return
end
if isempty(EEG.data)
error('Cannot filter empty dataset.');
end
% GUI
if nargin < 2
geometry = {[3, 1], [3, 1], [3, 1], 1, 1, 1, 1};
geomvert = [1 1 1 2 1 1 1];
uilist = {{'style', 'text', 'string', 'Lower edge of the frequency pass band (Hz)'} ...
{'style', 'edit', 'string', ''} ...
{'style', 'text', 'string', 'Higher edge of the frequency pass band (Hz)'} ...
{'style', 'edit', 'string', ''} ...
{'style', 'text', 'string', 'FIR Filter order (Mandatory even. Default is automatic*)'} ...
{'style', 'edit', 'string', ''} ...
{'style', 'text', 'string', {'*See help text for a description of the default filter order heuristic.', 'Manual definition is recommended.'}} ...
{'style', 'checkbox', 'string', 'Notch filter the data instead of pass band', 'value', 0} ...
{'Style', 'checkbox', 'String', 'Use minimum-phase converted causal filter (non-linear!; beta)', 'Value', 0} ...
{'style', 'checkbox', 'string', 'Plot frequency response', 'value', 1}};
result = inputgui('geometry', geometry, 'geomvert', geomvert, 'uilist', uilist, 'title', 'Filter the data -- pop_eegfiltnew()', 'helpcom', 'pophelp(''pop_eegfiltnew'')');
if isempty(result), return; end
locutoff = str2num(result{1});
hicutoff = str2num(result{2});
filtorder = str2num(result{3});
revfilt = result{4};
minphase = result{5};
plotfreqz = result{6};
usefft = [];
else
if nargin < 3
hicutoff = [];
end
if nargin < 4
filtorder = [];
end
if nargin < 5 || isempty(revfilt)
revfilt = 0;
end
if nargin < 6
usefft = [];
elseif usefft == 1
error('FFT filtering not supported. Argument is provided for backward compatibility in command line mode only.')
end
if nargin < 7 || isempty(plotfreqz)
plotfreqz = 0;
end
if nargin < 8 || isempty(minphase)
minphase = 0;
end
end
% Constants
TRANSWIDTHRATIO = 0.25;
fNyquist = EEG.srate / 2;
% Check arguments
if locutoff == 0, locutoff = []; end
if hicutoff == 0, hicutoff = []; end
if isempty(hicutoff) % Convert highpass to inverted lowpass
hicutoff = locutoff;
locutoff = [];
revfilt = ~revfilt;
end
edgeArray = sort([locutoff hicutoff]);
if isempty(edgeArray)
error('Not enough input arguments.');
end
if any(edgeArray < 0 | edgeArray >= fNyquist)
error('Cutoff frequency out of range');
end
if ~isempty(filtorder) && (filtorder < 2 || mod(filtorder, 2) ~= 0)
error('Filter order must be a real, even, positive integer.')
end
% Max stop-band width
maxTBWArray = edgeArray; % Band-/highpass
if revfilt == 0 % Band-/lowpass
maxTBWArray(end) = fNyquist - edgeArray(end);
elseif length(edgeArray) == 2 % Bandstop
maxTBWArray = diff(edgeArray) / 2;
end
maxDf = min(maxTBWArray);
% Transition band width and filter order
if isempty(filtorder)
% Default filter order heuristic
if revfilt == 1 % Highpass and bandstop
df = min([max([maxDf * TRANSWIDTHRATIO 2]) maxDf]);
else % Lowpass and bandpass
df = min([max([edgeArray(1) * TRANSWIDTHRATIO 2]) maxDf]);
end
filtorder = 3.3 / (df / EEG.srate); % Hamming window
filtorder = ceil(filtorder / 2) * 2; % Filter order must be even.
else
df = 3.3 / filtorder * EEG.srate; % Hamming window
filtorderMin = ceil(3.3 ./ ((maxDf * 2) / EEG.srate) / 2) * 2;
filtorderOpt = ceil(3.3 ./ (maxDf / EEG.srate) / 2) * 2;
if filtorder < filtorderMin
error('Filter order too low. Minimum required filter order is %d. For better results a minimum filter order of %d is recommended.', filtorderMin, filtorderOpt)
elseif filtorder < filtorderOpt
warning('firfilt:filterOrderLow', 'Transition band is wider than maximum stop-band width. For better results a minimum filter order of %d is recommended. Reported might deviate from effective -6dB cutoff frequency.', filtorderOpt)
end
end
filterTypeArray = {'lowpass', 'bandpass'; 'highpass', 'bandstop (notch)'};
fprintf('pop_eegfiltnew() - performing %d point %s filtering.\n', filtorder + 1, filterTypeArray{revfilt + 1, length(edgeArray)})
fprintf('pop_eegfiltnew() - transition band width: %.4g Hz\n', df)
fprintf('pop_eegfiltnew() - passband edge(s): %s Hz\n', mat2str(edgeArray))
% Passband edge to cutoff (transition band center; -6 dB)
dfArray = {df, [-df, df]; -df, [df, -df]};
cutoffArray = edgeArray + dfArray{revfilt + 1, length(edgeArray)} / 2;
fprintf('pop_eegfiltnew() - cutoff frequency(ies) (-6 dB): %s Hz\n', mat2str(cutoffArray))
% Window
winArray = windows('hamming', filtorder + 1);
% Filter coefficients
if revfilt == 1
filterTypeArray = {'high', 'stop'};
b = firws(filtorder, cutoffArray / fNyquist, filterTypeArray{length(cutoffArray)}, winArray);
else
b = firws(filtorder, cutoffArray / fNyquist, winArray);
end
if minphase
disp('pop_eegfiltnew() - converting filter to minimum-phase (non-linear!)');
b = minphaserceps(b);
end
% Plot frequency response
if plotfreqz
freqz(b, 1, 8192, EEG.srate);
end
% Filter
if minphase
disp('pop_eegfiltnew() - filtering the data (causal)');
EEG = firfiltsplit(EEG, b, 1);
else
disp('pop_eegfiltnew() - filtering the data (zero-phase)');
EEG = firfilt(EEG, b);
end
% History string
com = sprintf('%s = pop_eegfiltnew(%s, %s);', inputname(1), inputname(1), vararg2str({locutoff, hicutoff, filtorder, revfilt, usefft, plotfreqz}));
end
|
github
|
lcnhappe/happe-master
|
pop_xfirws.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/pop_xfirws.m
| 10,425 |
utf_8
|
d0777a1329eeb3b766e505a0b61242c9
|
% pop_xfirws() - Design and export xfir compatible windowed sinc FIR filter
%
% Usage:
% >> pop_xfirws; % pop-up window mode
% >> [b, a] = pop_xfirws; % pop-up window mode
% >> pop_xfirws('key1', value1, 'key2', value2, 'keyn', valuen);
% >> [b, a] = pop_xfirws('key1', value1, 'key2', value2, 'keyn', valuen);
%
% Inputs:
% 'srate' - scalar sampling rate (Hz)
% 'fcutoff' - vector or scalar of cutoff frequency/ies (-6 dB; Hz)
% 'forder' - scalar filter order. Mandatory even
%
% Optional inputs:
% 'ftype' - char array filter type. 'bandpass', 'highpass',
% 'lowpass', or 'bandstop' {default 'bandpass' or
% 'lowpass', depending on number of cutoff frequencies}
% 'wtype' - char array window type. 'rectangular', 'bartlett',
% 'hann', 'hamming', 'blackman', or 'kaiser' {default
% 'blackman'}
% 'warg' - scalar kaiser beta
% 'filename' - char array export filename
% 'pathname' - char array export pathname {default '.'}
%
% Outputs:
% b - filter coefficients
% a - filter coefficients
%
% Note:
% Window based filters' transition band width is defined by filter
% order and window type/parameters. Stopband attenuation equals
% passband ripple and is defined by the window type/parameters. Refer
% to table below for typical parameters. (Windowed sinc) FIR filters
% are zero phase in passband when shifted by the filters group delay
% (what firfilt does). Pi phase jumps noticable in the phase reponse
% reflect a negative frequency response and only occur in the
% stopband.
%
% Beta Max stopband Max passband Max passband Transition width Mainlobe width
% attenuation deviation ripple (dB) (normalized freq) (normalized rad freq)
% (dB)
% Rectangular -21 0.0891 1.552 0.9 / m* 4 * pi / m
% Bartlett -25 0.0562 0.977 (2.9** / m) 8 * pi / m
% Hann -44 0.0063 0.109 3.1 / m 8 * pi / m
% Hamming -53 0.0022 0.038 3.3 / m 8 * pi / m
% Blackman -74 0.0002 0.003 5.5 / m 12 * pi / m
% Kaiser 5.653 -60 0.001 0.017 3.6 / m
% Kaiser 7.857 -80 0.0001 0.002 5.0 / m
% * m = filter order
% ** estimate for higher m only
%
% Example:
% fs = 500; tbw = 2; dev = 0.001;
% beta = pop_kaiserbeta(dev);
% m = pop_firwsord('kaiser', fs, tbw, dev);
% pop_xfirws('srate', fs, 'fcutoff', [1 25], 'ftype', 'bandpass', 'wtype', 'kaiser', 'warg', beta, 'forder', m, 'filename', 'foo.fir')
%
% Author: Andreas Widmann, University of Leipzig, 2011
%
% See also:
% firfilt, firws, pop_firwsord, pop_kaiserbeta, plotfresp, windows
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2011 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [varargout] = pop_xfirws(varargin)
% Pop-up window mode
if nargin < 1
drawnow;
ftypes = {'bandpass' 'highpass' 'lowpass' 'bandstop'};
wtypes = {'rectangular' 'bartlett' 'hann' 'hamming' 'blackman' 'kaiser'};
uigeom = {[1 0.75 0.75] 1 [1 0.75 0.75] [1 0.75 0.75] 1 [1 0.75 0.75] [1 0.75 0.75] [1 0.75 0.75] 1 [1 0.75 0.75]};
uilist = {{'Style' 'text' 'String' 'Sampling frequency (Hz):'} ...
{'Style' 'edit' 'String' '2' 'Tag' 'srateedit'} {} ...
{} ...
{'Style' 'text' 'String' 'Cutoff frequency(ies) [hp lp] (-6 dB; Hz):'} ...
{'Style' 'edit' 'String' '' 'Tag' 'fcutoffedit'} {} ...
{'Style' 'text' 'String' 'Filter type:'} ...
{'Style' 'popupmenu' 'String' ftypes 'Tag' 'ftypepop'} {} ...
{} ...
{'Style' 'text' 'String' 'Window type:'} ...
{'Style' 'popupmenu' 'String' wtypes 'Tag' 'wtypepop' 'Value' 5 'Callback' 'temp = {''off'', ''on''}; set(findobj(gcbf, ''-regexp'', ''Tag'', ''^warg''), ''Enable'', temp{double(get(gcbo, ''Value'') == 6) + 1}), set(findobj(gcbf, ''Tag'', ''wargedit''), ''String'', '''')'} {} ...
{'Style' 'text' 'String' 'Kaiser window beta:' 'Tag' 'wargtext' 'Enable' 'off'} ...
{'Style' 'edit' 'String' '' 'Tag' 'wargedit' 'Enable' 'off'} ...
{'Style' 'pushbutton' 'String' 'Estimate' 'Tag' 'wargpush' 'Enable' 'off' 'Callback' @comwarg} ...
{'Style' 'text' 'String' 'Filter order (mandatory even):'} ...
{'Style' 'edit' 'String' '' 'Tag' 'forderedit'} ...
{'Style' 'pushbutton' 'String' 'Estimate' 'Callback' {@comforder, wtypes}} ...
{'Style' 'edit' 'Tag' 'devedit' 'Visible' 'off'} ...
{} {} {'Style' 'pushbutton' 'String', 'Plot filter responses' 'Callback' {@comfresp, wtypes, ftypes}}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_firws'')', 'Filter the data -- pop_firws()');
if isempty(result), return; end
Arg = struct;
Arg.srate = str2double(result{1});
Arg.fcutoff = str2num(result{2});
Arg.ftype = ftypes{result{3}};
Arg.wtype = wtypes{result{4}};
Arg.warg = str2num(result{5});
Arg.forder = str2double(result{6});
% Command line mode
else
Arg = struct(varargin{:});
end
% Sampling rate
if ~isfield(Arg, 'srate') || isempty(Arg.srate) % Use default
Arg.srate = 2;
end
% Filter order and cutoff frequencies
if ~isfield(Arg, 'fcutoff') || ~isfield(Arg, 'forder') || isempty(Arg.fcutoff) || isempty(Arg.forder)
error('Not enough input arguments.');
end
firwsArgArray = {Arg.forder sort(Arg.fcutoff / Arg.srate * 2)}; % Sorting and normalization
% Filter type
if ~isfield(Arg, 'ftype') || isempty(Arg.ftype) % Use default
switch length(Arg.fcutoff)
case 1
Arg.ftype = 'lowpass';
case 2
Arg.ftype = 'bandpass';
otherwise
error('Wrong number of arguments.')
end
else
if any(strcmpi(Arg.ftype, {'bandpass' 'bandstop'})) && length(Arg.fcutoff) ~= 2
error('Not enough input arguments.');
elseif any(strcmpi(Arg.ftype, {'highpass' 'lowpass'})) && length(Arg.fcutoff) ~= 1
error('Too many input arguments.');
end
switch Arg.ftype
case 'bandstop'
firwsArgArray(end + 1) = {'stop'};
case 'highpass'
firwsArgArray(end + 1) = {'high'};
end
end
% Window type
if ~isfield(Arg, 'wtype') || isempty(Arg.wtype) % Use default
Arg.wtype = 'blackman';
end
% Window parameter
if ~isfield(Arg, 'warg') || isempty(Arg.warg)
Arg.warg = [];
firwsArgArray(end + 1) = {windows(Arg.wtype, Arg.forder + 1)};
else
firwsArgArray(end + 1) = {windows(Arg.wtype, Arg.forder + 1, Arg.warg)};
end
b = firws(firwsArgArray{:});
a = 1;
if nargout == 0 || isfield(Arg, 'filename')
% Open file
if ~isfield(Arg, 'filename') || isempty(Arg.filename)
[Arg.filename Arg.pathname] = uiputfile('*.fir', 'Save filter -- pop_xfirws');
end
if ~isfield(Arg, 'pathname') || isempty(Arg.pathname)
Arg.pathname = '.';
end
[fid message] = fopen(fullfile(Arg.pathname, Arg.filename), 'w', 'l');
if fid == -1
error(message)
end
% Author
fprintf(fid, '[author]\n');
fprintf(fid, '%s\n\n', 'pop_xfirws 1.5.1');
% FIR design
fprintf(fid, '[fir design]\n');
fprintf(fid, 'method %s\n', 'fourier');
fprintf(fid, 'type %s\n', Arg.ftype);
fprintf(fid, 'fsample %f\n', Arg.srate);
fprintf(fid, 'length %d\n', Arg.forder + 1);
fprintf(fid, 'fcrit%d %f\n', [1:length(Arg.fcutoff); Arg.fcutoff]);
fprintf(fid, 'window %s %s\n\n', Arg.wtype, num2str(Arg.warg)); % fprintf bug
% FIR
fprintf(fid, '[fir]\n');
fprintf(fid, '%d\n', Arg.forder + 1);
fprintf(fid, '% 18.10e\n', b);
% Close file
fclose(fid);
end
if nargout > 0
varargout = {b a};
end
% Callback estimate Kaiser beta
function comwarg(varargin)
[warg, dev] = pop_kaiserbeta;
set(findobj(gcbf, 'Tag', 'wargedit'), 'String', warg);
set(findobj(gcbf, 'Tag', 'devedit'), 'String', dev);
% Callback estimate filter order
function comforder(obj, evt, wtypes)
srate = str2double(get(findobj(gcbf, 'Tag', 'srateedit'), 'String'));
wtype = wtypes{get(findobj(gcbf, 'Tag', 'wtypepop'), 'Value')};
dev = str2double(get(findobj(gcbf, 'Tag', 'devedit'), 'String'));
[forder, dev] = pop_firwsord(wtype, srate, [], dev);
set(findobj(gcbf, 'Tag', 'forderedit'), 'String', forder);
set(findobj(gcbf, 'Tag', 'devedit'), 'String', dev);
% Callback plot filter responses
function comfresp(obj, evt, wtypes, ftypes)
Arg.srate = str2double(get(findobj(gcbf, 'Tag', 'srateedit'), 'String'));
Arg.fcutoff = str2num(get(findobj(gcbf, 'Tag', 'fcutoffedit'), 'String'));
Arg.ftype = ftypes{get(findobj(gcbf, 'Tag', 'ftypepop'), 'Value')};
Arg.wtype = wtypes{get(findobj(gcbf, 'Tag', 'wtypepop'), 'Value')};
Arg.warg = str2num(get(findobj(gcbf, 'Tag', 'wargedit'), 'String'));
Arg.forder = str2double(get(findobj(gcbf, 'Tag', 'forderedit'), 'String'));
xfirwsArgArray(1, :) = fieldnames(Arg);
xfirwsArgArray(2, :) = struct2cell(Arg);
[b a] = pop_xfirws(xfirwsArgArray{:});
H = findobj('Tag', 'filter responses', 'type', 'figure');
if ~isempty(H)
figure(H);
else
H = figure;
set(H, 'color', [.93 .96 1], 'Tag', 'filter responses');
end
plotfresp(b, a, [], Arg.srate);
|
github
|
lcnhappe/happe-master
|
firfiltsplit.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/firfiltsplit.m
| 2,363 |
utf_8
|
8e58b4fa2694a8b1d55b8fcddcf94b4f
|
% firfiltsplit() - Split data at discontinuities and forward to dc padded
% filter function
%
% Usage:
% >> EEG = firfiltsplit(EEG, b);
%
% Inputs:
% EEG - EEGLAB EEG structure
% b - vector of filter coefficients
% causal - scalar boolean perform causal filtering {default 0}
%
% Outputs:
% EEG - EEGLAB EEG structure
%
% Note:
% This function is (in combination with firfiltdcpadded) just a
% non-memory optimized version of the firfilt function allowing causal
% filtering. Will possibly replace firfilt in the future.
%
% Author: Andreas Widmann, University of Leipzig, 2013
%
% See also:
% firfiltdcpadded, findboundaries
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2013 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function EEG = firfiltsplit(EEG, b, causal)
if nargin < 3 || isempty(causal)
causal = 0;
end
if nargin < 2
error('Not enough input arguments.');
end
% Find data discontinuities and reshape epoched data
if EEG.trials > 1 % Epoched data
EEG.data = reshape(EEG.data, [EEG.nbchan EEG.pnts * EEG.trials]);
dcArray = 1 : EEG.pnts : EEG.pnts * (EEG.trials + 1);
else % Continuous data
dcArray = [findboundaries(EEG.event) EEG.pnts + 1];
end
% Loop over continuous segments
for iDc = 1:(length(dcArray) - 1)
% Filter segment
EEG.data(:, dcArray(iDc):dcArray(iDc + 1) - 1) = firfiltdcpadded(b, EEG.data(:, dcArray(iDc):dcArray(iDc + 1) - 1)', causal)';
end
% Reshape epoched data
if EEG.trials > 1
EEG.data = reshape(EEG.data, [EEG.nbchan EEG.pnts EEG.trials]);
end
end
|
github
|
lcnhappe/happe-master
|
eegplugin_firfilt.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/eegplugin_firfilt.m
| 2,667 |
utf_8
|
681ba5e0933cafd6bb95672f910816cd
|
% eegplugin_firfilt() - EEGLAB plugin for filtering data using linear-
% phase FIR filters
%
% Usage:
% >> eegplugin_firfilt(fig, trystrs, catchstrs);
%
% Inputs:
% fig - [integer] EEGLAB figure
% trystrs - [struct] "try" strings for menu callbacks.
% catchstrs - [struct] "catch" strings for menu callbacks.
%
% Author: Andreas Widmann, University of Leipzig, Germany, 2005
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function vers = eegplugin_firfilt(fig, trystrs, catchstrs)
vers = 'firfilt1.6.1';
if nargin < 3
error('eegplugin_firfilt requires 3 arguments');
end
% add folder to path
% -----------------------
if ~exist('pop_firws')
p = which('eegplugin_firfilt');
p = p(1:findstr(p,'eegplugin_firfilt.m')-1);
addpath([p vers]);
end
% find import data menu
% ---------------------
menu = findobj(fig, 'tag', 'filter');
% menu callbacks
% --------------
comfirfiltnew = [trystrs.no_check '[EEG LASTCOM] = pop_eegfiltnew(EEG);' catchstrs.new_and_hist];
comfirws = [trystrs.no_check '[EEG LASTCOM] = pop_firws(EEG);' catchstrs.new_and_hist];
comfirpm = [trystrs.no_check '[EEG LASTCOM] = pop_firpm(EEG);' catchstrs.new_and_hist];
comfirma = [trystrs.no_check '[EEG LASTCOM] = pop_firma(EEG);' catchstrs.new_and_hist];
% create menus if necessary
% -------------------------
uimenu( menu, 'Label', 'Basic FIR filter (new, default)', 'CallBack', comfirfiltnew, 'Separator', 'on', 'position', 1);
uimenu( menu, 'Label', 'Windowed sinc FIR filter', 'CallBack', comfirws, 'position', 2);
uimenu( menu, 'Label', 'Parks-McClellan (equiripple) FIR filter', 'CallBack', comfirpm, 'position', 3);
uimenu( menu, 'Label', 'Moving average FIR filter', 'CallBack', comfirma, 'position', 4);
|
github
|
lcnhappe/happe-master
|
windows.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/windows.m
| 2,876 |
utf_8
|
581c2f660f641935667a234f9b024f3a
|
% windows() - Returns handle to window function or window
%
% Usage:
% >> h = windows(t);
% >> h = windows(t, m);
% >> h = windows(t, m, a);
%
% Inputs:
% t - char array 'rectangular', 'bartlett', 'hann', 'hamming',
% 'blackman', 'blackmanharris', or 'kaiser'
%
% Optional inputs:
% m - scalar window length
% a - scalar or vector with window parameter(s)
%
% Output:
% h - function handle or column vector window
%
% Author: Andreas Widmann, University of Leipzig, 2005
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function h = windows(t, m, a)
if nargin < 1
error('Not enough input arguments.');
end
h = str2func(t);
switch nargin
case 2
h = h(m);
case 3
h = h(m, a);
end
end
function w = rectangular(m)
w = ones(m, 1);
end
function w = bartlett(m)
w = 1 - abs(-1:2 / (m - 1):1)';
end
% von Hann
function w = hann(m);
w = hamming(m, 0.5);
end
% Hamming
function w = hamming(m, a)
if nargin < 2 || isempty(a)
a = 25 / 46;
end
m = [0:1 / (m - 1):1]';
w = a - (1 - a) * cos(2 * pi * m);
end
% Blackman
function w = blackman(m, a)
if nargin < 2 || isempty(a)
a = [0.42 0.5 0.08 0];
end
m = [0:1 / (m - 1):1]';
w = a(1) - a(2) * cos (2 * pi * m) + a(3) * cos(4 * pi * m) - a(4) * cos(6 * pi * m);
end
% Blackman-Harris
function w = blackmanharris(m)
w = blackman(m, [0.35875 0.48829 0.14128 0.01168]);
end
% Kaiser
function w = kaiser(m, a)
if nargin < 2 || isempty(a)
a = 0.5;
end
m = [-1:2 / (m - 1):1]';
w = besseli(0, a * sqrt(1 - m.^2)) / besseli(0, a);
end
% Tukey
function w = tukey(m, a)
if nargin < 2 || isempty(a)
a = 0.5;
end
if a <= 0
w = ones(m, 1);
elseif a >= 1
w = hann(m);
else
a = (m - 1) / 2 * a;
tapArray = (0:a)' / a;
w = [0.5 - 0.5 * cos(pi * tapArray); ...
ones(m - 2 * length(tapArray), 1); ...
0.5 - 0.5 * cos(pi * tapArray(end:-1:1))];
end
end
|
github
|
lcnhappe/happe-master
|
pop_firpmord.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/pop_firpmord.m
| 3,145 |
utf_8
|
f4dae3b8e73f8ab3d73c2d207506ddd8
|
% pop_firpmord() - Estimate Parks-McClellan filter order and weights
%
% Usage:
% >> [m, wtpass, wtstop] = pop_firpmord(f, a); % pop-up window mode
% >> [m, wtpass, wtstop] = pop_firpmord(f, a, dev);
% >> [m, wtpass, wtstop] = pop_firpmord(f, a, dev, fs);
%
% Inputs:
% f - vector frequency band edges
% a - vector desired amplitudes on bands defined by f
% dev - vector allowable deviations on bands defined by f
%
% Optional inputs:
% fs - scalar sampling frequency {default 2}
%
% Output:
% m - scalar estimated filter order
% wtpass - scalar passband weight
% wtstop - scalar stopband weight
%
% Note:
% Requires the signal processing toolbox. Convert passband ripple from
% dev to peak-to-peak dB: rp = 20 * log10((1 + dev) / (1 - dev)).
% Convert stopband attenuation from dev to dB: rs = 20 * log10(dev).
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% pop_firpm, firpm, firpmord
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [m, wtpass, wtstop] = pop_firpmord(f, a, dev, fs)
m = [];
wtpass = [];
wtstop = [];
if exist('firpmord') ~= 2
error('Requires the signal processing toolbox.');
end
if nargin < 2 || isempty(f) || isempty(a)
error('Not enough input arguments');
end
% Sampling frequency
if nargin < 4 || isempty(fs)
fs = 2;
end
% GUI
if nargin < 3 || isempty(dev)
drawnow;
uigeom = {[1 1] [1 1]};
uilist = {{'style' 'text' 'string' 'Peak-to-peak passband ripple (dB):'} ...
{'style' 'edit'} ...
{'style' 'text' 'string' 'Stopband attenuation (dB):'} ...
{'style' 'edit'}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_firpmord'')', 'Estimate filter order and weights -- pop_firpmord()');
if length(result) == 0, return, end
if ~isempty(result{1})
rp = str2num(result{1});
rp = (10^(rp / 20) - 1) / (10^(rp / 20) + 1);
dev(find(a == 1)) = rp;
else
error('Not enough input arguments.');
end
if ~isempty(result{2})
rs = str2num(result{2});
rs = 10^(-abs(rs) / 20);
dev(find(a == 0)) = rs;
else
error('Not enough input arguments.');
end
end
[m, fo, ao, w] = firpmord(f, a, dev, fs);
wtpass = w(find(a == 1, 1));
wtstop = w(find(a == 0, 1));
|
github
|
lcnhappe/happe-master
|
firfilt.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/firfilt.m
| 4,262 |
utf_8
|
d5703bbd52180bfb0661e6db5e649967
|
% firfilt() - Pad data with DC constant, filter data with FIR filter,
% and shift data by the filter's group delay
%
% Usage:
% >> EEG = firfilt(EEG, b, nFrames);
%
% Inputs:
% EEG - EEGLAB EEG structure
% b - vector of filter coefficients
%
% Optional inputs:
% nFrames - number of frames to filter per block {default 1000}
%
% Outputs:
% EEG - EEGLAB EEG structure
%
% Note:
% Higher values for nFrames increase speed and working memory
% requirements.
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% filter, findboundaries
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function EEG = firfilt(EEG, b, nFrames)
if nargin < 2
error('Not enough input arguments.');
end
if nargin < 3 || isempty(nFrames)
nFrames = 1000;
end
% Filter's group delay
if mod(length(b), 2) ~= 1
error('Filter order is not even.');
end
groupDelay = (length(b) - 1) / 2;
% Find data discontinuities and reshape epoched data
if EEG.trials > 1 % Epoched data
EEG.data = reshape(EEG.data, [EEG.nbchan EEG.pnts * EEG.trials]);
dcArray = 1 : EEG.pnts : EEG.pnts * (EEG.trials + 1);
else % Continuous data
dcArray = [findboundaries(EEG.event) EEG.pnts + 1];
end
% Initialize progress indicator
nSteps = 20;
step = 0;
fprintf(1, 'firfilt(): |');
strLength = fprintf(1, [repmat(' ', 1, nSteps - step) '| 0%%']);
tic
for iDc = 1:(length(dcArray) - 1)
% Pad beginning of data with DC constant and get initial conditions
ziDataDur = min(groupDelay, dcArray(iDc + 1) - dcArray(iDc));
[temp, zi] = filter(b, 1, double([EEG.data(:, ones(1, groupDelay) * dcArray(iDc)) ...
EEG.data(:, dcArray(iDc):(dcArray(iDc) + ziDataDur - 1))]), [], 2);
blockArray = [(dcArray(iDc) + groupDelay):nFrames:(dcArray(iDc + 1) - 1) dcArray(iDc + 1)];
for iBlock = 1:(length(blockArray) - 1)
% Filter the data
[EEG.data(:, (blockArray(iBlock) - groupDelay):(blockArray(iBlock + 1) - groupDelay - 1)), zi] = ...
filter(b, 1, double(EEG.data(:, blockArray(iBlock):(blockArray(iBlock + 1) - 1))), zi, 2);
% Update progress indicator
[step, strLength] = mywaitbar((blockArray(iBlock + 1) - groupDelay - 1), size(EEG.data, 2), step, nSteps, strLength);
end
% Pad end of data with DC constant
temp = filter(b, 1, double(EEG.data(:, ones(1, groupDelay) * (dcArray(iDc + 1) - 1))), zi, 2);
EEG.data(:, (dcArray(iDc + 1) - ziDataDur):(dcArray(iDc + 1) - 1)) = ...
temp(:, (end - ziDataDur + 1):end);
% Update progress indicator
[step, strLength] = mywaitbar((dcArray(iDc + 1) - 1), size(EEG.data, 2), step, nSteps, strLength);
end
% Reshape epoched data
if EEG.trials > 1
EEG.data = reshape(EEG.data, [EEG.nbchan EEG.pnts EEG.trials]);
end
% Deinitialize progress indicator
fprintf(1, '\n')
end
function [step, strLength] = mywaitbar(compl, total, step, nSteps, strLength)
progStrArray = '/-\|';
tmp = floor(compl / total * nSteps);
if tmp > step
fprintf(1, [repmat('\b', 1, strLength) '%s'], repmat('=', 1, tmp - step))
step = tmp;
ete = ceil(toc / step * (nSteps - step));
strLength = fprintf(1, [repmat(' ', 1, nSteps - step) '%s %3d%%, ETE %02d:%02d'], progStrArray(mod(step - 1, 4) + 1), floor(step * 100 / nSteps), floor(ete / 60), mod(ete, 60));
end
end
|
github
|
lcnhappe/happe-master
|
pop_firws.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/pop_firws.m
| 10,634 |
utf_8
|
830347cf85c318140462a11e9257b53b
|
% pop_firws() - Filter data using windowed sinc FIR filter
%
% Usage:
% >> [EEG, com, b] = pop_firws(EEG); % pop-up window mode
% >> [EEG, com, b] = pop_firws(EEG, 'key1', value1, 'key2', ...
% value2, 'keyn', valuen);
%
% Inputs:
% EEG - EEGLAB EEG structure
% 'fcutoff' - vector or scalar of cutoff frequency/ies (-6 dB; Hz)
% 'forder' - scalar filter order. Mandatory even
%
% Optional inputs:
% 'ftype' - char array filter type. 'bandpass', 'highpass',
% 'lowpass', or 'bandstop' {default 'bandpass' or
% 'lowpass', depending on number of cutoff frequencies}
% 'wtype' - char array window type. 'rectangular', 'bartlett',
% 'hann', 'hamming', 'blackman', or 'kaiser' {default
% 'blackman'}
% 'warg' - scalar kaiser beta
% 'minphase' - scalar boolean minimum-phase converted causal filter
% {default false}
%
% Outputs:
% EEG - filtered EEGLAB EEG structure
% com - history string
% b - filter coefficients
%
% Note:
% Window based filters' transition band width is defined by filter
% order and window type/parameters. Stopband attenuation equals
% passband ripple and is defined by the window type/parameters. Refer
% to table below for typical parameters. (Windowed sinc) symmetric FIR
% filters have linear phase and can be made zero phase (non-causal) by
% shifting the data by the filters group delay (what firfilt does by
% default). Pi phase jumps noticable in the phase reponse reflect a
% negative frequency response and only occur in the stopband. pop_firws
% also allows causal filtering with minimum-phase (non-linear!) converted
% filter coefficients with similar properties. Non-linear causal
% filtering is NOT recommended for most use cases.
%
% Beta Max stopband Max passband Max passband Transition width Mainlobe width
% attenuation deviation ripple (dB) (normalized freq) (normalized rad freq)
% (dB)
% Rectangular -21 0.0891 1.552 0.9 / m* 4 * pi / m
% Bartlett -25 0.0562 0.977 8 * pi / m
% Hann -44 0.0063 0.109 3.1 / m 8 * pi / m
% Hamming -53 0.0022 0.038 3.3 / m 8 * pi / m
% Blackman -74 0.0002 0.003 5.5 / m 12 * pi / m
% Kaiser 5.653 -60 0.001 0.017 3.6 / m
% Kaiser 7.857 -80 0.0001 0.002 5.0 / m
% * m = filter order
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% firfilt, firws, pop_firwsord, pop_kaiserbeta, plotfresp, windows
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com, b] = pop_firws(EEG, varargin)
com = '';
if nargin < 1
help pop_firws;
return;
end
if isempty(EEG.data)
error('Cannot process empty dataset');
end
if nargin < 2
drawnow;
ftypes = {'bandpass', 'highpass', 'lowpass', 'bandstop'};
ftypesStr = {'Bandpass', 'Highpass', 'Lowpass', 'Bandstop'};
wtypes = {'rectangular', 'bartlett', 'hann', 'hamming', 'blackman', 'kaiser'};
wtypesStr = {'Rectangular (PB dev=0.089, SB att=-21dB)', 'Bartlett (PB dev=0.056, SB att=-25dB)', 'Hann (PB dev=0.006, SB att=-44dB)', 'Hamming (PB dev=0.002, SB att=-53dB)', 'Blackman (PB dev=0.0002, SB att=-74dB)', 'Kaiser'};
uigeom = {[1 0.75 0.75] [1 0.75 0.75] 1 [1 0.75 0.75] [1 0.75 0.75] [1 0.75 0.75] [1 1.5] 1 [1 0.75 0.75]};
uilist = {{'Style' 'text' 'String' 'Cutoff frequency(ies) [hp lp] (-6 dB; Hz):'} ...
{'Style' 'edit' 'String' '' 'Tag' 'fcutoffedit'} {} ...
{'Style' 'text' 'String' 'Filter type:'} ...
{'Style' 'popupmenu' 'String' ftypesStr 'Tag' 'ftypepop'} {} ...
{} ...
{'Style' 'text' 'String' 'Window type:'} ...
{'Style' 'popupmenu' 'String' wtypesStr 'Tag' 'wtypepop' 'Value' 5 'Callback' 'temp = {''off'', ''on''}; set(findobj(gcbf, ''-regexp'', ''Tag'', ''^warg''), ''Enable'', temp{double(get(gcbo, ''Value'') == 6) + 1}), set(findobj(gcbf, ''Tag'', ''wargedit''), ''String'', '''')'} {} ...
{'Style' 'text' 'String' 'Kaiser window beta:' 'Tag' 'wargtext' 'Enable' 'off'} ...
{'Style' 'edit' 'String' '' 'Tag' 'wargedit' 'Enable' 'off'} ...
{'Style' 'pushbutton' 'String' 'Estimate' 'Tag' 'wargpush' 'Enable' 'off' 'Callback' @comwarg} ...
{'Style' 'text' 'String' 'Filter order (mandatory even):'} ...
{'Style' 'edit' 'String' '' 'Tag' 'forderedit'} ...
{'Style' 'pushbutton' 'String' 'Estimate' 'Callback' {@comforder, wtypes, EEG.srate}} ...
{} {'Style' 'checkbox', 'String', 'Use minimum-phase converted causal filter (non-linear!; beta)', 'Tag' 'minphase', 'Value', 0} ...
{'Style' 'edit' 'Tag' 'devedit' 'Visible' 'off'} ...
{} {} {'Style' 'pushbutton' 'String', 'Plot filter responses' 'Callback' {@comfresp, wtypes, ftypes, EEG.srate}}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_firws'')', 'Filter the data -- pop_firws()');
if isempty(result), return; end
args = {};
if ~isempty(result{1})
args = [args {'fcutoff'} {str2num(result{1})}];
end
args = [args {'ftype'} ftypes(result{2})];
args = [args {'wtype'} wtypes(result{3})];
if ~isempty(result{4})
args = [args {'warg'} {str2double(result{4})}];
end
if ~isempty(result{5})
args = [args {'forder'} {str2double(result{5})}];
end
args = [args {'minphase'} result{6}];
else
args = varargin;
end
% Convert args to structure
args = struct(args{:});
c = parseargs(args, EEG.srate);
b = firws(c{:});
% Check arguments
if ~isfield(args, 'minphase') || isempty(args.minphase)
args.minphase = 0;
end
% Filter
disp('pop_firws() - filtering the data');
if args.minphase
b = minphaserceps(b);
EEG = firfiltsplit(EEG, b, 1);
else
EEG = firfilt(EEG, b);
end
% History string
com = sprintf('%s = pop_firws(%s', inputname(1), inputname(1));
for c = fieldnames(args)'
if ischar(args.(c{:}))
com = [com sprintf(', ''%s'', ''%s''', c{:}, args.(c{:}))];
else
com = [com sprintf(', ''%s'', %s', c{:}, mat2str(args.(c{:})))];
end
end
com = [com ');'];
% Convert structure args to cell array firws parameters
function c = parseargs(args, srate)
% Filter order and cutoff frequencies
if ~isfield(args, 'fcutoff') || ~isfield(args, 'forder') || isempty(args.fcutoff) || isempty(args.forder)
error('Not enough input arguments.');
end
c = [{args.forder} {sort(args.fcutoff / (srate / 2))}]; % Sorting and normalization
% Filter type
if isfield(args, 'ftype') && ~isempty(args.ftype)
if (strcmpi(args.ftype, 'bandpass') || strcmpi(args.ftype, 'bandstop')) && length(args.fcutoff) ~= 2
error('Not enough input arguments.');
elseif (strcmpi(args.ftype, 'highpass') || strcmpi(args.ftype, 'lowpass')) && length(args.fcutoff) ~= 1
error('Too many input arguments.');
end
switch args.ftype
case 'bandstop'
c = [c {'stop'}];
case 'highpass'
c = [c {'high'}];
end
end
% Window type
if isfield(args, 'wtype') && ~isempty(args.wtype)
if strcmpi(args.wtype, 'kaiser')
if isfield(args, 'warg') && ~isempty(args.warg)
c = [c {windows(args.wtype, args.forder + 1, args.warg)'}];
else
error('Not enough input arguments.');
end
else
c = [c {windows(args.wtype, args.forder + 1)'}];
end
end
% Callback estimate Kaiser beta
function comwarg(varargin)
[warg, dev] = pop_kaiserbeta;
set(findobj(gcbf, 'Tag', 'wargedit'), 'String', warg);
set(findobj(gcbf, 'Tag', 'devedit'), 'String', dev);
% Callback estimate filter order
function comforder(obj, evt, wtypes, srate)
wtype = wtypes{get(findobj(gcbf, 'Tag', 'wtypepop'), 'Value')};
dev = get(findobj(gcbf, 'Tag', 'devedit'), 'String');
[forder, dev] = pop_firwsord(wtype, srate, [], dev);
set(findobj(gcbf, 'Tag', 'forderedit'), 'String', forder);
set(findobj(gcbf, 'Tag', 'devedit'), 'String', dev);
% Callback plot filter responses
function comfresp(obj, evt, wtypes, ftypes, srate)
args.fcutoff = str2num(get(findobj(gcbf, 'Tag', 'fcutoffedit'), 'String'));
args.ftype = ftypes{get(findobj(gcbf, 'Tag', 'ftypepop'), 'Value')};
args.wtype = wtypes{get(findobj(gcbf, 'Tag', 'wtypepop'), 'Value')};
args.warg = str2num(get(findobj(gcbf, 'Tag', 'wargedit'), 'String'));
args.forder = str2double(get(findobj(gcbf, 'Tag', 'forderedit'), 'String'));
args.minphase = get(findobj(gcbf, 'Tag', 'minphase'), 'Value');
causal = args.minphase;
c = parseargs(args, srate);
b = firws(c{:});
if args.minphase
b = minphaserceps(b);
end
H = findobj('Tag', 'filter responses', 'type', 'figure');
if ~isempty(H)
figure(H);
else
H = figure;
set(H, 'color', [.93 .96 1], 'Tag', 'filter responses');
end
plotfresp(b, 1, [], srate, causal);
|
github
|
lcnhappe/happe-master
|
plotfresp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/plotfresp.m
| 3,898 |
utf_8
|
71a74a912328b37353e1523b662840fa
|
% plotfresp() - Plot FIR filter's impulse, step, frequency, magnitude,
% and phase response
%
% Usage:
% >> plotfresp(b, a, n, fs);
%
% Inputs:
% b - vector filter coefficients
%
% Optional inputs:
% a - currently unused, reserved for future compatibility with IIR
% filters {default 1}
% n - scalar number of points
% fs - scalar sampling frequency
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% pop_firws, pop_firpm, pop_firma
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function plotfresp(b, a, nfft, fs, causal)
if nargin < 5 || isempty(causal)
causal = 0;
end
if nargin < 4 || isempty(fs)
fs = 1;
end
if nargin < 3 || isempty(nfft)
nfft = 2^fix(log2(length(b)));
if nfft < 512
nfft = 512;
end
end
if nargin < 1
error('Not enough input arguments.');
end
n = length(b);
f = (0:1 / nfft:1) * fs / 2;
% Impulse resonse
if causal, xval = 0:n-1; else xval = -(n - 1) / 2:(n - 1) / 2; end
ax(1) = subplot(2, 3, 1);
stem(xval, b, 'fill')
title('Impulse response');
ylabel('Amplitude');
% Step response
ax(4) = subplot(2, 3, 4);
stem(xval, cumsum(b), 'fill');
title('Step response');
foo = ylim;
if foo(2) < -foo(1) + 1;
foo(2) = -foo(1) + 1;
ylim(foo);
end
xMin = []; xMax = [];
children = get(ax(4), 'Children');
for child =1:length(children)
xData = get(children(child), 'XData');
xMin = min([xMin min(xData)]);
xMax = max([xMax max(xData)]);
end
set(ax([1 4]), 'xlim', [xMin xMax]);
ylabel('Amplitude');
% Frequency response
ax(2) = subplot(2, 3, 2);
m = fix((length(b) - 1) / 2); % Filter order
z = fft(b, nfft * 2);
z = z(1:fix(length(z) / 2) + 1);
% foo = real(abs(z) .* exp(-i * (angle(z) + [0:1 / nfft:1] * m * pi))); % needs further testing
plot(f, abs(z));
title('Frequency response');
ylabel('Amplitude');
% Magnitude response
ax(5) = subplot(2, 3, 5);
db = abs(z);
db(db < eps^(2 / 3)) = eps^(2 / 3); % Log of zero warning
plot(f, 20 * log10(db));
title('Magnitude response');
foo = ylim;
if foo(1) < 20 * log10(eps^(2 / 3))
foo(1) = 20 * log10(eps^(2 / 3));
end
ylabel('Magnitude (dB)');
ylim(foo);
% Phase response
ax(3) = subplot(2, 3, 3);
z(abs(z) < eps^(2 / 3)) = NaN; % Phase is undefined for magnitude zero
phi = angle(z);
if causal
phi = unwrap(phi);
else
delay = -mod((0:1 / nfft:1) * m * pi + pi, 2 * pi) + pi; % Zero-phase
phi = phi - delay;
phi = phi + 2 * pi * (phi <= -pi + eps ^ (1/3)); % Unwrap
end
plot(f, phi);
title('Phase response');
ylabel('Phase (rad)');
% ylim([-pi / 2 1.5 * pi]);
set(ax(1:5), 'ygrid', 'on', 'xgrid', 'on', 'box', 'on');
titles = get(ax(1:5), 'title');
set([titles{:}], 'fontweight', 'bold');
xlabels = get(ax(1:5), 'xlabel');
if fs == 1
set([xlabels{[2 3 5]}], 'String', 'Normalized frequency (2 pi rad / sample)');
else
set([xlabels{[2 3 5]}], 'String', 'Frequency (Hz)');
end
set([xlabels{[1 4]}], 'String', 'Sample');
set(ax([2 3 5]), 'xlim', [0 fs / 2]);
set(ax(1:5), 'colororder', circshift(get(ax(1), 'colororder'), -1));
set(ax(1:5), 'nextplot', 'add');
|
github
|
lcnhappe/happe-master
|
pop_firwsord.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/pop_firwsord.m
| 5,354 |
utf_8
|
5150d668b377feb0d9e95b49486978ca
|
% pop_firwsord() - Estimate windowed sinc filter order depending on
% window type and requested transition band width
%
% Usage:
% >> [m, dev] = pop_firwsord; % pop-up window mode
% >> m = pop_firwsord(wtype, fs, df);
% >> m = pop_firwsord('kaiser', fs, df, dev);
%
% Inputs:
% wtype - char array window type. 'rectangular', 'bartlett', 'hann',
% 'hamming', {'blackman'}, or 'kaiser'
% fs - scalar sampling frequency {default 2}
% df - scalar requested transition band width
% dev - scalar maximum passband deviation/ripple (Kaiser window
% only)
%
% Output:
% m - scalar estimated filter order
% dev - scalar maximum passband deviation/ripple
%
% References:
% [1] Smith, S. W. (1999). The scientist and engineer's guide to
% digital signal processing (2nd ed.). San Diego, CA: California
% Technical Publishing.
% [2] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal
% Processing: Principles, Algorithms, and Applications (3rd ed.).
% Englewood Cliffs, NJ: Prentice-Hall
% [3] Ifeachor E. C., & Jervis B. W. (1993). Digital Signal
% Processing: A Practical Approach. Wokingham, UK: Addison-Wesley
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% pop_firws, firws, pop_kaiserbeta, windows
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [m, dev] = pop_firwsord(wtype, fs, df, dev)
m = [];
wtypes = {'rectangular' 'bartlett' 'hann' 'hamming' 'blackman' 'kaiser'};
% Window type
if nargin < 1 || isempty(wtype)
wtype = 5;
elseif ~ischar(wtype) || isempty(strmatch(wtype, wtypes))
error('Unknown window type');
else
wtype = strmatch(wtype, wtypes);
end
% Sampling frequency
if nargin < 2 || isempty(fs)
fs = 2;
end
% Transition band width
if nargin < 3
df = [];
end
% Maximum passband deviation/ripple
if nargin < 4 || isempty(dev)
devs = {0.089 0.056 0.0063 0.0022 0.0002 []};
dev = devs{wtype};
end
% GUI
if nargin < 3 || isempty(df) || (wtype == 6 && isempty(dev))
drawnow;
uigeom = {[1 1] [1 1] [1 1] [1 1]};
uilist = {{'style' 'text' 'string' 'Sampling frequency:'} ...
{'style' 'edit' 'string' fs} ...
{'style' 'text' 'string' 'Window type:'} ...
{'style' 'popupmenu' 'string' wtypes 'tag' 'wtypepop' 'value' wtype 'callback' {@comwtype, dev}} ...
{'style' 'text' 'string' 'Transition bandwidth (Hz):'} ...
{'style' 'edit' 'string' df} ...
{'style' 'text' 'string' 'Max passband deviation/ripple:' 'tag' 'devtext'} ...
{'style' 'edit' 'tag' 'devedit' 'createfcn' {@comwtype, dev}}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_firwsord'')', 'Estimate filter order -- pop_firwsord()');
if length(result) == 0, return, end
if ~isempty(result{1})
fs = str2num(result{1});
else
fs = 2;
end
wtype = result{2};
if ~isempty(result{3})
df = str2num(result{3});
else
error('Not enough input arguments.');
end
if ~isempty(result{4})
dev = str2num(result{4});
elseif wtype == 6
error('Not enough input arguments.');
end
end
if length(fs) > 1 || ~isnumeric(fs) || ~isreal(fs) || fs <= 0
error('Sampling frequency must be a positive real scalar.');
end
if length(df) > 1 || ~isnumeric(df) || ~isreal(df) || fs <= 0
error('Transition bandwidth must be a positive real scalar.');
end
df = df / fs; % Normalize transition band width
if wtype == 6
if length(dev) > 1 || ~isnumeric(dev) || ~isreal(dev) || dev <= 0
error('Passband deviation/ripple must be a positive real scalar.');
end
devdb = -20 * log10(dev);
m = 1 + (devdb - 8) / (2.285 * 2 * pi * df);
else
dfs = [0.9 2.9 3.1 3.3 5.5];
m = dfs(wtype) / df;
end
m = ceil(m / 2) * 2; % Make filter order even (type 1)
function comwtype(obj, evt, dev)
enable = {'off' 'off' 'off' 'off' 'off' 'on'};
devs = {0.089 0.056 0.0063 0.0022 0.0002 dev};
wtype = get(findobj(gcbf, 'tag', 'wtypepop'), 'value');
set(findobj(gcbf, 'tag', 'devtext'), 'enable', enable{wtype});
set(findobj(gcbf, 'tag', 'devedit'), 'enable', enable{wtype}, 'string', devs{wtype});
|
github
|
lcnhappe/happe-master
|
pop_kaiserbeta.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/pop_kaiserbeta.m
| 2,315 |
utf_8
|
9a8a6636653865493068a0e901deeda6
|
% pop_kaiserbeta() - Estimate Kaiser window beta
%
% Usage:
% >> [beta, dev] = pop_kaiserbeta; % pop-up window mode
% >> beta = pop_kaiserbeta(dev);
%
% Inputs:
% dev - scalar maximum passband deviation/ripple
%
% Output:
% beta - scalar Kaiser window beta
% dev - scalar maximum passband deviation/ripple
%
% References:
% [1] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal
% Processing: Principles, Algorithms, and Applications (3rd ed.).
% Englewood Cliffs, NJ: Prentice-Hall
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% pop_firws, firws, pop_firwsord, windows
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [beta, dev] = pop_kaiserbeta(dev)
beta = [];
if nargin < 1 || isempty(dev)
drawnow;
uigeom = {[1 1]};
uilist = {{'style' 'text' 'string' 'Max passband deviation/ripple:'} ...
{'style' 'edit' 'string' ''}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_kaiserbeta'')', 'Estimate Kaiser window beta -- pop_kaiserbeta()');
if length(result) == 0, return, end
if ~isempty(result{1})
dev = str2num(result{1});
else
error('Not enough input arguments.');
end
end
devdb = -20 * log10(dev);
if devdb > 50
beta = 0.1102 * (devdb - 8.7);
elseif devdb >= 21
beta = 0.5842 * (devdb - 21)^0.4 + 0.07886 * (devdb - 21);
else
beta = 0;
end
end
|
github
|
lcnhappe/happe-master
|
findboundaries.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/firfilt1.6.2/findboundaries.m
| 1,867 |
utf_8
|
b4b28dadb5f28c802c41266f791d942c
|
% findboundaries() - Find boundaries (data discontinuities) in event
% structure of continuous EEG dataset
%
% Usage:
% >> boundaries = findboundaries(EEG.event);
%
% Inputs:
% EEG.event - EEGLAB EEG event structure
%
% Outputs:
% boundaries - scalar or vector of boundary event latencies
%
% Author: Andreas Widmann, University of Leipzig, 2005
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function boundaries = findboundaries(event)
if isfield(event, 'type') & isfield(event, 'latency') & cellfun('isclass', {event.type}, 'char')
% Boundary event indices
boundaries = strmatch('boundary', {event.type});
% Boundary event latencies
boundaries = [event(boundaries).latency];
% Shift boundary events to epoch onset
boundaries = fix(boundaries + 0.5);
% Remove duplicate boundary events
boundaries = unique(boundaries);
% Epoch onset at first sample?
if isempty(boundaries) || boundaries(1) ~= 1
boundaries = [1 boundaries];
end
else
boundaries = 1;
end
|
github
|
lcnhappe/happe-master
|
pop_dipfit_manual.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/pop_dipfit_manual.m
| 1,755 |
utf_8
|
eba5714bbc90a749dad3cbbf6d51a4d7
|
% pop_dipfit_manual() - interactively do dipole fit of selected ICA components
% Function deprecated. Use pop_dipfit_nonlinear()
% instead
% Usage:
% >> OUTEEG = pop_dipfit_manual( INEEG )
%
% Inputs:
% INEEG input dataset
%
% Outputs:
% OUTEEG output dataset
%
% Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003
% Arnaud Delorme, SCCN, La Jolla 2003
% SMI, University Aalborg, Denmark http://www.smi.auc.dk/
% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/
% Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [OUTEEG, com] = pop_dipfit_manual( varargin )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<1
help pop_dipfit_manual;
return
else
disp('Warning: pop_dipfit_manual is outdated. Use pop_dipfit_nonlinear instead');
[OUTEEG, com] = pop_dipfit_nonlinear( varargin{:} );
end;
|
github
|
lcnhappe/happe-master
|
eeglab2fieldtrip.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/eeglab2fieldtrip.m
| 5,810 |
utf_8
|
bebbd3c516538fee4fe6182dcd06e54c
|
% eeglab2fieldtrip() - do this ...
%
% Usage: >> data = eeglab2fieldtrip( EEG, fieldbox, transform );
%
% Inputs:
% EEG - [struct] EEGLAB structure
% fieldbox - ['preprocessing'|'freqanalysis'|'timelockanalysis'|'companalysis']
% transform - ['none'|'dipfit'] transform channel locations for DIPFIT
% using the transformation matrix in the field
% 'coord_transform' of the dipfit substructure of the EEG
% structure.
% Outputs:
% data - FIELDTRIP structure
%
% Author: Robert Oostenveld, F.C. Donders Centre, May, 2004.
% Arnaud Delorme, SCCN, INC, UCSD
%
% See also:
% Copyright (C) 2004 Robert Oostenveld, F.C. Donders Centre, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function data = eeglab2fieldtrip(EEG, fieldbox, transform)
if nargin < 2
help eeglab2fieldtrip
return;
end;
% start with an empty data object
data = [];
% add the objects that are common to all fieldboxes
tmpchanlocs = EEG.chanlocs;
data.label = { tmpchanlocs(EEG.icachansind).labels };
data.fsample = EEG.srate;
% get the electrode positions from the EEG structure: in principle, the number of
% channels can be more or less than the number of channel locations, i.e. not
% every channel has a position, or the potential was not measured on every
% position. This is not supported by EEGLAB, but it is supported by FIELDTRIP.
if strcmpi(fieldbox, 'chanloc_withfid')
% insert "no data channels" in channel structure
% ----------------------------------------------
if isfield(EEG.chaninfo, 'nodatchans') && ~isempty( EEG.chaninfo.nodatchans )
chanlen = length(EEG.chanlocs);
fields = fieldnames( EEG.chaninfo.nodatchans );
for index = 1:length(EEG.chaninfo.nodatchans)
ind = chanlen+index;
for f = 1:length( fields )
EEG.chanlocs = setfield(EEG.chanlocs, { ind }, fields{f}, ...
getfield( EEG.chaninfo.nodatchans, { index }, fields{f}));
end;
end;
end;
end;
data.elec.pnt = zeros(length( EEG.chanlocs ), 3);
for ind = 1:length( EEG.chanlocs )
data.elec.label{ind} = EEG.chanlocs(ind).labels;
if ~isempty(EEG.chanlocs(ind).X)
data.elec.pnt(ind,1) = EEG.chanlocs(ind).X;
data.elec.pnt(ind,2) = EEG.chanlocs(ind).Y;
data.elec.pnt(ind,3) = EEG.chanlocs(ind).Z;
else
data.elec.pnt(ind,:) = [0 0 0];
end;
end;
if nargin > 2
if strcmpi(transform, 'dipfit')
if ~isempty(EEG.dipfit.coord_transform)
disp('Transforming electrode coordinates to match head model');
transfmat = traditionaldipfit(EEG.dipfit.coord_transform);
data.elec.pnt = transfmat * [ data.elec.pnt ones(size(data.elec.pnt,1),1) ]';
data.elec.pnt = data.elec.pnt(1:3,:)';
else
disp('Warning: no transformation of electrode coordinates to match head model');
end;
end;
end;
switch fieldbox
case 'preprocessing'
for index = 1:EEG.trials
data.trial{index} = EEG.data(:,:,index);
data.time{index} = linspace(EEG.xmin, EEG.xmax, EEG.pnts); % should be checked in FIELDTRIP
end;
data.label = { tmpchanlocs(1:EEG.nbchan).labels };
case 'timelockanalysis'
data.avg = mean(EEG.data, 3);
data.var = std(EEG.data, [], 3).^2;
data.time = linspace(EEG.xmin, EEG.xmax, EEG.pnts); % should be checked in FIELDTRIP
data.label = { tmpchanlocs(1:EEG.nbchan).labels };
case 'componentanalysis'
if isempty(EEG.icaact)
icaacttmp = eeg_getica(EEG);
end
for index = 1:EEG.trials
% the trials correspond to the raw data trials, except that they
% contain the component activations
try
if isempty(EEG.icaact)
data.trial{index} = icaacttmp(:,:,index); % Using icaacttmp to not change EEG structure
else
data.trial{index} = EEG.icaact(:,:,index);
end
catch
end;
data.time{index} = linspace(EEG.xmin, EEG.xmax, EEG.pnts); % should be checked in FIELDTRIP
end;
data.label = [];
for comp = 1:size(EEG.icawinv,2)
% the labels correspond to the component activations that are stored in data.trial
data.label{comp} = sprintf('ica_%03d', comp);
end
% get the spatial distribution and electrode positions
tmpchanlocs = EEG.chanlocs;
data.topolabel = { tmpchanlocs(EEG.icachansind).labels };
data.topo = EEG.icawinv;
case { 'chanloc' 'chanloc_withfid' }
case 'freqanalysis'
error('freqanalysis fieldbox not implemented yet')
otherwise
error('unsupported fieldbox')
end
try
% get the full name of the function
data.cfg.version.name = mfilename('fullpath');
catch
% required for compatibility with Matlab versions prior to release 13 (6.5)
[st, i] = dbstack;
data.cfg.version.name = st(i);
end
% add the version details of this function call to the configuration
data.cfg.version.id = '$Id: eeglab2fieldtrip.m,v 1.6 2009-07-02 23:39:29 arno Exp $';
return
|
github
|
lcnhappe/happe-master
|
dipfit_reject.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/dipfit_reject.m
| 1,823 |
utf_8
|
7d157ab7d3da320a78bb851d5d3b5669
|
% dipfit_reject() - remove dipole models with a poor fit
%
% Usage:
% >> dipout = dipfit_reject( model, reject )
%
% Inputs:
% model struct array with a dipole model for each component
%
% Outputs:
% dipout struct array with a dipole model for each component
%
% Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003
% SMI, University Aalborg, Denmark http://www.smi.auc.dk/
% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/
% Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dipout] = dipfit_reject(model, reject)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin < 1
help dipfit_reject;
return;
end;
for i=1:length(model)
if model(i).rv>reject
% reject this dipole model by replacing it by an empty model
dipout(i).posxyz = [];
dipout(i).momxyz = [];
dipout(i).rv = 1;
else
dipout(i).posxyz = model(i).posxyz;
dipout(i).momxyz = model(i).momxyz;
dipout(i).rv = model(i).rv;
end
end
|
github
|
lcnhappe/happe-master
|
pop_dipplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/pop_dipplot.m
| 8,649 |
utf_8
|
f0e67d40c3bd34a95443673ebb76b95b
|
% pop_dipplot() - plot dipoles.
%
% Usage:
% >> pop_dipplot( EEG ); % pop up interactive window
% >> pop_dipplot( EEG, comps, 'key1', 'val1', 'key2', 'val2', ...);
%
% Graphic interface:
% "Components" - [edit box] enter component number to plot. By
% all the localized components are plotted. Command
% line equivalent: components.
% "Background image" - [edit box] MRI background image. This image
% has to be normalized to the MNI brain using SPM2 for
% instance. Dipplot() command line equivalent: 'image'.
% "Summary mode" - [Checkbox] when checked, plot the 3 views of the
% head model and dipole locations. Dipplot() equivalent
% is 'summary' and 'num'.
% "Plot edges" - [Checkbox] plot edges at the intersection between
% MRI slices. Diplot() equivalent is 'drawedges'.
% "Plot closest MRI slide" - [Checkbox] plot closest MRI slice to
% dipoles although not using the 'tight' view mode.
% Dipplot() equivalent is 'cornermri' and 'axistight'.
% "Plot dipole's 2-D projections" - [Checkbox] plot a dimed dipole
% projection on each 2-D MRI slice. Dipplot() equivalent
% is 'projimg'.
% "Plot projection lines" - [Checkbox] plot lines originating from
% dipoles and perpendicular to each 2-D MRI slice.
% Dipplot() equivalent is 'projline'.
% "Make all dipole point out" - [Checkbox] make all dipole point
% toward outside the brain. Dipplot() equivalent is
% 'pointout'.
% "Normalized dipole length" - [Checkbox] normalize the length of
% all dipoles. Dipplot() command line equivalent: 'normlen'.
% "Additionnal dipfit() options" - [checkbox] enter additionnal
% sequence of 'key', 'val' argument in this edit box.
%
% Inputs:
% EEG - Input dataset
% comps - [integer array] plot component indices. If empty
% all the localized components are plotted.
%
% Optional inputs:
% 'key','val' - same as dipplot()
%
% Author: Arnaud Delorme, CNL / Salk Institute, 26 Feb 2003-
%
% See also: dipplot()
% "Use dipoles from" - [list box] use dipoles from BESA or from the
% DIPFIT toolbox. Command line equivalent: type.
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [com] = pop_dipplot( EEG, comps, varargin);
com ='';
if nargin < 1
help pop_dipplot;
return;
end;
% check input structure
% ---------------------
if ~isfield(EEG, 'dipfit') & ~isfield(EEG, 'sources')
if ~isfield(EEG.dipfit.hdmfile) & ~isfield(EEG, 'sources')
error('No dipole information in dataset');
end;
error('No dipole information in dataset');
end;
if ~isfield(EEG.dipfit, 'model')
error('No dipole information in dataset');
end;
typedip = 'nonbesa';
if nargin < 2
% popup window parameters
% -----------------------
commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', ''mrifile''), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
geometry = { [2 1] [2 1] [0.8 0.3 1.5] [2.05 0.26 .75] [2.05 0.26 .75] [2.05 0.26 .75] ...
[2.05 0.26 .75] [2.05 0.26 .75] [2.05 0.26 .75] [2.05 0.26 .75] [2 1] };
uilist = { { 'style' 'text' 'string' 'Components indices ([]=all avaliable)' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' 'Plot dipoles within RV (%) range ([min max])' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' 'Background image' } ...
{ 'style' 'pushbutton' 'string' '...' 'callback' commandload } ...
{ 'style' 'edit' 'string' EEG.dipfit.mrifile 'tag' 'mrifile' } ...
{ 'style' 'text' 'string' 'Plot summary mode' } ...
{ 'style' 'checkbox' 'string' '' } {} ...
{ 'style' 'text' 'string' 'Plot edges' } ...
{ 'style' 'checkbox' 'string' '' } {} ...
{ 'style' 'text' 'string' 'Plot closest MRI slide' } ...
{ 'style' 'checkbox' 'string' '' } {} ...
{ 'style' 'text' 'string' 'Plot dipole''s 2-D projections' } ...
{ 'style' 'checkbox' 'string' '' } {} ...
{ 'style' 'text' 'string' 'Plot projection lines' } ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } {} ...
{ 'style' 'text' 'string' 'Make all dipoles point out' } ...
{ 'style' 'checkbox' 'string' '' } {} ...
{ 'style' 'text' 'string' 'Normalized dipole length' } ...
{ 'style' 'checkbox' 'string' '' 'value' 1 } {} ...
{ 'style' 'text' 'string' 'Additionnal dipplot() options' } ...
{ 'style' 'edit' 'string' '' } };
result = inputgui( geometry, uilist, 'pophelp(''pop_dipplot'')', 'Plot dipoles - pop_dipplot');
if length(result) == 0 return; end;
% decode parameters
% -----------------
options = {};
if ~isempty(result{1}), comps = eval( [ '[' result{1} ']' ] ); else comps = []; end;
if ~isempty(result{2}), options = { options{:} 'rvrange' eval( [ '[' result{2} ']' ] ) }; end;
options = { options{:} 'mri' result{3} };
if result{4} == 1, options = { options{:} 'summary' 'on' 'num' 'on' }; end;
if result{5} == 1, options = { options{:} 'drawedges' 'on' }; end;
if result{6} == 1, options = { options{:} 'cornermri' 'on' 'axistight' 'on' }; end;
if result{7} == 1, options = { options{:} 'projimg' 'on' }; end;
if result{8} == 1, options = { options{:} 'projlines' 'on' }; end;
if result{9} == 1, options = { options{:} 'pointout' 'on' }; end;
if result{10} == 1, options = { options{:} 'normlen' 'on' }; end;
if ~isempty( result{11} ), tmpopt = eval( [ '{' result{11} '}' ] ); options = { options{:} tmpopt{:} }; end;
else
if isstr(comps)
typedip = comps;
options = varargin(2:end);
comps = varargin{1};
else
options = varargin;
end;
end;
if strcmpi(typedip, 'besa')
if ~isfield(EEG, 'sources'), error('No BESA dipole information in dataset');end;
if ~isempty(comps)
[tmp1 int] = intersect( [ EEG.sources.component ], comps);
if isempty(int), error ('Localization not found for selected components'); end;
dipplot(EEG.sources(int), 'sphere', 1, options{:});
else
dipplot(EEG.sources, options{:});
end;
else
if ~isfield(EEG, 'dipfit'), error('No DIPFIT dipole information in dataset');end;
% components to plot
% ------------------
if ~isempty(comps)
if ~isfield(EEG.dipfit.model, 'component')
for index = double(comps(:)')
EEG.dipfit.model(index).component = index;
end;
end;
else
% find localized dipoles
comps = [];
for index2 = 1:length(EEG.dipfit.model)
if ~isempty(EEG.dipfit.model(index2).posxyz) ~= 0
comps = [ comps index2 ];
EEG.dipfit.model(index2).component = index2;
end;
end;
end;
% plotting
% --------
tmpoptions = { options{:} 'coordformat', EEG.dipfit.coordformat };
if strcmpi(EEG.dipfit.coordformat, 'spherical')
dipplot(EEG.dipfit.model(comps), tmpoptions{:});
elseif strcmpi(EEG.dipfit.coordformat, 'CTF')
dipplot(EEG.dipfit.model(comps), tmpoptions{:});
else
dipplot(EEG.dipfit.model(comps), 'meshdata', EEG.dipfit.hdmfile, tmpoptions{:});
end;
end;
if nargin < 3
com = sprintf('pop_dipplot( %s,%s);', inputname(1), vararg2str({ comps options{:}}));
end;
return;
|
github
|
lcnhappe/happe-master
|
dipplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/dipplot.m
| 61,455 |
utf_8
|
1bc351e760494d6b9df714acf3a089ed
|
% dipplot() - Visualize EEG equivalent-dipole locations and orientations
% in the MNI average MRI head or in the BESA spherical head model.
% Usage:
% >> dipplot( sources, 'key', 'val', ...);
% >> [sources X Y Z XE YE ZE] = dipplot( sources, 'key', 'val', ...);
%
% Inputs:
% sources - structure array of dipole information: can contain
% either BESA or DIPFIT dipole information. BESA dipole
% information are still supported but may disapear in the
% future. For DIPFIT
% sources.posxyz: contains 3-D location of dipole in each
% column. 2 rows indicate 2 dipoles.
% sources.momxyz: contains 3-D moments for dipoles above.
% sources.rv : residual variance from 0 to 1.
% other fields : used for graphic interface.
%
% Optional input:
% 'rvrange' - [min max] or [max] Only plot dipoles with residual variace
% within the given range. Default: plot all dipoles.
% 'summary' - ['on'|'off'|'3d'] Build a summary plot with three views (top,
% back, side). {default: 'off'}
% 'mri' - Matlab file containing an MRI volume and a 4-D transformation
% matrix to go from voxel space to electrode space:
% mri.anatomy contains a 3-D anatomical data array
% mri.transfrom contains a 4-D homogenous transformation matrix.
% 'coordformat' - ['MNI'|'spherical'] Consider that dipole coordinates are in
% MNI or spherical coordinates (for spherical, the radius of the
% head is assumed to be 85 (mm)). See also function sph2spm().
% 'transform' - [real array] traditional transformation matrix to convert
% dipole coordinates to MNI space. Default is assumed from
% 'coordformat' input above. Type help traditional for more
% information.
% 'image' - ['besa'|'mri'] Background image.
% 'mri' (or 'fullmri') uses mean-MRI brain images from the Montreal
% Neurological Institute. This option can also contain a 3-D MRI
% volume (dim 1: left to right; dim 2: anterior-posterior; dim 3:
% superior-inferior). Use 'coregist' to coregister electrodes
% with the MRI. {default: 'mri'}
% 'verbose' - ['on'|'off'] comment on operations on command line {default:
% 'on'}.
% 'plot' - ['on'|'off'] only return outputs {default: 'off'}.
%
% Plotting options:
% 'color' - [cell array of color strings or (1,3) color arrays]. For
% exemple { 'b' 'g' [1 0 0] } gives blue, green and red.
% Dipole colors will rotate through the given colors if
% the number given is less than the number of dipoles to plot.
% A single number will be used as color index in the jet colormap.
% 'view' - 3-D viewing angle in cartesian coords.,
% [0 0 1] gives a sagittal view, [0 -1 0] a view from the rear;
% [1 0 0] gives a view from the side of the head.
% 'mesh' - ['on'|'off'] Display spherical mesh. {Default is 'on'}
% 'meshdata' - [cell array|'file_name'] Mesh data in a cell array { 'vertices'
% data 'faces' data } or a boundary element model filename (the
% function will plot the 3rd mesh in the 'bnd' sub-structure).
% 'axistight' - ['on'|'off'] For MRI only, display the closest MRI
% slide. {Default is 'off'}
% 'gui' - ['on'|'off'] Display controls. {Default is 'on'} If gui 'off',
% a new figure is not created. Useful for incomporating a dipplot
% into a complex figure.
% 'num' - ['on'|'off'] Display component number. Take into account
% dipole size. {Default: 'off'}
% 'cornermri' - ['on'|'off'] force MRI images to the corner of the MRI volume
% (usefull when background is not black). Default: 'off'.
% 'drawedges' - ['on'|'off'] draw edges of the 3-D MRI (black in axistight,
% white otherwise.) Default is 'off'.
% 'projimg' - ['on'|'off'] Project dipole(s) onto the 2-D images, for use
% in making 3-D plots {Default 'off'}
% 'projlines' - ['on'|'off'] Plot lines connecting dipole with 2-D projection.
% Color is dashed black for BESA head and dashed black for the
% MNI brain {Default 'off'}
% 'projcol' - [color] color for the projected line {Default is same as dipole}
% 'dipolesize' - Size of the dipole sphere(s). This option may also contain one
% value per dipole {Default: 30}
% 'dipolelength' - Length of the dipole bar(s) {Default: 1}
% 'pointout' - ['on'|'off'] Point the dipoles outward. {Default: 'off'}
% 'sphere' - [float] radius of sphere corresponding to the skin. Default is 1.
% 'spheres' - ['on'|'off'] {default: 'off'} plot dipole markers as 3-D spheres.
% Does not yet interact with gui buttons, produces non-gui mode.
% 'spheresize' - [real>0] size of spheres (if 'on'). {default: 5}
% 'normlen' - ['on'|'off'] Normalize length of all dipoles. {Default: 'off'}
% 'dipnames' - [cell array] cell array of string with a name for each dipole (or
% pair of dipole).
% 'holdon' - ['on'|'off'] create a new dipplot figure or plot dipoles within an
% an existing figure. Default is 'off'.
% 'camera' - ['auto'|'set'] camera position. 'auto' is the default and
% an option using camera zoom. 'set' is a fixed view that
% does not depend on the content being plotted.
%
% Outputs:
% sources - EEG.source structure with two extra fiels 'mnicoord' and 'talcoord'
% containing the MNI and talairach coordinates of the dipoles. Note
% that for the BEM model, dipoles are already in MNI coordinates.
% X,Y,Z - Locations of dipole heads (Cartesian coordinates in MNI space).
% If there is more than one dipole per components, the last dipole
% is returned.
% XE,YE,ZE - Locations of dipole ends (Cartesian coordinates). The same
% remark as above applies.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 1st July 2002
%
% Notes: See DIPFIT web tutorial at sccn.ucsd.edu/eeglab/dipfittut/dipfit.html
% for more details about MRI co-registration etc...
%
% Example:
% % define dipoles
% sources(1).posxyz = [-59 48 -28]; % position for the first dipole
% sources(1).momxyz = [ 0 58 -69]; % orientation for the first dipole
% sources(1).rv = 0.036; % residual variance for the first dipole
% sources(2).posxyz = [74 -4 -38]; % position for the second dipole
% sources(2).momxyz = [43 -38 -16]; % orientation for the second dipole
% sources(2).rv = 0.027; % residual variance for the second dipole
%
% % plot of the two dipoles (first in green, second in blue)
% dipplot( sources, 'color', { 'g' 'b' });
%
% % To make a stereographic plot
% figure( 'position', [153 553 1067 421];
% subplot(1,3,1); dipplot( sources, 'view', [43 10], 'gui', 'off');
% subplot(1,3,3); dipplot( sources, 'view', [37 10], 'gui', 'off');
%
% % To make a summary plot
% dipplot( sources, 'summary', 'on', 'num', 'on');
%
% See also: eeglab(), dipfit()
% old options
% -----------
% 'std' - [cell array] plot standard deviation of dipoles. i.e.
% { [1:6] [7:12] } plot two elipsoids that best fit all the dipoles
% from 1 to 6 and 7 to 12 with radius 1 standard deviation.
% { { [1:6] 2 'linewidth' 2 } [7:12] } do the same but now the
% first elipsoid is 2 standard-dev and the lines are thicker.
% Copyright (C) 2002 Arnaud Delorme
%
% 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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
% README -- Plotting strategy:
% - All buttons have a tag 'tmp' so they can be removed
% - The component-number buttons have 'userdata' equal to 'editor' and
% can be found easily by other buttons find('userdata', 'editor')
% - All dipoles have a tag 'dipoleX' (X=their number) and can be made
% visible/invisible
% - The gcf object 'userdat' field stores the handle of the dipole that
% is currently being modified
% - Gca 'userdata' stores imqge names and position
function [outsources, XX, YY, ZZ, XO, YO, ZO] = dipplot( sourcesori, varargin )
DEFAULTVIEW = [0 0 1];
if nargin < 1
help dipplot;
return;
end;
% reading and testing arguments
% -----------------------------
sources = sourcesori;
if ~isstruct(sources)
updatedipplot(sources(1));
% sources countain the figure handler
return
end;
% key type range default
g = finputcheck( varargin, { 'color' '' [] [];
'axistight' 'string' { 'on' 'off' } 'off';
'camera' 'string' { 'auto' 'set' } 'auto';
'coordformat' 'string' { 'MNI' 'spherical' 'CTF' 'auto' } 'auto';
'drawedges' 'string' { 'on' 'off' } 'off';
'mesh' 'string' { 'on' 'off' } 'off';
'gui' 'string' { 'on' 'off' } 'on';
'summary' 'string' { 'on2' 'on' 'off' '3d' } 'off';
'verbose' 'string' { 'on' 'off' } 'on';
'view' 'real' [] [0 0 1];
'rvrange' 'real' [0 Inf] [];
'transform' 'real' [0 Inf] [];
'normlen' 'string' { 'on' 'off' } 'off';
'num' 'string' { 'on' 'off' } 'off';
'cornermri' 'string' { 'on' 'off' } 'off';
'mri' { 'string' 'struct' } [] '';
'dipnames' 'cell' [] {};
'projimg' 'string' { 'on' 'off' } 'off';
'projcol' '' [] [];
'projlines' 'string' { 'on' 'off' } 'off';
'pointout' 'string' { 'on' 'off' } 'off';
'holdon' 'string' { 'on' 'off' } 'off';
'dipolesize' 'real' [0 Inf] 30;
'dipolelength' 'real' [0 Inf] 1;
'sphere' 'real' [0 Inf] 1;
'spheres' 'string' {'on' 'off'} 'off';
'links' 'real' [] [];
'image' { 'string' 'real' } [] 'mri';
'plot' 'string' { 'on' 'off' } 'on';
'meshdata' { 'string' 'cell' } [] '' }, 'dipplot');
% 'std' 'cell' [] {};
% 'coreg' 'real' [] [];
if isstr(g), error(g); end;
if strcmpi(g.holdon, 'on'), g.gui = 'off'; end;
if length(g.dipolesize) == 1, g.dipolesize = repmat(g.dipolesize, [1 length(sourcesori)]); end;
g.zoom = 1500;
if strcmpi(g.image, 'besa')
error('BESA image not supported any more. Use EEGLAB version 4.512 or earlier. (BESA dipoles can still be plotted in MNI brain.)');
end;
% trying to determine coordformat
% -------------------------------
if ~isfield(sources, 'momxyz')
g.coordformat = 'spherical';
end;
if strcmpi(g.coordformat, 'auto')
if ~isempty(g.meshdata)
g.coordformat = 'MNI';
if strcmpi(g.verbose, 'on'),
disp('Coordinate format unknown: using ''MNI'' since mesh data was provided as input');
end
else
maxdiplen = 0;
for ind = 1:length(sourcesori)
maxdiplen = max(maxdiplen, max(abs(sourcesori(ind).momxyz(:))));
end;
if maxdiplen>2000
if strcmpi(g.verbose, 'on'),
disp('Coordinate format unknown: using ''MNI'' because of large dipole moments');
end
else
g.coordformat = 'spherical';
if strcmpi(g.verbose, 'on'),
disp('Coordinate format unknown: using ''spherical'' since no mesh data was provided as input');
end
end;
end;
end;
% axis image and limits
% ---------------------
dat.axistight = strcmpi(g.axistight, 'on');
dat.drawedges = g.drawedges;
dat.cornermri = strcmpi(g.cornermri, 'on');
radius = 85;
% look up an MRI file if necessary
% --------------------------------
if isempty(g.mri)
if strcmpi(g.verbose, 'on'),
disp('No MRI file given as input. Looking up one.');
end
dipfitdefs;
g.mri = template_models(1).mrifile;
end;
% read anatomical MRI using Fieldtrip and SPM2 functons
% -----------------------------------------------------
if isstr(g.mri);
try,
g.mri = load('-mat', g.mri);
g.mri = g.mri.mri;
catch,
disp('Failed to read Matlab file. Attempt to read MRI file using function ft_read_mri');
try,
warning off;
g.mri = ft_read_mri(g.mri);
%g.mri.anatomy(find(g.mri.anatomy > 255)) = 255;
%g.mri.anatomy = uint8(g.mri.anatomy);
g.mri.anatomy = round(gammacorrection( g.mri.anatomy, 0.8));
g.mri.anatomy = uint8(round(g.mri.anatomy/max(reshape(g.mri.anatomy, prod(g.mri.dim),1))*255));
% WARNING: if using double instead of int8, the scaling is different
% [-128 to 128 and 0 is not good]
% WARNING: the transform matrix is not 1, 1, 1 on the diagonal, some slices may be
% misplaced
warning on;
catch,
error('Cannot load file using ft_read_mri');
end;
end;
end;
if strcmpi(g.coordformat, 'spherical')
dat.sph2spm = sph2spm;
elseif strcmpi(g.coordformat, 'CTF')
dat.sph2spm = traditionaldipfit([0 0 0 0 0 0 10 -10 10]);
else
dat.sph2spm = []; %traditional([0 0 0 0 0 pi 1 1 1]);
end;
if ~isempty(g.transform), dat.sph2spm = traditionaldipfit(g.transform);
end;
if isfield(g.mri, 'anatomycol')
dat.imgs = g.mri.anatomycol;
else
dat.imgs = g.mri.anatomy;
end;
dat.transform = g.mri.transform;
% MRI coordinates for slices
% --------------------------
if ~isfield(g.mri, 'xgrid')
g.mri.xgrid = [1:size(dat.imgs,1)];
g.mri.ygrid = [1:size(dat.imgs,2)];
g.mri.zgrid = [1:size(dat.imgs,3)];
end;
if strcmpi(g.coordformat, 'CTF')
g.mri.zgrid = g.mri.zgrid(end:-1:1);
end;
dat.imgcoords = { g.mri.xgrid g.mri.ygrid g.mri.zgrid };
dat.maxcoord = [max(dat.imgcoords{1}) max(dat.imgcoords{2}) max(dat.imgcoords{3})];
COLORMESH = 'w';
BACKCOLOR = 'k';
% point 0
% -------
[xx yy zz] = transform(0, 0, 0, dat.sph2spm); % nothing happens for BEM since dat.sph2spm is empty
dat.zeroloc = [ xx yy zz ];
% conversion
% ----------
if strcmpi(g.normlen, 'on')
if isfield(sources, 'besaextori')
sources = rmfield(sources, 'besaextori');
end;
end;
if ~isfield(sources, 'besathloc') & strcmpi(g.image, 'besa') & ~is_sccn
error(['For copyright reasons, it is not possible to use the BESA ' ...
'head model to plot non-BESA dipoles']);
end;
if isfield(sources, 'besathloc')
sources = convertbesaoldformat(sources);
end;
if ~isfield(sources, 'posxyz')
sources = computexyzforbesa(sources);
end;
if ~isfield(sources, 'component')
if strcmpi(g.verbose, 'on'),
disp('No component indices, making incremental ones...');
end
for index = 1:length(sources)
sources(index).component = index;
end;
end;
% find non-empty sources
% ----------------------
noempt = cellfun('isempty', { sources.posxyz } );
sources = sources( find(~noempt) );
% transform coordinates
% ---------------------
outsources = sources;
for index = 1:length(sources)
sources(index).momxyz = sources(index).momxyz/1000;
end;
% remove 0 second dipoles if any
% ------------------------------
for index = 1:length(sources)
if size(sources(index).momxyz,1) == 2
if all(sources(index).momxyz(2,:) == 0)
sources(index).momxyz = sources(index).momxyz(1,:);
sources(index).posxyz = sources(index).posxyz(1,:);
end;
end;
end;
% remove sources with out of bound Residual variance
% --------------------------------------------------
if isfield(sources, 'rv') & ~isempty(g.rvrange)
if length(g.rvrange) == 1, g.rvrange = [ 0 g.rvrange ]; end;
for index = length(sources):-1:1
if sources(index).rv < g.rvrange(1)/100 | sources(index).rv > g.rvrange(2)/100
sources(index) = [];
end;
end;
end;
% color array
% -----------
if isempty(g.color)
g.color = { 'g' 'b' 'r' 'm' 'c' 'y' };
if strcmp(BACKCOLOR, 'w'), g.color = { g.color{:} 'k' }; end;
end;
g.color = g.color(mod(0:length(sources)-1, length(g.color)) +1);
if ~isempty(g.color)
g.color = strcol2real( g.color, jet(64) );
end;
if ~isempty(g.projcol)
g.projcol = strcol2real( g.projcol, jet(64) );
g.projcol = g.projcol(mod(0:length(sources)-1, length(g.projcol)) +1);
else
g.projcol = g.color;
for index = 1:length(g.color)
g.projcol{index} = g.projcol{index}/2;
end;
end;
% build summarized figure
% -----------------------
if strcmpi(g.summary, 'on') | strcmpi(g.summary, 'on2')
figure;
options = { 'gui', 'off', 'dipolesize', g.dipolesize/1.5,'dipolelength', g.dipolelength, 'sphere', g.sphere ...
'color', g.color, 'mesh', g.mesh, 'num', g.num, 'image', g.image 'normlen' g.normlen ...
'coordformat' g.coordformat 'mri' g.mri 'meshdata' g.meshdata 'axistight' g.axistight };
pos1 = [0 0 0.5 0.5];
pos2 = [0 0.5 0.5 .5];
pos3 = [.5 .5 0.5 .5]; if strcmp(g.summary, 'on2'), tmp = pos1; pos1 =pos3; pos3 = tmp; end;
axes('position', pos1); newsources = dipplot(sourcesori, 'view', [1 0 0] , options{:}); axis off;
axes('position', pos2); newsources = dipplot(sourcesori, 'view', [0 0 1] , options{:}); axis off;
axes('position', pos3); newsources = dipplot(sourcesori, 'view', [0 -1 0], options{:}); axis off;
axes('position', [0.5 0 0.5 0.5]);
colorcount = 1;
if isfield(newsources, 'component')
for index = 1:length(newsources)
if isempty(g.dipnames), tmpname = sprintf( 'Comp. %d', newsources(index).component);
else tmpname = char(g.dipnames{index});
end;
talpos = newsources(index).talcoord;
if strcmpi(g.coordformat, 'CTF')
textforgui(colorcount) = { sprintf( [ tmpname ' (RV:%3.2f%%)' ], 100*newsources(index).rv) };
elseif size(talpos,1) == 1
textforgui(colorcount) = { sprintf( [ tmpname ' (RV:%3.2f%%; Tal:%d,%d,%d)' ], ...
100*newsources(index).rv, ...
round(talpos(1,1)), round(talpos(1,2)), round(talpos(1,3))) };
else
textforgui(colorcount) = { sprintf( [ tmpname ' (RV:%3.2f%%; Tal:%d,%d,%d & %d,%d,%d)' ], ...
100*newsources(index).rv, ...
round(talpos(1,1)), round(talpos(1,2)), round(talpos(1,3)), ...
round(talpos(2,1)), round(talpos(2,2)), round(talpos(2,3))) };
end;
colorcount = colorcount+1;
end;
colorcount = colorcount-1;
allstr = strvcat(textforgui{:});
h = text(0,0.45, allstr);
if colorcount >= 15, set(h, 'fontsize', 8);end;
if colorcount >= 20, set(h, 'fontsize', 6);end;
if strcmp(BACKCOLOR, 'k'), set(h, 'color', 'w'); end;
end;
axis off;
return;
elseif strcmpi(g.summary, '3d')
options = { 'gui', 'off', 'dipolesize', g.dipolesize/1.5,'dipolelength', g.dipolelength, 'sphere', g.sphere, 'spheres', g.spheres ...
'color', g.color, 'mesh', g.mesh, 'num', g.num, 'image', g.image 'normlen' g.normlen ...
'coordformat' g.coordformat 'mri' g.mri 'meshdata' g.meshdata 'axistight' g.axistight };
figure('position', [ 100 600 600 200 ]);
axes('position', [-0.1 -0.1 1.2 1.2], 'color', 'k'); axis off; blackimg = zeros(10,10,3); image(blackimg);
axes('position', [0 0 1/3 1], 'tag', 'rear'); dipplot(sourcesori, options{:}, 'holdon', 'on'); view([0 -1 0]);
axes('position', [1/3 0 1/3 1], 'tag', 'top' ); dipplot(sourcesori, options{:}, 'holdon', 'on'); view([0 0 1]);
axes('position', [2/3 0 1/3 1], 'tag', 'side'); dipplot(sourcesori, options{:}, 'holdon', 'on'); view([1 -0.01 0]);
set(gcf, 'paperpositionmode', 'auto');
return;
end;
% plot head graph in 3D
% ---------------------
if strcmp(g.gui, 'on')
fig = figure('visible', g.plot);
pos = get(gca, 'position');
set(gca, 'position', [pos(1)+0.05 pos(2:end)]);
end;
indx = ceil(dat.imgcoords{1}(end)/2);
indy = ceil(dat.imgcoords{2}(end)/2);
indz = ceil(dat.imgcoords{3}(end)/2);
if strcmpi(g.holdon, 'off')
plotimgs( dat, [indx indy indz], dat.transform);
set(gca, 'color', BACKCOLOR);
%warning off; a = imread('besaside.pcx'); warning on;
% BECAUSE OF A BUG IN THE WARP FUNCTION, THIS DOES NOT WORK (11/02)
%hold on; warp([], wy, wz, a);
% set camera target
% -----------------
% format axis (BESA or MRI)
axis equal;
set(gca, 'cameraviewanglemode', 'manual'); % disable change size
camzoom(1.2^2);
if strcmpi(g.coordformat, 'CTF'), g.view(2:3) = -g.view(2:3); end;
view(g.view);
%set(gca, 'cameratarget', dat.zeroloc); % disable change size
%set(gca, 'cameraposition', dat.zeroloc+g.view*g.zoom); % disable change size
axis off;
end;
% plot sphere mesh and nose
% -------------------------
if strcmpi(g.holdon, 'off')
if isempty(g.meshdata)
SPHEREGRAIN = 20; % 20 is also Matlab default
[x y z] = sphere(SPHEREGRAIN);
hold on;
[xx yy zz] = transform(x*0.085, y*0.085, z*0.085, dat.sph2spm);
[xx yy zz] = transform(x*85 , y*85 , z*85 , dat.sph2spm);
%xx = x*100;
%yy = y*100;
%zz = z*100;
if strcmpi(COLORMESH, 'w')
hh = mesh(xx, yy, zz, 'cdata', ones(21,21,3), 'tag', 'mesh'); hidden off;
else
hh = mesh(xx, yy, zz, 'cdata', zeros(21,21,3), 'tag', 'mesh'); hidden off;
end;
else
try,
if isstr(g.meshdata)
tmp = load('-mat', g.meshdata);
g.meshdata = { 'vertices' tmp.vol.bnd(1).pnt 'faces' tmp.vol.bnd(1).tri };
end;
hh = patch(g.meshdata{:}, 'facecolor', 'none', 'edgecolor', COLORMESH, 'tag', 'mesh');
catch, disp('Unrecognize model file (probably CTF)'); end;
end;
end;
%x = x*100*scaling; y = y*100*scaling; z=z*100*scaling;
%h = line(xx,yy,zz); set(h, 'color', COLORMESH, 'linestyle', '--', 'tag', 'mesh');
%h = line(xx,zz,yy); set(h, 'color', COLORMESH, 'linestyle', '--', 'tag', 'mesh');
%h = line([0 0;0 0],[-1 -1.2; -1.2 -1], [-0.3 -0.7; -0.7 -0.7]);
%set(h, 'color', COLORMESH, 'linewidth', 3, 'tag', 'noze');
% determine max length if besatextori exist
% -----------------------------------------
sizedip = [];
for index = 1:length(sources)
sizedip = [ sizedip sources(index).momxyz(3) ];
end;
maxlength = max(sizedip);
% diph = gca; % DEBUG
% colormap('jet');
% cbar
% axes(diph);
for index = 1:length(sources)
nbdip = 1;
if size(sources(index).posxyz, 1) > 1 & any(sources(index).posxyz(2,:)) nbdip = 2; end;
% reorder dipoles for plotting
if nbdip == 2
if sources(index).posxyz(1,1) > sources(index).posxyz(2,1)
tmp = sources(index).posxyz(2,:);
sources(index).posxyz(2,:) = sources(index).posxyz(1,:);
sources(index).posxyz(1,:) = tmp;
tmp = sources(index).momxyz(2,:);
sources(index).momxyz(2,:) = sources(index).momxyz(1,:);
sources(index).momxyz(1,:) = tmp;
end;
if isfield(sources, 'active'),
nbdip = length(sources(index).active);
end;
end;
% dipole length
% -------------
multfactor = 1;
if strcmpi(g.normlen, 'on')
if nbdip == 1
len = sqrt(sum(sources(index).momxyz(1,:).^2));
else
len1 = sqrt(sum(sources(index).momxyz(1,:).^2));
len2 = sqrt(sum(sources(index).momxyz(2,:).^2));
len = mean([len1 len2]);
end;
if strcmpi(g.coordformat, 'CTF'), len = len*10; end;
if len ~= 0, multfactor = 15/len; end;
else
if strcmpi(g.coordformat, 'spherical')
multfactor = 100;
else multfactor = 1.5;
end;
end;
for dip = 1:nbdip
x = sources(index).posxyz(dip,1);
y = sources(index).posxyz(dip,2);
z = sources(index).posxyz(dip,3);
xo = sources(index).momxyz(dip,1)*g.dipolelength*multfactor;
yo = sources(index).momxyz(dip,2)*g.dipolelength*multfactor;
zo = sources(index).momxyz(dip,3)*g.dipolelength*multfactor;
xc = 0;
yc = 0;
zc = 0;
centvec = [xo-xc yo-yc zo-zc]; % vector pointing into center
dipole_orient = [x+xo y+yo z+zo]/norm([x+xo y+yo z+zo]);
c = dot(centvec, dipole_orient);
if strcmpi(g.pointout,'on')
if (c < 0) | (abs([x+xo,y+yo,z+zo]) < abs([x,y,z]))
xo1 = x-xo; % make dipole point outward from head center
yo1 = y-yo;
zo1 = z-zo;
%fprintf('invert because: %e \n', c);
else
xo1 = x+xo;
yo1 = y+yo;
zo1 = z+zo;
%fprintf('NO invert because: %e \n', c);
end
else
xo1 = x+xo;
yo1 = y+yo;
zo1 = z+zo;
%fprintf('NO invert because: %e \n', c);
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw dipole bar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
tag = [ 'dipole' num2str(index) ];
% from spherical to electrode space
% ---------------------------------
[xx yy zz] = transform(x, y, z, dat.sph2spm); % nothing happens for BEM
[xxo1 yyo1 zzo1] = transform(xo1, yo1, zo1, dat.sph2spm); % because dat.sph2spm = []
if ~strcmpi(g.spheres,'on') % plot dipole direction lines
h1 = line( [xx xxo1]', [yy yyo1]', [zz zzo1]');
elseif g.dipolelength>0 % plot dipole direction cylinders with end cap patch
[xc yc zc] = cylinder( 2, 10);
[xs ys zs] = sphere(10);
xc = [ xc; -xs(7:11,:)*2 ];
yc = [ yc; -ys(7:11,:)*2 ];
zc = [ zc; zs(7:11,:)/5+1 ];
colorarray = repmat(reshape(g.color{index}, 1,1,3), [size(zc,1) size(zc,2) 1]);
handles = surf(xc, yc, zc, colorarray, 'tag', tag, 'edgecolor', 'none', ...
'backfacelighting', 'lit', 'facecolor', 'interp', 'facelighting', ...
'phong', 'ambientstrength', 0.3);
[xc yc zc] = adjustcylinder2( handles, [xx yy zz], [xxo1 yyo1 zzo1] );
cx = mean(xc,2); %cx = [(3*cx(1)+cx(2))/4; (cx(1)+3*cx(2))/4];
cy = mean(yc,2); %cy = [(3*cy(1)+cy(2))/4; (cy(1)+3*cy(2))/4];
cz = mean(zc,2); %cz = [(3*cz(1)+cz(2))/4; (cz(1)+3*cz(2))/4];
tmpx = xc - repmat(cx, [1 size(xc, 2)]);
tmpy = yc - repmat(cy, [1 size(xc, 2)]);
tmpz = zc - repmat(cz, [1 size(xc, 2)]);
l=sqrt(tmpx.^2+tmpy.^2+tmpz.^2);
warning('off', 'MATLAB:divideByZero'); % this is due to a Matlab 2008b (or later)
normals = reshape([tmpx./l tmpy./l tmpz./l],[size(tmpx) 3]); % in the rotate function in adjustcylinder2
warning('off', 'MATLAB:divideByZero'); % one of the z (the last row is not rotated)
set( handles, 'vertexnormals', normals);
end
[xxmri yymri zzmri ] = transform(xx, yy, zz, pinv(dat.transform));
[xxmrio1 yymrio1 zzmrio1] = transform(xxo1, yyo1, zzo1, pinv(dat.transform));
dipstruct.mricoord = [xxmri yymri zzmri]; % Coordinates in MRI space
dipstruct.eleccoord = [ xx yy zz ]; % Coordinates in elec space
dipstruct.posxyz = sources(index).posxyz; % Coordinates in spherical space
outsources(index).eleccoord(dip,:) = [xx yy zz];
outsources(index).mnicoord(dip,:) = [xx yy zz];
outsources(index).mricoord(dip,:) = [xxmri yymri zzmri];
outsources(index).talcoord(dip,:) = mni2tal([xx yy zz]')';
dipstruct.talcoord = mni2tal([xx yy zz]')';
% copy for output
% ---------------
XX(index) = xxmri;
YY(index) = yymri;
ZZ(index) = zzmri;
XO(index) = xxmrio1;
YO(index) = yymrio1;
ZO(index) = zzmrio1;
if isempty(g.dipnames)
dipstruct.rv = sprintf('%3.2f', sources(index).rv*100);
dipstruct.name = sources(index).component;
else
dipstruct.rv = sprintf('%3.2f', sources(index).rv*100);
dipstruct.name = g.dipnames{index};
end;
if ~strcmpi(g.spheres,'on') % plot disk markers
set(h1,'userdata',dipstruct,'tag',tag,'color','k','linewidth',g.dipolesize(index)/7.5);
if strcmp(BACKCOLOR, 'k'), set(h1, 'color', g.color{index}); end;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw sphere or disk marker %%%%%%%%%%%%%%%%%%%%%%%%%
%
hold on;
if strcmpi(g.spheres,'on') % plot spheres
if strcmpi(g.projimg, 'on')
if strcmpi(g.verbose, 'on'),
disp('Warning: projections cannot be plotted for 3-D sphere');
end
%tmpcolor = g.color{index} / 2;
%h = plotsphere([xx yy zz], g.dipolesize/6, 'color', g.color{index}, 'proj', ...
% [dat.imgcoords{1}(1) dat.imgcoords{2}(end) dat.imgcoords{3}(1)]*97/100, 'projcol', tmpcolor);
%set(h(2:end), 'userdata', 'proj', 'tag', tag);
else
%h = plotsphere([xx yy zz], g.dipolesize/6, 'color', g.color{index});
end;
h = plotsphere([xx yy zz], g.dipolesize(index)/6, 'color', g.color{index});
set(h(1), 'userdata', dipstruct, 'tag', tag);
else % plot dipole markers
h = plot3(xx, yy, zz);
set(h, 'userdata', dipstruct, 'tag', tag, ...
'marker', '.', 'markersize', g.dipolesize(index), 'color', g.color{index});
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% project onto images %%%%%%%%%%%%%%%%%%%%%%%%%
%
[tmp1xx tmp1yy tmp1zz ] = transform( xxmri , yymri , dat.imgcoords{3}(1), dat.transform);
[tmp1xxo1 tmp1yyo1 tmp1zzo1] = transform( xxmrio1, yymrio1, dat.imgcoords{3}(1), dat.transform);
[tmp2xx tmp2yy tmp2zz ] = transform( xxmri , dat.imgcoords{2}(end), zzmri , dat.transform);
[tmp2xxo1 tmp2yyo1 tmp2zzo1] = transform( xxmrio1, dat.imgcoords{2}(end), zzmrio1, dat.transform);
[tmp3xx tmp3yy tmp3zz ] = transform( dat.imgcoords{1}(1), yymri , zzmri , dat.transform);
[tmp3xxo1 tmp3yyo1 tmp3zzo1] = transform( dat.imgcoords{1}(1), yymrio1, zzmrio1, dat.transform);
if strcmpi(g.projimg, 'on') & strcmpi(g.spheres, 'off')
tmpcolor = g.projcol{index};
% project onto z axis
tag = [ 'dipole' num2str(index) ];
if ~strcmpi(g.image, 'besa')
h = line( [tmp1xx tmp1xxo1]', [tmp1yy tmp1yyo1]', [tmp1zz tmp1zzo1]');
set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize(index)/7.5);
end;
if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;
h = plot3(tmp1xx, tmp1yy, tmp1zz);
set(h, 'userdata', 'proj', 'tag', tag, ...
'marker', '.', 'markersize', g.dipolesize(index), 'color', tmpcolor);
% project onto y axis
tag = [ 'dipole' num2str(index) ];
if ~strcmpi(g.image, 'besa')
h = line( [tmp2xx tmp2xxo1]', [tmp2yy tmp2yyo1]', [tmp2zz tmp2zzo1]');
set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize(index)/7.5);
end;
if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;
h = plot3(tmp2xx, tmp2yy, tmp2zz);
set(h, 'userdata', 'proj', 'tag', tag, ...
'marker', '.', 'markersize', g.dipolesize(index), 'color', tmpcolor);
% project onto x axis
tag = [ 'dipole' num2str(index) ];
if ~strcmpi(g.image, 'besa')
h = line( [tmp3xx tmp3xxo1]', [tmp3yy tmp3yyo1]', [tmp3zz tmp3zzo1]');
set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize(index)/7.5);
end;
if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;
h = plot3(tmp3xx, tmp3yy, tmp3zz);
set(h, 'userdata', 'proj', 'tag', tag, ...
'marker', '.', 'markersize', g.dipolesize(index), 'color', tmpcolor);
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% project onto axes %%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(g.projlines, 'on')
clear h;
% project onto z axis
tag = [ 'dipole' num2str(index) ];
h(1) = line( [xx tmp1xx]', [yy tmp1yy]', [zz tmp1zz]);
set(h(1), 'userdata', 'proj', 'linestyle', '--', ...
'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize(index)/7.5/5);
% project onto x axis
tag = [ 'dipole' num2str(index) ];
h(2) = line( [xx tmp2xx]', [yy tmp2yy]', [zz tmp2zz]);
set(h(2), 'userdata', 'proj', 'linestyle', '--', ...
'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize(index)/7.5/5);
% project onto y axis
tag = [ 'dipole' num2str(index) ];
h(3) = line( [xx tmp3xx]', [yy tmp3yy]', [zz tmp3zz]);
set(h(3), 'userdata', 'proj', 'linestyle', '--', ...
'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize(index)/7.5/5);
if ~isempty(g.projcol)
set(h, 'color', g.projcol{index});
end;
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw text %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isfield(sources, 'component')
if strcmp(g.num, 'on')
h = text(xx, yy, zz, [ ' ' int2str(sources(index).component)]);
set(h, 'userdata', dipstruct, 'tag', tag, 'fontsize', g.dipolesize(index)/2 );
if ~strcmpi(g.image, 'besa'), set(h, 'color', 'w'); end;
end;
end;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 3-D settings
if strcmpi(g.spheres, 'on')
lighting phong;
material shiny;
camlight left;
camlight right;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw elipse for group of dipoles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% does not work because of new scheme, have to be reprogrammed
%if ~isempty(g.std)
% for index = 1:length(g.std)
% if ~iscell(g.std{index})
% plotellipse(sources, g.std{index}, 1, dat.tcparams, dat.coreg);
% else
% sc = plotellipse(sources, g.std{index}{1}, g.std{index}{2}, dat.tcparams, dat.coreg);
% if length( g.std{index} ) > 2
% set(sc, g.std{index}{3:end});
% end;
% end;
% end;
% end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% buttons %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nbsrc = int2str(length(sources));
cbmesh = [ 'if get(gcbo, ''userdata''), ' ...
' set(findobj(''parent'', gca, ''tag'', ''mesh''), ''visible'', ''off'');' ...
' set(gcbo, ''string'', ''Mesh on'');' ...
' set(gcbo, ''userdata'', 0);' ...
'else,' ...
' set(findobj(''parent'', gca, ''tag'', ''mesh''), ''visible'', ''on'');' ...
' set(gcbo, ''string'', ''Mesh off'');' ...
' set(gcbo, ''userdata'', 1);' ...
'end;' ];
cbplot = [ 'if strcmpi(get(gcbo, ''string''), ''plot one''),' ...
' for tmpi = 1:' nbsrc ',' ...
' set(findobj(''parent'', gca, ''tag'', [ ''dipole'' int2str(tmpi) ]), ''visible'', ''off'');' ...
' end; clear tmpi;' ...
' dipplot(gcbf);' ...
' set(gcbo, ''string'', ''Plot all'');' ...
'else,' ...
' for tmpi = 1:' nbsrc ',' ...
' set(findobj(''parent'', gca, ''tag'', [ ''dipole'' int2str(tmpi) ]), ''visible'', ''on'');' ...
' end; clear tmpi;' ...
' set(gcbo, ''string'', ''Plot one'');' ...
'end;' ];
cbview = [ 'tmpuserdat = get(gca, ''userdata'');' ...
'if tmpuserdat.axistight, ' ...
' set(gcbo, ''string'', ''Tight view'');' ...
'else,' ...
' set(gcbo, ''string'', ''Loose view'');' ...
'end;' ...
'tmpuserdat.axistight = ~tmpuserdat.axistight;' ...
'set(gca, ''userdata'', tmpuserdat);' ...
'clear tmpuserdat;' ...
'dipplot(gcbf);' ];
viewstring = fastif(dat.axistight, 'Loose view', 'Tight view');
enmesh = fastif(isempty(g.meshdata) & strcmpi(g.coordformat, 'MNI'), 'off', 'on');
if strcmpi(g.coordformat, 'CTF'), viewcor = 'view([0 1 0]);'; viewtop = 'view([0 0 -1]);'; vis = 'off';
else viewcor = 'view([0 -1 0]);'; viewtop = 'view([0 0 1]);'; vis = 'on';
end;
h = uicontrol( 'unit', 'normalized', 'position', [0 0 .15 1], 'tag', 'tmp', ...
'style', 'text', 'string',' ');
h = uicontrol( 'unit', 'normalized', 'position', [0 0 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'fontweight', 'bold', 'string', 'No controls', 'callback', ...
'set(findobj(''parent'', gcbf, ''tag'', ''tmp''), ''visible'', ''off'');');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.05 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Top view', 'callback', viewtop);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.1 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Coronal view', 'callback', viewcor);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.15 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Sagittal view', 'callback', 'view([1 0 0]);');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.2 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', viewstring, 'callback', cbview);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.25 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Mesh on', 'userdata', 0, 'callback', ...
cbmesh, 'enable', enmesh, 'visible', vis );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.3 .15 .05], 'tag', 'tmp', ...
'style', 'text', 'string', 'Display:','fontweight', 'bold' );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.35 .15 .02], 'tag', 'tmp',...
'style', 'text', 'string', '');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.37 .15 .05], 'tag', 'tmp','userdata', 'z',...
'style', 'text', 'string', 'Z:', 'visible', vis );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.42 .15 .05], 'tag', 'tmp','userdata', 'y', ...
'style', 'text', 'string', 'Y:', 'visible', vis );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.47 .15 .05], 'tag', 'tmp', 'userdata', 'x',...
'style', 'text', 'string', 'X:', 'visible', vis );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.52 .15 .05], 'tag', 'tmp', 'userdata', 'rv',...
'style', 'text', 'string', 'RV:' );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.57 .15 .05], 'tag', 'tmp', 'userdata', 'comp', ...
'style', 'text', 'string', '');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.62 .15 .05], 'tag', 'tmp', 'userdata', 'editor', ...
'style', 'edit', 'string', '1', 'callback', ...
[ 'dipplot(gcbf);' ] );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.67 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Keep|Prev', 'callback', ...
[ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...
'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))-1));' ...
'tmpobj = get(gcf, ''userdata'');' ...
'eval(get(editobj, ''callback''));' ...
'set(tmpobj, ''visible'', ''on'');' ...
'clear editobj tmpobj;' ]);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.72 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Prev', 'callback', ...
[ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...
'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))-1));' ...
'eval(get(editobj, ''callback''));' ...
'clear editobj;' ]);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.77 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Next', 'callback', ...
[ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...
'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))+1));' ...
'dipplot(gcbf);' ...
'clear editobj;' ]);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.82 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Keep|Next', 'callback', ...
[ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...
'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))+1));' ...
'tmpobj = get(gcf, ''userdata'');' ...
'dipplot(gcbf);' ...
'set(tmpobj, ''visible'', ''on'');' ...
'clear editobj tmpobj;' ]);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.87 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Plot one', 'callback', cbplot);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.92 .15 .05], 'tag', 'tmp', ...
'style', 'text', 'string', [num2str(length(sources)) ' dipoles:'], 'fontweight', 'bold' );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.97 .15 .05], 'tag', 'tmp', ...
'style', 'text', 'string', '');
set(gcf, 'userdata', findobj('parent', gca, 'tag', 'dipole1'));
dat.nbsources = length(sources);
set(gca, 'userdata', dat ); % last param=1 for MRI view tight/loose
set(gcf, 'color', BACKCOLOR);
if strcmp(g.gui, 'off') | strcmpi(g.holdon, 'on')
set(findobj('parent', gcf, 'tag', 'tmp'), 'visible', 'off');
end;
if strcmp(g.mesh, 'off')
set(findobj('parent', gca, 'tag', 'mesh'), 'visible', 'off');
end;
updatedipplot(gcf);
rotate3d on;
% close figure if necessary
if strcmpi(g.plot, 'off')
try, close(fig); catch, end;
end;
if strcmpi(g.holdon, 'on')
box off;
axis equal;
axis off;
end;
% set camera positon
if strcmpi(g.camera, 'set')
set(gca, 'CameraPosition', [2546.94 -894.981 689.613], ...
'CameraPositionMode', 'manual', ...
'CameraTarget', [0 -18 18], ...
'CameraTargetMode', 'manual', ...
'CameraUpVector', [0 0 1], ...
'CameraUpVectorMode', 'manual', ...
'CameraViewAngle', [3.8815], ...
'CameraViewAngleMode', 'manual');
end;
return;
% electrode space to MRI space
% ============================
function [x,y,z] = transform(x, y, z, transmat);
if isempty(transmat), return; end;
for i = 1:size(x,1)
for j = 1:size(x,2)
tmparray = transmat * [ x(i,j) y(i,j) z(i,j) 1 ]';
x(i,j) = tmparray(1);
y(i,j) = tmparray(2);
z(i,j) = tmparray(3);
end;
end;
% does not work any more
% ----------------------
function sc = plotellipse(sources, ind, nstd, TCPARAMS, coreg);
for i = 1:length(ind)
tmpval(1,i) = -sources(ind(i)).posxyz(1);
tmpval(2,i) = -sources(ind(i)).posxyz(2);
tmpval(3,i) = sources(ind(i)).posxyz(3);
[tmpval(1,i) tmpval(2,i) tmpval(3,i)] = transform(tmpval(1,i), tmpval(2,i), tmpval(3,i), TCPARAMS);
end;
% mean and covariance
C = cov(tmpval');
M = mean(tmpval,2);
[U,L] = eig(C);
% For N standard deviations spread of data, the radii of the eliipsoid will
% be given by N*SQRT(eigenvalues).
radii = nstd*sqrt(diag(L));
% generate data for "unrotated" ellipsoid
[xc,yc,zc] = ellipsoid(0,0,0,radii(1),radii(2),radii(3), 10);
% rotate data with orientation matrix U and center M
a = kron(U(:,1),xc); b = kron(U(:,2),yc); c = kron(U(:,3),zc);
data = a+b+c; n = size(data,2);
x = data(1:n,:)+M(1); y = data(n+1:2*n,:)+M(2); z = data(2*n+1:end,:)+M(3);
% now plot the rotated ellipse
c = ones(size(z));
sc = mesh(x,y,z);
alpha(0.5)
function newsrc = convertbesaoldformat(src);
newsrc = [];
count = 1;
countdip = 1;
if ~isfield(src, 'besaextori'), src(1).besaextori = []; end;
for index = 1:length(src)
% convert format
% --------------
if isempty(src(index).besaextori), src(index).besaextori = 300; end; % 20 mm
newsrc(count).possph(countdip,:) = [ src(index).besathloc src(index).besaphloc src(index).besaexent];
newsrc(count).momsph(countdip,:) = [ src(index).besathori src(index).besaphori src(index).besaextori/300];
% copy other fields
% -----------------
if isfield(src, 'stdX')
newsrc(count).stdX = -src(index).stdY;
newsrc(count).stdY = src(index).stdX;
newsrc(count).stdZ = src(index).stdZ;
end;
if isfield(src, 'rv')
newsrc(count).rv = src(index).rv;
end;
if isfield(src, 'elecrv')
newsrc(count).rvelec = src(index).elecrv;
end;
if isfield(src, 'component')
newsrc(count).component = src(index).component;
if index ~= length(src) & src(index).component == src(index+1).component
countdip = countdip + 1;
else
count = count + 1; countdip = 1;
end;
else
count = count + 1; countdip = 1;
end;
end;
function src = computexyzforbesa(src);
for index = 1:length( src )
for index2 = 1:size( src(index).possph, 1 )
% compute coordinates
% -------------------
postmp = src(index).possph(index2,:);
momtmp = src(index).momsph(index2,:);
phi = postmp(1)+90; %% %%%%%%%%%%%%%%% USE BESA COORDINATES %%%%%
theta = postmp(2); %% %%%%%%%%%%%%%%% USE BESA COORDINATES %%%%%
phiori = momtmp(1)+90; %% %%%%%%%%%%%% USE BESA COORDINATES %%%%%
thetaori = momtmp(2); %% %%%%%%%%%%%% USE BESA COORDINATES %%%%%
% exentricities are in % of the radius of the head sphere
[x y z] = sph2cart(theta/180*pi, phi/180*pi, postmp(3)/1.2);
[xo yo zo] = sph2cart(thetaori/180*pi, phiori/180*pi, momtmp(3)*5); % exentricity scaled for compatibility with DIPFIT
src(index).posxyz(index2,:) = [-y x z];
src(index).momxyz(index2,:) = [-yo xo zo];
end;
end;
% update dipplot (callback call)
% ------------------------------
function updatedipplot(fig)
% find current dipole index and test for authorized range
% -------------------------------------------------------
dat = get(gca, 'userdata');
editobj = findobj('parent', fig, 'userdata', 'editor');
tmpnum = str2num(get(editobj(end), 'string'));
if tmpnum < 1, tmpnum = 1; end;
if tmpnum > dat.nbsources, tmpnum = dat.nbsources; end;
set(editobj(end), 'string', num2str(tmpnum));
% hide current dipole, find next dipole and show it
% -------------------------------------------------
set(get(gcf, 'userdata'), 'visible', 'off');
newdip = findobj('parent', gca, 'tag', [ 'dipole' get(editobj(end), 'string')]);
set(newdip, 'visible', 'on');
set(gcf, 'userdata', newdip);
% find all dipolar structures
% ---------------------------
index = 1;
count = 1;
for index = 1:length(newdip)
if isstruct( get(newdip(index), 'userdata') )
dip_mricoord(count,:) = getfield(get(newdip(index), 'userdata'), 'mricoord');
count = count+1;
foundind = index;
end;
end;
% get residual variance
% ---------------------
if exist('foundind')
tmp = get(newdip(foundind), 'userdata');
tal = tmp.talcoord;
if ~isstr( tmp.name )
tmprvobj = findobj('parent', fig, 'userdata', 'comp'); set( tmprvobj(end), 'string', [ 'Comp: ' int2str(tmp.name) ] );
else tmprvobj = findobj('parent', fig, 'userdata', 'comp'); set( tmprvobj(end), 'string', tmp.name );
end;
tmprvobj = findobj('parent', fig, 'userdata', 'rv'); set( tmprvobj(end), 'string', [ 'RV: ' tmp.rv '%' ] );
tmprvobj = findobj('parent', fig, 'userdata', 'x'); set( tmprvobj(end), 'string', [ 'X tal: ' int2str(round(tal(1))) ]);
tmprvobj = findobj('parent', fig, 'userdata', 'y'); set( tmprvobj(end), 'string', [ 'Y tal: ' int2str(round(tal(2))) ]);
tmprvobj = findobj('parent', fig, 'userdata', 'z'); set( tmprvobj(end), 'string', [ 'Z tal: ' int2str(round(tal(3))) ]);
end
% adapt the MRI to the dipole depth
% ---------------------------------
delete(findobj('parent', gca, 'tag', 'img'));
tmpdiv1 = dat.imgcoords{1}(2)-dat.imgcoords{1}(1);
tmpdiv2 = dat.imgcoords{2}(2)-dat.imgcoords{2}(1);
tmpdiv3 = dat.imgcoords{3}(2)-dat.imgcoords{3}(1);
if ~dat.axistight
[xx yy zz] = transform(0,0,0, pinv(dat.transform)); % elec -> MRI space
indx = minpos(dat.imgcoords{1}-zz);
indy = minpos(dat.imgcoords{2}-yy);
indz = minpos(dat.imgcoords{3}-xx);
else
if ~dat.cornermri
indx = minpos(dat.imgcoords{1} - mean(dip_mricoord(:,1))) - 3*tmpdiv1;
indy = minpos(dat.imgcoords{2} - mean(dip_mricoord(:,2))) + 3*tmpdiv2;
indz = minpos(dat.imgcoords{3} - mean(dip_mricoord(:,3))) - 3*tmpdiv3;
else % no need to shift slice if not ploted close to the dipole
indx = minpos(dat.imgcoords{1} - mean(dip_mricoord(:,1)));
indy = minpos(dat.imgcoords{2} - mean(dip_mricoord(:,2)));
indz = minpos(dat.imgcoords{3} - mean(dip_mricoord(:,3)));
end;
end;
% middle of the brain
% -------------------
plotimgs( dat,min(max([indx indy indz],1),size(dat.imgs)), dat.transform);
%end;
% plot images (transmat is the uniform matrix MRI coords -> elec coords)
% ----------------------------------------------------------------------
function plotimgs(dat, mricoord, transmat);
% loading images
% --------------
if ndims(dat.imgs) == 4 % true color data
img1(:,:,3) = rot90(squeeze(dat.imgs(mricoord(1),:,:,3)));
img2(:,:,3) = rot90(squeeze(dat.imgs(:,mricoord(2),:,3)));
img3(:,:,3) = rot90(squeeze(dat.imgs(:,:,mricoord(3),3)));
img1(:,:,2) = rot90(squeeze(dat.imgs(mricoord(1),:,:,2)));
img2(:,:,2) = rot90(squeeze(dat.imgs(:,mricoord(2),:,2)));
img3(:,:,2) = rot90(squeeze(dat.imgs(:,:,mricoord(3),2)));
img1(:,:,1) = rot90(squeeze(dat.imgs(mricoord(1),:,:,1)));
img2(:,:,1) = rot90(squeeze(dat.imgs(:,mricoord(2),:,1)));
img3(:,:,1) = rot90(squeeze(dat.imgs(:,:,mricoord(3),1)));
else
img1 = rot90(squeeze(dat.imgs(mricoord(1),:,:)));
img2 = rot90(squeeze(dat.imgs(:,mricoord(2),:)));
img3 = rot90(squeeze(dat.imgs(:,:,mricoord(3))));
if ndims(img1) == 2, img1(:,:,3) = img1; img1(:,:,2) = img1(:,:,1); end;
if ndims(img2) == 2, img2(:,:,3) = img2; img2(:,:,2) = img2(:,:,1); end;
if ndims(img3) == 2, img3(:,:,3) = img3; img3(:,:,2) = img3(:,:,1); end;
end;
% computing coordinates for planes
% --------------------------------
wy1 = [min(dat.imgcoords{2}) max(dat.imgcoords{2}); min(dat.imgcoords{2}) max(dat.imgcoords{2})];
wz1 = [min(dat.imgcoords{3}) min(dat.imgcoords{3}); max(dat.imgcoords{3}) max(dat.imgcoords{3})];
wx2 = [min(dat.imgcoords{1}) max(dat.imgcoords{1}); min(dat.imgcoords{1}) max(dat.imgcoords{1})];
wz2 = [min(dat.imgcoords{3}) min(dat.imgcoords{3}); max(dat.imgcoords{3}) max(dat.imgcoords{3})];
wx3 = [min(dat.imgcoords{1}) max(dat.imgcoords{1}); min(dat.imgcoords{1}) max(dat.imgcoords{1})];
wy3 = [min(dat.imgcoords{2}) min(dat.imgcoords{2}); max(dat.imgcoords{2}) max(dat.imgcoords{2})];
if dat.axistight & ~dat.cornermri
wx1 = [ 1 1; 1 1]*dat.imgcoords{1}(mricoord(1));
wy2 = [ 1 1; 1 1]*dat.imgcoords{2}(mricoord(2));
wz3 = [ 1 1; 1 1]*dat.imgcoords{3}(mricoord(3));
else
wx1 = [ 1 1; 1 1]*dat.imgcoords{1}(1);
wy2 = [ 1 1; 1 1]*dat.imgcoords{2}(end);
wz3 = [ 1 1; 1 1]*dat.imgcoords{3}(1);
end;
% transform MRI coordinates to electrode space
% --------------------------------------------
[ elecwx1 elecwy1 elecwz1 ] = transform( wx1, wy1, wz1, transmat);
[ elecwx2 elecwy2 elecwz2 ] = transform( wx2, wy2, wz2, transmat);
[ elecwx3 elecwy3 elecwz3 ] = transform( wx3, wy3, wz3, transmat);
% ploting surfaces
% ----------------
options = { 'FaceColor','texturemap', 'EdgeColor','none', 'CDataMapping', ...
'direct','tag','img', 'facelighting', 'none' };
hold on;
surface(elecwx1, elecwy1, elecwz1, img1(end:-1:1,:,:), options{:});
surface(elecwx2, elecwy2, elecwz2, img2(end:-1:1,:,:), options{:});
surface(elecwx3, elecwy3, elecwz3, img3(end:-1:1,:,:), options{:});
%xlabel('x'); ylabel('y'); zlabel('z'); axis equal; dsaffd
if strcmpi(dat.drawedges, 'on')
% removing old edges if any
delete(findobj( gcf, 'tag', 'edges'));
if dat.axistight & ~dat.cornermri, col = 'k'; else col = [0.5 0.5 0.5]; end;
h(1) = line([elecwx3(1) elecwx3(2)]', [elecwy3(1) elecwy2(1)]', [elecwz1(1) elecwz1(2)]'); % sagittal-transverse
h(2) = line([elecwx3(1) elecwx2(3)]', [elecwy2(1) elecwy2(2)]', [elecwz1(1) elecwz1(2)]'); % coronal-tranverse
h(3) = line([elecwx3(1) elecwx3(2)]', [elecwy2(1) elecwy2(2)]', [elecwz3(1) elecwz1(1)]'); % sagittal-coronal
set(h, 'color', col, 'linewidth', 2, 'tag', 'edges');
end;
%%fill3([-2 -2 2 2], [-2 2 2 -2], wz(:)-1, BACKCOLOR);
%%fill3([-2 -2 2 2], wy(:)-1, [-2 2 2 -2], BACKCOLOR);
rotate3d on
function index = minpos(vals);
vals(find(vals < 0)) = inf;
[tmp index] = min(vals);
function scalegca(multfactor)
xl = xlim; xf = ( xl(2) - xl(1) ) * multfactor;
yl = ylim; yf = ( yl(2) - yl(1) ) * multfactor;
zl = zlim; zf = ( zl(2) - zl(1) ) * multfactor;
xlim( [ xl(1)-xf xl(2)+xf ]);
ylim( [ yl(1)-yf yl(2)+yf ]);
zlim( [ zl(1)-zf zl(2)+zf ]);
function color = strcol2real(colorin, colmap)
if ~iscell(colorin)
for index = 1:length(colorin)
color{index} = colmap(colorin(index),:);
end;
else
color = colorin;
for index = 1:length(colorin)
if isstr(colorin{index})
switch colorin{index}
case 'r', color{index} = [1 0 0];
case 'g', color{index} = [0 1 0];
case 'b', color{index} = [0 0 1];
case 'c', color{index} = [0 1 1];
case 'm', color{index} = [1 0 1];
case 'y', color{index} = [1 1 0];
case 'k', color{index} = [0 0 0];
case 'w', color{index} = [1 1 1];
otherwise, error('Unknown color');
end;
end;
end;
end;
function x = gammacorrection(x, gammaval);
x = 255 * (double(x)/255).^ gammaval;
% image is supposed to be scaled from 0 to 255
% gammaval = 1 is identity of course
|
github
|
lcnhappe/happe-master
|
fieldtripchan2eeglab.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/fieldtripchan2eeglab.m
| 1,612 |
utf_8
|
0328813bbaaba65a3bcfde10ecb26e8b
|
% fieldtripchan2eeglab() - convert Fieldtrip channel location structure
% to EEGLAB channel location structure
%
% Usage:
% >> chanlocs = fieldtripchan2eeglab( fieldlocs );
%
% Inputs:
% fieldlocs - Fieldtrip channel structure. See help readlocs()
%
% Outputs:
% chanlocs - EEGLAB channel location structure.
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2006-
%
% See also: readlocs()
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function chanlocs = fieldtripchan2eeglab( loc );
if nargin < 1
help fieldtripchan2eeglab;
return;
end;
chanlocs = struct('labels', loc.label(:)', 'X', mattocell(loc.pnt(:,1)'), ...
'Y', mattocell(loc.pnt(:,2)'), ...
'Z', mattocell(loc.pnt(:,3)'));
chanlocs = convertlocs(chanlocs, 'cart2all');
|
github
|
lcnhappe/happe-master
|
sph2spm.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/sph2spm.m
| 3,331 |
utf_8
|
67c8de53ef88fdbaa69eea504e17997b
|
% sph2spm() - compute homogenous transformation matrix from
% BESA spherical coordinates to SPM 3-D coordinate
%
% Usage:
% >> trans = sph2spm;
%
% Outputs:
% trans - homogenous transformation matrix
%
% Note: head radius for spherical model is assumed to be 85 mm.
%
% Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2005
% Arnaud Delorme, SCCN, La Jolla 2005
% SMI, University Aalborg, Denmark http://www.smi.auc.dk/
% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/
% Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function besa2SPM_result = besa2SPM;
if 0
% original transformation: problem occipital part of the haed did not
% fit
% NAS, Left EAR, Right EAR coordinates in BESA
besa_NAS = [0.0000 0.0913 -0.0407];
besa_LPA = [-0.0865 0.0000 -0.0500];
besa_RPA = [0.0865 0.0000 -0.0500];
% NAS, Left EAR, Right EAR coordinates in SPM average
SPM_NAS = [0 84 -48];
SPM_LPA = [-82 -32 -54];
SPM_RPA = [82 -32 -54];
% transformation to CTF coordinate system
% ---------------------------------------
SPM2common = headcoordinates(SPM_NAS , SPM_LPA , SPM_RPA, 0);
besa2common = headcoordinates(besa_NAS, besa_LPA, besa_RPA, 0);
nazcommon1 = besa2common * [ besa_NAS 1]';
nazcommon2 = SPM2common * [ SPM_NAS 1]';
ratiox = nazcommon1(1)/nazcommon2(1);
lpacommon1 = besa2common * [ besa_LPA 1]';
lpacommon2 = SPM2common * [ SPM_LPA 1]';
ratioy = lpacommon1(2)/lpacommon2(2);
scaling = eye(4);
scaling(1,1) = 1/ratiox;
scaling(2,2) = 1/ratioy;
scaling(3,3) = mean([ 1/ratioy 1/ratiox]);
besa2SPM_result = inv(SPM2common) * scaling * besa2common;
end;
if 0
% using electrodenormalize to fit standard BESA electrode (haed radius
% has to be 85) to BEM electrodes
% problem: fit not optimal for temporal electrodes
% traditional takes as input the .m field returned in the output from
% electrodenormalize
besa2SPM_result = traditionaldipfit([0.5588 -14.5541 1.8045 0.0004 0.0000 -1.5623 1.1889 1.0736 132.6198])
end;
% adapted manualy from above for temporal electrodes (see factor 0.94
% instead of 1.1889 and x shift of -18.0041 instead of -14.5541)
%traditionaldipfit([0.5588 -18.0041 1.8045 0.0004 0.0000 -1.5623 1.1889 0.94 132.6198])
besa2SPM_result = [
0.0101 -0.9400 0 0.5588
1.1889 0.0080 0.0530 -18.0041
-0.0005 -0.0000 1.1268 1.8045
0 0 0 1.0000
];
|
github
|
lcnhappe/happe-master
|
homogenous2traditional.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/homogenous2traditional.m
| 5,576 |
utf_8
|
1cd0a7b795501f24b35360ecec62e420
|
function f = homogenous2traditional(H)
% HOMOGENOUS2TRADITIONAL estimates the traditional translation, rotation
% and scaling parameters from a homogenous transformation matrix. It will
% give an error if the homogenous matrix also describes a perspective
% transformation.
%
% Use as
% f = homogenous2traditional(H)
% where H is a 4x4 homogenous transformation matrix and f is a vector with
% nine elements describing
% x-shift
% y-shift
% z-shift
% followed by the
% pitch (rotation around x-axis)
% roll (rotation around y-axis)
% yaw (rotation around z-axis)
% followed by the
% x-rescaling factor
% y-rescaling factor
% z-rescaling factor
%
% The order in which the transformations would be done is exactly opposite
% as the list above, i.e. first z-rescale ... and finally x-shift.
% Copyright (C) 2005, Robert Oostenveld
%
% 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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
% remember the input homogenous transformation matrix
Horg = H;
% The homogenous transformation matrix is built up according to
% H = T * R * S
% where
% R = Rx * Ry * Rz
% estimate the translation
tx = H(1,4);
ty = H(2,4);
tz = H(3,4);
T = [
1 0 0 tx
0 1 0 ty
0 0 1 tz
0 0 0 1
];
% recompute the homogenous matrix excluding the translation
H = inv(T) * H;
% estimate the scaling
sx = norm(H(1:3,1));
sy = norm(H(1:3,2));
sz = norm(H(1:3,3));
S = [
sx 0 0 0
0 sy 0 0
0 0 sz 0
0 0 0 1
];
% recompute the homogenous matrix excluding the scaling
H = H * inv(S);
% the difficult part is to determine the rotations
% the order of the rotations matters
% compute the rotation using a probe point on the z-axis
p = H * [0 0 1 0]';
% the rotation around the y-axis is resulting in an offset in the positive x-direction
ry = asin(p(1));
% the rotation around the x-axis can be estimated by the projection on the yz-plane
if abs(p(2))<eps && abs(p(2))<eps
% the rotation around y was pi/2 or -pi/2, therefore I cannot estimate the rotation around x any more
error('need another estimate, not implemented yet');
elseif abs(p(3))<eps
% this is an unstable situation for using atan, but the rotation around x is either pi/2 or -pi/2
if p(2)<0
rx = pi/2
else
rx = -pi/2;
end
else
% this is the default equation for determining the rotation
rx = -atan(p(2)/p(3));
end
% recompute the individual rotation matrices
Rx = rotate([rx 0 0]);
Ry = rotate([0 ry 0]);
Rz = inv(Ry) * inv(Rx) * H; % use left side multiplication
% compute the remaining rotation using a probe point on the x-axis
p = Rz * [1 0 0 0]';
rz = asin(p(2));
% the complete rotation matrix was
R = rotate([rx ry rz]);
% compare the original translation with the one that was estimated
H = T * R * S;
%fprintf('remaining difference\n');
%disp(Horg - H);
f = [tx ty tz rx ry rz sx sy sz];
function [output] = rotate(R, input);
% ROTATE performs a 3D rotation on the input coordinates
% around the x, y and z-axis. The direction of the rotation
% is according to the right-hand rule. The rotation is first
% done around the x-, then the y- and finally the z-axis.
%
% Use as
% [output] = rotate(R, input)
% where
% R [rx, ry, rz] rotations around each of the axes in degrees
% input Nx3 matrix with the points before rotation
% output Nx3 matrix with the points after rotation
%
% Or as
% [Tr] = rotate(R)
% where
% R [rx, ry, rz] in degrees
% Tr corresponding homogenous transformation matrix
% Copyright (C) 2000-2004, Robert Oostenveld
%
% 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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
rotx = eye(3);
roty = eye(3);
rotz = eye(3);
rx = pi*R(1) / 180;
ry = pi*R(2) / 180;
rz = pi*R(3) / 180;
if rx~=0
% rotation around x-axis
rotx(2,:) = [ 0 cos(rx) -sin(rx) ];
rotx(3,:) = [ 0 sin(rx) cos(rx) ];
end
if ry~=0
% rotation around y-axis
roty(1,:) = [ cos(ry) 0 sin(ry) ];
roty(3,:) = [ -sin(ry) 0 cos(ry) ];
end
if rz~=0
% rotation around z-axis
rotz(1,:) = [ cos(rz) -sin(rz) 0 ];
rotz(2,:) = [ sin(rz) cos(rz) 0 ];
end
if nargin==1
% compute and return the homogenous transformation matrix
rotx(4,4) = 1;
roty(4,4) = 1;
rotz(4,4) = 1;
output = rotz * roty * rotx;
else
% apply the transformation on the input points
output = ((rotz * roty * rotx) * input')';
end
|
github
|
lcnhappe/happe-master
|
electroderealign.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/electroderealign.m
| 26,943 |
utf_8
|
c09b21089e582b6d28a1fc065011b317
|
function [norm] = electroderealign(cfg);
% 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] = electroderealign(cfg)
%
% Three different methods for aligning the input electrodes are implemented:
% based on a warping method, based on the fiducials or interactive with a
% graphical user interface. Each of these approaches is described below.
%
% 1) You can apply a spatial deformation method (i.e. 'warp') that
% automatically minimizes the distance between the electrodes and the
% averaged standard. The warping methods use a non-linear search to
% optimize the error between input and template electrodes or the
% head surface.
%
% 2) 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 electrode
% set as in the template electrode set.
%
% 3) You can display the electrode positions together with the skin surface,
% and manually (using the graphical user interface) adjust the rotation,
% translation and scaling parameters, so that the two match.
%
% The configuration can contain the following options
% cfg.method = different methods for aligning the electrodes
% 'rigidbody' apply a rigid-body warp
% '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
% 'realignfiducial' realign the fiducials
% 'interactive' manually using graphical user interface
% cfg.channel = Nx1 cell-array with selection of channels (default = 'all'),
% see 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 electrode set that will be realigned is specified as
% cfg.elecfile = string with filename, or alternatively
% cfg.elec = structure with electrode definition
%
% 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 want to align the electrodes to the head surface as obtained from
% an anatomical MRI (using one of the warping methods), you should specify
% the head surface
% cfg.headshape = a filename containing headshape, a structure containing a
% single triangulated boundary, or a Nx3 matrix with surface
% points
%
% In case you only want to realign the fiducials, the template electrode
% set only has to contain the three fiducials, e.g.
% cfg.template.pnt(1,:) = [110 0 0] % location of the nose
% cfg.template.pnt(2,:) = [0 90 0] % left ear
% cfg.template.pnt(3,:) = [0 -90 0] % right ear
% cfg.template.label = {''nasion', 'lpa', 'rpa'}
%
% See also READ_FCDC_ELEC, VOLUMEREALIGN
% Copyright (C) 2005-2006, Robert Oostenveld
%
% $Log: electroderealign.m,v $
% Revision 1.1 2009/01/30 04:02:02 arno
% *** empty log message ***
%
% Revision 1.6 2007/08/06 09:20:14 roboos
% added support for bti_hs
%
% Revision 1.5 2007/07/26 08:00:09 roboos
% also deal with cfg.headshape if specified as surface, set of points or ctf_hs file.
% the construction of the tri is now done consistently for all headshapes if tri is missing
%
% Revision 1.4 2007/02/13 15:12:51 roboos
% removed cfg.plot3d option
%
% Revision 1.3 2006/12/12 11:28:33 roboos
% moved projecttri subfunction into seperate function
%
% Revision 1.2 2006/10/04 07:10:07 roboos
% updated documentation
%
% Revision 1.1 2006/09/13 07:20:06 roboos
% renamed electrodenormalize to electroderealign, added "deprecated"-warning to the old function
%
% Revision 1.10 2006/09/13 07:09:24 roboos
% Implemented support for cfg.method=interactive, using GUI for specifying and showing transformations. Sofar only for electrodes+headsurface.
%
% Revision 1.9 2006/09/12 15:26:06 roboos
% implemented support for aligning electrodes to the skin surface, extended and improved documentation
%
% Revision 1.8 2006/04/20 09:58:34 roboos
% updated documentation
%
% Revision 1.7 2006/04/19 15:42:53 roboos
% replaced call to warp_pnt with new function name warp_optim
%
% Revision 1.6 2006/03/14 08:16:00 roboos
% changed function call to warp3d into warp_apply (thanks to Arno)
%
% Revision 1.5 2005/05/17 17:50:37 roboos
% changed all "if" occurences of & and | into && and ||
% this makes the code more compatible with Octave and also seems to be in closer correspondence with Matlab documentation on shortcircuited evaluation of sequential boolean constructs
%
% Revision 1.4 2005/03/21 15:49:43 roboos
% added cfg.casesensitive for string comparison of electrode labels
% added cfg.feedback and cfg.plot3d option for debugging
% changed output: now ALL electrodes of the input are rerurned, after applying the specified transformation
% fixed small bug in feedback regarding distarnce prior/after realignfiducials)
% added support for various warping strategies, a.o. traditional, rigidbody, nonlin1-5, etc.
%
% Revision 1.3 2005/03/16 09:18:56 roboos
% fixed bug in fprintf feedback, instead of giving mean squared distance it should give mean distance before and after normalization
%
% Revision 1.2 2005/01/18 12:04:39 roboos
% improved error handling of missing fiducials
% added other default fiducials
% changed debugging output
%
% Revision 1.1 2005/01/17 14:56:06 roboos
% new implementation
%
% 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
if ~isfield(cfg, 'template'), cfg.template = []; end
% this is a common mistake which can be accepted
if strcmp(cfg.method, 'realignfiducials')
cfg.method = 'realignfiducial';
end
if strcmp(cfg.method, 'warp')
% rename the default warp to one of the method recognized by the warping toolbox
cfg.method = 'traditional';
end
if strcmp(cfg.feedback, 'yes')
% use the global fb field to tell the warping toolbox to print feedback
global fb
fb = 1;
else
global fb
fb = 0;
end
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) = read_fcdc_elec(cfg.template{i});
end
end
elseif 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) && filetype(cfg.headshape, 'ctf_shape')
% read the headshape from file
headshape = read_ctf_shape(cfg.headshape);
elseif ischar(cfg.headshape) && filetype(cfg.headshape, '4d_hs')
% read the headshape from file
headshape = [];
headshape.pnt = read_bti_hs(cfg.headshape);
else
error('cfg.headshape is not specified correctly')
end
if ~isfield(headshape, 'tri')
% generate a closed triangulation from the surface points
headshape.tri = projecttri(headshape.pnt);
end
else
error('you should either specify template electrode positions, template fiducials or a head shape');
end
% get the electrode definition that should be warped
if isfield(cfg, 'elec')
elec = cfg.elec;
else
elec = read_fcdc_elec(cfg.elecfile);
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 usetemplate && any(strcmp(cfg.method, {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'}))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine electrode selection and overlapping subset for warping
cfg.channel = channelselection(cfg.channel, elec.label);
for i=1:Ntemplate
cfg.channel = 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.pnt = elec.pnt(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
all = [];
for i=1:Ntemplate
all = cat(3, all, template(i).pnt);
end
avg = mean(all,3);
stderr = std(all, [], 3);
fprintf('warping electrodes to template... '); % the newline comes later
[norm.pnt, norm.m] = warp_optim(elec.pnt, avg, cfg.method);
norm.label = elec.label;
dpre = mean(sqrt(sum((avg - elec.pnt).^2, 2)));
dpost = mean(sqrt(sum((avg - norm.pnt).^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.pnt, 'r.');
my_plot3(elec.pnt(1,:), 'r*');
my_plot3(elec.pnt(2,:), 'r*');
my_plot3(elec.pnt(3,:), 'r*');
my_text3(elec.pnt(1,:), elec.label{1}, 'color', 'r');
my_text3(elec.pnt(2,:), elec.label{2}, 'color', 'r');
my_text3(elec.pnt(3,:), elec.label{3}, 'color', 'r');
% plot all electrodes after warping
my_plot3(norm.pnt, 'm.');
my_plot3(norm.pnt(1,:), 'm*');
my_plot3(norm.pnt(2,:), 'm*');
my_plot3(norm.pnt(3,:), 'm*');
my_text3(norm.pnt(1,:), norm.label{1}, 'color', 'm');
my_text3(norm.pnt(2,:), norm.label{2}, 'color', 'm');
my_text3(norm.pnt(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.pnt, avg, 'color', 'r');
my_line3(norm.pnt, avg, 'color', 'm');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif useheadshape && any(strcmp(cfg.method, {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'}))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine electrode selection and overlapping subset for warping
cfg.channel = channelselection(cfg.channel, elec.label);
% make subselection of electrodes
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.pnt = elec.pnt(datsel,:);
fprintf('warping electrodes to head shape... '); % the newline comes later
[norm.pnt, norm.m] = warp_optim(elec.pnt, headshape, cfg.method);
norm.label = elec.label;
dpre = warp_error([], elec.pnt, headshape, cfg.method);
dpost = warp_error(norm.m, elec.pnt, headshape, cfg.method);
fprintf('mean distance prior to warping %f, after warping %f\n', dpre, dpost);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif strcmp(cfg.method, 'realignfiducial')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% try to determine the fiducials automatically if not specified
option1 = {'nasion' 'left' 'right'};
option2 = {'nasion' 'lpa' 'rpa'};
option3 = {'nz' 'lpa' 'rpa'};
if ~isfield(cfg, 'fiducial')
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 = channelselection(cfg.channel, elec.label);
[cfgsel, datsel] = match_str(cfg.channel, elec.label);
elec.label = elec.label(datsel);
elec.pnt = elec.pnt(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.pnt(nas_indx,:);
elec_lpa = elec.pnt(lpa_indx,:);
elec_rpa = elec.pnt(rpa_indx,:);
% 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).pnt(nas_indx,:);
templ_lpa(end+1,:) = template(i).pnt(lpa_indx,:);
templ_rpa(end+1,:) = 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.pnt = warp_apply(norm.m, elec.pnt, '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.pnt([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.pnt([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.pnt(1,:), 'r*');
my_plot3(elec.pnt(2,:), 'r*');
my_plot3(elec.pnt(3,:), 'r*');
my_text3(elec.pnt(1,:), elec.label{1}, 'color', 'r');
my_text3(elec.pnt(2,:), elec.label{2}, 'color', 'r');
my_text3(elec.pnt(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.pnt, 'm.');
my_plot3(norm.pnt(1,:), 'm*');
my_plot3(norm.pnt(2,:), 'm*');
my_plot3(norm.pnt(3,:), 'm*');
my_text3(norm.pnt(1,:), norm.label{1}, 'color', 'm');
my_text3(norm.pnt(2,:), norm.label{2}, 'color', 'm');
my_text3(norm.pnt(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, 'surf', 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
else
error('unknown method');
end
% apply the spatial transformation to all electrodes, and replace the
% electrode labels by their case-sensitive original values
if any(strcmp(cfg.method, {'rigidbody', 'globalrescale', 'traditional', 'nonlin1', 'nonlin2', 'nonlin3', 'nonlin4', 'nonlin5'}))
norm.pnt = warp_apply(norm.m, orig.pnt, cfg.method);
else
norm.pnt = warp_apply(norm.m, orig.pnt, 'homogenous');
end
norm.label = orig.label;
% add version information to the configuration
try
% get the full name of the function
cfg.version.name = mfilename('fullpath');
catch
% required for compatibility with Matlab versions prior to release 13 (6.5)
[st, i] = dbstack;
cfg.version.name = st(i);
end
cfg.version.id = '$Id: electroderealign.m,v 1.1 2009/01/30 04:02:02 arno Exp $';
% remember the configuration
norm.cfg = cfg;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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');
surf = getappdata(fig, 'surf');
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.pnt = warp_apply(H, elec.pnt);
axis vis3d; cla
xlabel('x')
ylabel('y')
zlabel('z')
if ~isempty(surf)
triplot(surf.pnt, surf.tri, [], 'faces_skin');
alpha(str2num(get(findobj(fig, 'tag', 'alpha'), 'string')));
end
if ~isempty(template)
triplot(template.pnt, [], [], 'nodes_blue')
end
triplot(elec.pnt, [], [], 'nodes');
if isfield(elec, 'line')
triplot(elec.pnt, elec.line, [], 'edges');
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');
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.pnt = warp_apply(H, elec.pnt);
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
|
lcnhappe/happe-master
|
pop_dipfit_nonlinear.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/pop_dipfit_nonlinear.m
| 19,264 |
utf_8
|
38b5b9d5f0129b1a4aaf3230c2578eac
|
% pop_dipfit_nonlinear() - interactively do dipole fit of selected ICA components
%
% Usage:
% >> EEGOUT = pop_dipfit_nonlinear( EEGIN )
%
% Inputs:
% EEGIN input dataset
%
% Outputs:
% EEGOUT output dataset
%
% Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003
% Arnaud Delorme, SCCN, La Jolla 2003
% Thanks to Nicolas Robitaille for his help on the CTF MEG
% implementation
% SMI, University Aalborg, Denmark http://www.smi.auc.dk/
% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/
% Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [EEGOUT, com] = pop_dipfit_nonlinear( EEG, subfunction, parent, dipnum )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the code for this interactive dialog has 4 major parts
% - draw the graphical user interface
% - synchronize the gui with the data
% - synchronize the data with the gui
% - execute the actual dipole analysis
% the subfunctions that perform handling of the gui are
% - dialog_selectcomponent
% - dialog_checkinput
% - dialog_setvalue
% - dialog_getvalue
% - dialog_plotmap
% - dialog_plotcomponent
% - dialog_flip
% the subfunctions that perform the fitting are
% - dipfit_position
% - dipfit_moment
if ~plugin_askinstall('Fieldtrip-lite', 'ft_sourceanalysis'), return; end;
if nargin<1
help pop_dipfit_nonlinear;
return
elseif nargin==1
EEGOUT = EEG;
com = '';
if ~isfield(EEG, 'chanlocs')
error('No electrodes present');
end
if ~isfield(EEG, 'icawinv')
error('No ICA components to fit');
end
if ~isfield(EEG, 'dipfit')
error('General dipolefit settings not specified');
end
if ~isfield(EEG.dipfit, 'vol') & ~isfield(EEG.dipfit, 'hdmfile')
error('Dipolefit volume conductor model not specified');
end
% select all ICA components as 'fitable'
select = 1:size(EEG.icawinv,2);
if ~isfield(EEG.dipfit, 'current')
% select the first component as the current component
EEG.dipfit.current = 1;
end
% verify the presence of a dipole model
if ~isfield(EEG.dipfit, 'model')
% create empty dipole model for each component
for i=select
EEG.dipfit.model(i).posxyz = zeros(2,3);
EEG.dipfit.model(i).momxyz = zeros(2,3);
EEG.dipfit.model(i).rv = 1;
EEG.dipfit.model(i).select = [1];
end
end
% verify the size of each dipole model
for i=select
if ~isfield(EEG.dipfit.model, 'posxyz') | length(EEG.dipfit.model) < i | isempty(EEG.dipfit.model(i).posxyz)
% replace all empty dipole models with a two dipole model, of which one is active
EEG.dipfit.model(i).select = [1];
EEG.dipfit.model(i).rv = 1;
EEG.dipfit.model(i).posxyz = zeros(2,3);
EEG.dipfit.model(i).momxyz = zeros(2,3);
elseif size(EEG.dipfit.model(i).posxyz,1)==1
% replace all one dipole models with a two dipole model
EEG.dipfit.model(i).select = [1];
EEG.dipfit.model(i).posxyz = [EEG.dipfit.model(i).posxyz; [0 0 0]];
EEG.dipfit.model(i).momxyz = [EEG.dipfit.model(i).momxyz; [0 0 0]];
elseif size(EEG.dipfit.model(i).posxyz,1)>2
% replace all more-than-two dipole models with a two dipole model
warning('pruning dipole model to two dipoles');
EEG.dipfit.model(i).select = [1];
EEG.dipfit.model(i).posxyz = EEG.dipfit.model(i).posxyz(1:2,:);
EEG.dipfit.model(i).momxyz = EEG.dipfit.model(i).momxyz(1:2,:);
end
end
% default is not to use symmetry constraint
constr = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% construct the graphical user interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define the callback functions for the interface elements
cb_plotmap = 'pop_dipfit_nonlinear(EEG, ''dialog_plotmap'', gcbf);';
cb_selectcomponent = 'pop_dipfit_nonlinear(EEG, ''dialog_selectcomponent'', gcbf);';
cb_checkinput = 'pop_dipfit_nonlinear(EEG, ''dialog_checkinput'', gcbf);';
cb_fitposition = 'pop_dipfit_nonlinear(EEG, ''dialog_getvalue'', gcbf); pop_dipfit_nonlinear(EEG, ''dipfit_position'', gcbf); pop_dipfit_nonlinear(EEG, ''dialog_setvalue'', gcbf);';
cb_fitmoment = 'pop_dipfit_nonlinear(EEG, ''dialog_getvalue'', gcbf); pop_dipfit_nonlinear(EEG, ''dipfit_moment'' , gcbf); pop_dipfit_nonlinear(EEG, ''dialog_setvalue'', gcbf);';
cb_close = 'close(gcbf)';
cb_help = 'pophelp(''pop_dipfit_nonlinear'');';
cb_ok = 'uiresume(gcbf);';
cb_plotdip = 'pop_dipfit_nonlinear(EEG, ''dialog_plotcomponent'', gcbf);';
cb_flip1 = 'pop_dipfit_nonlinear(EEG, ''dialog_flip'', gcbf, 1);';
cb_flip2 = 'pop_dipfit_nonlinear(EEG, ''dialog_flip'', gcbf, 2);';
cb_sym = [ 'set(findobj(gcbf, ''tag'', ''dip2sel''), ''value'', 1);' cb_checkinput ];
% vertical layout for each line
geomvert = [1 1 1 1 1 1 1 1 1];
% horizontal layout for each line
geomhoriz = {
[0.8 0.5 0.8 1 1]
[1]
[0.7 0.7 2 2 1]
[0.7 0.5 0.2 2 2 1]
[0.7 0.5 0.2 2 2 1]
[1]
[1 1 1]
[1]
[1 1 1]
};
% define each individual graphical user element
elements = { ...
{ 'style' 'text' 'string' 'Component to fit' } ...
{ 'style' 'edit' 'string' 'dummy' 'tag' 'component' 'callback' cb_selectcomponent } ...
{ 'style' 'pushbutton' 'string' 'Plot map' 'callback' cb_plotmap } ...
{ 'style' 'text' 'string' 'Residual variance = ' } ...
{ 'style' 'text' 'string' 'dummy' 'tag' 'relvar' } ...
{ } ...
{ 'style' 'text' 'string' 'dipole' } ...
{ 'style' 'text' 'string' 'fit' } ...
{ 'style' 'text' 'string' 'position' } ...
{ 'style' 'text' 'string' 'moment' } ...
{ } ...
...
{ 'style' 'text' 'string' '#1' 'tag' 'dip1' } ...
{ 'style' 'checkbox' 'string' '' 'tag' 'dip1sel' 'callback' cb_checkinput } { } ...
{ 'style' 'edit' 'string' '' 'tag' 'dip1pos' 'callback' cb_checkinput } ...
{ 'style' 'edit' 'string' '' 'tag' 'dip1mom' 'callback' cb_checkinput } ...
{ 'style' 'pushbutton' 'string' 'Flip (in|out)' 'callback' cb_flip1 } ...
...
{ 'style' 'text' 'string' '#2' 'tag' 'dip2' } ...
{ 'style' 'checkbox' 'string' '' 'tag' 'dip2sel' 'callback' cb_checkinput } { } ...
{ 'style' 'edit' 'string' '' 'tag' 'dip2pos' 'callback' cb_checkinput } ...
{ 'style' 'edit' 'string' '' 'tag' 'dip2mom' 'callback' cb_checkinput } ...
{ 'style' 'pushbutton' 'string' 'Flip (in|out)' 'callback' cb_flip2 } ...
...
{ } { 'style' 'checkbox' 'string' 'Symmetry constrain for dipole #2' 'tag' 'dip2sym' 'callback' cb_sym 'value' 1 } ...
{ } { } { } ...
{ 'style' 'pushbutton' 'string' 'Fit dipole(s)'' position & moment' 'callback' cb_fitposition } ...
{ 'style' 'pushbutton' 'string' 'OR fit only dipole(s)'' moment' 'callback' cb_fitmoment } ...
{ 'style' 'pushbutton' 'string' 'Plot dipole(s)' 'callback' cb_plotdip } ...
};
% add the cancel, help and ok buttons at the bottom
geomvert = [geomvert 1 1];
geomhoriz = {geomhoriz{:} [1] [1 1 1]};
elements = { elements{:} ...
{ } ...
{ 'Style', 'pushbutton', 'string', 'Cancel', 'callback', cb_close } ...
{ 'Style', 'pushbutton', 'string', 'Help', 'callback', cb_help } ...
{ 'Style', 'pushbutton', 'string', 'OK', 'callback', cb_ok } ...
};
% activate the graphical interface
supergui(0, geomhoriz, geomvert, elements{:});
dlg = gcf;
set(gcf, 'name', 'Manual dipole fit -- pop_dipfit_nonlinear()');
set(gcf, 'userdata', EEG);
pop_dipfit_nonlinear(EEG, 'dialog_setvalue', dlg);
uiwait(dlg);
if ishandle(dlg)
pop_dipfit_nonlinear(EEG, 'dialog_getvalue', dlg);
% FIXME, rv is undefined since the user may have changed dipole parameters
% FIXME, see also dialog_getvalue subfucntion
EEGOUT = get(dlg, 'userdata');
close(dlg);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% implement all subfunctions through a switch-yard
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif nargin>=3
%disp(subfunction)
EEG = get(parent, 'userdata');
switch subfunction
case 'dialog_selectcomponent'
current = get(findobj(parent, 'tag', 'component'), 'string');
current = str2num(current);
current = current(1);
current = min(current, size(EEG.icaweights,1));
current = max(current, 1);
set(findobj(parent, 'tag', 'component'), 'string', int2str(current));
EEG.dipfit.current = current;
% reassign the global EEG object back to the dialogs userdata
set(parent, 'userdata', EEG);
% redraw the dialog with the current model
pop_dipfit_nonlinear(EEG, 'dialog_setvalue', parent);
case 'dialog_plotmap'
current = str2num(get(findobj(parent, 'tag', 'component'), 'string'));
figure; pop_topoplot(EEG, 0, current, [ 'IC ' num2str(current) ], [1 1], 1);
title([ 'IC ' int2str(current) ]);
case 'dialog_plotcomponent'
current = get(findobj(parent, 'tag', 'component'), 'string');
EEG.dipfit.current = str2num(current);
if ~isempty( EEG.dipfit.current )
pop_dipplot(EEG, 'DIPFIT', EEG.dipfit.current, 'normlen', 'on', 'projlines', 'on', 'mri', EEG.dipfit.mrifile);
end;
case 'dialog_checkinput'
if get(findobj(parent, 'tag', 'dip1sel'), 'value') & ~get(findobj(parent, 'tag', 'dip1act'), 'value')
set(findobj(parent, 'tag', 'dip1act'), 'value', 1);
end
if get(findobj(parent, 'tag', 'dip2sel'), 'value') & ~get(findobj(parent, 'tag', 'dip2act'), 'value')
set(findobj(parent, 'tag', 'dip2act'), 'value', 1);
end
if ~all(size(str2num(get(findobj(parent, 'tag', 'dip1pos'), 'string')))==[1 3])
set(findobj(parent, 'tag', 'dip1pos'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).posxyz(1,:)));
else
EEG.dipfit.model(EEG.dipfit.current).posxyz(1,:) = str2num(get(findobj(parent, 'tag', 'dip1pos'), 'string'));
end
if ~all(size(str2num(get(findobj(parent, 'tag', 'dip2pos'), 'string')))==[1 3])
set(findobj(parent, 'tag', 'dip2pos'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).posxyz(2,:)));
else
EEG.dipfit.model(EEG.dipfit.current).posxyz(2,:) = str2num(get(findobj(parent, 'tag', 'dip2pos'), 'string'));
end
if ~all(size(str2num(get(findobj(parent, 'tag', 'dip1mom'), 'string')))==[1 3])
set(findobj(parent, 'tag', 'dip1mom'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).momxyz(1,:)));
else
EEG.dipfit.model(EEG.dipfit.current).momxyz(1,:) = str2num(get(findobj(parent, 'tag', 'dip1mom'), 'string'));
end
if ~all(size(str2num(get(findobj(parent, 'tag', 'dip2mom'), 'string')))==[1 3])
set(findobj(parent, 'tag', 'dip2mom'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).momxyz(2,:)));
else
EEG.dipfit.model(EEG.dipfit.current).momxyz(2,:) = str2num(get(findobj(parent, 'tag', 'dip2mom'), 'string'));
end
if get(findobj(parent, 'tag', 'dip2sel'), 'value') & get(findobj(parent, 'tag', 'dip2sym'), 'value') & ~get(findobj(parent, 'tag', 'dip1sel'), 'value')
set(findobj(parent, 'tag', 'dip2sel'), 'value', 0);
end
set(parent, 'userdata', EEG);
case 'dialog_setvalue'
% synchronize the gui with the data
set(findobj(parent, 'tag', 'component'), 'string', EEG.dipfit.current);
set(findobj(parent, 'tag', 'relvar' ), 'string', sprintf('%0.2f%%', EEG.dipfit.model(EEG.dipfit.current).rv * 100));
set(findobj(parent, 'tag', 'dip1sel'), 'value', ismember(1, EEG.dipfit.model(EEG.dipfit.current).select));
set(findobj(parent, 'tag', 'dip2sel'), 'value', ismember(2, EEG.dipfit.model(EEG.dipfit.current).select));
set(findobj(parent, 'tag', 'dip1pos'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).posxyz(1,:)));
if strcmpi(EEG.dipfit.coordformat, 'CTF')
set(findobj(parent, 'tag', 'dip1mom'), 'string', sprintf('%f %f %f', EEG.dipfit.model(EEG.dipfit.current).momxyz(1,:)));
else set(findobj(parent, 'tag', 'dip1mom'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).momxyz(1,:)));
end;
Ndipoles = size(EEG.dipfit.model(EEG.dipfit.current).posxyz, 1);
if Ndipoles>=2
set(findobj(parent, 'tag', 'dip2pos'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).posxyz(2,:)));
if strcmpi(EEG.dipfit.coordformat, 'CTF')
set(findobj(parent, 'tag', 'dip2mom'), 'string', sprintf('%f %f %f', EEG.dipfit.model(EEG.dipfit.current).momxyz(2,:)));
else set(findobj(parent, 'tag', 'dip2mom'), 'string', sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(EEG.dipfit.current).momxyz(2,:)));
end;
end
case 'dialog_getvalue'
% synchronize the data with the gui
if get(findobj(parent, 'tag', 'dip1sel'), 'value'); select = [1]; else select = []; end;
if get(findobj(parent, 'tag', 'dip2sel'), 'value'); select = [select 2]; end;
posxyz(1,:) = str2num(get(findobj(parent, 'tag', 'dip1pos'), 'string'));
posxyz(2,:) = str2num(get(findobj(parent, 'tag', 'dip2pos'), 'string'));
momxyz(1,:) = str2num(get(findobj(parent, 'tag', 'dip1mom'), 'string'));
momxyz(2,:) = str2num(get(findobj(parent, 'tag', 'dip2mom'), 'string'));
% assign the local values to the global EEG object
EEG.dipfit.model(EEG.dipfit.current).posxyz = posxyz;
EEG.dipfit.model(EEG.dipfit.current).momxyz = momxyz;
EEG.dipfit.model(EEG.dipfit.current).select = select;
% FIXME, rv is undefined after a manual change of parameters
% FIXME, this should either be undated continuously or upon OK buttonpress
% EEG.dipfit.model(EEG.dipfit.current).rv = nan;
% reassign the global EEG object back to the dialogs userdata
set(parent, 'userdata', EEG);
case 'dialog_flip'
% flip the orientation of the dipole
current = EEG.dipfit.current;
moment = EEG.dipfit.model(current).momxyz;
EEG.dipfit.model(current).momxyz(dipnum,:) = [ -moment(dipnum,1) -moment(dipnum,2) -moment(dipnum,3)];
set(findobj(parent, 'tag', ['dip' int2str(dipnum) 'mom']), 'string', ...
sprintf('%0.3f %0.3f %0.3f', EEG.dipfit.model(current).momxyz(dipnum,:)));
set(parent, 'userdata', EEG);
case {'dipfit_moment', 'dipfit_position'}
% determine the selected dipoles and components
current = EEG.dipfit.current;
select = find([get(findobj(parent, 'tag', 'dip1sel'), 'value') get(findobj(parent, 'tag', 'dip2sel'), 'value')]);
if isempty(select)
warning('no dipoles selected for fitting');
return
end
% remove the dipoles from the model that are not selected, but keep
% the original dipole model (to keep the GUI consistent)
model_before_fitting = EEG.dipfit.model(current);
EEG.dipfit.model(current).posxyz = EEG.dipfit.model(current).posxyz(select,:);
EEG.dipfit.model(current).momxyz = EEG.dipfit.model(current).momxyz(select,:);
if strcmp(subfunction, 'dipfit_moment')
% the default is 'yes' which should only be overruled for fitting dipole moment
cfg.nonlinear = 'no';
end
dipfitdefs;
if get(findobj(parent, 'tag', 'dip2sym'), 'value') & get(findobj(parent, 'tag', 'dip2sel'), 'value')
if strcmpi(EEG.dipfit.coordformat,'MNI')
cfg.symmetry = 'x';
else
cfg.symmetry = 'y';
end;
else
cfg.symmetry = [];
end
cfg.component = current;
% convert structure into list of input arguments
arg = [fieldnames(cfg)' ; struct2cell(cfg)'];
arg = arg(:)';
% make a dialog to interrupt the fitting procedure
fig = figure('visible', 'off');
supergui( fig, {1 1}, [], ...
{'style' 'text' 'string' 'Press button below to stop fitting' }, ...
{'style' 'pushbutton' 'string' 'Interupt' 'callback' 'figure(gcbf); set(gcbf, ''tag'', ''stop'');' } );
drawnow;
% start the dipole fitting
try
warning backtrace off;
EEG = dipfit_nonlinear(EEG, arg{:});
warning backtrace on;
catch,
disp('Dipole localization failed');
end;
% should the following string be put into com? ->NOT SUPPORTED
% --------------------------------------------------------
com = sprintf('%s = dipfit_nonlinear(%s,%s)\n', inputname(1), inputname(1), vararg2str(arg));
% this GUI always requires two sources in the dipole model
% first put the original model back in and then replace the dipole parameters that have been fitted
model_after_fitting = EEG.dipfit.model(current);
newfields = fieldnames( EEG.dipfit.model );
for index = 1:length(newfields)
eval( ['EEG.dipfit.model(' int2str(current) ').' newfields{index} ' = model_after_fitting.' newfields{index} ';' ]);
end;
EEG.dipfit.model(current).posxyz(select,:) = model_after_fitting.posxyz;
EEG.dipfit.model(current).momxyz(select,:) = model_after_fitting.momxyz;
EEG.dipfit.model(current).rv = model_after_fitting.rv;
%EEG.dipfit.model(current).diffmap = model_after_fitting.diffmap;
% reassign the global EEG object back to the dialogs userdata
set(parent, 'userdata', EEG);
% close the interrupt dialog
if ishandle(fig)
close(fig);
end
otherwise
error('unknown subfunction for pop_dipfit_nonlinear');
end % switch subfunction
end % if nargin
|
github
|
lcnhappe/happe-master
|
dipfit_1_to_2.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/dipfit_1_to_2.m
| 2,252 |
utf_8
|
1a1a49c9adb0d94ff59b4a2206a3f2f4
|
% dipfit_1_to_2() - convert dipfit 1 structure to dipfit 2 structure.
%
% Usage:
% >> EEG.dipfit = dipfit_1_to_2(EEG.dipfit);
%
% Note:
% For non-standard BESA models (where the radii or the conductances
% have been modified, users must create a new model in Dipfit2 from
% the default BESA model.
%
% Author: Arnaud Delorme, SCCN, La Jolla 2005
% Copyright (C) Arnaud Delorme, SCCN, La Jolla 2005
%
% 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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function newdipfit = dipfit_1_to_2( dipfit );
if isfield( dipfit, 'model')
newdipfit.model = dipfit.model;
end;
if isfield( dipfit, 'chansel')
newdipfit.chansel = dipfit.chansel;
end;
ind = 1; % use first template (BESA)
newdipfit.coordformat = template_models(ind).coordformat;
newdipfit.mrifile = template_models(ind).mrifile;
newdipfit.chanfile = template_models(ind).chanfile;
if ~isfield(dipfit, 'vol')
newdipfit.hdmfile = template_models(ind).hdmfile;
else
newdipfit.vol = dipfit.vol;
%if length(dipfit.vol) == 4
%if ~all(dipfit.vol == [85-6-7-1 85-6-7 85-6 85]) | ...
% ~all(dipfit.c == [0.33 1.00 0.0042 0.33]) | ...
% ~all(dipfit.o = [0 0 0])
% disp('Warning: Conversion from dipfit 1 to dipfit 2 can only deal');
% disp(' with standard (not modified) BESA model');
% disp(' See "help dipfit_1_to_2" to convert this model');
% newdipfit = [];
%end;
%end;
end;
|
github
|
lcnhappe/happe-master
|
dipfit_gridsearch.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/dipfit_gridsearch.m
| 4,519 |
utf_8
|
cc77806c9d0a7de350e540a72dc1c033
|
% dipfit_gridsearch() - do initial batch-like dipole scan and fit to all
% data components and return a dipole model with a
% single dipole for each component.
%
% Usage:
% >> EEGOUT = dipfit_gridsearch( EEGIN, varargin)
%
% Inputs:
% ...
%
% Optional inputs:
% 'component' - vector with integers, ICA components to scan
% 'xgrid' - vector with floats, grid positions along x-axis
% 'ygrid' - vector with floats, grid positions along y-axis
% 'zgrid' - vector with floats, grid positions along z-axis
%
% Output:
% ...
%
% Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003, load/save by
% Arnaud Delorme
% Thanks to Nicolas Robitaille for his help on the CTF MEG
% implementation
% SMI, University Aalborg, Denmark http://www.smi.auc.dk/
% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl
% Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [EEGOUT] = dipfit_gridsearch(EEG, varargin)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert the optional arguments into a configuration structure that can be
% understood by FIELDTRIPs dipolefitting function
if nargin>2
cfg = struct(varargin{:});
else
help dipfit_gridsearch
return
end
% specify the FieldTrip DIPOLEFITTING configuration
cfg.model = 'moving';
cfg.gridsearch = 'yes';
cfg.nonlinear = 'no';
% add some additional settings from EEGLAB to the configuration
tmpchanlocs = EEG.chanlocs;
cfg.channel = { tmpchanlocs(EEG.dipfit.chansel).labels };
if isfield(EEG.dipfit, 'vol')
cfg.vol = EEG.dipfit.vol;
elseif isfield(EEG.dipfit, 'hdmfile')
cfg.hdmfile = EEG.dipfit.hdmfile;
else
error('no head model in EEG.dipfit')
end
if isfield(EEG.dipfit, 'elecfile') & ~isempty(EEG.dipfit.elecfile)
cfg.elecfile = EEG.dipfit.elecfile;
end
if isfield(EEG.dipfit, 'gradfile') & ~isempty(EEG.dipfit.gradfile)
cfg.gradfile = EEG.dipfit.gradfile;
end
% convert the EEGLAB data structure into a structure that looks as if it
% was computed using FIELDTRIPs componentanalysis function
comp = eeglab2fieldtrip(EEG, 'componentanalysis', 'dipfit');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Added code to handle CTF data with multipleSphere head model %
% This code is copy-pasted in dipfit_gridSearch, dipfit_nonlinear %
% The flag .isMultiSphere is used by dipplot %
% Nicolas Robitaille, January 2007. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Do some trick to force fieldtrip to use the multiple sphere model
if strcmpi(EEG.dipfit.coordformat, 'CTF')
cfg = rmfield(cfg, 'channel');
comp = rmfield(comp, 'elec');
cfg.gradfile = EEG.dipfit.chanfile;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% END %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(cfg, 'component')
% default is to scan all components
cfg.component = 1:size(comp.topo,2);
end
% for each component scan the whole brain with dipoles using FIELDTRIPs
% dipolefitting function
source = ft_dipolefitting(cfg, comp);
% reformat the output dipole sources into EEGLABs data structure
for i=1:length(cfg.component)
EEG.dipfit.model(cfg.component(i)).posxyz = source.dip(i).pos;
EEG.dipfit.model(cfg.component(i)).momxyz = reshape(source.dip(i).mom, 3, length(source.dip(i).mom)/3)';
EEG.dipfit.model(cfg.component(i)).rv = source.dip(i).rv;
end
EEGOUT = EEG;
|
github
|
lcnhappe/happe-master
|
eegplugin_dipfit.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/eegplugin_dipfit.m
| 4,444 |
utf_8
|
2bcef6898d8184014480e6ed4f2e170b
|
% eegplugin_dipfit() - DIPFIT plugin version 2.0 for EEGLAB menu.
% DIPFIT is the dipole fitting Matlab Toolbox of
% Robert Oostenveld (in collaboration with A. Delorme).
%
% Usage:
% >> eegplugin_dipfit(fig, trystrs, catchstrs);
%
% Inputs:
% fig - [integer] eeglab figure.
% trystrs - [struct] "try" strings for menu callbacks.
% catchstrs - [struct] "catch" strings for menu callbacks.
%
% Notes:
% To create a new plugin, simply create a file beginning with "eegplugin_"
% and place it in your eeglab folder. It will then be automatically
% detected by eeglab. See also this source code internal comments.
% For eeglab to return errors and add the function's results to
% the eeglab history, menu callback must be nested into "try" and
% a "catch" strings. For more information on how to create eeglab
% plugins, see http://www.sccn.ucsd.edu/eeglab/contrib.html
%
% Author: Arnaud Delorme, CNL / Salk Institute, 22 February 2003
%
% See also: eeglab()
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1.07 USA
function vers = eegplugin_dipfit(fig, trystrs, catchstrs)
vers = 'dipfit2.2';
if nargin < 3
error('eegplugin_dipfit requires 3 arguments');
end;
% find tools menu
% ---------------
menu = findobj(fig, 'tag', 'tools');
% tag can be
% 'import data' -> File > import data menu
% 'import epoch' -> File > import epoch menu
% 'import event' -> File > import event menu
% 'export' -> File > export
% 'tools' -> tools menu
% 'plot' -> plot menu
% command to check that the '.source' is present in the EEG structure
% -------------------------------------------------------------------
check_dipfit = [trystrs.no_check 'if ~isfield(EEG, ''dipfit''), error(''Run the dipole setting first''); end;' ...
'if isempty(EEG.dipfit), error(''Run the dipole setting first''); end;' ];
check_dipfitnocheck = [ trystrs.no_check 'if ~isfield(EEG, ''dipfit''), error(''Run the dipole setting first''); end; ' ];
check_chans = [ '[EEG tmpres] = eeg_checkset(EEG, ''chanlocs_homogeneous'');' ...
'if ~isempty(tmpres), eegh(tmpres), end; clear tmpres;' ];
% menu callback commands
% ----------------------
comsetting = [ trystrs.check_ica check_chans '[EEG LASTCOM]=pop_dipfit_settings(EEG);' catchstrs.store_and_hist ];
combatch = [ check_dipfit check_chans '[EEG LASTCOM] = pop_dipfit_gridsearch(EEG);' catchstrs.store_and_hist ];
comfit = [ check_dipfitnocheck check_chans [ 'EEG = pop_dipfit_nonlinear(EEG); ' ...
'LASTCOM = ''% === History not supported for manual dipole fitting ==='';' ] catchstrs.store_and_hist ];
comauto = [ check_dipfit check_chans '[EEG LASTCOM] = pop_multifit(EEG);' catchstrs.store_and_hist ];
% preserve the '=" sign in the comment above: it is used by EEGLAB to detect appropriate LASTCOM
complot = [ check_dipfit check_chans 'LASTCOM = pop_dipplot(EEG);' catchstrs.add_to_hist ];
% create menus
% ------------
submenu = uimenu( menu, 'Label', 'Locate dipoles using DIPFIT 2.x', 'separator', 'on');
uimenu( submenu, 'Label', 'Head model and settings' , 'CallBack', comsetting);
uimenu( submenu, 'Label', 'Coarse fit (grid scan)' , 'CallBack', combatch);
uimenu( submenu, 'Label', 'Fine fit (iterative)' , 'CallBack', comfit);
uimenu( submenu, 'Label', 'Autofit (coarse fit, fine fit & plot)', 'CallBack', comauto);
uimenu( submenu, 'Label', 'Plot component dipoles' , 'CallBack', complot, 'separator', 'on');
|
github
|
lcnhappe/happe-master
|
pop_multifit.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/pop_multifit.m
| 10,370 |
utf_8
|
dd98129d0df98fcdfc6532ff87983696
|
% pop_multifit() - fit multiple component dipoles using DIPFIT
%
% Usage:
% >> EEG = pop_multifit(EEG); % pop-up graphical interface
% >> EEG = pop_multifit(EEG, comps, 'key', 'val', ...);
%
% Inputs:
% EEG - input EEGLAB dataset.
% comps - indices component to fit. Empty is all components.
%
% Optional inputs:
% 'dipoles' - [1|2] use either 1 dipole or 2 dipoles contrain in
% symmetry. Default is 1.
% 'dipplot' - ['on'|'off'] plot dipoles. Default is 'off'.
% 'plotopt' - [cell array] dipplot() 'key', 'val' options. Default is
% 'normlen', 'on', 'image', 'fullmri'
% 'rmout' - ['on'|'off'] remove dipoles outside the head. Artifactual
% component often localize outside the head. Default is 'off'.
% 'threshold' - [float] rejection threshold during component scan.
% Default is 40 (residual variance above 40%).
%
% Outputs:
% EEG - output dataset with updated "EEG.dipfit" field
%
% Note: residual variance is set to NaN if DIPFIT does not converge
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, Oct. 2003
% Copyright (C) 9/2003 Arnaud Delorme, SCCN/INC/UCSD, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com] = pop_multifit(EEG, comps, varargin);
if nargin < 1
help pop_multifit;
return;
end;
com = [];
ncomps = size(EEG.icaweights,1);
if ncomps == 0, error('you must run ICA first'); end;
if nargin<2
cb_chans = 'tmplocs = EEG.chanlocs; set(findobj(gcbf, ''tag'', ''chans''), ''string'', int2str(pop_chansel({tmplocs.labels}))); clear tmplocs;';
uilist = { { 'style' 'text' 'string' 'Component indices' } ...
{ 'style' 'edit' 'string' [ '1:' int2str(ncomps) ] } ...
{ 'style' 'text' 'string' 'Rejection threshold RV (%)' } ...
{ 'style' 'edit' 'string' '100' } ...
{ 'style' 'text' 'string' 'Remove dipoles outside the head' } ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } {} ...
{ 'style' 'text' 'string' 'Fit bilateral dipoles (check)' } ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } {} ...
{ 'style' 'text' 'string' 'Plot resulting dipoles (check)' } ...
{ 'style' 'checkbox' 'string' '' 'value' 0 } {} ...
{ 'style' 'text' 'string' 'dipplot() plotting options' } ...
{ 'style' 'edit' 'string' '''normlen'' ''on''' } ...
{ 'style' 'pushbutton' 'string' 'Help' 'callback' 'pophelp(''dipplot'')' } };
results = inputgui( { [1.91 2.8] [1.91 2.8] [3.1 0.8 1.6] [3.1 0.8 1.6] [3.1 0.8 1.6] [2.12 2.2 0.8]}, ...
uilist, 'pophelp(''pop_multifit'')', ...
'Fit multiple ICA components -- pop_multifit()');
if length(results) == 0 return; end;
comps = eval( [ '[' results{1} ']' ] );
% selecting model
% ---------------
options = {};
if ~isempty(results{2})
options = { options{:} 'threshold' eval( results{2} ) };
end;
if results{3}, options = { options{:} 'rmout' 'on' }; end;
if results{4}, options = { options{:} 'dipoles' 2 }; end;
if results{5}, options = { options{:} 'dipplot' 'on' }; end;
options = { options{:} 'plotopt' eval( [ '{ ' results{6} ' }' ]) };
else
options = varargin;
end;
% checking parameters
% -------------------
if isempty(comps), comps = [1:size(EEG.icaweights,1)]; end;
g = finputcheck(options, { 'settings' { 'cell' 'struct' } [] {}; % deprecated
'dipoles' 'integer' [1 2] 1;
'threshold' 'float' [0 100] 40;
'dipplot' 'string' { 'on' 'off' } 'off';
'rmout' 'string' { 'on' 'off' } 'off';
'plotopt' 'cell' {} {'normlen' 'on' }});
if isstr(g), error(g); end;
EEG = eeg_checkset(EEG, 'chanlocs_homogeneous');
% dipfit settings
% ---------------
if isstruct(g.settings)
EEG.dipfit = g.settings;
elseif ~isempty(g.settings)
EEG = pop_dipfit_settings( EEG, g.settings{:}); % will probably not work but who knows
end;
% Scanning dipole locations
% -------------------------
dipfitdefs;
skipscan = 0;
try
alls = cellfun('size', { EEG.dipfit.model.posxyz }, 2);
if length(alls) == ncomps
if all(alls == 3)
skipscan = 1;
end;
end;
catch, end;
if skipscan
disp('Skipping scanning since all dipoles have non-null starting positions.');
else
disp('Scanning dipolar grid to find acceptable starting positions...');
xg = linspace(-floor(meanradius), floor(meanradius),11);
yg = linspace(-floor(meanradius), floor(meanradius),11);
zg = linspace(0 , floor(meanradius), 6);
EEG = pop_dipfit_gridsearch( EEG, [1:ncomps], ...
eval(xgridstr), eval(ygridstr), eval(zgridstr), 100);
disp('Scanning terminated. Refining dipole locations...');
end;
% set symmetry constraint
% ----------------------
if strcmpi(EEG.dipfit.coordformat,'MNI')
defaultconstraint = 'x';
else
defaultconstraint = 'y';
end;
% Searching dipole localization
% -----------------------------
disp('Searching dipoles locations...');
chansel = EEG.dipfit.chansel;
%elc = getelecpos(EEG.chanlocs, EEG.dipfit);
plotcomps = [];
for i = comps(:)'
if i <= length(EEG.dipfit.model) & ~isempty(EEG.dipfit.model(i).posxyz)
if g.dipoles == 2,
% try to find a good origin for automatic dipole localization
EEG.dipfit.model(i).active = [1 2];
EEG.dipfit.model(i).select = [1 2];
if isempty(EEG.dipfit.model(i).posxyz)
EEG.dipfit.model(i).posxyz = zeros(1,3);
EEG.dipfit.model(i).momxyz = zeros(2,3);
else
EEG.dipfit.model(i).posxyz(2,:) = EEG.dipfit.model(i).posxyz;
if strcmpi(EEG.dipfit.coordformat, 'MNI')
EEG.dipfit.model(i).posxyz(:,1) = [-40;40];
else EEG.dipfit.model(i).posxyz(:,2) = [-40;40];
end;
EEG.dipfit.model(i).momxyz(2,:) = EEG.dipfit.model(i).momxyz;
end;
else
EEG.dipfit.model(i).active = [1];
EEG.dipfit.model(i).select = [1];
end;
warning backtrace off;
try,
if g.dipoles == 2,
EEG = dipfit_nonlinear(EEG, 'component', i, 'symmetry', defaultconstraint);
else
EEG = dipfit_nonlinear(EEG, 'component', i, 'symmetry', []);
end;
catch, EEG.dipfit.model(i).rv = NaN; disp('Maximum number of iterations reached. Fitting failed');
end;
warning backtrace on;
plotcomps = [ plotcomps i ];
end;
end;
% set RV to 1 for dipole with higher than 40% residual variance
% -------------------------------------------------------------
EEG.dipfit.model = dipfit_reject(EEG.dipfit.model, g.threshold/100);
% removing dipoles outside the head
% ---------------------------------
if strcmpi(g.rmout, 'on') & strcmpi(EEG.dipfit.coordformat, 'spherical')
rmdip = [];
for index = plotcomps
if ~isempty(EEG.dipfit.model(index).posxyz)
if any(sqrt(sum(EEG.dipfit.model(index).posxyz.^2,2)) > 85)
rmdip = [ rmdip index];
EEG.dipfit.model(index).posxyz = [];
EEG.dipfit.model(index).momxyz = [];
EEG.dipfit.model(index).rv = 1;
end;
end;
end;
plotcomps = setdiff(plotcomps, rmdip);
if length(rmdip) > 0
fprintf('%d out of cortex dipoles removed (usually artifacts)\n', length(rmdip));
end;
end;
% plotting dipoles
% ----------------
if strcmpi(g.dipplot, 'on')
pop_dipplot(EEG, 'DIPFIT', plotcomps, g.plotopt{:});
end;
com = sprintf('%s = pop_multifit(%s, %s);', inputname(1), inputname(1), vararg2str({ comps options{:}}));
return;
% get electrode positions from eeglag
% -----------------------------------
function elc = getelecpos(chanlocs, dipfitstruct);
try,
elc = [ [chanlocs.X]' [chanlocs.Y]' [chanlocs.Z]' ];
catch
disp('No 3-D carthesian coordinates; re-computing them from 2-D polar coordinates');
EEG.chanlocs = convertlocs(EEG.chanlocs, 'topo2all');
elc = [ [chanlocs.X]' [chanlocs.Y]' [chanlocs.Z]' ];
end;
% constrain electrode to sphere
% -----------------------------
disp('Constraining electrodes to sphere');
elc = elc - repmat( dipfitstruct.vol.o, [size(elc,1) 1]); % recenter
% (note the step above is not needed since the origin should always be 0)
elc = elc ./ repmat( sqrt(sum(elc.*elc,2)), [1 3]); % normalize
elc = elc * max(dipfitstruct.vol.r); % head size
%for index= 1:size(elc,1)
% elc(index,:) = max(dipfitstruct.vol.r) * elc(index,:) /norm(elc(index,:));
%end;
|
github
|
lcnhappe/happe-master
|
pop_dipfit_gridsearch.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/pop_dipfit_gridsearch.m
| 4,833 |
utf_8
|
39566131e1f04827a5eaf4dd7994f07f
|
% pop_dipfit_gridsearch() - scan all ICA components with a single dipole
% on a regular grid spanning the whole brain. Any dipoles that explains
% a component with a too large relative residual variance is removed.
%
% Usage:
% >> EEGOUT = pop_dipfit_gridsearch( EEGIN ); % pop up interactive window
% >> EEGOUT = pop_dipfit_gridsearch( EEGIN, comps );
% >> EEGOUT = pop_dipfit_gridsearch( EEGIN, comps, xgrid, ygrid, zgrid, thresh )
%
% Inputs:
% EEGIN - input dataset
% comps - [integer array] component indices
% xgrid - [float array] x-grid. Default is 10 elements between
% -1 and 1.
% ygrid - [float array] y-grid. Default is 10 elements between
% -1 and 1.
% zgrid - [float array] z-grid. Default is 10 elements between
% -1 and 1.
% thresh - [float] threshold in percent. Default 40.
%
% Outputs:
% EEGOUT output dataset
%
% Authors: Robert Oostenveld, SMI/FCDC, Nijmegen 2003
% Arnaud Delorme, SCCN, La Jolla 2003
% Thanks to Nicolas Robitaille for his help on the CTF MEG
% implementation
% SMI, University Aalborg, Denmark http://www.smi.auc.dk/
% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/
% Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [EEGOUT, com] = pop_dipfit_gridsearch(EEG, select, xgrid, ygrid, zgrid, reject );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin < 1
help pop_dipfit_gridsearch;
return;
end;
if ~plugin_askinstall('Fieldtrip-lite', 'ft_sourceanalysis'), return; end;
EEGOUT = EEG;
com = '';
if ~isfield(EEG, 'chanlocs')
error('No electrodes present');
end
if ~isfield(EEG, 'icawinv')
error('No ICA components to fit');
end
if ~isfield(EEG, 'dipfit')
error('General dipolefit settings not specified');
end
if ~isfield(EEG.dipfit, 'vol') & ~isfield(EEG.dipfit, 'hdmfile')
error('Dipolefit volume conductor model not specified');
end
dipfitdefs
if strcmpi(EEG.dipfit.coordformat, 'CTF')
maxrad = 8.5;
xgridstr = sprintf('linspace(-%2.1f,%2.1f,11)', maxrad, maxrad);
ygridstr = sprintf('linspace(-%2.1f,%2.1f,11)', maxrad, maxrad);
zgridstr = sprintf('linspace(0,%2.1f,6)', maxrad);
end;
if nargin < 2
% get the default values and filenames
promptstr = { 'Component(s) (not faster if few comp.)', ...
'Grid in X-direction', ...
'Grid in Y-direction', ...
'Grid in Z-direction', ...
'Rejection threshold RV(%)' };
inistr = {
[ '1:' int2str(size(EEG.icawinv,2)) ], ...
xgridstr, ...
ygridstr, ...
zgridstr, ...
rejectstr };
result = inputdlg2( promptstr, 'Batch dipole fit -- pop_dipfit_gridsearch()', 1, inistr, 'pop_dipfit_gridsearch');
if length(result)==0
% user pressed cancel
return
end
select = eval( [ '[' result{1} ']' ]);
xgrid = eval( result{2} );
ygrid = eval( result{3} );
zgrid = eval( result{4} );
reject = eval( result{5} ) / 100; % string is in percent
options = { };
else
if nargin < 2
select = [1:size(EEG.icawinv,2)];
end;
if nargin < 3
xgrid = eval( xgridstr );
end;
if nargin < 4
ygrid = eval( ygridstr );
end;
if nargin < 5
zgrid = eval( zgridstr );
end;
if nargin < 6
reject = eval( rejectstr );
end;
options = { 'waitbar' 'none' };
end;
% perform batch fit with single dipole for all selected channels and components
% warning off;
warning backtrace off;
EEGOUT = dipfit_gridsearch(EEG, 'component', select, 'xgrid', xgrid, 'ygrid', ygrid, 'zgrid', zgrid, options{:});
warning backtrace on;
EEGOUT.dipfit.model = dipfit_reject(EEGOUT.dipfit.model, reject);
% FIXME reject is not being used at the moment
disp('Done');
com = sprintf('%s = pop_dipfit_gridsearch(%s, %s);', ...
inputname(1), inputname(1), vararg2str( { select xgrid, ygrid, zgrid reject }));
|
github
|
lcnhappe/happe-master
|
dipfit_erpeeg.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/dipfit_erpeeg.m
| 3,634 |
utf_8
|
c387b5b84e9f4ee03b832f289837c1a2
|
% dipfit_erpeeg - fit multiple component dipoles using DIPFIT
%
% Usage:
% >> [ dipole model EEG] = dipfit_erpeeg(data, chanlocs, 'key', 'val', ...);
%
% Inputs:
% data - input data [channel x point]. One dipole per point is
% returned.
% chanlocs - channel location structure (returned by readlocs()).
%
% Optional inputs:
% 'settings' - [cell array] dipfit settings (arguments to the
% pop_dipfit_settings() function). Default is none.
% 'dipoles' - [1|2] use either 1 dipole or 2 dipoles contrain in
% symetry. Default is 1.
% 'dipplot' - ['on'|'off'] plot dipoles. Default is 'off'.
% 'plotopt' - [cell array] dipplot() 'key', 'val' options. Default is
% 'normlen', 'on', 'image', 'fullmri'
%
% Outputs:
% dipole - dipole structure ('posxyz' field is the position; 'momxyz'
% field is the moment and 'rv' the residual variance)
% model - structure containing model information ('vol.r' field is
% radius, 'vol.c' conductances, 'vol.o' the 3-D origin and
% 'chansel', the selected channels).
% EEG - faked EEG structure containing erp activation at the place
% of ICA components but allowing to plot ERP dipoles.
%
% Note: residual variance is set to NaN if Dipfit does not converge
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, Nov. 2003
% Copyright (C) 10/2003 Arnaud Delorme, SCCN/INC/UCSD, [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [dipoles, model, EEG] = dipfit_erpeeg(DATA, chanlocs, varargin);
if nargin < 1
help dipfit_erpeeg;
return;
end;
ncomps = size(DATA,2);
if size(DATA,1) ~= length(chanlocs)
error('# of row in ''DATA'' must equal # of channels in ''chanlocs''');
end;
% faking an EEG dataset
% ---------------------
EEG = eeg_emptyset;
EEG.data = rand(size(DATA,1), 1000);
EEG.nbchan = size(DATA,1);
EEG.pnts = 1000;
EEG.trials = 1;
EEG.chanlocs = chanlocs;
EEG.icawinv = [ DATA DATA ];
EEG.icaweights = zeros(size([ DATA DATA ]))';
EEG.icasphere = zeros(size(DATA,1), size(DATA,1));
%EEG = eeg_checkset(EEG);
EEG.icaact = EEG.icaweights*EEG.icasphere*EEG.data(:,:);
EEG.icaact = reshape( EEG.icaact, size(EEG.icaact,1), size(EEG.data,2), size(EEG.data,3));
% uses mutlifit to fit dipoles
% ----------------------------
EEG = pop_multifit(EEG, [1:ncomps], varargin{:});
% process outputs
% ---------------
dipoles = EEG.dipfit.model;
if isfield(dipoles, 'active')
dipoles = rmfield(dipoles, 'active');
end;
if isfield(dipoles, 'select')
dipoles = rmfield(dipoles, 'select');
end;
model = EEG.dipfit;
if isfield(model, 'model')
model = rmfield(model, 'model');
end;
return;
|
github
|
lcnhappe/happe-master
|
pop_dipfit_batch.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/pop_dipfit_batch.m
| 2,342 |
utf_8
|
349fbd140a3ba8c11fce24b8db9fa20c
|
% pop_dipfit_batch() - interactively do batch scan of all ICA components
% with a single dipole
% Function deprecated. Use pop_dipfit_gridsearch()
% instead
%
% Usage:
% >> OUTEEG = pop_dipfit_batch( INEEG ); % pop up interactive window
% >> OUTEEG = pop_dipfit_batch( INEEG, comps );
% >> OUTEEG = pop_dipfit_batch( INEEG, comps, xgrid, ygrid, zgrid, thresh )
%
% Inputs:
% INEEG - input dataset
% comps - [integer array] component indices
% xgrid - [float array] x-grid. Default is 10 elements between
% -1 and 1.
% ygrid - [float array] y-grid. Default is 10 elements between
% -1 and 1.
% zgrid - [float array] z-grid. Default is 10 elements between
% -1 and 1.
% threshold - [float] threshold in percent. Default 40.
%
% Outputs:
% OUTEEG output dataset
%
% Authors: Robert Oostenveld, SMI/FCDC, Nijmegen 2003
% Arnaud Delorme, SCCN, La Jolla 2003
% SMI, University Aalborg, Denmark http://www.smi.auc.dk/
% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl/
% Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [OUTEEG, com] = pop_dipfit_batch( varargin )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<1
help pop_dipfit_batch;
return
else
disp('Warning: pop_dipfit_manual is outdated. Use pop_dipfit_nonlinear instead');
[OUTEEG, com] = pop_dipfit_gridsearch( varargin{:} );
end;
|
github
|
lcnhappe/happe-master
|
dipfit_nonlinear.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/dipfit_nonlinear.m
| 4,979 |
utf_8
|
74c08245e5fcd0c004b5c7b3357238cf
|
% dipfit_nonlinear() - perform nonlinear dipole fit on one of the components
% to improve the initial dipole model. Only selected dipoles
% will be fitted.
%
% Usage:
% >> EEGOUT = dipfit_nonlinear( EEGIN, optarg)
%
% Inputs:
% ...
%
% Optional inputs are specified in key/value pairs and can be:
% ...
%
% Output:
% ...
%
% Author: Robert Oostenveld, SMI/FCDC, Nijmegen 2003
% Thanks to Nicolas Robitaille for his help on the CTF MEG
% implementation
% SMI, University Aalborg, Denmark http://www.smi.auc.dk/
% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl
% Copyright (C) 2003 Robert Oostenveld, SMI/FCDC [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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [EEGOUT] = dipfit_nonlinear( EEG, varargin )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert the optional arguments into a configuration structure that can be
% understood by FIELDTRIPs dipolefitting function
if nargin>2
cfg = struct(varargin{:});
else
help dipfit_nonlinear
return
end
% specify the FieldTrip DIPOLEFITTING configuration
cfg.model = 'moving';
cfg.gridsearch = 'no';
if ~isfield(cfg, 'nonlinear')
% if this flag is set to 'no', only the dipole moment will be fitted
cfg.nonlinear = 'yes';
end
% add some additional settings from EEGLAB to the configuration
tmpchanlocs = EEG.chanlocs;
cfg.channel = { tmpchanlocs(EEG.dipfit.chansel).labels };
if isfield(EEG.dipfit, 'vol')
cfg.vol = EEG.dipfit.vol;
elseif isfield(EEG.dipfit, 'hdmfile')
cfg.hdmfile = EEG.dipfit.hdmfile;
else
error('no head model in EEG.dipfit')
end
if isfield(EEG.dipfit, 'elecfile') & ~isempty(EEG.dipfit.elecfile)
cfg.elecfile = EEG.dipfit.elecfile;
end
if isfield(EEG.dipfit, 'gradfile') & ~isempty(EEG.dipfit.gradfile)
cfg.gradfile = EEG.dipfit.gradfile;
end
% set up the initial dipole model based on the one in the EEG structure
cfg.dip.pos = EEG.dipfit.model(cfg.component).posxyz;
cfg.dip.mom = EEG.dipfit.model(cfg.component).momxyz';
cfg.dip.mom = cfg.dip.mom(:);
% convert the EEGLAB data structure into a structure that looks as if it
% was computed using FIELDTRIPs componentanalysis function
comp = eeglab2fieldtrip(EEG, 'componentanalysis', 'dipfit');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Added code to handle CTF data with multipleSphere head model %
% This code is copy-pasted in dipfit_gridSearch, dipfit_nonlinear %
% The flag .isMultiSphere is used by dipplot %
% Nicolas Robitaille, January 2007. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Do some trick to force fieldtrip to use the multiple sphere model
if strcmpi(EEG.dipfit.coordformat, 'CTF')
cfg = rmfield(cfg, 'channel');
comp = rmfield(comp, 'elec');
cfg.gradfile = EEG.dipfit.chanfile;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% END %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fit the dipoles to the ICA component(s) of interest using FIELDTRIPs
% dipolefitting function
currentPath = pwd;
ptmp = which('ft_prepare_vol_sens');
ptmp = fileparts(ptmp);
if isempty(ptmp), error('Path to "forward" folder of Fieldtrip missing'); end;
cd(fullfile(ptmp, 'private'));
try,
source = ft_dipolefitting(cfg, comp);
catch,
cd(currentPath);
lasterr
error(lasterr);
end;
cd(currentPath);
% reformat the output dipole sources into EEGLABs data structure
EEG.dipfit.model(cfg.component).posxyz = source.dip.pos;
EEG.dipfit.model(cfg.component).momxyz = reshape(source.dip.mom, 3, length(source.dip.mom)/3)';
EEG.dipfit.model(cfg.component).diffmap = source.Vmodel - source.Vdata;
EEG.dipfit.model(cfg.component).sourcepot = source.Vmodel;
EEG.dipfit.model(cfg.component).datapot = source.Vdata;
EEG.dipfit.model(cfg.component).rv = source.dip.rv;
%EEG.dipfit.model(cfg.component).rv = sum((source.Vdata - source.Vmodel).^2) / sum( source.Vdata.^2 );
EEGOUT = EEG;
|
github
|
lcnhappe/happe-master
|
adjustcylinder2.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/adjustcylinder2.m
| 2,197 |
utf_8
|
34ff5cb12c3fc11a2456e7d82aedd980
|
% adjustcylinder() - Adjust 3d object coordinates to match a pair of points
%
% Usage:
% >> [x y z] = adjustcylinder( x, y, z, pos1, pos2);
%
% Inputs:
% x,y,z - 3-D point coordinates
% pos1 - position of first point [x y z]
% pos2 - position of second point [x y z]
%
% Outputs:
% x,y,z - updated 3-D point coordinates
%
% Author: Arnaud Delorme, CNL / Salk Institute, 30 Mai 2003
% Copyright (C) 2003 Arnaud Delorme
%
% 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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function [x, y, z] = adjustcylinder2( h, pos1, pos2);
% figure; plot3(x(2,:),y(2,:),z(2,:)); [ x(2,:)' y(2,:)' z(2,:)']
% stretch z coordinates to match for vector length
% ------------------------------------------------
dist = sqrt(sum((pos1-pos2).^2));
z = get(h, 'zdata');
zrange = max(z(:)) - min(z(:));
set(h, 'zdata', get(h, 'zdata') /zrange*dist);
% rotate in 3-D to match vector angle [0 0 1] -> vector angle)
% only have to rotate in the x-z and y-z plane
% --------------------------------------------
vectrot = [ pos2(1)-pos1(1) pos2(2)-pos1(2) pos2(3)-pos1(3)];
[thvect phivect] = cart2sph( vectrot(1), vectrot(2), vectrot(3) );
rotatematlab(h, [0 0 1], thvect/pi*180, [0 0 0]);
rotatematlab(h, [thvect+pi/2 0]/pi*180, (pi/2-phivect)/pi*180, [0 0 0]);
x = get(h, 'xdata') + pos1(1);
y = get(h, 'ydata') + pos1(2);
z = get(h, 'zdata') + pos1(3);
set(h, 'xdata', x);
set(h, 'ydata', y);
set(h, 'zdata', z);
return;
|
github
|
lcnhappe/happe-master
|
pop_dipfit_settings.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/dipfit2.3/pop_dipfit_settings.m
| 20,001 |
utf_8
|
7ef22305183621c09beb2691d0250fd9
|
% pop_dipfit_settings() - select global settings for dipole fitting through a pop up window
%
% Usage:
% >> OUTEEG = pop_dipfit_settings ( INEEG ); % pop up window
% >> OUTEEG = pop_dipfit_settings ( INEEG, 'key1', 'val1', 'key2', 'val2' ... )
%
% Inputs:
% INEEG input dataset
%
% Optional inputs:
% 'hdmfile' - [string] file containing a head model compatible with
% the Fieldtrip dipolefitting() function ("vol" entry)
% 'mrifile' - [string] file containing an anatomical MR head image.
% The MRI must be normalized to the MNI brain. See the .mat
% files used by the sphere and boundary element models
% (For instance, select the sphere model and study 'EEG.dipfit').
% If SPM2 software is installed, dipfit will be able to read
% most MRI file formats for plotting purposes (.mnc files, etc...).
% To plot dipoles in a subject MRI, first normalize the MRI
% to the MNI brain using SPM2.
% 'coordformat' - ['MNI'|'Spherical'] Coordinates returned by the selected
% head model. May be MNI coordinates or spherical coordinates
% (For spherical coordinates, the head radius is assumed to be 85 mm.
% 'chanfile' - [string] template channel locations file. (This function will
% check whether your channel locations file is compatible with
% your selected head model).
% 'chansel' - [integer vector] indices of channels to use for dipole fitting.
% {default: all}
% 'coord_transform' - [float array] Talairach transformation matrix for
% aligning the dataset channel locations to the selected
% head model.
% 'electrodes' - [integer array] indices of channels to include
% in the dipole model. {default: all}
% Outputs:
% OUTEEG output dataset
%
% Author: Arnaud Delorme, SCCN, La Jolla 2003-
% Robert Oostenveld, SMI/FCDC, Nijmegen 2003
% MEG flag:
% 'gradfile' - [string] file containing gradiometer locations
% ("gradfile" parameter in Fieldtrip dipolefitting() function)
% SMI, University Aalborg, Denmark http://www.smi.auc.dk/
% FC Donders Centre, University Nijmegen, the Netherlands http://www.fcdonders.kun.nl
% Copyright (C) 2003 [email protected], Arnaud Delorme, SCCN, La Jolla 2003-2005
%
% 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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [OUTEEG, com] = pop_dipfit_settings ( EEG, varargin )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin < 1
help pop_dipfit_settings;
return;
end;
if ~plugin_askinstall('Fieldtrip-lite', 'ft_sourceanalysis'), return; end;
OUTEEG = EEG;
com = '';
% get the default values and filenames
dipfitdefs;
if nargin < 2
if isstr(EEG) % setmodel
tmpdat = get(gcf, 'userdata');
chanfile = tmpdat.chanfile;
tmpdat = tmpdat.template_models;
tmpval = get(findobj(gcf, 'tag', 'listmodels'), 'value');
set(findobj(gcf, 'tag', 'model'), 'string', char(tmpdat(tmpval).hdmfile));
set(findobj(gcf, 'tag', 'coord'), 'value' , fastif(strcmpi(tmpdat(tmpval).coordformat,'MNI'),2, ...
fastif(strcmpi(tmpdat(tmpval).coordformat,'CTF'),3,1)));
set(findobj(gcf, 'tag', 'mri' ), 'string', char(tmpdat(tmpval).mrifile));
set(findobj(gcf, 'tag', 'meg'), 'string', char(tmpdat(tmpval).chanfile));
set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 0);
if tmpval < 3,
set(findobj(gcf, 'userdata', 'editable'), 'enable', 'off');
else,
set(findobj(gcf, 'userdata', 'editable'), 'enable', 'on');
end;
if tmpval == 3,
set(findobj(gcf, 'tag', 'headstr'), 'string', 'Subject CTF head model file (default.htm)');
set(findobj(gcf, 'tag', 'mristr'), 'string', 'Subject MRI (coregistered with CTF head)');
set(findobj(gcf, 'tag', 'chanstr'), 'string', 'CTF Res4 file');
set(findobj(gcf, 'tag', 'manualcoreg'), 'enable', 'off');
set(findobj(gcf, 'userdata', 'coreg'), 'enable', 'off');
else,
set(findobj(gcf, 'tag', 'headstr'), 'string', 'Head model file');
set(findobj(gcf, 'tag', 'mristr'), 'string', 'MRI file');
set(findobj(gcf, 'tag', 'chanstr'), 'string', 'Model template channel locations file');
set(findobj(gcf, 'tag', 'manualcoreg'), 'enable', 'on');
set(findobj(gcf, 'userdata', 'coreg'), 'enable', 'on');
end;
tmpl = tmpdat(tmpval).coord_transform;
set(findobj(gcf, 'tag', 'coregtext'), 'string', '');
set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 0);
[allkeywordstrue transform] = lookupchantemplate(chanfile, tmpl);
if allkeywordstrue,
set(findobj(gcf, 'tag', 'coregtext'), 'string', char(vararg2str({ transform })));
if isempty(transform)
set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 1);
else set(findobj(gcf, 'tag', 'coregcheckbox'), 'value', 0);
end;
end;
return;
end;
% detect DIPFIT1.0x structure
% ---------------------------
if isfield(EEG.dipfit, 'vol')
str = [ 'Dipole information structure from DIPFIT v1.02 detected.' ...
'Keep or erase the old dipole information including dipole locations? ' ...
'In either case, a new dipole model can be constructed.' ];
tmpButtonName=questdlg2( strmultiline(str, 60), 'Old DIPFIT structure', 'Keep', 'Erase', 'Keep');
if strcmpi(tmpButtonName, 'Keep'), return; end;
elseif isfield(EEG.dipfit, 'hdmfile')
% detect previous DIPFIT structure
% --------------------------------
str = [ 'Dipole information and settings are present in the dataset. ' ...
'Keep or erase this information?' ];
tmpButtonName=questdlg2( strmultiline(str, 60), 'Old DIPFIT structure', 'Keep', 'Erase', 'Keep');
if strcmpi(tmpButtonName, 'Keep'), return; end;
end;
% define the callbacks for the buttons
% -------------------------------------
cb_selectelectrodes = [ 'tmplocs = EEG.chanlocs; tmp = select_channel_list({tmplocs.label}, ' ...
'eval(get(findobj(gcbf, ''tag'', ''elec''), ''string'')));' ...
'set(findobj(gcbf, ''tag'', ''elec''), ''string'',[''['' num2str(tmp) '']'']); clear tmplocs;' ]; % did not work
cb_selectelectrodes = 'tmplocs = EEG.chanlocs; set(findobj(gcbf, ''tag'', ''elec''), ''string'', int2str(pop_chansel({tmplocs.labels}))); clear tmplocs;';
cb_volmodel = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'tmpind = get(gcbo, ''value'');' ...
'set(findobj(gcbf, ''tag'', ''radii''), ''string'', num2str(tmpdat{tmpind}.r,3));' ...
'set(findobj(gcbf, ''tag'', ''conduct''), ''string'', num2str(tmpdat{tmpind}.c,3));' ...
'clear tmpdat tmpind;' ];
cb_changeradii = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'tmpdat.vol.r = str2num(get(gcbo, ''string''));' ...
'set(gcf, ''userdata'', tmpdat)' ];
cb_changeconduct = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'tmpdat.vol.c = str2num(get(gcbo, ''string''));' ...
'set(gcf, ''userdata'', tmpdat)' ];
cb_changeorigin = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'tmpdat.vol.o = str2num(get(gcbo, ''string''));' ...
'set(gcf, ''userdata'', tmpdat)' ];
% cb_fitelec = [ 'if get(gcbo, ''value''),' ...
% ' set(findobj(gcbf, ''tag'', ''origin''), ''enable'', ''off'');' ...
% 'else' ...
% ' set(findobj(gcbf, ''tag'', ''origin''), ''enable'', ''on'');' ...
% 'end;' ];
valmodel = 1;
userdata = [];
if isfield(EEG.chaninfo, 'filename')
if ~isempty(findstr(lower(EEG.chaninfo.filename), 'standard-10-5-cap385')), valmodel = 1; end;
if ~isempty(findstr(lower(EEG.chaninfo.filename), 'standard_1005')), valmodel = 2; end;
end;
geomvert = [3 1 1 1 1 1 1 1 1 1 1];
geomhorz = {
[1 2]
[1]
[1 1.3 0.5 0.5 ]
[1 1.3 0.9 0.1 ]
[1 1.3 0.5 0.5 ]
[1 1.3 0.5 0.5 ]
[1 1.3 0.5 0.5 ]
[1 1.3 0.5 0.5 ]
[1]
[1]
[1] };
% define each individual graphical user element
comhelp1 = [ 'warndlg2(strvcat(''The two default head models are in ''standard_BEM'' and ''standard_BESA'''',' ...
''' sub-folders in the DIPFIT2 plugin folder, and may be modified there.''), ''Model type'');' ];
comhelp3 = [ 'warndlg2(strvcat(''Any MR image normalized to the MNI brain model may be used for plotting'',' ...
'''(see the DIPFIT 2.0 tutorial for more information)''), ''Model type'');' ];
comhelp2 = [ 'warndlg2(strvcat(''The template location file associated with the head model'',' ...
'''you are using must be entered (see tutorial).''), ''Template location file'');' ];
commandload1 = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', ''model''), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
commandload2 = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', ''meg''), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
commandload3 = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', ''mri''), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
cb_selectcoreg = [ 'tmpmodel = get( findobj(gcbf, ''tag'', ''model''), ''string'');' ...
'tmploc2 = get( findobj(gcbf, ''tag'', ''meg'') , ''string'');' ...
'tmploc1 = get( gcbo, ''userdata'');' ...
'tmptransf = get( findobj(gcbf, ''tag'', ''coregtext''), ''string'');' ...
'[tmp tmptransf] = coregister(tmploc1{1}, tmploc2, ''mesh'', tmpmodel,' ...
' ''transform'', str2num(tmptransf), ''chaninfo1'', tmploc1{2}, ''helpmsg'', ''on'');' ...
'if ~isempty(tmptransf), set( findobj(gcbf, ''tag'', ''coregtext''), ''string'', num2str(tmptransf)); end;' ...
'clear tmpmodel tmploc2 tmploc1 tmp tmptransf;' ];
setmodel = [ 'pop_dipfit_settings(''setmodel'');' ];
dipfitdefs; % contains template_model
templatenames = { template_models.name };
elements = { ...
{ 'style' 'text' 'string' [ 'Head model (click to select)' 10 '' ] } ...
{ 'style' 'listbox' 'string' strvcat(templatenames{:}) ...
'callback' setmodel 'value' valmodel 'tag' 'listmodels' } { } ...
{ 'style' 'text' 'string' '________' 'tag' 'headstr' } ...
{ 'style' 'edit' 'string' '' 'tag' 'model' 'userdata' 'editable' 'enable' 'off'} ...
{ 'style' 'pushbutton' 'string' 'Browse' 'callback' commandload1 'userdata' 'editable' 'enable' 'off' } ...
{ 'style' 'pushbutton' 'string' 'Help' 'callback' comhelp1 } ...
{ 'style' 'text' 'string' 'Output coordinates' } ...
{ 'style' 'popupmenu' 'string' 'spherical (head radius 85 mm)|MNI|CTF' 'tag' 'coord' ...
'value' 1 'userdata' 'editable' 'enable' 'off'} ...
{ 'style' 'text' 'string' 'Click to select' } { } ...
{ 'style' 'text' 'string' '________' 'tag' 'mristr' } ...
{ 'style' 'edit' 'string' '' 'tag' 'mri' } ...
{ 'style' 'pushbutton' 'string' 'Browse' 'callback' commandload3 } ...
{ 'style' 'pushbutton' 'string' 'Help' 'callback' comhelp3 } ...
{ 'style' 'text' 'string' '________', 'tag', 'chanstr' } ...
{ 'style' 'edit' 'string' '' 'tag' 'meg' 'userdata' 'editable' 'enable' 'off'} ...
{ 'style' 'pushbutton' 'string' 'Browse' 'callback' commandload2 'userdata' 'editable' 'enable' 'off'} ...
{ 'style' 'pushbutton' 'string' 'Help' 'callback' comhelp2 } ...
{ 'style' 'text' 'string' 'Co-register chan. locs. with head model' 'userdata' 'coreg' } ...
{ 'style' 'edit' 'string' '' 'tag' 'coregtext' 'userdata' 'coreg' } ...
{ 'style' 'pushbutton' 'string' 'Manual Co-Reg.' 'tag' 'manualcoreg' 'callback' cb_selectcoreg 'userdata' { EEG.chanlocs,EEG.chaninfo } } ...
{ 'style' 'checkbox' 'string' 'No Co-Reg.' 'tag' 'coregcheckbox' 'value' 0 'userdata' 'coreg' } ...
{ 'style' 'text' 'string' 'Channels to omit from dipole fitting' } ...
{ 'style' 'edit' 'string' '' 'tag' 'elec' } ...
{ 'style' 'pushbutton' 'string' 'List' 'callback' cb_selectelectrodes } { } ...
{ } ...
{ 'style' 'text' 'string' 'Note: For EEG, check that the channel locations are on the surface of the head model' } ...
{ 'style' 'text' 'string' '(To do this: ''Set head radius'' to about 85 in the channel editor).' } ...
};
% plot GUI and protect parameters
% -------------------------------
userdata.template_models = template_models;
if isfield(EEG.chaninfo, 'filename')
userdata.chanfile = lower(EEG.chaninfo.filename);
else userdata.chanfile = '';
end;
optiongui = { 'geometry', geomhorz, 'uilist', elements, 'helpcom', 'pophelp(''pop_dipfit_settings'')', ...
'title', 'Dipole fit settings - pop_dipfit_settings()', ...
'userdata', userdata, 'geomvert', geomvert 'eval' 'pop_dipfit_settings(''setmodel'');' };
[result, userdat2, strhalt, outstruct] = inputgui( 'mode', 'noclose', optiongui{:});
if isempty(result), return; end;
if ~isempty(get(0, 'currentfigure')) currentfig = gcf; else return; end;
while test_wrong_parameters(currentfig)
[result, userdat2, strhalt, outstruct] = inputgui( 'mode', currentfig, optiongui{:});
if isempty(result), return; end;
end;
close(currentfig);
% decode GUI inputs
% -----------------
options = {};
options = { options{:} 'hdmfile' result{2} };
options = { options{:} 'coordformat' fastif(result{3} == 2, 'MNI', fastif(result{3} == 1, 'Spherical', 'CTF')) };
options = { options{:} 'mrifile' result{4} };
options = { options{:} 'chanfile' result{5} };
if ~result{7}, options = { options{:} 'coord_transform' str2num(result{6}) }; end;
options = { options{:} 'chansel' setdiff(1:EEG.nbchan, str2num(result{8})) };
else
options = varargin;
end
g = finputcheck(options, { 'hdmfile' 'string' [] '';
'mrifile' 'string' [] '';
'chanfile' 'string' [] '';
'chansel' 'integer' [] [1:EEG.nbchan];
'electrodes' 'integer' [] [];
'coord_transform' 'real' [] [];
'coordformat' 'string' { 'MNI','spherical','CTF' } 'MNI' });
if isstr(g), error(g); end;
OUTEEG = rmfield(OUTEEG, 'dipfit');
OUTEEG.dipfit.hdmfile = g.hdmfile;
OUTEEG.dipfit.mrifile = g.mrifile;
OUTEEG.dipfit.chanfile = g.chanfile;
OUTEEG.dipfit.chansel = g.chansel;
OUTEEG.dipfit.coordformat = g.coordformat;
OUTEEG.dipfit.coord_transform = g.coord_transform;
if ~isempty(g.electrodes), OUTEEG.dipfit.chansel = g.electrodes; end;
% removing channels with no coordinates
% -------------------------------------
[tmpeloc labels Th Rd indices] = readlocs(EEG.chanlocs);
if length(indices) < length(EEG.chanlocs)
disp('Warning: Channels removed from dipole fitting no longer have location coordinates!');
OUTEEG.dipfit.chansel = intersect( OUTEEG.dipfit.chansel, indices);
end;
% checking electrode configuration
% --------------------------------
if 0
disp('Checking the electrode configuration');
tmpchan = readlocs(OUTEEG.dipfit.chanfile);
[tmp1 ind1 ind2] = intersect( lower({ tmpchan.labels }), lower({ OUTEEG.chanlocs.labels }));
if isempty(tmp1)
disp('No channel labels in common found between template and dataset channels');
if ~isempty(findstr(OUTEEG.dipfit.hdmfile, 'BESA'))
disp('Use the channel editor to fit a head sphere to your channel locations.');
disp('Check for inconsistency in dipole info.');
else
disp('Results using standard BEM model are INACCURATE when the chan locations are not on the head surface!');
end;
else % common channels: performing best transformation
TMP = OUTEEG;
elec1 = eeglab2fieldtrip(TMP, 'elec');
elec1 = elec1.elec;
TMP.chanlocs = tmpchan;
elec2 = eeglab2fieldtrip(TMP, 'elec');
elec2 = elec2.elec;
cfg.elec = elec1;
cfg.template = elec2;
cfg.method = 'warp';
elec3 = electrodenormalize(cfg);
% convert back to EEGLAB format
OUTEEG.chanlocs = struct( 'labels', elec3.label, ...
'X' , mat2cell(elec3.pnt(:,1)'), ...
'Y' , mat2cell(elec3.pnt(:,2)'), ...
'Z' , mat2cell(elec3.pnt(:,3)') );
OUTEEG.chanlocs = convertlocs(OUTEEG.chanlocs, 'cart2all');
end;
end;
com = sprintf('%s = pop_dipfit_settings( %s, %s);', inputname(1), inputname(1), vararg2str(options));
% test for wrong parameters
% -------------------------
function bool = test_wrong_parameters(hdl)
coreg1 = get( findobj( hdl, 'tag', 'coregtext') , 'string' );
coreg2 = get( findobj( hdl, 'tag', 'coregcheckbox'), 'value' );
meg = get( findobj( hdl, 'tag', 'coord'), 'value' );
bool = 0;
if meg == 3, return; end;
if coreg2 == 0 & isempty(coreg1)
bool = 1; warndlg2(strvcat('You must co-register your channel locations', ...
'with the head model (Press buttun, "Manual Co-Reg".', ...
'and follow instructions); To bypass co-registration,', ...
'check the checkbox " No Co-Reg".'), 'Error');
end;
|
github
|
lcnhappe/happe-master
|
eegplugin_cleanline.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/eegplugin_cleanline.m
| 2,154 |
utf_8
|
00012f272d3f6c21e4885de250f6e0ef
|
% eegplugin_cleanline() - EEGLAB plugin for removing line noise
%
% Usage:
% >> eegplugin_cleanline(fig, trystrs, catchstrs);
%
% Inputs:
% fig - [integer] EEGLAB figure
% trystrs - [struct] "try" strings for menu callbacks.
% catchstrs - [struct] "catch" strings for menu callbacks.
%
% Notes:
% This plugins consist of the following Matlab files:
%
% Create a plugin:
% For more information on how to create an EEGLAB plugin see the
% help message of eegplugin_besa() or visit http://www.sccn.ucsd.edu/eeglab/contrib.html
%
%
% See also: pop_cleanline(), cleanline()
% Copyright (C) 2011 Tim Mullen, SCCN/INC/UCSD
%
% 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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
function vers = eegplugin_cleanline(fig, trystrs, catchstrs)
vers = 'cleanline';
if nargin < 3
error('eegplugin_cleanline requires 3 arguments');
end;
% add folder to path
% ------------------
if exist('cleanline', 'file')
p = which('eegplugin_cleanline.m');
p = p(1:findstr(p,'eegplugin_cleanline.m')-1);
addpath(genpath(p));
end;
% find import data menu
% ---------------------
menu = findobj(fig, 'tag', 'tools');
% menu callbacks
% --------------
comcnt = [ trystrs.no_check '[EEG LASTCOM] = pop_cleanline(EEG);' catchstrs.new_and_hist ];
% create menus
% ------------
uimenu( menu, 'label', 'CleanLine', 'callback', comcnt,'separator', 'on', 'position',length(get(menu,'children'))+1);
|
github
|
lcnhappe/happe-master
|
cleanline.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/cleanline.m
| 27,439 |
utf_8
|
db2d5fa2e56fb92bf9e5165018650537
|
function [EEG, Sorig, Sclean, f, amps, freqs, g] = cleanline(varargin)
% Mandatory Information
% --------------------------------------------------------------------------------------------------
% EEG EEGLAB data structure
% --------------------------------------------------------------------------------------------------
%
% Optional Information
% --------------------------------------------------------------------------------------------------
% LineFrequencies: Line noise frequencies to remove
% Input Range : Unrestricted
% Default value: 60 120
% Input Data Type: real number (double)
%
% ScanForLines: Scan for line noise
% This will scan for the exact line frequency in a narrow range around the specified LineFrequencies
% Input Range : Unrestricted
% Default value: 1
% Input Data Type: boolean
%
% LineAlpha: p-value for detection of significant sinusoid
% Input Range : [0 1]
% Default value: 0.01
% Input Data Type: real number (double)
%
% Bandwidth: Bandwidth (Hz)
% This is the width of a spectral peak for a sinusoid at fixed frequency. As such, this defines the
% multi-taper frequency resolution.
% Input Range : Unrestricted
% Default value: 1
% Input Data Type: real number (double)
%
% SignalType: Type of signal to clean
% Cleaned ICA components will be backprojected to channels. If channels are cleaned, ICA activations
% are reconstructed based on clean channels.
% Possible values: 'Components','Channels'
% Default value : 'Components'
% Input Data Type: string
%
% ChanCompIndices: IDs of Chans/Comps to clean
% Input Range : Unrestricted
% Default value: 1:152
% Input Data Type: any evaluable Matlab expression.
%
% SlidingWinLength: Sliding window length (sec)
% Default is the epoch length.
% Input Range : [0 4]
% Default value: 4
% Input Data Type: real number (double)
%
% SlidingWinStep: Sliding window step size (sec)
% This determines the amount of overlap between sliding windows. Default is window length (no
% overlap).
% Input Range : [0 4]
% Default value: 4
% Input Data Type: real number (double)
%
% SmoothingFactor: Window overlap smoothing factor
% A value of 1 means (nearly) linear smoothing between adjacent sliding windows. A value of Inf means
% no smoothing. Intermediate values produce sigmoidal smoothing between adjacent windows.
% Input Range : [1 Inf]
% Default value: 100
% Input Data Type: real number (double)
%
% PaddingFactor: FFT padding factor
% Signal will be zero-padded to the desired power of two greater than the sliding window length. The
% formula is NFFT = 2^nextpow2(SlidingWinLen*(PadFactor+1)). e.g. For SlidingWinLen = 500, if PadFactor = -1, we
% do not pad; if PadFactor = 0, we pad the FFT to 512 points, if PadFactor=1, we pad to 1024 points etc.
% Input Range : [-1 Inf]
% Default value: 2
% Input Data Type: real number (double)
%
% ComputeSpectralPower: Visualize Original and Cleaned Spectra
% Original and clean spectral power will be computed and visualized at end
% Input Range : Unrestricted
% Default value: true
% Input Data Type: boolean
%
% NormalizeSpectrum: Normalize log spectrum by detrending (not generally recommended)
% Input Range : Unrestricted
% Default value: 0
% Input Data Type: boolean
%
% VerboseOutput: Produce verbose output
% Input Range : [true false]
% Default value: true
% Input Data Type: boolean
%
% PlotFigures: Plot Individual Figures
% This will generate figures of F-statistic, spectrum, etc for each channel/comp while processing
% Input Range : Unrestricted
% Default value: 0
% Input Data Type: boolean
%
% --------------------------------------------------------------------------------------------------
% Output Information
% --------------------------------------------------------------------------------------------------
% EEG Cleaned EEG dataset
% Sorig Original multitaper spectrum for each component/channel
% Sclean Cleaned multitaper spectrum for each component/channel
% f Frequencies at which spectrum is estimated in Sorig, Sclean
% amps Complex amplitudes of sinusoidal lines for each
% window (line time-series for window i can be
% reconstructed by creating a sinudoid with frequency f{i} and complex
% amplitude amps{i})
% freqs Exact frequencies at which lines were removed for
% each window (cell array)
% g Parameter structure. Function call can be
% replicated exactly by calling >> cleanline(EEG,g);
%
% Usage Example:
% EEG = pop_cleanline(EEG, 'Bandwidth',2,'ChanCompIndices',[1:EEG.nbchan], ...
% 'SignalType','Channels','ComputeSpectralPower',true, ...
% 'LineFrequencies',[60 120] ,'NormalizeSpectrum',false, ...
% 'LineAlpha',0.01,'PaddingFactor',2,'PlotFigures',false, ...
% 'ScanForLines',true,'SmoothingFactor',100,'VerboseOutput',1, ...
% 'SlidingWinLength',EEG.pnts/EEG.srate,'SlidingWinStep',EEG.pnts/EEG.srate);
%
% See Also:
% pop_cleanline()
% Author: Tim Mullen, SCCN/INC/UCSD Copyright (C) 2011
% Date: Nov 20, 2011
%
%
% 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 3 of the License, or
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307 USA
EEG = arg_extract(varargin,'EEG',[],[]);
if isempty(EEG)
EEG = eeg_emptyset;
end
if ~isempty(EEG.icawinv);
defSigType = {'Components','Channels'};
else
defSigType = {'Channels'};
end
g = arg_define([0 1], varargin, ...
arg_norep('EEG',mandatory), ...
arg({'linefreqs','LineFrequencies'},[60 120],[],'Line noise frequencies to remove.'),...
arg({'scanforlines','ScanForLines'},true,[],'Scan for line noise. This will scan for the exact line frequency in a narrow range around the specified LineFrequencies'),...
arg({'p','LineAlpha','alpha'},0.01,[0 1],'p-value for detection of significant sinusoid'), ...
arg({'bandwidth','Bandwidth'},2,[],'Bandwidth (Hz). This is the width of a spectral peak for a sinusoid at fixed frequency. As such, this defines the multi-taper frequency resolution.'), ...
arg({'sigtype','SignalType','chantype'},defSigType{1},defSigType,'Type of signal to clean. Cleaned ICA components will be backprojected to channels. If channels are cleaned, ICA activations are reconstructed based on clean channels.'), ...
arg({'chanlist','ChanCompIndices','ChanComps'},sprintf('1:%d',EEG.nbchan),[1 EEG.nbchan],'Indices of Channels/Components to clean.','type','expression'),...
arg({'winsize','SlidingWinLength'},fastif(EEG.trials==1,4,EEG.pnts/EEG.srate),[0 EEG.pnts/EEG.srate],'Sliding window length (sec). Default for epoched data is the epoch length. Default for continuous data is 4 seconds'), ...
arg({'winstep','SlidingWinStep'},fastif(EEG.trials==1,1,EEG.pnts/EEG.srate),[0 EEG.pnts/EEG.srate],'Sliding window step size (sec). This determines the amount of overlap between sliding windows. Default for epoched data is window length (no overlap). Default for continuous data is 1 second.'), ...
arg({'tau','SmoothingFactor'},100,[1 Inf],'Window overlap smoothing factor. A value of 1 means (nearly) linear smoothing between adjacent sliding windows. A value of Inf means no smoothing. Intermediate values produce sigmoidal smoothing between adjacent windows.'), ...
arg({'pad','PaddingFactor'},2,[-1 Inf],'FFT padding factor. Signal will be zero-padded to the desired power of two greater than the sliding window length. The formula is NFFT = 2^nextpow2(SlidingWinLen*(PadFactor+1)). e.g. For N = 500, if PadFactor = -1, we do not pad; if PadFactor = 0, we pad the FFT to 512 points, if PadFactor=1, we pad to 1024 points etc.'), ...
arg({'computepower','ComputeSpectralPower'},true,[],'Visualize Original and Cleaned Spectra. Original and clean spectral power will be computed and visualized at end'), ...
arg({'normSpectrum','NormalizeSpectrum'},false,[],'Normalize log spectrum by detrending. Not generally recommended.'), ...
arg({'verb','VerboseOutput','VerbosityLevel'},true,[],'Produce verbose output.'), ...
arg({'plotfigures','PlotFigures'},false,[],'Plot Individual Figures. This will generate figures of F-statistic, spectrum, etc for each channel/comp while processing') ...
);
if any(g.chanlist > fastif(strcmpi(g.sigtype,'channels'),EEG.nbchan,size(EEG.icawinv,1)))
error('''ChanCompIndices'' contains indices of channels or components that are not present in the dataset!');
end
arg_toworkspace(g);
% defaults
[Sorig, Sclean, f, amps, freqs] = deal([]);
hasica = ~isempty(EEG.icawinv);
% set up multi-taper parameters
hbw = g.bandwidth/2; % half-bandwidth
params.tapers = [hbw, g.winsize, 1];
params.Fs = EEG.srate;
params.g.pad = g.pad;
movingwin = [g.winsize g.winstep];
% NOTE: params.tapers = [W, T, p] where:
% T==frequency range in Hz over which the spectrum is maximally concentrated
% on either side of a center frequency (half of the spectral bandwidth)
% W==time resolution (seconds)
% p is used for num_tapers = 2TW-p (usually p=1).
SlidingWinLen = movingwin(1)*params.Fs;
if params.g.pad>=0
NFFT = 2^nextpow2(SlidingWinLen*(params.g.pad+1));
else
NFFT = SlidingWinLen;
end
if isempty(EEG.data) && isempty(EEG.icaact)
fprintf('Hey! Where''s your EEG data?\n');
return;
end
if g.verb
fprintf('\n\nWelcome to the CleanLine line noise removal toolbox!\n');
fprintf('CleanLine is written by Tim Mullen ([email protected]) and uses multi-taper routines modified from the Chronux toolbox (www.chronux.org)\n');
fprintf('\nTsk Tsk, you''ve allowed your data to get very dirty!\n');
fprintf('Let''s roll up our sleeves and do some cleaning!\n');
fprintf('Today we''re going to be cleaning your %s\n',g.sigtype);
if EEG.trials>1
if g.winsize~=g.winstep
fprintf('\n[!] Yikes! I noticed you have multiple trials, but you''ve selected overlapping windows.\n');
fprintf(' This probably means one or more of your windows will span two trials, which can be bad news (discontinuities)!\n');
resp = input('\n Are you sure you want to continue? (''y'',''n''): ','s');
if ~strcmpi(resp,'y')
return;
end
end
if g.winsize > EEG.pnts/EEG.srate
fprintf('\n[!] Yikes! I noticed you have multiple trials, but your window length (%0.4g sec) is greater than the epoch length (%0.4g sec).\n',g.winsize,EEG.pnts/EEG.srate);
fprintf(' This means each window will span multiple trials, which can be bad news!\n');
fprintf(' Ideally, your windows should be less than or equal to the epoch length\n');
resp = input('\n Are you sure you want to continue? (''y'',''n''): ','s');
if ~strcmpi(resp,'y')
return;
end
end
if g.winsize~=g.winstep || g.winsize > EEG.pnts/EEG.srate
fprintf('\nFine, have it your way, but if results are sub-optimal try selecting window length and step size so your windows don''t span multiple trials.\n\n');
pause(2);
end
end
ndiff = rem(EEG.pnts,(g.winsize*EEG.srate));
if ndiff>0
fprintf('\n[!] Please note that because the selected window length does not divide the data length, \n');
fprintf(' %0.4g seconds of data at the end of the record will not be cleaned.\n\n',ndiff/EEG.srate);
end
fprintf('Multi-taper parameters follow:\n');
fprintf('\tTime-bandwidth product:\t %0.4g\n',hbw*g.winsize);
fprintf('\tNumber of tapers:\t %0.4g\n',2*hbw*g.winsize-1);
fprintf('\tNumber of FFT points:\t %d\n',NFFT);
if ~isempty(g.linefreqs)
fprintf('I''m going try to remove lines at these frequencies: [%s] Hz\n',strtrim(num2str(g.linefreqs)));
if g.scanforlines
fprintf('I''m going to scan the range +/-%0.4g Hz around each of the above frequencies for the exact line frequency.\n',params.tapers(1));
fprintf('I''ll do this by selecting the frequency that maximizes Thompson''s F-statistic above a threshold of p=%0.4g.\n',g.p);
end
else
fprintf('You didn''t specify any lines (Hz) to remove, so I''ll try to find them using Thompson''s F-statistic.\n');
fprintf('I''ll use a p-value threshold of %0.4g.\n',g.p)
end
fprintf('\nOK, now stand back and let The Maid show you how it''s done!\n\n');
end
EEGLAB_backcolor = getbackcolor;
if g.plotfigures
% plot the overlap smoothing function
overlap = g.winsize-g.winstep;
toverlap = -overlap/2:(1/EEG.srate):overlap/2;
% specify the smoothing function
foverlap = 1-1./(1+exp(-g.tau.*toverlap/overlap));
% define some colours
yellow = [255, 255, 25]/255;
red = [255 0 0]/255;
% plot the figure
figure('color',EEGLAB_backcolor);
axis([-g.winsize+overlap/2 g.winsize-overlap/2 0 1]); set(gca,'ColorOrder',[0 0 0; 0.7 0 0.8; 0 0 1],'fontsize',11);
hold on
h(1)=hlp_vrect([-g.winsize+overlap/2 -overlap/2], 'yscale',[0 1],'patchProperties',{'FaceColor',yellow, 'FaceAlpha',1,'EdgeColor','none','EdgeAlpha',0.5});
h(2)=hlp_vrect([overlap/2 g.winsize-overlap/2], 'yscale',[0 1],'patchProperties',{'FaceColor',red, 'FaceAlpha',1,'EdgeColor','none','EdgeAlpha',0.5});
h(3)=hlp_vrect([-overlap/2 overlap/2], 'yscale',[0 1],'patchProperties',{'FaceColor',(yellow+red)/2,'FaceAlpha',1,'EdgeColor','none','EdgeAlpha',0.5});
plot(toverlap,foverlap,'linewidth',2);
plot(toverlap,1-foverlap,'linewidth',1,'linestyle','--');
hold off;
xlabel('Time (sec)'); ylabel('Smoothing weight');
title({'Plot of window overlap smoothing function vs. time',['Smoothing factor is \g.tau = ' num2str(g.tau)]});
legend(h,{'Window 1','Window 2','Overlap'});
end
if hasica && isempty(EEG.icaact)
EEG = eeg_checkset(EEG,'ica');
end
k=0;
for ch=g.chanlist
if g.verb,
fprintf('Cleaning %s %d...\n',fastif(strcmpi(g.sigtype,'Components'),'IC','Chan'),ch);
end
% extract data as [chans x frames*trials]
if strcmpi(g.sigtype,'components')
data = squeeze(EEG.icaact(ch,:));
else
data = squeeze(EEG.data(ch,:));
end
if g.plotfigures
% estimate the sinusoidal lines
[Fval sig f] = ftestmovingwinc(data,movingwin,params,g.p);
% plot the F-statistics
[F T] = meshgrid(f,1:size(Fval,1));
figure('color',EEGLAB_backcolor);
subplot(311);
surf(F,T,Fval); shading interp; caxis([0 prctile(Fval(:),99)]); axis tight
sigplane = ones(size(Fval))*sig;
hold on; surf(F,T,sigplane,'FaceColor','b','FaceAlpha',0.5);
xlabel('Frequency'); ylabel('Window'); zlabel('F-value');
title({[sprintf('%s %d: ',fastif(strcmpi(g.sigtype,'components'),'IC ','Chan '), ch) 'Thompson F-statistic for sinusoid'],sprintf('Black plane is p<%0.4g thresh',g.p)});
shadowplot x
shadowplot y
axcopy(gca);
subplot(312);
plot(F,mean(Fval,1),'k');
axis tight
hold on
plot(get(gca,'xlim'),[sig sig],'r:','linewidth',2);
xlabel('Frequency');
ylabel('Thompson F-stat');
title('F-statistic averaged over windows');
legend('F-val',sprintf('p=%0.4g',g.p));
hold off
axcopy(gca);
end
if g.plotfigures
subplot(313)
end
% DO THE MAGIC!
[datac,datafit,amps,freqs]=rmlinesmovingwinc(data,movingwin,g.tau,params,g.p,fastif(g.plotfigures,'y','n'),g.linefreqs,fastif(g.scanforlines,params.tapers(1),[]));
% append to clean dataset any remaining samples that were not cleaned
% due to sliding window and step size not dividing the data length
ndiff = length(data)-length(datac);
if ndiff>0
datac(end:end+ndiff) = data(end-ndiff:end);
end
if g.plotfigures
axis tight
legend('original','cleaned');
xlabel('Frequency (Hz)');
ylabel('Power (dB)');
title(sprintf('Power spectrum for %s %d',fastif(strcmpi(g.sigtype,'components'),'IC','Chan'),ch));
axcopy(gca);
end
if g.computepower
k = k+1;
if g.verb, fprintf('Computing spectral power...\n'); end
[Sorig(k,:) f] = mtspectrumsegc(data,movingwin(1),params);
[Sclean(k,:) f] = mtspectrumsegc(datac,movingwin(1),params);
if g.verb && ~isempty(g.linefreqs)
fprintf('Average noise reduction: ');
for fk=1:length(g.linefreqs)
[dummy fidx] = min(abs(f-g.linefreqs(fk)));
fprintf('%0.4g Hz: %0.4g dB %s ',f(fidx),10*log10(Sorig(k,fidx))-10*log10(Sclean(k,fidx)),fastif(fk<length(g.linefreqs),'|',''));
end
fprintf('\n');
end
if ch==g.chanlist(1)
% First run, so allocate memory for remaining spectra in
% Nchans x Nfreqs spectral matrix
Sorig = cat(1,Sorig,zeros(length(g.chanlist)-1,length(f)));
Sclean = cat(1,Sclean,zeros(length(g.chanlist)-1,length(f)));
end
end
if strcmpi(g.sigtype,'components')
EEG.icaact(ch,:) = datac';
else
EEG.data(ch,:) = datac';
end
end
if g.computepower
if g.verb, fprintf('Converting spectra to dB...\n'); end
% convert to log spectrum
Sorig = 10*log10(Sorig);
Sclean = 10*log10(Sclean);
if g.normSpectrum
if g.verb, fprintf('Normalizing log spectra...\n'); end
% normalize spectrum by standarization
% Sorig = (Sorig-repmat(mean(Sorig,2),1,size(Sorig,2)))./repmat(std(Sorig,[],2),1,size(Sorig,2));
% Sclean = (Sclean-repmat(mean(Sclean,2),1,size(Sclean,2)))./repmat(std(Sclean,[],2),1,size(Sclean,2));
% normalize the spectrum by detrending
Sorig = detrend(Sorig')';
Sclean = detrend(Sclean')';
end
end
if strcmpi(g.sigtype,'components')
if g.verb, fprintf('Backprojecting cleaned components to channels...\n'); end
try
EEG.data = EEG.icawinv*EEG.icaact(1:end,:);
catch e
% low memory, so back-project channels one by one
if g.verb, fprintf('Insufficient memory for fast back-projection. Back-projecting each channel individually...\n'); end
EEG.data = zeros(size(EEG.icaact));
for k=1:size(EEG.icaact,1)
EEG.data(k,:) = EEG.icawinv(:,k)*EEG.icaact(k,:);
end
end
EEG.data = reshape(EEG.data,EEG.nbchan,EEG.pnts*EEG.trials);
elseif hasica
if g.verb, fprintf('Recomputing component activations from cleaned channel data...\n'); end
EEG.icaact = [];
EEG = eeg_checkset(EEG,'ica');
end
function BACKCOLOR = getbackcolor
BACKCOLOR = 'w';
try, icadefs; catch, end;
|
github
|
lcnhappe/happe-master
|
para_dataflow.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/para_dataflow.m
| 15,079 |
utf_8
|
bdf197e6b019efdde172f215e4e5933b
|
function result = para_dataflow(varargin)
% Generic Signal Processing -> Feature Extraction -> Machine Learning BCI framework.
% Result = para_dataflow(FilterSetup, FeatureExtractionArguments, FeatureExtractionSetup, MachineLearningSetup, DialogSetup, ForwardedParameters...)
%
% Most BCI paradigms are implemented as a sequence of three major stages: Signal Processing, Feature Extraction and Machine Learning (see also bci_train).
% The Signal Processing stage operates on time series (plus meta-data), represented as EEGLAB datasets, and may contain multiple sub-stages, which together
% form a filter graph. The data passed from node to node in this graph is either continuous or epoched EEGLAB datasets, and may contain rich annotations, such as
% channel locations, ICA decompositions, DIPFIT models, etc. The nodes are filter components which are shared among many paradigms, and most of them
% are found in filters/flt_* and dataset_ops/set_*. For almost all paradigms, a default order of these stages can be defined, because several filters
% can be arbitrarily ordered w.r.t. each other (linear operators), and most other filters make sense only when executed before or after certain other stages.
% The default signal processing pipeline is implemented in flt_pipeline; its parameters allow to selectively enable processing stages. Paradims derived from
% para_dataflow usually set their own defaults for flt_pipeline (i.e., enable and configure various stages by default), which can be further modified by the user.
%
% The simplest filter components are stateless (such as a surface laplacian filter) and operate on each sample individually, while other filters are
% stateful (and have a certain "memory" of past data), such as FIR and IIR filters. Some of the stateful filters are time-variant (such as signal
% standardization) and some of those are adaptive (such as ICA). Some adaptive filters may be unsupervised, and others may depend on the target variable.
% The majority of filters is causal (i.e. does not need data from future samples to compute the transformed version of some sample) and can therefore be
% applied online, while some filters are non-causal (e.g., the signal envelope and zero-phase FIR filter), and can only be used for offline analyses
% (e.g. for neuroscience). Finally, most filters operate on continuous data, while some filters operate on epoched/segmented data (such as time window
% selection or fourier transform). All of these filter components are written against a unified framework.
%
% Following the Signal Processing stage, most paradigms implement the Feature Extraction stage (especially those paradigms which do not implement
% adaptive statistical signal processing), in which signals are transformed into sets of feature vectors. At this stage, signal meta-data is
% largely stripped off. The feature extraction performed by some paradigms is non-adaptive (such as windowed means or log-variance), while it is
% adaptive (and usually supervised) for others (e.g., CSP). Feature vectors can be viewed as (labeled) points in a high-dimensional space, the
% feature space, which serves as the representation on which the last stage, the machine learning, operates.
%
% The machine learning stage defines a standardized computational framework: it is practically always adaptive, and thus involves a 'learn' case
% and a 'predict' case. In the learning case, labeled sets of feature vectors are received, processed & analyzed, their distribution w.r.t. the
% target variables (labels) is estimated, and a predictive model (or prediction function) incorporating these relations is generated. In the prediction case,
% the previously computed predictive model is applied to individual feature vectors to predict their label/target value (or a probability distribution
% over possible label/target values).
%
% Likewise, a paradigm can be applied to data in a 'learn' mode, in which data is received, feature-extraction is possibly adapted, and a predictive model
% is computed (which is an arbitrary data structure that incorporates the state of all adaptive stages), and a 'predict' mode, in which a previously
% computed predictive model is used to map data to a prediction by sending it through all of the paradigm's stages. Finally, a paradigm has a 'preprocess'
% mode, in which all the signal processing steps take place. Separating the preprocessing from the other two stages leaves more control to the framework
% (bci_train, onl_predict), for example to control the granularity (block size) of data that is fed through the processing stages, buffering,
% caching of intermediate results, partitioning of datasets (for cross-validation, nested cross-validation and other resampling techniques) and
% various optimizations (such as common subexpression elimination and lazy evaluation). This functionality is invisible to the paradigms.
%
% The function para_dataflow represents a small sub-framework for the convenient implementation of paradigms that adhere to this overall three-stage system.
% Paradigms may implement their functionality by calling into para_dataflow, setting some of its parameters in order to customize its standard system.
% Therefore, para_dataflow exposes a set of named parameters for each of the three stages. For signal processing, it exposes all the parameters of
% flt_pipeline, the default signal processing pipeline, allowing paradims to enable various pipeline stages without having to care about their relative
% order or efficient execution. For feature extraction, it exposes the 'featureextract' and 'featureadapt' parameters, which are function handles which
% implement the feature extraction and feature adaption (if any) step of this processing phase; the 'featurevote' parameter specifies whether the 'featureadapt'
% stages requires a voting procedure in cases where more than two classes are present in the data. Very few constraints are imposed on the type of
% inputs, outputs and internal processing of these functions, or on the type of data that is passed through it (EEGLAB datasets or STUDY sets, for example).
% For the machine learning stage, the 'learner' parameter of ml_train is exposed, allowing to specify one of the ml_train*** / ml_predict*** functions
% for learning and prediction, respectively. See ml_train for more explanations of the options.
%
% Paradigms making use of para_dataflow typically pass all user-specified parameters down to para_dataflow (so that the user has maximum control with no
% interference from the paradigm), and set up their own characteristic parameterization of para_dataflow as defaults for these user parameters.
%
% In:
% Parameters... : parameters of the paradigm:
% * 'op' : one of the modes in which the paradigm can be applied to data:
% * 'preprocess', to pre-process the InputSet according to the paradigm (and parameters)
% * 'learn', to learn a predictive model from a pre-processed InputSet (and parameters)
% * 'predict', to make predictions given a pre-processed InputSet and a predictive model
%
% * 'data' : some data (usually an EEGLAB dataset)
%
% if op == 'preprocess':
% * all parameters of flt_pipeline can be supplied for preprocessing; (defaults: no defaults are imposed by para_dataflow itself)
%
% if op == 'learn'
% * 'featureadapt': the adaption stage of the feature extraction; function_handle,
% receives the preprocessed data and returns a model of feature-extraction parameters (default: returns [])
% * 'featureextract': the feature extraction stage; function_handle, receives the preprocessed data and
% the model from the featureadapt stage, and returns a NxF array of N feature vectors (for F features)
% (default: vectorizes each data epoch)
% * 'featurevote': true if the 'featureadapt' function supports only two classes, so that voting is necessary when three
% or more classes are in the data (default: false)
% * 'learner': parameter of ml_train; defines the machine-learning step that is applied to the features (default: 'lda')
%
% if op == 'predict'
% * 'model': the predictive model (as produced during the learning)
%
% Out:
% Result : depends on the op;
% * if 'preprocess', this is the preprocessed dataset
% * if 'learn', this is the learned model
% * if 'predict', this is the predictions produced by the model, given the data
%
% Notes:
% Pre-processing is usually a purely symbolic operation (i.e. symbolic data processing steps are added to the data expression); the framework
% evaluates this expression (and potentially transforms it prior to that, for example for cross-validation) and passes the evaluated expression
% back to the paradigm for 'learning' and/or 'prediction' modes.
%
% Name:
% Data-Flow Framework
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-29
if length(varargin) > 1 && iscell(varargin{1})
% the paradigm is being invoked via a user function (which sets flt_defaults, etc.)
[flt_defaults,fex_declaration,fex_defaults,ml_defaults,dialog_default] = deal(varargin{1:5});
varargin = varargin(6:end);
else
% the paradigm is being invoked directly
[flt_defaults,fex_declaration,fex_defaults,ml_defaults,dialog_default] = deal({});
end
cfg = arg_define(varargin, ...
... % core arguments for the paradigm framework (passed by the framework)
arg_norep('op',[],{'preprocess','learn','predict'},'Operation to execute on the data. Preprocess the raw data, learn a predictive model, or predict outputs given a model.'), ...
arg_norep('data',[],[],'Data to be processed by the paradigm.'), ...
arg_norep('model',[],[],'Model according to which to predict.'), ...
... % signal processing arguments (sourced from flt_pipeline)
arg_sub({'flt','SignalProcessing'},flt_defaults,@flt_pipeline,'Signal processing stages. These can be enabled, disabled and configured for the given paradigm. The result of this stage flows into the feature extraction stage','cat','Signal Processing'), ...
... % arguments for the feature-extraction plugins (passed by the user paradigms)
arg_sub({'fex','FeatureExtraction'},{},fex_declaration,'Parameters for the feature-extraction stage.','cat','Feature Extraction'), ...
... % feature-extraction plugin definitions (passed by the user paradigms)
arg_sub({'plugs','PluginFunctions'},fex_defaults,{ ...
arg({'adapt','FeatureAdaptor'},@default_feature_adapt,[],'The adaption function of the feature extraction. Function_handle, receives the preprocessed data, an options struct (with feature-extraction), and returns a model (which may just re-represent options).'),...
arg({'extract','FeatureExtractor'},@default_feature_extract,[],'The feature extraction function. Function_handle, receives the preprocessed data and the model from the featureadapt stage, and returns a NxF array of N feature vectors (for F features).'), ...
arg({'vote','FeatureAdaptorNeedsVoting'},false,[],'Feature-adaption function requires voting. Only relevant if the data contains three or more classes.') ...
},'The feature-extraction functions','cat','Feature Extraction'), ...
... % machine learning arguments (sourced from ml_train)
arg_sub({'ml','MachineLearning'},ml_defaults,@ml_train,'Machine learning stage of the paradigm. Operates on the feature vectors that are produced by the feature-extraction stage.','cat','Machine Learning'), ...
... % configuration dialog layout
arg({'arg_dialogsel','ConfigLayout'},dialog_default,[],'Parameters displayed in the config dialog. Cell array of parameter names to display (dot-notation allowed); blanks are translated into empty rows in the dialog. Referring to a structure argument lists all parameters of that struture, except if it is a switchable structure - in this case, a pulldown menu with switch options is displayed.','type','cellstr','shape','row'));
% map all of cfg's fields into the function's workspace, for convenience
arg_toworkspace(cfg,true);
switch op
case 'preprocess'
% apply default signal processing
result = flt_pipeline('signal',data,flt);
case 'learn'
classes = unique(set_gettarget(data));
if ~(plugs.vote && numel(classes) > 2)
% learn a model
[result.featuremodel,result.predictivemodel] = learn_model(data,cfg);
else
% binary stage and more than two classes: learn 1-vs-1 models for voting
result.classes = classes;
for i=1:length(classes)
for j=i+1:length(classes)
[result.voting{i,j}.featuremodel,result.voting{i,j}.predictivemodel] = learn_model(exp_eval(set_picktrials(data,'rank',{i,j})),cfg); end
end
end
result.plugs = plugs;
case 'predict'
if ~isfield(model,'voting')
% predict given the extracted features and the model
result = ml_predict(model.plugs.extract(data,model.featuremodel), model.predictivemodel);
else
% 1-vs-1 voting is necessary, construct the aggregate result
trialcount = exp_eval(set_partition(data,[]));
result = {'disc' , zeros(trialcount,length(model.classes)), model.classes};
% vote, adding up the probabilities from each vote
for i=1:length(model.classes)
for j=i+1:length(model.classes)
outcome = ml_predict(model.plugs.extract(data,model.voting{i,j}.featuremodel), model.voting{i,j}.predictivemodel);
result{2}(:,[i j]) = result{2}(:,[i j]) + outcome{2};
end
end
% renormalize probabilities
result{2} = result{2} ./ repmat(sum(result{2},2),1,size(result{2},2));
end
end
function [featuremodel,predictivemodel] = learn_model(data,cfg)
% adapt the feature extractor
switch nargin(cfg.plugs.adapt)
case 1
featuremodel = cfg.plugs.adapt(data);
case 2
featuremodel = cfg.plugs.adapt(data,cfg.fex);
otherwise
featuremodel = cfg.plugs.adapt(data,cfg.fex,cfg);
end
% extract features & learn a predictive model
predictivemodel = ml_train('data',{cfg.plugs.extract(data,featuremodel),set_gettarget(data)},'learner',cfg.ml.learner);
function mdl = default_feature_adapt(data,args)
mdl = args;
function data = default_feature_extract(data,mdl)
data = squeeze(reshape(data.data,[],1,size(data.data,3)))';
|
github
|
lcnhappe/happe-master
|
env_showmenu.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/environment/env_showmenu.m
| 16,401 |
utf_8
|
e922dbf8b0926a434e2012cc7cf148ee
|
function env_showmenu(varargin)
% Links the BCILAB menu into another menu, or creates a new root menu if necessary.
% env_showmenu(Options...)
%
% In:
% Options... : optional name-value pairs; names are:
% 'parent': parent menu to link into
%
% 'shortcuts': whether to enable keyboard shortcuts
%
% 'forcenew': whether to force creation of a new menu
%
% Example:
% % bring up the BCILAB main menu if it had been closed
% env_showmenu;
%
% See also:
% env_startup
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-10-29
% parse options...
hlp_varargin2struct(varargin,'parent',[], 'shortcuts',true,'forcenew',false);
% check if we're an EEGLAB plugin
folders = hlp_split(fileparts(mfilename('fullpath')),filesep);
within_eeglab = length(folders) >= 5 && strcmp(folders{end-3},'plugins') && ~isempty(strfind(folders{end-4},'eeglab'));
% don't open the menu twice
if ~isempty(findobj('Tag','bcilab_menu')) && ~forcenew
return; end
if isempty(parent) %#ok<NODEF>
if within_eeglab && ~forcenew
% try to link into the EEGLAB main menu
try
toolsmenu = findobj(0,'tag','tools');
if ~isempty(toolsmenu)
parent = uimenu(toolsmenu, 'Label','BCILAB');
set(toolsmenu,'Enable','on');
end
catch
disp('Unable to link BCILAB menu into EEGLAB menu.');
end
end
if isempty(parent)
% create new root menu, if no parent
from_left = 100;
from_top = 150;
width = 500;
height = 1;
% determine position on primary monitor
import java.awt.GraphicsEnvironment
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gd = ge.getDefaultScreenDevice();
scrheight = gd.getDisplayMode().getHeight();
pos = [from_left, scrheight-from_top, width, height];
% create figure
figtitle = ['BCILAB ' env_version ' (on ' hlp_hostname ')'];
parent = figure('DockControls','off','NumberTitle','off','Name',figtitle,'Resize','off','MenuBar','none','Position',pos,'Tag','bcilab_toolwnd');
end
end
% Data Source menu
source = uimenu(parent, 'Label','Data Source','Tag','bcilab_menu');
uimenu(source,'Label','Load recording(s)...','Accelerator',char(shortcuts*'l'),'Callback','gui_loadset');
wspace = uimenu(source,'Label','Workspace','Separator','on');
uimenu(wspace,'Label','Load...','Callback','io_loadworkspace');
uimenu(wspace,'Label','Save...','Callback','io_saveworkspace');
uimenu(wspace,'Label','Clear...','Callback','clear');
uimenu(source,'Label','Run script...','Separator','on','Callback',@invoke_script);
if isdeployed
uimenu(source,'Label','Quit','Separator','on','Callback','exit'); end
% Offline Analysis menu
offline = uimenu(parent, 'Label','Offline Analysis');
uimenu(offline,'Label','New approach...','Accelerator',char(shortcuts*'n'),'Callback','gui_newapproach');
uimenu(offline,'Label','Modify approach...','Accelerator',char(shortcuts*'m'),'Callback','gui_configapproach([],true);');
uimenu(offline,'Label','Review/edit approach...','Accelerator',char(shortcuts*'r'),'Callback','gui_reviewapproach([],true);');
uimenu(offline,'Label','Save approach...','Accelerator',char(shortcuts*'s'),'Callback','gui_saveapproach');
uimenu(offline,'Label','Train new model...','Accelerator',char(shortcuts*'t'),'Callback','gui_calibratemodel','Separator','on');
uimenu(offline,'Label','Apply model to data...','Accelerator',char(shortcuts*'a'),'Callback','gui_applymodel');
uimenu(offline,'Label','Visualize model...','Accelerator',char(shortcuts*'v'),'Callback','gui_visualizemodel');
uimenu(offline,'Label','Run batch analysis...','Accelerator',char(shortcuts*'b'),'Callback','gui_batchanalysis','Separator','on');
uimenu(offline,'Label','Review results...','Accelerator',char(shortcuts*'i'),'Callback','gui_selectresults','Separator','on');
% Online Analysis menu
online = uimenu(parent,'Label','Online Analysis');
pipe = uimenu(online,'Label','Process data within...');
read = uimenu(online,'Label','Read input from...');
write = uimenu(online,'Label','Write output to...');
cm_read = uicontextmenu('Tag','bcilab_cm_read');
cm_write = uicontextmenu('Tag','bcilab_cm_write');
% for each plugin sub-directory...
dirs = dir(env_translatepath('functions:/online_plugins'));
for d={dirs(3:end).name}
% find all files, their names, identifiers, and function handles
files = dir(env_translatepath(['functions:/online_plugins/' d{1} '/run_*.m']));
names = {files.name};
idents = cellfun(@(n)n(1:end-2),names,'UniformOutput',false);
% for each entry...
for f=1:length(idents)
try
if ~exist(idents{f},'file') && ~isdeployed
addpath(env_translatepath(['functions:/online_plugins/' d{1}])); end
% get properties...
props = arg_report('properties',str2func(idents{f}));
% get category
if strncmp(idents{f},'run_read',8);
cats = [read,cm_read];
elseif strncmp(idents{f},'run_write',9);
cats = [write,cm_write];
elseif strncmp(idents{f},'run_pipe',8);
cats = pipe;
end
if isfield(props,'name')
% add menu entry
for cat=cats
uimenu(cat,'Label',[props.name '...'],'Callback',['arg_guidialog(@' idents{f} ');'],'Enable','on'); end
else
warning('env_showmenu:missing_guiname','The online plugin %s does not declare a GUI name; ignoring...',idents{f});
end
catch
disp(['Could not integrate the online plugin ' idents{f} '.']);
end
end
end
uimenu(online,'Label','Clear all online processing','Callback','onl_clear','Separator','on');
% Settings menu
settings = uimenu(parent, 'Label','Settings');
uimenu(settings,'Label','Directory settings...','Callback','gui_configpaths');
uimenu(settings,'Label','Cache settings...','Callback','gui_configcache');
uimenu(settings,'Label','Cluster settings...','Callback','gui_configcluster');
uimenu(settings,'Label','Clear memory cache','Callback','env_clear_memcaches','Separator','on');
% Help menu
helping = uimenu(parent,'Label','Help');
uimenu(helping,'Label','BCI Paradigms...','Callback','env_doc code/paradigms');
uimenu(helping,'Label','Filters...','Callback','env_doc code/filters');
uimenu(helping,'Label','Machine Learning...','Callback','env_doc code/machine_learning');
scripting = uimenu(helping,'Label','Scripting');
uimenu(scripting,'Label','File input/output...','Callback','env_doc code/io');
uimenu(scripting,'Label','Dataset editing...','Callback','env_doc code/dataset_editing');
uimenu(scripting,'Label','Offline scripting...','Callback','env_doc code/offline_analysis');
uimenu(scripting,'Label','Online scripting...','Callback','env_doc code/online_analysis');
uimenu(scripting,'Label','BCILAB environment...','Callback','env_doc code/environment');
uimenu(scripting,'Label','Cluster handling...','Callback','env_doc code/parallel');
uimenu(scripting,'Label','Keywords...','Separator','on','Callback','env_doc code/keywords');
uimenu(scripting,'Label','Helpers...','Callback','env_doc code/helpers');
uimenu(scripting,'Label','Internals...','Callback','env_doc code/utils');
authoring = uimenu(helping,'Label','Plugin authoring');
uimenu(authoring,'Label','Argument declaration...','Callback','env_doc code/arguments');
uimenu(authoring,'Label','Expression functions...','Callback','env_doc code/expressions');
uimenu(authoring,'Label','Online processing...','Callback','env_doc code/online_analysis');
uimenu(helping,'Label','About...','Separator','on','Callback',@about);
uimenu(helping,'Label','Save bug report...','Separator','on','Callback','io_saveworkspace([],true)');
uimenu(helping,'Label','File bug report...','Callback','arg_guidialog(@env_bugreport);');
% toolbar (if not linked into the EEGLAB menu)
if ~(within_eeglab && ~forcenew)
global tracking;
cluster_requested = isfield(tracking,'cluster_requested') && ~isempty(tracking.cluster_requested);
cluster_requested = hlp_rewrite(cluster_requested,false,'off',true,'on');
ht = uitoolbar(parent,'HandleVisibility','callback');
uipushtool(ht,'TooltipString','Load recording(s)',...
'CData',load_icon('bcilab:/resources/icons/file_open.png'),...
'HandleVisibility','callback','ClickedCallback','gui_loadset');
uipushtool(ht,'TooltipString','New approach',...
'CData',load_icon('bcilab:/resources/icons/approach_new.png'),...
'HandleVisibility','callback','ClickedCallback','gui_newapproach','Separator','on');
uipushtool(ht,'TooltipString','Load Approach',...
'CData',load_icon('bcilab:/resources/icons/approach_load.png'),...
'HandleVisibility','callback','ClickedCallback',@load_approach);
uipushtool(ht,'TooltipString','Save approach',...
'CData',load_icon('bcilab:/resources/icons/approach_save.png'),...
'HandleVisibility','callback','ClickedCallback','gui_saveapproach');
uipushtool(ht,'TooltipString','Modify approach',...
'CData',load_icon('bcilab:/resources/icons/approach_edit.png'),...
'HandleVisibility','callback','ClickedCallback','gui_configapproach([],true);');
uipushtool(ht,'TooltipString','Review/edit approach',...
'CData',load_icon('bcilab:/resources/icons/approach_review.png'),...
'HandleVisibility','callback','ClickedCallback','gui_reviewapproach([],true);');
uipushtool(ht,'TooltipString','Train new model',...
'CData',load_icon('bcilab:/resources/icons/model_new.png'),...
'HandleVisibility','callback','ClickedCallback','gui_calibratemodel','Separator','on');
uipushtool(ht,'TooltipString','Load Model',...
'CData',load_icon('bcilab:/resources/icons/model_load.png'),...
'HandleVisibility','callback','ClickedCallback',@load_model);
uipushtool(ht,'TooltipString','Save Model',...
'CData',load_icon('bcilab:/resources/icons/model_save.png'),...
'HandleVisibility','callback','ClickedCallback','gui_savemodel');
uipushtool(ht,'TooltipString','Apply model to data',...
'CData',load_icon('bcilab:/resources/icons/model_apply.png'),...
'HandleVisibility','callback','ClickedCallback','gui_applymodel');
uipushtool(ht,'TooltipString','Visualize model',...
'CData',load_icon('bcilab:/resources/icons/model_visualize.png'),...
'HandleVisibility','callback','ClickedCallback','gui_visualizemodel');
uipushtool(ht,'TooltipString','Run batch analysis',...
'CData',load_icon('bcilab:/resources/icons/batch_analysis.png'),...
'HandleVisibility','callback','ClickedCallback','gui_batchanalysis');
uipushtool(ht,'TooltipString','Read input from (online)',...
'CData',load_icon('bcilab:/resources/icons/online_in.png'),...
'HandleVisibility','callback','Separator','on','ClickedCallback',@click_read);
uipushtool(ht,'TooltipString','Write output to (online)',...
'CData',load_icon('bcilab:/resources/icons/online_out.png'),...
'HandleVisibility','callback','ClickedCallback',@click_write);
uipushtool(ht,'TooltipString','Clear online processing',...
'CData',load_icon('bcilab:/resources/icons/online_clear.png'),...
'HandleVisibility','callback','ClickedCallback','onl_clear');
uitoggletool(ht,'TooltipString','Request cluster availability',...
'CData',load_icon('bcilab:/resources/icons/acquire_cluster.png'),'HandleVisibility','callback','Separator','on','State',cluster_requested,'OnCallback','env_acquire_cluster','OffCallback','env_release_cluster');
uipushtool(ht,'TooltipString','About BCILAB',...
'CData',load_icon('bcilab:/resources/icons/help.png'),'HandleVisibility','callback','Separator','on','ClickedCallback',@about);
end
if within_eeglab && forcenew
mainmenu = findobj('Tag','EEGLAB');
% make the EEGLAB menu current again
if ~isempty(mainmenu)
figure(mainmenu); end
end
function about(varargin)
infotext = strvcat(...
'BCILAB is an open-source toolbox for Brain-Computer Interfacing research.', ...
'It is being developed by Christian Kothe at the Swartz Center for Computational Neuroscience,',...
'Institute for Neural Computation (University of California San Diego).', ...
' ',...
'Development of this software was supported by the Army Research Laboratories under', ...
'Cooperative Agreement Number W911NF-10-2-0022, as well as by a gift from the Swartz Foundation.', ...
' ',...
'The design was inspired by the preceding PhyPA toolbox, written by C. Kothe and T. Zander', ...
'at the Berlin Institute of Technology, Chair Human-Machine Systems.', ...
' ',...
'BCILAB connects to the following toolboxes/libraries:', ...
'* AWS SDK (Amazon)', ...
'* Amica (SCCN/UCSD)', ...
'* Chronux (Mitra Lab, Cold Spring Harbor)', ...
'* CVX (Stanford)', ...
'* DAL (U. Tokyo)', ...
'* DataSuite (SCCN/UCSD)', ...
'* EEGLAB (SCCN/UCSD)', ...
'* BCI2000import (www.bci2000.org)', ...
'* Logreg (Jan Drugowitsch)', ...
'* FastICA (Helsinki UT)', ...
'* glm-ie (Max Planck Institute for Biological Cybernetics, Tuebingen)', ...
'* glmnet (Stanford)', ...
'* GMMBayes (Helsinki UT)', ...
'* HKL (Francis Bach, INRIA)', ...
'* KernelICA (Francis Bach, Berkeley)', ...
'* LIBLINEAR (National Taiwan University)', ...
'* matlabcontrol (Joshua Kaplan)', ...
'* mlUnit (Thomas Dohmke)', ...
'* NESTA (Caltech)', ...
'* OSC (Andy Schmeder) and LibLO (Steve Harris)', ...
'* PROPACK (Stanford)', ...
'* PropertyGrid (Levente Hunyadi)', ...
'* SparseBayes (Vector Anomaly)', ...
'* SVMlight (Thorsten Joachims)', ...
'* SVMperf (Thorsten Joachims)', ...
'* Talairach (UTHSCSA)', ...
'* Time-frequency toolbox (CRNS / Rice University)', ...
'* t-SNE (TU Delft)', ...
'* VDPGM (Kenichi Kurihara)'); %#ok<REMFF1>
warndlg2(infotext,'About');
function click_read(varargin)
% pop up a menu when clicking the "read input from" toolbar button
tw = findobj('tag','bcilab_toolwnd');
cm = findobj('tag','bcilab_cm_read');
tpos = get(tw,'Position');
ppos = get(0,'PointerLocation');
set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on');
set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on');
function click_write(varargin)
% pop up a menu when clicking the "write output to" toolbar button
tw = findobj('tag','bcilab_toolwnd');
cm = findobj('tag','bcilab_cm_write');
tpos = get(tw,'Position');
ppos = get(0,'PointerLocation');
set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on');
set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on');
% run a script
function invoke_script(varargin)
[filename,filepath] = uigetfile({'*.m', 'MATLAB file'},'Select script to run',env_translatepath('bcilab:/'));
if ~isnumeric(filename)
run_script([filepath filename],true); end
% load a toolbar icon
function cols = load_icon(filename)
[cols,palette,alpha] = imread(env_translatepath(filename));
if ~isempty(palette)
error('This function does not handle palettized icons.'); end
cls = class(cols);
cols = double(cols);
cols = cols/double(intmax(cls));
cols([alpha,alpha,alpha]==0) = NaN;
% load a BCI model from disk
function load_model(varargin)
[filename,filepath] = uigetfile({'*.mdl', 'BCI Model'},'Select BCI model to load',env_translatepath('home:/.bcilab/models'));
if ~isnumeric(filename)
contents = io_load([filepath filename],'-mat');
for fld=fieldnames(contents)'
tmp = contents.(fld{1});
if isstruct(tmp) && isfield(tmp,'timestamp')
tmp.timestamp = now;
assignin('base',fld{1},tmp);
end
end
end
% load a BCI approach from disk
function load_approach(varargin)
[filename,filepath] = uigetfile({'*.apr', 'BCI Approach'},'Select BCI approach to load',env_translatepath('home:/.bcilab/approaches'));
if ~isnumeric(filename)
contents = io_load([filepath filename],'-mat');
for fld=fieldnames(contents)'
tmp = contents.(fld{1});
if isstruct(tmp) && isfield(tmp,'paradigm')
tmp.timestamp = now;
assignin('base',fld{1},tmp);
end
end
end
|
github
|
lcnhappe/happe-master
|
env_startup.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/environment/env_startup.m
| 21,807 |
utf_8
|
100127e2a96b4156d68b8af7fec6c1ef
|
function env_startup(varargin)
% Start the BCILAB toolbox, i.e. set up global data structures and load dependency toolboxes.
% env_startup(Options...)
%
% Does all steps necessary for loading the toolbox -- the functions bcilab.m and eegplugin_bcilab.m
% are wrappers around this function which provide a higher level of convenience (configuration files
% in particular). Directly calling this function is not recommended.
%
% In:
% Options... : optional name-value pairs; allowed names are:
%
% --- directory settings ---
%
% 'data': Path where data sets are stored, used by data loading/saving routines.
% (default: path/to/bcilab/userdata)
% Note: this may also be a cell array of directories, in which case references
% to data:/ are looked up in all of the specified directories, and the
% best match is taken.
%
% 'store': Path in which data shall be stored. Write permissions necessary (by default
% identical to the data path)
%
% 'temp': temp directory (for misc outputs, e.g., AMICA models and dipole fits)
% (default: path/to/bcilab-temp, or path/to/cache/bcilab_temp if a cache
% directory was specified)
%
% --- caching settings ---
%
% 'cache': Path where intermediate data sets are cached. Should be located on a fast
% (local) drive with sufficient free capacity.
% * if this is left unspecified or empty, the cache is disabled
% * if this is a directory, it is used as the default cache location
% * a fine-grained cache setup can be defined by specifying a cell array of
% cache locations, where each cache location is a cell array of name-value
% pairs, with possible names:
% 'dir': directory of the cache location (e.g. '/tmp/bcilab_tmp/'), mandatory
% 'time': only computations taking more than this many seconds may be stored
% in this location, but if a computation takes so long that another
% cache location with a higher time applies, that other location is
% preferred. For example, the /tmp directory may take computations
% that take at least a minute, the home directory may take
% computations that take at least an hour, the shared /data/results
% location of the lab may take computations that take at least 12
% hours (default: 30 seconds)
% 'free': minimum amount of space to keep free on the given location, in GiB,
% or, if smaller than 1, free is taken as the fraction of total
% space to keep free (default: 0.1)
% 'tag': arbitrary identifier for the cache location (default: 'location_i',
% for the i'th location) must be a valid MATLAB struct field name,
% only for display purposes
%
% 'mem_capacity': capacity of the memory cache (default: 2)
% if this is smaller than 1, it is taken as a fraction of the total
% free physical memory at startup time, otherwise it is in GB
%
% 'data_reuses' : estimated number of reuses of a data set being computed (default: 3)
% ... depending on disk access speeds, this determines whether it makes
% sense to cache the data set
%
% --- parallel computing settings ---
%
% 'parallel' : parallelization options; cell array of name-value pairs, with names:
% 'engine': parallelization engine to use, can be 'local',
% 'ParallelComputingToolbox', or 'BLS' (BCILAB Scheduler)
% (default: 'local')
% 'pool': node pool, cell array of 'host:port' strings; necessary for the
% BLS scheduler (default: {'localhost:23547','localhost:23548',
% ..., 'localhost:23554'})
% 'policy': scheduling policy function; necessary for the BLS scheduler
% (default: 'par_reschedule_policy')
%
% note: Parallel processing has so far received only relatively little
% testing. Please use this facility at your own risk and report
% any issues (e.g., starving jobs) that you may encounter.
%
% 'aquire_options' : Cell array of arguments as expected by par_getworkers_ssh
% (with bcilab-specific defaults for unspecified arguments)
% (default: {})
%
% 'worker' : whether this toolbox instance is started as a worker process or not; if
% false, diary logging and GUI menus and popups are enabled. If given as a
% cell array, the cell contents are passed on to the function par_worker,
% which lets the toolbox act as a commandline-less worker (waiting to
% receive jobs over the network) (default: false)
%
% --- misc settings ---
%
% 'menu' : create a menu bar (default: true) -- if this is set to 'separate', the BCILAB
% menu will be detached from the EEGLAB menu, even if run as a plugin.
%
% 'autocompile' : whether to try to auto-compile mex/java files (default: true)
%
% Examples:
% Note that env_startup is usually not being called directly; instead the bcilab.m function in the
% bcilab root directory forwards its arguments (and variables declared in a config script) to this
% function.
%
% % start BCILAB with a custom data directory, and a custom cache directory
% env_startup('data','C:\Data', 'cache','C:\Data\Temp');
%
% % as before, but specify multiple data paths that are being fused into a common directory view
% % where possible (in case of ambiguities, the earlier directories take precedence)
% env_startup('data',{'C:\Data','F:\Data2'}, 'cache','C:\Data\Temp');
%
% % start BCILAB with a custom data and storage directory, and specify a cache location with some
% % additional meta-data (namely: only cache there if a computation takes at least 60 seconds, and
% % reserve 15GB free space
% env_startup('data','/media/data', 'store','/media/data/results', 'cache',{{'dir','/tmp/tracking','time',60,'free',15}});
%
% % as before, but make sure that the free space does not fall below 20% of the disk
% env_startup('data','/media/data', 'store','/media/data/results', 'cache',{{'dir','/tmp/tracking','time',60,'free',0.2}});
%
% % start BCILAB and set up a very big in-memory cache for working with large data sets (of 16GB)
% env_startup('mem_capacity',16)
%
% % start BCILAB but prevent the main menu from popping up
% env_startup('menu',false)
%
% % start BCILAB and specify which parallel computation resources to use; this assumes that the
% % respective hostnames are reachable from this computer, and are running MATLAB sessions which
% % execute a command similar to: cd /your/path/to/bcilab; bcilab('worker',true); par_worker;
% env_startup('parallel',{'engine','BLS', 'pool',{'computer1','computer2','computer3'}}
%
%
% % start the toolbox as a worker
% env_startup('worker',true)
%
% % start the toolbox as worker, and pass some arguments to par_worker (making it listen on port
% % 15456, using a portrange of 0, and using some custom update-checking arguments
% env_startup('worker',{15456,0,'update_check',{'/data/bcilab-0.9-beta2b/build/bcilab','/mnt/remote/bcilab-build/bcilab'}})
%
% See also:
% env_load_dependencies, env_translatepath
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-03-28
% determine the BCILAB core directories
if ~isdeployed
tmpdir = path_normalize(fileparts(mfilename('fullpath')));
delims = strfind(tmpdir,filesep);
base_dir = tmpdir(1:delims(end-1));
else
% in deployed mode, we walk up until we find the BCILAB base directory
tmpdir = pwd;
delims = strfind(tmpdir,filesep);
disp(['Launching from directory ' tmpdir ' ...']);
for k=length(delims):-1:1
base_dir = tmpdir(1:delims(k));
if exist([base_dir filesep 'code'],'dir')
success = true; %#ok<NASGU>
break;
end
end
if ~exist('success','var')
error('Could not find the ''code'' directory; make sure that the binary is in a sub-directory of a full BCILAB distribution.'); end
end
function_dir = [base_dir 'code'];
dependency_dir = [base_dir 'dependencies'];
resource_dir = [base_dir 'resources'];
script_dir = [base_dir 'userscripts'];
build_dir = [base_dir 'build'];
% add them all to the MATLAB path (except for dependencies, which are loaded separately)
if ~isdeployed
% remove existing BCILAB path references
ea = which('env_add');
if ~isempty(ea)
% get the bcilab root directory that's currently in the path
bad_path = ea(1:strfind(ea,'dependencies')-2);
% remove all references
paths = strsplit(path,pathsep);
retain = cellfun('isempty',strfind(paths,bad_path));
path(sprintf(['%s' pathsep],paths{retain}));
if ~all(retain)
disp(' BCILAB sub-directories have been detected in the MATLAB path, removing them.'); end
end
% add core function paths
addpath(genpath(function_dir));
if exist(build_dir,'dir')
addpath(build_dir); end
evalc('addpath(genpath(script_dir))');
evalc('addpath([base_dir ''userdata''])');
% remove existing eeglab path references, if BCILAB is not itself contained as a plugin in this
% EEGLAB distribution
ep = which('eeglab');
if ~isempty(ep) && isempty(strfind(mfilename('fullpath'),fileparts(which('eeglab'))))
paths = strsplit(path,pathsep);
ep = strsplit(ep,filesep);
retain = cellfun('isempty',strfind(paths,ep{end-1}));
path(sprintf(['%s' pathsep],paths{retain}));
if ~all(retain)
disp(' The previously loaded EEGLAB path has been replaced.'); end
end
end
if hlp_matlab_version < 706
disp('Note: Your version of MATLAB is not supported by BCILAB any more. You may try BCILAB version 0.9, which supports old MATLAB''s back to version 2006a.'); end
% get options
opts = hlp_varargin2struct(varargin,'data',[],'store',[],'cache',[],'temp',[],'mem_capacity',2,'data_reuses',3,'parallel',{'use','local'}, 'menu',true, 'configscript','', 'worker',false, 'autocompile',true, 'acquire_options',{});
% load all dependencies, recursively...
disp('Loading BCILAB dependencies...');
env_load_dependencies(dependency_dir,opts.autocompile);
if ischar(opts.worker)
try
disp(['Evaluating worker argument: ' opts.worker]);
opts.worker = eval(opts.worker);
catch
disp('Failed to evaluate worker; setting it to false.');
opts.worker = false;
end
elseif ~isequal(opts.worker,false)
fprintf('Worker was given as a %s with value %s\n',class(opts.worker),hlp_tostring(opts.worker));
end
if ischar(opts.parallel)
try
disp(['Evaluating parallel argument: ' opts.parallel]);
opts.parallel = eval(opts.parallel);
catch
disp('Failed to evaluate worker; setting it to empty.');
opts.parallel = {};
end
end
% process data directories
if isempty(opts.data)
opts.data = {}; end
if ~iscell(opts.data)
opts.data = {opts.data}; end
for d = 1:length(opts.data)
opts.data{d} = path_normalize(opts.data{d}); end
if isempty(opts.data) || ~any(cellfun(@exist,opts.data))
opts.data = {[base_dir 'userdata']}; end
% process store directory
if isempty(opts.store)
opts.store = opts.data{1}; end
opts.store = path_normalize(opts.store);
% process cache directories
if isempty(opts.cache)
opts.cache = {}; end
if ischar(opts.cache)
opts.cache = {{'dir',opts.cache}}; end
if iscell(opts.cache) && ~isempty(opts.cache) && ~iscell(opts.cache{1})
opts.cache = {opts.cache}; end
for d=1:length(opts.cache)
opts.cache{d} = hlp_varargin2struct(opts.cache{d},'dir','','tag',['location_' num2str(d)],'time',30,'free',0.1); end
% remove entries with empty dir
opts.cache = opts.cache(cellfun(@(e)~isempty(e.dir),opts.cache));
for d=1:length(opts.cache)
% make sure that the BCILAB cache is in its own proper sub-directory
opts.cache{d}.dir = [path_normalize(opts.cache{d}.dir) filesep 'bcilab_cache'];
% create the directory if necessary
if ~isempty(opts.cache{d}.dir) && ~exist(opts.cache{d}.dir,'dir')
try
io_mkdirs([opts.cache{d}.dir filesep],{'+w','a'});
catch
disp(['cache directory ' opts.cache{d}.dir ' does not exist and could not be created']);
end
end
end
% process temp directory
if isempty(opts.temp)
if ~isempty(opts.cache)
opts.temp = [fileparts(opts.cache{1}.dir) filesep 'bcilab_temp'];
else
opts.temp = [base_dir(1:end-1) '-temp'];
end
end
opts.temp = path_normalize(opts.temp);
try
io_mkdirs([opts.temp filesep],{'+w','a'});
catch
disp(['temp directory ' opts.temp ' does not exist and could not be created.']);
end
% set global variables
global tracking
tracking.paths = struct('bcilab_path',{base_dir(1:end-1)}, 'function_path',{function_dir}, 'data_paths',{opts.data}, 'store_path',{opts.store}, 'dependency_path',{dependency_dir},'resource_path',{resource_dir},'temp_path',{opts.temp});
for d=1:length(opts.cache)
location = rmfield(opts.cache{d},'tag');
% convert GiB to bytes
if location.free >= 1
location.free = location.free*1024*1024*1024; end
try
warning off MATLAB:DELETE:Permission;
% probe the cache locations...
import java.io.*;
% try to add a free space checker (Java File object), which we use to check the quota, etc.
location.space_checker = File(opts.cache{d}.dir);
filename = [opts.cache{d}.dir filesep '__probe_cache_ ' num2str(round(rand*2^32)) '__.mat'];
if exist(filename,'file')
delete(filename); end
oldvalue = location.space_checker.getFreeSpace;
testdata = double(rand(1024)); %#ok<NASGU>
objinfo = whos('testdata');
% do a quick read/write test
t0=tic; save(filename,'testdata'); location.writestats = struct('size',{0 objinfo.bytes},'time',{0 toc(t0)});
t0=tic; load(filename); location.readstats = struct('size',{0 objinfo.bytes},'time',{0 toc(t0)});
newvalue = location.space_checker.getFreeSpace;
if exist(filename,'file')
delete(filename); end
% test if the space checker works, and also get some quick measurements of disk read/write speeds
if newvalue >= oldvalue
location = rmfield(location,'space_checker'); end
% and turn the free space ratio into an absolute value
if location.free < 1
location.free = location.free*location.space_checker.getTotalSpace; end
catch e
disp(['Could not probe cache file system speed; reason: ' e.message]);
end
tracking.cache.disk_paths.(opts.cache{d}.tag) = location;
end
if opts.mem_capacity < 1
free_mem = hlp_memavail();
tracking.cache.capacity = round(opts.mem_capacity * free_mem);
if free_mem < 1024*1024*1024
sprintf('Warning: You have less than 1 GB of free memory (reserving %.0f%% = %.0fMB for data caches).\n',100*opts.mem_capacity,tracking.cache.capacity/(1024*1024));
sprintf(' This will severely impact the offline processing speed of BCILAB.\n');
sprintf(' You may force a fixed amount of cache cacpacity by assinging a value greater than 1 (in GB) to the ''mem_capacity'' variable in your bcilab_config.m.');
end
else
tracking.cache.capacity = opts.mem_capacity*1024*1024*1024;
end
tracking.cache.reuses = opts.data_reuses;
tracking.cache.data = struct();
tracking.cache.sizes = struct();
tracking.cache.times = struct();
if ~isfield(tracking.cache,'disk_paths')
tracking.cache.disk_paths = struct(); end
% initialize stack mechanisms
tracking.stack.base = struct('disable_expressions',false);
% set parallelization settings
tracking.parallel = hlp_varargin2struct(opts.parallel, ...
'engine','local', ...
'pool',{'localhost:23547','localhost:23548','localhost:23549','localhost:23550','localhost:23551','localhost:23552','localhost:23553','localhost:23554'}, ...
'policy','par_reschedule_policy');
tracking.acquire_options = opts.acquire_options;
tracking.configscript = opts.configscript;
try
cd(script_dir);
catch
end
% set up some microcache properties
hlp_microcache('arg','lambda_equality','proper');
hlp_microcache('spec','group_size',5);
hlp_microcache('findfunction','lambda_equality','fast','group_size',5);
% show toolbox status
fprintf('\n');
disp(['code is in ' function_dir]);
datalocs = [];
for d = opts.data
datalocs = [datalocs d{1} ', ']; end %#ok<AGROW>
disp(['data is in ' datalocs(1:end-2)]);
disp(['results are in ' opts.store]);
if ~isempty(opts.cache)
fnames = fieldnames(tracking.cache.disk_paths);
for f = 1:length(fnames)
if f == 1
disp(['cache is in ' tracking.cache.disk_paths.(fnames{f}).dir ' (' fnames{f} ')']);
else
disp([' ' tracking.cache.disk_paths.(fnames{f}).dir ' (' fnames{f} ')']);
end
end
else
disp('cache is disabled');
end
disp(['temp is in ' opts.temp]);
fprintf('\n');
% turn off a few nasty warnings
warning off MATLAB:log:logOfZero
warning off MATLAB:divideByZero %#ok<RMWRN>
warning off MATLAB:RandStream:ReadingInactiveLegacyGeneratorState % for GMMs....
if isequal(opts.worker,false) || isequal(opts.worker,0)
% --- regular mode ---
% set up logfile
if ~exist([hlp_homedir filesep '.bcilab'],'dir')
if ~mkdir(hlp_homedir,'.bcilab');
disp('Cannot create directory .bcilab in your home folder.'); end
end
tracking.logfile = env_translatepath('home:/.bcilab/logs/bcilab_console.log');
try
if ~exist([hlp_homedir filesep '.bcilab' filesep 'logs'],'dir')
mkdir([hlp_homedir filesep '.bcilab' filesep 'logs']); end
if exist(tracking.logfile,'file')
warning off MATLAB:DELETE:Permission
delete(tracking.logfile);
warning on MATLAB:DELETE:Permission
end
catch,end
try diary(tracking.logfile); catch,end
if ~exist([hlp_homedir filesep '.bcilab' filesep 'models'],'dir')
mkdir([hlp_homedir filesep '.bcilab' filesep 'models']); end
if ~exist([hlp_homedir filesep '.bcilab' filesep 'approaches'],'dir')
mkdir([hlp_homedir filesep '.bcilab' filesep 'approaches']); end
% create a menu
if ~(isequal(opts.menu,false) || isequal(opts.menu,0))
try
env_showmenu('forcenew',strcmp(opts.menu,'separate'));
catch e
disp('Could not open the BCILAB menu; traceback: ');
env_handleerror(e);
end
end
% display a version reminder
bpath = hlp_split(env_translatepath('bcilab:/'),filesep);
if ~isempty(strfind(bpath{end},'-stable'))
if isdeployed
disp(' This is the stable version.');
else
disp(' This is the stable version - please keep this in mind when editing.');
end
elseif ~isempty(strfind(bpath{end},'-devel'))
if isdeployed
disp(' This is the DEVELOPER version.');
else
try
cprintf([0 0.4 1],'This is the DEVELOPER version.\n');
catch
disp(' This is the DEVELOPER version.');
end
end
end
disp([' Welcome to the BCILAB toolbox on ' hlp_hostname '!'])
fprintf('\n');
else
disp('Now entering worker mode...');
% -- worker mode ---
if ~isdeployed
% disable standard dialogs in the workers
addpath(env_translatepath('dependencies:/disabled_dialogs')); end
% close EEGLAB main menu
mainmenu = findobj('Tag','EEGLAB');
if ~isempty(mainmenu)
close(mainmenu); end
drawnow;
% translate the options
if isequal(opts.worker,true)
opts.worker = {}; end
if ~iscell(opts.worker)
opts.worker = {opts.worker}; end
% start!
par_worker(opts.worker{:});
end
try
% pretend to invoke the dependency list so that the compiler finds it...
dependency_list;
catch
end
% normalize a directory path
function dir = path_normalize(dir)
dir = strrep(strrep(dir,'\',filesep),'/',filesep);
if dir(end) == filesep
dir = dir(1:end-1); end
% Split a string according to some delimiter(s). % Not as fast as hlp_split (and doesn't fuse
% delimiters), but works without bsxfun.
function strings = strsplit(string, splitter)
ix = strfind(string, splitter);
strings = cell(1,numel(ix)+1);
ix = [0 ix numel(string)+1];
for k = 2 : numel(ix)
strings{k-1} = string(ix(k-1)+1:ix(k)-1); end
|
github
|
lcnhappe/happe-master
|
strsetmatch.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/strsetmatch.m
| 928 |
utf_8
|
73f5541ad337bbbc7179cf71004b7062
|
% Indicator of which elements of a universal set are in a particular set.
%
% Input arguments:
% strset:
% the particular set as a cell array of strings
% struniversal:
% the universal set as a cell array of strings, all elements in the
% particular set are expected to be in the universal set
%
% Output arguments:
% ind:
% a logical vector of which elements of the universal set are found in
% the particular set
% Copyright 2010 Levente Hunyadi
function ind = strsetmatch(strset, struniversal)
assert(iscellstr(strset), 'strsetmatch:ArgumentTypeMismatch', ...
'The particular set is expected to be a cell array of strings.');
assert(iscellstr(struniversal), 'strsetmatch:ArgumentTypeMismatch', ...
'The particular set is expected to be a cell array of strings.');
ind = false(size(struniversal));
for k = 1 : numel(struniversal)
ind(k) = ~isempty(strmatch(struniversal{k}, strset, 'exact'));
end
|
github
|
lcnhappe/happe-master
|
helptext.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/helptext.m
| 1,593 |
utf_8
|
bd49205fc50aeae5a909c8b58a47be6d
|
% Help text associated with a function, class, property or method.
% Spaces are removed as necessary.
%
% See also: helpdialog
% Copyright 2008-2010 Levente Hunyadi
function text = helptext(obj)
if ischar(obj)
text = gethelptext(obj);
else
text = gethelptext(class(obj));
end
text = texttrim(text);
function text = gethelptext(key)
persistent dict;
if isempty(dict) && usejava('jvm')
dict = java.util.Properties();
end
if ~isempty(dict)
text = char(dict.getProperty(key)); % look up key in cache
if ~isempty(text) % help text found in cache
return;
end
text = help(key);
if ~isempty(text) % help text returned by help call, save it into cache
dict.setProperty(key, text);
end
else
text = help(key);
end
function lines = texttrim(text)
% Trims leading and trailing whitespace characters from lines of text.
% The number of leading whitespace characters to trim is determined by
% inspecting all lines of text.
loc = strfind(text, sprintf('\n'));
n = numel(loc);
loc = [ 0 loc ];
lines = cell(n,1);
if ~isempty(loc)
for k = 1 : n
lines{k} = text(loc(k)+1 : loc(k+1));
end
end
lines = deblank(lines);
% determine maximum leading whitespace count
f = ~cellfun(@isempty, lines); % filter for non-empty lines
firstchar = cellfun(@(line) find(~isspace(line), 1), lines(f)); % index of first non-whitespace character
if isempty(firstchar)
indent = 1;
else
indent = min(firstchar);
end
% trim leading whitespace
lines(f) = cellfun(@(line) line(min(indent,numel(line)):end), lines(f), 'UniformOutput', false);
|
github
|
lcnhappe/happe-master
|
javaclass.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/javaclass.m
| 3,635 |
utf_8
|
7165e1fd27bd4f5898132023dc04662b
|
% Return java.lang.Class instance for MatLab type.
%
% Input arguments:
% mtype:
% the MatLab name of the type for which to return the java.lang.Class
% instance
% ndims:
% the number of dimensions of the MatLab data type
%
% See also: class
% Copyright 2009-2010 Levente Hunyadi
function jclass = javaclass(mtype, ndims)
validateattributes(mtype, {'char'}, {'nonempty','row'});
if nargin < 2
ndims = 0;
else
validateattributes(ndims, {'numeric'}, {'nonnegative','integer','scalar'});
end
if ndims == 1 && strcmp(mtype, 'char'); % a character vector converts into a string
jclassname = 'java.lang.String';
elseif ndims > 0
jclassname = javaarrayclass(mtype, ndims);
else
% The static property .class applied to a Java type returns a string in
% MatLab rather than an instance of java.lang.Class. For this reason,
% use a string and java.lang.Class.forName to instantiate a
% java.lang.Class object; the syntax java.lang.Boolean.class will not
% do so.
switch mtype
case 'logical' % logical vaule (true or false)
jclassname = 'java.lang.Boolean';
case 'char' % a singe character
jclassname = 'java.lang.Character';
case {'int8','uint8'} % 8-bit signed and unsigned integer
jclassname = 'java.lang.Byte';
case {'int16','uint16'} % 16-bit signed and unsigned integer
jclassname = 'java.lang.Short';
case {'int32','uint32'} % 32-bit signed and unsigned integer
jclassname = 'java.lang.Integer';
case {'int64','uint64'} % 64-bit signed and unsigned integer
jclassname = 'java.lang.Long';
case 'single' % single-precision floating-point number
jclassname = 'java.lang.Float';
case 'double' % double-precision floating-point number
jclassname = 'java.lang.Double';
case 'cellstr' % a single cell or a character array
jclassname = 'java.lang.String';
otherwise
error('java:javaclass:InvalidArgumentValue', ...
'MatLab type "%s" is not recognized or supported in Java.', mtype);
end
end
% Note: When querying a java.lang.Class object by name with the method
% jclass = java.lang.Class.forName(jclassname);
% MatLab generates an error. For the Class.forName method to work, MatLab
% requires class loader to be specified explicitly.
jclass = java.lang.Class.forName(jclassname, true, java.lang.Thread.currentThread().getContextClassLoader());
function jclassname = javaarrayclass(mtype, ndims)
% Returns the type qualifier for a multidimensional Java array.
switch mtype
case 'logical' % logical array of true and false values
jclassid = 'Z';
case 'char' % character array
jclassid = 'C';
case {'int8','uint8'} % 8-bit signed and unsigned integer array
jclassid = 'B';
case {'int16','uint16'} % 16-bit signed and unsigned integer array
jclassid = 'S';
case {'int32','uint32'} % 32-bit signed and unsigned integer array
jclassid = 'I';
case {'int64','uint64'} % 64-bit signed and unsigned integer array
jclassid = 'J';
case 'single' % single-precision floating-point number array
jclassid = 'F';
case 'double' % double-precision floating-point number array
jclassid = 'D';
case 'cellstr' % cell array of strings
jclassid = 'Ljava.lang.String;';
otherwise
error('java:javaclass:InvalidArgumentValue', ...
'MatLab type "%s" is not recognized or supported in Java.', mtype);
end
jclassname = [repmat('[',1,ndims), jclassid];
|
github
|
lcnhappe/happe-master
|
helpdialog.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/helpdialog.m
| 3,397 |
utf_8
|
f16f23c1b608a247bc5298f5ebc6d321
|
% Displays a dialog to give help information on an object.
%
% Examples:
% helpdialog char
% gives information of character arrays
% helpdialog plot
% gives help on the plot command
% helpdialog(obj)
% gives help on the MatLab object obj
%
% See also: helptext, msgbox
% Copyright 2008-2010 Levente Hunyadi
function helpdialog(obj)
if nargin < 1
obj = 'helpdialog';
end
if ischar(obj)
key = obj;
else
key = class(obj);
end
title = [key ' - Quick help'];
text = helptext(key);
if isempty(text)
text = {'No help available.'};
end
if 0 % standard MatLab message dialog box
createmode = struct( ...
'WindowStyle', 'replace', ...
'Interpreter', 'none');
msgbox(text, title, 'help', createmode);
else
fig = figure( ...
'MenuBar', 'none', ...
'Name', title, ...
'NumberTitle', 'off', ...
'Position', [0 0 480 160], ...
'Toolbar', 'none', ...
'Visible', 'off', ...
'ResizeFcn', @helpdialog_resize);
% information icon
icons = load('dialogicons.mat');
icons.helpIconMap(256,:) = get(fig, 'Color');
iconaxes = axes( ...
'Parent', fig, ...
'Units', 'pixels', ...
'Tag', 'IconAxes');
try
iconimg = image('CData', icons.helpIconData, 'Parent', iconaxes);
set(fig, 'Colormap', icons.helpIconMap);
catch me
delete(fig);
rethrow(me)
end
if ~isempty(get(iconimg,'XData')) && ~isempty(get(iconimg,'YData'))
set(iconaxes, ...
'XLim', get(iconimg,'XData')+[-0.5 0.5], ...
'YLim', get(iconimg,'YData')+[-0.5 0.5]);
end
set(iconaxes, ...
'Visible', 'off', ...
'YDir', 'reverse');
% help text
rgb = get(fig, 'Color');
text = cellfun(@(line) helpdialog_html(line), text, 'UniformOutput', false);
html = ['<html>' strjoin(sprintf('\n'), text) '</html>'];
jtext = javax.swing.JLabel(html);
jcolor = java.awt.Color(rgb(1), rgb(2), rgb(3));
jtext.setBackground(jcolor);
jtext.setVerticalAlignment(1);
jscrollpane = javax.swing.JScrollPane(jtext, javax.swing.JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jscrollpane.getViewport().setBackground(jcolor);
jscrollpane.setBorder(javax.swing.border.EmptyBorder(0,0,0,0));
[jcontrol,jcontainer] = javacomponent(jscrollpane, [0 0 100 100]);
set(jcontainer, 'Tag', 'HelpText');
movegui(fig, 'center'); % center figure on screen
set(fig, 'Visible', 'on');
end
function helpdialog_resize(fig, event) %#ok<INUSD>
position = getpixelposition(fig);
width = position(3);
height = position(4);
iconaxes = findobj(fig, 'Tag', 'IconAxes');
helptext = findobj(fig, 'Tag', 'HelpText');
bottom = 7*height/12;
set(iconaxes, 'Position', [12 bottom 51 51]);
set(helptext, 'Position', [75 12 width-75-12 height-24]);
function html = helpdialog_html(line)
preline = deblank(line); % trailing spaces removed
line = strtrim(preline); % leading spaces removed
leadingspace = repmat(' ', 1, numel(preline)-numel(line)); % add leading spaces as non-breaking space
ix = strfind(line, 'See also');
if ~isempty(ix)
ix = ix(1) + numel('See also');
line = [ line(1:ix-1) regexprep(line(ix:end), '(\w[\d\w]+)', '<a href="matlab:helpdialog $1">$1</a>') ];
end
html = ['<p>' leadingspace line '</p>'];
|
github
|
lcnhappe/happe-master
|
getdependentproperties.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/getdependentproperties.m
| 907 |
utf_8
|
5f87bb7115d9bcacd8556d89a4492c44
|
% Publicly accessible dependent properties of an object.
%
% See also: meta.property
% Copyright 2010 Levente Hunyadi
function dependent = getdependentproperties(obj)
dependent = {};
if isstruct(obj) % structures have no dependent properties
return;
end
try
clazz = metaclass(obj);
catch %#ok<CTCH>
return; % old-style class (i.e. not defined with the classdef keyword) have no dependent properties
end
k = 0; % number of dependent properties found
n = numel(clazz.Properties); % maximum number of properties
dependent = cell(n, 1);
for i = 1 : n
property = clazz.Properties{i};
if property.Abstract || property.Hidden || ~strcmp(property.GetAccess, 'public') || ~property.Dependent
continue; % skip abstract, hidden, inaccessible and independent properties
end
k = k + 1;
dependent{k} = property.Name;
end
dependent(k+1:end) = []; % drop unused cells
|
github
|
lcnhappe/happe-master
|
example_matrixeditor.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/example_matrixeditor.m
| 471 |
utf_8
|
637b619421d215e7270f8502574e4ff7
|
% Demonstrates how to use the matrix editor.
%
% See also: MatrixEditor
% Copyright 2010 Levente Hunyadi
function example_matrixeditor
fig = figure( ...
'MenuBar', 'none', ...
'Name', 'Matrix editor demo - Copyright 2010 Levente Hunyadi', ...
'NumberTitle', 'off', ...
'Toolbar', 'none');
editor = MatrixEditor(fig, ...
'Item', [1,2,3,4;5,6,7,8;9,10,11,12], ...
'Type', PropertyType('denserealdouble','matrix'));
uiwait(fig);
disp(editor.Item);
|
github
|
lcnhappe/happe-master
|
example_propertyeditor.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/example_propertyeditor.m
| 473 |
utf_8
|
49faa2989b2f9c32c26f366e77eaf0b2
|
% Demonstrates how to use the property editor.
%
% See also: PropertyEditor
% Copyright 2010 Levente Hunyadi
function example_propertyeditor
% create figure
f = figure( ...
'MenuBar', 'none', ...
'Name', 'Property editor demo - Copyright 2010 Levente Hunyadi', ...
'NumberTitle', 'off', ...
'Toolbar', 'none');
items = { SampleObject SampleObject };
editor = PropertyEditor(f, 'Items', items);
editor.AddItem(SampleNestedObject, 1);
editor.RemoveItem(1);
|
github
|
lcnhappe/happe-master
|
nestedfetch.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/nestedfetch.m
| 1,000 |
utf_8
|
1f3b58597c8ee6879bc2650defb0799d
|
% Fetches the value of the named property of an object or structure.
% This function can deal with nested properties.
%
% Input arguments:
% obj:
% the handle or value object the value should be assigned to
% name:
% a property name with dot (.) separating property names at
% different hierarchy levels
% value:
% the value to assign to the property at the deepest hierarchy
% level
%
% Example:
% obj = struct('surface', struct('nested', 23));
% value = nestedfetch(obj, 'surface.nested');
% disp(value); % prints 23
%
% See also: nestedassign
% Copyright 2010 Levente Hunyadi
function value = nestedfetch(obj, name)
if ~iscell(name)
nameparts = strsplit(name, '.');
else
nameparts = name;
end
value = nestedfetch_recurse(obj, nameparts);
end
function value = nestedfetch_recurse(obj, name)
if numel(name) > 1
value = nestedfetch_recurse(obj.(name{1}), name(2:end));
else
value = obj.(name{1});
end
end
|
github
|
lcnhappe/happe-master
|
findobjuser.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/findobjuser.m
| 1,391 |
utf_8
|
3275be54ee6c453c85fd950bb6ac56b5
|
% Find handle graphics object with user data check.
% Retrieves those handle graphics objects (HGOs) that have the specified
% Tag property and whose UserData property satisfies the given predicate.
%
% Input arguments:
% fcn:
% a predicate (a function that returns a logical value) to test against
% the HGO's UserData property
% tag (optional):
% a string tag to restrict the set of controls to investigate
%
% See also: findobj
% Copyright 2010 Levente Hunyadi
function h = findobjuser(fcn, tag)
validateattributes(fcn, {'function_handle'}, {'scalar'});
if nargin < 2 || isempty(tag)
tag = '';
else
validateattributes(tag, {'char'}, {'row'});
end
%hh = get(0, 'ShowHiddenHandles');
%cleanup = onCleanup(@() set(0, 'ShowHiddenHandles', hh)); % restore visibility on exit or exception
if ~isempty(tag)
% look among all handles (incl. hidden handles) to help findobj locate the object it seeks
h = findobj(findall(0), '-property', 'UserData', '-and', 'Tag', tag); % more results if multiple matching HGOs exist
else
h = findobj(findall(0), '-property', 'UserData');
end
h = unique(h);
try
for k=1:length(h)
pred = fcn(get(h(k), 'UserData'));
if isempty(pred)
pred = false; end
f(k) = pred;
end
%f = arrayfun(@(handle) fcn(get(handle, 'UserData')), h, 'UniformOutput',false);
catch
1
end
h = h(f);
|
github
|
lcnhappe/happe-master
|
javaStringArray.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/javaStringArray.m
| 628 |
utf_8
|
fe0389e3b0d1933d49c1a78c416a279c
|
% Converts a MatLab cell array of strings into a java.lang.String array.
%
% Input arguments:
% str:
% a cell array of strings (i.e. a cell array of char row vectors)
%
% Output arguments:
% arr:
% a java.lang.String array instance (i.e. java.lang.String[])
%
% See also: javaArray
% Copyright 2009-2010 Levente Hunyadi
function arr = javaStringArray(str)
assert(iscellstr(str) && isvector(str), ...
'java:StringArray:InvalidArgumentType', ...
'Cell row or column vector of strings expected.');
arr = javaArray('java.lang.String', length(str));
for k = 1 : numel(str);
arr(k) = java.lang.String(str{k});
end
|
github
|
lcnhappe/happe-master
|
var2str.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/var2str.m
| 441 |
utf_8
|
5588acb0d18dcfac8183caf10a3b5675
|
% Textual representation of any MatLab value.
% Copyright 2009 Levente Hunyadi
function s = var2str(value)
if islogical(value) || isnumeric(value)
s = num2str(value);
elseif ischar(value) && isvector(value)
s = reshape(value, 1, numel(value));
elseif isjava(value)
s = char(value); % calls java.lang.Object.toString()
else
try
s = char(value);
catch %#ok<CTCH>
s = '[no preview available]';
end
end
|
github
|
lcnhappe/happe-master
|
getclassfield.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/getclassfield.m
| 376 |
utf_8
|
e3b87866af8da4dd40243e750a7e53f6
|
% Field value of each object in an array or cell array.
%
% See also: getfield
% Copyright 2010 Levente Hunyadi
function values = getclassfield(objects, field)
values = cell(size(objects));
if iscell(objects)
for k = 1 : numel(values)
values{k} = objects{k}.(field);
end
else
for k = 1 : numel(values)
values{k} = objects(k).(field);
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.