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
ZijingMao/baselineeegtest-master
std_topo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_topo.m
5,225
utf_8
b3a31f9654e617f8f7da77b1b962b870
% std_topo() - uses topoplot() to get the interpolated Cartesian grid of the % specified component topo maps. The topo map grids are saved % into a (.icatopo) file and a pointer to the file is stored % in the EEG structure. If such a file already exists, % loads the information from it. % % Returns the topo map grids of all the requested components. Also % returns the EEG sub-structure etc (i.e EEG.etc), which is modified % with a pointer to the float file and some information about the file. % Usage: % >> X = std_topo(EEG, components, option); % % % Returns the ICA topo map grid for a dataset. % % Updates the EEG structure in the Matlab environment and re-saves % Inputs: % EEG - an EEG dataset structure. % components - [numeric vector] components in the EEG structure to compute topo maps % {default|[] -> all} % option - ['gradient'|'laplacian'|'none'] compute gradient or laplacian of % the scale topography. This does not acffect the saved file which is % always 'none' {default is 'none' = the interpolated topo map} % Outputs: % X - the topo map grid of the requested ICA components, each grid is % one ROW of X. % % File output: [dataset_name].icatopo % % Authors: Hilit Serby, Arnaud Delorme, SCCN, INC, UCSD, January, 2005 % % See also topoplot(), std_erp(), std_ersp(), std_spec(), std_preclust() % Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 2004, [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 [X] = std_topo(EEG, comps, option, varargin) if nargin < 1 help std_topo; return; end; if isfield(EEG,'icaweights') numc = size(EEG.icaweights,1); else error('EEG.icaweights not found'); end if nargin < 2 comps = 1:numc; elseif isempty(comps) comps = 1:numc; end if nargin < 3 option = 'none'; end; g = finputcheck( varargin, { 'recompute' 'string' { 'on','off' } 'off' }, 'std_topo'); if isstr(g), error(g); end; % figure; toporeplot(grid,'style', 'both','plotrad', 0.5, 'intrad', 0.5, 'xsurface' ,Xi, 'ysurface',Yi ); % Topo information found in dataset % --------------------------------- if exist(fullfile(EEG.filepath, [ EEG.filename(1:end-3) 'icatopo' ])) & strcmpi(g.recompute, 'off') for k = 1:length(comps) tmp = std_readtopo( EEG, 1, comps(k)); if strcmpi(option, 'gradient') [tmpx, tmpy] = gradient(tmp); %Gradient tmp = [tmpx(:); tmpy(:)]'; elseif strcmpi(option, 'laplacian') tmp = del2(tmp); %Laplacian tmp = tmp(:)'; else tmp = tmp(:)'; end; tmp = tmp(find(~isnan(tmp))); if k == 1 X = zeros(length(comps),length(tmp)) ; end X(k,:) = tmp; end return end all_topos = []; for k = 1:numc % compute topo map grid (topoimage) % --------------------------------- chanlocs = EEG.chanlocs(EEG.icachansind); if isempty( [ chanlocs.theta ] ) error('Channel locations are required for computing scalp topographies'); end; [hfig grid plotrad Xi Yi] = topoplot( EEG.icawinv(:,k), chanlocs, ... 'verbose', 'off',... 'electrodes', 'on' ,'style','both',... 'plotrad',0.55,'intrad',0.55,... 'noplot', 'on', 'chaninfo', EEG.chaninfo); all_topos = setfield(all_topos, [ 'comp' int2str(k) '_grid' ], grid); all_topos = setfield(all_topos, [ 'comp' int2str(k) '_x' ] , Xi(:,1)); all_topos = setfield(all_topos, [ 'comp' int2str(k) '_y' ] , Yi(:,1)); end % Save topos in file % ------------------ all_topos.datatype = 'TOPO'; tmpfile = fullfile( EEG.filepath, [ EEG.filename(1:end-3) 'icatopo' ]); std_savedat(tmpfile, all_topos); for k = 1:length(comps) tmp = getfield(all_topos, [ 'comp' int2str(comps(k)) '_grid' ]); if strcmpi(option, 'gradient') [tmpx, tmpy] = gradient(tmp); % Gradient tmp = [tmpx(:); tmpy(:)]'; elseif strcmpi(option, 'laplacian') tmp = del2(tmp); % Laplacian tmp = tmp(:)'; else tmp = tmp(:)'; end; tmp = tmp(find(~isnan(tmp))); if k == 1 X = zeros(length(comps),length(tmp)) ; end X(k,:) = tmp; end
github
ZijingMao/baselineeegtest-master
std_stat.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_stat.m
11,175
utf_8
67c286fd36d7d44e591e5897fbf233ef
% std_stat() - compute statistics for ERP/spectral traces or ERSP/ITC images % of a component or channel cluster in a STUDY. % Usage: % >> [pcond, pgroup, pinter, statscond, statsgroup, statsinter] = std_stat( data, 'key', 'val', ...) % Inputs: % data - [cell array] mean data for each subject group and/or data % condition. For example, to compute mean ERPs statistics from a % STUDY for epochs of 800 frames in two conditions from three % groups of 12 subjects: % % >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1 % [800x12] [800x12] [800x12] }; % 3 groups, cond 2 % >> pcond = std_stat(data, 'condstats', 'on'); % % By default, parametric statistics are computed across subjects % in the three groups. See below and >> help statcond % for more information about the statistical computations. % % Statistics options (EEGLAB): % 'groupstats' - ['on'|'off'] Compute (or not) statistics across groups. % {default: 'off'} % 'condstats' - ['on'|'off'] Compute (or not) statistics across groups. % {default: 'off'} % 'method' - ['parametric'|'permutation'] Type of statistics to use % default is 'parametric'. 'perm' and 'param' legacy % abreviations are still functional. % 'naccu' - [integer] Number of surrogate averages fo accumulate when % computing permutation-based statistics. For example, to % test p<0.01 use naccu>=200; for p<0.001, use naccu>=2000. % If a non-NaN 'threshold' is set (see below) and 'naccu' % is too low, it will be automatically increased. This % keyword available only from the command line {default:500} % 'alpha' - [NaN|p-value] threshold for computing p-value. In this % function, it is only used to compute naccu above. NaN % means that no threshold has been set. % 'mcorrect' - ['none'|'fdr'] apply correcting for multiple comparisons. % 'mode' - ['eeglab'|'fieldtrip'] statistical framework to use. % 'eeglab' uses EEGLAB statistical functions and 'fieldtrip' % uses Fieldtrip statistical funcitons. Default is 'eeglab'. % % Fieldtrip statistics options: % 'fieldtripnaccu' - 'numrandomization' Fieldtrip parameter % 'fieldtripalpha' - 'alpha' Fieldtrip parameter. Default is 0.05. % 'fieldtripmethod' - 'method' Fieldtrip parameter. Default is 'analytic' % 'fieldtripmcorrect' - 'mcorrect' Fieldtrip parameter. Default is 'none'. % 'fieldtripclusterparam' - string or cell array for optional parameters % for cluster correction method, see function % ft_statistics_montecarlo for more information. % 'fieldtripchannelneighbor' - Fieldtrip channel neighbour structure for % cluster correction method, see function % std_prepare_neighbors for more information. % Legacy parameters: % 'threshold' - now 'alpha' % 'statistics' - now 'method' % % Outputs: % pcond - [cell] condition pvalues or mask (0 or 1) if an alpha value % is selected. One element per group. % pgroup - [cell] group pvalues or mask (0 or 1). One element per % condition. % pinter - [cell] three elements, condition pvalues (group pooled), % group pvalues (condition pooled) and interaction pvalues. % statcond - [cell] condition statistic values (F or T). % statgroup - [cell] group pvalues or mask (0 or 1). One element per % condition. % statinter - [cell] three elements, condition statistics (group pooled), % group statistics (condition pooled) and interaction F statistics. % % Author: Arnaud Delorme, CERCO, CNRS, 2006- % % See also: statcond() % Copyright (C) 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 [pcond, pgroup, pinter, statscond, statsgroup, statsinter] = std_stat(data, varargin) pgroup = {}; pcond = {}; pinter = {}; if nargin < 1 help std_stat; return; end; % decode inputs % ------------- if ~isempty(varargin) && isstruct(varargin{1}) opt = varargin{1}; varargin(1) = []; else opt = []; end; if ~isempty(varargin) ||isempty(opt); opt = pop_statparams(opt, varargin{:}); end; if ~isfield(opt, 'paired'), opt.paired = { 'off' 'off' }; end; if ~isnan(opt.eeglab.alpha(1)) && isempty(opt.eeglab.naccu), opt.eeglab.naccu = 1/opt.eeglab.alpha(end)*2; end; if any(any(cellfun('size', data, 2)==1)), opt.groupstats = 'off'; opt.condstats = 'off'; end; if strcmpi(opt.eeglab.mcorrect, 'fdr'), opt.eeglab.naccu = opt.eeglab.naccu*20; end; if isempty(opt.eeglab.naccu), opt.eeglab.naccu = 2000; end; if strcmpi(opt.eeglab.method(1:3), 'par') && ~isreal(data{1}) fprintf('*** Cannot use parametric statistics for single-trial ITC significance ***\n'); return; end; nc = size(data,1); ng = size(data,2); % compute significance mask % ------------------------- pcond = {}; pgroup = {}; pinter = {}; statscond = {}; statsgroup = {}; statsinter = {}; if strcmpi(opt.mode, 'eeglab') % EEGLAB statistics % ----------------- if strcmpi(opt.condstats, 'on') && nc > 1 for g = 1:ng [F df pval] = statcond(data(:,g), 'method', opt.eeglab.method, 'naccu', opt.eeglab.naccu, 'paired', opt.paired{1}); pcond{g} = squeeze(pval); statscond{g} = squeeze(F); end; end; if strcmpi(opt.groupstats, 'on') && ng > 1 for c = 1:nc [F df pval] = statcond(data(c,:), 'method', opt.eeglab.method, 'naccu', opt.eeglab.naccu, 'paired', opt.paired{2}); pgroup{c} = squeeze(pval); statsgroup{c} = squeeze(F); end; else end; if ( strcmpi(opt.groupstats, 'on') && strcmpi(opt.condstats, 'on') ) & ng > 1 & nc > 1 opt.paired = sort(opt.paired); % put 'off' first if present [F df pval] = statcond(data, 'method', opt.eeglab.method, 'naccu', opt.eeglab.naccu, 'paired', opt.paired{1}); for index = 1:length(pval) pinter{index} = squeeze(pval{index}); statsinter{index} = squeeze(F{index}); end; end; if ~isempty(opt.groupstats) || ~isempty(opt.condstats) if ~strcmpi(opt.eeglab.mcorrect, 'none'), disp([ 'Applying ' upper(opt.eeglab.mcorrect) ' correction for multiple comparisons' ]); for ind = 1:length(pcond), pcond{ind} = mcorrect( pcond{ind} , opt.eeglab.mcorrect ); end; for ind = 1:length(pgroup), pgroup{ind} = mcorrect( pgroup{ind}, opt.eeglab.mcorrect ); end; if ~isempty(pinter), pinter{1} = mcorrect(pinter{1}, opt.eeglab.mcorrect); pinter{2} = mcorrect(pinter{2}, opt.eeglab.mcorrect); pinter{3} = mcorrect(pinter{3}, opt.eeglab.mcorrect); end; end; if ~isnan(opt.eeglab.alpha) for ind = 1:length(pcond), pcond{ind} = applythreshold(pcond{ind}, opt.eeglab.alpha); end; for ind = 1:length(pgroup), pgroup{ind} = applythreshold(pgroup{ind}, opt.eeglab.alpha); end; for ind = 1:length(pinter), pinter{ind} = applythreshold(pinter{ind}, opt.eeglab.alpha); end; end; end; else if ~exist('ft_freqstatistics'), error('Install Fieldtrip-lite to use Fieldtrip statistics'); end; % Fieldtrip statistics % -------------------- params = {}; if strcmpi(opt.fieldtrip.mcorrect, 'cluster') params = eval( [ '{' opt.fieldtrip.clusterparam '}' ]); if isempty(opt.fieldtrip.channelneighbor), opt.fieldtrip.channelneighbor = struct([]); end; params = { params{:} 'neighbours' opt.fieldtrip.channelneighbor }; % channelneighbor is empty if only one channel selected end; params = { params{:} 'method', opt.fieldtrip.method, 'naccu', opt.fieldtrip.naccu 'mcorrect' opt.fieldtrip.mcorrect 'alpha' opt.fieldtrip.alpha 'numrandomization' opt.fieldtrip.naccu }; params = { params{:} 'structoutput' 'on' }; % before if ~isnan(opt.fieldtrip.alpha), end; if strcmpi(opt.condstats, 'on') && nc > 1 for g = 1:ng [F df pval] = statcondfieldtrip(data(:,g), 'paired', opt.paired{1}, params{:}); pcond{g} = applymask( F, opt.fieldtrip); statscond{g} = squeeze(F.stat); end; else pcond = {}; end; if strcmpi(opt.groupstats, 'on') && ng > 1 for c = 1:nc [F df pval] = statcondfieldtrip(data(c,:), 'paired', opt.paired{2}, params{:}); pgroup{c} = applymask( F, opt.fieldtrip); statsgroup{c} = squeeze(F.stat); end; else pgroup = {}; end; if ( strcmpi(opt.groupstats, 'on') && strcmpi(opt.condstats, 'on') ) & ng > 1 & nc > 1 opt.paired = sort(opt.paired); % put 'off' first if present [F df pval] = statcondfieldtrip(data, 'paired', opt.paired{1}, params{:}); for index = 1:length(pval) pinter{index} = applymask(F{inter}, opt.fieldtrip); statsinter{index} = squeeze(F.stat{index}); end; else pinter = {}; end; end; % apply mask for fieldtrip data % ----------------------------- function p = applymask(F, fieldtrip) if ~isnan(fieldtrip.alpha), p = squeeze(F.mask); else p = squeeze(F.pval); if ~strcmpi(fieldtrip.mcorrect, 'none') p(~F.mask) = 1; end; end; % apply stat threshold to data for EEGLAB stats % --------------------------------------------- function newdata = applythreshold(data, threshold) threshold = sort(threshold); newdata = zeros(size(data)); for index = 1:length(threshold) inds = data < threshold(index); data(inds) = 1; newdata(inds) = length(threshold)-index+1; end; % compute correction for multiple comparisons % ------------------------------------------- function pvals = mcorrect(pvals, method); switch method case {'no' 'none'}, return; case 'bonferoni', pvals = pvals*prod(size(pvals)); case 'holms', [tmp ind] = sort(pvals(:)); [tmp ind2] = sort(ind); pvals(:) = pvals(:).*(prod(size(pvals))-ind2+1); case 'fdr', pvals = fdr(pvals); otherwise error(['Unknown method ''' method ''' for correction for multiple comparisons' ]); end;
github
ZijingMao/baselineeegtest-master
std_selcomp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_selcomp.m
3,156
utf_8
00aa637c4e0c27267077e0bd01c2d8c6
% std_selcomp() - Helper function for std_erpplot(), std_specplot() % and std_erspplot() to select specific % components prior to plotting. % Usage: % >> std_selcomp( STUDY, data, cluster, setinds, compinds, comps) % % Inputs: % STUDY - EEGLAB STUDY structure. % data - [cell array] mean data for each subject group and/or data % condition. For example, to compute mean ERPs statistics from a % STUDY for epochs of 800 frames in two conditions from three % groups of 12 subjects, % >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1 % [800x12] [800x12] [800x12] }; % 3 groups, cond 2 % cluster - [integer] cluster index % setinds - [cell array] set indices for each of the last dimension of the % data cell array. % >> setinds = { [12] [12] [12];... % 3 groups, cond 1 % [12] [12] [12] }; % 3 groups, cond 2 % compinds - [cell array] component indices for each of the last dimension % of the data cell array. % >> compinds = { [12] [12] [12];... % 3 groups, cond 1 % [12] [12] [12] }; % 3 groups, cond 2 % comps - [integer] find and select specific component index in array % % Output: % data - [cell array] data array with the subject or component selected % subject - [string] subject name (for component selection) % comp_names - [cell array] component names (for component selection) % % Author: Arnaud Delorme, CERCO, CNRS, 2006- % % See also: std_erpplot(), std_specplot() and std_erspplot() function [data, subject, comp_names] = std_selcomp(STUDY, data, clust, setinds, compinds, compsel) if nargin < 2 help std_selcomp; return; end; optndims = ndims(data{1}); comp_names = {}; subject = ''; % find and select group % --------------------- if isempty(compsel), return; end; sets = STUDY.cluster(clust).sets(:,compsel); comps = STUDY.cluster(clust).comps(compsel); %grp = STUDY.datasetinfo(sets(1)).group; %grpind = strmatch( grp, STUDY.group ); %if isempty(grpind), grpind = 1; end; %data = data(:,grpind); % find component % -------------- for c = 1:length(data(:)) rminds = 1:size(data{c},optndims); for ind = length(compinds{c}):-1:1 setindex = STUDY.design(STUDY.currentdesign).cell(setinds{c}(ind)).dataset; if compinds{c}(ind) == comps && any(setindex == sets) rminds(ind) = []; end; end; if optndims == 2 data{c}(:,rminds) = []; %2-D elseif optndims == 3 data{c}(:,:,rminds) = []; %3-D else data{c}(:,:,:,rminds) = []; %3-D end; comp_names{c,1} = comps; end; % for c = 1:size(data,1) % for ind = 1:length(compinds{1,grpind}) % if compinds{1,grpind}(ind) == comps & any(setinds{1,grpind}(ind) == sets) % if optndims == 2 % data{c} = data{c}(:,ind); % else data{c} = data{c}(:,:,ind); % end; % comp_names{c,1} = comps; % end; % end; % end; subject = STUDY.datasetinfo(sets(1)).subject;
github
ZijingMao/baselineeegtest-master
neural_net.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/neural_net.m
507
utf_8
0511a54c57462633b86130c890cfbb4d
% neural_net() - computes clusters using Matlab Neural Net toolbox. % Alternative clustering algorithm to kmeans(). % This is a helper function called from pop_clust(). function [IDX,C] = neural_net(clustdata,clus_num) nmin = min(clustdata); nmax = max(clustdata); net = newc([nmin ;nmax].',clus_num); net = train(net,(clustdata).'); Y = sim(net,(clustdata).'); IDX = vec2ind(Y); C = zeros(clus_num,size(clustdata,2)); for k = 1:clus_num C(k,:) = sum(clustdata(find(IDX == k),:)); end
github
ZijingMao/baselineeegtest-master
std_spec.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_spec.m
17,435
utf_8
f0ee68a15f239bf6e29b3bb50c5bd8e9
% std_spec() - Returns the ICA component spectra for a dataset. Updates the EEG structure % in the Matlab environment and in the .set file as well. Saves the spectra % in a file. % Usage: % >> [spec freqs] = std_spec(EEG, 'key', 'val', ...); % % Computes the mean spectra of the activites of specified components of the % supplied dataset. The spectra are saved in a Matlab file. If such a file % already exists, loads the spectral information from this file. % Options (below) specify which components to use, and the desired frequency % range. There is also an option to specify other spectopo() input variables % (see >> help spectopo for details). % % Returns the removed mean spectra of the selected ICA components in the % requested frequency range. If the spectra were computed previously but a % different frequency range is selected, there is an overwrite option. % so. The function will load previously computed log spectra, if any, and % will remove the mean from the requested frequency range. The frequencies % vector is also returned. % Inputs: % EEG - a loaded epoched EEG dataset structure. % % Optional inputs: % 'components' - [numeric vector] components of the EEG structure for which % activation spectrum will be computed. Note that because % computation of ERP is so fast, all components spectrum are % computed and saved. Only selected component % are returned by the function to Matlab % {default|[] -> all} % 'channels' - [cell array] channels of the EEG structure for which % activation spectrum will be computed. Note that because % computation of ERP is so fast, all channels spectrum are % computed and saved. Only selected channels % are returned by the function to Matlab % {default|[] -> none} % 'recompute' - ['on'|'off'] force recomputing ERP file even if it is % already on disk. % 'trialindices' - [cell array] indices of trials for each dataset. % Default is all trials. % 'recompute' - ['on'|'off'] force recomputing data file even if it is % already on disk. % 'rmcomps' - [integer array] remove artifactual components (this entry % is ignored when plotting components). This entry contains % the indices of the components to be removed. Default is none. % 'interp' - [struct] channel location structure containing electrode % to interpolate ((this entry is ignored when plotting % components). Default is no interpolation. % 'fileout' - [string] name of the file to save on disk. The default % is the same name (with a different extension) as the % dataset given as input. % 'savetrials' - ['on'|'off'] save single-trials ERSP. Requires a lot of disk % space (dataset space on disk times 10) but allow for refined % single-trial statistics. % % spectrum specific optional inputs: % 'specmode' - ['psd'|'fft'|'pburg'|'pmtm'] method to compute spectral % decomposition. 'psd' uses the spectopo function (optional % parameters to this function may be given as input). 'fft' % uses a simple fft on each trial. For continuous data % data trials are extracted automatically (see 'epochlim' % and 'epochrecur' below). Two experimental modes are % 'pmtm' and 'pbug' which use multitaper and the Burg % method to compute spectrum respectively. NOTE THAT SOME % OF THESE OPTIONS REQUIRE THE SIGNAL PROCESSING TOOLBOX. % 'epochlim' - [min max] for FFT on continuous data, extract data % epochs with specific epoch limits in seconds (see also % 'epochrecur' below). Default is [0 1]. % 'epochrecur' - [float] for FFT on continuous data, set the automatic % epoch extraction recurence interval (default is 0.5 second). % 'timerange' - [min max] use data within a specific time range before % computing the data spectrum. For instance, for evoked % data trials, it is recommended to use the baseline time % period. % 'logtrials' - ['on'|'off'] compute single-trial log transform before % averaging them. Default is 'off' for 'psd' specmode and % 'on' for 'fft' specmode. % 'continuous' - ['on'|'off'] force epoch data to be treated as % continuous so small data epochs can be extracted for the % 'fft' specmode option. Default is 'off'. % 'freqrange' - [minhz maxhz] frequency range (in Hz) within which to % return the spectrum {default|[]: [0 sample rate/2]}. % Note that this does not affect the spectrum computed on % disk, only the data returned by this function as output. % 'nw' - [integer] number of tapers for the 'pmtm' spectral % method. Default is 4. % 'burgorder' - [integet] order for the Burg spectral method. % % Other optional spectral parameters: % All optional parameters to the spectopo function may be provided to this % function as well (requires the 'specmode' option above to be set to % 'psd'). % % Outputs: % spec - the mean spectra (in dB) of the requested ICA components in the selected % frequency range (with the mean of each spectrum removed). % freqs - a vector of frequencies at which the spectra have been computed. % % Files output or overwritten for ICA: % [dataset_filename].icaspec, % raw spectrum of ICA components % Files output or overwritten for data: % [dataset_filename].datspec, % % See also spectopo(), std_erp(), std_ersp(), std_map(), std_preclust() % % Authors: Arnaud Delorme, SCCN, INC, UCSD, January, 2005 % Defunct: 0 -> if frequency range is different from saved spectra, ask via a % pop-up window whether to keep existing spectra or to overwrite them. % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2004, [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 [X, f, overwrt] = std_spec(EEG, varargin) overwrt = 1; % deprecated if nargin < 1 help std_spec; return; end; % decode inputs % ------------- if ~isempty(varargin) if ~isstr(varargin{1}) varargin = { varargin{:} [] [] }; if all(varargin{1} > 0) options = { 'components' varargin{1} 'freqrange' varargin{2} }; else options = { 'channels' -varargin{1} 'freqrange' varargin{2} }; end; else options = varargin; end; else options = varargin; end; [g spec_opt] = finputcheck(options, { 'components' 'integer' [] []; 'channels' 'cell' {} {}; 'timerange' 'float' [] []; 'specmode' 'string' {'fft','psd','pmtm','pburg'} 'psd'; 'recompute' 'string' { 'on','off' } 'off'; 'savetrials' 'string' { 'on','off' } 'off'; 'continuous' 'string' { 'on','off' } 'off'; 'logtrials' 'string' { 'on','off' 'notset' } 'notset'; 'savefile' 'string' { 'on','off' } 'on'; 'epochlim' 'real' [] [0 1]; 'trialindices' { 'integer','cell' } [] []; 'epochrecur' 'real' [] 0.5; 'rmcomps' 'cell' [] cell(1,length(EEG)); 'nw' 'float' [] 4; 'fileout' 'string' [] ''; 'burgorder' 'integer' [] 20; 'interp' 'struct' { } struct([]); 'nfft' 'integer' [] []; 'freqrange' 'real' [] [] }, 'std_spec', 'ignore'); if isstr(g), error(g); end; if isfield(EEG,'icaweights') numc = size(EEG(1).icaweights,1); else error('EEG.icaweights not found'); end if isempty(g.components) g.components = 1:numc; end EEG_etc = []; % filename % -------- if isempty(g.fileout), g.fileout = fullfile(EEG(1).filepath, EEG(1).filename(1:end-4)); end; if ~isempty(g.channels) filename = [ g.fileout '.datspec']; prefix = 'chan'; else filename = [ g.fileout '.icaspec']; prefix = 'comp'; end; % SPEC information found in datasets % --------------------------------- if exist(filename) & strcmpi(g.recompute, 'off') fprintf('File "%s" found on disk, no need to recompute\n', filename); setinfo.filebase = g.fileout; if strcmpi(prefix, 'comp') [X tmp f] = std_readfile(setinfo, 'components', g.components, 'freqlimits', g.freqrange, 'measure', 'spec'); else [X tmp f] = std_readfile(setinfo, 'channels', g.channels, 'freqlimits', g.freqrange, 'measure', 'spec'); end; if ~isempty(X), return; end; end % No SPEC information found % ------------------------- options = {}; if ~isempty(g.rmcomps), options = { options{:} 'rmcomps' g.rmcomps }; end; if ~isempty(g.interp), options = { options{:} 'interp' g.interp }; end; if isempty(g.channels) [X boundaries] = eeg_getdatact(EEG, 'component', [1:size(EEG(1).icaweights,1)], 'trialindices', g.trialindices ); else [X boundaries] = eeg_getdatact(EEG, 'channel' , [1:EEG(1).nbchan], 'trialindices', g.trialindices, 'rmcomps', g.rmcomps, 'interp', g.interp); end; if ~isempty(boundaries) && boundaries(end) ~= size(X,2), boundaries = [boundaries size(X,2)]; end; % get specific time range for epoched and continuous data % ------------------------------------------------------- oritrials = EEG.trials; if ~isempty(g.timerange) if oritrials > 1 timebef = find(EEG(1).times >= g.timerange(1) & EEG(1).times < g.timerange(2) ); X = X(:,timebef,:); EEG(1).pnts = length(timebef); else disp('warning: ''timerange'' option cannot be used with continuous data'); end; end; % extract epochs if necessary % --------------------------- if ~strcmpi(g.specmode, 'psd') if EEG(1).trials == 1 || strcmpi(g.continuous, 'on') TMP = EEG(1); TMP.data = X; TMP.icaweights = []; TMP.icasphere = []; TMP.icawinv = []; TMP.icaact = []; TMP.icachansind = []; TMP.trials = size(TMP.data,3); TMP.pnts = size(TMP.data,2); TMP.event = []; TMP.epoch = []; for index = 1:length(boundaries) TMP.event(index).type = 'boundary'; TMP.event(index).latency = boundaries(index); end; TMP = eeg_checkset(TMP); if TMP.trials > 1 TMP = eeg_epoch2continuous(TMP); end; TMP = eeg_regepochs(TMP, g.epochrecur, g.epochlim); disp('Warning: continuous data, extracting 1-second epochs'); X = TMP.data; end; end; % compute spectral decomposition % ------------------------------ if strcmpi(g.logtrials, 'notset'), if strcmpi(g.specmode, 'fft') g.logtrials = 'on'; else g.logtrials = 'off'; end; end; if strcmpi(g.logtrials, 'on'), datatype = 'SPECTRUMLOG'; else datatype = 'SPECTRUMABS'; end; if strcmpi(g.specmode, 'psd') if strcmpi(g.savetrials, 'on') || strcmpi(g.logtrials, 'on') for iTrial = 1:size(X,3) [XX(:,:,iTrial), f] = spectopo(X(:,:,iTrial), size(X,2), EEG(1).srate, 'plot', 'off', 'boundaries', boundaries, 'nfft', g.nfft, spec_opt{:}); if iTrial == 1, XX(:,:,size(X,3)) = 0; end; end; if strcmpi(g.logtrials, 'off') X = 10.^(XX/10); else X = XX; end; if strcmpi(g.savetrials, 'off') X = mean(X,3); end; else [X, f] = spectopo(X, size(X,2), EEG(1).srate, 'plot', 'off', 'boundaries', boundaries, 'nfft', g.nfft, spec_opt{:}); X = 10.^(X/10); end; elseif strcmpi(g.specmode, 'pmtm') if strcmpi(g.logtrials, 'on') error('Log trials option cannot be used in conjunction with the PMTM option'); end; if all([ EEG.trials ] == 1) && ~isempty(boundaries), disp('Warning: multitaper does not take into account boundaries in continuous data'); end; fprintf('Computing spectrum using multitaper method:'); for cind = 1:size(X,1) fprintf('.'); for tind = 1:size(X,3) [tmpdat f] = pmtm(X(cind,:,tind), g.nw, g.nfft, EEG.srate); if cind == 1 && tind == 1 X2 = zeros(size(X,1), length(tmpdat), size(X,3)); end; X2(cind,:,tind) = tmpdat; end; end; fprintf('\n'); X = X2; if strcmpi(g.savetrials, 'off'), X = mean(X,3); end; elseif strcmpi(g.specmode, 'pburg') if strcmpi(g.logtrials, 'on') error('Log trials option cannot be used in conjunction with the PBURB option'); end; fprintf('Computing spectrum using Burg method:'); if all([ EEG.trials ] == 1) && ~isempty(boundaries), disp('Warning: pburg does not take into account boundaries in continuous data'); end; for cind = 1:size(X,1) fprintf('.'); for tind = 1:size(X,3) [tmpdat f] = pburg(X(cind,:,tind), g.burgorder, g.nfft, EEG.srate); if cind == 1 && tind == 1 X2 = zeros(size(X,1), length(tmpdat), size(X,3)); end; X2(cind,:,tind) = tmpdat; end; end; fprintf('\n'); X = X2; if strcmpi(g.savetrials, 'off'), X = mean(X,3); end; else % fft mode if oritrials == 1 || strcmpi(g.continuous, 'on') X = bsxfun(@times, X, hamming(size(X,2))'); end; if all([ EEG.trials ] == 1) && ~isempty(boundaries), disp('Warning: fft does not take into account boundaries in continuous data'); end; tmp = fft(X, g.nfft, 2); f = linspace(0, EEG(1).srate/2, floor(size(tmp,2)/2)); f = f(2:end); % remove DC (match the output of PSD) tmp = tmp(:,2:floor(size(tmp,2)/2),:); X = tmp.*conj(tmp); if strcmpi(g.logtrials, 'on'), X = 10*log10(X); end; if strcmpi(g.savetrials, 'off'), X = mean(X,3); end; if strcmpi(g.logtrials, 'off'), X = 10*log10(X); end; end; % Save SPECs in file (all components or channels) % ----------------------------------------------- fileNames = computeFullFileName( { EEG.filepath }, { EEG.filename }); if strcmpi(g.savefile, 'on') options = { options{:} spec_opt{:} 'timerange' g.timerange 'nfft' g.nfft 'specmode' g.specmode }; if strcmpi(prefix, 'comp') savetofile( filename, f, X, 'comp', 1:size(X,1), options, {}, fileNames, g.trialindices, datatype); else if ~isempty(g.interp) savetofile( filename, f, X, 'chan', 1:size(X,1), options, { g.interp.labels }, fileNames, g.trialindices, datatype); else tmpchanlocs = EEG(1).chanlocs; savetofile( filename, f, X, 'chan', 1:size(X,1), options, { tmpchanlocs.labels }, fileNames, g.trialindices, datatype); end; end; end; return; % compute full file names % ----------------------- function res = computeFullFileName(filePaths, fileNames); for index = 1:length(fileNames) res{index} = fullfile(filePaths{index}, fileNames{index}); end; % ------------------------------------- % saving SPEC information to Matlab file % ------------------------------------- function savetofile(filename, f, X, prefix, comps, params, labels, dataFiles, dataTrials, datatype); disp([ 'Saving SPECTRAL file ''' filename '''' ]); allspec = []; for k = 1:length(comps) allspec = setfield( allspec, [ prefix int2str(comps(k)) ], squeeze(X(k,:,:))); end; if nargin > 6 && ~isempty(labels) allspec.labels = labels; end; allspec.freqs = f; allspec.parameters = params; allspec.datatype = datatype; allspec.datafiles = dataFiles; allspec.datatrials = dataTrials; allspec.average_spec = mean(X,1); std_savedat(filename, allspec);
github
ZijingMao/baselineeegtest-master
std_precomp_worker.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_precomp_worker.m
2,834
utf_8
35f7db94f3bde2742d8ec681fae164f1
% std_precomp_worker() - allow dispatching ERSP to be computed in parallel % on a given cluster. % Usage: % >> feature = std_precomp_worker(filename, varargin); % % Inputs: % filename - STUDY file name % % Optional inputs: % Optional inputs are the same as for the std_precomp function. Note that % this function can currently only compute ERSP and ITC. The argument % 'cell' must be defined so a given node will only compute the measure on % one cell (one cell per node). % output trials {default: whole measure range} % Output: % feature - data structure containing ERSP and/or ITC % % Author: Arnaud Delorme, SCCN, UCSD, 2012- % Copyright (C) Arnaud Delorme, [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 feature = std_precomp_worker(filename, varargin) if nargin < 2 help std_precomp_worker; return; end; g = struct(varargin{2:end}); % load dataset % ------------ [STUDY ALLEEG] = pop_loadstudy('filename', filename); if ~isfield(g, 'design'), g.design = STUDY.currentdesign; end; if isfield(g, 'erp') || isfield(g, 'spec') || isfield(g, 'erpim') || isfield(g, 'scalp') error('This function is currently designed to compute time-frequency decompositions only'); end; if ~isfield(g, 'ersp') && ~isfield(g, 'itc') error('You must compute either ERSP or ITC when using the EC2 cluster'); end; % run std_precomp (THIS IS THE PART WE WANT TO PARALELIZE) % --------------- % for index = 1:length(STUDY.design(g.design).cell) % [STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, varargin{:}, 'cell', index); % end; std_precomp(STUDY, ALLEEG, varargin{:}); filebase = STUDY.design(g.design).cell(g.cell).filebase; if isfield(g, 'channel') fileERSP = [ filebase '.datersp' ]; fileITC = [ filebase '.datitc' ]; if exist(fileERSP), feature.ersp = load('-mat', fileERSP); end; if exist(fileITC ), feature.itc = load('-mat', fileITC ); end; else fileERSP = [ filebase '.icaersp' ]; fileITC = [ filebase '.icaitc' ]; if exist(fileERSP), feature.ersp = load('-mat', fileERSP); end; if exist(fileITC ), feature.itc = load('-mat', fileITC ); end; end;
github
ZijingMao/baselineeegtest-master
pop_studyerp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_studyerp.m
8,206
utf_8
b0813e4eb5cf7b6f15ee9f45028b7261
% pop_studyerp() - create a simple design for ERP analysis % % Usage: % >> [STUDY ALLEEG] = pop_studyerp; % pop up interface % % Outputs: % STUDY - an EEGLAB STUDY set of loaded EEG structures % ALLEEG - ALLEEG vector of one or more loaded EEG dataset structures % % Author: Arnaud Delorme, SCCN, UCSD, 2011- % % See also: eeg_checkset() % Copyright (C) 15 Feb 2002 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 [STUDY ALLEEG com ] = pop_studyerp; % first GUI, get the number of conditions and subjects % ---------------------------------------------------- textinfo = [ 'This interface creates a simple STUDY and ' 10 ... 'computes its condition grand average ERPs.' 10 ... 'For each subject, trials for each condition' 10 ... 'must first be stored in a separate dataset.' 10 ... 'Create other STUDY using the standard editor.' ]; guispec = { ... {'style' 'text' 'string' 'Create simple ERP STUDY' ... 'FontWeight' 'Bold' 'fontsize', 12} ... { 'style' 'text' 'string' textinfo } ... {'style' 'text' 'string' 'Number of conditions:' } ... {'style' 'edit' 'string' '1' 'tag' 'cond' } { } ... {'style' 'text' 'string' 'Number of subjects:' } ... {'style' 'edit' 'string' '15' 'tag' 'subjects' } { } }; guigeom = { [1] [1] [1 0.3 0.4] [1 0.3 0.4] }; optiongui = { 'geometry', guigeom, 'uilist' , guispec, ... 'geomvert', [ 1 4 1 1], ... 'helpcom' , 'pophelp(''pop_studyerp'')', ... 'title' , 'Create a new STUDY set -- pop_studyerp()' }; [result, userdat2, strhalt, outstruct] = inputgui(optiongui{:}); STUDY = []; ALLEEG = []; com = ''; if isempty(result), return; end; nSubjects = str2num(outstruct.subjects); nConds = str2num(outstruct.cond); % second GUI, enter the datasets % ------------------------------ guispec = { ... {'style' 'text' 'string' 'Create simple ERP STUDY' 'FontWeight' 'Bold' 'fontsize', 12} ... {} ... {} {'style' 'text' 'string' 'STUDY set name:' } { 'style' 'edit' 'string' '' 'tag' 'study_name' } ... {} }; guigeom = { [1] [1] [0.2 1 3.5] [1] }; % define conditions % ----------------- guigeom{end+1} = []; for icond = 1:nConds if icond == 1, guigeom{end} = [ guigeom{end} 1 0.2]; else guigeom{end} = [ guigeom{end} 0.1 1 0.2]; end; if icond > 1, guispec{end+1} = {}; end; guispec = { guispec{:}, {'style' 'text' 'string' [ 'Condition ' num2str(icond) ' name'] } {} }; end; % edit boxes for conditions % ------------------------- guigeom{end+1} = []; for icond = 1:nConds if icond == 1, guigeom{end} = [ guigeom{end} 1 0.2]; else guigeom{end} = [ guigeom{end} 0.1 1 0.2]; end; if icond > 1, guispec{end+1} = {}; end; guispec = { guispec{:}, {'style' 'edit' 'string' '' 'tag' [ 'cond' num2str(icond) ] } {} }; end; guispec{end+1} = {}; guigeom{end+1} = [1]; % define dataset headers % ---------------------- guigeom{end+1} = []; for icond = 1:nConds if icond == 1, guigeom{end} = [ guigeom{end} 1 0.2]; else guigeom{end} = [ guigeom{end} 0.1 1 0.2]; end; if icond > 1, guispec{end+1} = {}; end; guispec = { guispec{:}, {'style' 'text' 'string' ['Condition ' num2str(icond) ' datasets' ] } {} }; end; % create edit boxes % ----------------- for index = 1:nSubjects guigeom{end+1} = []; for icond = 1:nConds if icond == 1, guigeom{end} = [ guigeom{end} 1 0.2]; else guigeom{end} = [ guigeom{end} 0.1 1 0.2]; end; select_com = ['[inputname, inputpath] = uigetfile2(''*.set;*.SET'', ''Choose dataset to add to STUDY -- pop_study()'');'... 'if inputname ~= 0,' ... ' guiind = findobj(''parent'', gcbf, ''tag'', ''set' int2str(icond) '_' int2str(index) ''');' ... ' set( guiind,''string'', fullfile(inputpath, inputname));' ... 'end; clear inputname inputpath;']; if icond > 1, guispec{end+1} = {}; end; guispec = { guispec{:}, ... {'style' 'edit' 'string' '' 'tag' [ 'set' int2str(icond) '_' int2str(index) ] }, ... {'style' 'pushbutton' 'string' '...' 'Callback' select_com } }; end; end; % last text % --------- textinfo = [ 'When using more than 1 condition, datasets on each line must correspond to the same subject.' ]; guispec = { guispec{:}, {}, {'style' 'text' 'string' textinfo } }; guigeom = { guigeom{:} [1] [1] }; optiongui = { 'geometry', guigeom, ... 'uilist' , guispec, ... 'helpcom' , 'pophelp(''pop_studyerp'')', ... 'title' , 'Create a new STUDY set -- pop_studyerp()' }; [result, userdat2, strhalt, outstruct] = inputgui(optiongui{:}); if isempty(result), return; end; % decode outstruct and build call to std_editset % ---------------------------------------------- options = { 'name' outstruct.study_name 'updatedat' 'off' }; commands = {}; for icond = 1:nConds % check that condition name is defined tagCond = ['cond' int2str(icond) ]; if isempty(outstruct.(tagCond)) outstruct.(tagCond) = [ 'condition ' int2str(icond) ]; end; for index = 1:nSubjects tagSet = [ 'set' int2str(icond) '_' int2str(index) ]; subject = sprintf('S%2.2d', index); if ~isempty(outstruct.(tagSet)) commands = { commands{:}, {'index' nConds*index+icond-1 'load' outstruct.(tagSet) 'subject' subject 'condition' outstruct.(tagCond) } }; end; end; end; options = { options{:}, 'commands', commands }; % call std_editset to create the STUDY % ------------------------------------ com1 = sprintf( '[STUDY ALLEEG] = std_editset( STUDY, ALLEEG, %s );', vararg2str(options) ); [STUDY ALLEEG] = std_editset(STUDY, ALLEEG, options{:}); if exist([ STUDY.design(STUDY.currentdesign).cell(1).filebase '.daterp' ]) textmsg = [ 'WARNING: SOME ERP DATAFILES ALREADY EXIST, OVERWRITE THEM?' 10 ... '(if you have another STUDY using the same datasets, it might overwrite its' 10 ... 'precomputed data files. Instead, use a single STUDY and create multiple designs).' ]; res = questdlg2(textmsg, 'Precomputed datafiles already present on disk', 'No', 'Yes', 'Yes'); if strcmpi(res, 'No') error('User aborded precomputing ERPs'); end; end; % call std_precomp for ERP (channels) % ----------------------------------- com2 = '[STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, ''channels'', ''interpolate'', ''on'', ''recompute'',''on'',''erp'',''on'');'; [STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, 'channels','interp', 'on', 'recompute','on','erp','on'); % call std_erpplot to plot ERPs (channels) % ---------------------------------------- com3 = 'tmpchanlocs = ALLEEG(1).chanlocs; STUDY = std_erpplot(STUDY, ALLEEG, ''channels'', { tmpchanlocs.labels }, ''plotconditions'', ''together'');'; tmpchanlocs = ALLEEG(1).chanlocs; STUDY = std_erpplot(STUDY, ALLEEG, 'channels', { tmpchanlocs.labels }, 'plotconditions', 'together'); pos = get(gcf, 'position'); set(gcf, 'position', [10 pos(2) pos(3)*2 pos(4)*2]); % call the STUDY plotting interface % --------------------------------- disp('Press OK to close plotting interface and save the STUDY'); disp('If you press CANCEL, the whole STUDY will be lost.'); [STUDY com4] = pop_chanplot(STUDY, ALLEEG); com = sprintf('%s\n%s\n%s\n%s', com1, com2, com3, com4);
github
ZijingMao/baselineeegtest-master
std_itcplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_itcplot.m
2,459
utf_8
5d31d5576a555fc6e0ea524887479c2c
% std_itcplot() - Commandline function to plot cluster ITCs. Either displays mean cluster % ITCs, or else all cluster component ITCs, plus the mean cluster ITC, in % one figure per cluster and condition. ITCs can be visualized only if % component ITCs were calculated and saved in the STUDY EEG datasets. % These can be computed during pre-clustering using the gui-based function % pop_preclust(), or via the equivalent commandline functions % eeg_createdata() and eeg_preclust(). Called by pop_clustedit(). % Usage: % >> [STUDY] = std_itcplot(STUDY, ALLEEG, key1, val1, key2, val2); % >> [STUDY itcdata itctimes itcfreqs pgroup pcond pinter] = ... % std_itcplot(STUDY, ALLEEG ...); % Inputs: % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - global EEGLAB vector of EEG structures for the datasets in the STUDY. % Note: ALLEEG for a STUDY set is typically created using load_ALLEEG(). % % Additional help: % Inputs and output of this function are strictly identical to the std_erspplot(). % See the help message of this function for more information. std_itcplot() % plots the ITC while std_erspplot() plots the ERSP. % % See also: std_erspplot(), pop_clustedit(), pop_preclust() % % Authors: Arnaud Delorme, CERCO, August, 2006- % Copyright (C) Arnaud Delorme, [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 [STUDY, allitc, alltimes, allfreqs, pgroup, pcond, pinter] = std_itcplot(STUDY, ALLEEG, varargin) if nargin < 2 help std_itcplot; return; end; [STUDY allitc alltimes allfreqs pgroup pcond pinter ] = std_erspplot(STUDY, ALLEEG, 'datatype', 'itc', varargin{:});
github
ZijingMao/baselineeegtest-master
std_readerpimage.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readerpimage.m
1,501
utf_8
0c21798407bdacd79f5ef9bfe0c4110d
% std_readerpimage() - load ERPimage measures for data channels or % for all components of a specified cluster. % Usage: % >> [STUDY, erpimagedata, times, trials, events] = std_readerpimage(STUDY, ALLEEG, varargin); % % Note: this function is a helper function that contains a call to the % std_readersp function that reads all 2-D data matrices for EEGLAB STUDY. % See the std_readersp help message for more information. % % Author: Arnaud Delorme, CERCO, 2006- % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2004, [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 [STUDY, erspdata, alltimes, allfreqs, events] = std_readerpimage(STUDY, ALLEEG, varargin); [STUDY, erspdata, alltimes, allfreqs, erspbase, events] = std_readersp(STUDY, ALLEEG, 'infotype','erpim', varargin{:});
github
ZijingMao/baselineeegtest-master
std_fileinfo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_fileinfo.m
3,535
utf_8
e6de7fbc6e0b582bd20aabb2d0afafbf
% std_fileinfo() - Check uniform channel distribution accross datasets % % Usage: % >> [struct filepresent] = std_fileinfo(ALLEEG); % Inputs: % ALLEEG - EEGLAB ALLEEG structure % % Outputs: % struct - structure of the same length as the ALLEEG variable % containing all the fields in the datafiles % filepresent - array of 0 and 1 indicating if the file is present for % each dataset % % Authors: Arnaud Delorme, SCCN/UCSD, CERCO/CNRS, 2010- % Copyright (C) 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 [tmpstructout compinds filepresent] = std_fileinfo( ALLEEG, filetype ); firstpass = 1; notequal = 0; compinds = {}; tmpstructout = []; filepresent = zeros(1,length(ALLEEG)); for dat = 1:length(ALLEEG) filename = fullfile(ALLEEG(dat).filepath, [ ALLEEG(dat).filename(1:end-3) filetype ]); thisfilepresent = exist(filename); if thisfilepresent && firstpass == 1 %fprintf('Files of type "%s" detected, checking...', filetype); elseif firstpass == 1 notequal = 1; end; firstpass = 0; filepresent(dat) = thisfilepresent; if filepresent(dat) try warning('off', 'MATLAB:load:variableNotFound'); tmptmpstruct = load( '-mat', filename, 'times', 'freqs', 'parameters', 'labels', 'chanlabels' ); warning('on', 'MATLAB:load:variableNotFound'); catch passall = 0; fprintf(' Error\n'); break; end; % rename chanlabels and store structure if isfield(tmptmpstruct, 'chanlabels') tmptmpstruct.labels = tmptmpstruct.chanlabels; tmptmpstruct = rmfield(tmptmpstruct, 'chanlabels'); end; if filetype(1) ~= 'd' % ICA components allvars = whos('-file', filename); tmpinds = []; for cind = 1:length(allvars) str = allvars(cind).name(5:end); ind_ = find(str == '_'); if ~isempty(ind_), str(ind_:end) = []; end; tmpinds = [ tmpinds str2num(str) ]; end; compinds(dat) = { unique(tmpinds) }; elseif ~isfield(tmptmpstruct, 'labels') allvars = whos('-file', filename); allvarnames = { allvars.name }; tmptmpstruct.labels = allvarnames(strmatch('chan', allvarnames)); end; try, tmpstruct(dat) = tmptmpstruct; catch, passall = 0; break; end; end; end; if exist('tmpstruct') == 1 tmpstructout = tmpstruct; end;
github
ZijingMao/baselineeegtest-master
std_clustread.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_clustread.m
12,094
utf_8
fc68f0aa97d01ad111040de7a802cc1e
% std_clustread() - this function has been replaced by std_readdata() for % consistency. Please use std_readdata() instead. % load one or more requested measures % ['erp'|'spec'|'ersp'|'itc'|'dipole'|'map'] % for all components of a specified cluster. % Calls std_readerp(), std_readersp(), etc. % Usage: % >> clustinfo = std_clustread(STUDY,ALLEEG, cluster, infotype, condition); % Inputs: % STUDY - studyset structure containing some or all files in ALLEEG % ALLEEG - vector of loaded EEG datasets % cluster - cluster number in STUDY % infotype - ['erp'|'spec'|'ersp'|'itc'|'dipole'|'map'] type of stored % cluster information to read. May also be a cell array of % these types, for example: { 'erp' 'map' 'dipole' } % condition - STUDY condition number to read {default: all} % % Output: % clustinfo - structure of specified cluster information: % clustinfo.name % cluster name % clustinfo.clusternum % cluster index % clustinfo.condition % index of the condition asked for % % clustinfo.comp[] % array of component indices % clustinfo.subject{} % cell array of component subject codes % clustinfo.group{} % cell array of component group codes % % clustinfo.erp[] % (ncomps, ntimes) array of component ERPs % clustinfo.erp_times[] % vector of ERP epoch latencies % % clustinfo.spec[] % (ncomps, nfreqs) array of component spectra % clustinfo.spec_freqs[]% vector of spectral frequencies % % clustinfo.ersp[] % (ncomps,ntimes,nfreqs) array of component ERSPs % clustinfo.ersp_times[]% vector of ERSP latencies % clustinfo.ersp_freqs[]% vector of ERSP frequencies % % clustinfo.itc[] % (ncomps,ntimes,nfreqs) array of component ITCs % clustinfo.itc_times[] % vector of ITC latencies % clustinfo.itc_freqs[] % vector of ITC frequencies % % clustinfo.scalp[] % (ncomps,65,65) array of component scalp map grids % clustinfo.xi[] % abscissa values for columns of the scalp maps % clustinfo.yi[] % ordinate values for rows of the scalp maps % % clustinfo.dipole % array of component dipole information structs % % with same format as EEG.dipfit.model % Example: % % To plot the ERPs for all components in cluster 3 of a loaded STUDY % >> clustinfo = std_clustread(STUDY, ALLEEG, 3, 'erp'); % figure; plot(clustinfo.erp_times, clustinfo.erp); % % See also: std_readerp(), std_readspec(), std_readersp(), std_readitc(), std_readtopo() % % Authors: Hilit Serby, Scott Makeig & Arnaud Delorme, SCCN/INC/UCSD, 2005- % % RCS-recorded version number, date, editor and comments function clustinfo = std_clustread(STUDY,ALLEEG, cluster, infotype, condition); help std_clustread; return; if nargin < 4 help std_clustread; return; end if nargin < 5 condition = [1:length(STUDY.condition)]; % default end if ~iscell(infotype), infotype = { infotype }; end; clustinfo = []; clustinfo.name = STUDY.cluster(cluster).name; clustinfo.clusternum = cluster; clustinfo.comps = STUDY.cluster(cluster).comps; clustinfo.condition = condition; ncomps = length(STUDY.cluster(cluster).comps); for k = 1:ncomps %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for each channel | component %%%%%%%%%%%%%% for n = 1:length(condition) %%%%%%%%%%%%%%%%%%%%%%%% for each STUDY condition %%%%%%%%%%%%%% abset = [STUDY.datasetinfo(STUDY.cluster(cluster).sets(condition(n),k)).index]; comp = STUDY.cluster(cluster).comps(k); clustinfo.subject{k} = STUDY.datasetinfo(STUDY.cluster(cluster).sets(condition(n),k)).subject; clustinfo.group{k} = STUDY.datasetinfo(STUDY.cluster(cluster).sets(condition(n),k)).group; for index = 1:length(infotype) %%%%%%%%%%%%%% for each information type %%%%%%%%%%%%%%%% switch infotype{index} case 'erp' [erp, t] = std_readerp(ALLEEG, abset, comp, STUDY.preclust.erpclusttimes); clustinfo.erp_times = t; clustinfo.erp{n,k} = erp; case 'spec' [spec, f] = std_readspec(ALLEEG, abset, comp, STUDY.preclust.specclustfreqs); clustinfo.spec_freqs = f; clustinfo.spec{n,k} = spec; case 'ersp' if n == 1 abset = [STUDY.datasetinfo(STUDY.cluster(cluster).sets(condition,k)).index]; [ersp, logfreqs, timevals] = std_readersp(ALLEEG, abset, comp, ... STUDY.preclust.erspclusttimes, STUDY.preclust.erspclustfreqs); for cc = 1:length(condition) clustinfo.ersp{condition(cc), k} = ersp(:,:,cc); end; clustinfo.ersp_freqs = logfreqs; clustinfo.ersp_times = timevals; end; case 'itc' [itc, logfreqs, timevals] = std_readitc(ALLEEG, abset, comp, ... STUDY.preclust.erspclusttimes, STUDY.preclust.erspclustfreqs ); clustinfo.itc_freqs = logfreqs; clustinfo.itc_times = timevals; clustinfo.itc{n,k} = itc; case 'dipole' if n == 1, clustinfo.dipole(k) = ALLEEG(abset).dipfit.model(comp); end; case { 'map' 'scalp' 'topo' } if n == 1 [grid, yi, xi] = std_readtopo(ALLEEG, abset, comp); if k == 1 clustinfo.xi = xi; clustinfo.yi = yi; end clustinfo.scalp{k} = grid; end; otherwise, error('Unrecognized ''infotype'' entry'); end; % switch end; end; % infotype end % comp % FUTURE HEADER % std_clustread() - return detailed information and (any) requested component % measures for all components of a specified cluster. Restrict % component info to components from specified subjects, groups, % sessions, and/or conditions. Use in scripts handling results % of component clustering. Called by cluster plotting % functions: std_envtopo(), std_erpplot(), std_erspplot(), ... % Usage: % >> clsinfo = std_clustread(STUDY, ALLEEG, cluster); % use defaults % >> clsinfo = std_clustread(STUDY, ALLEEG, cluster, ... % 'keyword1', keyval1, ... % 'keyword2', keyval2, ...); % Inputs: % STUDY - studyset structure containing some or all files in ALLEEG % ALLEEG - vector of loaded EEG datasets including those in STUDY % cluster - cluster number in STUDY to return information for % % Optional keywords - and values: IMPLEMENT !! % 'measure' - ['erp'|'spec'|'ersp'|'itc'|'dipole'|'topo'] stored % cluster measure(s) to read. May also be a cell array of % these, for example: { 'erp' 'map' 'dipole' }. % Else 'all', meaning all measures available. % Else 'cls', meaning all measures clustered on. % Else [], for none {default: 'cls'} % 'condition' - STUDY condition 'name' or {'names'} to read, % Else 'all' {default: 'all'} % 'condnum'' - STUDY condition [number(s)] to read, % Else 0 -> all {default: 0} % 'subject' - STUDY subjects 'name' or {'names'} to read, % Else 'all' {default: 'all'} % 'subjnum' - STUDY subjects [number(s)] to read, % Else 0 -> all {default: 0} % 'group' - STUDY subject group 'name' or {'names'} to read, % Else 'all' {default: 'all'} % 'groupnum' - STUDY subject group [number(s)] to read, % Else 0 -> all {default: 0} % 'session' - STUDY session [number(s)] to read, % Else 0 -> all {default: 0} % % Output: % clsinfo - structure containing information about cluster components in fields: % % .clustername % cluster name % .clusternum % cluster index % % .dataset % {(conditions,components) cell array} component dataset indices % in the input ALLEEG array % .component % [(1,components) int array] component decomposition indices % .subject % {(1,components) cell array} component subject codes % .subjectnum % [(1,components) int array] component subject indices % .group % {(1,components) cell array} component group codes % .groupnum % [(1,components) int array] component group indices % % .condition % {(1,components) cell array} component condition codes % .conditionnum % [(1,components) int array] component condition indices % .session % [(1,components) int array] component session indices % % .erp % {(conditions, components) cell array} % (1, latencies) component ERPs CHECK DIM % .erp_times % [num vector] ERP epoch latencies (s) % % .spec % {(conditions, components) cell array} % (1,frequencies) component spectra CHECK DIM % .spec_freqs % [num vector] spectral frequencies (Hz) % % .ersp % {(conditions, components) cell array} % (freqs,latencies) component ERSPs CHECK DIM % .ersp_times % [num vector] ERSP epoch latencies (s) % .ersp_freqs % [num vector] ERSP frequencies (Hz) % % .itc % {(conditions, components) cell array} % (freqs,latencies) component ITCs CHECK DIM % .itc_times % [num vector] ITC epoch latencies (s) % .itc_freqs % [num vector] ITC frequencies (Hz) % % .topo % {(1,components) cell array} % (65,65) component topo map grids CHECK DIM % .xi % [vector] topo grid abscissa values % .yi % [vector] topo grid ordinate values % % .dipole % [struct array] component dipole information % % structures with same format as "EEG.dipfit.model" % % See >> help dipfit CHECK HELP % Example: % % To plot the ERPs for all Cluster-3 components in a one-condition STUDY % % % clsinfo3 = std_clustread(STUDY, ALLEEG, 3, 'measure', 'erp'); % assume 1 condition % times = clsinfo3.erp_times; figure; plot(times, clsinfo3.erp'); % % % % To plot ERPs for only those Cluster-3 components from subjects in group 'female' % % % feminfo3 = std_clustread(STUDY, ALLEEG, 3, 'measure', 'erp', 'group', 'female'); % figure; plot(times, feminfo3.erp'); % % % % Alternatively, to extract 'female' subject components from clsinfo3 above % % % femidx = find(strcmp({clsinfo3.group},'female')); % figure; plot(times, clustinfo.erp(femidx,:)'); CHECK EXAMPLE % % Authors: Hilit Serby, Scott Makeig, Toby Fernsler & Arnaud Delorme, SCCN/INC/UCSD, 2005-
github
ZijingMao/baselineeegtest-master
std_erpimageplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_erpimageplot.m
7,319
utf_8
5073f5d9c0bdd1e64fab8c87596d6553
% std_erpimageplot() - Commandline function to plot cluster ERPimage or channel erpimage. % % Usage: % >> [STUDY] = std_erpimageplot(STUDY, ALLEEG, key1, val1, key2, val2); % >> [STUDY data times freqs pgroup pcond pinter] = ... % std_erpimageplot(STUDY, ALLEEG ...); % Inputs: % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - global EEGLAB vector of EEG structures for the datasets in the STUDY. % Note: ALLEEG for a STUDY set is typically created using load_ALLEEG(). % % Additional help: % Inputs and output of this function are strictly identical to the std_erspplot(). % See the help message of this function for more information. % % See also: std_erspplot() % % Authors: Arnaud Delorme, UCSD/CERCO, August, 2011- % Copyright (C) Arnaud Delorme, [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 [STUDY, allitc, alltimes, allfreqs, pgroup, pcond, pinter, events] = std_erpimageplot(STUDY, ALLEEG, varargin) if nargin < 2 help std_erpimageplot; return; end; events = []; STUDY = pop_erpimparams(STUDY, 'default'); if strcmpi(STUDY.etc.erpimparams.concatenate, 'off') % use std_erspplot for stats when concatenate is off [STUDY allitc alltimes allfreqs pgroup pcond pinter events] = std_erspplot(STUDY, ALLEEG, 'datatype', 'erpim', varargin{:}); else params = STUDY.etc.erpimparams; [ opt moreparams ] = finputcheck( varargin, { ... 'design' 'integer' [] STUDY.currentdesign; 'topotime' 'real' [] params.topotime; 'topotrial' 'real' [] params.topotrial; 'timerange' 'real' [] params.timerange; 'trialrange' 'real' [] params.trialrange; 'colorlimits' 'real' [] params.colorlimits; % ERPimage 'statistics' 'string' [] params.statistics; 'groupstats' 'string' [] params.groupstats; 'condstats' 'string' [] params.condstats; 'threshold' 'real' [] params.threshold; 'naccu' 'integer' [] params.naccu; 'mcorrect' 'string' [] params.mcorrect; 'erpimageopt' 'cell' [] params.erpimageopt; 'concatenate' 'string' { 'on','off' } params.concatenate; 'channels' 'cell' [] {}; 'clusters' 'integer' [] []; 'comps' {'integer','string'} [] []; % for backward compatibility 'plotsubjects' 'string' { 'on','off' } 'off'; 'plotmode' 'string' { 'normal','condensed','none' } 'normal'; 'subject' 'string' [] '' }, 'std_erpimageplot', 'ignore'); if ~isempty(opt.topotime) && ~isempty(opt.topotrial) error('Cannot plot topography when ERP-image is in trial concatenation mode'); end; if ~isempty(opt.trialrange) error('Cannot select trial range when ERP-image is in trial concatenation mode'); end; if strcmpi(opt.groupstats, 'on') || strcmpi(opt.condstats, 'on') disp('Warning: cannot perform statistics when ERP-image is in trial concatenation mode'); end; % options if ~isempty(opt.colorlimits), options = { 'caxis' opt.colorlimits opt.erpimageopt{:} }; else options = { 'cbar' 'on' opt.erpimageopt{:} }; end; if ~isempty(opt.channels) [STUDY allerpimage alltimes alltrials tmp events] = std_readersp(STUDY, ALLEEG, 'channels', opt.channels, 'infotype', 'erpim', 'subject', opt.subject, ... 'concatenate', 'on', 'timerange', opt.timerange, 'design', opt.design); % get figure title % ---------------- locs = eeg_mergelocs(ALLEEG.chanlocs); locs = locs(std_chaninds(STUDY, opt.channels)); allconditions = STUDY.design(opt.design).variable(1).value; allgroups = STUDY.design(opt.design).variable(2).value; alltitles = std_figtitle('condnames', allconditions, 'cond2names', allgroups, 'chanlabels', { locs.labels }, ... 'subject', opt.subject, 'valsunit', 'ms', 'datatype', 'ERPIM'); figure; for iCond = 1:length(allconditions) for iGroup = 1:length(allgroups) tmpevents = events{iCond, iGroup}; if isempty(tmpevents), tmpevents = zeros(1, size(allerpimage{iCond, iGroup},2)); end; subplot(length(allconditions), length(allgroups), (iCond-1)*length(allgroups) + iGroup); % use color scale for last plot if ~isempty(opt.colorlimits) && iCond == length(allconditions) && iGroup == length(allgroups) options = { options{:} 'cbar' 'on' }; end; erpimage(allerpimage{iCond, iGroup}, tmpevents, alltimes, alltitles{iCond, iGroup}, params.smoothing, params.nlines, options{:}); end; end; else for cInd = 1:length(opt.clusters) [STUDY allerpimage alltimes alltrials tmp events] = std_readersp(STUDY, ALLEEG, 'clusters', opt.clusters(cInd), 'infotype', 'erpim', 'subject', opt.subject, ... 'concatenate', 'on', 'timerange', opt.timerange, 'design', opt.design); % get figure title % ---------------- locs = eeg_mergelocs(ALLEEG.chanlocs); locs = locs(std_chaninds(STUDY, opt.channels)); allconditions = STUDY.design(opt.design).variable(1).value; allgroups = STUDY.design(opt.design).variable(2).value; alltitles = std_figtitle('condnames', allconditions, 'cond2names', allgroups, 'clustname', STUDY.cluster(opt.clusters(cInd)).name, ... 'subject', opt.subject, 'valsunit', 'ms', 'datatype', 'ERPIM'); figure; for iCond = 1:length(allconditions) for iGroup = 1:length(allgroups) tmpevents = events{iCond, iGroup}; if isempty(tmpevents), tmpevents = zeros(1, size(allerpimage{iCond, iGroup},2)); end; subplot(length(allconditions), length(allgroups), (iCond-1)*length(allgroups) + iGroup); % use color scale for last plot if ~isempty(opt.colorlimits) && iCond == length(allconditions) && iGroup == length(allgroups) options = { options{:} 'cbar' 'on' }; end; erpimage(allerpimage{iCond, iGroup}, tmpevents, alltimes, alltitles{iCond, iGroup}, params.smoothing, params.nlines, options{:}); end; end; end; end; end;
github
ZijingMao/baselineeegtest-master
std_checkset.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_checkset.m
14,296
utf_8
71289d38f5dce5d1d46b11c920eeb2bd
% std_checkset() - check STUDY set consistency % % Usage: >> [STUDY, ALLEEG] = std_checkset(STUDY, ALLEEG); % % Input: % STUDY - EEGLAB STUDY set % ALLEEG - vector of EEG datasets included in the STUDY structure % % Output: % STUDY - a new STUDY set containing some or all of the datasets in ALLEEG, % plus additional information from the optional inputs above. % ALLEEG - an EEGLAB vector of EEG sets included in the STUDY structure % % Authors: Arnaud Delorme & Hilit Serby, SCCN, INC, UCSD, November 2005 % Copyright (C) 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 [STUDY, ALLEEG, command] = std_checkset(STUDY, ALLEEG, option); if nargin < 2 help std_checkset; return; end; command = ''; if isempty(STUDY), return; end; studywasempty = 0; modif = 0; if ~isfield(STUDY, 'name'), STUDY.name = ''; modif = 1; end; if ~isfield(STUDY, 'task'), STUDY.task = ''; modif = 1; end; if ~isfield(STUDY, 'notes'), STUDY.notes = ''; modif = 1; end; if ~isfield(STUDY, 'filename'), STUDY.filename = ''; modif = 1; end; if ~isfield(STUDY, 'filepath'), STUDY.filepath = ''; modif = 1; end; if ~isfield(STUDY, 'history'), STUDY.history = ''; modif = 1; end; if ~isfield(STUDY, 'subject'), STUDY.subject = {}; modif = 1; end; if ~isfield(STUDY, 'group'), STUDY.group = {}; modif = 1; end; if ~isfield(STUDY, 'session'), STUDY.session = {}; modif = 1; end; if ~isfield(STUDY, 'condition'), STUDY.condition = {}; modif = 1; end; if ~isfield(STUDY, 'setind'), STUDY.setind = {}; modif = 1; end; if ~isfield(STUDY, 'etc'), STUDY.etc = []; modif = 1; end; if ~isfield(STUDY, 'etc.warnmemory'), STUDY.etc.warnmemory = 1; modif = 1; end; if ~isfield(STUDY, 'preclust'), STUDY.preclust = []; modif = 1; end; if ~isfield(STUDY, 'datasetinfo'), STUDY.datasetinfo = []; modif = 1; end; if ~isfield(STUDY.etc, 'version'), STUDY.etc.version = []; modif = 1; end; if ~isfield(STUDY.preclust, 'erpclusttimes' ), STUDY.preclust.erpclusttimes = []; modif = 1; end; if ~isfield(STUDY.preclust, 'specclustfreqs' ), STUDY.preclust.specclustfreqs = []; modif = 1; end; if ~isfield(STUDY.preclust, 'erspclustfreqs' ), STUDY.preclust.erspclustfreqs = []; modif = 1; end; if ~isfield(STUDY.preclust, 'erspclusttimes' ), STUDY.preclust.erspclusttimes = []; modif = 1; end; if ~isfield(STUDY.datasetinfo, 'comps') & ~isempty(STUDY.datasetinfo), STUDY.datasetinfo(1).comps = []; modif = 1; end; if ~isfield(STUDY.datasetinfo, 'index') & ~isempty(STUDY.datasetinfo), STUDY.datasetinfo(1).index = []; modif = 1; end; % all summary fields % ------------------ try, subject = unique_bc({ STUDY.datasetinfo.subject }); catch, subject = ''; disp('Important warning: some datasets do not have subject codes; some functions may crash!'); end; try, group = unique_bc({ STUDY.datasetinfo.group }); catch, group = {}; % disp('Important warning: some datasets do not have group codes; some functions may crash!'); end; try, condition = unique_bc({ STUDY.datasetinfo.condition }); catch, condition = {}; disp('Important warning: some datasets do not have condition codes; some functions may crash!'); end; try, session = unique_bc([STUDY.datasetinfo.session]); catch, session = ''; % disp('Important warning: some datasets do not have session numbers; some functions may crash!'); end; if ~isequal(STUDY.subject, subject ), STUDY.subject = subject; modif = 1; end; if ~isequal(STUDY.group, group ), STUDY.group = group; modif = 1; end; if ~isequal(STUDY.condition, condition), STUDY.condition = condition; modif = 1; end; if ~isequal(STUDY.session, session ), STUDY.session = session; modif = 1; end; % check dataset info consistency % ------------------------------ for k = 1:length(STUDY.datasetinfo) if ~strcmpi(STUDY.datasetinfo(k).filename, ALLEEG(k).filename) STUDY.datasetinfo(k).filename = ALLEEG(k).filename; modif = 1; fprintf('Warning: file name has changed for dataset %d and the study has been updated\n', k); fprintf(' to discard this change in the study, reload it from disk\n'); end; end; % recompute setind array (setind is deprecated but we keep it anyway) % ------------------------------------------------------------------- setind = []; sameica = std_findsameica(ALLEEG); for index = 1:length(sameica) setind(length(sameica{index}):-1:1,index) = sameica{index}'; end; setind(find(setind == 0)) = NaN; if any(isnan(setind)) warndlg('Warning: non-uniform set of dataset, some function might not work'); end if ~isequal(setind, STUDY.setind), STUDY.setind = setind; modif = 1; end; % check that dipfit is present in all datasets % -------------------------------------------- for cc = 1:length(sameica) idat = []; for tmpi = 1:length(sameica{cc}) if isfield(ALLEEG(sameica{cc}(tmpi)).dipfit, 'model') idat = sameica{cc}(tmpi); end; end; if ~isempty(idat) for tmpi = 1:length(sameica{cc}) if ~isfield(ALLEEG(sameica{cc}(tmpi)).dipfit, 'model') ALLEEG(sameica{cc}(tmpi)).dipfit = ALLEEG(idat).dipfit; ALLEEG(sameica{cc}(tmpi)).saved = 'no'; fprintf('Warning: no ICA dipoles for dataset %d, using dipoles from dataset %d (same ICA)\n', sameica{cc}(tmpi), idat); end; end; end; end; % put in fake channels if channel labels are missing % -------------------------------------------------- chanlabels = { ALLEEG.chanlocs }; if any(cellfun(@isempty, chanlabels)) if any(~cellfun(@isempty, chanlabels)) disp('********************************************************************'); disp(' IMPORTANT WARNING: SOME DATASETS DO NOT HAVE CHANNEL LABELS AND '); disp(' SOME OTHERs HAVE CHANNEL LABELS. GENERATING CHANNEL LABELS FOR '); disp(' THE FORMER DATASETS (THIS SHOULD PROBABLY BE FIXED BY THE USER).'); disp('********************************************************************'); end; disp('Generating channel labels for all datasets...'); for currentind = 1:length(ALLEEG) for ind = 1:ALLEEG(currentind).nbchan ALLEEG(currentind).chanlocs(ind).labels = int2str(ind); end; end; ALLEEG(currentind).saved = 'no'; end; if length( unique( [ ALLEEG.srate ] )) > 1 disp('********************************************************************'); disp(' IMPORTANT WARNING: SOME DATASETS DO NOT HAVE THE SAME SAMPLING '); disp(' RATE AND THIS WILL MAKE MOST OF THE STUDY FUNCTIONS CRASH. THIS'); disp(' SHOULD PROBABLY BE FIXED BY THE USER.'); disp('********************************************************************'); end; % check cluster array % ------------------- rebuild_design = 0; if ~isfield(STUDY, 'cluster'), STUDY.cluster = []; modif = 1; end; if ~isfield(STUDY, 'changrp'), STUDY.changrp = []; modif = 1; end; if isempty(STUDY.changrp) && isempty(STUDY.cluster) rebuild_design = 1; end; if isfield(STUDY.cluster, 'sets'), if max(STUDY.cluster(1).sets(:)) > length(STUDY.datasetinfo) disp('Warning: Some datasets had been removed from the STUDY, clusters have been reinitialized'); STUDY.cluster = []; end; end; if ~studywasempty if isempty(STUDY.cluster) modif = 1; [STUDY] = std_createclust(STUDY, ALLEEG, 'parentcluster', 'on'); end; if length(STUDY.cluster(1).child) == length(STUDY.cluster)-1 && length(STUDY.cluster) > 1 newchild = { STUDY.cluster(2:end).name }; if ~isequal(STUDY.cluster(1).child, newchild) STUDY.cluster(1).child = newchild; end; end; end; % create STUDY design if it is not present % ---------------------------------------- if ~studywasempty if isfield(STUDY.datasetinfo, 'trialinfo') alltrialinfo = { STUDY.datasetinfo.trialinfo }; if any(cellfun(@isempty, alltrialinfo)) && any(~cellfun(@isempty, alltrialinfo)) disp('Rebuilding trial information structure for STUDY'); STUDY = std_maketrialinfo(STUDY, ALLEEG); % some dataset do not have trialinfo and % some other have it, remake it for everybody end; end; if ~isfield(STUDY, 'design') || isempty(STUDY.design) || ~isfield(STUDY.design, 'name') STUDY = std_maketrialinfo(STUDY, ALLEEG); STUDY = std_makedesign(STUDY, ALLEEG); STUDY = std_selectdesign(STUDY, ALLEEG,1); rebuild_design = 0; else if isfield(STUDY.design, 'indvar1') STUDY = std_convertdesign(STUDY, ALLEEG); end; % convert combined independent variable values % between dash to cell array of strings % ------------------------------------- for inddes = 1:length(STUDY.design) for indvar = 1:length(STUDY.design(inddes).variable) for indval = 1:length(STUDY.design(inddes).variable(indvar).value) STUDY.design(inddes).variable(indvar).value{indval} = convertindvarval(STUDY.design(inddes).variable(indvar).value{indval}); end; end; for indcell = 1:length(STUDY.design(inddes).cell) for indval = 1:length(STUDY.design(inddes).cell(indcell).value) STUDY.design(inddes).cell(indcell).value{indval} = convertindvarval(STUDY.design(inddes).cell(indcell).value{indval}); end; end; for indinclude = 1:length(STUDY.design(inddes).include) if iscell(STUDY.design(inddes).include{indinclude}) for indval = 1:length(STUDY.design(inddes).include{indinclude}) STUDY.design(inddes).include{indinclude}{indval} = convertindvarval(STUDY.design(inddes).include{indinclude}{indval}); end; end; end; % check for duplicate entries in filebase % --------------------------------------- if length( { STUDY.design(inddes).cell.filebase } ) > length(unique({ STUDY.design(inddes).cell.filebase })) if ~isempty(findstr('design_', STUDY.design(inddes).cell(1).filebase)) error('There is a problem with your STUDY, contact EEGLAB support'); else fprintf('Duplicate entry detected in Design %d, reinitializing design\n', inddes); [STUDY com] = std_makedesign(STUDY, ALLEEG, inddes, STUDY.design(inddes), 'defaultdesign', 'forceoff'); end end; end; end; if rebuild_design % in case datasets have been added or removed STUDY = std_rebuilddesign(STUDY, ALLEEG); end; % scan design to fix old paring format % ------------------------------------ for design = 1:length(STUDY.design) for var = 1:length(STUDY.design(design).variable) if isstr(STUDY.design(design).variable(1).pairing) if strcmpi(STUDY.design(design).variable(1).pairing, 'paired') STUDY.design(design).variable(1).pairing = 'on'; elseif strcmpi(STUDY.design(design).variable(1).pairing, 'unpaired') STUDY.design(design).variable(1).pairing = 'off'; end; end; if isstr(STUDY.design(design).variable(2).pairing) if strcmpi(STUDY.design(design).variable(2).pairing, 'paired') STUDY.design(design).variable(2).pairing = 'on'; elseif strcmpi(STUDY.design(design).variable(2).pairing, 'unpaired') STUDY.design(design).variable(2).pairing = 'off'; end; end; end; end; % add filepath field if absent for ind = 1:length(STUDY.design) if ~isfield(STUDY.design, 'filepath') || (isnumeric(STUDY.design(ind).filepath) && isempty(STUDY.design(ind).filepath)) STUDY.design(ind).filepath = ''; STUDY.saved = 'no'; modif = 1; end; end; % check that ICA is present and if it is update STUDY.datasetinfo allcompsSTUDY = { STUDY.datasetinfo.comps }; allcompsALLEEG = { ALLEEG.icaweights }; if all(cellfun(@isempty, allcompsSTUDY)) && ~all(cellfun(@isempty, allcompsALLEEG)) for index = 1:length(STUDY.datasetinfo) STUDY.datasetinfo(index).comps = [1:size(ALLEEG(index).icaweights,1)]; end; end; % make channel groups % ------------------- if ~isfield(STUDY, 'changrp') || isempty(STUDY.changrp) STUDY = std_changroup(STUDY, ALLEEG); modif = 1; end; end; % determine if there has been any change % -------------------------------------- if modif; STUDY.saved = 'no'; command = '[STUDY ALLEEG] = std_checkset(STUDY, ALLEEG);'; addToHistory = true; % check duplicate if length(STUDY.history) >= length(command) && strcmpi(STUDY.history(end-length(command)+1:end), command) addToHistory = false; end; if addToHistory STUDY.history = sprintf('%s\n%s', STUDY.history, command); end; end; % convert combined independent variables % -------------------------------------- function val = convertindvarval(val); if isstr(val) inddash = findstr(' - ', val); if isempty(inddash), return; end; inddash = [ -2 inddash length(val)+1]; for ind = 1:length(inddash)-1 newval{ind} = val(inddash(ind)+3:inddash(ind+1)-1); end; val = newval; end;
github
ZijingMao/baselineeegtest-master
std_checkfiles.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_checkfiles.m
7,593
utf_8
6ac22d4c5d62c3eaf4f9a4888c9fa0a9
% std_checkfiles() - Check all STUDY files consistency % % Usage: % >> boolval = std_checkfiles(STUDY, ALLEEG); % Inputs: % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - All EEGLAB datasets % % Outputs: % boolval - [0|1] 1 if uniform % % Authors: Arnaud Delorme, CERCO, 2010- % Copyright (C) Arnaud Delorme, CERCO % % 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 [boolval npersubj] = std_checkfiles(STUDY, ALLEEG); if nargin < 2 help std_checkfiles; return; end; return; filetypes = { 'daterp' 'datspec' 'datersp' 'datitc' 'dattimef' ... 'icaerp' 'icaspec' 'icaersp' 'icaitc' 'icatopo' }; % set channel interpolation mode % ------------------------------ uniformchannels = std_uniformsetinds( STUDY ); disp('---------------------------------------------'); disp('Checking data files integrity and consistency'); passall = 1; for index = 1:length(filetypes) % scan datasets % ------------- [ tmpstruct compinds filepresent ] = std_fileinfo(ALLEEG, filetypes{index}); if ~isempty(tmpstruct) fprintf('Files of type "%s" detected, checking...', filetypes{index}); end; % check if the structures are equal % --------------------------------- notequal = any(~filepresent); if ~isempty(tmpstruct) if any(filepresent == 0) fprintf(' Error, some files inconsistent or missing\n'); notequal = 1; passall = 0; else firstpass = 1; fields = fieldnames(tmpstruct); for f_ind = 1:length(fields) firstval = getfield(tmpstruct, {1}, fields{f_ind}); for dat = 2:length(tmpstruct) tmpval = getfield(tmpstruct, {dat}, fields{f_ind}); if ~isequal(firstval, tmpval) % check for NaNs if iscell(firstval) && iscell(tmpval) for cind = 1:length(firstval) if isreal(firstval{cind}) && ~isempty(firstval{cind}) && isnan(firstval{cind}(1)) firstval{cind} = 'NaN'; end; end; for cind = 1:length(tmpval) if isreal(tmpval{cind}) && ~isempty(tmpval{cind}) && isnan(tmpval{cind}(1)) tmpval{cind} = 'NaN'; end; end; end; if ~isequal(firstval, tmpval) if ~strcmpi(fields{f_ind}, 'labels') || strcmpi(uniformchannels, 'on') if firstpass == 1, fprintf('\n'); firstpass = 0; end; fprintf(' Error, difference accross data files for field "%s"\n', fields{f_ind}); notequal = 1; passall = 0; break; end; end; end; end; end; end; end; % check the consistency of changrp and cluster with saved information % ------------------------------------------------------------------- if isempty(tmpstruct), notequal = 1; end; if filetypes{index}(1) == 'd' && notequal == 0 % scan all channel labels % ----------------------- if isfield(tmpstruct(1), 'labels') for cind = 1:length(STUDY.changrp) if notequal == 0 for inddat = 1:length(ALLEEG) tmpind = cellfun(@(x)(find(x == inddat)), STUDY.changrp(cind).setinds(:), 'uniformoutput', false); indnonempty = find(~cellfun(@isempty, tmpind(:))); if ~isempty(indnonempty) tmpchan = STUDY.changrp(cind).allinds{indnonempty}(tmpind{indnonempty}); % channel index for dataset inddat tmpchan2 = strmatch(STUDY.changrp(cind).name, tmpstruct(inddat).labels, 'exact'); % channel index in file if ~isempty(tmpchan2) || ~strcmpi(filetypes{index}, 'datspec') % the last statement is because channel labels did not use to be saved in spec files if ~isequal(tmpchan2, tmpchan) fprintf('\nError: channel index in STUDY.changrp(%d) for dataset %d is "%d" but "%d" in data files\n', cind, inddat, tmpchan, tmpchan2); notequal = 1; break; end; end; end; end; end; end; end; elseif notequal == 0 && ~isempty(STUDY.cluster) % components % check that the cell structures are present % ------------------------------------------ if ~isfield(STUDY.cluster, 'setinds') STUDY.cluster(1).setinds = []; STUDY.cluster(1).allinds = []; end; for cind = 1:length(STUDY.cluster) if isempty(STUDY.cluster(cind).setinds) STUDY.cluster(cind) = std_setcomps2cell(STUDY, cind); end; end; for cind = 1:length(STUDY.cluster) if notequal == 0 for inddat = 1:length(ALLEEG) tmpind = cellfun(@(x)(find(x == inddat)), STUDY.cluster(cind).setinds(:), 'uniformoutput', false); indnonempty = find(~cellfun(@isempty, tmpind(:))); tmpcomp = []; for jind = 1:length(indnonempty) tmpcomp = [ tmpcomp STUDY.cluster(cind).allinds{indnonempty(jind)}(tmpind{indnonempty(jind)}) ]; end; if ~isempty(setdiff(tmpcomp, compinds{inddat})) if ~(isempty(compinds{inddat}) && strcmpi(filetypes{index}, 'icatopo')) fprintf('\nError: some components in clusters %d are absent from .%s files\n', cind, filetypes{index}); notequal = 1; passall = 0; break; end; end; end; end; end; end; if notequal == 0, fprintf(' Pass\n'); end; end; if ~passall disp('**** Recompute any measure above not receiving a "Pass" by') disp('**** calling menu items "STUDY > Precompute Channel/Component measures" '); disp('**** and by selecting the "Recompute even if present on disk" checkbox'); end; disp('Checking completed.');
github
ZijingMao/baselineeegtest-master
std_specgram.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_specgram.m
14,400
utf_8
c47a0f3d1446e9f4aa6ccb9446dc533a
% std_specgram() - Returns the ICA component or channel spectrogram for a dataset. % Saves the spectra in a file. % Usage: % >> [spec freqs] = std_specgram(EEG, 'key', 'val', ...); % % Inputs: % EEG - a loaded epoched EEG dataset structure. % % Optional inputs: % 'components' - [numeric vector] components of the EEG structure for which % activation spectogram will be computed. Note that because % computation of component spectra is relatively fast, all % components spectra are computed and saved. Only selected % component are returned by the function to Matlab % {default|[] -> all} % 'channels' - [cell array] channels of the EEG structure for which % activation spectogram will be computed. Note that because % computation of spectrum is relatively fast, all channels % spectrum are computed and saved. Only selected channels % are returned by the function to Matlab % {default|[] -> none} % 'recompute' - ['on'|'off'] force recomputing ERP file even if it is % already on disk. % % Other optional spectral parameters: % All optional parameters to the newtimef function may be provided to this function % as well. % % Outputs: % spec - the mean spectra (in dB) of the requested ICA components in the selected % frequency range (with the mean of each spectrum removed). % freqs - a vector of frequencies at which the spectra have been computed. % % Files output or overwritten for ICA: % [dataset_filename].icaspecgram, % Files output or overwritten for data: % [dataset_filename].datspecgram, % % See also spectopo(), std_erp(), std_ersp(), std_map(), std_preclust() % % Authors: Arnaud Delorme, SCCN, INC, UCSD, January, 2005 % Defunct: 0 -> if frequency range is different from saved spectra, ask via a % pop-up window whether to keep existing spectra or to overwrite them. % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2004, [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 % eeg_specgram() - Compute spectrogramme taking into account boundaries in % the data. % Usage: % >> EEGOUT = eeg_specgram( EEG, typeplot, num, 'key', 'val'); % % Inputs: % EEG - EEG dataset structure % typeplot - type of processinopt. 1 process the raw % data and 0 the ICA components % num - component or channel number % % Optional inputs: % 'winsize' - [integer] window size in points % 'overlap' - [integer] window overlap in points (default: 0) % 'movav' - [real] moving average % % Author: Arnaud Delorme, CERCO, CNRS, 2008- % Copyright (C) 2001 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 [erspinterp t f ] = eeg_specgram(EEG, varargin); if nargin < 1 help std_specgram; return; end; [opt moreopts] = finputcheck(varargin, { 'components' 'integer' [] []; 'channels' { 'cell','integer' } { [] [] } {} 'recompute' 'string' { 'on','off' } 'off'; 'winsize' 'integer' [] 3; % 3 seconds 'rmcomps' 'integer' [] []; 'interp' 'struct' { } struct([]); 'overlap' 'integer' [] 0; 'plot' 'string' { 'off','on' } 'off'; 'freqrange' 'real' [] []; 'timerange' 'real' [] []; 'filter' 'real' [] []}, ... % 11 points 'eeg_specgram', 'ignore'); if isstr(opt), error(opt); end; if isfield(EEG,'icaweights') numc = size(EEG.icaweights,1); else error('EEG.icaweights not found'); end if isempty(opt.components) opt.components = 1:numc; end %opt.winsize = 2^ceil(log2(opt.winsize*EEG.srate)); opt.winsize = opt.winsize*EEG.srate; % filename % -------- if ~isempty(opt.channels) filename = fullfile( EEG.filepath,[ EEG.filename(1:end-3) 'datspecgram']); prefix = 'chan'; opt.indices = opt.channels; if iscell(opt.channels) tmpchanlocs = EEG(1).chanlocs; for index = 1:length(opt.channels) chanind = strmatch( lower(opt.channels{index}), lower({ tmpchanlocs.labels }), 'exact'); if isempty(chanind), error('Channel group not found'); end; chaninds(index) = chanind; end; opt.indices = chaninds; opt.channels = chaninds; end; else filename = fullfile( EEG.filepath,[ EEG.filename(1:end-3) 'icaspecgram']); prefix = 'comp'; opt.indices = opt.components; end; % SPEC information found in datasets % ---------------------------------- if exist(filename) & strcmpi(opt.recompute, 'off') if strcmpi(prefix, 'comp') [erspinterp, t, f] = std_readspecgram(EEG, 1, opt.components, opt.freqrange); else [erspinterp, t, f] = std_readspecgram(EEG, 1, -opt.channels, opt.freqrange); end; return; end % No SPEC information found % ------------------------ options = {}; if strcmpi(prefix, 'comp') X = eeg_getdatact(EEG, 'component', [1:size(EEG.icaweights,1)]); else EEG.data = eeg_getdatact(EEG, 'channel', [1:EEG.nbchan], 'rmcomps', opt.rmcomps); if ~isempty(opt.rmcomps), options = { options{:} 'rmcomps' opt.rmcomps }; end; if ~isempty(opt.interp), EEG = eeg_interp(EEG, opt.interp, 'spherical'); end; X = EEG.data; end; % get the array of original point latency % --------------------------------------- urpnts = eeg_urpnts(EEG); urarray = eeg_makeurarray(EEG, urpnts); % contain the indices of the urpoint in the EEG data % urarray(1000) = 1000, urarray(2300) = 1600 if part removed in the data urwincenter = opt.winsize/2+1:opt.winsize-opt.overlap:urpnts-opt.winsize/2; wintag = ones(1, length(urwincenter)); if EEG.trials == 1 for i = 1:length(urwincenter) win = urwincenter(i)+[-opt.winsize/2+1:opt.winsize/2]; if ~all(urarray(win)) wintag(i) = 0; %fprintf('Missing data window: %3.1f-%3.1f s\n', (win(1)-1)/EEG.srate, (win(end)-1)/EEG.srate); end; end; else error('eeg_specgram can only be run on continuous data'); end; % compute spectrum 2 solutions % 1- use newtimef, have to set the exact times and window % 2- redo the FFT myself % ---------------------- wincenter = urwincenter(find(wintag)); % remove bad windows wincenter = urarray(wincenter); % latency in current dataset wincenter = 1000*(wincenter-1)/EEG.srate; % convert to ms freqs = linspace(0.1, 50, 100); options = { 0 'winsize', opt.winsize, 'baseline', [0 Inf], 'timesout', wincenter, ... 'plotersp', 'off', 'plotitc', 'off', 'freqs', freqs }; %freqs = exp(linspace(log(EEG.srate/opt.winsize*4), log(50), 100)); %cycles = linspace(3,8,100); %options = { [3 0.8] 'winsize', opt.winsize, 'baseline', [0 Inf], 'timesout', wincenter, ... % 'freqs' freqs 'cycles' cycles 'plotersp', 'off', 'plotitc', 'off' }; for ic = 1:length(opt.indices) [ersp(:,:,ic) itc powebase t f] = newtimef(X(opt.indices(ic), :), EEG.pnts, [EEG.xmin EEG.xmax]*1000, EEG.srate, options{:}, moreopts{:}); end; % interpolate and smooth in time % ------------------------------ disp('Now interpolating...'); wininterp = find(wintag == 0); erspinterp = zeros(size(ersp,1), length(urwincenter), size(ersp,3)); erspinterp(:,find(wintag),:) = ersp; for s = 1:size(ersp,3) for i=1:length(wininterp) first1right = find(wintag(wininterp(i):end)); first1left = find(wintag(wininterp(i):-1:1)); if isempty(first1right) erspinterp(:,wininterp(i),s) = erspinterp(:,wininterp(i)+1-first1left(1),s); elseif isempty(first1left) erspinterp(:,wininterp(i),s) = erspinterp(:,wininterp(i)-1+first1right(1),s); else erspinterp(:,wininterp(i),s) =(erspinterp(:,wininterp(i)-1+first1right(1),s) + erspinterp(:,wininterp(i)+1-first1left(1),s))/2; end; end; end; %erspinterp = vectdata(ersp, urwincenter(find(wintag))/EEG.srate, 'timesout', urwincenter/EEG.srate); % smooth in time with a simple convolution % ---------------------------------------- if ~isempty(opt.filter) filterlen = opt.filter(1); filterstd = opt.filter(2); incr = 2*filterstd/(filterlen-1); %gaussian filter filter = exp(-(-filterstd:incr:filterstd).^2); erspinterp = convn(erspinterp, filter/sum(filter), 'same'); %erspinterp = conv2(erspinterp, filter/sum(filter)); %erspinterp(:, [1:(filterlen-1)/2 end-(filterlen-1)/2+1:end]) = []; end; % plot result % ----------- t = (urwincenter-1)/EEG.srate; if strcmpi(opt.plot, 'on') figure; imagesc(t, log(f), erspinterp); ft = str2num(get(gca,'yticklabel')); ft = exp(1).^ft; ft = unique_bc(round(ft)); ftick = get(gca,'ytick'); ftick = exp(1).^ftick; ftick = unique_bc(round(ftick)); ftick = log(ftick); set(gca,'ytick',ftick); set(gca,'yticklabel', num2str(ft)); xlabel('Time (h)'); ylabel('Frequency (Hz)'); set(gca, 'ydir', 'normal'); end; % Save SPECs in file (all components or channels) % ---------------------------------- options = { 'winsize' opt.winsize 'overlap' opt.overlap moreopts{:} }; if strcmpi(prefix, 'comp') savetofile( filename, t, f, erspinterp, 'comp', opt.indices, options, [], opt.interp); [erspinterp, t, f] = std_readspecgram(EEG, 1, opt.components, opt.timerange, opt.freqrange); else tmpchanlocs = EEG(1).chanlocs; savetofile( filename, t, f, erspinterp, 'chan', opt.indices, options, { tmpchanlocs.labels }, opt.interp); [erspinterp, t, f] = std_readspecgram(EEG, 1, -opt.channels, opt.timerange, opt.freqrange); end; return; % recompute the original data length in points % -------------------------------------------- function urlat = eeg_makeurarray(EEG, urpnts); if isempty(EEG.event) | ~isfield(EEG.event, 'duration') urlat = 1:EEG.pnts; return; end; % get boundary events latency and duration % ---------------------------------------- tmpevent = EEG.event; bounds = strmatch('boundary', { tmpevent.type }); alldurs = [ tmpevent(bounds).duration ]; alllats = [ tmpevent(bounds).latency ]; if length(alldurs) >= 1 if alldurs(1) <= 1 alllats(1) = []; alldurs(1) = []; end; end; if isempty(alllats) urlat = 1:EEG.pnts; return; end; % build the ur boolean array % -------------------------- urlat = ones(1, urpnts); for i=1:length(alllats) urlat(round(alllats(i)+0.5):round(alllats(i)+0.5+alldurs(i)-1)) = 0; alllats(i+1:end) = alllats(i+1:end)+alldurs(i); end; urlat(find(urlat)) = 1:EEG.pnts; % ------------------------------------- % saving SPEC information to Matlab file % ------------------------------------- function savetofile(filename, t, f, X, prefix, comps, params, labels, interp); disp([ 'Saving SPECTRAL file ''' filename '''' ]); allspec = []; for k = 1:length(comps) allspec = setfield( allspec, [ prefix int2str(comps(k)) ], X(:,:,k)); end; if ~isempty(labels) allspec.labels = labels; end; allspec.freqs = f; allspec.times = t; allspec.parameters = params; allspec.datatype = 'SPECTROGRAM'; allerp.interpolation = fastif(isempty(interp), 'no', interp); allspec.average_spec = mean(X,1); std_savedat(filename, allspec); % recompute the original data length in points % -------------------------------------------- function pntslat = eeg_urpnts(EEG); if isempty(EEG.event) | ~isfield(EEG.event, 'duration') pntslat = EEG.pnts; return; end; tmpevent = EEG.event; bounds = strmatch('boundary', { tmpevent.type }); alldurs = [ tmpevent(bounds).duration ]; if length(alldurs) > 0 if alldurs(1) <= 1, alldurs(1) = []; end; end; pntslat = EEG.pnts + sum(alldurs); % recompute the original latency % ------------------------------ function pntslat = eeg_urlatency(EEG, pntslat); if isempty(EEG.event), return; end; if ~isstr(EEG.event(1).type), return; end; tmpevent = EEG.event; bounds = strmatch('boundary', { tmpevent.type }) for i=1:length(bounds) if EEG.event(bounds(i)).duration > 1 pntslat = pntslat + EEG.event(bounds(i)).duration; end; end;
github
ZijingMao/baselineeegtest-master
pop_preclust.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_preclust.m
35,559
utf_8
18c27f006ac8293d4a4fdf78bb6cc55b
% pop_preclust() - prepare STUDY components' location and activity measures for later clustering. % Collect information in an interactive pop-up query window. To pre-cluster % from the commandline, use std_preclust(). After data entry into the pop window, % selected measures (one or more from options: ERP, dipole locations, spectra, % scalp maps, ERSP, and ITC) are computed for each dataset in the STUDY % set, unless they already present. After all requested measures are computed % and saved in the STUDY datasets, a PCA matrix (by runica() with 'pca' option) % is constructed (this is the feature reduction step). This matrix will be used % as input to the clustering algorithm in pop_clust(). pop_preclust() allows % selection of a subset of components to cluster. This subset may either be % user-specified, all components with dipole model residual variance lower than % a defined threshold (see dipfit()), or components from an already existing cluster % (for hierarchical clustering). The EEG datasets in the ALLEEG structure are % updated; then the updated EEG sets are saved to disk. Calls std_preclust(). % Usage: % >> [STUDY, ALLEEG] = pop_preclust(STUDY, ALLEEG); % pop up interactive window % >> [STUDY, ALLEEG] = pop_preclust(STUDY, ALLEEG, clustind); % sub-cluster % % Inputs: % STUDY - STUDY set structure containing (loaded) EEG dataset structures % ALLEEG - ALLEEG vector of EEG structures, else a single EEG dataset. % clustind - (single) cluster index to sub-cluster, Hhierarchical clustering may be % useful, for example, to separate a bilteral cluster into left and right % hemisphere sub-clusters. Should be empty for whole STUDY (top level) clustering % {default: []} % Outputs: % STUDY - the input STUDY set with added pre-clustering data for use by pop_clust() % ALLEEG - the input ALLEEG vector of EEG dataset structures modified by adding % pre-clustering data (pointers to .mat files that hold cluster measure information). % % Authors: Arnaud Delorme, Hilit Serby & Scott Makeig, SCCN, INC, UCSD, May 13, 2004- % % See also: std_preclust() % Copyright (C) Hilit Serby, SCCN, INC, UCSD, May 13,2004, [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 [STUDY, ALLEEG, com] = pop_preclust(varargin) com = ''; if ~isstr(varargin{1}) %intial settings if length(varargin) < 2 error('pop_preclust(): needs both ALLEEG and STUDY structures'); end STUDY = varargin{1}; ALLEEG = varargin{2}; if length(varargin) >= 3 if length(varargin{3}) > 1 error('pop_preclust(): To cluster components from several clusters, merge them first!'); end cluster_ind = varargin{3}; else cluster_ind = []; end scalp_options = {'Use channel values' 'Use Laplacian values' 'Use Gradient values'} ; if isempty(ALLEEG) error('STUDY contains no datasets'); end if any(isnan(STUDY.cluster(1).sets(:))) warndlg2( [ 'FOR CLUSTERING, YOU MAY ONLY USE DIPOLE OR SCALP MAP CLUSTERING.' 10 ... 'This is because some datasets do not have ICA pairs. Look for NaN values in ' 10 ... 'STUDY.cluster(1).sets which indicate missing datasets. Each column in this ' 10 ... 'array indicate datasets with common ICA decompositions' ]); end; if length(STUDY.design(STUDY.currentdesign).cases.value) ~= length(STUDY.subject) warndlg2( [ 'GO BACK TO THE DESIGN INTERFACE AND SELECT A DESIGN THAT ' 10 ... 'INCLUDES ALL DATASETS. Some subjects or datasets have been excluded' 10 ... 'in the current design. ICA clusters are common to all designs, so all' 10 ... 'all datasets must be included for clustering. After clustering, you' 10 ... 'will then be able to select a different design (and keep the clustered' 10 ... 'components) if you wish to exclude a subject or group of dataset.' ]); return; end % cluster text % ------------ % load leaf clusters num_cls = 0; cls = 1:length(STUDY.cluster); N = length(cls); %number of clusters show_options{1} = [STUDY.cluster(1).name ' (' num2str(length(STUDY.cluster(1).comps)) ' ICs)']; cls(1) = 1; count = 2; for index1 = 1:length(STUDY.cluster(1).child) indclust1 = strmatch( STUDY.cluster(1).child(index1), { STUDY.cluster.name }, 'exact'); show_options{count} = [' ' STUDY.cluster(indclust1).name ' (' num2str(length(STUDY.cluster(indclust1).comps)) ' ICs)']; cls(count) = indclust1; count = count+1; for index2 = 1:length( STUDY.cluster(indclust1).child ) indclust2 = strmatch( STUDY.cluster(indclust1).child(index2), { STUDY.cluster.name }, 'exact'); show_options{count} = [' ' STUDY.cluster(indclust2).name ' (' num2str(length(STUDY.cluster(indclust2).comps)) ' ICs)']; cls(count) = indclust2; count = count+1; for index3 = 1:length( STUDY.cluster(indclust2).child ) indclust3 = strmatch( STUDY.cluster(indclust2).child(index3), { STUDY.cluster.name }, 'exact'); show_options{count} = [' ' STUDY.cluster(indclust3).name ' (' num2str(length(STUDY.cluster(indclust3).comps)) ' ICs)']; cls(count) = indclust3; count = count+1; end; end; end; % callbacks % --------- erspparams_str = [ '''cycles'', [3 0.5], ''padratio'', 1' ]; specparams_str = ''; show_clust = [ 'pop_preclust(''showclust'',gcf);']; show_comps = [ 'pop_preclust(''showcomplist'',gcf);']; help_spectopo = ['pophelp(''spectopo'')']; set_spectra = ['pop_preclust(''setspec'',gcf);']; set_erp = ['pop_preclust(''seterp'',gcf);']; set_scalp = ['pop_preclust(''setscalp'',gcf);']; set_dipole = ['pop_preclust(''setdipole'',gcf);']; set_ersp = ['pop_preclust(''setersp'',gcf);']; set_itc = ['pop_preclust(''setitc'',gcf);']; set_secpca = ['pop_preclust(''setsec'',gcf);']; set_mpcluster = ['tmp_preclust(''mpcluster'',gcf);']; % nima help_clusteron = ['pophelp(''std_helpselecton'');']; help_ersp = ['pophelp(''pop_timef'')']; preclust_PCA = ['pop_preclust(''preclustOK'',gcf);']; ersp_params = ['pop_preclust(''erspparams'',gcf);']; ersp_edit = ['pop_preclust(''erspedit'',gcf);']; test_ersp = ['pop_precomp(''testersp'',gcf);']; itc_edit = 'set(findobj(gcbf, ''tag'', ''ersp_params''), ''string'', get(gcbo, ''string''));'; ersp_edit = 'set(findobj(gcbf, ''tag'', ''itc_params'' ), ''string'', get(gcbo, ''string''));'; saveSTUDY = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''save''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ]; browsesave = [ '[filename, filepath] = uiputfile2(''*.study'', ''Save STUDY with .study extension -- pop_preclust()''); ' ... 'set(findobj(''parent'', gcbf, ''tag'', ''studyfile''), ''string'', [filepath filename]);' ]; str_name = ['Build pre-clustering matrix for STUDY set: ' STUDY.name '' ]; str_time = ''; help_secpca = [ 'warndlg2(strvcat(''This is the final number of dimensions (otherwise use the sum'',' ... '''of dimensions for all the selected options). See tutorial for more info''), ''Final number of dimensions'');' ]; gui_spec = { ... {'style' 'text' 'string' str_name 'FontWeight' 'Bold' 'horizontalalignment' 'left'} ... {'style' 'text' 'string' 'Select the cluster to refine by sub-clustering (any existing sub-hierarchy will be overwritten)' } {} ... {'style' 'listbox' 'string' show_options 'value' 1 'tag' 'clus_list' 'Callback' show_clust 'max' 1 } {} {} ... {'style' 'text' 'string' 'Note: Only measures that have been precomputed may be used for clustering.'} ... {'style' 'text' 'string' 'Measures Dims. Norm. Rel. Wt.' 'FontWeight' 'Bold'} ... {'style' 'checkbox' 'string' '' 'tag' 'spectra_on' 'value' 0 'Callback' set_spectra 'userdata' '1'} ... {'style' 'text' 'string' 'spectra' 'horizontalalignment' 'center' } ... {'style' 'edit' 'string' '10' 'tag' 'spectra_PCA' 'enable' 'off' 'userdata' 'specP'} ... {'style' 'checkbox' 'string' '' 'tag' 'spectra_norm' 'value' 1 'enable' 'off' 'userdata' 'specP' } ... {'style' 'edit' 'string' '1' 'tag' 'spectra_weight' 'enable' 'off' 'userdata' 'specP'} ... {'style' 'text' 'string' 'Freq.range [Hz]' 'tag' 'spectra_freq_txt' 'userdata' 'spec' 'enable' 'off' } ... {'style' 'edit' 'string' '3 25' 'tag' 'spectra_freq_edit' 'userdata' 'spec' 'enable' 'off' } { } { } ... {'style' 'checkbox' 'string' '' 'tag' 'erp_on' 'value' 0 'Callback' set_erp 'userdata' '1'} ... {'style' 'text' 'string' 'ERPs' 'horizontalalignment' 'center' } ... {'style' 'edit' 'string' '10' 'tag' 'erp_PCA' 'enable' 'off' 'userdata' 'erpP'} ... {'style' 'checkbox' 'string' '' 'tag' 'erp_norm' 'value' 1 'enable' 'off' 'userdata' 'erpP' } ... {'style' 'edit' 'string' '1' 'tag' 'erp_weight' 'enable' 'off' 'userdata' 'erpP'} ... {'style' 'text' 'string' 'Time range [ms]' 'tag' 'erp_time_txt' 'userdata' 'erp' 'enable' 'off' } ... {'style' 'edit' 'string' str_time 'tag' 'erp_time_edit' 'userdata' 'erp' 'enable' 'off' } { } { }... {'style' 'checkbox' 'string' '' 'tag' 'dipole_on' 'value' 0 'Callback' set_dipole 'userdata' '1'} ... {'style' 'text' 'string' 'dipoles' 'HorizontalAlignment' 'center' } ... {'style' 'text' 'string' '3' 'enable' 'off' 'userdata' 'dipoleP' } ... {'style' 'checkbox' 'string' '' 'tag' 'locations_norm' 'value' 1 'enable' 'off' 'userdata' 'dipoleP'} ... {'style' 'edit' 'string' '10' 'tag' 'locations_weight' 'enable' 'off' 'userdata' 'dipoleP'} {} {} {} {} ... {'style' 'checkbox' 'string' '' 'tag' 'scalp_on' 'value' 0 'Callback' set_scalp 'userdata' '1'} ... {'style' 'text' 'string' 'scalp maps' 'HorizontalAlignment' 'center' } ... {'style' 'edit' 'string' '10' 'tag' 'scalp_PCA' 'enable' 'off' 'userdata' 'scalpP'} ... {'style' 'checkbox' 'string' '' 'tag' 'scalp_norm' 'value' 1 'enable' 'off' 'userdata' 'scalpP'} ... {'style' 'edit' 'string' '1' 'tag' 'scalp_weight' 'enable' 'off' 'userdata' 'scalpP'} ... {'style' 'popupmenu' 'string' scalp_options 'value' 1 'tag' 'scalp_choice' 'enable' 'off' 'userdata' 'scalp' } {} ... {'style' 'checkbox' 'string' 'Absolute values' 'value' 1 'tag' 'scalp_absolute' 'enable' 'off' 'userdata' 'scalp' } {} ... {'style' 'checkbox' 'string' '' 'tag' 'ersp_on' 'value' 0 'Callback' set_ersp 'userdata' '1'} ... {'style' 'text' 'string' 'ERSPs' 'horizontalalignment' 'center' } ... {'style' 'edit' 'string' '10' 'tag' 'ersp_PCA' 'enable' 'off' 'userdata' 'erspP'} ... {'style' 'checkbox' 'string' '' 'tag' 'ersp_norm' 'value' 1 'enable' 'off' 'userdata' 'erspP'} ... {'style' 'edit' 'string' '1' 'tag' 'ersp_weight' 'enable' 'off' 'userdata' 'erspP'} ... {'style' 'text' 'string' 'Time range [ms]' 'tag' 'ersp_time_txt' 'userdata' 'ersp' 'enable' 'off' } ... {'style' 'edit' 'string' str_time 'tag' 'ersp_time_edit' 'userdata' 'ersp' 'enable' 'off' } ... {'style' 'text' 'string' 'Freq. range [Hz]' 'tag' 'ersp_time_txt' 'userdata' 'ersp' 'enable' 'off' } ... {'style' 'edit' 'string' str_time 'tag' 'ersp_freq_edit' 'userdata' 'ersp' 'enable' 'off' } ... {'style' 'checkbox' 'string' '' 'tag' 'itc_on' 'value' 0 'Callback' set_itc 'userdata' '1'} ... {'style' 'text' 'string' 'ITCs' 'horizontalalignment' 'center' } ... {'style' 'edit' 'string' '10' 'tag' 'itc_PCA' 'enable' 'off' 'userdata' 'itcP'} ... {'style' 'checkbox' 'string' '' 'tag' 'itc_norm' 'value' 1 'enable' 'off' 'userdata' 'itcP'} ... {'style' 'edit' 'string' '1' 'tag' 'itc_weight' 'enable' 'off' 'userdata' 'itcP'} ... {'style' 'text' 'string' 'Time range [ms]' 'tag' 'itc_time_txt' 'userdata' 'itcP' 'enable' 'off' } ... {'style' 'edit' 'string' str_time 'tag' 'itc_time_edit' 'userdata' 'itcP' 'enable' 'off' } ... {'style' 'text' 'string' 'Freq. range [Hz]' 'tag' 'itc_time_txt' 'userdata' 'itcP' 'enable' 'off' } ... {'style' 'edit' 'string' str_time 'tag' 'itc_freq_edit' 'userdata' 'itcP' 'enable' 'off' } ... {} ... {'style' 'checkbox' 'string' '' 'tag' 'sec_on' 'Callback' set_secpca 'value' 0} ... {'style' 'text' 'string' 'Final dimensions' } ... {'style' 'edit' 'string' '10' 'enable' 'off' 'tag' 'sec_PCA' 'userdata' 'sec' } ... {} {'style' 'pushbutton' 'string' 'Help' 'tag' 'finalDimHelp' 'callback' help_secpca } {} {} {} {} }; % {'link2lines' 'style' 'text' 'string' '' } {} {} {} ... % {'style' 'text' 'string' 'Time/freq. parameters' 'tag' 'ersp_push' 'value' 1 'enable' 'off' 'userdata' 'ersp' 'Callback' ersp_params} ... % {'style' 'edit' 'string' erspparams_str 'tag' 'ersp_params' 'enable' 'off' 'userdata' 'ersp' 'Callback' ersp_edit}... % {'style' 'text' 'string' 'Time/freq. parameters' 'tag' 'itc_push' 'value' 1 'enable' 'off' 'userdata' 'itc' 'Callback' ersp_params} ... % {'style' 'edit' 'string' erspparams_str 'tag' 'itc_params' 'enable' 'off' 'userdata' 'itc' 'Callback' itc_edit}% {'style' 'checkbox' 'string' '' 'tag' 'preclust_PCA' 'Callback' preclust_PCA 'value' 0} ... % {'style' 'text' 'string' 'Do not prepare dataset for clustering at this time.' 'FontWeight' 'Bold' } {} ... fig_arg{1} = { ALLEEG STUDY cls }; geomline = [0.5 2 1 0.5 1 2 1 2 1 ]; geometry = { [1] [1] [1 1 1] [1] [1] ... [3] geomline geomline geomline [0.5 2 1 0.5 1 2.9 .1 2.9 .1 ] geomline geomline [1] geomline }; geomvert = [ 1 1 3 1 1 1 1 1 1 1 1 1 0.5 1 ]; %if length(show_options) < 3 % gui_spec(2:6) = { {} ... % { 'style' 'text' 'string' [ 'Among the pre-selected components (Edit study),' ... % 'remove those which dipole res. var, exceed' ] 'tag' 'dipole_select_on' } ... % {'style' 'edit' 'string' '0.15' 'horizontalalignment' 'center' 'tag' 'dipole_rv'} ... % {'style' 'text' 'string' '(empty=all)'} {} }; % geometry{3} = [2.5 0.25 0.4]; % geomvert(3) = 1; %end; [preclust_param, userdat2, strhalt, os] = inputgui( 'geometry', geometry, 'uilist', gui_spec, 'geomvert', geomvert, ... 'helpcom', ' pophelp(''std_preclust'')', ... 'title', 'Select and compute component measures for later clustering -- pop_preclust()', ... 'userdata', fig_arg); if isempty(preclust_param), return; end; options = { STUDY, ALLEEG }; % precluster on what? % ------------------- options{3} = cls(os.clus_list); % hierarchical clustering %if ~(os.preclust_PCA) %create PCA data for clustering %preclust_command = '[STUDY ALLEEG] = eeg_createdata(STUDY, ALLEEG, '; %end % Spectrum option is on % -------------------- if os.spectra_on== 1 options{end+1} = { 'spec' 'npca' str2num(os.spectra_PCA) 'norm' os.spectra_norm ... 'weight' str2num(os.spectra_weight) 'freqrange' str2num(os.spectra_freq_edit) }; end % ERP option is on % ---------------- if os.erp_on == 1 options{end+1} = { 'erp' 'npca' str2num(os.erp_PCA) 'norm' os.erp_norm ... 'weight' str2num(os.erp_weight) 'timewindow' str2num(os.erp_time_edit) }; end % Scalp maps option is on % ---------------------- if os.scalp_on == 1 if os.scalp_absolute %absolute maps abso = 1; else abso = 0; end if (os.scalp_choice == 2) %Laplacian scalp maps options{end+1} = { 'scalpLaplac' 'npca' str2num(os.scalp_PCA) 'norm' os.scalp_norm ... 'weight' str2num(os.scalp_weight) 'abso' abso }; elseif (os.scalp_choice == 3) %Gradient scalp maps options{end+1} = { 'scalpGrad' 'npca' str2num(os.scalp_PCA) 'norm' os.scalp_norm, ... 'weight' str2num(os.scalp_weight) 'abso' abso }; elseif (os.scalp_choice == 1) %scalp map case options{end+1} = { 'scalp' 'npca' str2num(os.scalp_PCA) 'norm' os.scalp_norm, ... 'weight' str2num(os.scalp_weight) 'abso' abso }; end end % Dipole option is on % ------------------- if os.dipole_on == 1 options{end+1} = { 'dipoles' 'norm' os.locations_norm 'weight' str2num(os.locations_weight) }; end % ERSP option is on % ----------------- if os.ersp_on == 1 options{end+1} = { 'ersp' 'npca' str2num(os.ersp_PCA) 'freqrange' str2num(os.ersp_freq_edit) ... 'timewindow' str2num(os.ersp_time_edit) 'norm' os.ersp_norm 'weight' str2num(os.ersp_weight) }; end % ITC option is on % ---------------- if os.itc_on == 1 options{end+1} = { 'itc' 'npca' str2num(os.itc_PCA) 'freqrange' str2num(os.itc_freq_edit) 'timewindow' ... str2num(os.itc_time_edit) 'norm' os.itc_norm 'weight' str2num(os.itc_weight) }; end % ERSP option is on % ----------------- if os.sec_on == 1 options{end+1} = { 'finaldim' 'npca' str2num(os.sec_PCA) }; end % evaluate command % ---------------- if length(options) == 3 warndlg2('No measure selected: aborting.'); return; end; [STUDY ALLEEG] = std_preclust(options{:}); com = sprintf('[STUDY ALLEEG] = std_preclust(STUDY, ALLEEG, %s);', vararg2str(options(3:end))); % save updated STUDY to the disk % ------------------------------ % if os.saveSTUDY == 1 % if ~isempty(os.studyfile) % [filepath filename ext] = fileparts(os.studyfile); % STUDY.filename = [ filename ext ]; % STUDY.filepath = filepath; % end; % STUDY = pop_savestudy(STUDY, ALLEEG, 'filename', STUDY.filename, 'filepath', STUDY.filepath); % com = sprintf('%s\nSTUDY = pop_savestudy(STUDY, ALLEEG, %s);', com, ... % vararg2str( { 'filename', STUDY.filename, 'filepath', STUDY.filepath })); % end else hdl = varargin{2}; %figure handle userdat = get(varargin{2}, 'userdat'); ALLEEG = userdat{1}{1}; STUDY = userdat{1}{2}; cls = userdat{1}{3}; N = length(cls); switch varargin{1} case 'setspec' set_spec = get(findobj('parent', hdl, 'tag', 'spectra_on'), 'value'); set(findobj('parent', hdl, 'userdata', 'spec'), 'enable', fastif(set_spec,'on','off')); PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value'); if PCA_on set(findobj('parent', hdl, 'userdata', 'specP'), 'enable', 'off'); else set(findobj('parent', hdl, 'userdata', 'specP'), 'enable', fastif(set_spec,'on','off')); end case 'mpcluster' % nima mpclust = get(findobj('parent', hdl, 'tag', 'mpclust'), 'value'); if mpclust set(findobj('parent', hdl, 'tag', 'spectra_PCA'), 'visible','off'); set(findobj('parent', hdl, 'tag', 'spectra_norm'), 'visible','off'); set(findobj('parent', hdl, 'tag', 'spectra_weight'), 'visible','off'); set(findobj('parent', hdl, 'tag', 'erp_PCA' ), 'visible','off'); set(findobj('parent', hdl, 'tag','erp_norm' ), 'visible','off'); set(findobj('parent', hdl, 'tag','erp_weight' ), 'visible','off'); set(findobj('parent', hdl, 'tag', 'locations_norm' ), 'visible','off'); set(findobj('parent', hdl, 'tag','locations_weight'), 'visible','off'); set(findobj('parent', hdl, 'tag', 'scalp_PCA'), 'visible','off'); set(findobj('parent', hdl, 'tag','scalp_norm' ), 'visible','off'); set(findobj('parent', hdl, 'tag','scalp_weight'), 'visible','off'); set(findobj('parent', hdl, 'tag','ersp_PCA'), 'visible','off'); set(findobj('parent', hdl, 'tag', 'ersp_norm'), 'visible','off'); set(findobj('parent', hdl, 'tag','ersp_weight' ), 'visible','off'); set(findobj('parent', hdl, 'tag', 'itc_PCA'), 'visible','off'); set(findobj('parent', hdl, 'tag','itc_norm'), 'visible','off'); set(findobj('parent', hdl, 'tag','itc_weight'), 'visible','off'); set(findobj('parent', hdl, 'tag','sec_PCA'), 'visible','off'); set(findobj('parent', hdl, 'tag','sec_on'), 'visible','off'); set(findobj('parent', hdl, 'userdata' ,'dipoleP'), 'visible','off'); set(findobj('parent', hdl, 'string','Final dimensions'), 'visible','off'); set(findobj('parent', hdl, 'tag','finalDimHelp' ), 'visible','off'); set(findobj('parent', hdl, 'tag','spectra_freq_txt'), 'visible','off'); set(findobj('parent', hdl, 'tag','spectra_freq_edit'), 'visible','off'); %% these are made invisible for now, but in future we might use them in the new method set(findobj('parent', hdl, 'tag','erp_time_txt'), 'visible','off'); set(findobj('parent', hdl, 'tag','erp_time_edit'), 'visible','off'); set(findobj('parent', hdl, 'tag','scalp_choice'), 'visible','off'); set(findobj('parent', hdl, 'tag', 'scalp_absolute'), 'visible','off'); set(findobj('parent', hdl, 'tag','ersp_time_txt'), 'visible','off'); set(findobj('parent', hdl, 'tag','ersp_time_edit'), 'visible','off'); set(findobj('parent', hdl, 'tag','ersp_freq_edit'), 'visible','off'); set(findobj('parent', hdl, 'tag','itc_time_txt'), 'visible','off'); set(findobj('parent', hdl, 'tag','itc_time_edit'), 'visible','off'); set(findobj('parent', hdl, 'tag','itc_freq_edit'), 'visible','off'); set(findobj('parent', hdl, 'string','Measures Dims. Norm. Rel. Wt.'), 'string','Measures'); else set(findobj('parent', hdl, 'tag', 'spectra_PCA'), 'visible','on'); set(findobj('parent', hdl, 'tag', 'spectra_norm'), 'visible','on'); set(findobj('parent', hdl, 'tag', 'spectra_weight'), 'visible','on'); set(findobj('parent', hdl, 'tag', 'erp_PCA' ), 'visible','on'); set(findobj('parent', hdl, 'tag','erp_norm' ), 'visible','on'); set(findobj('parent', hdl, 'tag','erp_weight' ), 'visible','on'); set(findobj('parent', hdl, 'tag', 'locations_norm' ), 'visible','on'); set(findobj('parent', hdl, 'tag','locations_weight'), 'visible','on'); set(findobj('parent', hdl, 'tag', 'scalp_PCA'), 'visible','on'); set(findobj('parent', hdl, 'tag','scalp_norm' ), 'visible','on'); set(findobj('parent', hdl, 'tag','scalp_weight'), 'visible','on'); set(findobj('parent', hdl, 'tag','ersp_PCA'), 'visible','on'); set(findobj('parent', hdl, 'tag', 'ersp_norm'), 'visible','on'); set(findobj('parent', hdl, 'tag','ersp_weight' ), 'visible','on'); set(findobj('parent', hdl, 'tag', 'itc_PCA'), 'visible','on'); set(findobj('parent', hdl, 'tag','itc_norm'), 'visible','on'); set(findobj('parent', hdl, 'tag','itc_weight'), 'visible','on'); set(findobj('parent', hdl, 'tag','sec_PCA'), 'visible','on'); set(findobj('parent', hdl, 'tag','sec_on'), 'visible','on'); set(findobj('parent', hdl, 'userdata' ,'dipoleP'), 'visible','on'); set(findobj('parent', hdl, 'string','Final dimensions'), 'visible','on'); set(findobj('parent', hdl, 'tag','finalDimHelp' ), 'visible','on'); set(findobj('parent', hdl, 'tag','spectra_freq_txt'), 'visible','on'); set(findobj('parent', hdl, 'tag','spectra_freq_edit'), 'visible','on'); %% these are made invisible for now, but in future we might use them in the new method set(findobj('parent', hdl, 'tag','erp_time_txt'), 'visible','on'); set(findobj('parent', hdl, 'tag','erp_time_edit'), 'visible','on'); set(findobj('parent', hdl, 'tag','scalp_choice'), 'visible','on'); set(findobj('parent', hdl, 'tag', 'scalp_absolute'), 'visible','on'); set(findobj('parent', hdl, 'tag','ersp_time_txt'), 'visible','on'); set(findobj('parent', hdl, 'tag','ersp_time_edit'), 'visible','on'); set(findobj('parent', hdl, 'tag','ersp_freq_edit'), 'visible','on'); set(findobj('parent', hdl, 'tag','itc_time_txt'), 'visible','on'); set(findobj('parent', hdl, 'tag','itc_time_edit'), 'visible','on'); set(findobj('parent', hdl, 'tag','itc_freq_edit'), 'visible','on'); set(findobj('parent', hdl, 'string','Measures to Cluster on:'), 'string','Load Dims. Norm. Rel. Wt.'); set(findobj('parent', hdl, 'string','Measures'), 'string', 'Measures Dims. Norm. Rel. Wt.'); end; % set_mpcluster = get(findobj('parent', hdl, 'tag', 'spectra_on'), 'value'); % set(findobj('parent', hdl, 'userdata', 'spec'), 'enable', fastif(set_spec,'on','off')); % PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value'); % if PCA_on % set(findobj('parent', hdl, 'userdata', 'specP'), 'enable', 'off'); % else % set(findobj('parent', hdl, 'userdata', 'specP'), 'enable', fastif(set_spec,'on','off')); % end case 'seterp' set_erp = get(findobj('parent', hdl, 'tag', 'erp_on'), 'value'); set(findobj('parent', hdl, 'userdata', 'erp'), 'enable', fastif(set_erp,'on','off')); PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value'); if PCA_on set(findobj('parent', hdl, 'userdata', 'erpP'), 'enable', 'off'); else set(findobj('parent', hdl, 'userdata', 'erpP'), 'enable', fastif(set_erp,'on','off')); end case 'setscalp' set_scalp = get(findobj('parent', hdl, 'tag', 'scalp_on'), 'value'); set(findobj('parent', hdl, 'userdata', 'scalp'), 'enable', fastif(set_scalp,'on','off')); PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value'); if PCA_on set(findobj('parent', hdl, 'userdata', 'scalpP'), 'enable', 'off'); else set(findobj('parent', hdl, 'userdata', 'scalpP'), 'enable', fastif(set_scalp,'on','off')); end case 'setdipole' set_dipole = get(findobj('parent', hdl, 'tag', 'dipole_on'), 'value'); set(findobj('parent', hdl, 'userdata', 'dipole'), 'enable', fastif(set_dipole,'on','off')); PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value'); if PCA_on set(findobj('parent', hdl, 'userdata', 'dipoleP'), 'enable','off'); else set(findobj('parent', hdl, 'userdata', 'dipoleP'), 'enable', fastif(set_dipole,'on','off')); end case 'setersp' set_ersp = get(findobj('parent', hdl, 'tag', 'ersp_on'), 'value'); set(findobj('parent', hdl,'userdata', 'ersp'), 'enable', fastif(set_ersp,'on','off')); PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value'); if PCA_on set(findobj('parent', hdl,'userdata', 'erspP'), 'enable', 'off'); else set(findobj('parent', hdl,'userdata', 'erspP'), 'enable', fastif(set_ersp,'on','off')); end set_itc = get(findobj('parent', hdl, 'tag', 'itc_on'), 'value'); set(findobj('parent', hdl,'tag', 'ersp_push'), 'enable', fastif(set_itc,'off','on')); set(findobj('parent', hdl,'tag', 'ersp_params'), 'enable', fastif(set_itc,'off','on')); if (set_itc & (~set_ersp) ) set(findobj('parent', hdl,'tag', 'itc_push'), 'enable', 'on'); set(findobj('parent', hdl,'tag', 'itc_params'), 'enable', 'on'); end case 'setitc' set_itc = get(findobj('parent', hdl, 'tag', 'itc_on'), 'value'); set(findobj('parent', hdl,'userdata', 'itc'), 'enable', fastif(set_itc,'on','off')); PCA_on = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value'); if PCA_on set(findobj('parent', hdl,'userdata', 'itcP'), 'enable','off'); else set(findobj('parent', hdl,'userdata', 'itcP'), 'enable', fastif(set_itc,'on','off')); end set_ersp = get(findobj('parent', hdl, 'tag', 'ersp_on'), 'value'); set(findobj('parent', hdl,'tag', 'itc_push'), 'enable', fastif(set_ersp,'off','on')); set(findobj('parent', hdl,'tag', 'itc_params'), 'enable', fastif(set_ersp,'off','on')); if (set_ersp & (~set_itc) ) set(findobj('parent', hdl,'tag', 'ersp_push'), 'enable', 'on'); set(findobj('parent', hdl,'tag', 'ersp_params'), 'enable', 'on'); end case 'setsec' set_sec = get(findobj('parent', hdl, 'tag', 'sec_on'), 'value'); set(findobj('parent', hdl,'userdata', 'sec'), 'enable', fastif(set_sec,'on','off')); case 'erspparams' ersp = userdat{2}; [ersp_paramsout, erspuserdat, strhalt, erspstruct] = inputgui( { [1] [3 1] [3 1] [3 1] [3 1] [3 1] [1]}, ... { {'style' 'text' 'string' 'ERSP and ITC time/freq. parameters' 'FontWeight' 'Bold'} ... {'style' 'text' 'string' 'Frequency range [Hz]' 'tag' 'ersp_freq' } ... {'style' 'edit' 'string' ersp.f 'tag' 'ersp_f' 'Callback' ERSP_timewindow } ... {'style' 'text' 'string' 'Wavelet cycles (see >> help timef())' 'tag' 'ersp_cycle' } ... {'style' 'edit' 'string' ersp.c 'tag' 'ersp_c' 'Callback' ERSP_timewindow} ... {'style' 'text' 'string' 'Significance level (< 0.1)' 'tag' 'ersp_alpha' } ... {'style' 'edit' 'string' ersp.a 'tag' 'ersp_a'} ... {'style' 'text' 'string' 'timef() padratio' 'tag' 'ersp_pad' } ... {'style' 'edit' 'string' ersp.p 'tag' 'ersp_p' 'Callback' ERSP_timewindow} ... {'style' 'text' 'string' 'Desired time window within the indicated latency range [ms]' 'tag' 'ersp_trtxt' } ... {'style' 'edit' 'string' ersp.t 'tag' 'ersp_timewindow' 'Callback' ERSP_timewindow} {} }, ... 'pophelp(''pop_timef'')', 'Select clustering ERSP and ITC time/freq. parameters -- pop_preclust()'); if ~isempty(ersp_paramsout) ersp.f = erspstruct(1).ersp_f; ersp.c = erspstruct(1).ersp_c; ersp.p = erspstruct(1).ersp_p; ersp.a = erspstruct(1).ersp_a; ersp.t = erspstruct(1).ersp_timewindow; userdat{2} = ersp; set(findobj('parent', hdl, 'tag', 'ersp_params'), 'string', ... [' ''frange'', [' ersp.f '], ''cycles'', [' ... ersp.c '], ''alpha'', ' ersp.a ', ''padratio'', ' ersp.p ', ''tlimits'', [' ersp.t ']']); set(findobj('parent', hdl, 'tag', 'itc_params'), 'string', ... [' ''frange'', [' ersp.f '], ''cycles'', [' ... ersp.c '], ''alpha'', ' ersp.a ', ''padratio'', ' ersp.p ', ''tlimits'', [' ersp.t ']']); set(hdl, 'userdat',userdat); end case 'preclustOK' set_PCA = get(findobj('parent', hdl, 'tag', 'preclust_PCA'), 'value'); set_ersp = get(findobj('parent', hdl, 'tag', 'ersp_on'), 'value'); set(findobj('parent', hdl,'userdata', 'erspP'), 'enable', fastif(~set_PCA & set_ersp,'on','off')); set_itc = get(findobj('parent', hdl, 'tag', 'itc_on'), 'value'); set(findobj('parent', hdl,'userdata', 'itcP'), 'enable', fastif(~set_PCA & set_itc,'on','off')); set_erp = get(findobj('parent', hdl, 'tag', 'erp_on'), 'value'); set(findobj('parent', hdl,'userdata', 'erpP'), 'enable', fastif(~set_PCA & set_erp,'on','off')); set_spec = get(findobj('parent', hdl, 'tag', 'spectra_on'), 'value'); set(findobj('parent', hdl,'userdata', 'specP'), 'enable', fastif(~set_PCA & set_spec,'on','off')); set_scalp = get(findobj('parent', hdl, 'tag', 'scalp_on'), 'value'); set(findobj('parent', hdl,'userdata', 'scalpP'), 'enable', fastif(~set_PCA & set_scalp,'on','off')); set_dipole = get(findobj('parent', hdl, 'tag', 'dipole_on'), 'value'); set(findobj('parent', hdl,'userdata', 'dipoleP'), 'enable', fastif(~set_PCA & set_dipole,'on','off')); set(findobj('parent', hdl,'tag', 'chosen_component'), 'enable', fastif(~set_PCA,'on','off')); set(findobj('parent', hdl,'tag', 'dipole_rv'), 'enable', fastif(~set_PCA,'on','off')); set(findobj('parent', hdl,'tag', 'compstd_str'), 'enable', fastif(~set_PCA,'on','off')); end end STUDY.saved = 'no';
github
ZijingMao/baselineeegtest-master
std_selsubject.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_selsubject.m
2,842
utf_8
6466ff23a5fb9b15112c7274c77f6ea5
% std_selsubject() - Helper function for std_erpplot(), std_specplot() % and std_erspplot() to select specific subject when % plotting channel data. % Usage: % >> data = std_selsubject( data, subject, setinds, allsubjects); % % Inputs: % data - [cell array] mean data for each subject group and/or data % condition. For example, to compute mean ERPs statistics from a % STUDY for epochs of 800 frames in two conditions from three % groups of 12 subjects, % >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1 % [800x12] [800x12] [800x12] }; % 3 groups, cond 2 % subject - [string] subject name % setinds - [cell array] set indices for each of the last dimension of the % data cell array. % >> setinds = { [12] [12] [12];... % 3 groups, cond 1 % [12] [12] [12] }; % 3 groups, cond 2 % allsubject - [cell array] all subjects (same order as in % STUDY.datasetinfo) % % Output: % data - [cell array] data array with the subject or component selected % % Author: Arnaud Delorme, CERCO, CNRS, 2006- % % See also: std_erpplot(), std_specplot() and std_erspplot() function [data] = std_selsubject(data, subject, setinds, allsubjects, optndims); if nargin < 2 help std_selsubject; return; end; optndims = max(optndims, ndims(data{1})); if isempty(strmatch(lower(subject), lower(allsubjects))) error(sprintf('Cannot select subject %s in list %s', subject, vararg2str({ allsubjects }))); end; % plot specific subject % --------------------- if size(setinds{1},1) > 1 && size(setinds{1},2) > 1 % single trials % possible subject indices selectInds = strmatch(lower(subject), lower(allsubjects)); for c = 1:size(data,1) for g = 1:size(data,2) selectCol = []; for ind = 1:length(selectInds) selectCol = [ selectCol find(setinds{c,g} == selectInds') ]; end; if optndims == 2 data{c,g} = data{c,g}(:,selectCol); %2-D elseif optndims == 3 data{c,g} = data{c,g}(:,:,selectCol); %3-D else data{c,g} = data{c,g}(:,:,:,selectCol); %4-D end; end; end; else for c = 1:size(data,1) for g = 1:size(data,2) subjectind = strmatch(lower(subject), lower(allsubjects)); l = zeros(size(setinds{c,g})); for iSubj = 1:length(subjectind), l = l | setinds{c,g} == subjectind(iSubj); end; if optndims == 2 data{c,g}(:,~l) = []; %2-D elseif optndims == 3 data{c,g}(:,:,~l) = []; %3-D else data{c,g}(:,:,:,~l) = []; %4-D end; end; end; end;
github
ZijingMao/baselineeegtest-master
std_pac.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_pac.m
12,743
utf_8
9fc01e1de80025c52deebe220a9c0b20
% std_pac() - Compute or read PAC data (Phase Amplitude Coupling). % % Usage: % >> [X times logfreqs ] = std_pac(EEG, 'key', 'val', ...); % Inputs: % EEG - an EEG dataset structure. % % Optional inputs: % 'components1'- [numeric vector] components in the EEG structure used % for spectral amplitude in PAC {default|[]: all } % 'components2'- [numeric vector] components in the EEG structure used % for phase in PAC {default|[]: all } % 'channels1' - [numeric vector or cell array of channel labels] channels % in the EEG structure for spectral amplitude in PAC % {default|[]: no channels} % 'channels2' - [numeric vector or cell array of channel labels] channels % in the EEG structure for phase in PAC % {default|[]: no channels} % 'freqs' - [minHz maxHz] the PAC frequency range to compute power. % {default: 12 to EEG sampling rate divided by 2} % 'cycles' - [wavecycles (factor)]. If 0 -> DFT (constant window length % across frequencies). % If >0 -> the number of cycles in each analysis wavelet. % If [wavecycles factor], wavelet cycles increase with % frequency, beginning at wavecyles. (0 < factor < 1) % factor = 0 -> fixed epoch length (DFT, as in FFT). % factor = 1 -> no increase (standard wavelets) % {default: [0]} % 'freqphase' - [valHz] single number for computing the phase at a given % frequency. % 'cyclephase' - [valcycle] single cycle number. % 'timewindow' - [minms maxms] time window (in ms) to plot. % {default: all output latencies} % 'padratio' - (power of 2). Multiply the number of output frequencies % by dividing their frequency spacing through 0-padding. % Output frequency spacing is (low_freq/padratio). % 'recompute' - ['on'|'off'] 'on' forces recomputation of PAC. % {default: 'off'} % % Other optional inputs: % This function will take any of the newtimef() optional inputs (for instance % to compute log-space frequencies)... % % Outputs: % X - the PAC of the requested ICA components/channels % in the selected frequency and time range. % times - vector of time points for which the PAC were computed. % freqs - vector of frequencies (in Hz) at which the % PAC was evaluated. % % Files written or modified: % [dataset_filename].icapac <-- saved component PAC % OR for channels % [dataset_filename].datpac <-- saved channel PAC % % See also: timef(), std_itc(), std_erp(), std_spec(), std_topo(), std_preclust() % % Authors: Arnaud Delorme, SCCN, INC, UCSD, July, 2009- % Copyright (C) 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 [X, times, freqs, parameters] = std_pac(EEG, varargin) if nargin < 1 help std_pac; return; end; options = {}; [g timefargs] = finputcheck(varargin, { ... 'components1' 'integer' [] []; 'channels1' { 'cell','integer' } { [],[] } {}; 'components2' 'integer' [] []; 'channels2' { 'cell','integer' } { [],[] } {}; 'outputfile' 'string' [] ''; 'powbase' 'real' [] []; 'plot' 'string' { 'on','off' } 'off'; 'recompute' 'string' { 'on','off' } 'off'; 'getparams' 'string' { 'on','off' } 'off'; 'timerange' 'real' [] []; 'freqrange' 'real' [] []; 'padratio' 'real' [] 1; 'freqs' 'real' [] [12 EEG.srate/2]; 'cycles' 'real' [] [8]; 'freqphase' 'real' [] [5]; 'cyclephase' 'real' [] [3]; 'interp' 'struct' { } struct([]); 'rmcomps' 'integer' [] []; 'freqscale' 'string' [] 'log' }, 'std_pac', 'ignore'); if isstr(g), error(g); end; % checking input parameters % ------------------------- if isempty(g.components1) & isempty(g.channels1) if isempty(EEG(1).icaweights) error('EEG.icaweights not found'); end g.components1 = 1:size(EEG(1).icaweights,1); g.components2 = 1:size(EEG(1).icaweights,1); disp('Computing PAC with default values for all components of the dataset'); end % select ICA components or data channels % -------------------------------------- if ~isempty(g.outputfile) filenamepac = fullfile('', [ g.outputfile '.datpac' ]); g.indices1 = std_chaninds(EEG, g.channels1); g.indices2 = std_chaninds(EEG, g.channels2); prefix = 'chan'; elseif ~isempty(g.components1) g.indices1 = g.components1; g.indices2 = g.components2; prefix = 'comp'; filenamepac = fullfile(EEG.filepath, [ EEG.filename(1:end-3) 'icapac' ]); if ~isempty(g.channels1) error('Cannot compute PAC for components and channels at the same time'); end; elseif ~isempty(g.channels1) g.indices1 = std_chaninds(EEG, g.channels1); g.indices2 = std_chaninds(EEG, g.channels2); prefix = 'chan'; filenamepac = fullfile(EEG.filepath, [ EEG.filename(1:end-3) 'datpac' ]); end; % Compute PAC parameters % ----------------------- parameters = { 'wavelet', g.cycles, 'padratio', g.padratio, ... 'freqs2', g.freqphase, 'wavelet2', g.cyclephase, 'freqscale', g.freqscale, timefargs{:} }; if length(g.freqs)>0, parameters = { parameters{:} 'freqs' g.freqs }; end; % Check if PAC information found in datasets and if fits requested parameters % ---------------------------------------------------------------------------- if exist( filenamepac ) & strcmpi(g.recompute, 'off') fprintf('Use existing file for PAC: %s\n', filenamepac); if ~isempty(g.components1) [X, times, freqs, parameters] = std_readpac(EEG, 1, g.indices1, g.indices2, g.timerange, g.freqrange); else [X, times, freqs, parameters] = std_readpac(EEG, 1, -g.indices1, -g.indices2, g.timerange, g.freqrange); end; return; end; % return parameters % ----------------- if strcmpi(g.getparams, 'on') X = []; times = []; freqs = []; return; end; options = {}; if ~isempty(g.components1) tmpdata = eeg_getdatact(EEG, 'component', [1:size(EEG(1).icaweights,1)]); else EEG.data = eeg_getdatact(EEG, 'channel', [1:EEG.nbchan], 'rmcomps', g.rmcomps); if ~isempty(g.rmcomps), options = { options{:} 'rmcomps' g.rmcomps }; end; if ~isempty(g.interp), EEG = eeg_interp(EEG, g.interp, 'spherical'); options = { options{:} 'interp' g.interp }; end; tmpdata = EEG.data; end; % Compute PAC % ----------- all_pac = []; for k = 1:length(g.indices1) % for each (specified) component for l = 1:length(g.indices2) % for each (specified) component tmpparams = parameters; % Run pac() to get PAC % -------------------- timefdata1 = tmpdata(g.indices1(k),:,:); timefdata2 = tmpdata(g.indices2(l),:,:); if strcmpi(g.plot, 'on'), figure; end; %[logersp,logitc,logbase,times,logfreqs,logeboot,logiboot,alltfX] ... [pacvals, times, freqs1, freqs2] = pac( timefdata1, timefdata2, EEG(1).srate, 'tlimits', [EEG.xmin EEG.xmax]*1000, tmpparams{1:end}); all_pac = setfield( all_pac, [ prefix int2str(g.indices1(k)) '_' int2str(g.indices2(l)) '_pac' ], squeeze(single(pacvals ))); end; end % Save PAC into file % ------------------ all_pac.freqs = freqs1; all_pac.times = times; all_pac.datatype = 'PAC'; all_pac.parameters = tmpparams; if ~isempty(g.channels1) if ~isempty(EEG(1).chanlocs) tmpchanlocs = EEG(1).chanlocs; all_pac.chanlabels1 = { tmpchanlocs(g.indices1).labels }; all_pac.chanlabels2 = { tmpchanlocs(g.indices2).labels }; end; end; std_savedat( filenamepac , all_pac ); if ~isempty(g.components1) [X, times, freqs, parameters] = std_readpac(EEG, 1, g.indices1, g.indices2, g.timerange, g.freqrange); else [X, times, freqs, parameters] = std_readpac(EEG, 1, -g.indices1, -g.indices2, g.timerange, g.freqrange); end; % -------------------------------------------------------- % -------------------- READ PAC DATA --------------------- % -------------------------------------------------------- function [pacvals, freqs, timevals, params] = std_readpac(ALLEEG, abset, comp1, comp2, timewindow, freqrange); if nargin < 5 timewindow = []; end; if nargin < 6 freqrange = []; end; % multiple entry % -------------- if length(comp1) > 1 | length(comp2) > 1 for index1 = 1:length(comp1) for index2 = 1:length(comp2) [tmppac, freqs, timevals, params] = std_readpac(ALLEEG, abset, comp1(index1), comp2(index2), timewindow, freqrange); pacvals(index1,index2,:,:,:) = tmppac; end; end; return; end; for k = 1: length(abset) if comp1 < 0 filename = fullfile( ALLEEG(abset(k)).filepath,[ ALLEEG(abset(k)).filename(1:end-3) 'datpac']); comp1 = -comp1; comp2 = -comp2; prefix = 'chan'; else filename = fullfile( ALLEEG(abset(k)).filepath,[ ALLEEG(abset(k)).filename(1:end-3) 'icapac']); prefix = 'comp'; end; try tmppac = load( '-mat', filename, 'parameters', 'times', 'freqs'); catch error( [ 'Cannot read file ''' filename '''' ]); end; tmppac.parameters = removedup(tmppac.parameters); params = struct(tmppac.parameters{:}); params.times = tmppac.times; params.freqs = tmppac.freqs; if isempty(comp1) pacvals = []; freqs = []; timevals = []; return; end; tmppac = load( '-mat', filename, 'parameters', 'times', 'freqs', ... [ prefix int2str(comp1) '_' int2str(comp2) '_pac']); pacall{k} = double(getfield(tmppac, [ prefix int2str(comp1) '_' int2str(comp2) '_pac'])); tlen = length(tmppac.times); flen = length(tmppac.freqs); end % select plotting or clustering time/freq range % --------------------------------------------- if ~isempty(timewindow) if timewindow(1) > tmppac.times(1) | timewindow(end) < tmppac.times(end) maxind = max(find(tmppac.times <= timewindow(end))); minind = min(find(tmppac.times >= timewindow(1))); else minind = 1; maxind = tlen; end else minind = 1; maxind = tlen; end if ~isempty(freqrange) if freqrange(1) > exp(1)^tmppac.freqs(1) | freqrange(end) < exp(1)^tmppac.freqs(end) fmaxind = max(find(tmppac.freqs <= freqrange(end))); fminind = min(find(tmppac.freqs >= freqrange(1))); else fminind = 1; fmaxind = flen; end else fminind = 1; fmaxind = flen; end % return parameters % ---------------- for cond = 1:length(abset) try pac = pacall{cond}(fminind:fmaxind,minind:maxind); catch pac = pacall{cond}; % for 'method', 'latphase' end; pacvals(:,:,cond) = pac; end; freqs = tmppac.freqs(fminind:fmaxind); timevals = tmppac.times(minind:maxind); % remove duplicates in the list of parameters % ------------------------------------------- function cella = removedup(cella) [tmp indices] = unique_bc(cella(1:2:end)); if length(tmp) ~= length(cella)/2 %fprintf('Warning: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n'); end; cella = cella(sort(union(indices*2-1, indices*2)));
github
ZijingMao/baselineeegtest-master
compute_ersp_times.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/compute_ersp_times.m
2,069
utf_8
444923a87f00e754398384b467789b6d
% compute_ERSP_times() - computes the widest possible ERSP/ITC time window, % which depends on requested ERSP/ITC parameters such as epoch limits, % frequency range, wavelet parameters, sampling rate and frequency % resolution that are used by timef(). % This helper function is called by pop_preclust() & std_ersp(). % Example: % [time_range, winsize] = compute_ersp_times(cycles, ALLEEG(seti).srate, ... % [ALLEEG(seti).xmin ALLEEG(seti).xmax]*1000, freq(1),padratio); % % Authors: Hilit Serby & Arnaud Delorme, SCCN, INC, UCSD, Feb 03, 2005 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, Feb 03, 2005, [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 [time_range, winsize] = compute_ERSP_times(cycles, srate, epoch_lim, lowfreq, padratio) if cycles == 0 %FFT option if ~exist('padratio') error('You must enter padratio value for FFT ERSP'); end lowfreq = lowfreq*padratio; t = 1/lowfreq;%time window in sec winsize = t*srate;%time window in points %time window in points (must be power of 2) for FFT winsize =pow2(nextpow2(winsize)); %winsize =2^round(log2(winsize)); else %wavelet t = cycles(1)/lowfreq; %time window in sec winsize = round(t*srate); %time window in points end time_range(1) = epoch_lim(1) + .5*t*1000; time_range(2) = epoch_lim(2) - .5*t*1000;
github
ZijingMao/baselineeegtest-master
std_dipplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_dipplot.m
27,155
utf_8
7aa203b7ca134c606fdce5feeeca46e8
% std_dipplot() - Commandline function to plot cluster component dipoles. Dipoles for each % named cluster is displayed in a separate figure. To view all the clustered % components in the STUDY on the same figure (in a separate subplot), all % STUDY clusters must be requested. % To visualize dipoles, they first must be stored in the EEG dataset structures % using dipfit(). Only components that have dipole locations will be displayed, % along with the cluster mean dipole (in red). % Usage: % >> [STUDY] = std_dipplot(STUDY, ALLEEG, clusters); % Inputs: % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in % the STUDY. ALLEEG for a STUDY set is typically created using load_ALLEEG(). % % Optional inputs: % 'clusters' - [numeric vector | 'all'] -> specific cluster numbers to plot. % 'all' -> plot all clusters in STUDY. % {default: 'all'}. % 'comps' - [numeric vector] -> indices of the cluster components to plot. % 'all' -> plot all the components in the cluster % {default: 'all'}. % 'mode' - ['together'|'apart'] Display all requested cluster on one % figure ('together') or separate figures ('apart'). % 'together'-> plot all 'clusters' in one figure (without the gui). % 'apart' -> plot each cluster in a separate figure. Note that % this parameter has no effect if the 'comps' option (above) is used. % {default: 'together'} % 'figure' - ['on'|'off'] plots on a new figure ('on') or plots on current % figure ('off'). If 'figure','off' does not display gui controls, % Useful for incomporating a cluster dipplot into a complex figure. % {default: 'on'}. % 'groups' - ['on'|'off'] use different colors for different groups. % {default: 'off'}. % Outputs: % STUDY - the input STUDY set structure modified with plotted cluster % mean dipole, to allow quick replotting (unless cluster means % already exists in the STUDY). % Example: % >> [STUDY] = std_dipplot(STUDY,ALLEEG, 'clusters', 5, 'mode', 'apart', 'figure', 'off'); % % Plot cluster-5 component dipoles (in blue), plus ther mean dipole (in red), % % on an exisiting (gui-less) figure. % % See also pop_clustedit(), dipplot() % % Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005 % 'groups' added by Makoto Miyakoshi on June 2012. % Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 08, 2005, [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 STUDY = std_dipplot(STUDY, ALLEEG, varargin) % Set default values cls = []; % plot all clusters in STUDY figureon = 1; % plot on a new figure mode = 'apart'; STUDY = pop_dipparams(STUDY, 'default'); opt_dipplot = {'projlines',STUDY.etc.dipparams.projlines, 'axistight', STUDY.etc.dipparams.axistight, 'projimg', STUDY.etc.dipparams.projimg, 'normlen', 'on', 'pointout', 'on', 'verbose', 'off', 'dipolelength', 0,'spheres','on'}; %, 'spheres', 'on' groupval = 'off'; for k = 3:2:nargin switch varargin{k-2} case 'clusters' if isnumeric(varargin{k-1}) cls = varargin{k-1}; if isempty(cls) cls = 2:length(STUDY.cluster); end else if isstr(varargin{k-1}) & strcmpi(varargin{k-1}, 'all') cls = 2:length(STUDY.cluster); else error('std_dipplot: ''clusters'' input takes either specific clusters (numeric vector) or keyword ''all''.'); end end if length(cls) == 1, mode = 'apart'; else mode = 'together'; end; case 'comps' STUDY = std_plotcompdip(STUDY, ALLEEG, cls, varargin{k-1}, opt_dipplot{:}); return; case 'plotsubjects', % do nothing case 'mode', mode = varargin{k-1}; case 'groups', groupval = varargin{k-1}; case 'figure' if strcmpi(varargin{k-1},'off') opt_dipplot{end + 1} = 'gui'; opt_dipplot{end + 1} = 'off'; figureon = 0; end end end % select clusters to plot % ----------------------- if isempty(cls) tmp =[]; cls = 2:length(STUDY.cluster); % plot all clusters in STUDY for k = 1: length(cls) % don't include 'Notclust' clusters if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13) tmp = [tmp cls(k)]; end end cls = tmp; end; if strcmpi(mode, 'apart') % case each cluster on a separate figure for clus = 1: length(cls) % For each cluster requested if length(STUDY.cluster(cls(clus)).comps) > 0 % check there are comps in cluster max_r = 0; clear cluster_dip_models; len = length(STUDY.cluster(cls(clus)).comps); ndip = 0; dip_ind = []; if ~isfield(STUDY.cluster(cls(clus)),'dipole') STUDY = std_centroid(STUDY,ALLEEG, cls(clus) , 'dipole'); elseif isempty(STUDY.cluster(cls(clus)).dipole) STUDY = std_centroid(STUDY,ALLEEG, cls(clus) , 'dipole'); end for k = 1:len abset = STUDY.datasetinfo(STUDY.cluster(cls(clus)).sets(1,k)).index; subject = STUDY.datasetinfo(STUDY.cluster(cls(clus)).sets(1,k)).subject; if ~isfield(ALLEEG(abset), 'dipfit') warndlg2(['No dipole information available in dataset ' ALLEEG(abset).filename ' , abort plotting'], 'Aborting plot dipoles'); return; end comp = STUDY.cluster(cls(clus)).comps(k); cluster_dip_models(k).posxyz = ALLEEG(abset).dipfit.model(comp).posxyz; cluster_dip_models(k).momxyz = ALLEEG(abset).dipfit.model(comp).momxyz; cluster_dip_models(k).rv = ALLEEG(abset).dipfit.model(comp).rv; if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model load('-mat', ALLEEG(abset).dipfit.hdmfile); max_r = max(max_r, max(vol.r)); else % old version of dipfit max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r)); end end comp_to_disp{k} = [subject ', ' 'IC' num2str(comp) ]; if ~isempty(cluster_dip_models(k).posxyz) ndip = ndip +1; dip_ind = [dip_ind k]; end end % finished going over cluster comps STUDY.cluster(cls(clus)).dipole = computecentroid(cluster_dip_models); cluster_dip_models(end + 1) = STUDY.cluster(cls(clus)).dipole; % additional options % ------------------ dip_color = cell(1,ndip+1); dip_color(1:ndip) = {'b'}; dip_color(end) = {'r'}; options = opt_dipplot; options{end+1} = 'mri'; options{end+1} = ALLEEG(abset).dipfit.mrifile; options{end+1} = 'coordformat'; options{end+1} = ALLEEG(abset).dipfit.coordformat; options{end+1} = 'dipnames'; options{end+1} = {comp_to_disp{dip_ind } [STUDY.cluster(cls(clus)).name ' mean']}; options{end+1} = 'color'; options{end+1} = dip_color; % if 'groups'==1, overwrite cluster_dip_models, dip_color and dipnames in option -makoto if strcmpi(groupval, 'on') [cluster_dip_models, options] = dipgroups(ALLEEG, STUDY, cls, comp_to_disp, cluster_dip_models, options); break end if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') options{end+1} = 'sphere'; options{end+1} = max_r; else options{end+1} = 'meshdata'; options{end+1} = ALLEEG(abset).dipfit.hdmfile; end if ndip < 6 && strcmpi(options{1}, 'projlines') && length(cls) == 1 % less than 6 dipoles, project lines options{2} = 'on'; end if figureon dipplot(cluster_dip_models, options{:}); fig_h = gcf; set(fig_h,'Name', [STUDY.cluster(cls(clus)).name ' - ' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) ... ' sets - ' num2str(length(STUDY.cluster(cls(clus)).comps)) ' components (' num2str(ndip) ' dipoles)' ],'NumberTitle','off'); else dipplot(cluster_dip_models, options{:},'view', [0.5 -0.5 0.5]); for gind = 1:length(options) % remove the 'gui' 'off' option if isstr(options{gind}) if strfind(options{gind}, 'gui') break; end end end options(gind:gind+1) = []; dipinfo.dipmod = cluster_dip_models; dipinfo.op = options; diptitle = [STUDY.cluster(cls(clus)).name ', ' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) ' sets -' ... num2str(length(STUDY.cluster(cls(clus)).comps)) ' components (' num2str(ndip) ' dipoles)' ]; dipinfo.title = diptitle; set(gcf, 'UserData', dipinfo); set(gca,'UserData', dipinfo); rotate3d off; axcopy(gca, ['dipinfo = get(gca, ''''UserData''''); dipplot(dipinfo.dipmod, dipinfo.op{:}); set(gcf, ''''Name'''', dipinfo.title,''''NumberTitle'''',''''off''''); ']); end end % finished the if condition that cluster isn't empty end % finished going over requested clusters end if strcmpi(mode, 'together') % case all clusters are plotted in the same figure (must be a new figure) N = length(cls); rowcols(2) = ceil(sqrt(N)); % Number of rows in the subplot figure. rowcols(1) = ceil(N/rowcols(2)); fig_h = figure; orient tall set(fig_h,'Color', 'black'); set(fig_h,'Name', 'All clusters dipoles','NumberTitle','off'); set(fig_h, 'resize','off'); for l = 1:N len = length(STUDY.cluster(cls(l)).comps); max_r = 0; clear cluster_dip_models; if ~isfield(STUDY.cluster(cls(l)),'dipole') STUDY = std_centroid(STUDY,ALLEEG, cls(l), 'dipole'); elseif isempty(STUDY.cluster(cls(l)).dipole) STUDY = std_centroid(STUDY,ALLEEG, cls(l), 'dipole'); end for k = 1: len abset = STUDY.datasetinfo(STUDY.cluster(cls(l)).sets(1,k)).index; if ~isfield(ALLEEG(abset), 'dipfit') warndlg2(['No dipole information available in dataset ' num2str(abset) ' , abort plotting'], 'Aborting plot dipoles'); return; end comp = STUDY.cluster(cls(l)).comps(k); cluster_dip_models(k).posxyz = ALLEEG(abset).dipfit.model(comp).posxyz; cluster_dip_models(k).momxyz = ALLEEG(abset).dipfit.model(comp).momxyz; cluster_dip_models(k).rv = ALLEEG(abset).dipfit.model(comp).rv; if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model load('-mat', ALLEEG(abset).dipfit.hdmfile); max_r = max(max_r, max(vol.r)); else % old version of dipfit max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r)); end end end % finished going over cluster comps STUDY.cluster(cls(l)).dipole = computecentroid(cluster_dip_models); cluster_dip_models(end + 1) = STUDY.cluster(cls(l)).dipole; dip_color = cell(1,length(cluster_dip_models)); dip_color(1:end-1) = {'b'}; dip_color(end) = {'r'}; options = opt_dipplot; options{end + 1} = 'gui'; options{end + 1} = 'off'; options{end+1} = 'mri'; options{end+1} = ALLEEG(abset).dipfit.mrifile; options{end+1} = 'coordformat'; options{end+1} = ALLEEG(abset).dipfit.coordformat; options{end+1} = 'color'; options{end+1} = dip_color; if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') options{end+1} = 'sphere'; options{end+1} = max_r; else options{end+1} = 'meshdata'; options{end+1} = ALLEEG(abset).dipfit.hdmfile; end subplot(rowcols(1),rowcols(2),l) , dipplot(cluster_dip_models, options{:}); title([ STUDY.cluster(cls(l)).name ' (' num2str(length(unique(STUDY.cluster(cls(l)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(l)).comps)),' ICs)'],'color','white'); %diptitle = [STUDY.cluster(cls(l)).name ', ' num2str(length(unique(STUDY.cluster(cls(l)).sets(1,:)))) 'Ss']; %title(diptitle, 'Color', 'white'); % Complex axcopy %if l == 1 % for gind = 1:length(options) % remove the 'gui' 'off' option % if isstr(options{gind}) % if strfind(options{gind}, 'gui') % break; % end % end % end % options(gind:gind+1) = []; %end %dipinfo.dipmod = cluster_dip_models; %dipinfo.op = options; %dipinfo.title = diptitle; %set(gcf, 'UserData', dipinfo); %set(gca,'UserData', dipinfo); %axcopy(gcf, ['dipinfo = get(gca, ''''UserData''''); dipplot(dipinfo.dipmod, dipinfo.op{:}); set(gcf, ''''Name'''', dipinfo.title,''''NumberTitle'''',''''off'''');']); end %finished going over all clusters set(fig_h, 'resize','on'); end % finished case of 'all' clusters % std_plotcompdip() - Commandline function, to visualizing cluster components dipoles. % Displays the dipoles of specified cluster components with the cluster mean % dipole on separate figures. % To visualize dipoles they first must be stored in the EEG dataset structures % using dipfit(). Only components that have a dipole locations will be displayed, % along with the cluster mean dipole in red. % Usage: % >> [STUDY] = std_plotcompdip(STUDY, ALLEEG, cluster, comps); % Inputs: % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY. % ALLEEG for a STUDY set is typically created using load_ALLEEG(). % cluster - single cluster number. % % Optional inputs: % comps - [numeric vector] -> indices of the cluster components to plot. % 'all' -> plot all the components in the cluster {default: 'all'}. % % Outputs: % STUDY - the input STUDY set structure modified with plotted cluster % dipole mean, to allow quick replotting (unless cluster mean % already existed in the STUDY). % % Example: % >> cluster = 4; comps= 1; % >> [STUDY] = std_plotcompdip(STUDY,ALLEEG, cluster, comps); % Plots component 1 dipole in blue with the cluster 4 mean dipole in red. % % See also pop_clustedit, dipfit, std_dipplot % % Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 08, 2005, [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 STUDY = std_plotcompdip(STUDY, ALLEEG, cls, comp_ind, varargin) if ~exist('cls') error('std_plotcompdip: you must provide a cluster number as an input.'); end if isempty(cls) error('std_plotcompdip: you must provide a cluster number as an input.'); end if nargin == 3 % no components indices were given % Default plot all components of the cluster [STUDY] = std_dipplot(STUDY, ALLEEG, 'clusters', cls); return end for ci = 1:length(comp_ind) abset = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).index; comp = STUDY.cluster(cls).comps(comp_ind(ci)); subject = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).subject; if ~isfield(ALLEEG(abset), 'dipfit') warndlg2(['No dipole information available in dataset ' num2str(abset) ' , abort plotting'], 'Aborting plot dipoles'); return; end if length(comp_ind) == 1 & isempty(ALLEEG(abset).dipfit.model(comp).posxyz) warndlg2(strvcat('There is no dipole information available in', ... [ 'dataset ' num2str(abset) ' for this component, abort plotting']), 'Aborting plot dipoles'); return; end; if ~isfield(STUDY.cluster(cls),'dipole') STUDY = std_centroid(STUDY,ALLEEG, cls , 'dipole'); elseif isempty(STUDY.cluster(cls).dipole) STUDY = std_centroid(STUDY,ALLEEG, cls , 'dipole'); end comp_to_disp = [subject ' / ' 'IC' num2str(comp) ]; cluster_dip_models.posxyz = ALLEEG(abset).dipfit.model(comp).posxyz; cluster_dip_models.momxyz = ALLEEG(abset).dipfit.model(comp).momxyz; cluster_dip_models.rv = ALLEEG(abset).dipfit.model(comp).rv; cluster_dip_models(2) = STUDY.cluster(cls).dipole; if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model load('-mat', ALLEEG(abset).dipfit.hdmfile); max_r = max(vol.r); else max_r = max(ALLEEG(abset).dipfit.vol.r); end dipplot(cluster_dip_models, 'sphere', max_r, 'mri', ALLEEG(abset).dipfit.mrifile,'coordformat', ALLEEG(abset).dipfit.coordformat , ... 'normlen' ,'on', 'pointout' ,'on','color', {'b', 'r'}, 'dipnames', {comp_to_disp [ STUDY.cluster(cls).name ' mean' ] },... 'spheres', 'on', 'verbose', 'off', varargin{:}); else dipplot(cluster_dip_models, 'meshdata', ALLEEG(abset).dipfit.hdmfile, 'mri', ALLEEG(abset).dipfit.mrifile,'coordformat', ALLEEG(abset).dipfit.coordformat , ... 'normlen' ,'on', 'pointout' ,'on','color', {'b', 'r'}, 'dipnames', {comp_to_disp [STUDY.cluster(cls).name ' mean']}, ... 'spheres', 'on', 'verbose', 'off', varargin{:}); end fig_h = gcf; set(fig_h,'Name', [subject ' / ' 'IC' num2str(comp) ', ' STUDY.cluster(cls).name],'NumberTitle','off'); end % ----------------------- % load all dipoles and % compute dipole centroid % DEVELOPMENT: this function % should be the only one to % access dipole information % ----------------------- function STUDY = std_centroid(STUDY,ALLEEG, clsind, tmp); for clust = 1:length(clsind) max_r = 0; len = length(STUDY.cluster(clsind(clust)).comps); tmppos = [ 0 0 0 ]; tmpmom = [ 0 0 0 ]; tmprv = 0; ndip = 0; for k = 1:len fprintf('.'); comp = STUDY.cluster(clsind(clust)).comps(k); abset = STUDY.cluster(clsind(clust)).sets(1,k); if ~isfield(ALLEEG(abset), 'dipfit') warndlg2(['No dipole information available in dataset ' num2str(abset) ], 'Aborting compute centroid dipole'); return; end if ~isempty(ALLEEG(abset).dipfit.model(comp).posxyz) ndip = ndip +1; posxyz = ALLEEG(abset).dipfit.model(comp).posxyz; momxyz = ALLEEG(abset).dipfit.model(comp).momxyz; if size(posxyz,1) == 2 if all(posxyz(2,:) == [ 0 0 0 ]) posxyz(2,:) = []; momxyz(2,:) = []; end; end; tmppos = tmppos + mean(posxyz,1); tmpmom = tmpmom + mean(momxyz,1); tmprv = tmprv + ALLEEG(abset).dipfit.model(comp).rv; if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') if isfield(ALLEEG(abset).dipfit, 'hdmfile') %dipfit 2 spherical model load('-mat', ALLEEG(abset).dipfit.hdmfile); max_r = max(max_r, max(vol.r)); else % old version of dipfit max_r = max(max_r,max(ALLEEG(abset).dipfit.vol.r)); end end end end centroid{clust}.dipole.posxyz = tmppos/ndip; centroid{clust}.dipole.momxyz = tmpmom/ndip; centroid{clust}.dipole.rv = tmprv/ndip; if strcmpi(ALLEEG(abset).dipfit.coordformat, 'spherical') & (~isfield(ALLEEG(abset).dipfit, 'hdmfile')) %old dipfit centroid{clust}.dipole.maxr = max_r; end STUDY.cluster(clsind(clust)).dipole = centroid{clust}.dipole; end fprintf('\n'); % -------------------------------- % new function to compute centroid % was programmed to debug the function % above but is now used in the code % -------------------------------- function dipole = computecentroid(alldipoles) max_r = 0; len = length(alldipoles); dipole.posxyz = [ 0 0 0 ]; dipole.momxyz = [ 0 0 0 ]; dipole.rv = 0; ndip = 0; count = 0; warningon = 1; for k = 1:len if size(alldipoles(k).posxyz,1) == 2 if all(alldipoles(k).posxyz(2,:) == [ 0 0 0 ]) alldipoles(k).posxyz(2,:) = []; alldipoles(k).momxyz(2,:) = []; end; end; if ~isempty(alldipoles(k).posxyz) dipole.posxyz = dipole.posxyz + mean(alldipoles(k).posxyz,1); dipole.momxyz = dipole.momxyz + mean(alldipoles(k).momxyz,1); dipole.rv = dipole.rv + alldipoles(k).rv; count = count+1; elseif warningon disp('Some components do not have dipole information'); warningon = 0; end; end dipole.posxyz = dipole.posxyz/count; dipole.momxyz = dipole.momxyz/count; dipole.rv = dipole.rv/count; if isfield(alldipoles, 'maxr') dipole.maxr = alldipoles(1).max_r; end; function [cluster_dip_models, options] = dipgroups(ALLEEG, STUDY, cls, comp_to_disp, cluster_dip_models, options); % first, extract the subject number for n = 1:length(comp_to_disp) subjectnum(n,1) = str2num(comp_to_disp{n}(1:3)); end % second, extract group info for n = 1:length(subjectnum) subj_group{n,1} = ALLEEG(1,subjectnum(n)).group; end % third, replace the group names with numbers for n = 1:length(subj_group) for m = 1:length(STUDY.group) if strcmp(subj_group{n,1}, STUDY.group{1,m}) subj_groupnum(n,1) = m; break end end end % fourth, compute centroid for each group for n = 1:length(STUDY.group) samegroupIC = find(subj_groupnum==n); cluster_dip_models(1,length(subj_groupnum)+n) = computecentroid(cluster_dip_models(1, samegroupIC)); end % fifth, use subj_groupnum as a type of dipole color %%%%%%%%%%%%%%%%%%%%% color list %%%%%%%%%%%%%%%%%%%%% % This color list was developped for std_envtopo % 16 colors names officially supported by W3C specification for HTML colors{1,1} = [1 1 1]; % White colors{2,1} = [1 1 0]; % Yellow colors{3,1} = [1 0 1]; % Fuchsia colors{4,1} = [1 0 0]; % Red colors{5,1} = [0.75 0.75 0.75]; % Silver colors{6,1} = [0.5 0.5 0.5]; % Gray colors{7,1} = [0.5 0.5 0]; % Olive colors{8,1} = [0.5 0 0.5]; % Purple colors{9,1} = [0.5 0 0]; % Maroon colors{10,1} = [0 1 1]; % Aqua colors{11,1} = [0 1 0]; % Lime colors{12,1} = [0 0.5 0.5]; % Teal colors{13,1} = [0 0.5 0]; % Green colors{14,1} = [0 0 1]; % Blue colors{15,1} = [0 0 0.5]; % Navy colors{16,1} = [0 0 0]; % Black % Silver is twice brighter because silver is used for a background color colors{5,1} = [0.875 0.875 0.875]; % Choosing and sorting 12 colors for line plot, namely Red, Blue, Green, Fuchsia, Lime, Aqua, Maroon, Olive, Purple, Teal, Navy, and Gray selectedcolors = colors([4 13 14 3 11 10 9 7 8 12 15 6]); % determine the new dip colors for n = 1:length(subj_groupnum) dip_color{1,n}=selectedcolors{subj_groupnum(n,1)+1}; end for n = 1:length(STUDY.group) dip_color{1,end+1}= selectedcolors{n+1}; end for n = 1:length(options) if strcmp(options{1,n}, 'color') options{1,n+1} = dip_color; elseif strcmp(options{1,n}, 'dipnames') dipnames = options{1,n+1}; for m = 1:length(STUDY.group) dipnames{1,length(subj_groupnum)+m}= [STUDY.group{1,m} ' mean']; end options{1,n+1} = dipnames; end end
github
ZijingMao/baselineeegtest-master
std_erpplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_erpplot.m
18,380
utf_8
535691c16cdc9853ab40464f8e2402de
% std_erpplot() - Command line function to plot STUDY cluster component ERPs. Either % displays grand mean ERPs for all requested clusters in the same figure, % with ERPs for different conditions (if any) plotted in different colors. % Else, displays ERP for each specified cluster in separate figures % (per condition), each containing the cluster component ERPs plus % the grand mean cluster ERP (in bold). ERPs can be plotted only if % component ERPs were computed and saved in the STUDY EEG % datasets. % These can be computed during pre-clustering using the gui-based % function pop_preclust() or the equivalent command line functions % eeg_createdata() and eeg_preclust(). Called by pop_clustedit(). % and std_propplot(). % Usage: % >> [STUDY] = std_erpplot(STUDY, ALLEEG, key1, val1, key2, val2); % >> [STUDY erpdata erptimes pgroup pcond pinter] = std_erpplot(STUDY, ALLEEG, ...); % % Inputs: % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - global EEGLAB vector of EEG structures for the datasets included % in the STUDY. A STUDY set ALLEEG is typically created by load_ALLEEG(). % Optional inputs for channel plotting: % 'channels' - [numeric vector] specific channel group to plot. By % default, the grand mean channel ERP is plotted (using the % same format as for the cluster component means described % above). Default is to plot all channels. % 'subject' - [numeric vector] In 'changrp' mode (above), index of % the subject(s) to plot. Else by default, plot all components % in the cluster. % 'plotsubjects' - ['on'|'off'] When 'on', plot ERP of all subjects. % 'noplot' - ['on'|'off'] When 'on', only return output values. Default % is 'off'. % 'topoplotopt' - [cell array] options for topoplot plotting. % % Optional inputs for component plotting: % 'clusters' - [numeric vector|'all'] indices of clusters to plot. % If no component indices ('comps' below) are given, the average % ERPs of the requested clusters are plotted in the same figure, % with ERPs for different conditions (and groups if any) plotted % in different colors. In 'comps' (below) mode, ERPS for each % specified cluster are plotted in separate figures (one per % condition), each overplotting cluster component ERPs plus the % average cluster ERP in bold. Note this parameter has no effect % if the 'comps' option (below) is used. {default: 'all'} % 'comps' - [numeric vector|'all'] indices of the cluster components to plot. % Note that 'comps', 'all' is equivalent to 'plotsubjects', 'on'. % % Other optional inputs: % 'key','val' - All optional inputs to pop_erpparams() are also accepted here % to plot subset of time, statistics etc. The values used by default % are the ones set using pop_erpparams() and stored in the % STUDY structure. % % Outputs: % STUDY - the input STUDY set structure with plotted cluster mean % ERPs data to allow quick replotting % erpdata - [cell] ERP data for each condition, group and subjects. % size of cell array is [nconds x ngroups]. Size of each element % is [times x subjects] for data channels or [times x components] % for component clusters. This array may be gicen as input % directly to the statcond() function or std_stats function % to compute statistics. % erptimes - [array] ERP time point latencies. % pgroup - [array or cell] p-values group statistics. Output of the % statcond() function. % pcond - [array or cell] condition statistics. Output of the statcond() % function. % pinter - [array or cell] groups x conditions statistics. Output of % statcond() function. % % Example: % >> [STUDY] = std_erpplot(STUDY,ALLEEG, 'clusters', 2, 'comps', 'all'); % % Plot cluster-2 component ERPs plus the mean ERP in bold. % % See also pop_clustedit(), pop_preclust(), eeg_createdata(), eeg_preclust(). std_propplot() % % Authors: Arnaud Delorme, CERCO, August, 2006- % Copyright (C) Arnaud Delorme, [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 [STUDY, erpdata, alltimes, pgroup, pcond, pinter] = std_erpplot(STUDY, ALLEEG, varargin) if nargin < 2 help std_erpplot; return; end; erpdata = []; alltimes = []; pgroup = []; pcond = []; pinter = []; % find datatype and default options % --------------------------------- dtype = 'erp'; for ind = 1:2:length(varargin) if strcmpi(varargin{ind}, 'datatype') dtype = varargin{ind+1}; end; end; % get parameters % -------------- eval( [ 'tmp = pop_' dtype 'params(STUDY, varargin{:});' ... 'params = tmp.etc.' dtype 'params; clear tmp;' ] ); statstruct.etc = STUDY.etc; statstruct.design = STUDY.design; %added by behnam statstruct.currentdesign = STUDY.currentdesign; %added by behnam statstruct = pop_statparams(statstruct, varargin{:}); stats = statstruct.etc.statistics; stats.fieldtrip.channelneighbor = struct([]); % asumes one channel or 1 component % potentially missing fields % -------------------------- fields = { 'filter' 'subtractsubjectmean' 'timerange' 'freqrange' 'topotime' 'topofreq' 'averagechan'}; defaultval = { [] 'off' [] [] [] [] }; for ind=1:length(fields) if ~isfield(params, fields{ind}), params = setfield(params, fields{ind}, defaultval{ind}); end; end; % decode parameters % ----------------- if isempty(varargin) tmplocs = eeg_mergelocs(ALLEEG.chanlocs); options.channels = { tmplocs.labels }; else options = mystruct(varargin); end; options = myrmfield( options, myfieldnames(params)); options = myrmfield( options, myfieldnames(stats)); options = myrmfield( options, { 'threshold' 'statistics' } ); % for backward compatibility opt = finputcheck( options, ... { 'design' 'integer' [] STUDY.currentdesign; 'plotstderr' 'string' [] 'off'; 'channels' 'cell' [] {}; 'clusters' 'integer' [] []; 'datatype' 'string' { 'erp','spec' } 'erp'; 'mode' 'string' [] ''; % for backward compatibility (now used for statistics) 'comps' { 'string','integer' } [] []; % for backward compatibility 'statmode' 'string' { 'subjects','common','trials' } 'subjects'; % ignored 'plotmode' 'string' { 'normal','condensed' } 'normal'; 'unitx' 'string' { 'ms','Hz' } 'ms'; 'plotsubjects' 'string' { 'on','off' } 'off'; 'noplot' 'string' { 'on','off' } 'off'; 'topoplotopt' 'cell' {} { 'style' 'both' }; 'subject' 'string' [] '' }, 'std_erpplot'); if isstr(opt), error(opt); end; if isstr(opt.comps), opt.comps = []; opt.plotsubjects = 'on'; end; if ~isempty(params.topofreq) && strcmpi(opt.datatype, 'spec'), params.topotime = params.topofreq; end; if ~isempty(params.freqrange), params.timerange = params.freqrange; end; datatypestr = upper(opt.datatype); if strcmpi(datatypestr, 'spec'), datatypestr = 'Spectrum'; end; % ======================================================================= % below this line, all the code should be non-specific to ERP or spectrum % ======================================================================= allconditions = STUDY.design(opt.design).variable(1).value; allgroups = STUDY.design(opt.design).variable(2).value; paired = { STUDY.design(opt.design).variable(1).pairing ... STUDY.design(opt.design).variable(2).pairing }; stats.paired = paired; % for backward compatibility % -------------------------- if strcmpi(opt.mode, 'comps'), opt.plotsubjects = 'on'; end; if strcmpi(stats.singletrials, 'off') && ((~isempty(opt.subject) || ~isempty(opt.comps))) if strcmpi(stats.condstats, 'on') || strcmpi(stats.groupstats, 'on') stats.groupstats = 'off'; stats.condstats = 'off'; disp('No statistics for single subject/component, to get statistics compute single-trial measures'); end; end; if ~isnan(params.topotime) & length(opt.channels) < 5 warndlg2(strvcat('ERP parameters indicate that you wish to plot scalp maps', 'Select at least 5 channels to plot topography')); return; end; plotcurveopt = {}; if length(opt.clusters) > 1 plotcurveopt = { 'figure' 'off' }; params.plotconditions = 'together'; params.plotgroups = 'together'; stats.condstats = 'off'; stats.groupstats = 'off'; end; % if length(opt.channels) > 1 && strcmpi(opt.plotconditions, 'together') && strcmpi(opt.plotgroups, 'together') % plotcurveopt = { 'figure' 'off' }; % opt.plotconditions = 'together'; % opt.plotgroups = 'together'; % opt.condstats = 'off'; % opt.groupstats = 'off'; % end; alpha = fastif(strcmpi(stats.mode, 'eeglab'), stats.eeglab.alpha, stats.fieldtrip.alpha); mcorrect = fastif(strcmpi(stats.mode, 'eeglab'), stats.eeglab.mcorrect, stats.fieldtrip.mcorrect); method = fastif(strcmpi(stats.mode, 'eeglab'), stats.eeglab.method, ['Fieldtrip ' stats.fieldtrip.method ]); plotcurveopt = { plotcurveopt{:} ... 'ylim', params.ylim, ... 'threshold', alpha ... 'unitx' opt.unitx, ... 'filter', params.filter, ... 'plotgroups', params.plotgroups, ... 'plotconditions', params.plotconditions }; % channel plotting % ---------------- if ~isempty(opt.channels) chaninds = 1:length(opt.channels); if strcmpi(opt.datatype, 'erp') [STUDY erpdata alltimes] = std_readerp(STUDY, ALLEEG, 'channels', opt.channels(chaninds), 'timerange', params.timerange, ... 'subject', opt.subject, 'singletrials', stats.singletrials, 'design', opt.design); else [STUDY erpdata alltimes] = std_readspec(STUDY, ALLEEG, 'channels', opt.channels(chaninds), 'freqrange', params.freqrange, ... 'rmsubjmean', params.subtractsubjectmean, 'subject', opt.subject, 'singletrials', stats.singletrials, 'design', opt.design); end; if strcmpi(params.averagechan, 'on') && length(chaninds) > 1 for index = 1:length(erpdata(:)) erpdata{index} = squeeze(mean(erpdata{index},2)); end; end; if isempty(erpdata), return; end; % select specific time % -------------------- if ~isempty(params.topotime) & ~isnan(params.topotime) [tmp ti1] = min(abs(alltimes-params.topotime(1))); [tmp ti2] = min(abs(alltimes-params.topotime(end))); for condind = 1:length(erpdata(:)) if ~isempty(erpdata{condind}) erpdata{condind} = mean(erpdata{condind}(ti1:ti2,:,:),1); end; end; end; % compute statistics % ------------------ if (isempty(params.topotime) || any(isnan(params.topotime))) && length(alpha) > 1 alpha = alpha(1); end; if ~isempty(params.topotime) && all(~isnan(params.topotime)) statstruct = std_prepare_neighbors(statstruct, ALLEEG, 'channels', opt.channels); stats.fieldtrip.channelneighbor = statstruct.etc.statistics.fieldtrip.channelneighbor; end; [pcond pgroup pinter] = std_stat(erpdata, stats); if (~isempty(pcond) && length(pcond{1}) == 1) || (~isempty(pgroup) && length(pgroup{1}) == 1), pcond = {}; pgroup = {}; pinter = {}; end; % single subject STUDY if length(opt.channels) > 5 && ndims(erpdata{1}) < 3, pcond = {}; pgroup = {}; pinter = {}; end; % topo plotting for single subject if strcmpi(opt.noplot, 'on') return; end; % get titles (not included in std_erspplot because it is not possible % to merge channels for that function % ----------------------------------- locs = eeg_mergelocs(ALLEEG.chanlocs); locs = locs(std_chaninds(STUDY, opt.channels(chaninds))); if strcmpi(params.averagechan, 'on') && length(chaninds) > 1 chanlabels = { locs.labels }; chanlabels(2,:) = {','}; chanlabels(2,end) = {''}; locs(1).labels = [ chanlabels{:} ]; locs(2:end) = []; end; [alltitles alllegends ] = std_figtitle('threshold', alpha, 'mcorrect', mcorrect, 'condstat', stats.condstats, 'cond2stat', stats.groupstats, ... 'statistics', method, 'condnames', allconditions, 'plotsubjects', opt.plotsubjects, 'cond2names', allgroups, 'chanlabels', { locs.labels }, ... 'subject', opt.subject, 'valsunit', opt.unitx, 'vals', params.topotime, 'datatype', datatypestr, 'cond2group', params.plotgroups, 'condgroup', params.plotconditions); % plot % ---- if ~isempty(params.topotime) && all(~isnan(params.topotime)) std_chantopo(erpdata, 'groupstats', pgroup, 'condstats', pcond, 'interstats', pinter, 'caxis', params.ylim, ... 'chanlocs', locs, 'threshold', alpha, 'titles', alltitles, 'topoplotopt', opt.topoplotopt); else std_plotcurve(alltimes, erpdata, 'groupstats', pgroup, 'legend', alllegends, 'condstats', pcond, 'interstats', pinter, ... 'chanlocs', locs, 'titles', alltitles, 'plotsubjects', opt.plotsubjects, 'plotstderr', opt.plotstderr, ... 'condnames', allconditions, 'groupnames', allgroups, plotcurveopt{:}); end; set(gcf,'name',['Channel ' datatypestr ]); axcopy(gca); else % plot component % -------------- if length(opt.clusters) > 1, figure('color', 'w'); end; nc = ceil(sqrt(length(opt.clusters))); nr = ceil(length(opt.clusters)/nc); comp_names = {}; for index = 1:length(opt.clusters) if length(opt.clusters) > 1, subplot(nr,nc,index); end; if strcmpi(opt.datatype, 'erp') [STUDY erpdata alltimes] = std_readerp(STUDY, ALLEEG, 'clusters', opt.clusters(index), 'timerange', params.timerange, ... 'component', opt.comps, 'singletrials', stats.singletrials, 'design', opt.design); else [STUDY erpdata alltimes] = std_readspec(STUDY, ALLEEG, 'clusters', opt.clusters(index), 'freqrange', params.freqrange, ... 'rmsubjmean', params.subtractsubjectmean, 'component', opt.comps, 'singletrials', stats.singletrials, 'design', opt.design); end; if isempty(erpdata), return; end; % plot specific component % ----------------------- if ~isempty(opt.comps) comp_names = { STUDY.cluster(opt.clusters(index)).comps(opt.comps) }; opt.subject = STUDY.datasetinfo(STUDY.cluster(opt.clusters(index)).sets(1,opt.comps)).subject; end; stats.paired = paired; [pcond pgroup pinter] = std_stat(erpdata, stats); if strcmpi(opt.noplot, 'on'), return; end; [alltitles alllegends ] = std_figtitle('threshold', alpha, 'plotsubjects', opt.plotsubjects, 'mcorrect', mcorrect, 'condstat', stats.condstats, 'cond2stat', stats.groupstats, ... 'statistics', method, 'condnames', allconditions, 'cond2names', allgroups, 'clustname', STUDY.cluster(opt.clusters(index)).name, 'compnames', comp_names, ... 'subject', opt.subject, 'valsunit', opt.unitx, 'vals', params.topotime, 'datatype', datatypestr, 'cond2group', params.plotgroups, 'condgroup', params.plotconditions); if length(opt.clusters) > 1 && index < length(opt.clusters), alllegends = {}; end; std_plotcurve(alltimes, erpdata, 'condnames', allconditions, 'legend', alllegends, 'groupnames', allgroups, 'plotstderr', opt.plotstderr, ... 'titles', alltitles, 'groupstats', pgroup, 'condstats', pcond, 'interstats', pinter, ... 'plotsubjects', opt.plotsubjects, plotcurveopt{:}); end; set(gcf,'name', ['Component ' datatypestr ] ); axcopy(gca); end; % remove fields and ignore fields who are absent % ---------------------------------------------- function s = myrmfield(s, f); for index = 1:length(f) if isfield(s, f{index}) s = rmfield(s, f{index}); end; end; % convert to structure (but take into account cells) % -------------------------------------------------- function s = mystruct(v); for index=1:length(v) if iscell(v{index}) v{index} = { v{index} }; end; end; try s = struct(v{:}); catch, error('Parameter error'); end; % convert to structure (but take into account cells) % -------------------------------------------------- function s = myfieldnames(v); s = fieldnames(v); if isfield(v, 'eeglab') s2 = fieldnames(v.eeglab); s = { s{:} s2{:} }; end; if isfield(v, 'fieldtrip') s3 = fieldnames(v.fieldtrip); for index=1:length(s3) s3{index} = [ 'fieldtrip' s3{index} ]; end; s = { s{:} s3{:} }; end;
github
ZijingMao/baselineeegtest-master
std_preclust.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_preclust.m
27,008
utf_8
90006ebed95a949b1fd306df6e5d0454
% std_preclust() - select measures to be included in computation of a preclustering array. % This array is used by pop_clust() to find component clusters from a % specified parent cluster. % Selected measures (dipole location, ERPs, spectra, scalp maps, ERSPs, % and/or ITCs) should already be precomputed using pop-precomp(). Each % feature dimension is reduced by PCA decomposition. These PCA matrices % (one per measure) are concatenated and used as input to the clustering % algorithm in pop_clust(). Follow with pop_clust(). % See Example below: % % >> [STUDY,ALLEEG] = std_preclust(STUDY,ALLEEG); % prepare to cluster all comps % % in all sets on all measures % % >> [STUDY,ALLEEG] = std_preclust(STUDY,ALLEEG, clustind, preproc1, preproc2...); % % prepare to cluster specifed % % cluster on specified measures % Required inputs: % STUDY - an EEGLAB STUDY set of loaded EEG structures % ALLEEG - ALLEEG vector of one or more loaded EEG dataset structures % % Optional inputs: % clustind - a cluster index for further (hierarchical) clustering - % for example to cluster a spectrum-based mu-rhythm cluster into % dipole location-based left mu and right mu sub-clusters. % Should be empty for first stage (whole-STUDY) clustering {default: []} % % preproc - {'command' 'key1' val1 'key2' val2 ...} component clustering measures to prepare % % * 'command' = component measure to compute: % 'erp' = cluster on the component ERPs, % 'dipoles' = cluster on the component [X Y Z] dipole locations % 'spec' = cluster on the component log activity spectra (in dB) % (with the baseline mean dB spectrum subtracted). % 'scalp' = cluster on component (topoplot()) scalp maps % (or on their absolute values), % 'scalpLaplac' = cluster on component (topoplot()) laplacian scalp maps % (or on their absolute values), % 'scalpGrad' = cluster on the (topoplot()) scalp map gradients % (or on their absolute values), % 'ersp' = cluster on components ERSP. (requires: 'cycles', % 'freqrange', 'padratio', 'timewindow', 'alpha'). % 'itc' = cluster on components ITC.(requires: 'cycles', % 'freqrange', 'padratio', 'timewindow', 'alpha'). % 'finaldim' = final number of dimensions. Enables second-level PCA. % By default this command is not used (see Example below). % % * 'key' optional keywords and [valuess] used to compute the above 'commands': % 'npca' = [integer] number of principal components (PCA dimension) of % the selected measures to retain for clustering. {default: 5} % 'norm' = [0|1] 1 -> normalize the PCA components so the variance of % first principal component is 1 (useful when using several % clustering measures - 'ersp','scalp',...). {default: 1} % 'weight' = [integer] weight with respect to other clustering measures. % 'freqrange' = [min max] frequency range (in Hz) to include in activity % spectrum, 'ersp', and 'itc' measures. % 'timewindow' = [min max] time window (in sec) to include in 'erp', % 'ersp', and 'itc' measures. % 'abso' = [0|1] 1 = use absolute values of topoplot(), gradient, or % Laplacian maps {default: 1} % 'funarg' = [cell array] optional function arguments for mean spectrum % calculation (>> help spectopo) {default: none} % Outputs: % STUDY - the input STUDY set with pre-clustering data added, for use by pop_clust() % ALLEEG - the input ALLEEG vector of EEG dataset structures, modified by adding preprocessing % data as pointers to Matlab files that hold the pre-clustering component measures. % % Example: % >> [STUDY ALLEEG] = std_preclust(STUDY, ALLEEG, [],... % { 'spec' 'npca' 10 'norm' 1 'weight' 1 'freqrange' [ 3 25 ] } , ... % { 'erp' 'npca' 10 'norm' 1 'weight' 2 'timewindow' [ 350 500 ] } ,... % { 'scalp' 'npca' 10 'norm' 1 'weight' 2 'abso' 1 } , ... % { 'dipoles' 'norm' 1 'weight' 15 } , ... % { 'ersp' 'npca' 10 'freqrange' [ 3 25 ] 'cycles' [ 3 0.5 ] 'alpha' 0.01 .... % 'padratio' 4 'timewindow' [ -1600 1495 ] 'norm' 1 'weight' 1 } ,... % { 'itc' 'npca' 10 'freqrange' [ 3 25 ] 'cycles' [ 3 0.5 ] 'alpha' 0.01 ... % 'padratio' 4 'timewindow' [ -1600 1495 ] 'norm' 1 'weight' 1 }, ... % { 'finaldim' 'npca' 10 }); % % % This prepares, for initial clustering, all components in the STUDY datasets % % except components with dipole model residual variance (see function % % std_editset() for how to select such components). % % Clustering will be based on the components' mean spectra in the [3 25] Hz % % frequency range, on the components' ERPs in the [350 500] ms time window, % % on the (absolute-value) component scalp maps, on the equivalent dipole % % locations, and on the component mean ERSP and ITC images. % % The final keyword specifies final PCA dimension reduction to 10 % % principal dimensions. See the clustering tutorial for more details. % % Authors: Arnaud Delorme, Hilit Serby & Scott Makeig, SCCN, INC, UCSD, May 13, 2004 % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, May 13,2004, [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 [ STUDY, ALLEEG ] = std_preclust(STUDY, ALLEEG, cluster_ind, varargin) if nargin < 2 help std_preclust; return; end; if nargin == 2 cluster_ind = 1; % default to clustering the whole STUDY end % check dataset length consistency before computing % ------------------------------------------------- pnts = ALLEEG(STUDY.datasetinfo(1).index).pnts; srate = ALLEEG(STUDY.datasetinfo(1).index).srate; xmin = ALLEEG(STUDY.datasetinfo(1).index).xmin; xmax = ALLEEG(STUDY.datasetinfo(1).index).xmax; for index = 1:length(STUDY.datasetinfo) ind = STUDY.datasetinfo(index).index; if srate ~= ALLEEG(ind).srate, error(sprintf('Dataset %d does not have the same sampling rate as dataset 1', ind)); end; if ~all([ ALLEEG.trials ] == 1) if abs(xmin-ALLEEG(ind).xmin) > 1e-7, warning(sprintf('Dataset %d does not have the same time limit as dataset 1', ind)); end; if abs(xmax-ALLEEG(ind).xmax) > 1e-7, warning(sprintf('Dataset %d does not have the same time limit as dataset 1', ind)); end; if pnts ~= ALLEEG(ind).pnts, error(sprintf('Dataset %d does not have the same number of point as dataset 1', ind)); end; end; end; % Get component indices that are part of the cluster % -------------------------------------------------- if isempty(cluster_ind) cluster_ind = 1; end; if length(cluster_ind) ~= 1 error('Only one cluster can be sub-clustered. To sub-cluster multiple clusters, first merge them.'); end % % the goal of this code below is to find the components in the cluster % % of interest for each set of condition % for k = 1:size(STUDY.setind,2) % % Find the first entry in STUDY.setind(:,k) that is non-NaN. We only need one since % % components are the same across conditions. % for ri = 1:size(STUDY.setind,1) % if ~isnan(STUDY.setind(ri,k)), break; end % end % sind = find(STUDY.cluster(cluster_ind).sets(ri,:) == STUDY.setind(ri,k)); % succompind{k} = STUDY.cluster(cluster_ind).comps(sind); % end; % for ind = 1:size(STUDY.setind,2) % succompind{ind} = succompind{ind}(find(succompind{ind})); % remove zeros % % (though there should not be any? -Arno) % succompind{ind} = sort(succompind{ind}); % sort the components % end; % scan all commands to see if file exist % -------------------------------------- % for index = 1:length(varargin) % scan commands % strcom = varargin{index}{1}; % if strcmpi(strcom, 'scalp') || strcmpi(strcom, 'scalplaplac') || strcmpi(strcom, 'scalpgrad') % strcom = 'topo'; % end; % if ~strcmpi(strcom, 'dipoles') && ~strcmpi(strcom, 'finaldim') % tmpfile = fullfile( ALLEEG(1).filepath, [ ALLEEG(1).filename(1:end-3) 'ica' strcom ]); % if exist(tmpfile) ~= 2 % %error([ 'Could not find "' upper(strcom) '" file, they must be precomputed' ]); % end; % end; % end; % Decode input arguments % ---------------------- update_flag = 0; rv = 1; secondlevpca = Inf; indrm = []; for index = 1:length(varargin) % scan commands strcom = varargin{index}{1}; if strcmpi(strcom,'dipselect') update_flag = 1; rv = varargin{index}{3}; indrm = [indrm index]; %remove this command elseif strcmpi(strcom,'finaldim') % second level pca secondlevpca = varargin{index}{3}; indrm = [indrm index]; %remove this command end end varargin(indrm) = []; %remove commands % Scan which component to remove (no dipole info) % ----------------------------------------------- if update_flag % dipole information is used to select components error('Update flag is obsolete'); end; % scan all commands % ----------------- clustdata = []; erspquery = 0; for index = 1:length(varargin) % decode inputs % ------------- strcom = varargin{index}{1}; if any(strcom == 'X'), disp('character ''X'' found in command'); end; %defult values npca = NaN; norm = 1; weight = 1; freqrange = []; timewindow = []; abso = 1; fun_arg = []; savetrials = 'off'; recompute = 'on'; for subind = 2:2:length(varargin{index}) switch varargin{index}{subind} case 'npca' npca = varargin{index}{subind+1}; case 'norm' norm = varargin{index}{subind+1}; case 'weight' weight = varargin{index}{subind+1}; case 'freqrange' freqrange = varargin{index}{subind+1}; case 'timewindow' timewindow = varargin{index}{subind+1}; case 'abso' abso = varargin{index}{subind+1}; case 'savetrials' error('You may now use the function std_precomp to precompute measures'); case 'cycles' error('You may now use the function std_precomp to precompute measures'); case 'alpha' error('You may now use the function std_precomp to precompute measures'); case 'padratio' error('You may now use the function std_precomp to precompute measures'); otherwise fun_arg{length(fun_arg)+1} = varargin{index}{subind+1}; end end % scan datasets % ------------- if strcmpi(strcom, 'scalp'), scalpmodif = 'none'; elseif strcmpi(strcom, 'scalpLaplac'), scalpmodif = 'laplacian'; else scalpmodif = 'gradient'; end; % check that all datasets are in preclustering for current design % --------------------------------------------------------------- tmpstruct = std_setcomps2cell(STUDY, STUDY.cluster(cluster_ind).sets, STUDY.cluster(cluster_ind).comps); alldatasets = unique_bc(STUDY.cluster(cluster_ind).sets(:)); if length(alldatasets) < length(STUDY.datasetinfo) && cluster_ind == 1 error( [ 'Some datasets not included in preclustering' 10 ... 'because of partial STUDY design. You need to' 10 ... 'use a STUDY design that includes all datasets.' ]); end; for si = 1:size(STUDY.cluster(cluster_ind).sets,2) % test consistency of the .set structure % -------------------------------------- if strcmpi(strcom, 'erp') || strcmpi(strcom, 'spec') || strcmpi(strcom, 'ersp') || strcmpi(strcom, 'itc') if any(isnan(STUDY.cluster(cluster_ind).sets(:))) error( [ 'std_preclust error: some datasets do not have ICA pairs.' 10 ... 'Look for NaN values in STUDY.cluster(1).sets which' 10 ... 'indicate missing datasets. FOR CLUSTERING, YOU MAY ONLY' 10 ... 'USE DIPOLE OR SCALP MAP CLUSTERING.' ]); end; end; switch strcom % select ica component ERPs % ------------------------- case 'erp', % read and concatenate all cells for this specific set % of identical ICA decompositions STUDY.cluster = checkcentroidfield(STUDY.cluster, 'erp', 'erp_times'); tmpstruct = std_setcomps2cell(STUDY, STUDY.cluster(cluster_ind).sets(:,si), STUDY.cluster(cluster_ind).comps(si)); cellinds = [ tmpstruct.setinds{:} ]; compinds = [ tmpstruct.allinds{:} ]; cells = STUDY.design(STUDY.currentdesign).cell(cellinds); fprintf('Pre-clustering array row %d, adding ERP for design %d cell(s) [%s] component %d ...\n', si, STUDY.currentdesign, int2str(cellinds), compinds(1)); X = std_readfile( cells, 'components', compinds, 'timelimits', timewindow, 'measure', 'erp'); X = abs(X(:)'); % take the absolute value of the ERP to avoid polarities issues % select ica scalp maps % -------------------------- case { 'scalp' 'scalpLaplac' 'scalpGrad' } idat = STUDY.datasetinfo(STUDY.cluster(cluster_ind).sets(:,si)).index; icomp = STUDY.cluster(cluster_ind).comps(si); fprintf('Pre-clustering array row %d, adding interpolated scalp maps for dataset %d component %d...\n', si, idat, icomp); X = std_readtopo(ALLEEG, idat, icomp, scalpmodif, 'preclust'); % select ica comp spectra % ----------------------- case 'spec', % read and concatenate all cells for this specific set % of identical ICA decompositions STUDY.cluster = checkcentroidfield(STUDY.cluster, 'spec', 'spec_freqs'); tmpstruct = std_setcomps2cell(STUDY, STUDY.cluster(cluster_ind).sets(:,si), STUDY.cluster(cluster_ind).comps(si)); cellinds = [ tmpstruct.setinds{:} ]; compinds = [ tmpstruct.allinds{:} ]; cells = STUDY.design(STUDY.currentdesign).cell(cellinds); fprintf('Pre-clustering array row %d, adding spectrum for design %d cell(s) [%s] component %d ...\n', si, STUDY.currentdesign, int2str(cellinds), compinds(1)); X = std_readfile( cells, 'components', compinds, 'freqlimits', freqrange, 'measure', 'spec'); if size(X,2) > 1, X = X - repmat(mean(X,2), [1 size(X,2)]); end; X = X - repmat(mean(X,1), [size(X,1) 1]); X = X(:)'; % select dipole information % ------------------------- case 'dipoles' idat = STUDY.datasetinfo(STUDY.cluster(cluster_ind).sets(1,si)).index; icomp = STUDY.cluster(cluster_ind).comps(si); fprintf('Pre-clustering array row %d, adding dipole for dataset %d component %d...\n', si, idat, icomp); try % select among 3 sub-options % -------------------------- ldip = 1; if size(ALLEEG(idat).dipfit.model(icomp).posxyz,1) == 2 % two dipoles model if any(ALLEEG(idat).dipfit.model(icomp).posxyz(1,:)) ... && any(ALLEEG(idat).dipfit.model(icomp).posxyz(2,:)) %both dipoles exist % find the leftmost dipole [garb ldip] = max(ALLEEG(idat).dipfit.model(icomp).posxyz(:,2)); elseif any(ALLEEG(idat).dipfit.model(icomp).posxyz(2,:)) ldip = 2; % the leftmost dipole is the only one that exists end end X = ALLEEG(idat).dipfit.model(icomp).posxyz(ldip,:); catch error([ sprintf('Some dipole information is missing (e.g. component %d of dataset %d)', icomp, idat) 10 ... 'Components are not assigned a dipole if residual variance is too high so' 10 ... 'in the STUDY info editor, remember to select component by residual' 10 ... 'variance (column "select by r.v.") prior to preclustering them.' ]); end % cluster on ica ersp / itc values % -------------------------------- case {'ersp', 'itc' } % read and concatenate all cells for this specific set % of identical ICA decompositions STUDY.cluster = checkcentroidfield(STUDY.cluster, 'ersp', 'ersp_times', 'ersp_freqs', 'itc', 'itc_times', 'itc_freqs'); tmpstruct = std_setcomps2cell(STUDY, STUDY.cluster(cluster_ind).sets(:,si), STUDY.cluster(cluster_ind).comps(si)); cellinds = [ tmpstruct.setinds{:} ]; compinds = [ tmpstruct.allinds{:} ]; cells = STUDY.design(STUDY.currentdesign).cell(cellinds); fprintf('Pre-clustering array row %d, adding %s for design %d cell(s) [%s] component %d ...\n', si, upper(strcom), STUDY.currentdesign, int2str(cellinds), compinds(1)); X = std_readfile( cells, 'components', compinds, 'timelimits', timewindow, 'measure', strcom); end; % copy data in the array % ---------------------- if ~isreal(X) X = abs(X); end; % for ITC data X = reshape(X, 1, numel(X)); if si == 1, data = zeros(size(STUDY.cluster(cluster_ind).sets,2),length(X)); end; data(si,:) = X; try data(si,:) = X; catch, error([ 'This type of pre-clustering requires that all subjects' 10 ... 'be represented for all combination of selected independent' 10 ... 'variables in the current STUDY design. In addition, for each' 10 ... 'different ICA decomposition included in the STUDY (some' 10 ... 'datasets may have the same decomposition), at least one' 10 ... 'dataset must be represented.' ]); end; end; % end scan datasets % adjust number of PCA values % --------------------------- if isnan(npca), npca = 5; end; % default number of components if npca >= size(data,2) % no need to run PCA, just copy the data. % But still run it to "normalize" coordinates % -------------------------------------- npca = size(data,2); end; if npca >= size(data,1) % cannot be more than the number of components npca = size(data,1); end; if ~strcmp(strcom, 'dipoles') fprintf('PCA dimension reduction to %d for command ''%s'' (normalize:%s; weight:%d)\n', ... npca, strcom, fastif(norm, 'on', 'off'), weight); else fprintf('Retaining the three-dimensional dipole locations (normalize:%s; weight:%d)\n', ... fastif(norm, 'on', 'off'), weight); end % run PCA to reduce data dimension % -------------------------------- switch strcom case {'ersp','itc'} dsflag = 1; while dsflag try, clustdatatmp = runpca( double(data.'), npca, 1); dsflag = 0; catch, % downsample frequency by 2 and times by 2 % ---------------------------------------- data = data(:,1:2:end); %idat = STUDY.datasetinfo(STUDY.setind(1)).index; %[ tmp freqs times ] = std_readersp( ALLEEG, idat, succompind{1}(1)); %[data freqs times ] = erspdownsample(data,4, freqs,times,Ncond); if strcmp(varargin{index}(end-1) , 'downsample') varargin{index}(end) = {celltomat(varargin{index}(end)) + 4}; else varargin{index}(end+1) = {'downsample'}; varargin{index}(end+1) = {4}; end end end clustdatatmp = clustdatatmp.'; case 'dipoles' % normalize each cordinate by the std dev of the radii normval = std(sqrt(data(:,1).^2 + data(:,2).^2 + data(:,3).^2)); clustdatatmp = data./normval; norm = 0; case 'erp' clustdatatmp = runpca( double(data.'), npca, 1); clustdatatmp = abs(clustdatatmp.'); otherwise clustdatatmp = runpca( double(data.'), npca, 1); clustdatatmp = clustdatatmp.'; end if norm %normalize the first pc std to 1 normval = std(clustdatatmp(:,1)); for icol = 1:size(clustdatatmp,2) clustdatatmp(:,icol) = clustdatatmp(:,icol) /normval; end; end; if weight ~= 1 clustdata(:,end+1:end+size(clustdatatmp,2)) = clustdatatmp * weight; else clustdata(:,end+1:end+size(clustdatatmp,2)) = clustdatatmp; end if strcmpi(strcom, 'itc') | strcmpi(strcom, 'ersp') erspmode = 'already_computed'; end; end % Compute a second PCA of the already PCA'd data if there are too many PCA dimensions. % ------------------------------------------------------------------------------------ if size(clustdata,2) > secondlevpca fprintf('Performing second-level PCA: reducing dimension from %d to %d \n', ... size(clustdata,2), secondlevpca); clustdata = runpca( double(clustdata.'), secondlevpca, 1); clustdata = clustdata.'; end STUDY.etc.preclust.preclustdata = clustdata; STUDY.etc.preclust.preclustparams = varargin; if isfield(STUDY.etc.preclust, 'preclustcomps') STUDY.etc.preclust = rmfield(STUDY.etc.preclust, 'preclustcomps'); end; % The preclustering level is equal to the parent cluster that the components belong to. if ~isempty(cluster_ind) STUDY.etc.preclust.clustlevel = cluster_ind; else STUDY.etc.preclust.clustlevel = 1; % No parent cluster (cluster on all components in STUDY). end return % erspdownsample() - down samples component ERSP/ITC images if the % PCA operation in the clustering feature reduction step fails. % This is a helper function called by eeg_preclust(). function [dsdata, freqs, times] = erspdownsample(data, n, freqs,times,cond) len = length(freqs)*length(times); %size of ERSP nlen = ceil(length(freqs)/2)*ceil(length(times)/2); %new size of ERSP dsdata = zeros(size(data,1),cond*nlen); for k = 1:cond tmpdata = data(:,1+(k-1)*len:k*len); for l = 1:size(data,1) % go over components tmpersp = reshape(tmpdata(l,:)',length(freqs),length(times)); tmpersp = downsample(tmpersp.', n/2).'; %downsample times tmpersp = downsample(tmpersp, n/2); %downsample freqs dsdata(l,1+(k-1)*nlen:k*nlen) = tmpersp(:)'; end end % the function below checks the precense of the centroid field function cluster = checkcentroidfield(cluster, varargin); for kk = 1:length(cluster) if ~isfield('centroid', cluster(kk)), cluster(kk).centroid = []; end; for vi = 1:length(varargin) if isfield(cluster(kk).centroid, varargin{vi}) cluster(kk).centroid = rmfield(cluster(kk).centroid, varargin{vi}); end; end; end;
github
ZijingMao/baselineeegtest-master
std_filecheck.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_filecheck.m
8,785
utf_8
ed6e134b227c42300f92308c99c82ecc
% std_filecheck() - Check if ERSP or SPEC file contain specific parameters. % This file must contain a Matlab structure with a field % named 'parameter'. The content of this field will be % compared to the 'params' input. If they are identical % the output flag will indicate that recomputing this % file is not necessary. If they are different, the user % is queried ('guion' option) to see if he wishes to use % the new parameters and recompute the file (not done in % this function) or if he wishes to use the parameters % of the file on disk. % % Usage: % >> [ recompflag params ] = std_filecheck(filename, params, mode, ignorefields); % % Inputs: % filename - [string] file containing a given measure (ERSP data for % instance). % params - [cell array or structure] cell array of parameters or % structure. This is compared to the 'parameters' field % in the data file. % mode - ['guion'|'usedisk'|'recompute'] 'guion' query the user % if the disk and input parameters are different. The % outcome may be either 'usedisk' or 'recompute'. See % recompflag output for more information. % ignorefields - [cell array] list fields to ignore % % Outputs: % recompflag - ['same'|'different'|'recompute'|'usedisk'|'cancel'] 'same' % (resp. 'different') indicates that the parameters in the % data file are identical (resp. different). 'recompute' % indicate that the measure should be recomputed and the % file has been erased. 'usedisk' indicate that the user % wishes (from the GUI) to use the version on disk. % params - [structure] final parameter. This is usually identical % to the 'params' input unless the user choose to use % parameters from the file on disk. These are then % copied to this output structure. % % Authors: Arnaud Delorme, 2006- % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2006, [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 [ res, params2 ] = std_filecheck(filename, params2, guiflag, ignorefields); if nargin < 2 help std_filecheck; return; end; if nargin < 3 guiflag = 'guion'; end; if nargin < 4 ignorefields = {}; end; if ~exist( filename ), res = guiflag; return; end; params1 = load('-mat', filename, 'parameters'); params1 = finputcheck( params1.parameters, { 'tmp' 'real' [] NaN}, '', 'ignore'); % allow to tackle duplicate fields params1 = rmfield(params1, 'tmp'); if iscell(params2), params2 = struct(params2{:}); end; % test if the fields are different % -------------------------------- params1 = orderfields(params1); params2 = orderfields(params2); fields1 = fieldnames( params1 ); fields1 = setdiff_bc( fields1, ignorefields); fields2 = fieldnames( params2 ); fields2 = setdiff_bc( fields2, ignorefields); allfields = union_bc(fields1, fields2); % make fields the same % -------------------- res = 'same'; if ~isequal( fields1, fields2 ), for ind = 1:length(allfields) if strcmpi(allfields{ind}, 'plotitc'), adsfads; end; if ~isfield( params1, allfields{ind}) if isstr(getfield(params2, allfields{ind})) params1 = setfield(params1, allfields{ind}, ''); else params1 = setfield(params1, allfields{ind}, []); end; res = 'different'; end; if ~isfield( params2, allfields{ind}) if isstr(getfield(params1, allfields{ind})) params2 = setfield(params2, allfields{ind}, ''); else params2 = setfield(params2, allfields{ind}, []); end; res = 'different'; end; end; end; % data type % --------- if ~isempty(strmatch('cycles', allfields)), strcom = 'ERSP'; else strcom = 'SPECTRAL'; end; % compare fields % -------------- txt = {}; for ind = 1:length(allfields) if ~strcmp(allfields{ind},'baseline') val1 = getfield(params1, allfields{ind}); val2 = getfield(params2, allfields{ind}); val1str = fastif(isempty(val1), 'not set', vararg2str({val1(1:min(3, length(val1)))})); val2str = fastif(isempty(val2), 'not set', vararg2str({val2(1:min(3, length(val2)))})); tmptxt = sprintf(' ''%s'' is %s in the file (vs. %s)', allfields{ind}, val1str, val2str); if length(val1) ~= length(val2) res = 'different'; txt{end+1} = tmptxt; elseif ~isequal(val1, val2) if ~isnan(val1) & ~isnan(val2) res = 'different'; txt{end+1} = tmptxt; end end end end % build gui or return % ------------------- if strcmpi(guiflag, 'usedisk'), if isempty(txt) params2 = params1; res = 'usedisk'; disp(['Using file on disk: ' filename ]); return; else strvcat(txt{:}) error([ 'Two ' strcom ' files had different parameters and the ' strcom ' function' 10 ... 'cannot handle that. We suggest that you delete all files. See command line details' ]); end; elseif strcmpi(guiflag, 'recompute'), res = 'recompute'; disp(['Deleting and recomputing file: ' filename ]); return; elseif strcmpi(res, 'same') & ( strcmpi(guiflag, 'guion') | strcmpi(guiflag, 'same') ) disp(['Using file on disk: ' filename ]); return; end; set_yes = [ 'set(findobj(''parent'', gcbf, ''tag'', ''ersp_no''), ''value'', 0);']; set_no = [ 'set(findobj(''parent'', gcbf, ''tag'', ''ersp_yes''), ''value'', 0);' ]; textgui1 = strvcat( [ upper(strcom) ' info exists in file: ' filename ], ... 'However, as detailed below, it does not fit with the requested values:'); textgui2 = strvcat(txt{:}); %textgui2 = ['wavelet cycles - [' num2str(params1.cycles(1)) ' ' num2str(params2.cycles(2)) ... % '] instead of [' num2str(params1.cycles(1)) ' ' num2str(params2.cycles(2)) ... % '], padratio - ' num2str(params1.padratio) ' instead of ' num2str(param2.padratio) ... % ', and bootstrap significance - ' num2str(params1.alpha) ' instead of ' num2str(params2.alpha) ]; uilist = { {'style' 'text' 'string' textgui1 } ... {'style' 'text' 'string' textgui2 } {} ... {'style' 'text' 'string' ['Would you like to recompute ' upper(strcom) ' and overwrite those values?' ]} ... {'style' 'checkbox' 'tag' 'ersp_yes' 'string' 'Yes, recompute' 'value' 1 'Callback' set_yes } ... {'style' 'checkbox' 'tag' 'ersp_no' 'string' 'No, use data file parameters (and existing ERSP info)' 'value' 0 'Callback' set_no } }; ersp_ans = inputgui('geometry', {[1] [1] [1] [1] [0.5 1] }, 'geomvert', [2 max(length(txt),1)*0.7 1 1 1 1], 'uilist', uilist, ... 'helpcom', '', 'title', ['Recalculate ' upper(strcom) ' parameters -- part of std_ersp()']); if isempty(ersp_ans), res = 'cancel'; return; end; if find(celltomat(ersp_ans)) == 2 % use existing ERSP info from this dataset disp(['Using file on disk: ' filename ]); params2 = params1; res = 'usedisk'; else % Over write data in dataset disp(['Deleting and recomputing file: ' filename ]); res = 'recompute'; %delete(filename); end
github
ZijingMao/baselineeegtest-master
std_changroup.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_changroup.m
5,933
utf_8
3ec8fa1b075f3697d4a1c1970be1031b
% std_changroup() - Create channel groups for plotting. % % Usage: % >> STUDY = std_changroup(STUDY, ALLEEG); % >> STUDY = std_changroup(STUDY, ALLEEG, chanlocs, 'interp'); % Inputs: % ALLEEG - Top-level EEGLAB vector of loaded EEG structures for the dataset(s) % in the STUDY. ALLEEG for a STUDY set is typically loaded using % pop_loadstudy(), or in creating a new STUDY, using pop_createstudy(). % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % chanlocs - EEGLAB channel structure. Only construct the STUDY.changrp % structure for a subset of channels. % 'interp' - optional input in case channel locations are interpolated % % Outputs: % STUDY - The input STUDY set structure modified according to specified user % edits, if any. The STUDY.changrp structure is created. It contains as % many elements as there are channels. For example, STUDY.changrp(1) % is the first channel. Fields of the changrp structure created at this % point are % STUDY.changrp.name : name of the channel group % STUDY.changrp.channels : cell array containing channel labels % for the group. % STUDY.changrp.setinds : indices of datasets containing the % selected channels. % STUDY.changrp.allinds : indices of channels within the datasets % above. % % Authors: Arnaud Delorme, CERCO, 2006 % Copyright (C) Arnaud Delorme, CERCO, [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 STUDY = std_changroup(STUDY, ALLEEG, alllocs, interp); if nargin < 4 interp = 'off'; end; % union of all channel structures % ------------------------------- inputloc = 0; if nargin >= 3 if ~isempty(alllocs) inputloc = 1; end; end; if ~inputloc alllocs = eeg_mergelocs(ALLEEG.chanlocs); end; % create group for each electrode % ------------------------------- if isstruct(alllocs) alllocs = { alllocs.labels }; end; STUDY.changrp = []; for indc = 1:length(alllocs) STUDY.changrp(indc).name = alllocs{indc}; STUDY.changrp(indc).channels = { alllocs{indc} }; tmp = std_chanlookupnew( STUDY, ALLEEG, STUDY.changrp(indc), interp); STUDY.changrp(indc).setinds = tmp.setinds; STUDY.changrp(indc).allinds = tmp.allinds; STUDY.changrp(indc).centroid = []; end; % if strcmpi(interp, 'off') % if length(unique( cellfun(@length, { ALLEEG.chanlocs }))) ~= 1 % STUDY.changrpstatus = 'some channels missing in some datasets'; % else STUDY.changrpstatus = 'all channels present in all datasets'; % end; % else STUDY.changrpstatus = 'all channels present in all datasets - interpolated'; % end; %STUDY.changrp(indc).name = [ 'full montage' ]; %STUDY.changrp(indc).channels = { alllocs.labels }; %tmp = std_chanlookup( STUDY, ALLEEG, STUDY.changrp(indc)); %STUDY.changrp(indc).chaninds = tmp.chaninds; return; % find datasets and channel indices % --------------------------------- function changrp = std_chanlookupnew( STUDY, ALLEEG, changrp, interp); setinfo = STUDY.design(STUDY.currentdesign).cell; allconditions = STUDY.design(STUDY.currentdesign).variable(1).value; allgroups = STUDY.design(STUDY.currentdesign).variable(2).value; nc = max(length(allconditions),1); ng = max(length(allgroups), 1); changrp.allinds = cell( nc, ng ); changrp.setinds = cell( nc, ng ); for index = 1:length(setinfo) % get index of independent variables % ---------------------------------- condind = std_indvarmatch( setinfo(index).value{1}, allconditions); grpind = std_indvarmatch( setinfo(index).value{2}, allgroups ); if isempty(allconditions), condind = 1; end; if isempty(allgroups), grpind = 1; end; % scan all channel labels % ----------------------- if strcmpi(interp, 'off') datind = setinfo(index).dataset; tmpchanlocs = ALLEEG(datind(1)).chanlocs; tmplocs = { tmpchanlocs.labels }; for indc = 1:length(changrp.channels) % usually just one channel ind = strmatch( changrp.channels{indc}, tmplocs, 'exact'); if length(ind) > 1, error([ 'Duplicate channel label ''' tmplocs{ind(1)} ''' for dataset ' int2str(datind) ]); end; if ~isempty(ind) changrp.allinds{ condind, grpind } = [ changrp.allinds{ condind, grpind } ind ]; changrp.setinds{ condind, grpind } = [ changrp.setinds{ condind, grpind } index ]; end; end; else % interpolation is "on", all channels for all datasets alllocs = { STUDY.changrp.name }; ind = strmatch( changrp.name, alllocs, 'exact'); changrp.allinds{ condind, grpind } = [ changrp.allinds{ condind, grpind } ind ]; changrp.setinds{ condind, grpind } = [ changrp.setinds{ condind, grpind } index ]; end; end;
github
ZijingMao/baselineeegtest-master
std_reset.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_reset.m
1,619
utf_8
72ffdfcbfcf2b3d338ff1b59bcf6d6d5
% std_reset() - Remove all preloaded measures from STUDY % % Usage: % >> STUDY = std_reset(STUDY); % % Inputs: % STUDY - EEGLAB STUDY structure % % Outputs: % STUDY - EEGLAB STUDY structure % % Author: Arnaud Delorme, CERCO/CNRS & SCCN, INC, UCSD, 2009- % Copyright (C) Arnaud Delorme, [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 STUDY = std_reset(STUDY) if nargin < 1 help std_reset; return; end; fields = { 'erpdata' 'erptimes' 'specdata' 'specfreqs' 'erspdata' ... 'ersptimes' 'erspfreqs' 'itcdata' 'itctimes' 'itcfreqs' ... 'topo' 'topox' 'topoy' 'topoall' 'topopol' 'dipole' }; for ind = 1:length(fields) if isfield(STUDY.cluster, fields{ind}) STUDY.cluster = rmfield(STUDY.cluster, fields{ind}); end; if isfield(STUDY, 'changrp') if isfield(STUDY.changrp, fields{ind}) STUDY.changrp = rmfield(STUDY.changrp, fields{ind}); end; end; end;
github
ZijingMao/baselineeegtest-master
std_substudy.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_substudy.m
5,138
utf_8
d57013b3c25ff4a8d8588e247f07bd61
% std_substudy() - create a sub-STUDY set by removing datasets, conditions, groups, or % subjects. % Usage: % >> [ STUDY ALLEEG ] = std_substudy(STUDY, ALLEEG, 'key', 'val', ...); % % Optional Inputs: % STUDY - existing study structure. % ALLEEG - vector of EEG dataset structures to be included in the STUDY. % % Optional Inputs: % 'dataset' - [integer array] indices of dataset to include in sub-STUDY % Default is all datasets. % 'subject' - [cell array] name of subjects to include in sub-STUDY. % Default is all subjects.% % 'condition' - [cell array] name of conditions to include in sub-STUDY % Default is all conditions. % 'group' - [cell array] name of gourps to include in sub-STUDY % Default is all groups. % 'rmdat' - ['on'|'off'] actually remove datasets 'on', or simply % remove all references to these datasets for channels and % clusters ('off'). % % Example: % % create a sub-STUDY using only the first 3 subjects % % WARNING: make sure your STUDY is saved before creating a sub-STUDY % [STUDY ALLEEG] = std_substudy(STUDY, ALLEEG, 'subject', STUDY.subjects(1:3)); % % Authors: Arnaud Delorme, CERCO/CNSR & SCCN, INC, UCSD, 2009- % Copyright (C) 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 [ STUDY ALLEEG ] = std_substudy(STUDY, ALLEEG, varargin); if nargin < 3 help std_substudy; return; end opt = finputcheck(varargin, { 'condition' 'cell' {} {}; 'dataset' 'integer' {} []; 'group' 'cell' {} {}; 'rmdat' 'string' { 'on','off' } 'on'; 'subject' 'cell' {} {} }, 'std_substudy'); if isstr(opt), return; end; % find datasets to remove % ----------------------- tagdel = []; if ~isempty(opt.subject) for index = 1:length(STUDY.datasetinfo) if ~strmatch(STUDY.datasetinfo.subject, opt.subject, 'exact') tagdel = [ tagdel index ]; end; end; end; if ~isempty(opt.condition) for index = 1:length(STUDY.datasetinfo) if ~strmatch(STUDY.datasetinfo.condition, opt.condition, 'exact') tagdel = [ tagdel index ]; end; end; end; if ~isempty(opt.group) for index = 1:length(STUDY.datasetinfo) if ~strmatch(STUDY.datasetinfo.group, opt.group, 'exact') tagdel = [ tagdel index ]; end; end; end; if ~isempty(opt.dataset) tagdel = [ tagdel setdiff([1:length(ALLEEG)], opt.dataset) ]; end; tagdel = unique_bc(tagdel); % find new dataset indices % ------------------------ alldats = [1:length(ALLEEG)]; if strcmpi(opt.rmdat, 'on') alldats(tagdel) = []; for index = 1:length(ALLEEG) tmp = find(alldats == index); if isempty(tmp), tmp = NaN; end; datcoresp(index) = tmp; end; ALLEEG(tagdel) = []; STUDY.datasetinfo(tagdel) = []; for index = 1:length(STUDY.datasetinfo) STUDY.datasetinfo(index).index = index; end; else alldats(tagdel) = []; for index = 1:length(ALLEEG) tmp = find(alldats == index); if isempty(tmp), tmp = NaN; else tmp = index; end; datcoresp(index) = tmp; end; end; % check channel consistency % ------------------------- for i = 1:length(STUDY.changrp) for c = 1:size(STUDY.changrp(i).setinds,1) for g = 1:size(STUDY.changrp(i).setinds,2) newinds = datcoresp(STUDY.changrp(i).setinds{c,g}); nonnans = find(~isnan(newinds)); STUDY.changrp(i).setinds{c,g} = newinds(nonnans); STUDY.changrp(i).allinds{c,g} = STUDY.changrp(i).allinds{c,g}(nonnans); end; end; end; % check cluster consistency % ------------------------- for index = 1:length(STUDY.cluster) STUDY.cluster(index).sets(:) = datcoresp(STUDY.cluster(index).sets(:)); for i = size(STUDY.cluster(index).sets,2):-1:1 if all(isnan(STUDY.cluster(index).sets(:,i))) STUDY.cluster(index).sets(:,i) = []; STUDY.cluster(index).comps(:,i) = []; end; end; [tmp STUDY.cluster(index).setinds STUDY.cluster(index).allinds] = std_setcomps2cell(STUDY, STUDY.cluster(index).sets, STUDY.cluster(index).comps); end; STUDY = std_reset(STUDY); STUDY = std_checkset(STUDY, ALLEEG);
github
ZijingMao/baselineeegtest-master
std_plot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_plot.m
1,013
utf_8
c20379b5799cb761b42ccc8e155eb139
% std_plot() - This function is outdated. Use std_plottf() to plot time/ % frequency decompositions and function std_plotcurve() to % plot erp and spectrum. % Copyright (C) 2006 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 [pgroup, pcond, pinter] = std_plot(allx, data, varargin) help std_plot; return;
github
ZijingMao/baselineeegtest-master
pop_precomp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_precomp.m
21,303
utf_8
3635c5fd488f6a3f81aadbc21962c9c5
% pop_precomp() - precompute measures (spectrum, ERP, ERSP) for a collection of data % channels. Calls std_precomp(). % Usage: % >> [STUDY, ALLEEG] = pop_precomp(STUDY, ALLEEG); % pop up interactive window % Inputs: % STUDY - STUDY set structure containing (loaded) EEG dataset structures % ALLEEG - ALLEEG vector of EEG structures, else a single EEG dataset. % % Outputs: % STUDY - the input STUDY set with added pre-clustering data for use by pop_clust() % ALLEEG - the input ALLEEG vector of EEG dataset structures modified by adding % pre-clustering data (pointers to .mat files that hold cluster measure information). % % Authors: Arnaud Delorme, CERCO, CNRS, 2006- % % See also: std_precomp() % Copyright (C) Arnaud Delorme, CERCO, CNRS, [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 [STUDY, ALLEEG, com] = pop_precomp(varargin) com = ''; if ~isstr(varargin{1}) %intial settings if length(varargin) < 2 error('pop_precomp(): needs both ALLEEG and STUDY structures'); end STUDY = varargin{1}; ALLEEG = varargin{2}; comps = false; if nargin > 2 if strcmpi(varargin{3}, 'components') comps = true; end; end; if isempty(ALLEEG) error('STUDY contains no datasets'); end % callbacks % --------- erspparams_str = [ '''cycles'', [3 0.8], ''nfreqs'', 100, ''ntimesout'', 200' ]; specparams_str = '''specmode'', ''fft'', ''logtrials'', ''off'''; erpimageparams_str = '''nlines'', 10,''smoothing'', 10'; set_ersp = ['pop_precomp(''setersp'',gcf);']; test_ersp = ['pop_precomp(''testersp'',gcf);']; set_itc = ['pop_precomp(''setitc'',gcf);']; set_spec = ['pop_precomp(''setspec'',gcf);']; set_erp = ['pop_precomp(''seterp'',gcf);']; set_erpimage = ['pop_precomp(''seterpimage'',gcf);']; test_spec = ['pop_precomp(''testspec'',gcf);']; test_erpimage = ['pop_precomp(''testerpimage'',gcf);']; chanlist = ['pop_precomp(''chanlist'',gcf);']; chanlist = 'warndlg2([ ''You need to compute measures on all data channels.'' 10 ''This functionality is under construction.'']);'; chaneditbox = ['pop_precomp(''chaneditbox'',gcf);']; warninterp = ''; %['warndlg2(''EEGLAB will crash when plotting a given channel if it is missing in one dataset'');' ]; cb_ica1 = ''; %[ 'if get(gcbo, ''value''), set(findobj(gcbf, ''tag'', ''rmica2_on''), ''value'', 0); end;' ]; cb_ica2 = ''; %[ 'if get(gcbo, ''value''), set(findobj(gcbf, ''tag'', ''rmica1_on''), ''value'', 0); end;' ]; geomline = [0.35 6]; if comps == true str_name = sprintf('Pre-compute component measures for STUDY ''%s'' - ''%s''', ... STUDY.name, STUDY.design(STUDY.currentdesign).name); if length(str_name) > 80, str_name = [ str_name(1:80) '...' ]; end; guiadd1 = { {'style' 'checkbox' 'string' '' 'tag' 'compallersp' 'value' 1 } ... {'style' 'text' 'string' 'Compute ERP/spectrum/ERSP only for components selected by RV (set) or for all components (unset)' } }; guiadd2 = { {'style' 'checkbox' 'string' '' 'tag' 'scalp_on' 'value' 0 } ... {'style' 'text' 'string' 'Scalp maps' } }; geomadd1 = { geomline }; geomvertadd1 = [ 1 ]; geomadd2 = { geomline }; else str_name = sprintf('Pre-compute channel measures for STUDY ''%s'' - ''%s''', ... STUDY.name, STUDY.design(STUDY.currentdesign).name); if length(str_name) > 80, str_name = [ str_name(1:80) '...''' ]; end; guiadd1 = { {'style' 'text' 'string' 'Channel list (default:all)' 'FontWeight' 'Bold'} ... {'Style' 'edit' 'string' '' 'tag' 'chans' 'callback' chaneditbox 'enable' 'off' }, ... {'style' 'pushbutton' 'string' '...', 'enable' fastif(isempty(ALLEEG(1).chanlocs), 'off', 'on') ... 'callback' chanlist }, ... {'style' 'checkbox' 'string' '' 'tag' 'interpolate_on' 'value' 1 'callback' warninterp } ... {'style' 'text' 'string' 'Spherical interpolation of missing channels (performed after optional ICA removal below)' } ... {'style' 'checkbox' 'string' ' ' 'tag' 'rmica1_on' 'value' 0 'callback' cb_ica1 } ... {'style' 'text' 'string' 'Remove ICA artifactual components pre-tagged in each dataset' } ... {'style' 'checkbox' 'string' [ ' ' 10 ' ' ] 'tag' 'rmica2_on' 'value' 0 'callback' cb_ica2 } ... {'style' 'text' 'string' [ 'Remove artifactual ICA cluster or clusters (hold shift key)' 10 ' ' ] } ... {'style' 'listbox' 'string' { STUDY.cluster.name } 'value' 1 'max' 2 'tag' 'rmica2_val'} }; guiadd2 = {}; geomadd1 = { [2 3 0.5] geomline geomline [0.35 4 2] }; geomvertadd1 = [ 1 1 1 2 ]; geomadd2 = { }; end; gui_spec = { ... {'style' 'text' 'string' str_name 'FontWeight' 'Bold' 'horizontalalignment' 'left'}, ... {'style' 'text' 'string' '(warning: define your STUDY designs first as precomputation is specific to a given STUDY design)' } {}, ... guiadd1{:}, ... {} {'style' 'text' 'string' 'List of measures to precompute' 'FontWeight' 'Bold' 'horizontalalignment' 'left'}, ... {'style' 'checkbox' 'string' '' 'tag' 'erp_on' 'value' 0 'Callback' set_erp } , ... {'style' 'text' 'string' 'ERPs' }, {}, ... {'style' 'text' 'string' 'Baseline ([min max] in ms)' 'tag' 'erp_text' 'enable' 'off'}... {'style' 'edit' 'string' '' 'tag' 'erp_base' 'enable' 'off' }, { }, ... {'style' 'checkbox' 'string' '' 'tag' 'spectra_on' 'value' 0 'Callback' set_spec }, ... {'style' 'text' 'string' 'Power spectrum' }, {}, ... {'style' 'text' 'string' 'Spectopo parameters' 'tag' 'spec_push' 'enable' 'off'}... {'style' 'edit' 'string' specparams_str 'tag' 'spec_params' 'enable' 'off' }, ... {'style' 'pushbutton' 'string' 'Test' 'tag' 'spec_test' 'enable' 'off' 'callback' test_spec}... {'style' 'checkbox' 'string' '' 'tag' 'erpimage_on' 'value' 0 'Callback' set_erpimage }, ... {'style' 'text' 'string' 'ERP-image' }, {}, ... {'style' 'text' 'string' 'ERP-image parameters' 'tag' 'erpimage_push' 'enable' 'off'}... {'style' 'edit' 'string' erpimageparams_str 'tag' 'erpimage_params' 'enable' 'off' }, ... {'style' 'pushbutton' 'string' 'Test' 'tag' 'erpimage_test' 'enable' 'off' 'callback' test_erpimage}... {'style' 'checkbox' 'string' '' 'tag' 'ersp_on' 'value' 0 'Callback' set_ersp } , ... {'style' 'text' 'string' 'ERSPs' 'horizontalalignment' 'center' }, {}, ... {'vertshift' 'style' 'text' 'string' 'Time/freq. parameters' 'tag' 'ersp_push' 'value' 1 'enable' 'off'}, ... {'vertshift' 'style' 'edit' 'string' erspparams_str 'tag' 'ersp_params' 'enable' 'off'}... {'vertshift' 'style' 'pushbutton' 'string' 'Test' 'tag' 'ersp_test' 'enable' 'off' 'callback' test_ersp }... {'style' 'checkbox' 'string' '' 'tag' 'itc_on' 'value' 0 'Callback' set_itc }, ... {'style' 'text' 'string' 'ITCs' 'horizontalalignment' 'center' }, {'link2lines' 'style' 'text' 'string' '' } {} {} {}, ... guiadd2{:}, ... {}, ... {'style' 'checkbox' 'string' 'Save single-trial measures for single-trial statistics (beta) - requires disk space' 'tag' 'savetrials_on' 'value' 0 } {}, ... {'style' 'checkbox' 'string' 'Overwrite files on disk' 'tag' 'recomp_on' 'value' 1 } {}, ... }; %{'style' 'checkbox' 'string' '' 'tag' 'precomp_PCA' 'Callback' precomp_PCA 'value' 0} ... %{'style' 'text' 'string' 'Do not prepare dataset for clustering at this time.' 'FontWeight' 'Bold' } {} ... % find the list of all channels % ----------------------------- allchans = { }; keepindex = 0; for index = 1:length(ALLEEG) tmpchanlocs = ALLEEG(index).chanlocs; tmpchans = { tmpchanlocs.labels }; allchans = unique_bc({ allchans{:} tmpchanlocs.labels }); if length(allchans) == length(tmpchans), keepindex = index; end; end; if keepindex, tmpchanlocs = ALLEEG(keepindex).chanlocs; allchans = { tmpchanlocs.labels }; end; chanlist = {}; firsttimeersp = 1; fig_arg = { ALLEEG STUDY allchans chanlist firsttimeersp }; geomline1 = [0.40 1.3 0.1 2 2.4 0.65 ]; geomline2 = [0.40 0.9 0.5 2 2.4 0.65 ]; geometry = { [1] [1] [1] geomadd1{:} [1] [1] geomline1 geomline1 geomline1 geomline2 geomline2 geomadd2{:} 1 [1 0.1] [1 0.1] }; geomvert = [ 1 1 0.5 geomvertadd1 0.5 1 1 1 1 1 1 1 fastif(length(geomadd2) == 1,1,[]) 1 1]; [precomp_param, userdat2, strhalt, os] = inputgui( 'geometry', geometry, 'uilist', gui_spec, 'geomvert', geomvert, ... 'helpcom', ' pophelp(''std_precomp'')', ... 'title', 'Select and compute component measures for later clustering -- pop_precomp()', ... 'userdata', fig_arg); if isempty(precomp_param), return; end; if comps == 1 options = { STUDY ALLEEG 'components' }; else options = { STUDY ALLEEG userdat2{4} }; end if ~isfield(os, 'interpolate_on'), os.interpolate_on = 0; end; if ~isfield(os, 'scalp_on'), os.scalp_on = 0; end; if ~isfield(os, 'compallersp'), os.compallersp = 1; end; warnflag = 0; % rm_ica option is on % ------------------- if isfield(os, 'rmica1_on') if os.rmica1_on == 1 options = { options{:} 'rmicacomps' 'on' }; end end; % remove ICA cluster % ------------------ if isfield(os, 'rmica2_on') if os.rmica2_on == 1 options = { options{:} 'rmclust' os.rmica2_val }; end end; % interpolate option is on % ------------------------ if os.savetrials_on == 1 options = { options{:} 'savetrials' 'on' }; end % interpolate option is on % ------------------------ if os.interpolate_on == 1 options = { options{:} 'interp' 'on' }; end % compallersp option is on % ------------------------ if os.compallersp == 0 options = { options{:} 'allcomps' 'on' }; end % recompute option is on % ---------------------- if os.recomp_on == 1 options = { options{:} 'recompute' 'on' }; end % ERP option is on % ---------------- if os.erp_on == 1 options = { options{:} 'erp' 'on' }; if ~isempty(os.erp_base) options = { options{:} 'erpparams' { 'rmbase' str2num(os.erp_base) } }; end warnflag = checkFilePresent(STUDY, 'erp', comps, warnflag, os.recomp_on); end % SCALP option is on % ---------------- if os.scalp_on == 1 options = { options{:} 'scalp' 'on' }; end % Spectrum option is on % -------------------- if os.spectra_on== 1 tmpparams = eval( [ '{' os.spec_params '}' ] ); options = { options{:} 'spec' 'on' 'specparams' tmpparams }; warnflag = checkFilePresent(STUDY, 'spec', comps, warnflag, os.recomp_on); end % ERPimage option is on % -------------------- if os.erpimage_on== 1 tmpparams = eval( [ '{' os.erpimage_params '}' ] ); options = { options{:} 'erpim' 'on' 'erpimparams' tmpparams }; warnflag = checkFilePresent(STUDY, 'erpim', comps, warnflag, os.recomp_on); end % ERSP option is on % ----------------- if os.ersp_on == 1 tmpparams = eval( [ '{' os.ersp_params '}' ] ); options = { options{:} 'ersp' 'on' 'erspparams' tmpparams }; warnflag = checkFilePresent(STUDY, 'ersp', comps, warnflag, os.recomp_on); end % ITC option is on % ---------------- if os.itc_on == 1 tmpparams = eval( [ '{' os.ersp_params '}' ] ); options = { options{:} 'itc' 'on' }; if os.ersp_on == 0, options = { options{:} 'erspparams' tmpparams }; end; warnflag = checkFilePresent(STUDY, 'itc', comps, warnflag, os.recomp_on); end % evaluate command % ---------------- if length(options) == 4 warndlg2('No measure selected: aborting.'); return; end; [STUDY ALLEEG] = std_precomp(options{:}); com = sprintf('[STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, %s);', vararg2str(options(3:end))); else hdl = varargin{2}; %figure handle userdat = get(varargin{2}, 'userdata'); ALLEEG = userdat{1}; STUDY = userdat{2}; allchans = userdat{3}; chansel = userdat{4}; firsttimeersp = userdat{5}; switch varargin{1} case 'chanlist' [tmp tmp2 tmp3] = pop_chansel(allchans, 'select', chansel); if ~isempty(tmp) set(findobj('parent', hdl, 'tag', 'chans'), 'string', tmp2); userdat{4} = tmp3; end; set(hdl, 'userdata',userdat); case 'chaneditbox' userdat{4} = parsetxt(get(findobj('parent', hdl, 'tag', 'chans'), 'string')); set(hdl, 'userdata',userdat); case { 'setitc' 'setersp' } set_itc = get(findobj('parent', hdl, 'tag', 'itc_on'), 'value'); set_ersp = get(findobj('parent', hdl, 'tag', 'ersp_on'), 'value'); if (~set_ersp & ~set_itc ) set(findobj('parent', hdl,'tag', 'ersp_push'), 'enable', 'off'); set(findobj('parent', hdl,'tag', 'ersp_params'), 'enable', 'off'); set(findobj('parent', hdl,'tag', 'ersp_test'), 'enable', 'off'); else set(findobj('parent', hdl,'tag', 'ersp_push'), 'enable', 'on'); set(findobj('parent', hdl,'tag', 'ersp_params'), 'enable', 'on'); set(findobj('parent', hdl,'tag', 'ersp_test'), 'enable', 'on'); end userdat{5} = 0; set(hdl, 'userdata',userdat); if firsttimeersp warndlg2(strvcat('Checking both ''ERSP'' and ''ITC'' does not require further', ... 'computing time. However it requires disk space')); end; case 'setspec' set_spec = get(findobj('parent', hdl, 'tag', 'spectra_on'), 'value'); if set_spec set(findobj('parent', hdl,'tag', 'spec_push'), 'enable', 'on'); set(findobj('parent', hdl,'tag', 'spec_params'), 'enable', 'on'); set(findobj('parent', hdl,'tag', 'spec_test'), 'enable', 'on'); else set(findobj('parent', hdl,'tag', 'spec_push'), 'enable', 'off'); set(findobj('parent', hdl,'tag', 'spec_params'), 'enable', 'off'); set(findobj('parent', hdl,'tag', 'spec_test'), 'enable', 'off'); end case 'seterpimage' set_spec = get(findobj('parent', hdl, 'tag', 'erpimage_on'), 'value'); if set_spec set(findobj('parent', hdl,'tag', 'erpimage_push'), 'enable', 'on'); set(findobj('parent', hdl,'tag', 'erpimage_params'), 'enable', 'on'); set(findobj('parent', hdl,'tag', 'erpimage_test'), 'enable', 'on'); else set(findobj('parent', hdl,'tag', 'erpimage_push'), 'enable', 'off'); set(findobj('parent', hdl,'tag', 'erpimage_params'), 'enable', 'off'); set(findobj('parent', hdl,'tag', 'erpimage_test'), 'enable', 'off'); end case 'seterp' set_erp = get(findobj('parent', hdl, 'tag', 'erp_on'), 'value'); if set_erp set(findobj('parent', hdl,'tag', 'erp_text'), 'enable', 'on'); set(findobj('parent', hdl,'tag', 'erp_base'), 'enable', 'on'); else set(findobj('parent', hdl,'tag', 'erp_text'), 'enable', 'off'); set(findobj('parent', hdl,'tag', 'erp_base'), 'enable', 'off'); end case 'testspec' try, spec_params = eval([ '{' get(findobj('parent', hdl, 'tag', 'spec_params'), 'string') '}' ]); TMPEEG = eeg_checkset(ALLEEG(1), 'loaddata'); [ X f ] = std_spec(TMPEEG, 'channels', { TMPEEG.chanlocs(1).labels }, 'trialindices', { [1:min(20,TMPEEG.trials)] }, 'recompute', 'on', 'savefile', 'off', spec_params{:}); figure; plot(f, X); xlabel('Frequencies (Hz)'); ylabel('Power'); xlim([min(f) max(f)]); tmplim = ylim; text( TMPEEG.srate/4, mean(tmplim)+(max(tmplim)-min(tmplim))/3, ... strvcat('This is a test plot performed on', ... 'the first 20 trials of the first', ... 'dataset (1 line per channel).', ... 'Frequency range may be adjusted', ... 'after computation')); icadefs; set(gcf, 'color', BACKCOLOR); catch, warndlg2('Error while calling function, check parameters'); end; case 'testersp' try, ersp_params = eval([ '{' get(findobj('parent', hdl, 'tag', 'ersp_params'), 'string') '}' ]); tmpstruct = struct(ersp_params{:}); [ tmpX tmpt tmpf ersp_params ] = std_ersp(ALLEEG(1), 'channels', 1, 'trialindices', { [1:min(20,ALLEEG(1).trials)] }, 'type', 'ersp', 'recompute', 'on', 'savefile', 'off', ersp_params{:}); std_plottf(tmpt, tmpf, { tmpX }); catch, warndlg2('Error while calling function, check parameters'); end; case 'testerpimage' try, erpimage_params = eval([ '{' get(findobj('parent', hdl, 'tag', 'erpimage_params'), 'string') '}' ]); tmpstruct = struct(erpimage_params{:}); erpimstruct = std_erpimage(ALLEEG(1), 'channels', 1, 'recompute', 'on', 'savefile', 'off', erpimage_params{:}); figure; pos = get(gcf, 'position'); pos(3)=pos(3)*2; set(gcf, 'position', pos); subplot(1,2,1); tftopo(erpimstruct.chan1, erpimstruct.times, 1:size(erpimstruct.chan1,1), 'ylabel', 'Trials'); subplot(1,2,2); text( 0.2, 0.8, strvcat( 'This is a test plot performed on', ... 'the first channel of the first', ... 'dataset.', ... ' ', ... 'Time and trial range may be', ... 'adjusted after computation.'), 'fontsize', 18); axis off; icadefs; set(gcf, 'color', BACKCOLOR); catch, warndlg2('Error while calling function, check parameters'); end; end; end STUDY.saved = 'no'; % check if file is present % ------------------------ function warnflag = checkFilePresent(STUDY, datatype, comps, warnflag, recompute); if ~recompute, return; end; if warnflag, return; end; % warning has already been issued if comps dataFilename = [ STUDY.design(STUDY.currentdesign).cell(1).filebase '.ica' datatype ]; else dataFilename = [ STUDY.design(STUDY.currentdesign).cell(1).filebase '.dat' datatype ]; end; if exist(dataFilename) textmsg = [ 'WARNING: SOME DATAFILES ALREADY EXIST, OVERWRITE THEM?' 10 ... '(if you have another STUDY using the same datasets, it might overwrite its' 10 ... 'precomputed data files. Instead, use a single STUDY and create multiple designs).' ]; res = questdlg2(textmsg, 'Precomputed datafiles already present on disk', 'No', 'Yes', 'Yes'); if strcmpi(res, 'No') error('User aborded precomputing measures'); end; end; warnflag = 1;
github
ZijingMao/baselineeegtest-master
std_prepare_neighbors.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_prepare_neighbors.m
4,382
utf_8
a4a473e9fb500e8887f25e81a5641d93
% std_prepare_neighbors() - prepare Fieldtrip channel neighbor structure. % Only prepare the structure if necessary based % on statistical options in STUDY.etc.statistics. % Use the 'force' option to force preparing the % matrix. % % Usage: % >> [STUDY neighbors] = std_prepare_neighbors( STUDY, ALLEEG, 'key', val) % % Inputs: % STUDY - an EEGLAB STUDY set of loaded EEG structures % ALLEEG - ALLEEG vector of one or more loaded EEG dataset structures % % Optional inputs: % 'force' - ['on'|'off'] force generating the structure irrespective % of the statistics options selected. Default is 'off'. % 'channels' - [cell] list of channels to include in the matrix % 'method' - [string] method for preparing. See ft_prepare_neighbors % 'neighbordist' - [float] max distance. See ft_prepare_neighbors % % Note: other ft_prepare_neighbors fields such as template, layout may % also be used as optional keywords. % % Outputs: % STUDY - an EEGLAB STUDY set of loaded EEG structures % neighbors - Fieldtrip channel neighbour structure % % Author: Arnaud Delorme, SCCN, UCSD, 2012- % % See also: statcondfieldtrip() % Copyright (C) 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 [STUDY neighbors] = std_prepare_neighbors(STUDY, ALLEEG, varargin); neighbors = []; if nargin < 2 return; end; [opt addopts] = finputcheck( varargin, { 'force' 'string' { 'on','off' } 'off'; 'channels' 'cell' {} {} }, 'std_stat', 'ignore'); if strcmpi(opt.force, 'on') || (strcmpi(STUDY.etc.statistics.fieldtrip.mcorrect, 'cluster') && ... strcmpi(STUDY.etc.statistics.mode, 'fieldtrip') && (strcmpi(STUDY.etc.statistics.groupstats, 'on') || strcmpi(STUDY.etc.statistics.condstats, 'on'))) EEG = eeg_emptyset; EEG.chanlocs = eeg_mergelocs(ALLEEG.chanlocs); if isempty(EEG.chanlocs) disp('std_prepare_neighbors: cannot prepare channel neighbour structure because of empty channel structures'); return; end; if ~isempty(STUDY.etc.statistics.fieldtrip.channelneighbor) && isempty(addopts) && ... length(STUDY.etc.statistics.fieldtrip.channelneighbor) == length(EEG.chanlocs) disp('Using stored channel neighbour structure'); neighbors = STUDY.etc.statistics.fieldtrip.channelneighbor; else if ~isempty(opt.channels) indChans = eeg_chaninds(EEG, opt.channels); EEG.chanlocs = EEG.chanlocs(indChans); end; EEG.nbchan = length(EEG.chanlocs); EEG.data = zeros(EEG.nbchan,100,1); EEG.trials = 1; EEG.pnts = 100; EEG.xmin = 0; EEG.srate = 1; EEG.xmax = 99; EEG = eeg_checkset(EEG); tmpcfg = eeglab2fieldtrip(EEG, 'preprocessing', 'none'); % call the function that find channel neighbors % --------------------------------------------- addparams = eval( [ '{' STUDY.etc.statistics.fieldtrip.channelneighborparam '}' ]); for index = 1:2:length(addparams) tmpcfg = setfield(tmpcfg, addparams{index}, addparams{index+1}); end; for index = 1:2:length(addopts) tmpcfg = setfield(tmpcfg, addopts{index}, addopts{index+1}); end; warning off; cfg.neighbors = ft_prepare_neighbours(tmpcfg, tmpcfg); warning on; neighbors = cfg.neighbors; end; STUDY.etc.statistics.fieldtrip.channelneighbor = neighbors; end;
github
ZijingMao/baselineeegtest-master
std_savedat.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_savedat.m
1,752
utf_8
32ee6d94f325818156111da795834c6d
% std_savedat() - save measure for computed data % % Usage: std_savedat( filename, structure); % % Authors: Arnaud Delorme, SCCN, INC, UCSD, 2006- % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2004, [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 std_savedat( tmpfile, structure) delims = find( tmpfile == '.'); if ~isfield(structure, 'datafile') && ~isfield(structure, 'datafiles') structure.datafile = [ tmpfile(1:delims(end)-1) '.set' ]; end; % fix reading problem (bug 764) tmpfile2 = which(tmpfile); if isempty(tmpfile2), tmpfile2 = tmpfile; end; tmpfile = tmpfile2; eeglab_options; if option_saveversion6 try save('-v6' , tmpfile, '-struct', 'structure'); catch fields = fieldnames(structure); for i=1:length(fields) eval([ fields{i} '=structure.' fields{i} ';']); end; save('-mat', tmpfile, fields{:}); end; else save('-v7.3' , tmpfile, '-struct', 'structure'); end;
github
ZijingMao/baselineeegtest-master
std_clustmaxelec.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_clustmaxelec.m
2,424
utf_8
1a243dcf2ffd5e5be4cbaf58a69e3ac9
% std_clustmaxelec() - function to find the electrode with maximum absolute projection % for each component of a cluster % Usage: % >> [STUDY, ALLEEG] = std_clustmaxelec(STUDY, ALLEEG, clustind); % % Inputs: % STUDY - STUDY set structure containing (loaded) EEG dataset structures % ALLEEG - ALLEEG vector of EEG structures, else a single EEG dataset. % clustind - (single) cluster index % % Outputs: % eleclist - [cell] electrode list % setlist - [integer] set indices for the cluster % complist - [integer] component indices for the cluster % % Authors: Claire Braboszcz & Arnaud Delorme , CERCO, UPS/CRNS, 2011 % Copyright (C) Claire Braboszcz, CERCO, UPS/CRNS, 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 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 std_clustmaxelec(STUDY, ALLEEG, clusterind); if nargin < 1 help findicmaxelec; return; end; fprintf('Finding electrodes with max weight for cluster %d\n', clusterind); fprintf('-------------------------------------------------\n'); for index = 1:length(STUDY.cluster(clusterind).comps) set = STUDY.cluster(clusterind).sets(1,index); comp = STUDY.cluster(clusterind).comps( index); [tmp maxelec] = max( abs(ALLEEG(set).icawinv(:, comp)) ); indelec = ALLEEG(set).icachansind(maxelec); maxallelec{index} = ALLEEG(set).chanlocs(indelec).labels; allelec = unique_bc(maxallelec); fprintf('The electrode with the max weight for component %d of dataset %d is "%s"\n', comp, set, maxallelec{index}); end; for indelec=1:length(allelec) nbelec{indelec} = length(find(strcmp(allelec{indelec}, maxallelec) == 1)); fprintf('Number of occurrence of electrode %s: %d\n', allelec{indelec}, nbelec{indelec}); end;
github
ZijingMao/baselineeegtest-master
pop_studydesign.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_studydesign.m
28,474
utf_8
785b66d84c775b18999011c0f96bc16d
% pop_studydesign() - create a STUDY design structure. % % Usage: % >> [STUDY, ALLEEG] = pop_studydesign(STUDY, ALLEEG, key1, val1, ...); % % Inputs: % STUDY - EEGLAB STUDY set % ALLEEG - vector of the EEG datasets included in the STUDY structure % % Optional inputs: % % Authors: Arnaud Delorme, April 2010 % Copyright (C) Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, October 11, 2004, [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 [STUDY allcom] = pop_studydesign(STUDY, ALLEEG, designind, varargin); allcom = ''; if nargin < 2 help pop_studydesign; return; end; if nargin < 3 && ~isstr(STUDY) %% create GUI [ usrdat.factors usrdat.factorvals usrdat.factsubj] = std_getindvar(STUDY, 'both', 1); usrdat.factors = { 'None' usrdat.factors{:} }; usrdat.factorvals = { {} usrdat.factorvals{:} }; usrdat.factsubj = { {} usrdat.factsubj{:} }; usrdat.subjects = STUDY.subject; usrdat.datasetinfo = STUDY.datasetinfo; usrdat.design = STUDY.design; usrdat.filepath = STUDY.filepath; for ind = 1:length(usrdat.design) usrdat.design(ind).deletepreviousfiles = 0; end; % build menu popupselectsubj = { 'Select all subjects' }; for ind1 = 1:length(usrdat.factors) if ~isempty(usrdat.factsubj{ind1}) if any(cellfun(@length, usrdat.factsubj{ind1}) ~= length(usrdat.subjects)) for ind2 = 1:length(usrdat.factorvals{ind1}) if ~iscell(usrdat.factorvals{ind1}{ind2}) % not a combined value tmpval = encodevals(usrdat.factorvals{ind1}(ind2)); popupselectsubj{end+1} = [ num2str(usrdat.factors{ind1}) ' - ' tmpval{1} ]; end; end; end; end; end; cb_rename = 'pop_studydesign(''rename'', gcbf);'; cb_add = 'pop_studydesign(''add'', gcbf);'; cb_del = 'pop_studydesign(''del'', gcbf);'; cb_listboxfact1 = 'pop_studydesign(''selectfact'', gcf, 0);'; cb_listboxfact2 = 'pop_studydesign(''selectfact'', gcf, 1);'; cb_selectsubj = 'pop_studydesign(''selectsubj'', gcbf);'; cb_combinevals1 = 'pop_studydesign(''combinevals'', gcbf, 0);'; cb_combinevals2 = 'pop_studydesign(''combinevals'', gcbf, 1);'; cb_lbval = 'pop_studydesign(''updatedesign'', gcbf);'; cb_selectdesign = 'pop_studydesign(''selectdesign'', gcbf);'; cb_selectdata = 'pop_studydesign(''selectdatatrials'', gcbf);'; cb_selectfolder = 'pop_studydesign(''selectfolder'', gcbf);'; cb_setfolder = 'pop_studydesign(''updatedesign'', gcbf);'; uilist = { { 'style' 'text' 'string' 'Select STUDY design' 'fontweight' 'bold' } ... { 'style' 'listbox' 'string' { usrdat.design.name } 'tag' 'listboxdesign' 'callback' cb_selectdesign 'value' STUDY.currentdesign } ... { 'style' 'pushbutton' 'string' 'Add design' 'callback' cb_add } ... { 'style' 'pushbutton' 'string' 'Rename design' 'callback' cb_rename } ... { 'style' 'pushbutton' 'string' 'Delete design' 'callback' cb_del } ... { 'style' 'text' 'string' 'Subjects' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Independent variable 1 ' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Independent variable 2 ' 'fontweight' 'bold' } ... { 'style' 'listbox' 'string' usrdat.subjects 'tag' 'lbsubj' 'min' 0 'max' 2 'value' 1 'callback' cb_lbval } ... { 'style' 'listbox' 'string' usrdat.factors 'tag' 'lbfact0' 'callback' cb_listboxfact1 'value' 2 } ... { 'style' 'listbox' 'string' usrdat.factors 'tag' 'lbfact1' 'callback' cb_listboxfact2 'value' 1 } ... { 'style' 'text' 'string' 'Ind. var. 1 values ' } ... { 'style' 'text' 'string' 'Ind. var. 2 values' } ... { 'style' 'listbox' 'string' '' 'tag' 'lbval0' 'min' 0 'max' 2 'callback' cb_lbval } ... { 'style' 'listbox' 'string' '' 'tag' 'lbval1' 'min' 0 'max' 2 'callback' cb_lbval } ... { 'style' 'popupmenu' 'string' popupselectsubj 'tag' 'popupselect' 'callback' cb_selectsubj } ... { 'style' 'pushbutton' 'string' 'Combine selected values' 'tag' 'combine1' 'callback' cb_combinevals1 } ... { 'style' 'pushbutton' 'string' 'Combine selected values' 'tag' 'combine2' 'callback' cb_combinevals2 } ... { 'style' 'popupmenu' 'string' 'Paired statistics|Unpaired statistics' 'tag' 'lbpair0' 'callback' cb_lbval } ... { 'style' 'popupmenu' 'string' 'Paired statistics|Unpaired statistics' 'tag' 'lbpair1' 'callback' cb_lbval } ... { 'style' 'pushbutton' 'string' 'Use only specific datasets/trials' 'callback' cb_selectdata } ... { 'style' 'edit' 'string' '' 'tag' 'edit_selectdattrials' 'callback' cb_lbval } ... { 'style' 'text' 'string' 'Store pre-computed files in folder' } ... { 'style' 'edit' 'string' '' 'tag' 'edit_storedir' 'callback' cb_setfolder } ... { 'style' 'pushbutton' 'string' '...' 'callback' cb_selectfolder } ... { 'style' 'checkbox' 'string' 'Delete all pre-computed datafiles associated with this specific STUDY design' 'tag' 'chk_del' 'callback' cb_lbval } ... { 'style' 'checkbox' 'string' 'Save the STUDY' 'tag' 'chk_save' 'value' 1 } }; % { 'style' 'checkbox' 'string' 'Paired statistics' 'tag' 'lbpair0' 'callback' cb_lbval } ... % { 'style' 'checkbox' 'string' 'Paired statistics' 'tag' 'lbpair1' 'callback' cb_lbval } ... geometry = { {3 18 [1 1] [2 1] } ... {3 18 [1 2] [2 3] } ... {3 18 [3 2] [1 1] } ... {3 18 [3 3] [1 1] } ... {3 18 [3 4] [1 1] } ... {3 18 [1 5] [1 1] } ... {3 18 [2 5] [1 1] } ... {3 18 [3 5] [1 1] } ... {3 18 [1 6] [1 8] } ... {3 18 [2 6] [0.98 3] } ... {3 18 [3 6] [0.98 3] } ... {3 18 [2 9] [1 1] } ... {3 18 [3 9] [1 1] } ... {3 18 [2 10] [0.98 3] } ... {3 18 [3 10] [0.98 3] } ... {3 18 [1 14] [1 1] } ... {3 18 [2 13] [1 1] } ... {3 18 [3 13] [1 1] } ... {3 18 [2 14] [1 1] } ... {3 18 [3 14] [1 1] } ... {3 18 [1 15.5] [1.3 1] } ... {3 18 [2.25 15.5] [1.7 1] } ... {3 18 [1 16.5] [1.3 1] } ... {3 18 [2.25 16.5] [1.2 1] } ... {3 18 [3.45 16.5] [0.55 1] } ... {3 18 [1 17.5] [3 1] } ... {3 18 [1 19] [3 1] } ... }; for i = 1:length(geometry), geometry{i}{3} = geometry{i}{3}-1; end; streval = [ 'pop_studydesign(''selectdesign'', gcf);' ]; [tmp usrdat tmp2 result] = inputgui('uilist', uilist, 'title', 'Edit STUDY design -- pop_studydesign()', 'helpbut', 'Web help', 'helpcom', 'web(''http://sccn.ucsd.edu/wiki/Chapter_03:_Working_with_STUDY_designs'', ''-browser'')', 'geom', geometry, 'userdata', usrdat, 'eval', streval); if isempty(tmp), return; end; % call std_makedesign % ------------------- des = usrdat.design; allcom = ''; if length(des) < length(STUDY.design) for index = length(des)+1:length(STUDY.design) fprintf('Deleting STUDY design %d\n', index); com = 'STUDY.design(index).name = '';'; eval(com); allcom = [ allcom 10 com ]; end; end; for index = 1:length(des) tmpdes = rmfield(des(index), 'deletepreviousfiles'); rmfiles = fastif(des(index).deletepreviousfiles, 'limited', 'off'); if index > length(STUDY.design) || ~isequal(STUDY.design(index), tmpdes) || strcmpi(rmfiles, 'on') fprintf('Updating/creating STUDY design %d\n', index); % test if file exist and issue warning if length(STUDY.design) >= index && isfield('cell', STUDY.design) && ~isempty(STUDY.design(index).cell) && ... ~isempty(dir([ STUDY.design(index).cell(1).filebase '.*' ])) && strcmpi(rmfiles, 'off') if ~isequal(tmpdes.variable(1).label, STUDY.design(index).variable(1).label) || ... ~isequal(tmpdes.variable(2).label, STUDY.design(index).variable(2).label) || ... ~isequal(tmpdes.include, STUDY.design(index).include) || ... ~isequal(tmpdes.variable(1).value, STUDY.design(index).variable(1).value) || ... ~isequal(tmpdes.cases.value, STUDY.design(index).cases.value) || ... ~isequal(tmpdes.variable(2).value, STUDY.design(index).variable(2).value) res = questdlg2(strvcat([ 'Precomputed data files exist for design ' int2str(index) '.' ], ' ', ... 'Modifying this design without deleting the associated files', ... 'might mean that they will stay on disk and will be unusable'), ... 'STUDY design warning', 'Abort', 'Continue', 'Continue'); if strcmpi(res, 'Abort'), return; end; end; end; [STUDY com] = std_makedesign(STUDY, ALLEEG, index, tmpdes, 'delfiles', rmfiles); allcom = [ allcom 10 com ]; else fprintf('STUDY design %d not modified\n', index); end; end; if result.listboxdesign ~= STUDY.currentdesign fprintf('Selecting STUDY design %d\n', result.listboxdesign); com = sprintf('STUDY = std_selectdesign(STUDY, ALLEEG, %d);', result.listboxdesign); eval(com); allcom = [ allcom 10 com ]; end; if result.chk_save == 1 fprintf('Resaving STUDY\n'); [STUDY ALLEEG com] = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave'); allcom = [ allcom 10 com ]; end; if ~isempty(allcom), allcom(1) = []; end; elseif isstr(STUDY) com = STUDY; fig = ALLEEG; usrdat = get(fig, 'userdata'); datinfo = usrdat.datasetinfo; des = usrdat.design; filepath = usrdat.filepath; switch com % summary of callbacks % case 'add', Add new study design % case 'del', Delete study design % case 'rename', Rename study design % % case 'selectdesign', select a specific design % case 'updatedesign', update the study information (whenever the % user click on a button % % case 'selectfact', select a specific ind. var. (update value listboxes) % case 'combinevals', combine values in value listboxes % case 'selectsubj', select specific subjects % % case 'selectdatatrials', new GUI to select specific dataset and trials % case 'selectdatatrialssel', % select in the GUI above % case 'selectdatatrialsadd', % add new selection in the GUI above case 'add', % Add new study design inde = find( cellfun(@isempty,{ des.name })); if isempty(inde), inde = length(des)+1; end; des(inde(1)) = des(1); des(inde(1)).name = sprintf('Design %d', inde(1)); set(findobj(fig, 'tag', 'listboxdesign'), 'string', { des.name }, 'value', inde(1)); usrdat.design = des; set(fig, 'userdata', usrdat); pop_studydesign( 'selectstudy', fig); return; case 'del', % Delete study design val = get(findobj(fig, 'tag', 'listboxdesign'), 'value'); if val == 1 warndlg2('The first STUDY design cannot be removed, only modified'); return; end; des(val).name = ''; set(findobj(fig, 'tag', 'listboxdesign'), 'value', 1, 'string', { des.name } ); usrdat.design = des; set(fig, 'userdata', usrdat); pop_studydesign( 'selectstudy', fig); return; case 'rename', % Rename study design val = get(findobj(fig, 'tag', 'listboxdesign'), 'value'); strs = get(findobj(fig, 'tag', 'listboxdesign'), 'string'); result = inputdlg2( { 'Study design name: ' }, ... 'Rename Study Design', 1, { strs{val} }, 'pop_studydesign'); if isempty(result), return; end; des(val).name = result{1}; set(findobj(fig, 'tag', 'listboxdesign'), 'string', { des.name } ); case 'selectdesign', % select a specific design val = get(findobj(fig, 'tag', 'listboxdesign'), 'value'); if isempty(des(val).name) set(findobj(fig, 'tag', 'lbfact0'), 'string', '', 'value', 1); set(findobj(fig, 'tag', 'lbfact1'), 'string', '', 'value', 1); set(findobj(fig, 'tag', 'lbval0') , 'string', '', 'value', 1); set(findobj(fig, 'tag', 'lbval1') , 'string', '', 'value', 1); set(findobj(fig, 'tag', 'lbpair0'), 'value', 1); set(findobj(fig, 'tag', 'lbpair1'), 'value', 1); set(findobj(fig, 'tag', 'lbsubj') , 'value' , 1, 'string', ''); set(findobj(fig, 'tag', 'chk_del'), 'value', des(val).deletepreviousfiles ); set(findobj(fig, 'tag', 'edit_selectdattrials'), 'string', '' ); % do not change file path return; end; val1 = strmatch(des(val).variable(1).label, usrdat.factors, 'exact'); if isempty(val1), val1 = 1; end; val2 = strmatch(des(val).variable(2).label, usrdat.factors, 'exact'); if isempty(val2), val2 = 1; end; set(findobj(fig, 'tag', 'lbfact0'), 'string', usrdat.factors, 'value', val1); set(findobj(fig, 'tag', 'lbfact1'), 'string', usrdat.factors, 'value', val2); valfact1 = strmatchmult(des(val).variable(1).value, usrdat.factorvals{val1}); valfact2 = strmatchmult(des(val).variable(2).value, usrdat.factorvals{val2}); if isempty(valfact1), listboxtop1 = 1; else listboxtop1 = valfact1(1); end; if isempty(valfact2), listboxtop2 = 1; else listboxtop2 = valfact2(1); end; set(findobj(fig, 'tag', 'lbval0'), 'string', encodevals(usrdat.factorvals{val1}), 'value', valfact1, 'listboxtop', listboxtop1); set(findobj(fig, 'tag', 'lbval1'), 'string', encodevals(usrdat.factorvals{val2}), 'value', valfact2, 'listboxtop', listboxtop2); valsubj = strmatchmult(des(val).cases.value, usrdat.subjects); set(findobj(fig, 'tag', 'lbsubj'), 'string', usrdat.subjects, 'value', valsubj); if isempty(des(val).include), str = ''; else str = vararg2str(des(val).include); end; set(findobj(fig, 'tag', 'chk_del'), 'value', des(val).deletepreviousfiles ); set(findobj(fig, 'tag', 'edit_selectdattrials'), 'string', str ); set(findobj(fig, 'tag', 'popupselect'), 'value', 1 ); set(findobj(fig, 'tag', 'lbpair0'), 'value', fastif(isequal(des(val).variable(1).pairing,'on'),1,2)); set(findobj(fig, 'tag', 'lbpair1'), 'value', fastif(isequal(des(val).variable(2).pairing,'on'),1,2)); if ~isfield(des, 'filepath') || isempty(des(val).filepath), des(val).filepath = ''; end; set(findobj(fig, 'tag', 'edit_storedir'), 'string', des(val).filepath); case 'updatedesign', % update the study information (whenever the user click on a button) val = get(findobj(fig, 'tag', 'listboxdesign'), 'value'); val1 = get(findobj(fig, 'tag', 'lbfact0'), 'value'); val2 = get(findobj(fig, 'tag', 'lbfact1'), 'value'); valf1 = get(findobj(fig, 'tag', 'lbval0'), 'value'); valf2 = get(findobj(fig, 'tag', 'lbval1'), 'value'); valp1 = get(findobj(fig, 'tag', 'lbpair0'), 'value'); valp2 = get(findobj(fig, 'tag', 'lbpair1'), 'value'); vals = get(findobj(fig, 'tag', 'lbsubj'), 'value'); valchk = get(findobj(fig, 'tag', 'chk_del'), 'value'); filep = get(findobj(fig, 'tag', 'edit_storedir'), 'string'); strs = get(findobj(fig, 'tag', 'edit_selectdattrials'), 'string'); valpaired = { 'on' 'off' }; if ~strcmpi(des(val).variable(1).label, usrdat.factors{val1}) des(val).variable(1).label = usrdat.factors{val1}; des(val).variable(1).value = usrdat.factorvals{val1}(valf1); end; if ~strcmpi(des(val).variable(2).label, usrdat.factors{val2}) des(val).variable(2).label = usrdat.factors{val2}; des(val).variable(2).value = usrdat.factorvals{val2}(valf2); end; if ~isequal(mysort(des(val).variable(1).value), mysort(usrdat.factorvals{val1}(valf1))) des(val).variable(1).value = usrdat.factorvals{val1}(valf1); end; if ~isequal(mysort(des(val).variable(2).value), mysort(usrdat.factorvals{val2}(valf2))) des(val).variable(2).value = usrdat.factorvals{val2}(valf2); end; if ~isequal(mysort(des(val).cases.value), mysort(usrdat.subjects(vals))) des(val).cases.value = usrdat.subjects(vals); end; if ~isequal(des(val).variable(1).pairing, valpaired{valp1}) des(val).variable(1).pairing = valpaired{valp1}; end; if ~isequal(des(val).variable(2).pairing, valpaired{valp2}) des(val).variable(2).pairing = valpaired{valp2}; end; if ~isequal(des(val).deletepreviousfiles, valchk) des(val).deletepreviousfiles = 1; end; if ~isfield(des, 'filepath') || ~isequal(des(val).filepath, filep) des(val).filepath = filep; end; if ~isequal(des(val).include, strs) try, des(val).include = eval( [ '{' strs '}' ]); catch, disp('Error while decoding list of parameters'); des(val).include = {}; set(findobj(fig, 'tag', 'edit_selectdattrials'), 'string', ''); end; end; case 'selectfact', % select a specific ind. var. (update value listboxes) factval = designind; val = get(findobj(fig, 'tag', 'listboxdesign'), 'value'); val1 = get(findobj(fig, 'tag', [ 'lbfact' num2str(factval) ]), 'value'); val2 = get(findobj(fig, 'tag', [ 'lbfact' num2str(~factval) ]), 'value'); % if val1 == val2 && val1 ~= 1 % warndlg2('Cannot select twice the same independent variable'); % val1 = 1; % set(findobj(fig, 'tag', [ 'lbfact' num2str(factval) ]), 'value', val1); % end; valfact = [1:length(usrdat.factorvals{val1})]; set(findobj(fig, 'tag', ['lbval' num2str(factval) ]), 'string', encodevals(usrdat.factorvals{val1}), 'value', valfact, 'listboxtop', 1); pop_studydesign('updatedesign', fig); return; case 'combinevals', % combine values in value listboxes factval = designind; val1 = get(findobj(fig, 'tag', [ 'lbfact' num2str(factval) ]), 'value'); vals = get(findobj(fig, 'tag', [ 'lbval' num2str(factval) ]), 'value'); strs = get(findobj(fig, 'tag', [ 'lbval' num2str(factval) ]), 'string'); if length(vals) == 1 warndlg2('You need to select several values to combine them'); return; end; if ~iscell(usrdat.factorvals{val1}) warndlg2('Cannot combine values from numerical variables'); return; end; % combine values for string and integers if isstr(usrdat.factorvals{val1}{1}) || iscell(usrdat.factorvals{val1}{1}) tmpcell = {}; for indCell = vals(:)' if iscell(usrdat.factorvals{val1}{indCell}) tmpcell = { tmpcell{:} usrdat.factorvals{val1}{indCell}{:} }; else tmpcell = { tmpcell{:} usrdat.factorvals{val1}{indCell} }; end; end; usrdat.factorvals{val1}{end+1} = unique_bc(tmpcell); else usrdat.factorvals{val1}{end+1} = unique_bc([ usrdat.factorvals{val1}{vals} ]); end; set(findobj(fig, 'tag', ['lbval' num2str(factval) ]), 'string', encodevals(usrdat.factorvals{val1})); case 'selectsubj', % select specific subjects val = get(findobj(fig, 'tag', 'popupselect'), 'value'); str = get(findobj(fig, 'tag', 'popupselect'), 'string'); str = str{val}; if val == 1, subjbox = get(findobj(fig, 'tag', 'lbsubj'), 'string'); set(findobj(fig, 'tag', 'lbsubj'), 'value', [1:length(subjbox)]); return; end; indunders = findstr( ' - ', str); factor = str(1:indunders-1); factorval = str(indunders+3:end); % select subjects eval( [ 'allsetvals = { datinfo.' factor '};' ]); indset = strmatch(factorval, allsetvals, 'exact'); subjects = unique_bc( { datinfo(indset).subject } ); % change the subject listbox val = get(findobj(fig, 'tag', 'popupselect'), 'value'); subjbox = get(findobj(fig, 'tag', 'lbsubj'), 'string'); indsubj = []; for ind = 1:length(subjects); indsubj(ind) = strmatch(subjects{ind}, subjbox, 'exact'); end; set(findobj(fig, 'tag', 'lbsubj'), 'value', indsubj); set(findobj(fig, 'tag', 'popupselect'), 'value', 1); pop_studydesign('updatedesign', fig); return; %set(findobj(get(gcbf, ''userdata''), ''tag'', ''edit_selectdattrials'' case 'selectdatatrials', % select specific dataset and trials cb_sel = 'pop_studydesign(''selectdatatrialssel'',gcbf);'; cb_add = 'pop_studydesign(''selectdatatrialsadd'',gcbf);'; uilist = { { 'style' 'text' 'string' strvcat('Press ''Add'' to add data', 'selection. Multiple variables', 'are combined using AND.') } ... { 'style' 'text' 'string' 'Select data based on variable', 'fontweight' 'bold' } ... { 'style' 'listbox' 'string' usrdat.factors 'tag' 'lbfact2' 'callback' cb_sel 'value' 1 } ... { 'style' 'text' 'string' 'Select data based on value(s)' 'fontweight' 'bold' } ... { 'style' 'listbox' 'string' encodevals(usrdat.factorvals{1}) 'tag' 'lbval2' 'min' 0 'max' 2} }; cb_renamehelp = [ 'set(findobj(gcf, ''tag'', ''help''), ''string'', ''Add'');' ... 'set(findobj(gcf, ''tag'', ''cancel''), ''string'', ''Erase'', ''callback'', ''set(findobj(''''tag'''', ''''edit_selectdattrials''''), ''''string'''', '''''''');'');' ... 'set(findobj(gcf, ''tag'', ''ok''), ''string'', ''Close'');' ]; usrdat.fig = fig; inputgui('uilist', uilist, 'geometry', { [1] [1] [1] [1] [1] }, 'geomvert', [2 1 2.5 1 2.5], ... 'helpcom', cb_add, 'userdata', usrdat, 'eval', cb_renamehelp); pop_studydesign('updatedesign', fig); return; case 'selectdatatrialssel', % select in the GUI above val1 = get(findobj(fig, 'tag', 'lbfact2'), 'value'); valfact = [1:length(usrdat.factorvals{val1})]; tmpval = get(findobj(fig, 'tag', 'lbval2'), 'value'); if max(tmpval) > max(valfact) set(findobj(fig, 'tag', 'lbval2'), 'value', valfact, 'string', encodevals(usrdat.factorvals{val1})); else set(findobj(fig, 'tag', 'lbval2'), 'string', encodevals(usrdat.factorvals{val1}), 'value', valfact); end; return; case 'selectfolder', res = uigetdir; if ~isempty(findstr(filepath, res)) && findstr(filepath, res) == 1 res = res(length(filepath)+2:end); end; if res(1) == 0, return; end; set(findobj(fig, 'tag', 'edit_storedir'), 'string', res); pop_studydesign('updatedesign', fig); return; case 'selectdatatrialsadd', % Add button in the GUI above val1 = get(findobj(fig, 'tag', 'lbfact2'), 'value'); val2 = get(findobj(fig, 'tag', 'lbval2') , 'value'); objedit = findobj(usrdat.fig, 'tag', 'edit_selectdattrials'); str = get(objedit, 'string'); if ~isempty(str), str = [ str ',' ]; end; set(objedit, 'string', [ str vararg2str( { usrdat.factors{val1} usrdat.factorvals{val1}(val2) }) ]); return; end; usrdat.design = des; set(fig, 'userdata', usrdat); end; function res = strmatchmult(a, b); if isempty(b), res = []; return; end; res = zeros(1,length(a)); for index = 1:length(a) tmpi = std_indvarmatch(a{index}, b); res(index) = tmpi(1); % in case there is a duplicate end; %[tmp ind] = mysetdiff(b, a); %res = setdiff_bc([1:length(b)], ind); function cellarray = mysort(cellarray) return; % was crashing for combinations of selection % also there is no reason the order should be different if ~isempty(cellarray) && isstr(cellarray{1}) cellarray = sort(cellarray); end; function [cellout inds ] = mysetdiff(cell1, cell2); if (~isempty(cell1) && isstr(cell1{1})) || (~isempty(cell2) && isstr(cell2{1})) [ cellout inds ] = setdiff_bc(cell1, cell2); else [ cellout inds ] = setdiff_bc([ cell1{:} ], [ cell2{:} ]); cellout = mattocell(cellout); end; % encode string an numerical values for list boxes function cellout = encodevals(cellin) if isempty(cellin) cellout = {}; elseif ~iscell(cellin) cellout = { num2str(cellin) }; elseif ischar(cellin{1}) || iscell(cellin{1}) for index = 1:length(cellin) if isstr(cellin{index}) cellout{index} = cellin{index}; else cellout{index} = cellin{index}{1}; for indcell = 2:length(cellin{index}) cellout{index} = [ cellout{index} ' & ' cellin{index}{indcell} ]; end; end; end; else for index = 1:length(cellin) if length(cellin{index}) == 1 cellout{index} = num2str(cellin{index}); else cellout{index} = num2str(cellin{index}(1)); for indcell = 2:length(cellin{index}) cellout{index} = [ cellout{index} ' & ' num2str(cellin{index}(indcell)) ]; end; end; end; end;
github
ZijingMao/baselineeegtest-master
std_createclust.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_createclust.m
11,296
utf_8
324e2986c5494686e6ea9fa03913cb90
% std_createclust() - dreate a new empty cluster. After creation, components % may be (re)assigned to it using std_movecomp(). % Usage: % >> [STUDY] = std_createclust(STUDY, ALLEEG, 'key', val); % Inputs: % STUDY - STUDY set comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - vector of EEG datasets included in the STUDY, typically created % using load_ALLEEG(). % % Optional inputs: % 'name' - ['string'] name of the new cluster {default: 'Cls #', where % '#' is the next available cluster number} % 'clusterind' - [integer] cluster for each of the component. Ex: 61 components % and 2 clusters: 'clusterind' will be a 61x1 vector of 1 and % 2 (and 0=outlisers) % 'centroid' - centroid for clusters. If 2 clusters, size will be 2 x % width of the preclustering matrix. This is a deprecated % functionality. % 'algorithm' - [cell] algorithm parameters used to obtain the clusters % 'parentcluster' - ['on'|'off'] use the parent cluster (cluster 1) to % perform clustering (this cluster contains all the selected % components by default). Otherwise, the cluster defined in % STUDY.etc.preclust.clustlevel is used as parent. % % Outputs: % STUDY - the input STUDY set structure modified with the new cluster. % % Example: % >> [STUDY] = std_createclust(STUDY, ALLEEG, 'name', 'eye_movements', ... % 'clusterind', [0 1 0 1 0 1], 'parentcluster', 'on'); % % Create a new cluster named 'eye_movements' with components 2, 4, and % % of 6 the default parent cluster defined in % % See also pop_clustedit(), std_movecomp() % % Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 07, 2005, [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 [STUDY] = std_createclust(STUDY, ALLEEG, varargin) if nargin< 2 help std_createclust; return; end; % decoding options for backward compatibility % ------------------------------------------- options = {}; if length(varargin) > 0 && ~isstr(varargin{1}) % STUDY, IDX, algorithm, parentClusterNumber if isnumeric(ALLEEG) options = { options{:} 'clusterind' ALLEEG }; if nargin > 3, options = { options{:} 'centroid' varargin{1} }; end; if nargin > 4, options = { options{:} 'algorithm' varargin{2} }; end; ALLEEG = []; end; elseif length(varargin) < 2 options = { options{:} 'name' varargin{1} }; else options = varargin; end; opt = finputcheck(options, { 'name' 'string' [] 'Cls'; 'clusterind' 'integer' [] length(STUDY.cluster)+1; 'parentcluster' 'string' { 'on','off' } 'off'; 'algorithm' 'cell' [] {}; 'ignore0' 'string' { 'on','off' } 'off'; 'centroid' 'real' [] [] }, 'std_createclust'); if isstr(opt), error(opt); end; % opt.clusterind - index of cluster for each component. Ex: 63 components and 2 % clusters: opt.clusterind will be a 61x1 vector of 1 and 2 (and 0=outlisers) % C - centroid for clusters. If 2 clusters, size will be 2 x % width of the preclustering matrix if strcmpi(opt.parentcluster, 'on') firstind = 1; cls = 1; sameica = std_findsameica(ALLEEG); sets = []; comps = []; STUDY.cluster = []; for index = 1:length(sameica) newcomps = STUDY.datasetinfo(sameica{index}(1)).comps; if isempty(newcomps), newcomps = [1:size(ALLEEG(sameica{index}(1)).icaweights,1)]; end; comps = [ comps newcomps ]; sets(length(sameica{index}):-1:1,end+1:end+length(newcomps)) = repmat( sameica{index}', [1 length(newcomps) ] ); end; sets(find(sets == 0)) = NaN; STUDY.cluster(1).name = 'Parentcluster 1'; STUDY.cluster(1).sets = sets; STUDY.cluster(1).comps = comps; STUDY.cluster(1).parent = {}; STUDY.cluster(1).child = {}; STUDY.cluster.preclust.preclustparams = []; STUDY.cluster.preclust.preclustdata = []; if isfield(STUDY, 'design') && ~isempty(STUDY.design) STUDY.cluster = std_setcomps2cell(STUDY, 1); end; else % Find the next available cluster index % ------------------------------------- cls = min(max(opt.clusterind), length(unique(opt.clusterind))); nc = 0; % index of last cluster for k = 1:length(STUDY.cluster) ti = strfind(STUDY.cluster(k).name, ' '); tmp = STUDY.cluster(k).name(ti(end) + 1:end); nc = max(nc,str2num(tmp)); % check if there is a cluster of Notclust components if isfield(STUDY.etc, 'preclust') && isfield(STUDY.etc.preclust, 'preclustparams') if ~isempty(STUDY.cluster(k).parent) %strcmp(STUDY.cluster(k).parent,STUDY.cluster(STUDY.etc.preclust.clustlevel).name) STUDY.cluster(k).preclust.preclustparams = STUDY.etc.preclust.preclustparams; end; end end len = length(STUDY.cluster); if ~isempty(find(opt.clusterind==0)) && strcmpi(opt.ignore0, 'off') %outliers exist firstind = 0; nc = nc + 1; len = len + 1; else firstind = 1; end % create clustlevel if it does not exist % -------------------------------------- if ~isfield(STUDY.etc, 'preclust') STUDY.etc.preclust.clustlevel = 1; STUDY.etc.preclust.preclustdata = []; elseif ~isfield(STUDY.etc.preclust, 'clustlevel') STUDY.etc.preclust.clustlevel = 1; STUDY.etc.preclust.preclustdata = []; end; % create all clusters % ------------------- for k = firstind:cls % cluster name % ------------ if k == 0 STUDY.cluster(len).name = [ 'outlier ' num2str(k+nc)]; else STUDY.cluster(k+len).name = [ opt.name ' ' num2str(k+nc)]; end % find indices % ------------ tmp = find(opt.clusterind==k); % opt.clust.erind contains the cluster index for each component STUDY.cluster(k+len).sets = STUDY.cluster(STUDY.etc.preclust.clustlevel).sets(:,tmp); STUDY.cluster(k+len).comps = STUDY.cluster(STUDY.etc.preclust.clustlevel).comps(tmp); STUDY.cluster(k+len).algorithm = opt.algorithm; STUDY.cluster(k+len).parent{end+1} = STUDY.cluster(STUDY.etc.preclust.clustlevel).name; STUDY.cluster(k+len).child = []; if ~isempty(STUDY.etc.preclust.preclustdata) && all(tmp <= size(STUDY.etc.preclust.preclustdata,1)) STUDY.cluster(k+len).preclust.preclustdata = STUDY.etc.preclust.preclustdata(tmp,:); STUDY.cluster(k+len).preclust.preclustparams = STUDY.etc.preclust.preclustparams; else STUDY.cluster(k+len).preclust.preclustdata = []; end; STUDY.cluster(k+len) = std_setcomps2cell(STUDY, k+len); %update parents clusters with cluster child indices % ------------------------------------------------- STUDY.cluster(STUDY.etc.preclust.clustlevel).child{end+1} = STUDY.cluster(k+nc).name; end end; % Find out the highst cluster id number (in cluster name), to find % next available cluster index % % find max cluster ID % % max_id = 0; % if ~isfield(STUDY, 'cluster'), STUDY.cluster = []; end; % for k = 1:length(STUDY.cluster) % ti = strfind(STUDY.cluster(k).name, ' '); % clus_id = STUDY.cluster(k).name(ti(end) + 1:end); % max_id = max(max_id, str2num(clus_id)); % end % max_id = max_id + 1; % opt.name = sprintf('%s %d', opt.name, max_id); % clustind = length(STUDY.cluster)+1; % % Initialize the new cluster fields. % if length(STUDY.cluster) > 0 % STUDY.cluster(clustind).parent{1} = STUDY.cluster(1).name; % if ~iscell(STUDY.cluster(1).child) % STUDY.cluster(1).child = { opt.name }; % else STUDY.cluster(1).child = { STUDY.cluster(1).child{:} opt.name }; % end; % else % STUDY.cluster(clustind).parent{1} = 'manual'; % update parent cluster if exists. % end; % STUDY.cluster(clustind).name = opt.name; % STUDY.cluster(clustind).child = []; % STUDY.cluster(clustind).comps = []; % STUDY.cluster(clustind).sets = []; % STUDY.cluster(clustind).algorithm = []; % STUDY.cluster(clustind).centroid = []; % STUDY.cluster(clustind).preclust.preclustparams = []; % STUDY.cluster(clustind).preclust.preclustdata = []; % % if (~isempty(opt.datasets) | ~isempty(opt.subjects)) & ~isempty(opt.components) % % % convert subjects to dataset indices % % ----------------------------------- % if ~isempty(opt.subjects) % if length(opt.subjects) ~= length(opt.components) % error('If subjects are specified, the length of the cell array must be the same as for the components'); % end; % alls = { ALLEEG.subject }; % for index = 1:length(opt.subjects) % tmpinds = strmatch(opt.subjects{index}, alls, 'exact'); % if isempty(tmpinds) % error('Cannot find subject'); % end; % opt.datasets(1:length(tmpinds),index) = tmpinds; % end; % opt.datasets(opt.datasets(:) == 0) = NaN; % end; % % % deal with cell array inputs % % --------------------------- % if iscell(opt.components) % newcomps = []; % newdats = []; % for ind1 = 1:length(opt.components) % for ind2 = 1:length(opt.components{ind1}) % if iscell(opt.datasets) % newdats = [ newdats opt.datasets{ind1}' ]; % else newdats = [ newdats opt.datasets(:,ind1) ]; % end; % newcomps = [ newcomps opt.components{ind1}(ind2) ]; % end; % end; % opt.datasets = newdats; % opt.components = newcomps; % end; % % % create .sets, .comps, .setinds, .allinds fields % % ----------------------------------------------- % [tmp setinds allinds] = std_setcomps2cell( STUDY, opt.datasets, opt.components); % STUDY.cluster(clustind).setinds = setinds; % STUDY.cluster(clustind).allinds = allinds; % STUDY.cluster(clustind) = std_cell2setcomps( STUDY, ALLEEG, clustind); % STUDY.cluster(clustind) = std_setcomps2cell( STUDY, clustind); % %[ STUDY.cluster(finalinds(ind)) setinds allinds ] = % %std_setcomps2cell(STUDY, finalinds(ind)); % end;
github
ZijingMao/baselineeegtest-master
std_checkconsist.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_checkconsist.m
2,299
utf_8
e6cbe33ddc8c1fb52b95a02d9bfff1e3
% std_checkconsist() - Create channel groups for plotting. % % Usage: % >> boolval = std_checkconsist(STUDY, 'uniform', 'condition'); % >> boolval = std_checkconsist(STUDY, 'uniform', 'group'); % Inputs: % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % 'uniform' - ['condition'|'group'] check if there is one group % condition per subject % Outputs: % boolval - [0|1] 1 if uniform % % Authors: Arnaud Delorme, CERCO, 2009 % Copyright (C) Arnaud Delorme, CERCO, [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 [boolval npersubj] = std_checkconsist(STUDY, varargin); if nargin < 3 help std_checkconsist; return; end; opt = struct(varargin{:}); if strcmpi(opt.uniform, 'condition') allvals = { STUDY.datasetinfo.condition }; vallist = STUDY.condition; elseif strcmpi(opt.uniform, 'group') allvals = { STUDY.datasetinfo.group }; vallist = STUDY.group; elseif strcmpi(opt.uniform, 'session') allvals = { STUDY.datasetinfo.session }; allvals = cellfun(@num2str, allvals, 'uniformoutput', false); vallist = STUDY.session; if isempty(vallist), boolval = 1; return; end; vallist = cellfun(@num2str, mattocell(vallist), 'uniformoutput', false); else error('unknown option'); end; if isempty(vallist), boolval = 1; return; end; for index = 1:length(vallist) tmplist = strmatch( vallist{index}, allvals, 'exact'); vallen(index) = length(unique( { STUDY.datasetinfo(tmplist).subject } )); end; if length(unique(vallen)) == 1 boolval = 1; else boolval = 0; end;
github
ZijingMao/baselineeegtest-master
std_readersp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readersp.m
27,159
utf_8
f5d97a5a750d3b52e1853a6264369d5f
% std_readersp() - load ERSP measures for data channels or for all % components of a specified cluster. This function is % also being used to read ITC and ERPimage data. % Usage: % >> [STUDY, erspdata, times, freqs, erspbase] = ... % std_readersp(STUDY, ALLEEG, varargin); % Inputs: % STUDY - studyset structure containing some or all files in ALLEEG % ALLEEG - vector of loaded EEG datasets % % Optional inputs: % 'design' - [integer] read files from a specific STUDY design. Default % is empty (use current design in STUDY.currentdesign). % 'channels' - [cell] list of channels to import {default: none} % 'clusters' - [integer] list of clusters to import {[]|default: all but % the parent cluster (1) and any 'NotClust' clusters} % 'singletrials' - ['on'|'off'] load single trials spectral data (if % available). Default is 'off'. % 'forceread' - ['on'|'off'] Force rereading data from disk. % Default is 'off'. % 'subject' - [string] select a specific subject {default:all} % 'component' - [integer] select a specific component in a cluster % {default:all} % 'datatype' - {'ersp'|'itc'|'erpim'} This function is used to read all % 2-D STUDY matrices stored on disk (not only ERSP). It may % read ERSP ('ersp' option), ITC ('itc' option) or ERPimage % data ('erpim' option). % % ERSP specific options: % 'timerange' - [min max] time range {default: whole measure range} % 'freqrange' - [min max] frequency range {default: whole measure range} % 'subbaseline' - ['on'|'off'] subtract the ERSP baseline for paired % conditions. The conditions for which baseline is removed % are indicated on the command line. See help % std_studydesign for more information about paired and % unpaired variables. % % ERPimage specific option: % This function is used to read all 2-D STUDY matrices stored on disk % (this includes ERPimages). It therefore takes as input specific % ERPimage options. Note that the 'singletrials' optional input is % irrelevant for ERPimages (which are always stored as single trials). % 'concatenate' - ['on'|'off'] read concatenated ERPimage data ('on') or % stacked ERPimage data. See help std_erpimage for more % information. % 'timerange' - [min max] time range {default: whole measure range} % 'trialrange' - [min max] read only a specific range of the ERPimage % output trials {default: whole measure range} % Output: % STUDY - updated studyset structure % erspdata - [cell array] ERSP data (the cell array size is % condition x groups). This may also be ITC data or ERPimage % data (see above). % times - [float array] array of time points % freqs - [float array] array of frequencies. For ERPimage this % contains trial indices. % erspbase - [cell array] baseline values % events - [cell array] events (ERPimage only). % % Author: Arnaud Delorme, CERCO, 2006- % Copyright (C) Arnaud Delorme, [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 [STUDY, erspdata, alltimes, allfreqs, erspbase, events, unitPower] = std_readersp(STUDY, ALLEEG, varargin) if nargin < 2 help std_readersp; return; end events = {}; unitPower = 'dB'; if ~isstruct(ALLEEG) % old calling format dataset = ALLEEG; EEG = STUDY(dataset); comp = varargin{1}; if length(varargin) > 1, timelim = varargin{2}; else timelim = []; end; if length(varargin) > 2, freqlim = varargin{3}; else freqlim = []; end; filebase = fullfile(EEG.filepath, EEG.filename(1:end-4)); if comp < 0 error('Old format function call, channel reading not supported'); [ersp params alltimes allfreqs] = std_readfile(filebase, 'channels', -comp, 'timelimits', timelim, 'freqlimits', freqlim); else [ersp params alltimes allfreqs] = std_readfile(filebase, 'components', comp, 'timelimits', timelim, 'freqlimits', freqlim, 'measure', 'ersp'); [erspbase params alltimes allfreqs] = std_readfile(filebase, 'components', comp, 'timelimits', timelim, 'freqlimits', freqlim, 'measure', 'erspbase'); end; STUDY = ersp; erspdata = allfreqs; allfreqs = params; return; end; STUDY = pop_erspparams( STUDY, 'default'); STUDY = pop_erpimparams(STUDY, 'default'); [opt moreopts] = finputcheck( varargin, { ... 'design' 'integer' [] STUDY.currentdesign; 'channels' 'cell' [] {}; 'clusters' 'integer' [] []; 'trialrange' 'real' [] STUDY.etc.erpimparams.trialrange; 'freqrange' 'real' [] STUDY.etc.erspparams.freqrange; 'timerange' 'real' [] NaN; 'singletrials' 'string' { 'on','off' } 'off'; 'forceread' 'string' { 'on','off' } 'off'; 'concatenate' 'string' { 'on','off' } STUDY.etc.erpimparams.concatenate; 'subbaseline' 'string' { 'on','off' } STUDY.etc.erspparams.subbaseline; 'component' 'integer' [] []; 'infotype' 'string' { 'ersp','itc','erpim' } 'ersp'; ... % deprecated 'datatype' 'string' { 'ersp','itc','erpim' } 'ersp'; ... 'subject' 'string' [] '' }, ... 'std_readersp', 'ignore'); if isstr(opt), error(opt); end; if ~strcmpi(opt.infotype, 'ersp'), opt.datatype = opt.infotype; end; if strcmpi(opt.datatype, 'erpim'), if isnan(opt.timerange), opt.timerange = STUDY.etc.erpimparams.timerange; end; opt.freqrange = opt.trialrange; ordinate = 'trials'; else if isnan(opt.timerange) opt.timerange = STUDY.etc.erspparams.timerange; end; ordinate = 'freqs'; end; nc = max(length(STUDY.design(opt.design).variable(1).value),1); ng = max(length(STUDY.design(opt.design).variable(2).value),1); paired1 = STUDY.design(opt.design).variable(1).pairing; paired2 = STUDY.design(opt.design).variable(2).pairing; dtype = opt.datatype; % find channel indices % -------------------- if ~isempty(opt.channels) allChangrp = lower({ STUDY.changrp.name }); finalinds = std_chaninds(STUDY, opt.channels); else finalinds = opt.clusters; end; for ind = 1:length(finalinds) erspbase = cell( nc, ng ); % find indices % ------------ if ~isempty(opt.channels) tmpstruct = STUDY.changrp(finalinds(ind)); allinds = tmpstruct.allinds; setinds = tmpstruct.setinds; else tmpstruct = STUDY.cluster(finalinds(ind)); allinds = tmpstruct.allinds; setinds = tmpstruct.setinds; end; % check if data is already here % ----------------------------- if strcmpi(dtype, 'erpim') % ERP images dataread = 0; eqtf = isequal( STUDY.etc.erpimparams.timerange , opt.timerange) && ... isequal( STUDY.etc.erpimparams.trialrange, opt.trialrange); if isfield(tmpstruct, 'erpimdata') && eqtf && ~isempty(tmpstruct.erpimdata) dataread = 1; end; else dataread = 0; eqtf = isequal( STUDY.etc.erspparams.timerange, opt.timerange) && ... isequal( STUDY.etc.erspparams.freqrange, opt.freqrange); eqtfb = isequal( STUDY.etc.erspparams.subbaseline, opt.subbaseline) && eqtf; if strcmpi(opt.singletrials,'off') if isfield(tmpstruct, [ dtype 'data']) && eqtfb && ~isempty(getfield(tmpstruct, [ dtype 'data'])) dataread = 1; end; else if isfield(tmpstruct, [ dtype 'datatrials']) && eqtf && ~isempty(getfield(tmpstruct, [ dtype 'datatrials'])) if ~isempty(opt.channels) && strcmpi(getfield(tmpstruct, [ dtype 'trialinfo' ]), opt.subject) dataread = 1; elseif isempty(opt.channels) && isequal(getfield(tmpstruct, [ dtype 'trialinfo' ]), opt.component) dataread = 1; end; end; end; end; if dataread && strcmpi(opt.forceread, 'off') disp('Using pre-loaded data. To force rereading data from disk use the ''forceread'' flag'); else if strcmpi(dtype, 'erpim') % ERP images if strcmpi(opt.singletrials, 'on') error( [ 'Single trial loading option not supported with STUDY ERP-image' 10 '(there is no such thing as a single-trial ERPimage)' ]); end; % read the data and select channels % --------------------------------- setinfo = STUDY.design(opt.design).cell; erpim = cell( nc, ng ); events = cell( nc, ng ); for c = 1:nc for g = 1:ng if ~isempty(setinds{c,g}) if ~isempty(opt.channels), opts = { 'channels', allChangrp(allinds{c,g}(:)), 'timelimits', opt.timerange, 'triallimits', opt.trialrange, 'concatenate', opt.concatenate }; else opts = { 'components', allinds{c,g}(:), 'timelimits', opt.timerange, 'triallimits', opt.trialrange, 'concatenate', opt.concatenate }; end; [erpim{c, g} tmpparams alltimes alltrials events{c,g}] = std_readfile( setinfo(setinds{c,g}(:)), 'measure', 'erpim', opts{:}); fprintf('.'); end; end; end; if strcmpi(opt.concatenate, 'on'), alltrials = []; end; fprintf('\n'); ersp = erpim; allfreqs = alltrials; else % ERSP/ITC % reserve arrays % -------------- events = {}; ersp = cell( nc, ng ); erspinds = cell( nc, ng ); % find total nb of trials % THIS CODE IS NOT NECESSARY ANY MORE (SEE BUG 1170) % ----------------------- %setinfo = STUDY.design(opt.design).cell; %tottrials = cell( nc, ng ); %if strcmpi(opt.singletrials, 'on') % for indSet = 1:length(setinfo) % condind = std_indvarmatch( setinfo(indSet).value{1}, STUDY.design(opt.design).variable(1).value ); % grpind = std_indvarmatch( setinfo(indSet).value{2}, STUDY.design(opt.design).variable(2).value ); % if isempty(tottrials{condind, grpind}), tottrials{condind, grpind} = sum(cellfun(@length, setinfo(indSet).trials)); % else tottrials{condind, grpind} = tottrials{condind, grpind} + sum(cellfun(@length, setinfo(indSet).trials)); % end; % end; %end; % read the data and select channels % --------------------------------- fprintf('Reading all %s data:', upper(dtype)); setinfo = STUDY.design(opt.design).cell; if strcmpi(opt.singletrials, 'on') for c = 1:nc for g = 1:ng if ~isempty(opt.channels) allsubjects = { STUDY.design(opt.design).cell.case }; if ~isempty(opt.subject), inds = strmatch( opt.subject, allsubjects(setinds{c,g})); else inds = 1:length(allinds{c,g}); end; else if ~isempty(opt.component) inds = find( allinds{c,g} == STUDY.cluster(finalinds(ind)).comps(opt.component)); else inds = 1:length(allinds{c,g}); end; end; if ~isempty(inds) count{c, g} = 1; for indtmp = 1:length(inds) setindtmp = STUDY.design(opt.design).cell(setinds{c,g}(inds(indtmp))); tmpopts = { 'measure', 'timef' 'timelimits', opt.timerange, 'freqlimits', opt.freqrange }; if ~isempty(opt.channels), [ tmpersp tmpparams alltimes allfreqs] = std_readfile(setindtmp, 'channels', allChangrp(allinds{c,g}(inds(indtmp))), tmpopts{:}); else [ tmpersp tmpparams alltimes allfreqs] = std_readfile(setindtmp, 'components', allinds{c,g}(inds(indtmp)), tmpopts{:}); end; indices = [count{c, g}:count{c, g}+size(tmpersp,3)-1]; if indtmp == 1 ersp{c, g} = permute(tmpersp, [2 1 3]); else ersp{c, g}(:,:,indices) = permute(tmpersp, [2 1 3]); end; erspinds{c, g}(1:2,indtmp) = [ count{c, g} count{c, g}+size(tmpersp,3)-1 ]; count{c, g} = count{c, g}+size(tmpersp,3); if size(tmpersp,3) ~= sum(cellfun(@length, setindtmp.trials)) error( sprintf('Wrong number of trials in datafile for design index %d\n', setinds{c,g}(inds(indtmp)))); end; end; end; end; end; else for c = 1:nc for g = 1:ng if ~isempty(setinds{c,g}) if ~isempty(opt.channels), opts = { 'channels', allChangrp(allinds{c,g}(:)), 'timelimits', opt.timerange, 'freqlimits', opt.freqrange }; else opts = { 'components', allinds{c,g}(:) , 'timelimits', opt.timerange, 'freqlimits', opt.freqrange }; end; if strcmpi(dtype, 'ersp') erspbase{c, g} = std_readfile( setinfo(setinds{c,g}(:)), 'measure', 'erspbase', opts{:}); [ ersp{c, g} tmpparams alltimes allfreqs ] = std_readfile( setinfo(setinds{c,g}(:)), 'measure', 'ersp' , opts{:}); else [ ersp{c, g} tmpparams alltimes allfreqs ] = std_readfile( setinfo(setinds{c,g}(:)), 'measure', 'itc' , opts{:}); ersp{c, g} = abs(ersp{c, g}); end; fprintf('.'); %ersp{c, g} = permute(ersp{c, g} , [3 2 1]); %erspbase{c, g} = 10*log(permute(erspbase{c, g}, [3 2 1])); end; end; end; end; fprintf('\n'); % compute ERSP or ITC if trial mode % (since only the timef have been loaded) % --------------------------------------- if strcmpi(opt.singletrials, 'on') tmpparams2 = fieldnames(tmpparams); tmpparams2 = tmpparams2'; tmpparams2(2,:) = struct2cell(tmpparams); precomp.times = alltimes; precomp.freqs = allfreqs; precomp.recompute = dtype; for c = 1:nc for g = 1:ng if ~isempty(ersp{c,g}) precomp.tfdata = permute(ersp{c,g}, [2 1 3]); if strcmpi(dtype, 'itc') [tmp ersp{c,g}] = newtimef(zeros(ALLEEG(1).pnts,2), ALLEEG(1).pnts, [ALLEEG(1).xmin ALLEEG(1).xmax]*1000, ... ALLEEG(1).srate, [], tmpparams2{:}, 'precomputed', precomp, 'verbose', 'off'); elseif strcmpi(dtype, 'ersp') [ersp{c,g} tmp] = newtimef(zeros(ALLEEG(1).pnts,2), ALLEEG(1).pnts, [ALLEEG(1).xmin ALLEEG(1).xmax]*1000, ... ALLEEG(1).srate, [], tmpparams2{:}, 'precomputed', precomp, 'verbose', 'off'); end; ersp{c,g} = permute(ersp{c,g}, [2 1 3]); end; end; end; end; % compute average baseline across groups and conditions % ----------------------------------------------------- if strcmpi(opt.subbaseline, 'on') && strcmpi(dtype, 'ersp') if strcmpi(opt.singletrials, 'on') disp('WARNING: no ERSP baseline may not be subtracted when using single trials'); else disp('Recomputing baseline...'); if strcmpi(paired1, 'on') && strcmpi(paired2, 'on') disp('Removing ERSP baseline for both indep. variables'); meanpowbase = computeerspbaseline(erspbase(:), opt.singletrials); ersp = removeerspbaseline(ersp, erspbase, meanpowbase); elseif strcmpi(paired1, 'on') disp('Removing ERSP baseline for first indep. variables (second indep. var. is unpaired)'); for g = 1:ng % ng = number of groups meanpowbase = computeerspbaseline(erspbase(:,g), opt.singletrials); ersp(:,g) = removeerspbaseline(ersp(:,g), erspbase(:,g), meanpowbase); end; elseif strcmpi(paired2, 'on') disp('Removing ERSP baseline for second indep. variables (first indep. var. is unpaired)'); for c = 1:nc % ng = number of groups meanpowbase = computeerspbaseline(erspbase(c,:), opt.singletrials); ersp(c,:) = removeerspbaseline(ersp(c,:), erspbase(c,:), meanpowbase); end; else disp('Not removing ERSP baseline (both indep. variables are unpaired'); end; end; end; end; % if strcmpi(opt.statmode, 'common') % % collapse the two last dimensions before computing significance % % i.e. 18 subject with 4 channels -> same as 4*18 subjects % % -------------------------------------------------------------- % disp('Using all channels for statistics...'); % for c = 1:nc % for g = 1:ng % ersp{c,g} = reshape( ersp{c,g}, size(ersp{c,g},1), size(ersp{c,g},2), size(ersp{c,g},3)*size(ersp{c,g},4)); % end; % end; % end; % copy data to structure % ---------------------- if ~isempty(events) tmpstruct = setfield(tmpstruct, [ dtype 'events' ], events); end; tmpstruct = setfield(tmpstruct, [ dtype ordinate ], allfreqs); tmpstruct = setfield(tmpstruct, [ dtype 'times' ], alltimes); if strcmpi(opt.singletrials, 'on') tmpstruct = setfield(tmpstruct, [ dtype 'datatrials' ], ersp); tmpstruct = setfield(tmpstruct, [ dtype 'subjinds' ], erspinds); tmpstruct = setfield(tmpstruct, [ dtype 'times' ], alltimes); if ~isempty(opt.channels) tmpstruct = setfield(tmpstruct, [ dtype 'trialinfo' ], opt.subject); else tmpstruct = setfield(tmpstruct, [ dtype 'trialinfo' ], opt.component); end; else tmpstruct = setfield(tmpstruct, [ dtype 'data' ], ersp); if strcmpi(dtype, 'ersp') tmpstruct = setfield(tmpstruct, [ dtype 'base' ], erspbase); end; end; % copy results to structure % ------------------------- fields = { [ dtype 'data' ] [ dtype 'events' ] [ dtype ordinate ] [ dtype 'datatrials' ] ... [ dtype 'subjinds' ] [ dtype 'base' ] [ dtype 'times' ] [ dtype 'trialinfo' ] 'allinds' 'setinds' }; for f = 1:length(fields) if isfield(tmpstruct, fields{f}), tmpdata = getfield(tmpstruct, fields{f}); if ~isempty(opt.channels) STUDY.changrp = setfield(STUDY.changrp, { finalinds(ind) }, fields{f}, tmpdata); else STUDY.cluster = setfield(STUDY.cluster, { finalinds(ind) }, fields{f}, tmpdata); end; end; end; end; end; % output unit % ----------- if exist('tmpparams') ~= 1 if ~isempty(opt.channels), [tmpersp tmpparams] = std_readfile(STUDY.design(opt.design).cell(1), 'channels', {STUDY.changrp(1).name}, 'measure', opt.datatype); else [tmpersp tmpparams] = std_readfile(STUDY.design(opt.design).cell(1), 'components', STUDY.cluster(finalinds(end)).allinds{1,1}(1), 'measure', opt.datatype); end; end; if ~isfield(tmpparams, 'baseline'), tmpparams.baseline = 0; end; if ~isfield(tmpparams, 'scale' ), tmpparams.scale = 'log'; end; if ~isfield(tmpparams, 'basenorm'), tmpparams.basenorm = 'off'; end; if strcmpi(tmpparams.scale, 'log') if strcmpi(tmpparams.basenorm, 'on') unitPower = '10*log(std.)'; % impossible elseif isnan(tmpparams.baseline) unitPower = '10*log10(\muV^{2}/Hz)'; else unitPower = 'dB'; end; else if strcmpi(tmpparams.basenorm, 'on') unitPower = 'std.'; elseif isnan(tmpparams.baseline) unitPower = '\muV^{2}/Hz'; else unitPower = '% of baseline'; end; end; % return structure % ---------------- if nargout <2 return end allinds = finalinds; if ~isempty(opt.channels) structdat = STUDY.changrp; erspdata = cell(nc, ng); events = {}; for ind = 1:length(erspdata(:)) if strcmpi(opt.singletrials, 'on') tmpdat = getfield(structdat(allinds(1)), [ dtype 'datatrials' ]); else tmpdat = getfield(structdat(allinds(1)), [ dtype 'data' ]); end; if ndims(tmpdat{ind}) == 2, erspdata{ind} = zeros([ size(tmpdat{ind}) 1 length(allinds)]); else erspdata{ind} = zeros([ size(tmpdat{ind}) length(allinds)]); end; for index = 1:length(allinds) if strcmpi(opt.singletrials, 'on') tmpdat = getfield(structdat(allinds(index)), [ dtype 'datatrials' ]); else tmpdat = getfield(structdat(allinds(index)), [ dtype 'data' ]); end; erspdata{ind}(:,:,:,index) = tmpdat{ind}; allfreqs = getfield(structdat(allinds(index)), [ dtype ordinate ]); alltimes = getfield(structdat(allinds(index)), [ dtype 'times' ]); if isfield(structdat, [ dtype 'events' ]) events = getfield(structdat(allinds(index)), [ dtype 'events' ]); end; compinds = structdat(allinds(index)).allinds; setinds = structdat(allinds(index)).setinds; end; erspdata{ind} = permute(erspdata{ind}, [1 2 4 3]); % time freqs elec subjects end; if ~isempty(opt.subject) && strcmpi(opt.singletrials,'off') erspdata = std_selsubject(erspdata, opt.subject, setinds, { STUDY.design(opt.design).cell.case }, 2); end; else if strcmpi(opt.singletrials, 'on') erspdata = getfield(STUDY.cluster(allinds(1)), [ dtype 'datatrials' ]); else erspdata = getfield(STUDY.cluster(allinds(1)), [ dtype 'data' ]); end; allfreqs = getfield(STUDY.cluster(allinds(1)), [ dtype ordinate ]); alltimes = getfield(STUDY.cluster(allinds(1)), [ dtype 'times' ]); if isfield(STUDY.cluster, [ dtype 'events' ]) events = getfield(STUDY.cluster(allinds(1)), [ dtype 'events' ]); end; compinds = STUDY.cluster(allinds(1)).allinds; setinds = STUDY.cluster(allinds(1)).setinds; if ~isempty(opt.component) && length(allinds) == 1 && strcmpi(opt.singletrials,'off') erspdata = std_selcomp(STUDY, erspdata, allinds, setinds, compinds, opt.component); end; end; % compute ERSP baseline % --------------------- function meanpowbase = computeerspbaseline(erspbase, singletrials) try len = length(erspbase(:)); count = 0; for index = 1:len if ~isempty(erspbase{index}) if strcmpi(singletrials, 'on') if count == 0, meanpowbase = abs(mean(erspbase{index},3)); else meanpowbase = meanpowbase + abs(mean(erspbase{index},3)); end; else if count == 0, meanpowbase = abs(erspbase{index}); else meanpowbase = meanpowbase + abs(erspbase{index}); end; end; count = count+1; end; end; meanpowbase = reshape(meanpowbase , [size(meanpowbase,1) 1 size(meanpowbase,2)])/count; catch, error([ 'Problem while subtracting common ERSP baseline.' 10 ... 'Common baseline subtraction is performed based on' 10 ... 'pairing settings in your design. Most likelly, one' 10 ... 'independent variable should not have its data paired.' ]); end; % remove ERSP baseline % --------------------- function ersp = removeerspbaseline(ersp, erspbase, meanpowbase) convert2log = 0; for g = 1:size(ersp,2) % ng = number of groups for c = 1:size(ersp,1) if ~isempty(erspbase{c,g}) && ~isempty(ersp{c,g}) erspbasetmp = reshape(erspbase{c,g}, [size(meanpowbase,1) 1 size(meanpowbase,3)]); if any(erspbasetmp(:) > 1000) convert2log = 1; end; tmpmeanpowbase = repmat(meanpowbase, [1 size(ersp{c,g},2) 1]); if convert2log ersp{c,g} = ersp{c,g} - repmat(10*log10(erspbasetmp), [1 size(ersp{c,g},2) 1 1]) + 10*log10(tmpmeanpowbase); else ersp{c,g} = ersp{c,g} - repmat(abs(erspbasetmp), [1 size(ersp{c,g},2) 1 1]) + tmpmeanpowbase; end; end; end; end;
github
ZijingMao/baselineeegtest-master
std_moveoutlier.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_moveoutlier.m
3,042
utf_8
d3911bba9d7caea1be8f3002aac0e6aa
% std_moveoutlier() - Commandline function, to reassign specified outlier component(s) % from a cluster to its outlier cluster. % Usage: % >> STUDY = std_moveoutlier(STUDY, ALLEEG, from_cluster, comps); % Inputs: % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - global EEGLAB vector of EEG structures for the dataset(s) included in the STUDY. % ALLEEG for a STUDY set is typically created using load_ALLEEG(). % from_cluster - cluster number, the cluster outlier components are moved from. % comps - [numeric vector] component indices in the from_cluster to move. % % Outputs: % STUDY - the input STUDY set structure modified with the components reassignment. % % Example: % >> from_cluster = 10; comps = [2 7]; % >> STUDY = std_movecomp(STUDY,ALLEEG, from_cluster, to_cluster, comps); % Components 2 and 7 of cluster 10 are moved to the its outlier cluster ('Outliers Cls 10'). % % See also pop_clustedit % % Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, June, 2005 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, June 07, 2005, [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 STUDY = std_moveoutlier(STUDY, ALLEEG, old_clus, comps) % Cannot move components if the cluster is either a 'Notclust' or % 'Outliers' cluster if strncmpi('Notclust',STUDY.cluster(old_clus).name,8) | strncmpi('Outliers',STUDY.cluster(old_clus).name,8) warndlg2('std_moveoutlier: cannot move components from Notclust or Outliers cluster'); return; end % Cannot move components if clusters have children clusters if ~isempty(STUDY.cluster(old_clus).child) warndlg2('Cannot move components if cluster has children clusters!' , 'Aborting remove outliers'); return; end outlier_clust = std_findoutlierclust(STUDY,old_clus); %find the outlier cluster for this cluster if outlier_clust == 0 %no such cluster exist STUDY = std_createclust(STUDY, ALLEEG, ['Outliers ' STUDY.cluster(old_clus).name]); %create an outlier cluster outlier_clust = length(STUDY.cluster); end %move the compnents to the outliers cluster STUDY = std_movecomp(STUDY, ALLEEG, old_clus, outlier_clust, comps);
github
ZijingMao/baselineeegtest-master
pop_savestudy.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_savestudy.m
4,821
utf_8
fa0293fa03f7350151ab08e951c9bee4
% pop_savestudy() - save a STUDY structure to a disk file % % Usage: % >> STUDY = pop_savestudy( STUDY, EEG ); % pop up and interactive window % >> STUDY = pop_savestudy( STUDY, EEG, 'key', 'val', ...); % no pop-up % % Inputs: % STUDY - STUDY structure. % EEG - Array of datasets contained in the study. % % Optional inputs: % 'filename' - [string] name of the STUDY file {default: STUDY.filename} % 'filepath' - [string] path of the STUDY file {default: STUDY.filepath} % 'savemode' - ['resave'|'standard'] in resave mode, the file name in % the study is being used to resave it. % % Note: the parameter EEG is currenlty not being used. In the future, this function % will check if any of the datasets of the study have been modified and % have to be resaved. % % Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, September 2005 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, Spetember 2005, [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 [STUDY, EEG, com] = pop_savestudy(STUDY, EEG, varargin); com = ''; if nargin < 1 help pop_savestudy; return; end; if isempty(STUDY) , error('pop_savestudy(): cannot save empty STUDY'); end; if length(STUDY) >1, error('pop_savestudy(): cannot save multiple STUDY sets'); end; % backward compatibility % ---------------------- if nargin > 1 if isstr(EEG) options = { EEG varargin{:} }; else options = varargin; end; end; if nargin < 3 % pop up window to ask for file type % ---------------------------------- [filename, filepath] = uiputfile2('*.study', ... 'Save STUDY with .study extension -- pop_savestudy()'); if isequal(filename,0), return; end; if ~strncmp(filename(end-5:end), '.study',6) if isempty(strfind(filename,'.')) filename = [filename '.study']; else filename = [filename(1:strfind(filename,'.')-1) '.study']; end end options = { 'filename' filename 'filepath' filepath }; end % decoding parameters % ------------------- g = finputcheck(options, { 'filename' 'string' [] STUDY.filename; 'filepath' 'string' [] STUDY.filepath; 'savemode' 'string' { 'standard','resave' } 'standard' }); if isstr(g), error(g); end; % fields to remove % ---------------- fields = { 'erptimes' 'erpdata' ... 'specfreqs' 'specdata' ... 'erspdata' 'ersptimes' 'erspfreqs' 'erspdatatrials' 'erspsubjinds' 'erspbase' 'ersptrialinfo' ... 'itcdata' 'itcfreqs' 'itctimes' ... 'erpimdata' 'erpimevents' 'erpimtrials' 'erpimtimes' }; for fInd = 1:length(fields) if isfield(STUDY.changrp, fields{fInd}) STUDY.changrp = rmfield(STUDY.changrp, fields{fInd}); end; if isfield(STUDY.changrp, fields{fInd}) STUDY.cluster = rmfield(STUDY.cluster, fields{fInd}); end; end; % resave mode % ----------- STUDY.saved = 'yes'; if strcmpi(g.savemode, 'resave') disp('Re-saving study file'); g.filename = STUDY.filename; g.filepath = STUDY.filepath; end; if isempty(g.filename) disp('pop_savestudy(): no STUDY filename: make sure the STUDY has a filename'); return; end if ~strncmp(g.filename(end-5:end), '.study',6) if isempty(strfind(g.filename,'.')) g.filename = [g.filename '.study']; else g.filename = [g.filename(1:strfind(g.filename,'.')-1) '.study']; end end % [filepath filenamenoext ext] = fileparts(varargin{1}); % filename = [filenamenoext '.study']; % make sure a .study extension STUDY.filepath = g.filepath; STUDY.filename = g.filename; STUDYfile = fullfile(STUDY.filepath,STUDY.filename); STUDYTMP = STUDY; STUDY = std_rmalldatafields(STUDY); eeglab_options; if option_saveversion6, save('-v6' , STUDYfile, 'STUDY'); else save('-v7.3' , STUDYfile, 'STUDY'); end; STUDY = STUDYTMP; % history % ------- com = sprintf('[STUDY EEG] = pop_savestudy( %s, %s, %s);', inputname(1), inputname(2), vararg2str(options));
github
ZijingMao/baselineeegtest-master
pop_chanplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_chanplot.m
27,582
utf_8
dcfb38346565d3ab979d9dbbfb4adfc1
% pop_chanplot() - graphic user interface (GUI)-based function with plotting % options for visualizing. Only channel measures (e.g., spectra, % ERPs, ERSPs, ITCs) that have been computed and saved in the study EEG % datasets can be visualized. These can be computed using the GUI-based % pop_precomp(). % Usage: % >> STUDY = pop_chanplot(STUDY, ALLEEG); % Inputs: % ALLEEG - Top-level EEGLAB vector of loaded EEG structures for the dataset(s) % in the STUDY. ALLEEG for a STUDY set is typically loaded using % pop_loadstudy(), or in creating a new STUDY, using pop_createstudy(). % STUDY - EEGLAB STUDY set comprising some or all of the EEG % datasets in ALLEEG. % % Outputs: % STUDY - The input STUDY set structure modified according to specified user edits, % if any. Plotted channel measure means (maps, ERSPs, etc.) are added to % the STUDY structure after they are first plotted to allow quick replotting. % % Graphic interface buttons: % "Select channel to plot" - [list box] Displays available channels to plot (format is % 'channel name (number of channels)'). The presented channels depend s % on the optional input variable 'channels'. Selecting (clicking on) a % channel from the list will display the selected channel channels in the % "Select channel(s) to plot" list box. Use the plotting buttons below % to plot selected measures of the selected channel. % "Select channel(s) to plot" - [list box] Displays the ICA channels of the currently % selected channel (in the "Select channel to plot" list box). Each channel % has the format: 'subject name, channel index'. % "Plot channel properties" - [button] Displays in one figure all the mean channel measures % (e.g., dipole locations, scalp maps, spectra, etc.) that were calculated % and saved in the EEG datsets. If there is more than one condition, the ERP % and the spectrum will have different colors for each condition. The ERSP % and ITC plots will show only the first condition; clicking on the subplot % will open a new figure with the different conditions displayed together. % Uses the command line function std_propplot(). % "Plot ERSPs" - [button] Displays the channel channel ERSPs. % If applied to a channel, channel ERSPs are plotted in one figure % (per condition) with the channel mean ERSP. If "All # channel centroids" % option is selected, plots all average ERSPs of the channels in one figure % per condition. If applied to channels, display the ERSP images of specified % channel channels in separate figures, using one figure for all conditions. % Uses the command line functions std_erspplot(). % "Plot ITCs" - [button] Same as "Plot ERSPs" but with ITC. % Uses the command line functions std_itcplot(). % "Plot spectra" - [button] Displays the channel channel spectra. % If applied to a channel, displays channel spectra plus the average channel % spectrum in bold. For a specific channel, displays the channel channel % spectra plus the average channel spectrum (in bold) in one figure per condition. % If the "All # channel centroids" option is selected, displays the average % spectrum of all channels in the same figure, with spectrum for different % conditions (if any) plotted in different colors. % If applied to channels, displays the spectrum of specified channel % channels in separate figures using one figure for all conditions. % Uses the command line functions std_specplot(). % "Plot ERPs" - [button] Same as "Plot spectra" but for ERPs. % Uses the command line functions std_erpplot(). % "Plot ERPimage" - [button] Same as "Plot ERP" but for ERPimave. % Uses the command line functions std_erpimplot(). % % Authors: Arnaud Delorme, Scott Makeig, SCCN/INC/UCSD, October 11, 2004 % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2004, [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 % Coding notes: Useful information on functions and global variables used. function [STUDY, com] = pop_chanplot(varargin) icadefs; com = []; if ~isstr(varargin{1}) if nargin < 2 error('pop_chanplot(): You must provide ALLEEG and STUDY structures'); end STUDY = varargin{1}; STUDY.etc.erpparams.topotime = []; % [] for channels and NaN for components STUDY.etc.specparams.topofreq = []; % NaN -> GUI disabled STUDY.etc.erspparams.topotime = []; STUDY.etc.erspparams.topofreq = []; STUDY.etc.erpimparams.topotime = []; STUDY.etc.erpimparams.topotrial = []; % test path % --------- pathwarn = 'off'; if ~strcmpi(pwd, STUDY.filepath) && ~strcmpi(pwd, STUDY.filepath(1:end-1)) if length(STUDY.datasetinfo(1).filepath) < 1 pathwarn = 'on'; elseif STUDY.datasetinfo(1).filepath(1) == '.' pathwarn = 'on'; end; end; if strcmpi(pathwarn, 'on') warndlg2(strvcat('You have changed your working path and data files are', ... 'no longer available; Cancel, and go back to your STUDY folder'), 'warning'); end; STUDY.tmphist = ''; ALLEEG = varargin{2}; if ~isfield(STUDY, 'changrp') STUDY = std_changroup(STUDY, ALLEEG); disp('Warning: history not saved for group creation'); elseif isempty(STUDY.changrp) STUDY = std_changroup(STUDY, ALLEEG); disp('Warning: history not saved for group creation'); end; show_chan = ['pop_chanplot(''showchan'',gcf);']; show_onechan = ['pop_chanplot(''showchanlist'',gcf);']; plot_chan_maps = ['pop_chanplot(''topoplot'',gcf); ']; plot_onechan_maps = ['pop_chanplot(''plotchantopo'',gcf); ']; plot_chan_ersps = ['pop_chanplot(''erspplot'',gcf); ']; plot_onechan_ersps = ['pop_chanplot(''plotchanersp'',gcf); ']; plot_chan_itcs = ['pop_chanplot(''itcplot'',gcf); ']; plot_onechan_itcs = ['pop_chanplot(''plotchanitc'',gcf); ']; plot_chan_erpim = ['pop_chanplot(''erpimageplot'',gcf); ']; plot_onechan_erpim = ['pop_chanplot(''plotchanerpimage'',gcf); ']; plot_chan_spectra = ['pop_chanplot(''specplot'',gcf); ']; plot_onechan_spectra = ['pop_chanplot(''plotchanspec'',gcf); ']; plot_chan_erp = ['pop_chanplot(''erpplot'',gcf); ']; plot_onechan_erp = ['pop_chanplot(''plotchanerp'',gcf); ']; plot_chan_dip = ['pop_chanplot(''dipplot'',gcf); ']; plot_onechan_dip = ['pop_chanplot(''plotchandip'',gcf); ']; plot_chan_sum = ['pop_chanplot(''plotsum'',gcf); ']; plot_onechan_sum = ['pop_chanplot(''plotonechanum'',gcf); ']; rename_chan = ['pop_chanplot(''renamechan'',gcf);']; move_onechan = ['pop_chanplot(''movecomp'',gcf);']; move_outlier = ['pop_chanplot(''moveoutlier'',gcf);']; create_chan = ['pop_chanplot(''createchan'',gcf);']; reject_outliers = ['pop_chanplot(''rejectoutliers'',gcf);']; merge_channels = ['pop_chanplot(''mergechannels'',gcf);']; erp_opt = ['pop_chanplot(''erp_opt'',gcf);']; spec_opt = ['pop_chanplot(''spec_opt'',gcf);']; erpim_opt = ['pop_chanplot(''erpim_opt'',gcf);']; ersp_opt = ['pop_chanplot(''ersp_opt'',gcf);']; stat_opt = ['pop_chanplot(''stat_opt'',gcf);']; create_group = ['pop_chanplot(''create_group'',gcf);']; edit_group = ['pop_chanplot(''edit_group'',gcf);']; delete_group = ['pop_chanplot(''delete_group'',gcf);']; saveSTUDY = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''save''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ]; browsesave = [ '[filename, filepath] = uiputfile2(''*.study'', ''Save STUDY with .study extension -- pop_chan()''); ' ... 'set(faindobj(''parent'', gcbf, ''tag'', ''studyfile''), ''string'', [filepath filename]);' ]; sel_all_chans = ['pop_chanplot(''sel_all_chans'',gcf);']; % list of channel groups % ---------------------- show_options = {}; for index = 1:length(STUDY.changrp) show_options{end+1} = [ 'All ' STUDY.changrp(index).name ]; end; % enable buttons % -------------- filename = STUDY.design(STUDY.currentdesign).cell(1).filebase; if exist([filename '.datspec']) , spec_enable = 'on'; else spec_enable = 'off'; end; if exist([filename '.daterp'] ) , erp_enable = 'on'; else erp_enable = 'off'; end; if exist([filename '.datersp']) , ersp_enable = 'on'; else ersp_enable = 'off'; end; if exist([filename '.datitc']) , itc_enable = 'on'; else itc_enable = 'off'; end; if exist([filename '.daterpim']),erpim_enable = 'on'; else erpim_enable = 'off'; end; if isfield(ALLEEG(1).dipfit, 'model'), dip_enable = 'on'; else dip_enable = 'off'; end; % userdata below % -------------- fig_arg{1}{1} = ALLEEG; fig_arg{1}{2} = STUDY; fig_arg{1}{3} = STUDY.changrp; fig_arg{1}{4} = { STUDY.changrp.name }; fig_arg{2} = length(STUDY.changrp); std_line = [0.9 0.35 0.9]; geometry = { [4] [1] [0.6 0.35 0.1 0.1 0.9] std_line std_line std_line std_line std_line std_line }; str_name = sprintf('STUDY name ''%s'' - ''%s''', STUDY.name, STUDY.design(STUDY.currentdesign).name); if length(str_name) > 80, str_name = [ str_name(1:80) '...''' ]; end; uilist = { ... {'style' 'text' 'string' str_name 'FontWeight' 'Bold' 'HorizontalAlignment' 'center'} {} ... {'style' 'text' 'string' 'Select channel to plot' 'FontWeight' 'Bold' } ... {'style' 'pushbutton' 'string' 'Sel. all' 'callback' sel_all_chans } {} {} ... {'style' 'text' 'string' 'Select subject(s) to plot' 'FontWeight' 'Bold'} ... {'style' 'listbox' 'string' show_options 'value' 1 'max' 2 'tag' 'chan_list' 'Callback' show_chan } ... {'style' 'pushbutton' 'enable' 'on' 'string' [ 'STATS' 10 'params' ] 'callback' stat_opt } ... {'style' 'listbox' 'string' '' 'tag' 'chan_onechan' 'max' 2 'min' 1 'callback' show_onechan } ... {'style' 'pushbutton' 'enable' erp_enable 'string' 'Plot ERPs' 'Callback' plot_chan_erp} ... {'style' 'pushbutton' 'enable' erp_enable 'string' 'Params' 'Callback' erp_opt } ... {'style' 'pushbutton' 'enable' erp_enable 'string' 'Plot ERP(s)' 'Callback' plot_onechan_erp} ... {'style' 'pushbutton' 'enable' spec_enable 'string' 'Plot spectra' 'Callback' plot_chan_spectra} ... {'style' 'pushbutton' 'enable' spec_enable 'string' 'Params' 'Callback' spec_opt } ... {'style' 'pushbutton' 'enable' spec_enable 'string' 'Plot spectra' 'Callback' plot_onechan_spectra} ... {'style' 'pushbutton' 'enable' erpim_enable 'string' 'Plot ERPimage' 'Callback' plot_chan_erpim } ... {'style' 'pushbutton' 'enable' erpim_enable 'string' 'Params' 'Callback' erpim_opt } ... {'style' 'pushbutton' 'enable' erpim_enable 'string' 'Plot ERPimage(s)' 'Callback' plot_onechan_erpim } ... {'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ERSPs' 'Callback' plot_chan_ersps} ... {'vertexpand' 2.15 'style' 'pushbutton' 'enable' ersp_enable 'string' 'Params' 'Callback' ersp_opt } ... {'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ERSP(s)' 'Callback' plot_onechan_ersps}... {'style' 'pushbutton' 'enable' itc_enable 'string' 'Plot ITCs' 'Callback' plot_chan_itcs} { } ... {'style' 'pushbutton' 'enable' itc_enable 'string' 'Plot ITC(s)' 'Callback' plot_onechan_itcs}... }; % {'style' 'pushbutton' 'string' 'Plot channel properties' 'Callback' plot_chan_sum} {} ... %{'style' 'pushbutton' 'string' 'Plot channel properties (soon)' 'Callback' plot_onechan_sum 'enable' 'off'} % additional UI given on the command line % --------------------------------------- geomvert = [ 1 0.5 1 5 1 1 1 1 1]; if nargin > 2 addui = varargin{3}; if ~isfield(addui, 'uilist') error('Additional GUI definition (argument 4) requires the field "uilist"'); end; if ~isfield(addui, 'geometry') addui.geometry = mat2cell(ones(1,length(addui.uilist))); end; uilist = { uilist{:}, addui.uilist{:} }; geometry = { geometry{:} addui.geometry{:} }; geomvert = [ geomvert ones(1,length(addui.geometry)) ]; end; [out_param userdat] = inputgui( 'geometry' , geometry, 'uilist', uilist, ... 'helpcom', 'pophelp(''pop_chanplot'')', ... 'title', 'View and edit current channels -- pop_chanplot()' , 'userdata', fig_arg, ... 'geomvert', geomvert, 'eval', show_chan ); if ~isempty(userdat) ALLEEG = userdat{1}{1}; STUDY = userdat{1}{2}; end % history % ------- com = STUDY.tmphist; STUDY = rmfield(STUDY, 'tmphist'); else hdl = varargin{2}; %figure handle userdat = get(varargin{2}, 'userdat'); ALLEEG = userdat{1}{1}; STUDY = userdat{1}{2}; cls = userdat{1}{3}; allchans = userdat{1}{4}; changrp = get(findobj('parent', hdl, 'tag', 'chan_list') , 'value'); onechan = get(findobj('parent', hdl, 'tag', 'chan_onechan'), 'value'); try switch varargin{1} case {'topoplot', 'erspplot','itcplot','specplot', 'erpplot', 'erpimageplot' } changrpstr = allchans(changrp); plotting_option = varargin{1}; plotting_option = [ plotting_option(1:end-4) 'plot' ]; a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''channels'',' vararg2str({changrpstr}) ');' ]; % update Study history eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); case {'plotchanersp','plotchanitc','plotchanspec', 'plotchanerp','plotchanerpimage' } changrpstr = allchans(changrp); %if length(changrp) > 1 % subject = STUDY.subject{onechan-1}; %else % changrpstruct = STUDY.changrp(changrp); % allsubjects = unique_bc({ STUDY.datasetinfo([ changrpstruct.setinds{:} ]).subject }); % subject = allsubjects{onechan-1}; %end; plotting_option = varargin{1}; plotting_option = [ plotting_option(9:end) 'plot' ]; if onechan(1) ~= 1 % check that not all onechan in channel are requested subject = STUDY.design(STUDY.currentdesign).cases.value{onechan-1}; a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''channels'',' vararg2str({changrpstr}) ', ''subject'', ''' subject ''' );' ]; eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); else a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''channels'',' vararg2str({changrpstr}) ', ''plotsubjects'', ''on'' );' ]; eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); case 'stat_opt' % save the list of selected channels [STUDY com] = pop_statparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'erp_opt' % save the list of selected channels [STUDY com] = pop_erpparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'spec_opt' % save the list of selected channels [STUDY com] = pop_specparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'ersp_opt' % save the list of selected channels [STUDY com] = pop_erspparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'erpim_opt' % save the list of selected channels [STUDY com] = pop_erpimparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'showchanlist' % save the list of selected channels if length(changrp) == 1 STUDY.changrp(changrp).selected = onechan; end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'showchan' cind = get(findobj('parent', hdl, 'tag', 'chan_list') , 'value'); changrp = STUDY.changrp(cind); % Find datasets availaible % ------------------------ %setind = STUDY.setind .* (changrp.chaninds > 0); % set to 0 the cell not %% % containing any electrode %allchansets = unique_bc( setind(find(setind(:))) ); % Generate channel list % --------------------- chanid{1} = 'All subjects'; if length(changrp) == 1 allsubjects = unique_bc({ STUDY.design(STUDY.currentdesign).cell([ changrp.setinds{:} ]).case }); for l = 1:length(allsubjects) chanid{end+1} = [ allsubjects{l} ' ' changrp.name ]; end; else for l = 1:length(STUDY.design(STUDY.currentdesign).cases.value) chanid{end+1} = [ STUDY.design(STUDY.currentdesign).cases.value{l} ]; end; end; selected = 1; if isfield(changrp, 'selected') & length(cind) == 1 if ~isempty(STUDY.changrp(cind).selected) selected = min(STUDY.changrp(cind).selected, 1+length(chanid)); STUDY.changrp(cind).selected = selected; end; end; set(findobj('parent', hdl, 'tag', 'chan_onechan'), 'value', selected, 'String', chanid); case 'sel_all_chans' set(findobj('parent', hdl, 'tag', 'chan_list'), 'value', [1:length(STUDY.changrp)]); % Generate channel list % --------------------- chanid{1} = 'All subjects'; for l = 1:length(STUDY.design(STUDY.currentdesign).cases.value) chanid{end+1} = [ STUDY.design(STUDY.currentdesign).cases.value{l} ' All' ]; end; selected = 1; set(findobj('parent', hdl, 'tag', 'chan_onechan'), 'value', selected, 'String', chanid); case 'plotsum' changrpstr = allchans(changrp); [STUDY] = std_propplot(STUDY, ALLEEG, allchans(changrp)); a = ['STUDY = std_propplot(STUDY, ALLEEG, ' vararg2str({ allchans(changrp) }) ' );' ]; STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); case 'create_group' channames = { STUDY.changrp(changrp).name }; for i=1:length(channames), channames{i} = [ ' ' channames{i} ]; end; channamestr = strcat(channames{:}); res = inputdlg2({ 'Name of channel group', 'Channels to group' }, 'Create channel group', 1, { '' channamestr(2:end) }); if isempty(res), return; end; STUDY.changrp(end+1).name = res{1}; allchans(end+1) = { res{1} }; chanlabels = parsetxt(res{2}); if length(chanlabels) == 1 warndlg2('Cannot create a channel group with a single channel'); return; end; STUDY.changrp(end).channels = chanlabels; tmp = std_chanlookup( STUDY, ALLEEG, STUDY.changrp(end)); STUDY.changrp(end).chaninds = tmp.chaninds; userdat{1}{2} = STUDY; userdat{1}{4} = allchans; set(hdl, 'userdat',userdat); % list of channel groups % ---------------------- tmpobj = findobj('parent', hdl, 'tag', 'chan_list'); tmptext = get(tmpobj, 'string'); tmptext{end+1} = [ 'All ' STUDY.changrp(end).name ]; set(tmpobj, 'string', tmptext, 'value', length(tmptext)); case 'edit_group' if length(changrp) > 1, return; end; if length(STUDY.changrp(changrp).channels) < 2, return; end; channames = STUDY.changrp(changrp).channels; for i=1:length(channames), channames{i} = [ ' ' channames{i} ]; end; channamestr = strcat(channames{:}); res = inputdlg2({ 'Name of channel group', 'Channels to group' }, 'Create channel group', ... 1, { STUDY.changrp(changrp).name channamestr(2:end) }); if isempty(res), return; end; STUDY.changrp(end+1).name = ''; STUDY.changrp(changrp) = STUDY.changrp(end); STUDY.changrp(end) = []; STUDY.changrp(changrp).name = res{1}; allchans(changrp) = { res{1} }; chanlabels = parsetxt(res{2}); STUDY.changrp(changrp).channels = chanlabels; tmp = std_chanlookup( STUDY, ALLEEG, STUDY.changrp(end)); STUDY.changrp(changrp).chaninds = tmp.chaninds; userdat{1}{2} = STUDY; userdat{1}{4} = allchans; set(hdl, 'userdat',userdat); % list of channel groups % ---------------------- show_options = {}; for index = 1:length(STUDY.changrp) show_options{end+1} = [ 'All ' STUDY.changrp(index).name ]; end; tmpobj = findobj('parent', hdl, 'tag', 'chan_list'); set(tmpobj, 'string', show_options, 'value', changrp); case 'delete_group' if length(changrp) > 1, return; end; if length(STUDY.changrp(changrp).channels) < 2, return; end; STUDY.changrp(changrp) = []; % list of channel groups % ---------------------- show_options = {}; for index = 1:length(STUDY.changrp) show_options{end+1} = [ 'All ' STUDY.changrp(index).name ]; end; tmpobj = findobj('parent', hdl, 'tag', 'chan_list'); set(tmpobj, 'string', show_options, 'value', changrp-1); case 'renamechan' STUDY.saved = 'no'; chan_name_list = get(findobj('parent', hdl, 'tag', 'chan_list'), 'String'); chan_num = get(findobj('parent', hdl, 'tag', 'chan_list'), 'Value') -1; if chan_num == 0 % 'all subjects' option return; end % Don't rename 'Notchan' and 'Outliers' channels. if strncmpi('Notchan',STUDY.channel(cls(chan_num)).name,8) | strncmpi('Outliers',STUDY.channel(cls(chan_num)).name,8) | ... strncmpi('Parentchannel',STUDY.channel(cls(chan_num)).name,13) warndlg2('The Parentchannel, Outliers, and Notchan channels cannot be renamed'); return; end old_name = STUDY.channel(cls(chan_num)).name; rename_param = inputgui( { [1] [1] [1]}, ... { {'style' 'text' 'string' ['Rename ' old_name] 'FontWeight' 'Bold'} {'style' 'edit' 'string' '' 'tag' 'chan_rename' } {} }, ... '', 'Rename channel - from pop_chanplot()' ); if ~isempty(rename_param) %if not canceled new_name = rename_param{1}; STUDY = std_renamechan(STUDY, ALLEEG, cls(chan_num), new_name); % update Study history a = ['STUDY = std_renamechan(STUDY, ALLEEG, ' num2str(cls(chan_num)) ', ' STUDY.channel(cls(chan_num)).name ');']; STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); new_name = [ STUDY.channel(cls(chan_num)).name ' (' num2str(length(STUDY.channel(cls(chan_num)).onechan)) ' ICs)']; chan_name_list{chan_num+1} = renamechan( chan_name_list{chan_num+1}, new_name); set(findobj('parent', hdl, 'tag', 'chan_list'), 'String', chan_name_list); set(findobj('parent', hdl, 'tag', 'chan_rename'), 'String', ''); userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update STUDY end end catch eeglab_error; end; end function newname = renamechan(oldname, newname); tmpname = deblank(oldname(end:-1:1)); strpos = strfind(oldname, tmpname(end:-1:1)); newname = [ oldname(1:strpos-1) newname ];
github
ZijingMao/baselineeegtest-master
std_erpimage.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_erpimage.m
11,020
utf_8
e610e6ac79890f95ca1b2048f25013fa
% std_erpimage() - Compute ERP images and save them on disk. % % Usage: % >> std_erpimage( EEG, 'key', 'val', ...); % % Inputs: % EEG - a loaded epoched EEG dataset structure. May be an array % of such structure containing several datasets. % % Optional inputs: % 'components' - [numeric vector] components of the EEG structure for which % the measure will be computed {default|[] -> all} % 'channels' - [cell array] channels of the EEG structure for which % activation ERPs will be computed {default|[] -> none} % 'trialindices' - [cell array] indices of trials for each dataset. % Default is all trials. % 'recompute' - ['on'|'off'] force recomputing data file even if it is % already on disk. % 'rmcomps' - [integer array] remove artifactual components (this entry % is ignored when plotting components). This entry contains % the indices of the components to be removed. Default is none. % 'interp' - [struct] channel location structure containing electrode % to interpolate ((this entry is ignored when plotting % components). Default is no interpolation. % 'fileout' - [string] name of the file to save on disk. The default % is the same name (with a different extension) as the % dataset given as input. % % ERPimage options: % 'concatenate' - ['on'|'off'] concatenate single trial of different % subjects for plotting ERPimages ('on'). The default % ('off') computes an ERPimage for each subject and then % averages these ERPimages. This allows to perform % statistics (the 'on' options does not allow statistics). % 'smoothing' - Smoothing parameter (number of trials). {Default: 10} % erpimage() equivalent: 'avewidth' % 'nlines' - Number of lines for ERPimage. erpaimge() equivalent is % 'decimate'. Note that this parameter must be larger than % the minimum number of trials in each design cell % {Default: 10} % 'sorttype' - Sorting event type(s) ([int vector]; []=all). See Notes below. % Either a string or an integer. % 'sortwin' - Sorting event window [start, end] in milliseconds ([]=whole epoch) % 'sortfield' - Sorting field name. {default: latency}. % 'erpimageopt' - erpimage() options, separated by commas (Ex: 'erp', 'cbar'). % {Default: none}. For further details see >> erpimage help % Outputs: % erpimagestruct - structure containing ERPimage information that is % been saved on disk. % % Files are saved on disk. % [dataset_file].icaerpim % component ERPimage file % OR % [dataset_file].daterpim % channel ERPimage file % % Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2011- % Copyright (C) 2011 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 allerpimage = std_erpimage( EEG, varargin); if nargin < 1 help std_erpimage; return; end allerpimage = []; [opt moreopts] = finputcheck( varargin, { ... 'components' 'integer' [] []; 'channels' { 'cell','integer' } { [] [] } {}; 'trialindices' { 'integer','cell' } [] []; 'recompute' 'string' { 'on','off' } 'off'; 'savefile' 'string' { 'on','off' } 'on'; 'fileout' 'string' [] ''; 'rmcomps' 'cell' [] cell(1,length(EEG)); 'interp' 'struct' { } struct([]); 'nlines' '' [] 10; 'smoothing' '' [] 10; 'sorttype' '' {} ''; 'sortwin' '' {} []; 'sortfield' '' {} 'latency'; 'concatenate' 'string' { 'on','off' } 'off'; 'erpimageopt' 'cell' {} {}}, ... 'std_erpimage', 'ignore'); if isstr(opt), error(opt); end; if length(EEG) == 1 && isempty(opt.trialindices), opt.trialindices = { [1:EEG.trials] }; end; if isempty(opt.trialindices), opt.trialindices = cell(length(EEG)); end; if ~iscell(opt.trialindices), opt.trialindices = { opt.trialindices }; end; if isfield(EEG,'icaweights') numc = size(EEG(1).icaweights,1); else error('EEG.icaweights not found'); end if isempty(opt.components) opt.components = 1:numc; end % filename % -------- if isempty(opt.fileout), opt.fileout = fullfile(EEG(1).filepath, EEG(1).filename(1:end-4)); end; if ~isempty(opt.channels) filenameshort = [ opt.fileout '.daterpim']; prefix = 'chan'; if iscell(opt.channels) if ~isempty(opt.interp) opt.indices = eeg_chaninds(opt.interp, opt.channels, 0); else opt.indices = eeg_chaninds(EEG(1), opt.channels, 0); for ind = 2:length(EEG) if ~isequal(eeg_chaninds(EEG(ind), opt.channels, 0), opt.indices) error([ 'Channel information must be consistant when ' 10 'several datasets are merged for a specific design' ]); end; end; end; else opt.indices = opt.channels; end; else opt.indices = opt.components; filenameshort = [ opt.fileout '.icaerpim']; prefix = 'comp'; end; filename = filenameshort; % ERP information found in datasets % --------------------------------- if exist(filename) && strcmpi(opt.recompute, 'off') fprintf('File "%s" found on disk, no need to recompute\n', filenameshort); return; end allerpimage = []; if strcmpi(opt.concatenate, 'off') % compute ERP images % ------------------ if isempty(opt.channels) X = eeg_getdatact(EEG, 'component', opt.indices, 'trialindices', opt.trialindices ); else X = eeg_getdatact(EEG, 'channel' , opt.indices, 'trialindices', opt.trialindices, 'rmcomps', opt.rmcomps, 'interp', opt.interp); end; if ~isempty(opt.sorttype) events = eeg_getepochevent(EEG, 'type', opt.sorttype, 'timewin', opt.sortwin, 'fieldname', opt.sortfield, 'trials', opt.trialindices); else events = []; end; % reverse engeeneering the number of lines for ERPimage finallines = opt.nlines; if ~isempty(events) if all(isnan(events)) error('Cannot sort trials for one of the dataset'); end; lastx = sum(~isnan(events)); else lastx = size(X,3); end; if lastx < finallines + floor((opt.smoothing-1)/2) + 3 error('The default number of ERPimage lines is too large for one of the dataset'); end; firstx = 1; xwidth = opt.smoothing; %xadv = lastx/finallines; nout = finallines; %floor(((lastx-firstx+xadv+1)-xwidth)/xadv); nlines = (lastx-xwidth)/(nout-0.5)*i; % make it imaginary %nlines = ceil(lastx/((lastx-firstx+1-xwidth)/(nout-1))); if 0 % testing conversion back and forth % --------------------------------- for lastx = 20:300 for xwidth = 1:19 for nlines = (xwidth+1):100 nout = floor(((lastx+nlines)-xwidth)/nlines); realnlines = (lastx-xwidth)/(nout-0.5); noutreal = floor(((lastx+realnlines)-xwidth)/realnlines); if nout ~= noutreal error('Wrong conversion 2'); end; end; end; end; end; clear tmperpimage eventvals; parfor index = 1:size(X,1) [tmpX tmpevents] = erpimage(squeeze(X(index,:,:)), events, EEG(1).times, '', opt.smoothing, nlines, 'noplot', 'on', opt.erpimageopt{:}, moreopts{:}); if isempty(events), tmpevents = []; end; eventvals{index} = tmpevents; tmperpimage{index} = tmpX'; end; allerpimage.events = eventvals{1}; for index = 1:size(X,1) allerpimage.([ prefix int2str(opt.indices(index)) ]) = tmperpimage{index}; end; else % generate dynamic loading commands % --------------------------------- for dat = 1:length(EEG) filenames{dat} = fullfile(EEG(1).filepath, EEG(1).filename); end; allerpimage.times = EEG(1).times; for index = 1:length(opt.indices) if ~isempty(opt.channels) com = sprintf('squeeze(eeg_getdatact(%s, ''interp'', chanlocsforinterp));', vararg2str( { filenames 'channel' , opt.indices(index), 'rmcomps', opt.rmcomps, 'trialindices', opt.trialindices } )); else com = sprintf('squeeze(eeg_getdatact(%s));', vararg2str( { filenames 'component', opt.indices(index), 'trialindices', opt.trialindices } )); end; allerpimage = setfield(allerpimage, [ prefix int2str(opt.indices(index)) ], com); end; allerpimage = setfield(allerpimage, 'chanlocsforinterp', opt.interp); if ~isempty(opt.sorttype) events = eeg_getepochevent(EEG, 'type', opt.sorttype, 'timewin', opt.sortwin, 'fieldname', opt.sortfield, 'trials', opt.trialindices); %geteventcom = sprintf('eeg_getepochevent(%s);', vararg2str( { filenames 'type', opt.sorttype, 'timewin', opt.sortwin, 'fieldname', opt.sortfield } )); else events = []; end; allerpimage = setfield(allerpimage, 'events', events); end; allerpimage.times = EEG(1).times; allerpimage.parameters = varargin; allerpimage.datatype = 'ERPIMAGE'; allerpimage.datafiles = computeFullFileName( { EEG.filepath }, { EEG.filename }); allerpimage.datatrials = opt.trialindices; % Save ERPimages in file (all components or channels) % ---------------------------------------------- if strcmpi(opt.savefile, 'on') if strcmpi(prefix, 'comp') std_savedat(filename, allerpimage); else tmpchanlocs = EEG(1).chanlocs; allerpimage.labels = opt.channels; std_savedat(filename, allerpimage); end; end; % compute full file names % ----------------------- function res = computeFullFileName(filePaths, fileNames); for index = 1:length(fileNames) res{index} = fullfile(filePaths{index}, fileNames{index}); end;
github
ZijingMao/baselineeegtest-master
std_cell2setcomps.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_cell2setcomps.m
3,058
utf_8
199bb737c086d50fb622cb63d9511eeb
% std_cell2setcomps - convert .sets and .comps to cell array. The .sets and % .comps format is useful for GUI but the cell array % format is used for plotting and statistics. % % Usage: % [ struct sets comps ] = std_cell2setcomps(STUDY, clustind); % % Author: Arnaud Delorme, CERCO/CNRS, UCSD, 2009- % Copyright (C) Arnaud Delorme, [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 [ tmpstruct setlist complist ] = std_cell2setcomps(STUDY, ALLEEG, setinds, allinds) if nargin < 4 tmpstruct = STUDY.cluster(setinds); sets = STUDY.cluster(setinds).setinds; inds = STUDY.cluster(setinds).allinds; else tmpstruct = []; sets = setinds; inds = allinds; end; % initialize flag array % --------------------- flag = cell(size(inds)); for i = 1:size(inds,1) for j = 1:size(inds,2) flag{i,j} = zeros(size(inds{i,j})); end; end; % find datasets with common ICA decompositions clusters = std_findsameica(ALLEEG); setlist = []; complist = []; count = 1; for i = 1:size(inds,1) for j = 1:size(inds,2) for ind = 1:length(inds{i,j}) if ~flag{i,j}(ind) % found one good component complist(count) = inds{i,j}(ind); %if complist(count) == 12, dfds; end; % search for the same component in other datasets for c = 1:length(clusters) if any(clusters{c} == sets{i,j}(ind)) setlist(:,count) = clusters{c}'; % flag all of these datasets for i2 = 1:size(inds,1) for j2 = 1:size(inds,2) for ind2 = 1:length(sets{i2,j2}) if any(sets{i2,j2}(ind2) == clusters{c}) && complist(count) == inds{i2, j2}(ind2) flag{i2,j2}(ind2) = 1; end; end; end; end; end; end; count = count+1; end; end; end; end; tmpstruct.sets = setlist; tmpstruct.comps = complist;
github
ZijingMao/baselineeegtest-master
std_editset.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_editset.m
16,290
utf_8
f7eebc870fafd57a1465c80e576543d1
% std_editset() - modify a STUDY set structure. % % Usage: % >> [STUDY, ALLEEG] = std_editset(STUDY, ALLEEG, key1, val1, ...); % Inputs: % STUDY - EEGLAB STUDY set % ALLEEG - vector of the EEG datasets included in the STUDY structure % % Optional inputs: % 'commands' - {cell_array} change STUDY (see command description and % example below. % 'name' - [string] specify a (mnemonic) name for the STUDY structure. % {default: ''} % 'task' - [string] attach a description of the experimental task(s) % performed by the STUDY subjects {default: ''}. % 'filename' - [string] filename for the STUDY set. % 'filepath' - [string] file path (directory/folder) in which the STUDY file % will be saved. % 'addchannellabels' - ['on'|'off'] add channel labels ('1', '2', '3', ...) % to all datasets of a STUDY to ensure that all STUDY functions % will work {default: 'off' unless no dataset has channel % locations and then it is automatically set to on} % 'notes' - [string] notes about the experiment, the datasets, the STUDY, % or anything else to store with the STUDY itself {default: ''}. % 'updatedat' - ['on'|'off'] update 'subject' 'session' 'condition' and/or % 'group' fields of STUDY dataset(s). % 'savedat' - ['on'|'off'] re-save datasets % 'inbrain' - ['on'|'off'] select components for clustering from all STUDY % datasets with equivalent dipoles located inside the brain volume. % Dipoles are selected based on their residual variance and their % location {default: 'off'} % 'resave' - ['on'|'off'] save or resave STUDY {default: 'off'} % % Each of the 'commands' (above) is a cell array composed of any of the following: % 'index' - [integer] modify/add dataset index. Note that if a % dataset is added and that this leaves some indices not % populated, the dataset is automatically set to the last % empty index. For instance creating a STUDY with a single % dataset at index 10 will result with a STUDY with a % single dataset at index 1. % 'remove' - [integer] remove dataset index. % 'subject' - [string] subject code. % 'condition' - [string] dataset condition. % 'session ' - [integer] dataset session number. % 'group' - [string] dataset group. % 'load' - [filename] load dataset from specified filename % 'dipselect' - [float<1] select components for clustering from all STUDY % datasets with dipole model residual var. below this value. % 'inbrain' - ['on'|'off'] same as above. This option may also be % placed in the command list (preceeding the 'dipselect' % option). % % Outputs: % STUDY - a new STUDY set containing some or all of the datasets in ALLEEG, % plus additional information from the optional inputs above. % ALLEEG - a vector of EEG datasets included in the STUDY structure % % See also: pop_createstudy(), std_loadalleeg(), pop_clust(), pop_preclust(), % eeg_preclust(), eeg_createdata() % % Authors: Arnaud Delorme, Hilit Serby, SCCN/INC/UCSD, October , 2004- % Copyright (C) Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, October 11, 2004, [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 [STUDY, ALLEEG] = std_editset(STUDY, ALLEEG, varargin) if (nargin < 3) help std_editset; return; end; % decode input parameters % ----------------------- g = finputcheck(varargin, { 'updatedat' 'string' { 'on','off' } 'off'; 'name' 'string' { } ''; 'task' 'string' { } ''; 'notes' 'string' { } ''; 'filename' 'string' { } ''; 'filepath' 'string' { } ''; 'resave' 'string' { 'on','off','info' } 'off'; 'savedat' 'string' { 'on','off' } 'off'; 'addchannellabels' 'string' { 'on','off' } 'off'; 'rmclust' 'string' { 'on','off' } 'on'; 'inbrain' 'string' { 'on','off' } 'off'; 'commands' 'cell' {} {} }, 'std_editset'); if isstr(g), error(g); end; if isempty(STUDY), STUDY.history = 'STUDY = [];'; end; if ~isempty(g.name), STUDY.name = g.name; end if ~isempty(g.task), STUDY.task = g.task; end if ~isempty(g.notes), STUDY.notes = g.notes; end % default addchannellabels % ------------------------ if ~isempty(ALLEEG) allchanlocs = { ALLEEG.chanlocs }; if all(cellfun( @isempty, allchanlocs)) g.addchannellabels = 'on'; else if any(cellfun( @isempty, allchanlocs)) error( [ 'Some datasets have channel locations and some other don''t' 10 ... 'the STUDY is not homogenous and cannot be created.' ]); end; end; end; % make one cell array with commands % --------------------------------- allcoms = {}; if ~isempty(g.commands) if iscell(g.commands{1}) for k = 1:length(g.commands) % put index field first indindex = strmatch('index', lower(g.commands{k}(1:2:end))); if ~isempty(indindex) tmpcom = { 'index' g.commands{k}{2*(indindex-1)+1+1} g.commands{k}{:} }; else tmpcom = g.commands{k}; end; allcoms = { allcoms{:} tmpcom{:} }; end; else allcoms = g.commands; end; end; g.commands = allcoms; % add 'dipselect' command if 'inbrain' option is selected % --------------------------------- dipselectExists = false; for k = 1:2:length(g.commands) if strcmp(g.commands{k},'dipselect') dipselectExists = true; end; end; if strcmp(g.inbrain,'on') && ~dipselectExists g.commands{length(g.commands)+1} = 'dipselect'; g.commands{length(g.commands)+1} = 0.15; end; % copy values % ----------- if ~isfield(STUDY, 'datasetinfo') for realindex = 1:length(ALLEEG) if ~isempty(ALLEEG(realindex).data) [tmppath tmpfile tmpext] = fileparts( fullfile(ALLEEG(realindex).filepath, ALLEEG(realindex).filename) ); STUDY.datasetinfo(realindex).filepath = tmppath; STUDY.datasetinfo(realindex).filename = [ tmpfile tmpext ]; STUDY.datasetinfo(realindex).subject = ALLEEG(realindex).subject; STUDY.datasetinfo(realindex).session = ALLEEG(realindex).session; STUDY.datasetinfo(realindex).condition = ALLEEG(realindex).condition; STUDY.datasetinfo(realindex).group = ALLEEG(realindex).group; end; end; end; % execute commands % ---------------- currentind = 1; rmlist = []; for k = 1:2:length(g.commands) switch g.commands{k} case 'index' currentind = g.commands{k+1}; case 'subject' STUDY.datasetinfo(currentind).subject = g.commands{k+1}; case 'comps' STUDY.datasetinfo(currentind).comps = g.commands{k+1}; case 'condition' STUDY.datasetinfo(currentind).condition = g.commands{k+1}; case 'group' STUDY.datasetinfo(currentind).group = g.commands{k+1}; case 'session' STUDY.datasetinfo(currentind).session = g.commands{k+1}; case 'session' STUDY.datasetinfo(currentind).session = g.commands{k+1}; case 'remove' % create empty structure allfields = fieldnames(ALLEEG); tmpfields = allfields; tmpfields(:,2) = cell(size(tmpfields)); tmpfields = tmpfields'; ALLEEG(g.commands{k+1}) = struct(tmpfields{:}); % create empty structure allfields = fieldnames(STUDY.datasetinfo); tmpfields = allfields; tmpfields(:,2) = cell(size(tmpfields)); tmpfields = tmpfields'; STUDY.datasetinfo(g.commands{k+1}) = struct(tmpfields{:}); if isfield(STUDY.datasetinfo, 'index') STUDY.datasetinfo = rmfield(STUDY.datasetinfo, 'index'); end; STUDY.datasetinfo(1).index = []; STUDY.changrp = []; case 'return', return; case 'inbrain' g.inbrain = g.commands{k+1}; case 'dipselect' STUDY = std_checkset(STUDY, ALLEEG); rv = g.commands{k+1}; clusters = std_findsameica(ALLEEG); for cc = 1:length(clusters) idat = 0; for tmpi = 1:length(clusters{cc}) if isfield(ALLEEG(clusters{cc}(tmpi)).dipfit, 'model') idat = clusters{cc}(tmpi); end; end; indleft = []; if rv ~= 1 if idat ~= 0 if strcmp(g.inbrain,'on') fprintf('Selecting dipoles with less than %%%2.1f residual variance and removing dipoles outside brain volume in dataset ''%s''\n', ... 100*rv, ALLEEG(idat).setname); indleft = eeg_dipselect(ALLEEG(idat), rv*100,'inbrain'); else fprintf('Selecting dipoles with less than %%%2.1f residual variance in dataset ''%s''\n', ... 100*rv, ALLEEG(idat).setname); indleft = eeg_dipselect(ALLEEG(idat), rv*100,'rv'); end; else fprintf('No dipole information found in ''%s'' dataset, using all components\n', ALLEEG.setname) end end; for tmpi = 1:length(clusters{cc}) STUDY.datasetinfo(clusters{cc}(tmpi)).comps = indleft; end; end; STUDY.cluster = []; STUDY = std_checkset(STUDY, ALLEEG); % recreate parent dataset case 'load' TMPEEG = std_loadalleeg( { g.commands{k+1} } ); ALLEEG = eeg_store(ALLEEG, eeg_checkset(TMPEEG), currentind); ALLEEG(currentind).saved = 'yes'; % update datasetinfo structure % ---------------------------- [tmppath tmpfile tmpext] = fileparts( fullfile(ALLEEG(currentind).filepath, ... ALLEEG(currentind).filename) ); STUDY.datasetinfo(currentind).filepath = tmppath; STUDY.datasetinfo(currentind).filename = [ tmpfile tmpext ]; STUDY.datasetinfo(currentind).subject = ALLEEG(currentind).subject; STUDY.datasetinfo(currentind).session = ALLEEG(currentind).session; STUDY.datasetinfo(currentind).condition = ALLEEG(currentind).condition; STUDY.datasetinfo(currentind).group = ALLEEG(currentind).group; STUDY.datasetinfo(currentind).index = currentind; otherwise, error(sprintf('Unknown command %s', g.commands{k})); end end % add channel labels automatically % ------------------------------- if strcmpi(g.addchannellabels, 'on') disp('Generating channel labels for all datasets...'); for currentind = 1:length(ALLEEG) for ind = 1:ALLEEG(currentind).nbchan ALLEEG(currentind).chanlocs(ind).labels = int2str(ind); end; end; ALLEEG(currentind).saved = 'no'; g.savedat = 'on'; end; % update ALLEEG structure? % ------------------------ if strcmpi(g.updatedat, 'on') for currentind = 1:length(ALLEEG) if ~strcmpi(ALLEEG(currentind).subject, STUDY.datasetinfo(currentind).subject) ALLEEG(currentind).subject = STUDY.datasetinfo(currentind).subject; ALLEEG(currentind).saved = 'no'; end; if ~strcmpi(ALLEEG(currentind).condition, STUDY.datasetinfo(currentind).condition) ALLEEG(currentind).condition = STUDY.datasetinfo(currentind).condition; ALLEEG(currentind).saved = 'no'; end; if ~isequal(ALLEEG(currentind).session, STUDY.datasetinfo(currentind).session) ALLEEG(currentind).session = STUDY.datasetinfo(currentind).session; ALLEEG(currentind).saved = 'no'; end; if ~strcmpi(char(ALLEEG(currentind).group), char(STUDY.datasetinfo(currentind).group)) ALLEEG(currentind).group = STUDY.datasetinfo(currentind).group; ALLEEG(currentind).saved = 'no'; end; end; end; % remove empty datasets (cannot be done above because some empty datasets % might not have been removed) % --------------------- rmindex = []; for index = 1:length(STUDY.datasetinfo) if isempty(STUDY.datasetinfo(index).subject) && isempty(ALLEEG(index).nbchan) rmindex = [ rmindex index ]; end; end; STUDY.datasetinfo(rmindex) = []; ALLEEG(rmindex) = []; for index = 1:length(STUDY.datasetinfo) STUDY.datasetinfo(index).index = index; end; % remove empty ALLEEG structures % ------------------------------ while length(ALLEEG) > length(STUDY.datasetinfo) ALLEEG(end) = []; end; %[ ALLEEG STUDY.datasetinfo ] = remove_empty(ALLEEG, STUDY.datasetinfo); % save datasets if necessary % -------------------------- if strcmpi(g.savedat, 'on') for index = 1:length(ALLEEG) if isempty(ALLEEG(index).filename) fprintf('Cannot resave ALLEEG(%d) because the dataset has no filename\n', index); else TMP = pop_saveset(ALLEEG(index), 'savemode', 'resave'); ALLEEG = eeg_store(ALLEEG, TMP, index); ALLEEG(index).saved = 'yes'; end; end; end; % remove cluster information if necessary % --------------------------------------- if strcmpi(g.rmclust, 'on') STUDY.cluster = []; end; % save study if necessary % ----------------------- if ~isempty(g.commands) STUDY.changrp = []; STUDY.cluster = []; % if ~isempty(STUDY.design) % [STUDY] = std_createclust(STUDY, ALLEEG, 'parentcluster', 'on'); % end; end; [STUDY ALLEEG] = std_checkset(STUDY, ALLEEG); if ~isempty(g.filename), [STUDY.filepath STUDY.filename ext] = fileparts(fullfile( g.filepath, g.filename )); STUDY.filename = [ STUDY.filename ext ]; g.resave = 'on'; end if strcmpi(g.resave, 'on') STUDY = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave'); end; % --------------------- % remove empty elements % --------------------- function [ALLEEG, datasetinfo] = remove_empty(ALLEEG, datasetinfo); rmindex = []; for index = 1:length(datasetinfo) if isempty(datasetinfo(index).subject) && isempty(ALLEEG(index).nbchan) rmindex = [ rmindex index ]; end; end; datasetinfo(rmindex) = []; ALLEEG(rmindex) = []; for index = 1:length(datasetinfo) datasetinfo(index).index = index; end; % remove empty ALLEEG structures % ------------------------------ while length(ALLEEG) > length(datasetinfo) ALLEEG(end) = []; end;
github
ZijingMao/baselineeegtest-master
std_readitc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readitc.m
1,475
utf_8
0c0874e2789900f1ae4de7b00a08107f
% std_readitc() - load ITC measures for data channels or % for all components of a specified cluster. % Usage: % >> [STUDY, itcdata, times, freqs] = ... % std_readitc(STUDY, ALLEEG, varargin); % % Note: this function is a helper function that contains a call to the % std_readersp function that reads all 2-D data matrices for EEGLAB STUDY. % See the std_readersp help message for more information. % % Author: Arnaud Delorme, CERCO, 2006- % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 11, 2004, [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 [STUDY, erspdata, alltimes, allfreqs, erspbase] = std_readersp(STUDY, ALLEEG, varargin); [STUDY, erspdata, alltimes, allfreqs] = std_readersp(STUDY, ALLEEG, 'infotype','itc', varargin{:});
github
ZijingMao/baselineeegtest-master
pop_loadstudy.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_loadstudy.m
7,058
utf_8
2620548ba19051c9deb0e0f1ee8474bf
% pop_loadstudy() - load an existing EEGLAB STUDY set of EEG datasets plus % its corresponding ALLEEG structure. Calls std_loadalleeg(). % Usage: % >> [STUDY ALLEEG] = pop_loadstudy; % pop up a window to collect filename % >> [STUDY ALLEEG] = pop_loadstudy( 'key', 'val', ...); % no pop-up % % Optional inputs: % 'filename' - [string] filename of the STUDY set file to load. % 'filepath' - [string] filepath of the STUDY set file to load. % % Outputs: % STUDY - the requested STUDY set structure. % ALLEEG - the corresponding ALLEEG structure containing % the (loaded) STUDY EEG datasets. % % See also: std_loadalleeg(), pop_savestudy() % % Authors: Hilit Serby & Arnaud Delorme, SCCN, INC, UCSD, September 2005 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, Spetember 2005, [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 % Coding notes: Useful information on functions and global variables used. function [STUDY, ALLEEG, com] = pop_loadstudy(varargin) STUDY = []; ALLEEG = []; com = ''; if isempty(varargin) [filename, filepath] = uigetfile2('*.study', 'Load a STUDY -- pop_loadstudy()'); if filename(1) == 0, return; end; if ~strncmp(filename(end-5:end), '.study',6) if isempty(strfind(filename,'.')) filename = [filename '.study']; else filename = [filename(1:strfind(filename,'.')-1) '.study']; end end else filepath = ''; if nargin == 1 varargin = { 'filename' varargin{:} }; end; for k = 1:2:length(varargin) switch varargin{k} case 'filename' filename = varargin{k+1}; case 'filepath' filepath = varargin{k+1}; end end end if ~isempty(filename) STUDYfile = fullfile(filepath,filename); try load('-mat', STUDYfile); catch error(['pop_loadstudy(): STUDY set file ''STUDYfile'' not loaded -- check filename and path']); end [filepath filename ext] = fileparts(STUDYfile); STUDY.filename = [filename ext]; STUDY.etc.oldfilepath = STUDY.filepath; STUDY.filepath = filepath; else error(['pop_loadstudy(): No STUDY set file provided.']); end ALLEEG = std_loadalleeg(STUDY); % Update the pointers from STUDY to the ALLEEG datasets for k = 1:length(STUDY.datasetinfo) STUDY.datasetinfo(k).index = k; STUDY.datasetinfo(k).filename = ALLEEG(k).filename; STUDY.datasetinfo(k).filepath = ALLEEG(k).filepath; end if ~isfield(STUDY, 'changrp'), STUDY.changrp = []; end; [STUDY ALLEEG] = std_checkset(STUDY, ALLEEG); if ~isfield(STUDY, 'changrp') || isempty(STUDY.changrp) if std_uniformfiles(STUDY, ALLEEG) == 0 STUDY = std_changroup(STUDY, ALLEEG); else STUDY = std_changroup(STUDY, ALLEEG, [], 'interp'); end; end; % Update the design path for inddes = 1:length(STUDY.design) for indcell = 1:length(STUDY.design(inddes).cell) pathname = STUDY.datasetinfo(STUDY.design(inddes).cell(indcell).dataset(1)).filepath; filebase = STUDY.design(inddes).cell(indcell).filebase; tmpinds1 = find(filebase == '/'); tmpinds2 = find(filebase == '\'); if ~isempty(tmpinds1) STUDY.design(inddes).cell(indcell).filebase = fullfile(pathname, filebase(tmpinds1(end)+1:end)); elseif ~isempty(tmpinds2) STUDY.design(inddes).cell(indcell).filebase = fullfile(pathname, filebase(tmpinds2(end)+1:end)); else STUDY.design(inddes).cell(indcell).filebase = fullfile(pathname, filebase ); end; end; end; % check for corrupted ERSP ICA data files % A corrupted file is present if % - components have been selected % - .icaersp or .icaitc files are present % - the .trialindices field is missing from these files try %% check for corrupted ERSP ICA data files ncomps1 = cellfun(@length, { STUDY.datasetinfo.comps }); ncomps2 = cellfun(@(x)(size(x,1)), { ALLEEG.icaweights }); if any(~isempty(ncomps1)) if any(ncomps1 ~= ncomps2) warningshown = 0; for des = 1:length(STUDY.design) for iCell = 1:length(STUDY.design(des).cell) if ~warningshown if exist( [ STUDY.design(des).cell(iCell).filebase '.icaersp' ] ) warning('off', 'MATLAB:load:variableNotFound'); tmp = load('-mat', [ STUDY.design(des).cell(iCell).filebase '.icaersp' ], 'trialindices'); warning('on', 'MATLAB:load:variableNotFound'); if ~isfield(tmp, 'trialindices') warningshown = 1; warndlg( [ 'Warning: ICA ERSP or ITC data files computed with old version of EEGLAB for design ' int2str(des) 10 ... '(and maybe other designs). These files may be corrupted and must be recomputed.' ], 'Important EEGLAB warning', 'nonmodal'); end; end; if warningshown == 0 && exist( [ STUDY.design(des).cell(iCell).filebase '.icaitc' ] ) tmp = load('-mat', [ STUDY.design(des).cell(iCell).filebase '.icaersp' ], 'trialindices'); if ~isfield(tmp, 'trialindices') warningshown = 1; warndlg( [ 'Warning: ICA ERSP or ITC data files computed with old version of EEGLAB for design ' int2str(des) 10 ... '(and maybe other designs). These files may be corrupted and must be recomputed.' ], 'Important EEGLAB warning', 'modal'); end; end; end; end; end; end; end; catch, disp('Warning: failed to test STUDY file version'); end; TMP = STUDY.datasetinfo; STUDY = std_maketrialinfo(STUDY, ALLEEG); if ~isequal(STUDY.datasetinfo, TMP) disp('STUDY Warning: the trial information collected from datasets has changed'); end; std_checkfiles(STUDY, ALLEEG); STUDY.saved = 'yes'; STUDY = std_selectdesign(STUDY, ALLEEG, STUDY.currentdesign); com = sprintf('[STUDY ALLEEG] = pop_loadstudy(''filename'', ''%s'', ''filepath'', ''%s'');', STUDY.filename, STUDY.filepath);
github
ZijingMao/baselineeegtest-master
std_readspecgram.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readspecgram.m
4,381
utf_8
96b0d97423e8bcaaf19884201bfb7a63
% std_readspecgram() - returns the stored mean power spectrogram for an ICA component % or a data channel in a specified dataset. The spectrogram is % assumed to have been saved in a Matlab file, % "[dataset_name].datspecgram", in the same % directory as the dataset file. If this file doesn't exist, % use std_specgram() to create it. % Usage: % >> [spec, times, freqs] = std_readspecgram(ALLEEG, setindx, component, timerange, freqrange); % % Inputs: % ALLEEG - a vector of dataset EEG structures (may also be one dataset). % Must contain the dataset of interest (the 'setindx' below). % setindx - [integer] an index of an EEG dataset in the ALLEEG % structure for which to read a component spectrum. % component - [integer] index of the component in the selected EEG dataset % for which to return the spectrum % freqrange - [min max in Hz] frequency range to return % % % Outputs: % spec - the log-power spectrum of the requested ICA component in the % specified dataset (in dB) % freqs - vector of spectral frequencies (in Hz) % % See also std_spec(), pop_preclust(), std_preclust() % % Authors: Arnaud Delorme, SCCN, INC, UCSD, February, 2008 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 2004, [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 [X, t, f] = std_readspecgram(ALLEEG, abset, comp, timerange, freqrange, rmsubjmean); if nargin < 4 timerange = []; end; if nargin < 5 freqrange = []; end; X = []; if iscell(comp) % find channel indices list % ------------------------- chanind = []; tmpchanlocs = ALLEEG(abset).chanlocs; chanlabs = lower({ tmpchanlocs.labels }); for index = 1:length(comp) tmp = strmatch(lower(comp{index}), chanlabs, 'exact'); if isempty(tmp) error([ 'Channel ''' comp{index} ''' not found in dataset ' int2str(abset)]); else chanind = [ chanind tmp ]; end; end; filename = fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'datspecgram']); prefix = 'chan'; inds = chanind; elseif comp(1) < 0 filename = fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'datspecgram']); prefix = 'chan'; inds = -comp; else filename = fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'icaspecgram']); prefix = 'comp'; inds = comp; end; for k=1:length(inds) try, warning backtrace off; erpstruct = load( '-mat', filename, [ prefix int2str(inds(k)) ], 'freqs', 'times'); warning backtrace on; catch error( [ 'Cannot read file ''' filename '''' ]); end; tmpdat = getfield(erpstruct, [ prefix int2str(inds(k)) ]); if k == 1 X = zeros([size(tmpdat) length(comp)]); end; X(:,:,k) = tmpdat; f = getfield(erpstruct, 'freqs'); t = getfield(erpstruct, 'times'); end; % select frequency range of interest % ---------------------------------- if ~isempty(freqrange) maxind = max(find(f <= freqrange(end))); minind = min(find(f >= freqrange(1))); else %if not, use whole spectrum maxind = length(f); minind = 1; end f = f(minind:maxind); X = X(minind:maxind,:,:); % select time range of interest % ----------------------------- if ~isempty(timerange) maxind = max(find(t <= timerange(end))); minind = min(find(t >= timerange(1))); else %if not, use whole spectrum maxind = length(t); minind = 1; end t = t(minind:maxind); X = X(:,minind:maxind,:); return;
github
ZijingMao/baselineeegtest-master
std_pacplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_pacplot.m
1,889
utf_8
b3f29ed622b651d14f649518b13acd9f
% std_pacplot() - Commandline function to plot cluster PAC % (phase-amplitude coupling). % % Usage: % >> [STUDY] = std_pacplot(STUDY, ALLEEG, key1, val1, key2, val2); % >> [STUDY itcdata itctimes itcfreqs pgroup pcond pinter] = ... % std_pacplot(STUDY, ALLEEG ...); % Inputs: % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - global EEGLAB vector of EEG structures for the datasets in the STUDY. % Note: ALLEEG for a STUDY set is typically created using load_ALLEEG(). % % Additional help: % Inputs and output of this function are strictly identical to the std_erspplot(). % See the help message of this function for more information. % % See also: std_erspplot(), pop_clustedit(), pop_preclust() % % Authors: Arnaud Delorme, CERCO, July, 2009- % Copyright (C) Arnaud Delorme, [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 [STUDY, allpac, alltimes, allfreqs, pgroup, pcond, pinter] = std_pacplot(STUDY, ALLEEG, varargin) if nargin < 2 help std_pacplot; return; end; [STUDY allpac alltimes allfreqs pgroup pcond pinter ] = std_erspplot(STUDY, ALLEEG, 'datatype', 'pac', varargin{:});
github
ZijingMao/baselineeegtest-master
pop_dipparams.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_dipparams.m
3,898
utf_8
49636409e08a138da902e72246f3131a
% pop_dipparams() - Set plotting parameters for dipoles. % % Usage: % >> STUDY = pop_dipparams(STUDY, 'key', 'val'); % % Inputs: % STUDY - EEGLAB STUDY set % % Optional inputs: % 'axistight' - ['on'|'off'] Plot closest MRI slide. Default is 'off'. % 'projimg' - ['on'|'off'] lot dipoles projections on each axix. Default is 'off'. % 'projlines' - ['on'|'off'] Plot projection lines. Default is 'off'. % % See also: std_dipplot() % % Authors: Arnaud Delorme % Copyright (C) Arnaud Delorme, 20013 % % 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 [ STUDY, com ] = pop_dipparams(STUDY, varargin); STUDY = default_params(STUDY); TMPSTUDY = STUDY; com = ''; if isempty(varargin) val_axistight = fastif(strcmpi(STUDY.etc.dipparams.axistight,'on'), 1, 0); val_projimg = fastif(strcmpi(STUDY.etc.dipparams.projimg,'on'), 1, 0); val_projlines = fastif(strcmpi(STUDY.etc.dipparams.projlines,'on'), 1, 0); uilist = { ... {'style' 'checkbox' 'tag' 'axistight' 'value' val_axistight } { 'style' 'text' 'string' 'Plot closest MRI slide' } ... {'style' 'checkbox' 'tag' 'projlines' 'value' val_projlines } { 'style' 'text' 'string' 'Plot projection lines' } ... {'style' 'checkbox' 'tag' 'projimg' 'value' val_projimg } { 'style' 'text' 'string' 'Plot dipoles projections' } }; [out_param userdat tmp res] = inputgui( 'geometry' , { [0.1 1] [0.1 1] [0.1 1] }, 'uilist', uilist, 'geomvert', [1 1 1], ... 'title', 'ERP plotting options -- pop_dipparams()'); if isempty(res), return; end; % decode inputs % ------------- res.axistight = fastif(res.axistight, 'on', 'off'); res.projimg = fastif(res.projimg , 'on', 'off'); res.projlines = fastif(res.projlines, 'on', 'off'); % build command call % ------------------ options = {}; if ~strcmpi( res.axistight, STUDY.etc.dipparams.axistight), options = { options{:} 'axistight' res.axistight }; end; if ~strcmpi( res.projimg, STUDY.etc.dipparams.projimg ), options = { options{:} 'projimg' res.projimg }; end; if ~strcmpi( res.projlines, STUDY.etc.dipparams.projlines), options = { options{:} 'projlines' res.projlines }; end; if ~isempty(options) STUDY = pop_dipparams(STUDY, options{:}); com = sprintf('STUDY = pop_dipparams(STUDY, %s);', vararg2str( options )); end; else if strcmpi(varargin{1}, 'default') STUDY = default_params(STUDY); else for index = 1:2:length(varargin) if ~isempty(strmatch(varargin{index}, fieldnames(STUDY.etc.dipparams), 'exact')) STUDY.etc.dipparams = setfield(STUDY.etc.dipparams, varargin{index}, varargin{index+1}); end; end; end; end; function STUDY = default_params(STUDY) if ~isfield(STUDY.etc, 'dipparams'), STUDY.etc.dipparams = []; end; if ~isfield(STUDY.etc.dipparams, 'axistight'), STUDY.etc.dipparams.axistight = 'off'; end; if ~isfield(STUDY.etc.dipparams, 'projimg'), STUDY.etc.dipparams.projimg = 'off'; end; if ~isfield(STUDY.etc.dipparams, 'projlines'), STUDY.etc.dipparams.projlines = 'off'; end;
github
ZijingMao/baselineeegtest-master
std_precomp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_precomp.m
29,624
utf_8
dd96b4908b3c59eeb35b08d9b80b4c87
% std_precomp() - Precompute measures (ERP, spectrum, ERSP, ITC) for channels in a % study. If channels are interpolated before computing the measures, % the updated EEG datasets are also saved to disk. Called by % pop_precomp(). Follow with pop_plotstudy(). See Example below. % Usage: % >> [STUDY ALLEEG customRes] = std_precomp(STUDY, ALLEEG, chanorcomp, 'key', 'val', ...); % % Required inputs: % STUDY - an EEGLAB STUDY set of loaded EEG structures % ALLEEG - ALLEEG vector of one or more loaded EEG dataset structures % chanorcomp - ['components'|'channels'| or channel cell array] The string % 'components' forces the program to precompute all selected % measures for components. The string 'channels' forces the % program to compute all measures for all channels. % A channel cell array containing channel labels will precompute % the selected measures. Note that the name of the channel is % not case-sensitive. % Optional inputs: % 'design' - [integer] use specific study index design to compute measure. % 'cell' - [integer] compute measure only for a give data file. % 'erp' - ['on'|'off'] pre-compute ERPs for each dataset. % 'spec' - ['on'|'off'] pre-compute spectrum for each dataset. % Use 'specparams' to set spectrum parameters. % 'ersp' - ['on'|'off'] pre-compute ERSP for each dataset. % Use 'erspparams' to set time/frequency parameters. % 'itc' - ['on'|'off'] pre-compute ITC for each dataset. % Use 'erspparams' to set time/frequency parameters. % 'scalp' - ['on'|'off'] pre-compute scalp maps for components. % 'allcomps' - ['on'|'off'] compute ERSP/ITC for all components ('off' % only use pre-selected components in the pop_study interface). % 'erpparams' - [cell array] Parameters for the std_erp function. See % std_erp for more information. % 'specparams' - [cell array] Parameters for the std_spec function. See % std_spec for more information. % 'erspparams' - [cell array] Optional arguments for the std_ersp function. % 'erpimparams' - [cell array] Optional argument for std_erpimage. See % std_erpimage for the list of arguments. % 'recompute' - ['on'|'off'] force recomputing ERP file even if it is % already on disk. % 'rmicacomps' - ['on'|'off'|'processica'] remove ICA components pre-selected in % each dataset (EEGLAB menu item, "Tools > Reject data using ICA % > Reject components by map). This option is ignored when % precomputing measures for ICA clusters. Default is 'off'. % 'processica' forces to process ICA components instead of % removing them. % 'rmclust' - [integer array] remove selected ICA component clusters. % For example, ICA component clusters containing % artifacts. This option is ignored when precomputing % measures for ICA clusters. % 'savetrials' - ['on'|'off'] save single-trials ERSP. Requires a lot of disk % space (dataset space on disk times 10) but allow for refined % single-trial statistics. % 'customfunc' - [function_handle] execute a specific function on each % EEGLAB dataset of the selected STUDY design. The fist % argument to the function is an EEGLAB dataset. Example is % @(EEG)mean(EEG.data,3) % This will compute the ERP for the STUDY design. EEG is the % EEGLAB dataset corresponding to each cell design. It % corresponds to a dataset computed dynamically based on % the design selection. If 'rmclust', 'rmicacomps' or 'interp' % are being used, the channel data is affected % accordingly. Anonymous and non-anonymous functions may be % used. The output is returned in CustomRes or saved on % disk. The output of the custom function may be an numerical % array or a structure. % 'customparams' - [cell array] Parameters for the custom function above. % 'customfileext' - [string] file extension for saving custom data. Use % function to read custom data. If left empty, the % result is returned in the customRes output. Note that % if the custom function does not return a structure, % the data is automatically saved in a variable named % 'data'. % 'customclusters' - [integer array] load only specific clusters. This is % used with SIFT. chanorcomp 3rd input must be 'components'. % % Outputs: % ALLEEG - the input ALLEEG vector of EEG dataset structures, modified % by adding preprocessing data as pointers to Matlab files that % hold the pre-clustering component measures. % STUDY - the input STUDY set with pre-clustering data added, % for use by pop_clust() % customRes - cell array of custom results (one cell for each pair of % independent variables as defined in the STUDY design). % If a custom file extension is specified, this variable % is empty as the function assumes that the result is too % large to hold in memory. % % Example: % >> [STUDY ALLEEG customRes] = std_precomp(STUDY, ALLEEG, { 'cz' 'oz' }, 'interp', ... % 'on', 'erp', 'on', 'spec', 'on', 'ersp', 'on', 'erspparams', ... % { 'cycles' [ 3 0.5 ], 'alpha', 0.01, 'padratio' 1 }); % % % This prepares, channels 'cz' and 'oz' in the STUDY datasets. % % If a data channel is missing in one dataset, it will be % % interpolated (see eeg_interp()). The ERP, spectrum, ERSP, and % % ITC for each dataset is then computed. % % Example of custom call: % The function below computes the ERP of the EEG data for each channel and plots it. % >> [STUDY ALLEEG customres] = std_precomp(STUDY, ALLEEG, 'channels', 'customfunc', @(EEG,varargin)(mean(EEG.data,3)')); % >> std_plotcurve([1:size(customres{1},1)], customres, 'chanlocs', eeg_mergelocs(ALLEEG.chanlocs)); % plot data % % The function below uses a data file to store the information then read % the data and eventyally plot it % >> [STUDY ALLEEG customres] = std_precomp(STUDY, ALLEEG, 'channels', 'customfunc', @(EEG,varargin)(mean(EEG.data,3)), 'customfileext', 'tmperp'); % >> erpdata = std_readcustom(STUDY, ALLEEG, 'tmperp'); % >> std_plotcurve([1:size(erpdata{1})], erpdata, 'chanlocs', eeg_mergelocs(ALLEEG.chanlocs)); % plot data % % Authors: Arnaud Delorme, SCCN, INC, UCSD, 2006- % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2006, [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 [ STUDY, ALLEEG customRes ] = std_precomp(STUDY, ALLEEG, chanlist, varargin) if nargin < 2 help std_precomp; return; end; if nargin == 2 chanlist = 'channels'; % default to clustering the whole STUDY end customRes = []; Ncond = length(STUDY.condition); if Ncond == 0 Ncond = 1; end g = finputcheck(varargin, { 'erp' 'string' { 'on','off' } 'off'; 'interp' 'string' { 'on','off' } 'off'; 'ersp' 'string' { 'on','off' } 'off'; 'recompute' 'string' { 'on','off' } 'off'; 'spec' 'string' { 'on','off' } 'off'; 'erpim' 'string' { 'on','off' } 'off'; 'scalp' 'string' { 'on','off' } 'off'; 'allcomps' 'string' { 'on','off' } 'off'; 'itc' 'string' { 'on','off' } 'off'; 'savetrials' 'string' { 'on','off' } 'off'; 'rmicacomps' 'string' { 'on','off','processica' } 'off'; 'cell' 'integer' [] []; 'design' 'integer' [] STUDY.currentdesign; 'rmclust' 'integer' [] []; 'rmbase' 'integer' [] []; % deprecated, for backward compatibility purposes, not documented 'specparams' 'cell' {} {}; 'erpparams' 'cell' {} {}; 'customfunc' {'function_handle' 'integer' } { { } {} } []; 'customparams' 'cell' {} {}; 'customfileext' 'string' [] ''; 'customclusters' 'integer' [] []; 'erpimparams' 'cell' {} {}; 'erspparams' 'cell' {} {}}, 'std_precomp'); if isstr(g), error(g); end; if ~isempty(g.rmbase), g.erpparams = { g.erpparams{:} 'rmbase' g.rmbase }; end; % union of all channel structures % ------------------------------- computewhat = 'channels'; if isstr(chanlist) if strcmpi(chanlist, 'channels') chanlist = []; else % components computewhat = 'components'; if strcmpi(g.allcomps, 'on') chanlist = {}; for index = 1:length(STUDY.datasetinfo) chanlist = { chanlist{:} [1:size(ALLEEG(STUDY.datasetinfo(index).index).icaweights,1)] }; end; else chanlist = { STUDY.datasetinfo.comps }; end; end; end; if isempty(chanlist) alllocs = eeg_mergelocs(ALLEEG.chanlocs); chanlist = { alllocs.labels }; elseif ~isnumeric(chanlist{1}) alllocs = eeg_mergelocs(ALLEEG.chanlocs); [tmp c1 c2] = intersect_bc( lower({ alllocs.labels }), lower(chanlist)); [tmp c2] = sort(c2); alllocs = alllocs(c1(c2)); end; % test if interp and reconstruct channel list % ------------------------------------------- if strcmpi(computewhat, 'channels') if strcmpi(g.interp, 'on') STUDY.changrp = []; STUDY = std_changroup(STUDY, ALLEEG, chanlist, 'interp'); g.interplocs = alllocs; else STUDY.changrp = []; STUDY = std_changroup(STUDY, ALLEEG, chanlist); g.interplocs = struct([]); end; end; % components or channels % ---------------------- if strcmpi(computewhat, 'channels') curstruct = STUDY.changrp; else curstruct = STUDY.cluster; end; % compute custom measure % ---------------------- if ~isempty(g.customfunc) nc = max(length(STUDY.design(g.design).variable(1).value),1); ng = max(length(STUDY.design(g.design).variable(2).value),1); allinds = curstruct(1).allinds; % same for all channels and components (see std_selectdesign) setinds = curstruct(1).setinds; % same for all channels and components (see std_selectdesign) if ~isempty(g.customclusters) allinds = curstruct(g.customclusters).allinds; % same for all channels and components (see std_selectdesign) setinds = curstruct(g.customclusters).setinds; % same for all channels and components (see std_selectdesign) end; for cInd = 1:nc for gInd = 1:ng if ~isempty(setinds{cInd,gInd}) desset = STUDY.design(g.design).cell(setinds{cInd,gInd}(:)); for iDes = 1:length(desset) if strcmpi(computewhat, 'channels') [tmpchanlist opts] = getchansandopts(STUDY, ALLEEG, chanlist, desset(iDes).dataset, g); TMPEEG = std_getdataset(STUDY, ALLEEG, 'design', g.design, 'cell', setinds{cInd,gInd}(iDes), opts{:}); % trial indices included in cell selection else TMPEEG = std_getdataset(STUDY, ALLEEG, 'design', g.design, 'cell', setinds{cInd,gInd}(iDes), 'cluster', g.customclusters); end; addopts = { 'savetrials', g.savetrials, 'recompute', g.recompute }; % not currently used tmpData = feval(g.customfunc, TMPEEG, g.customparams{:}); if isempty(g.customfileext) resTmp(:,:,iDes) = tmpData; else fileName = [ desset(iDes).filebase '.' g.customfileext ]; clear data; data.data = tmpData; data.datafile = computeFullFileName( { ALLEEG(desset(iDes).dataset).filepath }, { ALLEEG(desset(iDes).dataset).filename }); data.datatrials = desset(iDes).trials; data.datatype = upper(g.customfileext); if ~isempty(g.customparams) data.parameters = g.customparams; end; std_savedat(fileName, data); end; end; if isempty(g.customfileext) customRes{cInd,gInd} = resTmp; end; clear resTmp; end; end; end; end; % compute ERPs % ------------ if strcmpi(g.erp, 'on') % check dataset consistency % ------------------------- allPnts = [ALLEEG([STUDY.design(g.design).cell.dataset]).pnts]; if iscell(allPnts), allPnts = [ allPnts{:} ]; end; if length(unique(allPnts)) > 1 error([ 'Cannot compute ERPs because datasets' 10 'do not have the same number of data points' ]) end; for index = 1:length(STUDY.design(g.design).cell) if ~isempty(g.cell) desset = STUDY.design(g.design).cell(g.cell); else desset = STUDY.design(g.design).cell(index); end; addopts = { 'savetrials', g.savetrials, 'recompute', g.recompute, 'fileout', desset.filebase, 'trialindices', desset.trials }; if strcmpi(computewhat, 'channels') [tmpchanlist opts] = getchansandopts(STUDY, ALLEEG, chanlist, desset.dataset, g); std_erp(ALLEEG(desset.dataset), 'channels', tmpchanlist, opts{:}, addopts{:}, g.erpparams{:}); else if length(desset.dataset)>1 && ~isequal(chanlist{desset.dataset}) error(['ICA decompositions must be identical if' 10 'several datasets are concatenated to build' 10 'the design, abording' ]); end; std_erp(ALLEEG(desset.dataset), 'components', chanlist{desset.dataset(1)}, addopts{:}, g.erpparams{:}); end; if ~isempty(g.cell), break; end; end; if isfield(curstruct, 'erpdata') curstruct = rmfield(curstruct, 'erpdata'); curstruct = rmfield(curstruct, 'erptimes'); end; end; % compute spectrum % ---------------- if strcmpi(g.spec, 'on') % check dataset consistency % ------------------------- for index = 1:length(STUDY.design(g.design).cell) if ~isempty(g.cell) desset = STUDY.design(g.design).cell(g.cell); else desset = STUDY.design(g.design).cell(index); end; addopts = { 'savetrials', g.savetrials, 'recompute', g.recompute, 'fileout', desset.filebase, 'trialindices', desset.trials }; if strcmpi(computewhat, 'channels') [tmpchanlist opts] = getchansandopts(STUDY, ALLEEG, chanlist, desset.dataset, g); std_spec(ALLEEG(desset.dataset), 'channels', tmpchanlist, opts{:}, addopts{:}, g.specparams{:}); else if length(desset.dataset)>1 && ~isequal(chanlist{desset.dataset}) error(['ICA decompositions must be identical if' 10 'several datasets are concatenated to build' 10 'the design, abording' ]); end; std_spec(ALLEEG(desset.dataset), 'components', chanlist{desset.dataset(1)}, addopts{:}, g.specparams{:}); end; if ~isempty(g.cell), break; end; end; if isfield(curstruct, 'specdata') curstruct = rmfield(curstruct, 'specdata'); curstruct = rmfield(curstruct, 'specfreqs'); end; end; % compute spectrum % ---------------- if strcmpi(g.erpim, 'on') % check dataset consistency % ------------------------- allPnts = [ALLEEG([STUDY.design(g.design).cell.dataset]).pnts]; if iscell(allPnts), allPnts = [ allPnts{:} ]; end; if length(unique(allPnts)) > 1 error([ 'Cannot compute ERSPs/ITCs because datasets' 10 'do not have the same number of data points' ]) end; % check consistency with parameters on disk % ----------------------------------------- guimode = 'guion'; tmpparams = {}; tmpparams = g.erpimparams; if strcmpi(g.recompute, 'off') for index = 1:length(STUDY.design(g.design).cell) desset = STUDY.design(g.design).cell(index); if strcmpi(computewhat, 'channels') filename = [ desset.filebase '.daterpim']; else filename = [ desset.filebase '.icaerpim']; end; [guimode, g.erpimparams] = std_filecheck(filename, g.erpimparams, guimode, { 'fileout' 'recompute', 'channels', 'components', 'trialindices'}); if strcmpi(guimode, 'cancel'), return; end; end; if strcmpi(guimode, 'usedisk') || strcmpi(guimode, 'same'), g.recompute = 'off'; else g.recompute = 'on'; end; if ~isempty(g.erpimparams) && isstruct(g.erpimparams) tmpparams = fieldnames(g.erpimparams); tmpparams = tmpparams'; tmpparams(2,:) = struct2cell(g.erpimparams); end; end; % set parameters in ERPimage parameters % ------------------------------------- STUDY = pop_erpimparams(STUDY, tmpparams{:}); % a little trashy as the function pop_erpimparams does not check the fields % compute ERPimages % ----------------- for index = 1:length(STUDY.design(g.design).cell) if ~isempty(g.cell) desset = STUDY.design(g.design).cell(g.cell); else desset = STUDY.design(g.design).cell(index); end; addopts = { 'recompute', g.recompute, 'fileout', desset.filebase, 'trialindices', desset.trials }; if strcmpi(computewhat, 'channels') [tmpchanlist opts] = getchansandopts(STUDY, ALLEEG, chanlist, desset.dataset, g); std_erpimage(ALLEEG(desset.dataset), 'channels', tmpchanlist, opts{:}, addopts{:}, tmpparams{:}); else if length(desset.dataset)>1 && ~isequal(chanlist{desset.dataset}) error(['ICA decompositions must be identical if' 10 'several datasets are concatenated to build' 10 'the design, abording' ]); end; std_erpimage(ALLEEG(desset.dataset), 'components', chanlist{desset.dataset(1)}, addopts{:}, tmpparams{:}); end; if ~isempty(g.cell), break; end; end; if isfield(curstruct, 'erpimdata') curstruct = rmfield(curstruct, 'erpimdata'); curstruct = rmfield(curstruct, 'erpimtimes'); curstruct = rmfield(curstruct, 'erpimtrials'); curstruct = rmfield(curstruct, 'erpimevents'); end; end; % compute component scalp maps % ---------------------------- if strcmpi(g.scalp, 'on') && ~strcmpi(computewhat, 'channels') for index = 1:length(STUDY.datasetinfo) % find duplicate % -------------- found = []; ind1 = STUDY.datasetinfo(index).index; inds = strmatch(STUDY.datasetinfo(index).subject, { STUDY.datasetinfo(1:index-1).subject }); for index2 = 1:length(inds) ind2 = STUDY.datasetinfo(inds(index2)).index; if isequal(ALLEEG(ind1).icawinv, ALLEEG(ind2).icawinv) found = ind2; end; end; % make link if duplicate % ---------------------- fprintf('Computing/checking topo file for dataset %d\n', ind1); if ~isempty(found) tmpfile1 = fullfile( ALLEEG(index).filepath, [ ALLEEG(index).filename(1:end-3) 'icatopo' ]); tmp.file = fullfile( ALLEEG(found).filepath, [ ALLEEG(found).filename(1:end-3) 'icatopo' ]); std_savedat(tmpfile1, tmp); else std_topo(ALLEEG(index), chanlist{index}, 'none', 'recompute', g.recompute); end; end; if isfield(curstruct, 'topo') curstruct = rmfield(curstruct, 'topo'); curstruct = rmfield(curstruct, 'topox'); curstruct = rmfield(curstruct, 'topoy'); curstruct = rmfield(curstruct, 'topoall'); curstruct = rmfield(curstruct, 'topopol'); end; end; % compute ERSP and ITC % -------------------- if strcmpi(g.ersp, 'on') || strcmpi(g.itc, 'on') % check dataset consistency % ------------------------- allPnts = [ALLEEG([STUDY.design(g.design).cell.dataset]).pnts]; if iscell(allPnts), allPnts = [ allPnts{:} ]; end; if length(unique(allPnts)) > 1 error([ 'Cannot compute ERSPs/ITCs because datasets' 10 'do not have the same number of data points' ]) end; if strcmpi(g.ersp, 'on') & strcmpi(g.itc, 'on'), type = 'both'; elseif strcmpi(g.ersp, 'on') , type = 'ersp'; else type = 'itc'; end; % check for existing files % ------------------------ guimode = 'guion'; [ tmpX tmpt tmpf g.erspparams ] = std_ersp(ALLEEG(1), 'channels', 1, 'type', type, 'recompute', 'on', 'getparams', 'on', 'savetrials', g.savetrials, g.erspparams{:}); if strcmpi(g.recompute, 'off') for index = 1:length(STUDY.design(g.design).cell) desset = STUDY.design(g.design).cell(index); if strcmpi(computewhat, 'channels') filename = [ desset.filebase '.datersp']; else filename = [ desset.filebase '.icaersp']; end; [guimode, g.erspparams] = std_filecheck(filename, g.erspparams, guimode, { 'plotitc' 'plotersp' 'plotphase' }); if strcmpi(guimode, 'cancel'), return; end; end; if strcmpi(guimode, 'usedisk') || strcmpi(guimode, 'same'), g.recompute = 'off'; else g.recompute = 'on'; end; end; % check for existing files % ------------------------ if isempty(g.erspparams), tmpparams = {}; elseif iscell(g.erspparams), tmpparams = g.erspparams; else tmpparams = fieldnames(g.erspparams); tmpparams = tmpparams'; tmpparams(2,:) = struct2cell(g.erspparams); end; tmpparams = { tmpparams{:} 'recompute' g.recompute }; for index = 1:length(STUDY.design(g.design).cell) if ~isempty(g.cell) desset = STUDY.design(g.design).cell(g.cell); else desset = STUDY.design(g.design).cell(index); end; if strcmpi(computewhat, 'channels') [tmpchanlist opts] = getchansandopts(STUDY, ALLEEG, chanlist, desset.dataset, g); std_ersp(ALLEEG(desset.dataset), 'channels', tmpchanlist, 'type', type, 'fileout', desset.filebase, 'trialindices', desset.trials, opts{:}, tmpparams{:}); else if length(desset.dataset)>1 && ~isequal(chanlist{desset.dataset}) error(['ICA decompositions must be identical if' 10 'several datasets are concatenated to build' 10 'the design, abording' ]); end; std_ersp(ALLEEG(desset.dataset), 'components', chanlist{desset.dataset(1)}, 'type', type, 'fileout', desset.filebase, 'trialindices', desset.trials, tmpparams{:}); end; if ~isempty(g.cell), break; end; end; if isfield(curstruct, 'erspdata') curstruct = rmfield(curstruct, 'erspdata'); curstruct = rmfield(curstruct, 'ersptimes'); curstruct = rmfield(curstruct, 'erspfreqs'); end; if isfield(curstruct, 'itcdata') curstruct = rmfield(curstruct, 'itcdata'); curstruct = rmfield(curstruct, 'itctimes'); curstruct = rmfield(curstruct, 'itcfreqs'); end; end; % components or channels % ---------------------- if strcmpi(computewhat, 'channels') STUDY.changrp = curstruct; else STUDY.cluster = curstruct; end; return; % find components in cluster for specific dataset % ----------------------------------------------- function rmcomps = getclustcomps(STUDY, rmclust, settmpind); rmcomps = cell(1,length(settmpind)); for idat = 1:length(settmpind) % scan dataset for which to find component clusters for rmi = 1:length(rmclust) % scan clusters comps = STUDY.cluster(rmclust(rmi)).comps; sets = STUDY.cluster(rmclust(rmi)).sets; indmatch = find(sets(:) == settmpind(idat)); indmatch = ceil(indmatch/size(sets,1)); % get the column number rmcomps{idat} = [rmcomps{idat} comps(indmatch(:)') ]; end; rmcomps{idat} = sort(rmcomps{idat}); end; % make option array and channel list (which depend on interp) for any type of measure % ---------------------------------------------------------------------- function [tmpchanlist, opts] = getchansandopts(STUDY, ALLEEG, chanlist, idat, g); opts = { }; if ~isempty(g.rmclust) || strcmpi(g.rmicacomps, 'on') || strcmpi(g.rmicacomps, 'processica') rmcomps = cell(1,length(idat)); if ~isempty(g.rmclust) rmcomps = getclustcomps(STUDY, g.rmclust, idat); end; if strcmpi(g.rmicacomps, 'on') for ind = 1:length(idat) rmcomps{ind} = union_bc(rmcomps{ind}, find(ALLEEG(idat(1)).reject.gcompreject)); end; elseif strcmpi(g.rmicacomps, 'processica') for ind = 1:length(idat) rmcomps{ind} = union_bc(rmcomps{ind}, find(~ALLEEG(idat(1)).reject.gcompreject)); end; end; opts = { opts{:} 'rmcomps' rmcomps }; end; if strcmpi(g.interp, 'on') tmpchanlist = chanlist; allocs = eeg_mergelocs(ALLEEG.chanlocs); [tmp1 tmp2 neworder] = intersect_bc( {allocs.labels}, chanlist); [tmp1 ordertmp2] = sort(tmp2); neworder = neworder(ordertmp2); opts = { opts{:} 'interp' allocs(neworder) }; else newchanlist = []; tmpchanlocs = ALLEEG(idat(1)).chanlocs; chanlocs = { tmpchanlocs.labels }; for i=1:length(chanlist) newchanlist = [ newchanlist strmatch(chanlist{i}, chanlocs, 'exact') ]; end; tmpchanlocs = ALLEEG(idat(1)).chanlocs; tmpchanlist = { tmpchanlocs(newchanlist).labels }; end; % compute full file names % ----------------------- function res = computeFullFileName(filePaths, fileNames); for index = 1:length(fileNames) res{index} = fullfile(filePaths{index}, fileNames{index}); end;
github
ZijingMao/baselineeegtest-master
std_rebuilddesign.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_rebuilddesign.m
2,984
utf_8
09dbb018032fb646a0680536ac8e28a2
% std_rebuilddesign - reduild design structure when datasets have been % removed or added. % Usage: % STUDY = std_rebuilddesign(STUDY, ALLEEG); % STUDY = std_rebuilddesign(STUDY, ALLEEG, designind); % % Inputs: % STUDY - EEGLAB STUDY set % ALLEEG - vector of the EEG datasets included in the STUDY structure % % Optional inputs: % designind - [integer>0] indices (number) of the design to rebuild. % Default is all. % Ouput: % STUDY - updated EEGLAB STUDY set % % Author: Arnaud Delorme, Institute for Neural Computation UCSD, 2010- % Copyright (C) Arnaud Delorme, [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 STUDY = std_rebuilddesign(STUDY, ALLEEG, designind); if nargin < 2 help std_rebuilddesign; return; end; if nargin < 3 designind = 1:length(STUDY.design); end; [indvars indvarvals] = std_getindvar(STUDY); for indDesign = designind % find out if some independent variables or independent % variable values have been removed tmpdesign = STUDY.design(indDesign); indVar1 = strmatch(tmpdesign.variable(1).label, indvars, 'exact'); indVar2 = strmatch(tmpdesign.variable(2).label, indvars, 'exact'); if isempty(indVar1) tmpdesign.variable(1).label = ''; tmpdesign.variable(1).value = {}; else tmpdesign.variable(1).value = myintersect( tmpdesign.variable(1).value, indvarvals{indVar1} ); end; if isempty(indVar2) tmpdesign.variable(2).label = ''; tmpdesign.variable(2).value = {}; else tmpdesign.variable(2).value = myintersect( tmpdesign.variable(2).value, indvarvals{indVar2} ); end; STUDY = std_makedesign(STUDY, ALLEEG, indDesign, tmpdesign); end; STUDY = std_selectdesign(STUDY, ALLEEG, STUDY.currentdesign); % take the intersection for independent variables % ----------------------------------------------- function a = myintersect(a,b); if isempty(b) || isempty(a), a = {}; return; end; for index = 1:length(a) if isstr(a{index}) a(index) = intersect_bc(a(index), b); elseif iscell(a{index}) a{index} = intersect_bc(a{index}, b); elseif isnumeric(a{index}) a{index} = intersect_bc(a{index}, [ b{:} ]); end; end;
github
ZijingMao/baselineeegtest-master
pop_clustedit.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_clustedit.m
58,975
utf_8
bf0668415dcac6e239fdf4b53031d7a9
% pop_clustedit() - graphic user interface (GUI)-based function with editing and plotting % options for visualizing and manipulating an input STUDY structure. % Only component measures (e.g., dipole locations, scalp maps, spectra, % ERPs, ERSPs, ITCs) that have been computed and saved in the study EEG % datasets can be visualized. These can be computed during pre-clustering % using the GUI-based function pop_preclust() or the equivalent command % line functions std_preclust(). To use dipole locations for clustering, % they must first be stored in the EEG dataset structures using dipfit(). % Supported cluster editing functions include new cluster creation, cluster % merging, outlier rejection, and cluster renaming. Components can also be % moved from one cluster to another or to the outlier cluster. % Usage: % >> STUDY = pop_clustedit(STUDY, ALLEEG, clusters, addui, addgeom); % Inputs: % ALLEEG - Top-level EEGLAB vector of loaded EEG structures for the dataset(s) % in the STUDY. ALLEEG for a STUDY set is typically loaded using % pop_loadstudy(), or in creating a new STUDY, using pop_createstudy(). % STUDY - EEGLAB STUDY set comprising some or all of the EEG datasets in ALLEEG. % % Optional inputs: % clusters - [integer vector] of cluster numbers. These clusters will be visualized % and manipulated in the pop_clustedit() graphic interface. There are % restrictions on which clusters can be loaded together. The clusters must % either originate from the same clustering (same pre_clustering() and % subsequent pop_clust() execution), or they must all be leaf clusters % (i.e., clusters with no child clusters) {default: all leaf clusters}. % addui - [struct] additional uicontrols entries for the graphic % interface. Must contains the fiels "uilist", "geometry". % % Outputs: % STUDY - The input STUDY set structure modified according to specified user edits, % if any. Plotted cluster measure means (maps, ERSPs, etc.) are added to % the STUDY structure after they are first plotted to allow quick replotting. % % Graphic interface buttons: % "Select cluster to plot" - [list box] Displays available clusters to plot (format is % 'cluster name (number of components)'). The presented clusters depend % on the optional input variable 'clusters'. Selecting (clicking on) a % cluster from the list will display the selected cluster components in the % "Select component(s) to plot" list box. Use the plotting buttons below % to plot selected measures of the selected cluster. Additional editing % options (renaming the cluster, rejecting outliers, moving components to % another cluster) are also available. The option 'All N cluster centroids' % at the top of the list displays all the clusters in the list except the % 'Notcluster', 'Outlier' and 'ParentCluster' clusters. Selecting this option % will plot the cluster centroids (i.e. ERP, ERSP, ...) in a single figure. % "Select component(s) to plot" - [list box] Displays the ICA components of the currently % selected cluster (in the "Select cluster to plot" list box). Each component % has the format: 'subject name, component index'. Multiple components can be % selected from the list. Use the plotting buttons below to plot different % measures of the selected components on different figures. Selecting the % "All components" option is equivalent to using the cluster plotting buttons. % Additional editing options are reassigning the selected components to % another cluster or moving them to the outlier cluster. % "Plot Cluster properties" - [button] Displays in one figure all the mean cluster measures % (e.g., dipole locations, scalp maps, spectra, etc.) that were calculated % and saved in the EEG datsets. If there is more than one condition, the ERP % and the spectrum will have different colors for each condition. The ERSP % and ITC plots will show only the first condition; clicking on the subplot % will open a new figure with the different conditions displayed together. % Uses the command line function std_propplot(). % "Plot scalp maps" - [button] Displays the scalp maps of cluster components. % If applied to a cluster, scalp maps of the cluster components % are plotted along with the cluster mean scalp map in one figure. % If "All # cluster centroids" option is selected, all cluster scalp map % means are plotted in the same figure. If applied to components, displays % the scalp maps of the specified cluster components in separate figures. % Uses the command line functions std_topoplot(). % "Plot ERSPs" - [button] Displays the cluster component ERSPs. % If applied to a cluster, component ERSPs are plotted in one figure % (per condition) with the cluster mean ERSP. If "All # cluster centroids" % option is selected, plots all average ERSPs of the clusters in one figure % per condition. If applied to components, display the ERSP images of specified % cluster components in separate figures, using one figure for all conditions. % Uses the command line functions std_erspplot(). % "Plot ITCs" - [button] Same as "Plot ERSPs" but with ITC. % Uses the command line functions std_itcplot(). % "Plot dipoles" - [button] Displays the dipoles of the cluster components. % If applied to a cluster, plots the cluster component dipoles (in blue) % plus the average cluster dipole (in red). If "All # cluster centroids" option % is selected, all cluster plots are displayed in one figure each cluster in % a separate subplot. If applied to components, displays the ERSP images of the % specified cluster. For specific components displays components dipole (in blue) % plus the average cluster dipole (in Red) in separate figures. % Uses the command line functions std_dipplot(). % "Plot spectra" - [button] Displays the cluster component spectra. % If applied to a cluster, displays component spectra plus the average cluster % spectrum in bold. For a specific cluster, displays the cluster component % spectra plus the average cluster spectrum (in bold) in one figure per condition. % If the "All # cluster centroids" option is selected, displays the average % spectrum of all clusters in the same figure, with spectrum for different % conditions (if any) plotted in different colors. % If applied to components, displays the spectrum of specified cluster % components in separate figures using one figure for all conditions. % Uses the command line functions std_specplot(). % "Plot ERPs" - [button] Same as "Plot spectra" but for ERPs. % Uses the command line functions std_erpplot(). % "Plot ERPimage" - [button] Same as "Plot ERP" but for ERPimave. % Uses the command line functions std_erpimplot(). % "Create new cluster" - [button] Creates a new empty cluster. % Opens a popup window in which a name for the new cluster can be entered. % If no name is given the default name is 'Cls #', where '#' is the next % available cluster number. For changes to take place, press the popup % window 'OK' button, else press the 'Cancel' button. After the empty % cluster is created, components can be moved into it using, % 'Reassign selected component(s)' (see below). Uses the command line % function std_createclust(). % "Rename selected cluster" - [button] Renames a cluster using the selected (mnemonic) name. % Opens a popup window in which a new name for the selected cluster can be % entered. For changes to take place, press the popup window 'OK' button, % else press the 'Cancel' button. Uses the command line function std_renameclust(). % "Reject outlier components" - [button] rejects outlier components to an outlier cluster. % Opens a popup window to specify the outlier threshold. Move outlier % components that are more than x standard deviations devs from the % cluster centroid to an outlier cluster. For changes to take place, % press the popup window 'OK' button, else press the 'Cancel' button. % Uses the command line function std_rejectoutliers(). % "Merge clusters" - [button] Merges several clusters into one cluster. % Opens a popup window in which the clusters to merge may be specified % An optional name can be given to the merged cluster. If no name is given, % the default name is 'Cls #', where '#' is the next available cluster number. % For changes to take place, press the popup window 'OK' button, else press % the 'Cancel' button. Uses the command line function std_mergeclust(). % "Remove selected outlier component(s)" - [button] Moves selected component(s) to the % outlier cluster. The components that will be moved are the ones selected % in the "Select component(s) to plot" list box. Opens a popup window in which % a list of the selected component(s) is presented. For changes to take place, % press the popup window 'OK' button, else press the 'Cancel' button. % Uses the command line function std_moveoutlier(). % "Reassign selected component(s)" - [button] Moves selected component(s) from one cluster % to another. The components that will reassign are the ones selected in the % "Select component(s) to plot" list box. Opens a popup window in which % a list of possible clusters to which to move the selected component(s) is % presented. For changes to take place, press the popup window 'OK' button, % else press the 'Cancel' button. Uses the command line function std_movecomp(). % "Save STUDY set to disk" - [check box] Saves the STUDY set structure modified according % to specified user edits to the disk. If no file name is entered will % overwrite the current STUDY set file. % % See also: pop_preclust(), pop_clust(). % % Authors: Arnaud Delorme, Hilit Serby, Scott Makeig, SCCN/INC/UCSD, October 11, 2004 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, October 11, 2004, [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 % Coding notes: Useful information on functions and global variables used. function [STUDY, com] = pop_clustedit(varargin) icadefs; if nargin < 2 help pop_clustedit; return; end if ~isstr(varargin{1}) STUDY = varargin{1}; STUDY.etc.erpparams.topotime = NaN; % [] for channels and NaN for components STUDY.etc.specparams.topofreq = NaN; % NaN -> GUI disabled STUDY.etc.erspparams.topotime = NaN; STUDY.etc.erspparams.topofreq = NaN; STUDY.etc.erpimparams.topotime = NaN; STUDY.etc.erpimparams.topotrial = NaN; STUDY.tmphist = ''; ALLEEG = varargin{2}; clus_comps = 0; % the number of clustered components if nargin > 2 && ~isempty(varargin{3}) % load specific clusters cls = varargin{3}; %cluster numbers N = length(cls); %number of clusters % Check clusters are either from the same level (same parents) or are % all leaf clusters. % Check all input clusters have the same parent sameparent = 1; for k = 1: N % Assess the number of clustered components if (~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8)) & (~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)) clus_comps = clus_comps + length(STUDY.cluster(cls(k)).comps); end if k == 1 parent = STUDY.cluster(cls(k)).parent; else if isempty(parent) % if the first cluster was the parent cluster parent = STUDY.cluster(cls(k)).parent; end % For any other case verify that all clusters have the same parents if ~(sum(strcmp(STUDY.cluster(cls(k)).parent, parent)) == length(parent)) % different parent if ~strcmp(STUDY.cluster(cls(k)).parent,'manual') & ~strcmp(parent, 'manual') % if nither is an empty cluster (which was created manually) sameparent = 0; % then the clusters have different parents end end end end % If not same parent check if all leaf clusters % --------------------------------------------- if ~sameparent for k = 1: N %check if all leaves if ~isempty(STUDY.cluster(cls(k)).child) error([ 'pop_clustedit(): All clusters must be from the same level \n' ... ' (i.e., have the same parents or not be child clusters)' ]); end end end % ploting text etc ... % -------------------- num_cls = 0; for k = 1:N show_options{k+1} = [STUDY.cluster(cls(k)).name ' (' num2str(length(STUDY.cluster(cls(k)).comps)) ' ICs)']; if (~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8)) & (~strncmpi('Outliers',STUDY.cluster(cls(k)).name,8)) & ... (~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)) num_cls = num_cls + 1; end end show_options{1} = ['All ' num2str(num_cls) ' cluster centroids']; else % load leaf clusters sameparent = 1; cls = []; for k = 2:length(STUDY.cluster) if isempty(STUDY.cluster(k).child) if isempty(cls) parent = STUDY.cluster(k).parent; elseif ~isempty(STUDY.cluster(k).parent) | ~isempty(parent) % if not both empty % Check if all parents are the same if ~(sum(strcmp(STUDY.cluster(k).parent, parent)) == length(parent)) % different parent if ~strcmp(STUDY.cluster(k).parent,'manual') & ~strcmp(parent, 'manual') sameparent = 0; end end end cls = [ cls k]; if ~strncmpi('Notclust',STUDY.cluster(k).name,8) clus_comps = clus_comps + length(STUDY.cluster(k).comps); end end end % Plot clusters hierarchically % ---------------------------- num_cls = 0; cls = 1:length(STUDY.cluster); N = length(cls); %number of clusters show_options{1} = [STUDY.cluster(1).name ' (' num2str(length(STUDY.cluster(1).comps)) ' ICs)']; cls(1) = 1; count = 2; for index1 = 1:length(STUDY.cluster(1).child) indclust1 = strmatch( STUDY.cluster(1).child(index1), { STUDY.cluster.name }, 'exact'); show_options{count} = [' ' STUDY.cluster(indclust1).name ' (' num2str(length(STUDY.cluster(indclust1).comps)) ' ICs)']; cls(count) = indclust1; count = count+1; for index2 = 1:length( STUDY.cluster(indclust1).child ) indclust2 = strmatch( STUDY.cluster(indclust1).child(index2), { STUDY.cluster.name }, 'exact'); show_options{count} = [' ' STUDY.cluster(indclust2).name ' (' num2str(length(STUDY.cluster(indclust2).comps)) ' ICs)']; cls(count) = indclust2; count = count+1; for index3 = 1:length( STUDY.cluster(indclust2).child ) indclust3 = strmatch( STUDY.cluster(indclust2).child(index3), { STUDY.cluster.name }, 'exact'); show_options{count} = [' ' STUDY.cluster(indclust3).name ' (' num2str(length(STUDY.cluster(indclust3).comps)) ' ICs)']; cls(count) = indclust3; count = count+1; end; end; end; show_options = { ['All cluster centroids'] show_options{:} }; end all_comps = length(STUDY.cluster(1).comps); show_clust = [ 'pop_clustedit(''showclust'',gcf);']; show_comps = [ 'pop_clustedit(''showcomplist'',gcf);']; plot_clus_maps = [ 'pop_clustedit(''topoplot'',gcf); ']; plot_comp_maps = [ 'pop_clustedit(''plotcomptopo'',gcf); ']; plot_clus_ersps = ['pop_clustedit(''erspplot'',gcf); ']; plot_comp_ersps = ['pop_clustedit(''plotcompersp'',gcf); ']; plot_clus_itcs = ['pop_clustedit(''itcplot'',gcf); ']; plot_comp_itcs = ['pop_clustedit(''plotcompitc'',gcf); ']; plot_clus_erpim = ['pop_clustedit(''erpimageplot'',gcf); ']; plot_comp_erpim = ['pop_clustedit(''plotcomperpimage'',gcf); ']; plot_clus_spectra = ['pop_clustedit(''specplot'',gcf); ']; plot_comp_spectra = ['pop_clustedit(''plotcompspec'',gcf); ']; plot_clus_erp = ['pop_clustedit(''erpplot'',gcf); ']; plot_comp_erp = ['pop_clustedit(''plotcomperp'',gcf); ']; plot_clus_dip = ['pop_clustedit(''dipplot'',gcf); ']; plot_comp_dip = ['pop_clustedit(''plotcompdip'',gcf); ']; plot_clus_sum = ['pop_clustedit(''plotsum'',gcf); ']; plot_comp_sum = ['pop_clustedit(''plotcompsum'',gcf); ']; rename_clust = ['pop_clustedit(''renameclust'',gcf);']; move_comp = ['pop_clustedit(''movecomp'',gcf);']; move_outlier = ['pop_clustedit(''moveoutlier'',gcf);']; create_clus = ['pop_clustedit(''createclust'',gcf);']; reject_outliers = ['pop_clustedit(''rejectoutliers'',gcf);']; merge_clusters = ['pop_clustedit(''mergeclusters'',gcf);']; dip_opt = ['pop_clustedit(''dip_opt'',gcf);']; erp_opt = ['pop_clustedit(''erp_opt'',gcf);']; spec_opt = ['pop_clustedit(''spec_opt'',gcf);']; ersp_opt = ['pop_clustedit(''ersp_opt'',gcf);']; erpim_opt = ['pop_clustedit(''erpim_opt'',gcf);']; stat_opt = ['pop_clustedit(''stat_opt'',gcf);']; saveSTUDY = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''save''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ]; browsesave = [ '[filename, filepath] = uiputfile2(''*.study'', ''Save STUDY with .study extension -- pop_clust()''); ' ... 'set(findobj(''parent'', gcbf, ''tag'', ''studyfile''), ''string'', [filepath filename]);' ]; % Create default ERSP / ITC time/freq. paramters % ---------------------------------------------- if isempty(ALLEEG) error('STUDY contains no datasets'); end % enable buttons % -------------- filename = STUDY.design(STUDY.currentdesign).cell(1).filebase; if exist([filename '.icaspec']) , spec_enable = 'on'; else spec_enable = 'off'; end; if exist([filename '.icaerp'] ) , erp_enable = 'on'; else erp_enable = 'off'; end; if exist([filename '.icaerpim'] ), erpim_enable = 'on'; else erpim_enable = 'off'; end; if exist([filename '.icaersp']) , ersp_enable = 'on'; else ersp_enable = 'off'; end; filename = fullfile( ALLEEG(1).filepath, ALLEEG(1).filename(1:end-4)); if exist([filename '.icatopo']), scalp_enable = 'on'; else scalp_enable = 'off'; end; if isfield(ALLEEG(1).dipfit, 'model'), dip_enable = 'on'; else dip_enable = 'off'; end; % userdata below % -------------- fig_arg{1}{1} = ALLEEG; fig_arg{1}{2} = STUDY; fig_arg{1}{3} = cls; fig_arg{2} = N; str_name = sprintf('STUDY ''%s'' - ''%s'' component clusters', STUDY.name, STUDY.design(STUDY.currentdesign).name); if length(str_name) > 80, str_name = [ str_name(1:80) '...''' ]; end; if length(cls) > 1, vallist = 1; else vallist = 2; end; geomline = [1 0.35 1]; geometry = { [4 .1 .1 .1 .1] [1] geomline geomline geomline geomline geomline geomline geomline geomline ... geomline geomline [1] geomline geomline geomline }; geomvert = [ 1 .5 1 3 1 1 1 1 1 1 1 1 1 1 1 1]; uilist = { ... {'style' 'text' 'string' str_name ... 'FontWeight' 'Bold' 'HorizontalAlignment' 'center'} {} {} {} {} {} ... {'style' 'text' 'string' 'Select cluster to plot' 'FontWeight' 'Bold' } {} ... {'style' 'text' 'string' 'Select component(s) to plot ' 'FontWeight' 'Bold'} ... {'style' 'listbox' 'string' show_options 'value' vallist 'tag' 'clus_list' 'Callback' show_clust } ... {'style' 'pushbutton' 'enable' 'on' 'string' 'STATS' 'Callback' stat_opt } ... {'style' 'listbox' 'string' '' 'tag' 'clust_comp' 'max' 2 'min' 1 'callback' show_comps } ... {'style' 'pushbutton' 'enable' scalp_enable 'string' 'Plot scalp maps' 'Callback' plot_clus_maps} {} ... {'style' 'pushbutton' 'enable' scalp_enable 'string' 'Plot scalp map(s)' 'Callback' plot_comp_maps}... {'style' 'pushbutton' 'enable' dip_enable 'string' 'Plot dipoles' 'Callback' plot_clus_dip} ... {'style' 'pushbutton' 'enable' erp_enable 'string' 'Params' 'Callback' dip_opt } ... {'style' 'pushbutton' 'enable' dip_enable 'string' 'Plot dipole(s)' 'Callback' plot_comp_dip}... {'style' 'pushbutton' 'enable' erp_enable 'string' 'Plot ERPs' 'Callback' plot_clus_erp} ... {'style' 'pushbutton' 'enable' erp_enable 'string' 'Params' 'Callback' erp_opt } ... {'style' 'pushbutton' 'enable' erp_enable 'string' 'Plot ERP(s)' 'Callback' plot_comp_erp} ... {'style' 'pushbutton' 'enable' spec_enable 'string' 'Plot spectra' 'Callback' plot_clus_spectra} ... {'style' 'pushbutton' 'enable' spec_enable 'string' 'Params' 'Callback' spec_opt } ... {'style' 'pushbutton' 'enable' spec_enable 'string' 'Plot spectra' 'Callback' plot_comp_spectra} ... {'style' 'pushbutton' 'enable' erpim_enable 'string' 'Plot ERPimage' 'Callback' plot_clus_erpim} ... {'style' 'pushbutton' 'enable' erpim_enable 'string' 'Params' 'Callback' erpim_opt } ... {'style' 'pushbutton' 'enable' erpim_enable 'string' 'Plot ERPimage(s)' 'Callback' plot_comp_erpim} ... {'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ERSPs' 'Callback' plot_clus_ersps} ... {'vertexpand' 2.1 'style' 'pushbutton' 'enable' ersp_enable 'string' 'Params' 'Callback' ersp_opt } ... {'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ERSP(s)' 'Callback' plot_comp_ersps} ... {'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ITCs' 'Callback' plot_clus_itcs} { } ... {'style' 'pushbutton' 'enable' ersp_enable 'string' 'Plot ITC(s)' 'Callback' plot_comp_itcs} ... {} {}... %{'style' 'pushbutton' 'string' 'Plot cluster properties' 'Callback' plot_clus_sum 'enable' 'off'} {} ... {'style' 'pushbutton' 'string' 'Plot component properties' 'Callback' plot_comp_sum 'enable' 'off'} ... % nima, was off {} ... {'style' 'pushbutton' 'string' 'Create new cluster' 'Callback' create_clus} {} ... {'style' 'pushbutton' 'string' 'Reassign selected component(s)' 'Callback' move_comp} ... {'style' 'pushbutton' 'string' 'Rename selected cluster' 'Callback' rename_clust } {} ... {'style' 'pushbutton' 'string' 'Remove selected outlier comps.' 'Callback' move_outlier} ... {'style' 'pushbutton' 'string' 'Merge clusters' 'Callback' merge_clusters 'enable' 'off' } {} ... {'style' 'pushbutton' 'string' 'Auto-reject outlier components' 'Callback' reject_outliers 'enable' 'off' } }; % additional UI given on the command line % --------------------------------------- if nargin > 3 addui = varargin{4}; if ~isfield(addui, 'uilist') error('Additional GUI definition (argument 4) requires the field "uilist"'); end; if ~isfield(addui, 'geometry') addui.geometry = mat2cell(ones(1,length(addui.uilist))); end; uilist = { uilist{:}, addui.uilist{:} }; geometry = { geometry{:} addui.geometry{:} }; geomvert = [ geomvert ones(1,length(addui.geometry)) ]; end; [out_param userdat] = inputgui( 'geometry' , geometry, 'uilist', uilist, ... 'helpcom', 'pophelp(''pop_clustoutput'')', ... 'title', 'View and edit current component clusters -- pop_clustedit()' , 'userdata', fig_arg, ... 'geomvert', geomvert, 'eval', show_clust ); if ~isempty(userdat) ALLEEG = userdat{1}{1}; STUDY = userdat{1}{2}; end % history % ------- com = STUDY.tmphist; STUDY = rmfield(STUDY, 'tmphist'); else hdl = varargin{2}; %figure handle userdat = get(varargin{2}, 'userdat'); ALLEEG = userdat{1}{1}; STUDY = userdat{1}{2}; cls = userdat{1}{3}; clus = get(findobj('parent', hdl, 'tag', 'clus_list'), 'value'); comp_ind = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'Value'); if clus == 1 & length(cls) == 1 warndlg2('No cluster', 'No cluster'); return; end; try switch varargin{1} case {'plotcomptopo', 'plotcompersp','plotcompitc','plotcompspec', 'plotcomperp', 'plotcompdip', 'plotcomperpimage'} plotting_option = varargin{1}; plotting_option = [ plotting_option(9:end) 'plot' ]; if (clus ~= 1 ) %specific cluster if comp_ind(1) ~= 1 % check that not all comps in cluster are requested subject = STUDY.datasetinfo( STUDY.cluster(cls(clus-1)).sets(1,comp_ind-1)).subject; a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''clusters'',' num2str(cls(clus-1)) ', ''comps'', ' num2str(comp_ind-1) ' );' ]; eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); else a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''clusters'',' num2str(cls(clus-1)) ', ''plotsubjects'', ''on'' );' ]; eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); end else comp_list = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'String'); comp_name = comp_list(comp_ind); for ci = 1:length(comp_name) num_comps = 0; tmp = strfind(comp_name{ci},''''); clust_name = comp_name{ci}(tmp(1)+1:tmp(end)-1); for k = 1:length(cls) if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('Outliers',STUDY.cluster(cls(k)).name,8) & ... (~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)) if strcmpi(STUDY.cluster(cls(k)).name, clust_name) cind = comp_ind(ci) - num_comps; % component index in the cluster subject = STUDY.datasetinfo( STUDY.cluster(cls(k)).sets(1,cind)).subject; a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''clusters'',' num2str(cls(k)) ', ''comps'',' num2str(cind) ' );' ]; eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); break; else num_comps = num_comps + length(STUDY.cluster(cls(k)).comps); end end end end end userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); case {'topoplot', 'erspplot', 'itcplot', 'specplot', 'erpplot', 'dipplot', 'erpimageplot' } plotting_option = varargin{1}; plotting_option = [ plotting_option(1:end-4) 'plot' ]; if (clus ~= 1 ) % specific cluster option if ~isempty(STUDY.cluster(cls(clus-1)).comps) a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''clusters'',' num2str(cls(clus-1)) ');' ]; eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); end else % all clusters % All clusters does not include 'Notclust' 'ParentCluster' and 'Outliers' clusters. tmpcls = []; for k = 1:length(cls) if ~strncmpi(STUDY.cluster(cls(k)).name,'Notclust',8) & ~strncmpi(STUDY.cluster(cls(k)).name,'Outliers',8) & ... (~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)) & ~isempty(STUDY.cluster(cls(k)).comps) tmpcls = [ tmpcls cls(k)]; end end a = ['STUDY = std_' plotting_option '(STUDY,ALLEEG,''clusters'',[' num2str(tmpcls) ']);' ]; %if strcmpi(plotting_option, 'dipplot'), a = [a(1:end-2) ',''mode'', ''together'');' ]; end; eval(a); STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); end userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); case 'dip_opt' % save the list of selected chaners [STUDY com] = pop_dipparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'erp_opt' % save the list of selected chaners [STUDY com] = pop_erpparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'stat_opt' % save the list of selected chaners [STUDY com] = pop_statparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'spec_opt' % save the list of selected channels [STUDY com] = pop_specparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'erpim_opt' % save the list of selected channels [STUDY com] = pop_erpimparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'ersp_opt' % save the list of selected channels [STUDY com] = pop_erspparams(STUDY); if ~isempty(com) STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, com); end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'showcomplist' % save the list of selected clusters clust = get(findobj('parent', hdl, 'tag', 'clus_list') , 'value'); comp = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'value'); N = userdat{2}; count = 1; if clust ~= 1 %specific cluster STUDY.cluster(cls(clust-1)).selected = comp; end; userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update information (STUDY) case 'showclust' cind = get(findobj('parent', hdl, 'tag', 'clus_list'), 'value'); N = userdat{2}; count = 1; selected = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'value'); if cind ~= 1 %specific cluster len = length(STUDY.cluster(cls(cind-1)).comps); compid = cell(len+1,1); compid{1} = 'All components'; % Convert from components numbering to the indexing form 'setXcomY' for l = 1:len % go over the components of the cluster if ~isnan(STUDY.cluster(cls(cind-1)).sets(1,l)) subject = STUDY.datasetinfo(STUDY.cluster(cls(cind-1)).sets(1,l)).subject; compid{l+1} = [ subject ' IC' num2str(STUDY.cluster(cls(cind-1)).comps(1,l)) ]; end end if isfield(STUDY.cluster, 'selected') if ~isempty(STUDY.cluster(cls(cind-1)).selected) selected = min(STUDY.cluster(cls(cind-1)).selected, 1+length(STUDY.cluster(cls(cind-1)).comps(1,:))); STUDY.cluster(cls(cind-1)).selected = selected; end; end; else % All clusters accept 'Notclust' and 'Outliers' count = 1; for k = 1: length(cls) if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('Outliers',STUDY.cluster(cls(k)).name,8) & ... (~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)) for l = 1: length(STUDY.cluster(cls(k)).comps) if ~isnan(STUDY.cluster(cls(k)).sets(1,l)) subject = STUDY.datasetinfo(STUDY.cluster(cls(k)).sets(1,l)).subject; % This line chokes on NaNs. TF 2007.05.31 compid{count} = [ '''' STUDY.cluster(cls(k)).name ''' comp. ' ... num2str(l) ' (' subject ' IC' num2str(STUDY.cluster(cls(k)).comps(l)) ')']; count = count +1; end end end end end if selected > length(compid), selected = 1; end; set(findobj('parent', hdl, 'tag', 'clust_comp'), 'value', selected, 'String', compid); case 'plotsum' if clus ~= 1 % specific cluster option [STUDY] = std_propplot(STUDY, ALLEEG, 'cluster', cls(clus-1)); % update Study history a = ['STUDY = std_propplot(STUDY, ALLEEG, ''cluster'', ' num2str(cls(clus-1)) ' );' ]; STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); else % all clusters % All clusters does not include 'Notclust' and 'Outliers' clusters. tmpcls = []; for k = 1:length(cls) if ~strncmpi(STUDY.cluster(cls(k)).name,'Notclust',8) & ~strncmpi(STUDY.cluster(cls(k)).name,'Outliers',8) & ... (~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)) tmpcls = [tmpcls cls(k)]; end end [STUDY] = std_propplot(STUDY, ALLEEG, 'cluster', tmpcls); % update Study history a = ['STUDY = std_propplot(STUDY, ALLEEG, ''cluster'', [' num2str(tmpcls) '] );' ]; STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); end userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); case 'plotcompsum' for ci = 1 : length(comp_ind) % place holder for component properties % nima end case 'renameclust' STUDY.saved = 'no'; clus_name_list = get(findobj('parent', hdl, 'tag', 'clus_list'), 'String'); clus_num = get(findobj('parent', hdl, 'tag', 'clus_list'), 'Value') -1; if clus_num == 0 % 'all clusters' option return; end % Don't rename 'Notclust' and 'Outliers' clusters. if strncmpi('Notclust',STUDY.cluster(cls(clus_num)).name,8) | strncmpi('Outliers',STUDY.cluster(cls(clus_num)).name,8) | ... strncmpi('ParentCluster',STUDY.cluster(cls(clus_num)).name,13) warndlg2('The ParentCluster, Outliers, and Notclust clusters cannot be renamed'); return; end old_name = STUDY.cluster(cls(clus_num)).name; rename_param = inputgui( { [1] [1] [1]}, ... { {'style' 'text' 'string' ['Rename ' old_name] 'FontWeight' 'Bold'} {'style' 'edit' 'string' '' 'tag' 'clus_rename' } {} }, ... '', 'Rename cluster - from pop_clustedit()' ); if ~isempty(rename_param) %if not canceled new_name = rename_param{1}; STUDY = std_renameclust(STUDY, ALLEEG, cls(clus_num), new_name); % update Study history a = ['STUDY = std_renameclust(STUDY, ALLEEG, ' num2str(cls(clus_num)) ', ' STUDY.cluster(cls(clus_num)).name ');']; STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); new_name = [ STUDY.cluster(cls(clus_num)).name ' (' num2str(length(STUDY.cluster(cls(clus_num)).comps)) ' ICs)']; clus_name_list{clus_num+1} = renameclust( clus_name_list{clus_num+1}, new_name); set(findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_name_list); set(findobj('parent', hdl, 'tag', 'clus_rename'), 'String', ''); userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); %update STUDY end case 'movecomp' STUDY.saved = 'no'; old_clus = get(findobj('parent', hdl, 'tag', 'clus_list'), 'value') -1; comp_ind = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'Value'); if old_clus == 0 % 'all clusters' option return; end % Don't reassign components of 'Notclust' or the 'ParentCluster'. if strncmpi('ParentCluster',STUDY.cluster(cls(old_clus)).name,13) warndlg2('Cannot reassign components of ''ParentCluster''.'); return; end old_name = STUDY.cluster(cls(old_clus)).name; ncomp = length(comp_ind); % number of selected components optionalcls =[]; for k = 1:length(cls) if (~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13)) & (k~= old_clus) optionalcls = [optionalcls cls(k)]; end end reassign_param = inputgui( { [1] [1] [1]}, ... { {'style' 'text' 'string' strvcat(['Reassign ' fastif(ncomp >1, [num2str(length(comp_ind)) ' currently selected components'], ... 'currently selected component') ], ... [' from ' old_name ' to the cluster selected below']) 'FontWeight' 'Bold'} ... {'style' 'listbox' 'string' {STUDY.cluster(optionalcls).name} 'tag' 'new_clus'} {} }, ... '', 'Reassign cluster - from pop_clustedit()' ,[] , 'normal', [2 3 1] ); if ~isempty(reassign_param) %if not canceled new_clus = reassign_param{1}; comp_to_disp = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'String'); if strcmp(comp_to_disp{comp_ind(1)},'All components') warndlg2('Cannot move all the components of the cluster - abort move components', 'Aborting move components'); return; end STUDY = std_movecomp(STUDY, ALLEEG, cls(old_clus), optionalcls(new_clus), comp_ind - 1); % update Study history a = ['STUDY = std_movecomp(STUDY, ALLEEG, ' num2str(cls(old_clus)) ', ' num2str(optionalcls(new_clus)) ', [' num2str(comp_ind - 1) ']);']; STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); newind = find(cls == optionalcls(new_clus)); % update GUI % ---------- clus_name_list = get(findobj('parent', hdl, 'tag', 'clus_list'), 'String'); newname = [STUDY.cluster(optionalcls(new_clus)).name ' (' num2str(length(STUDY.cluster(optionalcls(new_clus)).comps)) ' ICs)']; clus_name_list{newind+1} = renameclust( clus_name_list{newind+1}, newname); newname = [STUDY.cluster(cls(old_clus)).name ' (' num2str(length(STUDY.cluster(cls(old_clus)).comps)) ' ICs)']; clus_name_list{old_clus+1} = renameclust( clus_name_list{old_clus+1}, newname); set( findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_name_list); userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); pop_clustedit('showclust',hdl); end case 'moveoutlier' STUDY.saved = 'no'; old_clus = get(findobj('parent', hdl, 'tag', 'clus_list'), 'value') -1; comp_ind = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'Value'); if ~isempty(find(comp_ind ==1)) warndlg2('Cannot remove all the cluster components'); return; end if old_clus == 0 % 'all clusters' option return; end if strncmpi('Notclust',STUDY.cluster(cls(old_clus)).name,8) | strncmpi('ParentCluster',STUDY.cluster(cls(old_clus)).name,13) % There are no outliers to 'Notclust' warndlg2('Cannot reassign components of ''Notclust'' or ''ParentCluster''.'); return; end comp_list = get(findobj('parent', hdl, 'tag', 'clust_comp'), 'String'); ncomp = length(comp_ind); old_name = STUDY.cluster(cls(old_clus)).name; if strncmpi('Outliers',STUDY.cluster(cls(old_clus)).name,8) % There are no outliers of 'Outliers' warndlg2('Cannot use ''Outliers'' clusters for this option.'); return; end reassign_param = inputgui( { [1] [1] [1]}, ... { {'style' 'text' 'string' ['Remove ' fastif(ncomp >1, [num2str(length(comp_ind)) ' currently selected components below '], 'currently selected component below ') ... 'from ' old_name ' to its outlier cluster?'] 'FontWeight' 'Bold'} ... {'style' 'listbox' 'string' {comp_list{comp_ind}} 'tag' 'new_clus'} {} }, ... '', 'Remove outliers - from pop_clustedit()' ,[] , 'normal', [1 3 1] ); if ~isempty(reassign_param) %if not canceled STUDY = std_moveoutlier(STUDY, ALLEEG, cls(old_clus), comp_ind - 1); clus_name_list = get(findobj('parent', hdl, 'tag', 'clus_list'), 'String'); outlier_clust = std_findoutlierclust(STUDY,cls(old_clus)); %find the outlier cluster for this cluster oind = find(cls == outlier_clust); % the outlier clust index (if already exist) in the cluster list GUI if ~isempty(oind) % the outlier clust is already presented in the cluster list GUI newname = [STUDY.cluster(outlier_clust).name ' (' num2str(length(STUDY.cluster(outlier_clust).comps)) ' ICs)']; clus_name_list{oind+1} = renameclust( clus_name_list{oind+1}, newname); elseif outlier_clust == length(STUDY.cluster) % update the list with the Outlier cluster (if didn't exist before) clus_name_list{end+1} = [STUDY.cluster(outlier_clust).name ' (' num2str(length(STUDY.cluster(outlier_clust).comps)) ' ICs)']; userdat{2} = userdat{2} + 1; % update N, number of clusters in edit window cls(end +1) = length(STUDY.cluster); % update the GUI clusters list with the outlier cluster userdat{1}{3} = cls; % update cls, the cluster indices in edit window end newname = [STUDY.cluster(cls(old_clus)).name ' (' num2str(length(STUDY.cluster(cls(old_clus)).comps)) ' ICs)']; clus_name_list{old_clus+1} = renameclust(clus_name_list{old_clus+1}, newname); set(findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_name_list); % update Study history a = ['STUDY = std_moveoutlier(STUDY, ALLEEG, ' num2str(cls(old_clus)) ', [' num2str(comp_ind - 1) ']);']; STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); pop_clustedit('showclust',hdl); end case 'rejectoutliers' STUDY.saved = 'no'; clus = get(findobj('parent', hdl, 'tag', 'clus_list'), 'Value') -1; if clus std_name = STUDY.cluster(cls(clus)).name; % Cannot reject outliers from 'Notclust', 'ParentCluster' and 'Outlier' clusters if strncmpi('Notclust',std_name,8) | strncmpi('ParentCluster', std_name,13) | ... strncmpi('Outliers',std_name,8) warndlg2('Cannot reject outliers of ''Notclust'' or ''Outliers'' or ''ParentCluster'' clusters.'); return; end clusters = cls(clus); else std_name = 'All clusters'; clusters = []; for k = 1:length(cls) if ~strncmpi('Notclust',STUDY.cluster(cls(k)).name,8) & ~strncmpi('Outliers',STUDY.cluster(cls(k)).name,8) & ... ~strncmpi('ParentCluster',STUDY.cluster(cls(k)).name,13) clusters = [ clusters cls(k)]; end end end reject_param = inputgui( { [1] [1] [4 1 2] [1]}, ... { {'style' 'text' 'string' ['Reject "' std_name '" outliers ' ] 'FontWeight' 'Bold'} {} ... {'style' 'text' 'string' 'Move outlier components that are more than'} {'style' 'edit' 'string' '3' 'tag' 'outliers_std' } ... {'style' 'text' 'string' 'standard deviations' } ... {'style' 'text' 'string' [ 'from the "' std_name '" centroid to an outlier cluster.']} }, ... '', 'Reject outliers - from pop_clustedit()' ); if ~isempty(reject_param) %if not canceled ostd = reject_param{1}; % the requested outlier std [STUDY] = std_rejectoutliers(STUDY, ALLEEG, clusters, str2num(ostd)); % update Study history a = ['STUDY = std_rejectoutliers(STUDY, ALLEEG, [ ' num2str(clusters) ' ], ' ostd ');']; STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); clus_name_list = get(findobj('parent', hdl, 'tag', 'clus_list'), 'String'); for k = 1:length(clusters) outlier_clust = std_findoutlierclust(STUDY,clusters(k)); %find the outlier cluster for this cluster oind = find(cls == outlier_clust); % the outlier clust index (if already exist) in the cluster list GUI if ~isempty(oind) % the outlier clust is already presented in the cluster list GUI newname = [STUDY.cluster(outlier_clust).name ' (' num2str(length(STUDY.cluster(outlier_clust).comps)) ' ICs)']; clus_name_list{oind+1} = renameclust( clus_name_list{oind+1}, newname); else % update the list with the outlier cluster clus_name_list{end+1} = [STUDY.cluster(outlier_clust).name ' (' num2str(length(STUDY.cluster(outlier_clust).comps)) ' ICs)']; userdat{2} = userdat{2} + 1; % update N, number of clusters in edit window cls(end +1) = outlier_clust; % update the GUI clusters list with the outlier cluster userdat{1}{3} = cls; % update cls, the cluster indices in edit window end clsind = find(cls == clusters(k)); newname = [STUDY.cluster(clusters(k)).name ' (' num2str(length(STUDY.cluster(clusters(k)).comps)) ' ICs)']; clus_name_list{clsind+1} = renameclust( clus_name_list{clsind+1}, newname); set(findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_name_list); end % If outlier cluster doesn't exist in the GUI window add it userdat{1}{2} = STUDY; set(hdl, 'userdat',userdat); pop_clustedit('showclust',hdl); end case 'createclust' STUDY.saved = 'no'; create_param = inputgui( { [1] [1 1] [1]}, ... { {'style' 'text' 'string' 'Create new empty cluster' 'FontWeight' 'Bold'} ... {'style' 'text' 'string' 'Enter cluster name:'} {'style' 'edit' 'string' '' } {} }, ... '', 'Create new empty cluster - from pop_clustedit()' ); if ~isempty(create_param) %if not canceled clus_name = create_param{1}; % the name of the new cluster [STUDY] = std_createclust(STUDY, ALLEEG, 'name', clus_name); % Update cluster list clus_name_list = get(findobj('parent', hdl, 'tag', 'clus_list'), 'String'); clus_name_list{end+1} = [STUDY.cluster(end).name ' (0 ICs)']; %update the cluster list with the new cluster % update the first option on the GUI list : 'All 10 cluster centroids' % with the new number of cluster centroids ti = strfind(clus_name_list{1},'cluster'); %get the number of clusters centroid cent = num2str(str2num(clus_name_list{1}(5:ti-2))+1); % new number of centroids clus_name_list{1} = [clus_name_list{1}(1:4) cent clus_name_list{1}(ti-1:end)]; %update list set(findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_name_list); % update Study history if isempty(clus_name) a = ['STUDY = std_createclust(STUDY, ALLEEG);']; else a = ['STUDY = std_createclust(STUDY, ALLEEG, ''name'', ' clus_name ');']; end STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); userdat{1}{2} = STUDY; userdat{2} = userdat{2} + 1; % update N, the number of cluster options in edit window cls(end +1) = length(STUDY.cluster); % update the GUI clusters list with the new cluster userdat{1}{3} = cls; % update cls, the cluster indices in edit window set(hdl, 'userdat',userdat); %update STUDY, cls and N end case 'mergeclusters' STUDY.saved = 'no'; clus_names = get(findobj('parent', hdl, 'tag', 'clus_list'), 'string') ; optionalcls =[]; for k = 2:length(clus_names) if (~strncmpi('Notclust',clus_names{k},8)) & (~strncmpi('Outliers',clus_names{k},8)) & ... (~strncmpi('ParentCluster',clus_names{k},13)) optionalcls = [optionalcls k]; end end reassign_param = inputgui( { [1] [1] [1] [2 1] [1]}, ... { {'style' 'text' 'string' 'Select clusters to Merge' 'FontWeight' 'Bold'} ... {'style' 'listbox' 'string' clus_names(optionalcls) 'tag' 'new_clus' 'max' 3 'min' 1} {} ... {'style' 'text' 'string' 'Optional, enter a name for the merged cluster:' 'FontWeight' 'Bold'} ... {'style' 'edit' 'string' ''} {} }, ... '', 'Merge clusters - from pop_clustedit()' ,[] , 'normal', [1 3 1 1 1] ); if ~isempty(reassign_param) std_mrg = cls(optionalcls(reassign_param{1})-1); name = reassign_param{2}; allleaves = 1; N = userdat{2}; for k = 1: N %check if all leaves if ~isempty(STUDY.cluster(cls(k)).child) allleaves = 0; end end [STUDY] = std_mergeclust(STUDY, ALLEEG, std_mrg, name); % % update Study history % if isempty(name) a = ['STUDY = std_mergeclust(STUDY, ALLEEG, [' num2str(std_mrg) ']);']; else a = ['STUDY = std_mergeclust(STUDY, ALLEEG, [' num2str(std_mrg) '], ' name ');']; end STUDY.tmphist = sprintf('%s\n%s', STUDY.tmphist, a); userdat{1}{2} = STUDY; % % Replace the merged clusters with the one new merged cluster % in the GUI if all clusters are leaves % if allleaves % % Update cluster list % clus_names{end+1} = [STUDY.cluster(end).name ' (' num2str(length(STUDY.cluster(end).comps)) ' ICs)']; % % update the cluster list with the new cluster % clus_names([optionalcls(reassign_param{1})]) = []; cls = setdiff_bc(cls, std_mrg); % remove from the GUI clusters list the merged clusters cls(end+1) = length(STUDY.cluster); % update the GUI clusters list with the new cluster N = length(cls); % % update the first option on the GUI list : 'All 10 cluster centroids' % with the new number of cluster centroids % ti = strfind(clus_names{1},'cluster'); %get the number of clusters centroid cent = num2str(str2num(clus_names{1}(5:ti-2))+1- length(std_mrg)); % new number of centroids clus_names{1} = [clus_names{1}(1:4) cent clus_names{1}(ti-1:end)]; %update list set(findobj('parent', hdl, 'tag', 'clus_list'), 'String', clus_names); % % update Study history % userdat{2} = N; % update N, the number of cluster options in edit window userdat{1}{3} = cls; % update cls, the cluster indices in edit window end set(hdl, 'userdat',userdat); %update information (STUDY) pop_clustedit('showclust',hdl); end end catch eeglab_error; end; end function newname = renameclust(oldname, newname); tmpname = deblank(oldname(end:-1:1)); strpos = strfind(oldname, tmpname(end:-1:1)); newname = [ oldname(1:strpos-1) newname ];
github
ZijingMao/baselineeegtest-master
std_findsameica.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_findsameica.m
2,100
utf_8
7c74914fce1976eb61bd77192f81f3d7
% std_findsameica() - find groups of datasets with identical ICA decomposiotions % % Usage: % >> clusters = std_findsameica(ALLEEG); % >> clusters = std_findsameica(ALLEEG,icathreshold); % Inputs: % ALLEEG - a vector of loaded EEG dataset structures of all sets in the STUDY set. % icathreshold - Threshold to compare icaweights % % Outputs: % cluster - cell array of groups of datasets % % Authors: Arnaud Delorme, SCCN, INC, UCSD, July 2009- % Copyright (C) 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 % Coding notes: Useful information on functions and global variables used. function cluster = std_findsameica(ALLEEG, varargin); % 6/2/2014 Ramon : Allow ica threshold as input. if nargin == 1 icathreshold = 2e-5; elseif nargin == 2; icathreshold = varargin{1}; end cluster = { [1] }; for index = 2:length(ALLEEG) found = 0; for c = 1:length(cluster) if all(size(ALLEEG(cluster{c}(1)).icaweights) == size(ALLEEG(index).icaweights)) %if isequal(ALLEEG(cluster{c}(1)).icaweights, ALLEEG(index).icaweights) if sum(sum(abs(ALLEEG(cluster{c}(1)).icaweights-ALLEEG(index).icaweights))) < icathreshold cluster{c}(end+1) = index; found = 1; break; end; end; end; if ~found cluster{end+1} = index; end; end;
github
ZijingMao/baselineeegtest-master
std_plotcurve.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_plotcurve.m
28,054
utf_8
4970bcc4787dd785a2c417f854ecdcdd
% std_plotcurve() - plot ERP or spectral traces for a STUDY component % or channel cluster % Usage: % >> std_plotcurve( axvals, data, 'key', 'val', ...) % Inputs: % axvals - [vector or cell array] axis values for the data. % data - [cell array] mean data for each subject group and/or data % condition. For example, to plot mean ERPs from a STUDY % for epochs of 800 frames in two conditions from three groups % of 12 subjects: % % >> data = { [800x12] [800x12] [800x12];... % 3 groups, cond 1 % [800x12] [800x12] [800x12] }; % 3 groups, cond 2 % >> std_plotcurve(erp_ms,data); % % By default, parametric statistics are computed across subjects % in the three groups. (group,condition) ERP averages are plotted. % See below and >> help statcond % for more information about the statistical computations. For % plotting multiple channels, use the second dimension. For % example data = { [800x64x12] [800x64x12] } for 12 subjects, % 64 channels and 800 data points. The 'chanlocs' option must be % used as well to specify channel positions. % % Optional display parameters: % 'datatype' - ['erp'|'spec'] data type {default: 'erp'} % 'titles' - [cell array of string] titles for each of the subplots. % { default: none} % % Statistics options: % 'groupstats' - [cell] One p-value array per group {default: {}} % 'condstats' - [cell] One p-value array per condition {default: {}} % 'interstats' - [cell] Interaction p-value arrays {default: {}} % 'threshold' - [NaN|real<<1] Significance threshold. NaN -> plot the % p-values themselves on a different figure. When possible, % significance regions are indicated below the data. % {default: NaN} % % Curve plotting options (ERP and spectrum): % 'plotgroups' - ['together'|'apart'] 'together' -> plot mean results % for subject groups in the same figure panel in different % colors. 'apart' -> plot group results on different figure % panels {default: 'apart'} % 'plotconditions' - ['together'|'apart'] 'together' -> plot mean results % for data conditions on the same figure panel in % different % colors. 'apart' -> plot conditions on different figure % panel. Note: 'plotgroups' and 'plotconditions' arguments % cannot both be 'together' {default: 'apart'} % 'legend' - ['on'|'off'] turn plot legend on/off {default: 'off'} % 'colors' - [cell] cell array of colors % 'plotdiff' - ['on'|'off'] plot difference between two groups % or conditions plotted together. % 'plotstderr' - ['on'|'off'|'diff'|'nocurve'|'diffnocurve'] plots in % a surface indicating the standard error. 'diff' only % does it for the difference (requires 'plotdiff' 'on' % above). 'nocurve' does not plot the mean. This functionality % does not work for all data configuration {default: 'off'} % 'figure' - ['on'|'off'] creates a new figure ('on'). The 'off' mode % plots all of the groups and conditions on the same pannel. % 'plotsubjects' - ['on'|'off'] overplot traces for individual components % or channels {default: 'off'} % 'singlesubject' - ['on'|'off'] set to 'on' to plot single subject. % {default: 'off'} % 'ylim' - [min max] ordinate limits for ERP and spectrum plots % {default: all available data} % % Scalp map plotting options: % 'chanlocs' - [struct] channel locations structure % % Author: Arnaud Delorme, CERCO, CNRS, 2006- % % See also: pop_erspparams(), pop_erpparams(), pop_specparams(), statcond() function std_plotcurve(allx, data, varargin) pgroup = []; pcond = []; pinter = []; if nargin < 2 help std_plotcurve; return; end; opt = finputcheck( varargin, { 'ylim' 'real' [] []; 'filter' 'real' [] []; 'threshold' 'real' [] NaN; 'unitx' 'string' [] 'ms'; 'chanlocs' 'struct' [] struct('labels', {}); 'plotsubjects' 'string' { 'on','off' } 'off'; 'condnames' 'cell' [] {}; % just for legends 'groupnames' 'cell' [] {}; % just for legends 'groupstats' 'cell' [] {}; 'condstats' 'cell' [] {}; 'interstats' 'cell' [] {}; 'titles' 'cell' [] {}; 'colors' 'cell' [] {}; 'figure' 'string' { 'on','off' } 'on'; 'plottopo' 'string' { 'on','off' } 'off'; 'plotstderr' 'string' { 'on','off','diff','nocurve' } 'off'; 'plotdiff' 'string' { 'on','off' } 'off'; 'legend' { 'string','cell' } { { 'on','off' } {} } 'off'; 'datatype' 'string' { 'ersp','itc','erp','spec' } 'erp'; 'plotgroups' 'string' { 'together','apart' } 'apart'; 'plotmode' 'string' { 'test','condensed' } 'test'; % deprecated 'plotconditions' 'string' { 'together','apart' } 'apart' }, 'std_plotcurve'); % opt.figure = 'off'; % test by nima if isstr(opt), error(opt); end; opt.singlesubject = 'off'; if length(opt.chanlocs) > 1, opt.plottopo = 'on'; end; if strcmpi(opt.plottopo, 'on') && size(data{1},3) == 1, opt.singlesubject = 'on'; end; %if size(data{1},2) == 1, opt.singlesubject = 'on'; end; if all(all(cellfun('size', data, 2)==1)) opt.singlesubject = 'on'; end; if any(any(cellfun('size', data, 2)==1)), opt.groupstats = {}; opt.condstats = {}; end; if strcmpi(opt.datatype, 'spec'), opt.unit = 'Hz'; end; if strcmpi(opt.plotsubjects, 'on') opt.plotgroups = 'apart'; opt.plotconditions = 'apart'; end; if strcmpi(opt.plotconditions, 'together') && ~isempty(opt.groupstats), opt.plotconditions = 'apart'; end; if strcmpi(opt.plotgroups, 'together') && ~isempty(opt.condstats) , opt.plotgroups = 'apart'; end; if isstr(opt.legend), opt.legend = {}; end; if isempty(opt.titles), opt.titles = cell(10,10); opt.titles(:) = { '' }; end; if length(data(:)) == length(opt.legend(:)), opt.legend = reshape(opt.legend, size(data))'; opt.legend(cellfun(@isempty, data)) = []; opt.legend = (opt.legend)'; end; % color matrix % ----------------------- onecol = { 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' }; manycol = { 'b' 'g' 'm' 'c' 'r' 'k' 'y' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' ... 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' }; modifier = { '-' '--' '-.' ':' '-' '--' '-.' ':' '-' '--' '-.' ':' }; if strcmpi(opt.plotgroups, 'together') || strcmpi(opt.plotconditions, 'together') || strcmpi(opt.figure, 'off') col = manycol; else col = onecol; end; if ~isempty(opt.colors), col = opt.colors; end; nonemptycell = find(~cellfun(@isempty, data)); maxdim = max(length(data(:)), size(data{nonemptycell(1)}, ndims(data{nonemptycell(1)}))); if strcmpi(opt.plotsubjects, 'off') % both group and conditions together if strcmpi(opt.plotconditions, 'together') && strcmpi(opt.plotgroups, 'together') dim1 = max(size(data)); dim2 = min(size(data)); coldata = col([1:dim1]); for iRow = 2:dim2 coldata(iRow,:) = coldata(1,:); for iCol = 1:dim1 coldata{iRow,iCol} = [ coldata{iRow,iCol} modifier{iRow} ]; end; end; if size(coldata,1) ~= size(data,1), coldata = coldata'; end; else coldata = manycol; end; %coldata = col(mod([0:maxdim-1], length(col))+1); %coldata = col(mod([0:maxdim-1], length(col))+1); %coldata = reshape(coldata(1:length(data(:))), size(data)); else coldata = cell(size(data)); end; % remove empty entries % -------------------- datapresent = ~cellfun(@isempty, data); if size(data,1) > 1, for c = size(data,1):-1:1, if sum(datapresent(c,:)) == 0, data(c,:) = []; coldata(c,:) = []; if ~strcmpi(opt.plotconditions, 'together') opt.titles(c,:) = []; end; if ~isempty(opt.groupstats), opt.groupstats(c) = []; end; end; end; end; if size(data,2) > 1, for g = size(data,2):-1:1, if sum(datapresent(:,g)) == 0, data(:,g) = []; coldata(:,g) = []; if ~strcmpi(opt.plotgroups , 'together') opt.titles(:,g) = []; end; if ~isempty(opt.condstats ), opt.condstats( g) = []; end; end; end; end; if strcmpi(opt.plotsubjects, 'off'), tmpcol = coldata'; tmpcol = tmpcol(:)'; end; % number of columns and rows to plot % ---------------------------------- nc = size(data,1); ng = size(data,2); if strcmpi(opt.plotgroups, 'together'), ngplot = 1; else ngplot = ng; end; if strcmpi(opt.plotconditions, 'together'), ncplot = 1; else ncplot = nc; end; if nc >= ng, opt.subplot = 'transpose'; else opt.subplot = 'normal'; end; if isempty(opt.condnames) for c=1:nc, opt.condnames{c} = sprintf('Cond. %d', c); end; if nc == 1, opt.condnames = { '' }; end; end; if isempty(opt.groupnames) for g=1:ng, opt.groupnames{g} = sprintf('Group. %d', g); end; if ng == 1, opt.groupnames = { '' }; end; end; % plotting paramters % ------------------ if ng > 1 && ~isempty(opt.groupstats), addc = 1; else addc = 0; end; if nc > 1 && ~isempty(opt.condstats ), addr = 1; else addr = 0; end; if length(opt.threshold) > 1, opt.threshold = opt.threshold(1); end; if strcmpi(opt.singlesubject, 'off') ... && ( ~isempty(opt.condstats) || ~isempty(opt.groupstats) ) % only for curves plottag = 0; if strcmpi(opt.plotgroups, 'together') && isempty(opt.condstats) && ~isempty(opt.groupstats) && ~isnan(opt.threshold), addc = 0; plottag = 1; end; if strcmpi(opt.plotconditions , 'together') && ~isempty(opt.condstats) && isempty(opt.groupstats) && ~isnan(opt.threshold), addr = 0; plottag = 1; end; if ~isnan(opt.threshold) && plottag == 0 && strcmpi(opt.figure, 'on') disp('Warning: cannot plot condition/group on the same panel while using a fixed'); disp(' threshold, unless you only compute statistics for ether groups or conditions'); opt.plotgroups = 'apart'; opt.plotconditions = 'apart'; end; end; % resize data to match points x channels x subjects % or points x 1 x components % ------------------------------------------------- for index = 1:length(data(:)) if length(opt.chanlocs) ~= size(data{index},2) && (length(opt.chanlocs) == 1 || isempty(opt.chanlocs)) data{index} = reshape(data{index}, [ size(data{index},1) 1 size(data{index},2) ]); end; end; % compute significance mask % -------------------------- if ~isempty(opt.interstats), pinter = opt.interstats{3}; end; if ~isnan(opt.threshold) && ( ~isempty(opt.groupstats) || ~isempty(opt.condstats) ) pcondplot = opt.condstats; pgroupplot = opt.groupstats; pinterplot = pinter; maxplot = 1; else for ind = 1:length(opt.condstats), pcondplot{ind} = -log10(opt.condstats{ind}); end; for ind = 1:length(opt.groupstats), pgroupplot{ind} = -log10(opt.groupstats{ind}); end; if ~isempty(pinter), pinterplot = -log10(pinter); end; maxplot = 3; end; % labels % ------ if strcmpi(opt.unitx, 'ms'), xlab = 'Time (ms)'; ylab = 'Potential (\muV)'; else xlab = 'Frequency (Hz)'; ylab = 'Power (10*log_{10}(\muV^{2}))'; end; if ~isnan(opt.threshold), statopt = { 'xlabel' xlab }; else statopt = { 'logpval' 'on' 'xlabel' xlab 'ylabel' '-log10(p)' 'ylim' [0 maxplot] }; end; % adjust figure size % ------------------ if strcmpi(opt.figure, 'on') figure('color', 'w'); pos = get(gcf, 'position'); basewinsize = 200/max(nc,ng)*3; if strcmpi(opt.plotgroups, 'together') pos(3) = 200*(1+addc); else pos(3) = 200*(ng+addc); end; if strcmpi(opt.plotconditions , 'together') pos(4) = 200*(1+addr); else pos(4) = 200*(nc+addr); end; if strcmpi(opt.subplot, 'transpose'), set(gcf, 'position', [ pos(1) pos(2) pos(4) pos(3)]); else set(gcf, 'position', pos); end; else opt.subplot = 'noplot'; end; tmplim = [Inf -Inf]; colcount = 1; % only when plotting all conditions on the same figure tmpcol = col; for c = 1:ncplot for g = 1:ngplot if strcmpi(opt.figure, 'off'), tmpcol(1) = []; end; % knock off colors if strcmpi(opt.plotgroups, 'together'), hdl(c,g)=mysubplot(ncplot+addr, ngplot+addc, 1 + (c-1)*(ngplot+addc), opt.subplot); ci = g; elseif strcmpi(opt.plotconditions, 'together'), hdl(c,g)=mysubplot(ncplot+addr, ngplot+addc, g, opt.subplot); ci = c; else hdl(c,g)=mysubplot(ncplot+addr, ngplot+addc, g + (c-1)*(ngplot+addc), opt.subplot); ci = 1; end; if ~isempty(data{c,g}) % read all data from one condition or group % ----------------------------------------- dimreduced_sizediffers = 0; if ncplot ~= nc && ngplot ~= ng maxdim = max(max(cellfun(@(x)(size(x, ndims(x))), data))); for cc = 1:size(data,1) for gg = 1:size(data,2) tmptmpdata = real(data{cc,gg}); if cc == 1 && gg == 1, tmpdata = NaN*zeros([size(tmptmpdata,1) size(tmptmpdata,2) maxdim length(data(:))]); end; tmpdata(:,:,1:size(tmptmpdata,3),gg+((cc-1)*ng)) = tmptmpdata; end; end; elseif ncplot ~= nc % plot conditions together for ind = 2:size(data,1), if any(size(data{ind,1}) ~= size(data{1})), dimreduced_sizediffers = 1; end; end; for cc = 1:nc tmptmpdata = real(data{cc,g}); if dimreduced_sizediffers tmptmpdata = nan_mean(tmptmpdata,ndims(tmptmpdata)); % average across last dim end; if cc == 1 && ndims(tmptmpdata) == 3, tmpdata = zeros([size(tmptmpdata) nc]); end; if cc == 1 && ndims(tmptmpdata) == 2, tmpdata = zeros([size(tmptmpdata) 1 nc]); end; tmpdata(:,:,:,cc) = tmptmpdata; end; elseif ngplot ~= ng % plot groups together for ind = 2:size(data,2), if any(size(data{1,ind}) ~= size(data{1})), dimreduced_sizediffers = 1; end; end; for gg = 1:ng tmptmpdata = real(data{c,gg}); if dimreduced_sizediffers tmptmpdata = nan_mean(tmptmpdata,ndims(tmptmpdata)); end; if gg == 1 && ndims(tmptmpdata) == 3, tmpdata = zeros([size(tmptmpdata) ng]); end; if gg == 1 && ndims(tmptmpdata) == 2, tmpdata = zeros([size(tmptmpdata) 1 ng]); end; tmpdata(:,:,:,gg) = tmptmpdata; end; else tmpdata = real(data{c,g}); end; % plot difference % --------------- if ~strcmpi(opt.plotdiff, 'off') if ngplot ~= ng || ncplot ~= nc if size(tmpdata,3) == 2 tmpdata(:,:,end+1) = tmpdata(:,:,2)-tmpdata(:,:,1); opt.legend{end+1} = [ opt.legend{2} '-' opt.legend{1} ]; elseif size(tmpdata,4) == 2 tmpdata(:,:,:,end+1) = tmpdata(:,:,:,2)-tmpdata(:,:,:,1); opt.legend{end+1} = [ opt.legend{2} '-' opt.legend{1} ]; else disp('Cannot plot difference, more than 2 indep. variable values'); end; else disp('Cannot plot difference, indep. variable value must be plotted together'); end; end; if ~isempty(opt.filter), tmpdata = myfilt(tmpdata, 1000/(allx(2)-allx(1)), 0, opt.filter); end; % plotting options % ---------------- plotopt = { allx }; % ------------------------------------------------------------- % tmpdata is of size "points x channels x subject x conditions" % or "points x 1 x components x conditions" % ------------------------------------------------------------- if ~dimreduced_sizediffers && strcmpi(opt.plotsubjects, 'off') % average accross subjects tmpstd = squeeze(real(std(tmpdata,[],3)))/sqrt(size(tmpdata,3)); tmpstd = squeeze(permute(tmpstd, [2 1 3])); tmpdata = squeeze(real(nan_mean(tmpdata,3))); end; tmpdata = squeeze(permute(tmpdata, [2 1 3 4])); % ----------------------------------------------------------------- % tmpdata is now of size "channels x points x subject x conditions" % ----------------------------------------------------------------- if strcmpi(opt.plottopo, 'on'), highlight = 'background'; else highlight = 'bottom'; end; if strcmpi(opt.plotgroups, 'together') && isempty(opt.condstats) && ... ~isnan(opt.threshold) && ~isempty(opt.groupstats) plotopt = { plotopt{:} 'maskarray' }; tmpdata = { tmpdata pgroupplot{c}' }; elseif strcmpi(opt.plotconditions, 'together') && isempty(opt.groupstats) && ... ~isnan(opt.threshold) && ~isempty(opt.condstats) plotopt = { plotopt{:} 'maskarray' }; tmpdata = { tmpdata pcondplot{g}' }; end; plotopt = { plotopt{:} 'highlightmode', highlight }; if strcmpi(opt.plotsubjects, 'on') plotopt = { plotopt{:} 'plotmean' 'on' 'plotindiv' 'on' }; else plotopt = { plotopt{:} 'plotmean' 'off' }; end; plotopt = { plotopt{:} 'ylim' opt.ylim 'xlabel' xlab 'ylabel' ylab }; if ncplot ~= nc || ngplot ~= ng plotopt = { plotopt{:} 'legend' opt.legend }; end; if strcmpi(opt.plottopo, 'on') && length(opt.chanlocs) > 1 metaplottopo(tmpdata, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ... 'plotargs', { plotopt{:} }, 'datapos', [2 3], 'title', opt.titles{c,g}); elseif iscell(tmpdata) plotcurve( allx, tmpdata{1}, 'colors', tmpcol, 'maskarray', tmpdata{2}, plotopt{3:end}, 'title', opt.titles{c,g}); else if isempty(findstr(opt.plotstderr, 'nocurve')) plotcurve( allx, tmpdata, 'colors', tmpcol, plotopt{2:end}, 'traceinfo', 'on', 'title', opt.titles{c,g}); end; if ~strcmpi(opt.plotstderr, 'off') if ~dimreduced_sizediffers if ~isempty(findstr(opt.plotstderr, 'diff')), begind = 3; else begind = 1; end; set(gcf, 'renderer', 'OpenGL') for tmpi = begind:size(tmpdata,1) hold on; chandle = fillcurves( allx, tmpdata(tmpi,:)-tmpstd(tmpi,:), tmpdata(tmpi,:)+tmpstd(tmpi,:), tmpcol{tmpi}); hold on; numfaces = size(get(chandle(1), 'Vertices'),1); set(chandle(1), 'FaceVertexCData', repmat([1 1 1], [numfaces 1]), 'Cdatamapping', 'direct', 'facealpha', 0.3, 'edgecolor', 'none'); end; else disp('Some conditions have more subjects than others, cannot plot standard error'); end; end; end; end; if strcmpi(opt.plottopo, 'off'), % only non-topographic xlim([allx(1) allx(end)]); hold on; if isempty(opt.ylim) tmp = ylim; tmplim = [ min(tmplim(1), tmp(1)) max(tmplim(2), tmp(2)) ]; else ylim(opt.ylim); end; end; % statistics accross groups % ------------------------- if g == ngplot && ng > 1 && ~isempty(opt.groupstats) if ~strcmpi(opt.plotgroups, 'together') || ~isempty(opt.condstats) || isnan(opt.threshold) if strcmpi(opt.plotgroups, 'together'), mysubplot(ncplot+addr, ngplot+addc, 2 + (c-1)*(ngplot+addc), opt.subplot); ci = g; elseif strcmpi(opt.plotconditions, 'together'), mysubplot(ncplot+addr, ngplot+addc, ngplot + 1, opt.subplot); ci = c; else mysubplot(ncplot+addr, ngplot+addc, ngplot + 1 + (c-1)*(ngplot+addc), opt.subplot); ci = 1; end; if strcmpi(opt.plotconditions, 'together'), condnames = 'Conditions'; else condnames = opt.condnames{c}; end; if ~isnan(opt.threshold) if strcmpi(opt.plottopo, 'on'), metaplottopo({zeros(size(pgroupplot{c}')) pgroupplot{c}'}, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ... 'plotargs', { allx 'maskarray' statopt{:} }, 'datapos', [2 3], 'title', opt.titles{c, g+1}); else plotcurve(allx, zeros(size(allx)), 'maskarray', mean(pgroupplot{c},2), 'ylim', [0.1 1], 'title', opt.titles{c, g+1}, statopt{:}); end; else if strcmpi(opt.plottopo, 'on'), metaplottopo(pgroupplot{c}', 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ... 'plotargs', { allx statopt{:} }, 'datapos', [2 3], 'title', opt.titles{c, g+1}); else plotcurve(allx, mean(pgroupplot{c},2), 'title', opt.titles{c, g+1}, statopt{:}); end; end; end; end; end; end; for g = 1:ng % statistics accross conditions % ----------------------------- if ~isempty(opt.condstats) && nc > 1 if ~strcmpi(opt.plotconditions, 'together') || ~isempty(opt.groupstats) || isnan(opt.threshold) if strcmpi(opt.plotgroups, 'together'), mysubplot(ncplot+addr, ngplot+addc, 1 + c*(ngplot+addc), opt.subplot); ci = g; elseif strcmpi(opt.plotconditions, 'together'), mysubplot(ncplot+addr, ngplot+addc, g + ngplot+addc, opt.subplot); ci = c; else mysubplot(ncplot+addr, ngplot+addc, g + c*(ngplot+addc), opt.subplot); ci = 1; end; if strcmpi(opt.plotgroups, 'together'), groupnames = 'Groups'; else groupnames = opt.groupnames{g}; end; if ~isnan(opt.threshold) if strcmpi(opt.plottopo, 'on'), metaplottopo({zeros(size(pcondplot{g}')) pcondplot{g}'}, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ... 'plotargs', { allx 'maskarray' statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, g}); else plotcurve(allx, zeros(size(allx)), 'maskarray', mean(pcondplot{g},2), 'ylim', [0.1 1], 'title', opt.titles{end, g}, statopt{:}); end; else if strcmpi(opt.plottopo, 'on'), metaplottopo(pcondplot{g}', 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ... 'plotargs', { allx statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, g}); else plotcurve(allx, mean(pcondplot{g},2), 'title', opt.titles{end, g}, statopt{:}); end; end; end; end; end; % statistics accross group and conditions % --------------------------------------- if ~isempty(opt.groupstats) && ~isempty(opt.condstats) && ng > 1 && nc > 1 mysubplot(ncplot+addr, ngplot+addc, ngplot + 1 + ncplot*(ngplot+addr), opt.subplot); if ~isnan(opt.threshold) if strcmpi(opt.plottopo, 'on'), metaplottopo({zeros(size(pinterplot')) pinterplot'}, 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ... 'plotargs', { allx 'maskarray' statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, end}); else plotcurve(allx, zeros(size(allx)), 'maskarray', mean(pinterplot,2), 'ylim', [0.1 1], 'title', opt.titles{end, end}, statopt{:}); xlabel(xlab); ylabel('-log10(p)'); end; else if strcmpi(opt.plottopo, 'on'), metaplottopo(pinterplot', 'chanlocs', opt.chanlocs, 'plotfunc', 'plotcurve', ... 'plotargs', { allx statopt{:} }, 'datapos', [2 3], 'title', opt.titles{end, end}); else plotcurve(allx, mean(pinterplot,2), 'title', opt.titles{end, end}, statopt{:}); end; end; end; % axis limit % ---------- for c = 1:ncplot for g = 1:ngplot if isempty(opt.ylim) && strcmpi(opt.plottopo, 'off') set(hdl(c,g), 'ylim', tmplim); end; end; end; if strcmpi(opt.plottopo, 'off') && length(hdl(:)) > 1 axcopy; % remove axis labels (for most but not all) % ------------------ if strcmpi(opt.subplot, 'transpose') for c = 1:size(hdl,2) for g = 1:size(hdl,1) axes(hdl(g,c)); if c ~= 1 && size(hdl,2) ~=1, xlabel(''); legend off; end; if g ~= 1 && size(hdl,1) ~= 1, ylabel(''); legend off; end; end; end; else for c = 1:size(hdl,1) for g = 1:size(hdl,2) axes(hdl(c,g)); if g ~= 1 && size(hdl,2) ~=1, ylabel(''); legend off; end; if c ~= size(hdl,1) && size(hdl,1) ~= 1, xlabel(''); legend off; end; end; end; end; end; % mysubplot (allow to transpose if necessary) % ------------------------------------------- function hdl = mysubplot(nr,nc,ind,subplottype); r = ceil(ind/nc); c = ind -(r-1)*nc; if strcmpi(subplottype, 'transpose'), hdl = subplot(nc,nr,(c-1)*nr+r); elseif strcmpi(subplottype, 'normal'), hdl = subplot(nr,nc,(r-1)*nc+c); elseif strcmpi(subplottype, 'noplot'), hdl = gca; else error('Unknown subplot type'); end; % rapid filtering for ERP % ----------------------- function tmpdata2 = myfilt(tmpdata, srate, lowpass, highpass); bscorrect = 1; if bscorrect % Getting initial baseline bs_val1 = mean(tmpdata,1); bs1 = repmat(bs_val1, size(tmpdata,1), 1); end % Filtering tmpdata2 = reshape(tmpdata, size(tmpdata,1), size(tmpdata,2)*size(tmpdata,3)*size(tmpdata,4)); tmpdata2 = eegfiltfft(tmpdata2',srate, lowpass, highpass)'; tmpdata2 = reshape(tmpdata2, size(tmpdata,1), size(tmpdata,2), size(tmpdata,3), size(tmpdata,4)); if bscorrect % Getting after-filter baseline bs_val2 = mean(tmpdata2,1); bs2 = repmat(bs_val2, size(tmpdata2,1), 1); % Correcting the baseline realbs = bs1-bs2; tmpdata2 = tmpdata2 + realbs; end
github
ZijingMao/baselineeegtest-master
std_movie.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_movie.m
5,749
utf_8
b76bc3cff273bfdc46ca097d380720fa
% std_topomovie - make movie in the frequency domain % % Usage: % >> [STUDY] = std_movie(STUDY, ALLEEG, key1, val1, key2, val2, ...); % % Inputs: % STUDY - STUDY structure comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - vector of EEG dataset structures for the dataset(s) in the STUDY, % typically created using load_ALLEEG(). % 'channels' - [numeric vector] specific channel group to plot. By % default, the grand mean channel spectrum is plotted (using the % same format as for the cluster component means described above) % 'moviemode' - ['erp'|'spec'|'ersptime'] movie mode. Currently only % 'spec' is implemented. % 'erspfreq' - [min max] frequency range when making movie of ERSP. The % ERSP values are averaged over the selected frequency % range. Not implemented % 'limitbeg' - [min max] limits at the beginning of the movie % 'limitend' - [min max] limits at the end of the movie % 'freqslim' - [freqs] array of landmark frequencies to set color % limits. % 'movieparams' - [low inc high] lower limit, higher limit and increment. If % increment is omited, movie is generate at every possible % increment (max freq resolution or max time resolution) % % Authors: Arnaud Delorme, CERCO, August, 2006 % % See also: std_specplot(), std_erppplot(), std_erspplot() % Copyright (C) Arnaud Delorme, [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 [STUDY, M] = std_movie(STUDY, ALLEEG, varargin); if nargin < 2 help std_specplot; return; end; [opt addparams ] = finputcheck( varargin, ... { 'erspfreq' 'real' [] []; 'movieparams' 'real' [] []; 'channels' 'cell' [] {}; 'freqslim' 'real' [] []; 'limitbeg' 'real' [] []; 'limitend' 'real' [] []; 'moviemode' 'string' { 'ersptime','erp','spec' } 'spec' }, 'std_movie', 'ignore'); if isstr(opt), error(opt); end; tmpchanlocs = ALLEEG(1).chanlocs; if isempty(opt.channels), opt.channels = { tmpchanlocs.labels }; end; if ~strcmpi(opt.moviemode, 'spec'), error('Only spec has been implemented so far'); end; % read data once % -------------- STUDY = std_specplot(STUDY, ALLEEG, 'channels', opt.channels, 'topofreq', [10 11]); close; % find first data channel with info % --------------------------------- for cind = 1:length(STUDY.changrp) if ~isempty(STUDY.changrp(cind).specdata), break; end; end; % generate movie % -------------- if isempty(opt.movieparams), opt.movieparams(1) = STUDY.changrp(cind).specfreqs(1); opt.movieparams(2) = STUDY.changrp(cind).specfreqs(end); end; if length(opt.movieparams) == 2 opt.movieparams(3) = opt.movieparams(2); opt.movieparams(2) = STUDY.changrp(cind).specfreqs(2)-STUDY.changrp(cind).specfreqs(1); end; if length(opt.movieparams) == 3 opt.movieparams = [opt.movieparams(1):opt.movieparams(2):opt.movieparams(3)]; end; % find limits % ----------- if isempty(opt.limitbeg) [STUDY specdata] = std_specplot(STUDY, ALLEEG, 'channels', opt.channels, 'topofreq', opt.movieparams(1)); close; opt.limitbeg = [ min(specdata{1}) max(specdata{1}) ]; [STUDY specdata] = std_specplot(STUDY, ALLEEG, 'channels', opt.channels, 'topofreq', opt.movieparams(end)); close; opt.limitend = [ min(specdata{1}) max(specdata{1}) ]; end; lowlims = linspace(opt.limitbeg(1), opt.limitend(1), length(opt.movieparams)); highlims = linspace(opt.limitbeg(2), opt.limitend(2), length(opt.movieparams)); % limits at specific frequencies % ------------------------------ if ~isempty(opt.freqslim) if opt.freqslim(1) ~= opt.movieparams(1) , opt.freqslim = [ opt.movieparams(1) opt.freqslim ]; end; if opt.freqslim(end) ~= opt.movieparams(end), opt.freqslim = [ opt.freqslim opt.movieparams(end) ]; end; for ind = 1:length(opt.freqslim) [tmp indf(ind)] = min(abs(opt.freqslim(ind) - opt.movieparams)); [STUDY specdata] = std_specplot(STUDY, ALLEEG, 'channels', opt.channels, 'topofreq', opt.movieparams(indf(ind))); close; minimum(ind) = min(specdata{1}); maximum(ind) = max(specdata{1}); end; indf(1) = 0; lowlims = [ ]; highlims = [ ]; for ind = 2:length(opt.freqslim) lowlims = [lowlims linspace(minimum(ind-1), minimum(ind), indf(ind)-indf(ind-1)) ]; highlims = [highlims linspace(maximum(ind-1), maximum(ind), indf(ind)-indf(ind-1)) ]; end; end; % make movie % ---------- for ind = 1:length(opt.movieparams) STUDY = std_specplot(STUDY, ALLEEG, 'channels', opt.channels, 'topofreq', opt.movieparams(ind), 'caxis', [lowlims(ind) highlims(ind)]); pos = get(gcf, 'position'); set(gcf, 'position', [pos(1) pos(2) pos(3)*2 pos(4)*2]); M(ind) = getframe(gcf); close; end; figure; axis off; movie(M);
github
ZijingMao/baselineeegtest-master
std_readfile.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readfile.m
15,609
utf_8
5f6b1005263321cdba24e80b92827d6c
% std_readfile() - Read data file containing STUDY measures. % % Usage: % >> [data param range1 range2] = std_readfile(filename, 'key', val); % % Inputs: % filename - [string] read specific file, for instance 's1.daterp' % containing ERP data for dataset "s1.set". It is also % possible to provide only the "base" file name "s1" and % function will load the appropriate file based on the % selected input measure (measure input). % % Optional inputs: % 'channels' - [cell or integer] channel labels - for instance % { 'cz' 'pz' } - or indices - for instance [1 2 3] % of channels to load from the data file. % 'components' - [integer] component index in the selected EEG dataset for which % to read the ERSP % 'timelimits' - [min max] ERSP time (latency in ms) range of interest % 'freqlimits' - [min max] ERSP frequency range (in Hz) of interest % 'measure' - ['erp'|'spec'|'ersp'|'itc'|'timef'|'erspbase'|'erspboot' % 'itcboot'|'erpim'] data measure to read. If a full file name % is provided, the data measure is selected automatically. % 'getparamsonly' - ['on'|'off'] only read file parameters not data. % % Outputs: % data - the multi-channel or multi-component data. The size of this % output depends on the number of dimension (for ERSP or ERP % for instance). The last dimension is channels or components. % params - structure containing parameters saved with the data file. % range1 - time points (ERP, ERSP) or frequency points (spectrum) % range2 - frequency points (ERSP, ITCs) % % Examples: % % the examples below read all data channels for the selected files % [ersp params times freqs] = std_readfiles('s1.datersp'); % [erp params times] = std_readfiles('s1.daterp'); % [erp params times] = std_readfiles('s1.daterp', timerange', [-100 500]); % % Authors: Arnaud Delorme, SCCN, INC, UCSD, May 2010 % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2010, [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 % dimensions % time x freqs x channel_comps x subjects_trials function [measureData, parameters, measureRange1, measureRange2, events, setinfoTrialIndices] = std_readfile(fileBaseName, varargin); if nargin < 1 help std_readfile; return; end; opt = finputcheck(varargin, { 'components' 'integer' [] []; 'getparamonly' 'string' { 'on','off' } 'off'; 'singletrials' 'string' { 'on','off' } 'off'; 'concatenate' 'string' { 'on','off' } 'off'; % ERPimage only 'channels' 'cell' [] {}; 'setinfoinds' 'integer' [] []; 'measure' 'string' { 'erpim','ersp','erspboot','erspbase','itc','itcboot','spec','erp','timef' } 'erp'; 'timelimits' 'real' [] []; % ERPimage, ERP, ERSP, ITC 'triallimits' 'real' [] []; % ERPimage only 'freqlimits' 'real' [] []; % SPEC, ERSP, ITC 'dataindices' 'integer' [] [] }, 'std_readdatafile'); if isstr(opt), error(opt); end; if ~isempty(opt.triallimits), opt.freqlimits = opt.triallimits; end; if strcmpi(opt.concatenate, 'on'), opt.singletrials = 'on'; end; if isstruct(fileBaseName), fileBaseName = { fileBaseName.filebase }; else fileBaseName = { fileBaseName }; end; if ~isempty(opt.channels) && length(opt.channels) < length(fileBaseName) opt.channels(2:length(fileBaseName)) = opt.channels(1); end; % get file extension % ------------------ if ~isempty(opt.channels) || (~isempty(opt.dataindices) && opt.dataindices(1) < 0) , dataType = 'chan'; else dataType = 'comp'; end; [tmp1 tmp2 currentFileExt] = fileparts(fileBaseName{1}); if length(currentFileExt) > 3 && (strcmpi(currentFileExt(2:4), 'dat') || strcmpi(currentFileExt(2:4), 'ica')) opt.measure = currentFileExt(5:end); if strcmpi(currentFileExt(2:4), 'dat'), dataType = 'chan'; else dataType = 'comp'; end; fileExt = ''; else if strcmpi(dataType, 'chan'), fileExt = [ '.dat' opt.measure ]; else fileExt = [ '.ica' opt.measure ]; end; end; if nargin > 5 && strcmpi(opt.singletrials, 'on') indFlag = true; else indFlag = false; end; % get fields to read % ------------------ erspFreqOnly = 0; switch opt.measure case 'erpim' , fieldExt = ''; case 'erp' , fieldExt = ''; case 'spec' , fieldExt = ''; case 'ersp' , fieldExt = '_ersp'; case 'itc' , fieldExt = '_itc'; case 'timef' , fieldExt = '_timef'; case 'erspbase', fieldExt = '_erspbase'; fileExt = fileExt(1:end-4); erspFreqOnly = 1; case 'erspboot', fieldExt = '_erspboot'; fileExt = fileExt(1:end-4); erspFreqOnly = 1; case 'itcboot' , fieldExt = '_itcboot'; fileExt = fileExt(1:end-4); erspFreqOnly = 1; end; % get channel or component indices % -------------------------------- if ~isempty(opt.channels) && isnumeric(opt.channels) opt.dataindices = opt.channels; elseif ~isempty(opt.channels) %if length(fileBaseName) > 1, error('Cannot read channel labels when reading more than 1 input file'); end; for iFile = 1:length(fileBaseName) filename = [ fileBaseName{iFile} fileExt ]; try, warning('off', 'MATLAB:load:variableNotFound'); fileData = load( '-mat', filename, 'labels', 'chanlabels' ); warning('on', 'MATLAB:load:variableNotFound'); catch, fileData = []; end; if isfield(fileData, 'labels'), chan.chanlocs = struct('labels', fileData.labels); elseif isfield(fileData, 'chanlabels') chan.chanlocs = struct('labels', fileData.chanlabels); else error('Cannot use file to lookup channel names, the file needs to be recomputed'); end; opt.dataindices(iFile) = std_chaninds(chan, opt.channels{iFile}); end; elseif ~isempty(opt.components) opt.dataindices = opt.components; else opt.dataindices = abs(opt.dataindices); end; % file names and indices must have the same number of values % ---------------------------------------------------------- if strcmpi(opt.getparamonly, 'on'), opt.dataindices = 1; end; if length(fileBaseName ) == 1, fileBaseName( 1:length(opt.dataindices)) = fileBaseName; end; if length(opt.dataindices) == 1, opt.dataindices(1:length(fileBaseName )) = opt.dataindices; end; if length(opt.dataindices) ~= length(fileBaseName) && ~isempty(opt.dataindices), error('Number of files and number of indices must be the same'); end; % scan datasets % ------------- measureRange1 = []; measureRange2 = []; measureData = []; parameters = []; events = {}; setinfoTrialIndices = []; % read only specific fields % ------------------------- counttrial = 0; for fInd = 1:length(opt.dataindices) % usually only one value fieldsToRead = [ dataType int2str(opt.dataindices(fInd)) fieldExt ]; try, warning('off', 'MATLAB:load:variableNotFound'); fileData = load( '-mat', [ fileBaseName{fInd} fileExt ], 'parameters', 'freqs', 'times', 'events', 'chanlocsforinterp', fieldsToRead ); warning('on', 'MATLAB:load:variableNotFound'); catch error( [ 'Cannot read file ''' fileBaseName{fInd} fileExt '''' ]); end; % get output for parameters and measure ranges % -------------------------------------------- if isfield(fileData, 'chanlocsforinterp'), chanlocsforinterp = fileData.chanlocsforinterp; end; if isfield(fileData, 'parameters') parameters = removedup(fileData.parameters); for index = 1:length(parameters), if iscell(parameters{index}), parameters{index} = { parameters{index} }; end; end; parameters = struct(parameters{:}); end; if isfield(fileData, 'times'), measureRange1 = fileData.times; end; if isfield(fileData, 'freqs'), measureRange2 = fileData.freqs; end; if isfield(fileData, 'events'), events{fInd} = fileData.events; end; % if the function is only called to get parameters % ------------------------------------------------ if strcmpi(opt.getparamonly, 'on'), measureRange1 = indicesselect(measureRange1, opt.timelimits); measureRange2 = indicesselect(measureRange2, opt.freqlimits); if strcmpi(opt.measure, 'spec'), measureRange1 = measureRange2; end; parameters.singletrials = 'off'; if strcmpi(opt.measure, 'timef') parameters.singletrials = 'on'; elseif strcmpi(opt.measure, 'erp') || strcmpi(opt.measure, 'spec') if strcmpi(dataType, 'chan') if size(fileData.chan1,1) > 1 && size(fileData.chan1,2) > 1 parameters.singletrials = 'on'; end; else if size(fileData.comp1,1) > 1 && size(fileData.comp1,2) > 1 parameters.singletrials = 'on'; end; end; end; return; end; % copy fields to output variables % ------------------------------- if isfield(fileData, fieldsToRead) fieldData = getfield(fileData, fieldsToRead); if isempty(fieldData) tmpSize = size(fieldData); tmpSize(tmpSize == 0) = 1; fieldData = ones(tmpSize)*NaN; end; if isstr(fieldData), eval( [ 'fieldData = ' fieldData ] ); end; % average single trials if necessary % ---------------------------------- if strcmpi(opt.measure, 'erp') || strcmpi(opt.measure, 'spec') if strcmpi(opt.singletrials, 'off') && size(fieldData,1) > 1 && size(fieldData,2) > 1 fieldData = mean(fieldData,2); end; end; % array reservation % ----------------- if fInd == 1 sizeFD = size(fieldData); if length(sizeFD) == 2 && (sizeFD(1) == 1 || sizeFD(2) == 1), sizeFD = sizeFD(1)*sizeFD(2); end; if length(sizeFD) == 2 && (sizeFD(1) == 0 || sizeFD(2) == 0), sizeFD = max(sizeFD(1)); end; if strcmpi(opt.singletrials, 'off'), measureData = zeros([ sizeFD length(opt.dataindices) ], 'single'); else measureData = zeros([ sizeFD ], 'single'); end; if indFlag, setinfoTrialIndices = zeros(1, size(measureData,ndims(measureData)), 'int16'); if length(opt.setinfoinds) ~= length(opt.dataindices) error('For single trial output, the "setinfoinds" parameter must be set'); end; end; nDimData = length(sizeFD); end; % copy data to output variable % ---------------------------- if nDimData == 1, measureData(:,fInd) = fieldData; else if strcmpi(opt.singletrials, 'off') if nDimData == 2, measureData(:,:,fInd) = fieldData; else measureData(:,:,:,fInd) = fieldData; end; else if nDimData == 2, measureData(:,counttrial+1:counttrial+size(fieldData,2)) = fieldData; else measureData(:,:,counttrial+1:counttrial+size(fieldData,2)) = fieldData; end; setinfoTrialIndices(counttrial+1:counttrial+size(fieldData,2)) = opt.setinfoinds(fInd); counttrial = counttrial+size(fieldData,2); end; end; elseif ~isempty(findstr('comp', fieldsToRead)) error( sprintf([ 'Field "%s" not found in file %s' 10 'Try recomputing measure.' ], fieldsToRead, [ fileBaseName{fInd} fileExt ])); else error(['Problem loading data, most likely your design has' 10 ... 'conditions with no trials or missing channels' 10 ... 'If you think this is a bug, report it on Bugzilla for EEGLAB' ]); % the case below is for the rare case where all the channels are read and the end of the array needs to be trimmed % error('There is a problem with your data, please enter a bug report and upload your data at http://sccn.ucsd.edu/eeglab/bugzilla'); if nDimData == 1, measureData(:,1:(fInd-1)) = []; elseif nDimData == 2, measureData(:,:,1:(fInd-1)) = []; else measureData(:,:,:,1:(fInd-1)) = []; end; break; end; end; % special ERP image % ----------------- if ~isempty(events) len = length(events{1}); events = [ events{:} ]; if strcmpi(opt.singletrials, 'off') && ~isempty(events), events = reshape(events, len, length(events)/len); end; end; % select plotting or clustering time/freq range % --------------------------------------------- if ~isempty(measureRange1) && ~erspFreqOnly [measureRange1 indBegin indEnd] = indicesselect(measureRange1, opt.timelimits); if ~isempty(measureData) if strcmpi(opt.measure, 'erp') || ( strcmpi(opt.measure, 'erpim') && strcmpi(opt.singletrials, 'on') ) measureData = measureData(indBegin:indEnd,:,:); else measureData = measureData(:,indBegin:indEnd,:); end; end; end; if isempty(measureRange2) && size(measureData,1) > 1 && size(measureData,2) > 1 % for ERPimage measureRange2 = [1:size(measureData,1)]; end; if ~isempty(measureRange2) [measureRange2 indBegin indEnd] = indicesselect(measureRange2, opt.freqlimits); if ~isempty(measureData) measureData = measureData(indBegin:indEnd,:,:); end; if strcmpi(opt.measure, 'spec'), measureRange1 = measureRange2; end; end; % remove duplicates in the list of parameters % ------------------------------------------- function cella = removedup(cella) [tmp indices] = unique_bc(cella(1:2:end)); if length(tmp) ~= length(cella)/2 %fprintf('Warning: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n'); end; cella = cella(sort(union(indices*2-1, indices*2))); % find indices for selection of measure % ------------------------------------- function [measureRange indBegin indEnd] = indicesselect(measureRange, measureLimits); indBegin = 1; indEnd = length(measureRange); if ~isempty(measureRange) && ~isempty(measureLimits) && (measureLimits(1) > measureRange(1) || measureLimits(end) < measureRange(end)) indBegin = min(find(measureRange >= measureLimits(1))); indEnd = max(find(measureRange <= measureLimits(end))); measureRange = measureRange(indBegin:indEnd); end;
github
ZijingMao/baselineeegtest-master
std_figtitle.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_figtitle.m
11,976
utf_8
8d0cdf735518b04d1c27c37441ecc076
% std_figtitle() - Generate plotting figure titles in a cell array % % Usage: % >> celltxt = std_figtitle(key1, val1, key2, val2); % % Inputs: % 'subject' - [string] Subject name % 'datatype' - [string] data type (For example 'erp') % 'chanlabels' - [cell array or string] channel names % 'compnames' - [cell array or string] component names % 'condnames' - [cell array] names of conditions % 'cond2names' - [cell array] names of conditions % 'vals' - [cell array or real array] value for plot panel (for % example, 0 ms) % 'valsunit' - [cell array or string] unit value (i.e. ms) % % Optional statistical titles: % 'condstat' - ['on'|'off'] default is 'off' % 'cond2stat' - ['on'|'off'] default is 'off' % 'mcorrect' - [string] correction for multiple comparisons. Default is % empty. % 'statistics' - [string] type of statictics % 'threshold' - [real] treshold value % % Optional grouping: % 'condgroup' - ['on'|'off'] group conditions together default is 'off' % 'cond2group' - ['on'|'off'] default is 'off' % % Outputs: % celltxt - cell array of text string, one for each set of condition % % Example: % std_figtitle('subject', 'toto', 'condnames', { 'test1' 'test2' }, ... % 'vals' , { [100] [4] }, 'valsunit', { 'ms' 'Hz' }) % % Authors: Arnaud Delorme, SCCN/UCSD, Feb 2010 % Copyright (C) Arnaud Delorme, [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 [all_titles alllegends ] = std_figtitle(varargin) if nargin < 1 help std_figtitle; return; end; alllegends = {}; opt = finputcheck( varargin, { 'chanlabels' {'cell','string'} [] {}; 'condnames' {'cell','string'} [] ''; 'cond2names' {'cell','string'} [] ''; 'condstat' 'string' {'on','off'} 'off'; 'cond2stat' 'string' {'on','off'} 'off'; 'condgroup' 'string' {'on','off','together','apart'} 'off'; 'cond2group' 'string' {'on','off','together','apart'} 'off'; 'plotmode' 'string' {'normal','condensed'} 'normal'; 'plotsubjects' 'string' {'on','off'} 'off'; 'threshold' 'real' [] NaN; 'statistics' 'string' [] ''; 'mcorrect' 'string' [] ''; 'datatype' 'string' [] ''; 'clustname' 'string' [] ''; 'compnames' {'cell','string'} [] {}; 'vals' {'cell','real'} [] {}; % just for titles 'valsunit' {'cell','string'} [] {}; % just for titles 'subject' 'string' [] '' }, 'std_figtitle'); %, 'ignore'); if isstr(opt), error(opt); end; if ~iscell(opt.vals), opt.vals = { opt.vals }; end; ncori = length(opt.condnames); nc2ori = length(opt.cond2names); if ~isempty(opt.vals) && ~isempty(opt.vals{1}) && ~isnan(opt.vals{1}(1)), opt.condgroup = 'off'; opt.cond2group = 'off'; end; if strcmpi(opt.plotmode, 'condensed'), opt.condgroup = 'on'; opt.cond2group = 'on'; end; if strcmpi(opt.plotsubjects, 'on'), opt.condgroup = 'off'; opt.cond2group = 'off'; end; if strcmpi(opt.plotsubjects, 'on') opt.condgroup = 'apart'; opt.cond2group = 'apart'; end; if strcmpi(opt.condgroup, 'on'), opt.condgroup = 'together'; end; if strcmpi(opt.cond2group, 'on'), opt.cond2group = 'together'; end; if strcmpi(opt.condgroup, 'together') && strcmpi(opt.cond2stat, 'on'), opt.condgroup = 'apart'; end; if strcmpi(opt.cond2group, 'together') && strcmpi(opt.condstat , 'on') , opt.cond2group = 'apart'; end; if ~( strcmpi(opt.condgroup, 'together') && strcmpi(opt.cond2group, 'together') ) if strcmpi(opt.condgroup, 'together'), alllegends = opt.condnames ; opt.condnames = ''; end; if strcmpi(opt.cond2group, 'together'), alllegends = opt.cond2names; opt.cond2names = ''; end; end; if ~iscell(opt.valsunit), opt.valsunit = { opt.valsunit }; end; if ~iscell(opt.chanlabels), opt.chanlabels = { opt.chanlabels }; end; if ~iscell(opt.condnames), opt.condnames = { opt.condnames }; end; if ~iscell(opt.cond2names), opt.cond2names = { opt.cond2names }; end; if isempty(opt.condnames), opt.condnames{1} = ''; end; if isempty(opt.cond2names), opt.cond2names{1} = ''; end; for c1 = 1:length(opt.condnames) for c2 = 1:length(opt.cond2names) % value (ms or Hz) % ---------------- fig_title1 = ''; for i = 1:length(opt.vals) if ~isempty(opt.vals{i}) && ~isnan(opt.vals{i}(1)) if opt.vals{i}(1) == opt.vals{i}(end), fig_title1 = [ num2str(opt.vals{i}(1)) '' opt.valsunit{i} fig_title1]; else fig_title1 = [ num2str(opt.vals{i}(1)) '-' num2str(opt.vals{i}(2)) '' opt.valsunit{i} fig_title1 ]; end; if length(opt.vals) > i, fig_title1 = [ ' & ' fig_title1 ]; end; end; end; % conditions % ---------- if ~isempty(opt.condnames{c1}) fig_title1 = [ value2str(opt.condnames{c1}) ', ' fig_title1]; end; if ~isempty(opt.cond2names{c2}) fig_title1 = [ value2str(opt.cond2names{c2}) ', ' fig_title1]; end; % channel labels, component name, subject name and datatype % --------------------------------------------------------- fig_title2 = ''; if length( opt.chanlabels ) == 1 && ~isempty( opt.chanlabels{1} ) fig_title2 = [ opt.chanlabels{1} ', ' fig_title2 ]; end; % cluster and component name % -------------------------- if ~isempty( opt.clustname ) if ~isempty( opt.compnames ) if iscell( opt.compnames ) compstr = [ 'C' num2str(opt.compnames{min(c1,size(opt.compnames,1)),min(c2,size(opt.compnames,2))}) ]; else compstr = [ opt.compnames ]; end; else compstr = ''; end; if ~isempty( opt.subject ) if ~isempty( compstr ) fig_title2 = [ opt.subject '/' compstr ', ' fig_title2 ]; else fig_title2 = [ opt.subject ', ' fig_title2 ]; end; elseif ~isempty( compstr ) fig_title2 = [ compstr ', ' fig_title2 ]; end; if ~isempty( opt.datatype ) fig_title2 = [ opt.clustname ' ' opt.datatype ', ' fig_title2 ]; else fig_title2 = [ opt.clustname ', ' fig_title2 ]; end; else if ~isempty( opt.compnames ) if iscell( opt.compnames ) else fig_title2 = [ 'C' num2str(opt.compnames{c1,c2}) ', ' fig_title2 ]; fig_title2 = [ opt.compnames ', ' fig_title2 ]; end; end; % subject and data type % --------------------- if ~isempty( opt.subject ) if ~isempty( opt.datatype ) fig_title2 = [ opt.subject ' ' opt.datatype ', ' fig_title2 ]; else fig_title2 = [ opt.subject ', ' fig_title2 ]; end; elseif ~isempty( opt.datatype ) fig_title2 = [ opt.datatype ' - ' fig_title2 ]; end; end; if strcmpi(opt.cond2group, 'together') && strcmpi(opt.condgroup, 'together') fig_title = fig_title2; if ~isempty(fig_title1) && length(fig_title1) > 1 && strcmpi(fig_title1(end-1:end), ', '), fig_title1(end-1:end) = []; end; if ~isempty(fig_title1) && length(fig_title1) > 1 && strcmpi(fig_title1(end-1:end), '- '), fig_title1(end-1:end) = []; end; alllegends{c1, c2} = fig_title1; else fig_title = [ fig_title2 fig_title1 ]; end; if ~isempty(fig_title) && length(fig_title) > 1 && strcmpi(fig_title(end-1:end), ', '), fig_title(end-1:end) = []; end; if ~isempty(fig_title) && length(fig_title) > 1 && strcmpi(fig_title(end-1:end), '- '), fig_title(end-1:end) = []; end; all_titles{c1,c2} = fig_title; end; end; if ~isempty(alllegends) alllegends = alllegends'; alllegends = alllegends(:)'; % convert legends to string if necessary % -------------------------------------- for ileg = 1:length(alllegends), alllegends{ileg} = value2str(alllegends{ileg}); end; end; % statistic titles % ---------------- if isnan(opt.threshold), basicstat = '(p-value)'; else if length(opt.threshold) >= 1 basicstat = sprintf([ '(p<%.' thresh_pres(opt.threshold(1)) 'f)'], opt.threshold(1)); end; if length(opt.threshold) >= 2 basicstat = [ basicstat(1:end-1) sprintf([' red;p<%.' thresh_pres(opt.threshold(2)) 'f brown)'], opt.threshold(2)) ]; end; if length(opt.threshold) >= 3 basicstat = [ basicstat(1:end-1) sprintf([';\np<%.' thresh_pres(opt.threshold(3)) 'f black)' ], opt.threshold(3)) ]; end; end; if ~isempty(opt.statistics), basicstat = [ basicstat ' ' opt.statistics ]; end; if ~isempty(opt.mcorrect) && ~strcmpi(opt.mcorrect, 'none'), basicstat = [ basicstat ' with ' opt.mcorrect ]; end; if strcmpi(opt.condstat, 'on') rown = size(all_titles,1)+1; for c2 = 1:length(opt.cond2names) all_titles{rown, c2} = [ value2str(opt.cond2names{c2}) ' ' basicstat ]; end; end; if strcmpi(opt.cond2stat, 'on') coln = size(all_titles,2)+1; for c1 = 1:length(opt.condnames) all_titles{c1, coln} = [ value2str(opt.condnames{c1}) ' ' basicstat ]; end; end; if strcmpi(opt.condstat, 'on') && strcmpi(opt.cond2stat, 'on') all_titles{rown, coln} = [ 'Interaction ' basicstat ]; end; function pres = thresh_pres(thresh_pres); if (round(thresh_pres*100)-thresh_pres*100) == 0 pres = 2; elseif (round(thresh_pres*1000)-thresh_pres*1000) == 0 pres = 3; else pres = -round(log10(thresh_pres))+1; end; pres = num2str(pres); % convert % ------- function str = value2str(value) if isstr(value) str = value; elseif isnumeric(value) if length(value) == 1 str = num2str(value); else str = num2str(value(1)); if length(value) <= 5 for ind = 2:length(value) str = [ str ' & ' num2str(value(ind)) ]; end; else str = [ str ' & ' num2str(value(2)) ' & ...' ]; end; end; else % cell array str = value{1}; for ind = 2:length(value) str = [ str ' & ' value{ind} ]; end; end;
github
ZijingMao/baselineeegtest-master
std_chantopo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_chantopo.m
9,652
utf_8
28bf5cd485d8031d2b9e2dc3180c2738
% std_chantopo() - plot ERP/spectral/ERSP topoplot at a specific % latency/frequency. % Usage: % >> std_chantopo( data, 'key', 'val', ...) % Inputs: % data - [cell array] mean data for each subject group and/or data % condition. These arrays are usually returned by function % std_erspplot and std_erpplot. For example % % >> data = { [1x64x12] [1x64x12 }; % 2 groups of 12 subjects, 64 channels % >> std_chantopo(data, 'chanlocs', 'chanlocfile.txt'); % % Scalp map plotting option (mandatory): % 'chanlocs' - [struct] channel location structure % % Other scalp map plotting options: % 'chanlocs' - [struct] channel location structure % 'topoplotopt' - [cell] topoplot options. Default is { 'style', 'both', % 'shading', 'interp' }. See topoplot help for details. % 'ylim' - [min max] ordinate limits for ERP and spectrum plots % {default: all available data} % 'caxis' - [min max] same as above % % Optional display parameters: % 'datatype' - ['erp'|'spec'] data type {default: 'erp'} % 'titles' - [cell array of string] titles for each of the subplots. % { default: none} % 'subplotpos' - [addr addc posr posc] perform ploting in existing figure. % Add "addr" rows, "addc" columns and plot the scalp % topographies starting at position (posr,posc). % % Statistics options: % 'groupstats' - [cell] One p-value array per group {default: {}} % 'condstats' - [cell] One p-value array per condition {default: {}} % 'interstats' - [cell] Interaction p-value arrays {default: {}} % 'threshold' - [NaN|real<<1] Significance threshold. NaN -> plot the % p-values themselves on a different figure. When possible, % significance regions are indicated below the data. % {default: NaN} % 'binarypval' - ['on'|'off'] if a threshold is set, show only significant % channels as red dots. Default is 'off'. % % Author: Arnaud Delorme, CERCO, CNRS, 2006- % % See also: pop_erspparams(), pop_erpparams(), pop_specparams(), statcond() function std_chantopo(data, varargin) pgroup = []; pcond = []; pinter = []; if nargin < 2 help std_chantopo; return; end; opt = finputcheck( varargin, { 'ylim' 'real' [] []; 'titles' 'cell' [] cell(20,20); 'threshold' 'real' [] NaN; 'chanlocs' 'struct' [] struct('labels', {}); 'groupstats' 'cell' [] {}; 'condstats' 'cell' [] {}; 'interstats' 'cell' [] {}; 'subplotpos' 'integer' [] []; 'topoplotopt' 'cell' [] { 'style', 'both' }; 'binarypval' 'string' { 'on','off' } 'on'; 'datatype' 'string' { 'ersp','itc','erp','spec' } 'erp'; 'caxis' 'real' [] [] }, 'std_chantopo', 'ignore'); %, 'ignore'); if isstr(opt), error(opt); end; if ~isempty(opt.ylim), opt.caxis = opt.ylim; end; if isnan(opt.threshold), opt.binarypval = 'off'; end; if strcmpi(opt.binarypval, 'on'), opt.ptopoopt = { 'style' 'blank' }; else opt.ptopoopt = opt.topoplotopt; end; % remove empty entries datapresent = ~cellfun(@isempty, data); for c = size(data,1):-1:1, if sum(datapresent(c,:)) == 0, data(c,:) = []; opt.titles(c,:) = []; if ~isempty(opt.groupstats), opt.groupstats(c) = []; end; end; end; for g = size(data,2):-1:1, if sum(datapresent(:,g)) == 0, data(:,g) = []; opt.titles(:,g) = []; if ~isempty(opt.condstats ), opt.condstats( g) = []; end; end; end; nc = size(data,1); ng = size(data,2); if nc >= ng, opt.transpose = 'on'; else opt.transpose = 'off'; end; % plotting paramters % ------------------ if ng > 1 & ~isempty(opt.groupstats), addc = 1; else addc = 0; end; if nc > 1 & ~isempty(opt.condstats ), addr = 1; else addr = 0; end; if ~isempty(opt.subplotpos), if strcmpi(opt.transpose, 'on'), opt.subplotpos = opt.subplotpos([2 1 4 3]); end; addr = opt.subplotpos(1); addc = opt.subplotpos(2); posr = opt.subplotpos(4); posc = opt.subplotpos(3); else posr = 0; posc = 0; end; % compute significance mask % ------------------------- if ~isempty(opt.interstats), pinter = opt.interstats{3}; end; if ~isnan(opt.threshold(1)) && ( ~isempty(opt.groupstats) || ~isempty(opt.condstats) ) pcondplot = opt.condstats; pgroupplot = opt.groupstats; pinterplot = pinter; maxplot = 1; else for ind = 1:length(opt.condstats), pcondplot{ind} = -log10(opt.condstats{ind}); end; for ind = 1:length(opt.groupstats), pgroupplot{ind} = -log10(opt.groupstats{ind}); end; if ~isempty(pinter), pinterplot = -log10(pinter); end; maxplot = 3; end; % adjust figure size % ------------------ if isempty(opt.subplotpos) fig = figure('color', 'w'); pos = get(fig, 'position'); set(fig, 'position', [ pos(1)+15 pos(2)+15 pos(3)/2.5*(nc+addr), pos(4)/2*(ng+addc) ]); pos = get(fig, 'position'); if strcmpi(opt.transpose, 'off'), set(gcf, 'position', [ pos(1) pos(2) pos(4) pos(3)]); else set(gcf, 'position', pos); end; end % topoplot % -------- tmpc = [inf -inf]; for c = 1:nc for g = 1:ng hdl(c,g) = mysubplot(nc+addr, ng+addc, g + posr + (c-1+posc)*(ng+addc), opt.transpose); if ~isempty(data{c,g}) tmpplot = double(mean(data{c,g},3)); if ~all(isnan(tmpplot)) if ~isreal(tmpplot), error('This function cannot plot complex values'); end; topoplot( tmpplot, opt.chanlocs, opt.topoplotopt{:}); if isempty(opt.caxis) tmpc = [ min(min(tmpplot), tmpc(1)) max(max(tmpplot), tmpc(2)) ]; else caxis(opt.caxis); end; title(opt.titles{c,g}, 'interpreter', 'none'); else axis off; end; else axis off; end; % statistics accross groups % ------------------------- if g == ng & ng > 1 & ~isempty(opt.groupstats) hdl(c,g+1) = mysubplot(nc+addr, ng+addc, g + posr + 1 + (c-1+posc)*(ng+addc), opt.transpose); topoplot( pgroupplot{c}, opt.chanlocs, opt.ptopoopt{:}); title(opt.titles{c,g+1}); caxis([-maxplot maxplot]); end; end; end; % color scale % ----------- if isempty(opt.caxis) for c = 1:nc for g = 1:ng axes(hdl(c,g)); caxis(tmpc); end; end; end; for g = 1:ng % statistics accross conditions % ----------------------------- if ~isempty(opt.condstats) && nc > 1 hdl(nc+1,g) = mysubplot(nc+addr, ng+addc, g + posr + (c+posc)*(ng+addc), opt.transpose); topoplot( pcondplot{g}, opt.chanlocs, opt.ptopoopt{:}); title(opt.titles{nc+1,g}); caxis([-maxplot maxplot]); end; end; % statistics accross group and conditions % --------------------------------------- if ~isempty(opt.condstats) && ~isempty(opt.groupstats) && ng > 1 && nc > 1 hdl(nc+1,ng+1) = mysubplot(nc+addr, ng+addc, g + posr + 1 + (c+posc)*(ng+addc), opt.transpose); topoplot( pinterplot, opt.chanlocs, opt.ptopoopt{:}); title(opt.titles{nc+1,ng+1}); caxis([-maxplot maxplot]); end; % color bars % ---------- axes(hdl(nc,ng)); cbar_standard(opt.datatype, ng); if isnan(opt.threshold(1)) && (nc ~= size(hdl,1) || ng ~= size(hdl,2)) axes(hdl(end,end)); cbar_signif(ng, maxplot); end; % remove axis labels % ------------------ for c = 1:size(hdl,1) for g = 1:size(hdl,2) if g ~= 1 && size(hdl,2) ~=1, ylabel(''); end; if c ~= size(hdl,1) && size(hdl,1) ~= 1, xlabel(''); end; end; end; % colorbar for ERSP and scalp plot % -------------------------------- function cbar_standard(datatype, ng); pos = get(gca, 'position'); tmpc = caxis; fact = fastif(ng == 1, 40, 20); tmp = axes('position', [ pos(1)+pos(3)+pos(3)/fact pos(2) pos(3)/fact pos(4) ]); set(gca, 'unit', 'normalized'); if strcmpi(datatype, 'itc') cbar(tmp, 0, tmpc, 10); ylim([0.5 1]); else cbar(tmp, 0, tmpc, 5); end; % colorbar for significance % ------------------------- function cbar_signif(ng, maxplot); % Retrieving Defaults icadefs; pos = get(gca, 'position'); tmpc = caxis; fact = fastif(ng == 1, 40, 20); tmp = axes('position', [ pos(1)+pos(3)+pos(3)/fact pos(2) pos(3)/fact pos(4) ]); map = colormap(DEFAULT_COLORMAP); n = size(map,1); cols = [ceil(n/2):n]'; image([0 1],linspace(0,maxplot,length(cols)),[cols cols]); %cbar(tmp, 0, tmpc, 5); tick = linspace(0, maxplot, maxplot+1); set(gca, 'ytickmode', 'manual', 'YAxisLocation', 'right', 'xtick', [], ... 'ytick', tick, 'yticklabel', round(10.^-tick*1000)/1000); xlabel(''); colormap(DEFAULT_COLORMAP); % mysubplot (allow to transpose if necessary) % ------------------------------------------- function hdl = mysubplot(nr,nc,ind,transp); r = ceil(ind/nc); c = ind -(r-1)*nc; if strcmpi(transp, 'on'), hdl = subplot(nc,nr,(c-1)*nr+r); else hdl = subplot(nr,nc,(r-1)*nc+c); end;
github
ZijingMao/baselineeegtest-master
std_uniformfiles.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_uniformfiles.m
3,122
utf_8
4338ced427d77d85832ff2965d6735b9
% std_uniformfiles() - Check uniform channel distribution accross data files % % Usage: % >> boolval = std_uniformfiles(STUDY, ALLEEG); % % Inputs: % STUDY - EEGLAB STUDY % % Outputs: % boolval - [-1|0|1] 0 if non uniform, 1 if uniform, -1 if error % % Authors: Arnaud Delorme, SCCN/UCSD, CERCO/CNRS, 2010- % Copyright (C) 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 uniformlabels = std_uniformfiles( STUDY, ALLEEG ); if nargin < 2 help std_checkconsist; return; end; filetypes = { 'daterp' 'datspec' 'datersp' 'datitc' 'dattimef' }; % set channel interpolation mode % ------------------------------ uniformlabels = []; count = 1; selectedtypes = {}; for index = 1:length(filetypes) % scan datasets % ------------- [ tmpstruct compinds filepresent ] = std_fileinfo(ALLEEG, filetypes{index}); % check if the structures are equal % --------------------------------- if ~isempty(tmpstruct) if any(filepresent == 0) uniformlabels = -1; return; else firstval = tmpstruct(1).labels; uniformlabels(count) = length(firstval); for dat = 2:length(tmpstruct) tmpval = tmpstruct(dat).labels; if ~isequal(firstval, tmpval) uniformlabels(count) = 0; end; end; selectedtypes{count} = filetypes{index}; count = count+1; end; end; end; % check output % ------------ if any(uniformlabels == 0) if any(uniformlabels) == 1 disp('Warning: conflict between datafiles - all should have the same channel distribution'); for index = 1:length(selectedtypes) if uniformlabels(index) fprintf(' Data files with extention "%s" have interpolated channels\n', selectedtypes{index}); else fprintf(' Data files with extention "%s" have non-interpolated channels\n', selectedtypes{index}); end; end; uniformlabels = -1; else uniformlabels = 0; end; else if ~(length(unique(uniformlabels)) == 1) fprintf('Warning: Data files have different number of channel in each file\n'); for index = 1:length(selectedtypes) fprintf(' Data files with extention "%s" have %d channels\n', selectedtypes{index}, uniformlabels(index)); end; end; uniformlabels = 1; end;
github
ZijingMao/baselineeegtest-master
iseeglabdeployed.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/iseeglabdeployed.m
154
utf_8
cb8716ae372b37132bb2a58c54d09cd0
% iseeglabdeployed - true for EEGLAB compile version and false otherwise function val = iseeglabdeployed try val = isdeployed; catch val = 0; end
github
ZijingMao/baselineeegtest-master
eeg_getversion.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeg_getversion.m
1,551
utf_8
a6ee3614031195b8aaf40cfab1251520
% eeg_getversion() - obtain EEGLAB version number % % Usage: % >> vers = eeg_getversion; % >> [vers vnum] = eeg_getversion; % % Outputs: % vers = [string] EEGLAB version number % vnum = [float] numerical value for the version. For example 11.3.2.4b % is converted to 11.324 % % Authors: Arnaud Delorme, SCCN/INC/UCSD, 2010 % Copyright (C) 2010 Arnaud Delorme, 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 function [vers, versnum, releaseDate] = eeg_getversion; vers = ''; filepath = fileparts(which('eeglab.m')); filename = dir(fullfile(filepath, 'Contents.m')); releaseDate = filename.date; if isempty(filename), return; end; fid = fopen(fullfile(filepath, filename.name), 'r'); fgetl(fid); versionline = fgetl(fid); vers = versionline(11:end); fclose(fid); tmpvers = vers; if isempty(str2num(tmpvers(end))), tmpvers(end) = []; end; indsDot = find(tmpvers == '.' ); tmpvers(indsDot(2:end)) = []; versnum = str2num(tmpvers);
github
ZijingMao/baselineeegtest-master
gethelpvar.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/gethelpvar.m
9,432
utf_8
7d60bb94c02933e99c9a469f683938dc
% gethelpvar() - convert a Matlab m-file help-message header % into out variables % Usage: % >> [vartext, varnames] = gethelpvar( filein, varlist); % % Inputs: % filein - input filename (with .m extension) % varlist - optional list of variable to return. If absent % retrun all variables. % % Outputs: % vartext - variable text % varnames - name of the varialbe returned; % % Notes: see help2html() for file format % % Example: >> gethelpvar( 'gethelpvar.m', 'filein') % % Author: Arnaud Delorme, Salk Institute 20 April 2002 % % See also: help2html() % Copyright (C) 2001 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 [alltext, allvars] = gethelpvar( filename, varlist ) if nargin < 1 help gethelpvar; return; end; % input file % ---------- fid = fopen( filename, 'r'); if fid == -1 error('File not found'); end; cont = 1; % scan file % ----------- str = fgets( fid ); % if first line is the name of the function, reload if str(1) ~= '%', str = fgets( fid ); end; % state variables % ----------- maindescription = 1; varname = []; oldvarname = []; vartext = []; newvar = 0; allvars = {}; alltext = {}; indexout = 1; while (str(1) == '%') str = deblank(str(2:end-1)); % --- DECODING INPUT newvar = 0; str = deblank2(str); if ~isempty(str) % find a title % ------------ i2d = findstr(str, ':'); newtitle = 0; if ~isempty(i2d) i2d = i2d(1); switch lower(str(1:i2d)) case { 'usage:' 'authors:' 'author:' 'notes:' 'note:' 'input:' ... 'inputs:' 'outputs:' 'output' 'example:' 'examples:' 'see also:' }, newtitle = 1; end; if (i2d == length(str)) & (str(1) ~= '%'), newtitle = 1; end; end; if newtitle tilehtml = str(1:i2d); newtitle = 1; oldvarname = varname; oldvartext = vartext; if i2d < length(str) %vartext = formatstr(str(i2d+1:end), g.refcall); vartext = str(i2d+1:end); else vartext = []; end; varname = []; else % not a title % ------------ % scan lines [tok1 strrm] = strtok( str ); [tok2 strrm] = strtok( strrm ); if ~isempty(tok2) & ( isequal(tok2,'-') | isequal(tok2,'=')) % new variable newvar = 1; oldvarname = varname; oldvartext = vartext; varname = tok1; strrm = deblank(strrm); % remove tail blanks strrm = deblank(strrm(end:-1:1)); % remove initial blanks %strrm = formatstr( strrm(end:-1:1), g.refcall); strrm = strrm(end:-1:1); vartext = strrm; else % continue current text str = deblank(str); % remove tail blanks str = deblank(str(end:-1:1)); % remove initial blanks %str = formatstr( str(end:-1:1), g.refcall ); str = str(end:-1:1); if isempty(vartext) vartext = str; else if ~isempty(varname) vartext = [ vartext 10 str]; % espace if in array else if length(vartext)>3 & all(vartext( end-2:end) == '.') vartext = [ deblank2(vartext(1:end-3)) 10 str]; % espace if '...' else vartext = [ vartext 10 str]; % CR otherwise end; end; end; end; newtitle = 0; end; % --- END OF DECODING str = fgets( fid ); % test if last entry % ------------------ if str(1) ~= '%' if ~newtitle if ~isempty(oldvarname) allvars{indexout} = oldvarname; alltext{indexout} = oldvartext; indexout = indexout + 1; %fprintf( fo, [ '</tr>' g.normrow g.normcol1 g.var '</td>\n' ], oldvarname); %fprintf( fo, [ g.normcol2 g.vartext '</td></tr>\n' ], oldvartext); else if ~isempty(oldvartext) %fprintf( fo, [ g.normcol2 g.tabtext '</td></tr>\n' ], oldvartext); end; end; newvar = 1; oldvarname = varname; oldvartext = vartext; end; end; % test if new input for an array % ------------------------------ if newvar | newtitle if maindescription if ~isempty(oldvartext) % FUNCTION TITLE maintext = oldvartext; maindescription = 0; functioname = oldvarname( 1:findstr( oldvarname, '()' )-1); %fprintf( fo, [g.normrow g.normcol1 g.functionname '</td>\n'],upper(functioname)); %fprintf( fo, [g.normcol2 g.description '</td></tr>\n'], [ upper(oldvartext(1)) oldvartext(2:end) ]); % INSERT IMAGE IF PRESENT %imagename = [ htmlfile( 1:findstr( htmlfile, functioname )-1) functioname '.jpg' ]; %if exist( imagename ) % do not make link if the file does not exist %fprintf(fo, [ g.normrow g.doublecol ... % '<CENTER><BR><A HREF="' imagename '" target="_blank"><img SRC=' imagename ... % ' height=150 width=200></A></CENTER></td></tr>' ]); %end; end; elseif ~isempty(oldvarname) allvars{indexout} = oldvarname; alltext{indexout} = oldvartext; indexout = indexout + 1; %fprintf( fo, [ '</tr>' g.normrow g.normcol1 g.var '</td>\n' ], oldvarname); %fprintf( fo, [ g.normcol2 g.vartext '</td></tr>\n' ], oldvartext); else if ~isempty(oldvartext) %fprintf( fo, [ g.normcol2 g.text '</td></tr>\n' ], oldvartext); end; end; end; % print title % ----------- if newtitle %fprintf( fo, [ g.normrow g.doublecol '<BR></td></tr>' g.normrow g.normcol1 g.title '</td>\n' ], tilehtml); if str(1) ~= '%' % last input %fprintf( fo, [ g.normcol2 g.text '</td></tr>\n' ], vartext); end; oldvarname = []; oldvartext = []; end; else str = fgets( fid ); end; end; fclose( fid ); % remove quotes of variables % -------------------------- for index = 1:length(allvars) if allvars{index}(1) == '''', allvars{index} = eval( allvars{index} ); end; end; if exist('varlist') == 1 if ~iscell(varlist), varlist = { varlist }; end; newtxt = mat2cell(zeros(length(varlist), 1), length(varlist), 1); % preallocation for index = 1:length(varlist) loc = strmatch( varlist{index}, allvars); if ~isempty(loc) newtxt{index} = alltext{loc(1)}; else disp([ 'warning: variable ''' varlist{index} ''' not found']); newtxt{index} = ''; end; end; alltext = newtxt; end; return; % ----------------- % sub-functions % ----------------- function str = deblank2( str ); % deblank two ways str = deblank(str(end:-1:1)); % remove initial blanks str = deblank(str(end:-1:1)); % remove tail blanks return; function strout = formatstr( str, refcall ); [tok1 strrm] = strtok( str ); strout = []; while ~isempty(tok1) tokout = functionformat( tok1, refcall ); if isempty( strout) strout = tokout; else strout = [strout ' ' tokout ]; end; [tok1 strrm] = strtok( strrm ); end; return; function tokout = functionformat( tokin, refcall ); tokout = tokin; % default [test, realtokin, tail] = testfunc1( tokin ); if ~test, [test, realtokin, tail] = testfunc2( tokin ); end; if test i1 = findstr( refcall, '%s'); i2 = findstr( refcall(i1(1):end), ''''); if isempty(i2) i2 = length( refcall(i1(1):end) )+1; end; filename = [ realtokin refcall(i1+2:i1+i2-2)]; if exist( filename ) % do not make link if the file does not exist tokout = sprintf( [ '<A HREF="' refcall '">%s</A>' tail ' ' ], realtokin, realtokin ); end; end; return; function [test, realtokin, tail] = testfunc1( tokin ) % test if is string is 'function()[,]' test = 0; realtokin = ''; tail = ''; if ~isempty( findstr( tokin, '()' ) ) realtokin = tokin( 1:findstr( tokin, '()' )-1); if length(realtokin) < (length(tokin)-2) tail = tokin(end); else tail = []; end; test = 1; end; return; function [test, realtokin, tail] = testfunc2( tokin ) % test if is string is 'FUNCTION[,]' test = 0; realtokin = ''; tail = ''; if all( upper(tokin) == tokin) if tokin(end) == ',' realtokin = tokin(1:end-1); tail = ','; else realtokin = tokin; end; testokin = realtokin; testokin(findstr(testokin, '_')) = 'A'; testokin(findstr(testokin, '2')) = 'A'; if all(double(testokin) > 64) & all(double(testokin) < 91) test = 1; end; realtokin = lower(realtokin); end; return;
github
ZijingMao/baselineeegtest-master
eeg_retrieve.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeg_retrieve.m
2,820
utf_8
fc0ecd37ff8b71e41ef51d43a4aca461
% eeg_retrieve() - Retrieve an EEG dataset from the variable % containing all datasets (standard: ALLEEG). % % Usage: >> EEG = eeg_retrieve( ALLEEG, index ); % % Inputs: % ALLEEG - variable containing all datasets % index - index of the dataset to retrieve % % Outputs: % EEG - output dataset. The workspace variable EEG is also updated % ALLEEG - updated ALLEEG structure % CURRENTSET - workspace variable index of the current dataset % % Note: The function performs >> EEG = ALLEEG(index); % It also runs eeg_checkset() on it. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeg_store(), eeglab() % Copyright (C) 2001 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 [EEG, ALLEEG, CURRENTSET] = eeg_retrieve( ALLEEG, CURRENTSET); if nargin < 2 help eeg_retrieve; return; end; %try eeglab_options; try, % check whether recent changes to this dataset have been saved or not %-------------------------------------------------------------------- tmpsaved = { ALLEEG.saved }; tmpsaved = tmpsaved(CURRENTSET); catch, tmpsaved = 'no'; end; if length(CURRENTSET) > 1 & option_storedisk [ EEG tmpcom ] = eeg_checkset(ALLEEG(CURRENTSET)); % do not load data if several datasets if length(CURRENTSET) ~= length(ALLEEG) [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET); else ALLEEG = EEG; end; else if CURRENTSET ~= 0 [ EEG tmpcom ] = eeg_checkset(ALLEEG(CURRENTSET), 'loaddata'); [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET); else EEG = eeg_emptyset; % empty dataset return; end; end; % retain saved field % ------------------ for index = 1:length(CURRENTSET) ALLEEG(CURRENTSET(index)).saved = tmpsaved{index}; EEG(index).saved = tmpsaved{index}; end; %catch % fprintf('Warning: cannot retrieve dataset with index %d\n', CURRENTSET); % return; %end; return;
github
ZijingMao/baselineeegtest-master
vararg2str.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/vararg2str.m
6,803
utf_8
547476651c6901a530169197da722d2d
% vararg2str() - transform arguments into string for evaluation % using the eval() command % % Usage: % >> strout = vararg2str( allargs ); % >> strout = vararg2str( allargs, inputnames, inputnum, nostrconv ); % % Inputs: % allargs - Cell array containing all arguments % inputnames - Cell array of input names for these arguments, if any. % inputnum - Vector of indices for all inputs. If present, the % string output may by replaced by varargin{num}. % Include NaN in the vector to avoid specific parameters % being converted in this way. % nostrconv - Vector of 0s and 1s indicating where the string % should be not be converted. % % Outputs: % strout - output string % % Author: Arnaud Delorme, CNL / Salk Institute, 9 April 2002 % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 9 April 2002 % % 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 strout = vararg2str(allargs, inputnam, inputnum, int2str ); if nargin < 1 help vararg2str; return; end; if isempty(allargs) strout = ''; return; end; % default arguments % ----------------- if nargin < 2 inputnam(1:length(allargs)) = {''}; else if length(inputnam) < length(allargs) inputnam(end+1:length(allargs)) = {''}; end; end; if nargin < 3 inputnum(1:length(allargs)) = NaN; else if length(inputnum) < length(allargs) inputnum(end+1:length(allargs)) = NaN; end; end; if nargin < 4 int2str(1:length(allargs)) = 0; else if length(int2str) < length(allargs) int2str(end+1:length(allargs)) = 0; end; end; if ~iscell( allargs ) allargs = { allargs }; end; % actual conversion % ----------------- strout = ''; for index = 1:length(allargs) tmpvar = allargs{index}; if ~isempty(inputnam{index}) strout = [ strout ',' inputnam{index} ]; else if isstr( tmpvar ) if int2str(index) strout = [ strout ',' tmpvar ]; else strout = [ strout ',' str2str( tmpvar ) ]; end; elseif isnumeric( tmpvar ) | islogical( tmpvar ) strout = [ strout ',' array2str( tmpvar ) ]; elseif iscell( tmpvar ) tmpres = vararg2str( tmpvar ); comas = find( tmpres == ',' ); tmpres(comas) = ' '; strout = [ strout ',{' tmpres '}' ]; elseif isstruct(tmpvar) strout = [ strout ',' struct2str( tmpvar ) ]; else error('Unrecognized input'); end; end; end; if ~isempty(strout) strout = strout(2:end); end; % convert string to string % ------------------------ function str = str2str( array ) if isempty( array), str = ''''''; return; end; str = ''; for index = 1:size(array,1) tmparray = deblank(array(index,:)); if isempty(tmparray) str = [ str ','' ''' ]; else str = [ str ',''' doublequotes(tmparray) '''' ]; end; end; if size(array,1) > 1 str = [ 'strvcat(' str(2:end) ')']; else str = str(2:end); end; return; % convert array to string % ----------------------- function str = array2str( array ) if isempty( array), str = '[]'; return; end; if prod(size(array)) == 1, str = num2str(array); return; end; if size(array,1) == 1, str = [ '[' contarray(array) '] ' ]; return; end; if size(array,2) == 1, str = [ '[' contarray(array') ']'' ' ]; return; end; str = ''; for index = 1:size(array,1) str = [ str ';' contarray(array(index,:)) ]; end; str = [ '[' str(2:end) ']' ]; return; % convert struct to string % ------------------------ function str = struct2str( structure ) if isempty( structure ) str = 'struct([])'; return; end; str = ''; allfields = fieldnames( structure ); for index = 1:length( allfields ) strtmp = ''; eval( [ 'allcontent = { structure.' allfields{index} ' };' ] ); % getfield generates a bug str = [ str, '''' allfields{index} ''',{' vararg2str( allcontent ) '},' ]; end; str = [ 'struct(' str(1:end-1) ')' ]; return; % double the quotes in strings % ---------------------------- function str = doublequotes( str ) quoteloc = union_bc(findstr( str, ''''), union(findstr(str, '%'), findstr(str, '\'))); if ~isempty(quoteloc) for index = length(quoteloc):-1:1 str = [ str(1:quoteloc(index)) str(quoteloc(index):end) ]; end; end; return; % test continuous arrays % ---------------------- function str = contarray( array ) array = double(array); tmpind = find( round(array) ~= array ); if prod(size(array)) == 1 str = num2str(array); return; end; if size(array,1) == 1 & size(array,2) == 2 str = [num2str(array(1)) ' ' num2str(array(2))]; return; end; if isempty(tmpind) | all(isnan(array(tmpind))) str = num2str(array(1)); skip = 0; indent = array(2) - array(1); for index = 2:length(array) if array(index) ~= array(index-1)+indent | indent == 0 if skip <= 1 if skip == 0 str = [str ' ' num2str(array(index))]; else str = [str ' ' num2str(array(index-1)) ' ' num2str(array(index))]; end; else if indent == 1 str = [str ':' num2str(array(index-1)) ' ' num2str(array(index))]; else str = [str ':' num2str(indent) ':' num2str(array(index-1)) ' ' num2str(array(index))]; end; end; skip = 0; indent = array(index) - array(index-1); else skip = skip + 1; end; end; if array(index) == array(index-1)+indent if skip ~= 0 if indent == 1 str = [str ':' num2str(array(index)) ]; elseif indent == 0 str = [str ' ' num2str(array(index)) ]; else str = [str ':' num2str(indent) ':' num2str(array(index)) ]; end; end; end; else if length(array) < 10 str = num2str(array(1)); for index = 2:length(array) str = [str ' ' num2str(array(index)) ]; end; else str = num2str(double(array)); end; end;
github
ZijingMao/baselineeegtest-master
unique_bc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/unique_bc.m
717
utf_8
1ac4b80ca073d969c0b6d0e7a0db1f3d
% unique_bc - unique backward compatible with Matlab versions prior to 2013a function [C,IA,IB] = unique_bc(A,varargin); errorFlag = error_bc; v = version; indp = find(v == '.'); v = str2num(v(1:indp(2)-1)); if v > 7.19, v = floor(v) + rem(v,1)/10; end; if nargin > 2 ind = strmatch('legacy', varargin); if ~isempty(ind) varargin(ind) = []; end; end; if v >= 7.14 [C,IA,IB] = unique(A,varargin{:},'legacy'); if errorFlag [C2,IA2] = unique(A,varargin{:}); if ~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2) warning('backward compatibility issue with call to unique function'); end; end; else [C,IA,IB] = unique(A,varargin{:}); end;
github
ZijingMao/baselineeegtest-master
setdiff_bc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/setdiff_bc.m
704
utf_8
6ff610d1b3099610817bea2fc877650d
% setdiff_bc - setdiff backward compatible with Matlab versions prior to 2013a function [C,IA] = setdiff_bc(A,B,varargin); errorFlag = error_bc; v = version; indp = find(v == '.'); v = str2num(v(1:indp(2)-1)); if v > 7.19, v = floor(v) + rem(v,1)/10; end; if nargin > 2 ind = strmatch('legacy', varargin); if ~isempty(ind) varargin(ind) = []; end; end; if v >= 7.14 [C,IA] = setdiff(A,B,varargin{:},'legacy'); if errorFlag [C2,IA2] = setdiff(A,B,varargin{:}); if (~isequal(C, C2) || ~isequal(IA, IA2)) warning('backward compatibility issue with call to setdiff function'); end; end; else [C,IA] = setdiff(A,B,varargin{:}); end;
github
ZijingMao/baselineeegtest-master
union_bc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/union_bc.m
724
utf_8
958b5b56de3e20c3892b2d7809e830fd
% union_bc - union backward compatible with Matlab versions prior to 2013a function [C,IA,IB] = union_bc(A,B,varargin); errorFlag = error_bc; v = version; indp = find(v == '.'); v = str2num(v(1:indp(2)-1)); if v > 7.19, v = floor(v) + rem(v,1)/10; end; if nargin > 2 ind = strmatch('legacy', varargin); if ~isempty(ind) varargin(ind) = []; end; end; if v >= 7.14 [C,IA,IB] = union(A,B,varargin{:},'legacy'); if errorFlag [C2,IA2,IB2] = union(A,B,varargin{:}); if (~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2)) warning('backward compatibility issue with call to union function'); end; end; else [C,IA,IB] = union(A,B,varargin{:}); end;
github
ZijingMao/baselineeegtest-master
getkeyval.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/getkeyval.m
4,294
utf_8
f3f11db9f974963b9b8b34e48f778ae9
% getkeyval() - get variable value from a 'key', 'val' sequence string. % % Usage: % >> val = getkeyval( keyvalstr, varname, mode, defaultval); % % Inputs: % keyvalstr - string containing 'key', 'val' arguments % varname - string for the name of the variable or index % of the value to retrieve (assuming arguments are % separated by comas). % mode - if the value extracted is an integer array, the % 'mode' variable can contain a subset of indexes to return. % If mode is 'present', then either 0 or 1 is returned % depending on wether the variable is present. % defaultval - default value if the varible is not found % % Outputs: % val - a value for the variable % % Note: this function is helpful for finding arguments in string commands % stored in command history. % % Author: Arnaud Delorme, CNL / Salk Institute, 29 July 2002 % % See also: gethelpvar() % Copyright (C) 2002 [email protected], Arnaud Delorme, CNL / Salk Institute % % 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 txt = getkeyval(lastcom, var, mode, default) % mode can be present for 0 and 1 if the variable is present if nargin < 1 help getkeyval; return; end; if nargin < 4 default = ''; end; if isempty(lastcom) txt = default; return; end; if nargin < 3 mode = ''; end; if isstr(mode) & strcmp(mode, 'present') if ~isempty(findstr(var, lastcom)) txt = 1; return; else txt = 0; return; end; end; if isnumeric(var) comas = findstr(lastcom, ','); if length(comas) >= var txt = lastcom(comas(var-1)+1:comas(var)-1); tmpval = eval( txt ); if isempty(tmpval), txt = ''; else txt = vararg2str( tmpval ); end; return; % txt = deblank(txt(end:-1:1)); % txt = deblank(txt(end:-1:1)); % % if ~isempty(txt) & txt(end) == '}', txt = txt(2:end-1); end; % if ~isempty(txt) % txt = deblank(txt(end:-1:1)); % txt = deblank(txt(end:-1:1)); % end; % if ~isempty(txt) & txt(end) == ']', txt = txt(2:end-1); end; % if ~isempty(txt) % txt = deblank(txt(end:-1:1)); % txt = deblank(txt(end:-1:1)); % end; % if ~isempty(txt) & txt(end) == '''', txt = txt(2:end-1); end; else txt = default; end; %fprintf('%s:%s\n', var, txt); return; else comas = findstr(lastcom, ','); % finding all comas comas = [ comas findstr(lastcom, ');') ]; % and end of lines varloc = findstr(lastcom, var); if ~isempty(varloc) % finding comas surrounding 'val' var in 'key', 'val' sequence comas = comas(find(comas >varloc(end))); txt = lastcom(comas(1)+1:comas(2)-1); txt = deblank(txt(end:-1:1)); txt = deblank(txt(end:-1:1)); if strcmp(mode, 'full') parent = findstr(lastcom, '}'); if ~isempty(parent) comas = comas(find(comas >parent(1))); txt = lastcom(comas(1)+1:comas(2)-1); end; txt = [ '''' var ''', ' txt ]; elseif isnumeric(mode) txt = str2num(txt); if ~isempty(mode) if length(txt) >= max(mode) if all(isnan(txt(mode))), txt = ''; else txt = num2str(txt(mode)); end; elseif length(txt) >= mode(1) if all(isnan(txt(mode(1)))), txt = ''; else txt = num2str(txt(mode(1))); end; else txt = default; end; else txt = num2str(txt); end; elseif txt(1) == '''' txt = txt(2:end-1); % remove quotes for text end; else txt = default; end; end; %fprintf('%s:%s\n', var, txt);
github
ZijingMao/baselineeegtest-master
is_sccn.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/is_sccn.m
388
utf_8
99847041e8b1f185a51f93939d33b819
% is_sccn() - returns 1 if computer is located at SCCN (Swartz Center % for computational Neuroscience) and 0 otherwise function bool = is_sccn; bool = 0; domnane = ' '; try eval([ 'if isunix, [tmp domname] = unix(''hostname -d'');' ... 'end;' ... 'bool = strcmpi(domname(1:end-1), ''ucsd.edu'');' ], ''); catch, end;
github
ZijingMao/baselineeegtest-master
gettext.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/gettext.m
2,465
utf_8
414488f77905ebf88c561e892df73cd7
% gettext() - This function prints a dialog box on screen and waits for % the user to enter a string. There is a cancel button which % returns a value of []. % Usage: % >> out = gettext(label1,label2,...,label7); % % Author: Colin Humphries, CNL / Salk Institute, La Jolla, 1997 % Copyright (C) 1997 Colin Humphries, Salk Institute % % 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 % 01-25-02 reformated help & license -ad function out = gettext(label1,label2,label3,label4,label5,label6,label7); global is_text_entered is_text_entered = 0; for i = 1:nargin eval(['leng(i) = length(label',num2str(i),');']) end figurelength = 15*1.0*max(leng); if figurelength < 240 figurelength = 290; end figureheight = 80+nargin*18; % Set figure figure('Position',[302 396 figurelength figureheight],'color',[.6 .6 .6],'NumberTitle','off') f1 = gcf; ax = axes('Units','Pixels','Position',[0 0 figurelength figureheight],'Visible','off','XLim',[0 figurelength],'YLim',[0 figureheight]); for i = 1:nargin eval(['text(figurelength/2,',num2str(figureheight-(i-1)*18-20),',label',num2str(i),',''color'',''k'',''FontSize'',16,''HorizontalAlignment'',''center'')']) end % Set up uicontrols TIMESTRING = ['global is_text_entered;is_text_entered = 1;clear is_text_entered']; u = uicontrol('Style','Edit','Units','Pixels','Position',[15 20 figurelength-95 25],'HorizontalAlignment','left','Callback',TIMESTRING); TIMESTRING = ['global is_text_entered;is_text_entered = 2;clear is_text_entered']; v = uicontrol('Style','Pushbutton','Units','Pixels','Position',[figurelength-70 20 55 25],'String','Cancel','Callback',TIMESTRING); while(is_text_entered == 0) drawnow end if is_text_entered == 1 out = get(u,'string'); else out = []; end clear is_text_entered delete(f1)
github
ZijingMao/baselineeegtest-master
eeg_getdatact.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeg_getdatact.m
12,037
utf_8
bc4bb0dfeb0f9183cb320544ba36fbdd
% eeg_getdatact() - get EEG data from a specified dataset or % component activity % % Usage: % >> signal = eeg_getdatact( EEG ); % >> signal = eeg_getdatact( EEG, 'key', 'val'); % % Inputs: % EEG - Input dataset % % Optional input: % 'channel' - [integer array] read only specific channels. % Default is to read all data channels. % 'component' - [integer array] read only specific components % 'projchan' - [integer or cell array] channel(s) onto which the component % should be projected. % 'rmcomps' - [integer array] remove selected components from data % channels. This is only to be used with channel data not % when selecting components. % 'trialindices' - [integer array] only read specific trials. Default is % to read all trials. % 'samples' - [integer array] only read specific samples. Default is % to read all samples. % 'reshape' - ['2d'|'3d'] reshape data. Default is '3d' when possible. % 'verbose' - ['on'|'off'] verbose mode. Default is 'on'. % % Outputs: % signal - EEG data or component activity % % Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2008- % % See also: eeg_checkset() % Copyright (C) 15 Feb 2002 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 [data boundaries] = eeg_getdatact( EEG, varargin); data = []; if nargin < 1 help eeg_getdatact; return; end; % reading data from several datasets and concatening it % ----------------------------------------------------- if iscell(EEG) || (~isstr(EEG) && length(EEG) > 1) % decode some arguments % --------------------- trials = cell(1,length(EEG)); rmcomps = cell(1,length(EEG)); for iArg = length(varargin)-1:-2:1 if strcmpi(varargin{iArg}, 'trialindices') trials = varargin{iArg+1}; varargin(iArg:iArg+1) = []; elseif strcmpi(varargin{iArg}, 'rmcomps') rmcomps = varargin{iArg+1}; varargin(iArg:iArg+1) = []; end; end; if isnumeric(rmcomps), rmtmp = rmcomps; rmcomps = cell(1,length(EEG)); rmcomps(:) = { rmtmp }; end; % concatenate datasets % -------------------- data = []; boundaries = []; for dat = 1:length(EEG) if iscell(EEG) [tmpdata datboundaries] = eeg_getdatact(EEG{dat}, 'trialindices', trials{dat}, 'rmcomps', rmcomps{dat}, varargin{:} ); else [tmpdata datboundaries] = eeg_getdatact(EEG(dat), 'trialindices', trials{dat}, 'rmcomps', rmcomps{dat}, varargin{:} ); end; if isempty(data), data = tmpdata; boundaries = datboundaries; else if all([ EEG.trials ] == 1) % continuous data if size(data,1) ~= size(tmpdata,1), error('Datasets to be concatenated do not have the same number of channels'); end; % adding boundaries if ~isempty(datboundaries) boundaries = [boundaries datboundaries size(data,2)]; else boundaries = [boundaries size(data,2)]; end; data(:,end+1:end+size(tmpdata,2)) = tmpdata; % concatenating trials else if size(data,1) ~= size(tmpdata,1), error('Datasets to be concatenated do not have the same number of channels'); end; if size(data,2) ~= size(tmpdata,2), error('Datasets to be concatenated do not have the same number of time points'); end; data(:,:,end+1:end+size(tmpdata,3)) = tmpdata; % concatenating trials end; end; end; return; end; % if string load dataset % ---------------------- if isstr(EEG) EEG = pop_loadset('filename', EEG, 'loadmode', 'info'); end; opt = finputcheck(varargin, { ... 'channel' 'integer' {} []; 'verbose' 'string' { 'on','off' } 'on'; 'reshape' 'string' { '2d','3d' } '3d'; 'projchan' {'integer','cell' } { {} {} } []; 'component' 'integer' {} []; 'samples' 'integer' {} []; 'interp' 'struct' { } struct([]); 'trialindices' {'integer','cell'} { {} {} } []; 'rmcomps' {'integer','cell'} { {} {} } [] }, 'eeg_getdatact'); if isstr(opt), error(opt); end; channelNotDefined = 0; if isempty(opt.channel), opt.channel = [1:EEG.nbchan]; channelNotDefined = 1; elseif isequal(opt.channel, [1:EEG.nbchan]) && ~isempty(opt.interp) channelNotDefined = 1; end; if isempty(opt.trialindices), opt.trialindices = [1:EEG.trials]; end; if iscell( opt.trialindices), opt.trialindices = opt.trialindices{1}; end; if iscell(opt.rmcomps ), opt.rmcomps = opt.rmcomps{1}; end; if (~isempty(opt.rmcomps) | ~isempty(opt.component)) & isempty(EEG.icaweights) error('No ICA weight in dataset'); end; if strcmpi(EEG.data, 'in set file') EEG = pop_loadset('filename', EEG.filename, 'filepath', EEG.filepath); end; % get data boundaries if continuous data % -------------------------------------- boundaries = []; if nargout > 1 && EEG.trials == 1 && ~isempty(EEG.event) && isfield(EEG.event, 'type') && isstr(EEG.event(1).type) if ~isempty(opt.samples) disp('WARNING: eeg_getdatact.m, boundaries are not accurate when selecting data samples'); end; tmpevent = EEG.event; tmpbound = strmatch('boundary', lower({ tmpevent.type })); if ~isempty(tmpbound) boundaries = [tmpevent(tmpbound).latency ]-0.5; end; end; % getting channel or component activation % --------------------------------------- filename = fullfile(EEG.filepath, [ EEG.filename(1:end-4) '.icaact' ] ); if ~isempty(opt.component) & ~isempty(EEG.icaact) data = EEG.icaact(opt.component,:,:); elseif ~isempty(opt.component) & exist(filename) % reading ICA file % ---------------- data = repmat(single(0), [ length(opt.component) EEG.pnts EEG.trials ]); fid = fopen( filename, 'r', 'ieee-le'); %little endian (see also pop_saveset) if fid == -1, error( ['file ' filename ' could not be open' ]); end; for ind = 1:length(opt.component) fseek(fid, (opt.component(ind)-1)*EEG.pnts*EEG.trials*4, -1); data(ind,:) = fread(fid, [EEG.trials*EEG.pnts 1], 'float32')'; end; fclose(fid); elseif ~isempty(opt.component) if isempty(EEG.icaact) data = eeg_getdatact( EEG ); data = (EEG.icaweights(opt.component,:)*EEG.icasphere)*data(EEG.icachansind,:); else data = EEG.icaact(opt.component,:,:); end; else if isnumeric(EEG.data) % channel data = EEG.data; else % channel but no data loaded filename = fullfile(EEG.filepath, EEG.data); fid = fopen( filename, 'r', 'ieee-le'); %little endian (see also pop_saveset) if fid == -1 error( ['file ' filename ' not found. If you have renamed/moved' 10 ... 'the .set file, you must also rename/move the associated data file.' ]); else if strcmpi(opt.verbose, 'on') fprintf('Reading float file ''%s''...\n', filename); end; end; % old format = .fdt; new format = .dat (transposed) % ------------------------------------------------- datformat = 0; if length(filename) > 3 if strcmpi(filename(end-2:end), 'dat') datformat = 1; end; end; EEG.datfile = EEG.data; % reading data file % ----------------- eeglab_options; if length(opt.channel) == EEG.nbchan && option_memmapdata fclose(fid); data = mmo(filename, [EEG.nbchan EEG.pnts EEG.trials], false); %data = memmapdata(filename, [EEG.nbchan EEG.pnts EEG.trials]); else if datformat if length(opt.channel) == EEG.nbchan || ~isempty(opt.interp) data = fread(fid, [EEG.trials*EEG.pnts EEG.nbchan], 'float32')'; else data = repmat(single(0), [ length(opt.channel) EEG.pnts EEG.trials ]); for ind = 1:length(opt.channel) fseek(fid, (opt.channel(ind)-1)*EEG.pnts*EEG.trials*4, -1); data(ind,:) = fread(fid, [EEG.trials*EEG.pnts 1], 'float32')'; end; opt.channel = [1:size(data,1)]; end; else data = fread(fid, [EEG.nbchan Inf], 'float32'); end; fclose(fid); end; end; % subracting components from data % ------------------------------- if ~isempty(opt.rmcomps) if strcmpi(opt.verbose, 'on') fprintf('Removing %d artifactual components\n', length(opt.rmcomps)); end; rmcomps = eeg_getdatact( EEG, 'component', opt.rmcomps); % loaded from file rmchan = []; rmchanica = []; for index = 1:length(opt.channel) tmpicaind = find(opt.channel(index) == EEG.icachansind); if ~isempty(tmpicaind) rmchan = [ rmchan index ]; rmchanica = [ rmchanica tmpicaind ]; end; end; data(rmchan,:) = data(rmchan,:) - EEG.icawinv(rmchanica,opt.rmcomps)*rmcomps(:,:); %EEG = eeg_checkset(EEG, 'loaddata'); %EEG = pop_subcomp(EEG, opt.rmcomps); %data = EEG.data(opt.channel,:,:); %if strcmpi(EEG.subject, 'julien') & strcmpi(EEG.condition, 'oddball') & strcmpi(EEG.group, 'after') % jjjjf %end; end; if ~isempty(opt.interp) EEG.data = data; EEG.event = []; EEG.epoch = []; EEG = eeg_interp(EEG, opt.interp, 'spherical'); data = EEG.data; if channelNotDefined, opt.channel = [1:EEG.nbchan]; end; end; if ~isequal(opt.channel, [1:EEG.nbchan]) data = data(intersect(opt.channel,[1:EEG.nbchan]),:,:); end; end; % projecting components on data channels % -------------------------------------- if ~isempty(opt.projchan) if iscell(opt.projchan) opt.projchan = std_chaninds(EEG, opt.projchan); end; finalChanInds = []; for iChan = 1:length(opt.projchan) tmpInd = find(EEG.icachansind == opt.projchan(iChan)); if isempty(tmpInd) error(sprintf('Warning: can not backproject component on channel %d (not used for ICA)\n', opt.projchan(iChan))); end; finalChanInds = [ finalChanInds tmpInd ]; end; data = EEG.icawinv(finalChanInds, opt.component)*data(:,:); end; if size(data,2)*size(data,3) ~= EEG.pnts*EEG.trials disp('WARNING: The file size on disk does not correspond to the dataset, file has been truncated'); end; try, if EEG.trials == 1, EEG.pnts = size(data,2); end; if strcmpi(opt.reshape, '3d') data = reshape(data, size(data,1), EEG.pnts, EEG.trials); else data = reshape(data, size(data,1), EEG.pnts*EEG.trials); end; catch error('The file size on disk does not correspond to the dataset information.'); end; % select trials % ------------- if length(opt.trialindices) ~= EEG.trials data = data(:,:,opt.trialindices); end; if ~isempty(opt.samples) data = data(:,opt.samples,:); end;
github
ZijingMao/baselineeegtest-master
eeg_readoptions.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeg_readoptions.m
3,419
utf_8
4104fa6db19f22201a63ba183b0d2f5f
% eeg_readoptions() - Read EEGLAB memory options file (eeg_options) into a % structure variable (opt). % % Usage: % [ header, opt ] = eeg_readoptions( filename, opt ); % % Input: % filename - [string] name of the option file % opt - [struct] option structure containing backup values % % Outputs: % header - [string] file header. % opt - [struct] option structure containing an array of 3 fields % varname -> all variable names. % value -> value for each variable name % description -> all description associated with each variable % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2006- % % See also: eeg_options(), eeg_editoptions() % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2006- % % 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 [ header, opt ] = eeg_readoptions( filename, opt_backup ); if nargin < 1 help eeg_readoptions; return; end; if nargin < 2 opt_backup = []; end; if isstr(filename) fid = fopen(filename, 'r'); else fid = filename; end; % skip header % ----------- header = ''; str = fgets( fid ); while (str(1) == '%') header = [ header str]; str = fgets( fid ); end; % read variables values and description % -------------------------------------- str = fgetl( fid ); % jump a line index = 1; opt = []; while (str(1) ~= -1) if str(1) == '%' opt(index).description = str(3:end-1); opt(index).value = []; opt(index).varname = ''; else [ opt(index).varname str ] = strtok(str); % variable name [ equal str ] = strtok(str); % = [ opt(index).value str ] = strtok(str); % value [ tmp str ] = strtok(str); % ; [ tmp dsc ] = strtok(str); % comment dsc = deblank( dsc(end:-1:1) ); opt(index).description = deblank( dsc(end:-1:1) ); opt(index).value = str2num( opt(index).value ); end; str = fgets( fid ); % jump a line index = index+1; end; fclose(fid); % replace in backup structure if any % ---------------------------------- if ~isempty(opt_backup) if ~isempty(opt) for index = 1:length(opt_backup) ind = strmatch(opt_backup(index).varname, { opt.varname }, 'exact'); if ~isempty(ind) & ~isempty(opt_backup(index).varname) opt_backup(index).value = opt(ind).value; end; end; end; opt = opt_backup; end;
github
ZijingMao/baselineeegtest-master
hlp_argstruct2linearcell.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/hlp_argstruct2linearcell.m
1,953
utf_8
cf2a64e0864d59a83ffeefe20c9f2b09
% hlp_argstruct2linearcell() - Linearize configation output of arg_guipanel % % Usage: % >> cellval = hlp_argstruct2linearcells( cfg ); % % Inputs: % cfg - output configuration structure from arg_guipanel % % Output: % cellval - cell array of output values % % Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2013- % Copyright (C) 2013 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 cellval = hlp_argstruct2linearcell(cfg); cellval = {}; if isstruct(cfg) ff = fieldnames(cfg); for iField = 1:length(ff) if ~strcmpi(ff{iField}, 'arg_direct') if strcmpi(ff{iField}, 'arg_selection') cellval = { cfg.arg_selection cellval{:} }; else val = cfg.(ff{iField}); if isstruct(val) val = hlp_argstruct2linearcell(val); cellval = { cellval{:} ff{iField} val{:} }; elseif iscell(val) cellval = { cellval{:} ff{iField} vararg2str(val) }; else cellval = { cellval{:} ff{iField} val }; end; end; end; end else cellval = cfg; end;
github
ZijingMao/baselineeegtest-master
eeg_checkset.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeg_checkset.m
66,957
utf_8
bd9effa16d52b65b814263a1c016032b
% eeg_checkset() - check the consistency of the fields of an EEG dataset % Also: See EEG dataset structure field descriptions below. % % Usage: >> [EEGOUT,changes] = eeg_checkset(EEG); % perform all checks % except 'makeur' % >> [EEGOUT,changes] = eeg_checkset(EEG, 'keyword'); % perform 'keyword' check(s) % % Inputs: % EEG - EEGLAB dataset structure or (ALLEEG) array of EEG structures % % Optional keywords: % 'icaconsist' - if EEG contains several datasets, check whether they have % the same ICA decomposition % 'epochconsist' - if EEG contains several datasets, check whether they have % identical epoch lengths and time limits. % 'chanconsist' - if EEG contains several datasets, check whether they have % the same number of channela and channel labels. % 'data' - check whether EEG contains data (EEG.data) % 'loaddata' - load data array (if necessary) % 'savedata' - save data array (if necessary - see EEG.saved below) % 'contdata' - check whether EEG contains continuous data % 'epoch' - check whether EEG contains epoched or continuous data % 'ica' - check whether EEG contains an ICA decomposition % 'besa' - check whether EEG contains component dipole locations % 'event' - check whether EEG contains an event array % 'makeur' - remake the EEG.urevent structure % 'checkur' - check whether the EEG.urevent structure is consistent % with the EEG.event structure % 'chanlocsize' - check the EEG.chanlocs structure length; show warning if % necessary. % 'chanlocs_homogeneous' - check whether EEG contains consistent channel % information; if not, correct it. % 'eventconsistency' - check whether EEG.event information are consistent; % rebuild event* subfields of the 'EEG.epoch' structure % (can be time consuming). % Outputs: % EEGOUT - output EEGLAB dataset or dataset array % changes - change code: 'no' = no changes; 'yes' = the EEG % structure was modified % % =========================================================== % The structure of an EEG dataset under EEGLAB (as of v5.03): % % Basic dataset information: % EEG.setname - descriptive name|title for the dataset % EEG.filename - filename of the dataset file on disk % EEG.filepath - filepath (directory/folder) of the dataset file(s) % EEG.trials - number of epochs (or trials) in the dataset. % If data are continuous, this number is 1. % EEG.pnts - number of time points (or data frames) per trial (epoch). % If data are continuous (trials=1), the total number % of time points (frames) in the dataset % EEG.nbchan - number of channels % EEG.srate - data sampling rate (in Hz) % EEG.xmin - epoch start latency|time (in sec. relative to the % time-locking event at time 0) % EEG.xmax - epoch end latency|time (in seconds) % EEG.times - vector of latencies|times in seconds (one per time point) % EEG.ref - ['common'|'averef'|integer] reference channel type or number % EEG.history - cell array of ascii pop-window commands that created % or modified the dataset % EEG.comments - comments about the nature of the dataset (edit this via % menu selection Edit > About this dataset) % EEG.etc - miscellaneous (technical or temporary) dataset information % EEG.saved - ['yes'|'no'] 'no' flags need to save dataset changes before exit % % The data: % EEG.data - two-dimensional continuous data array (chans, frames) % ELSE, three-dim. epoched data array (chans, frames, epochs) % % The channel locations sub-structures: % EEG.chanlocs - structure array containing names and locations % of the channels on the scalp % EEG.urchanlocs - original (ur) dataset chanlocs structure containing % all channels originally collected with these data % (before channel rejection) % EEG.chaninfo - structure containing additional channel info % EEG.ref - type of channel reference ('common'|'averef'|+/-int] % EEG.splinefile - location of the spline file used by headplot() to plot % data scalp maps in 3-D % % The event and epoch sub-structures: % EEG.event - event structure containing times and nature of experimental % events recorded as occurring at data time points % EEG.urevent - original (ur) event structure containing all experimental % events recorded as occurring at the original data time points % (before data rejection) % EEG.epoch - epoch event information and epoch-associated data structure array (one per epoch) % EEG.eventdescription - cell array of strings describing event fields. % EEG.epochdescription - cell array of strings describing epoch fields. % --> See the http://sccn.ucsd.edu/eeglab/maintut/eeglabscript.html for details % % ICA (or other linear) data components: % EEG.icasphere - sphering array returned by linear (ICA) decomposition % EEG.icaweights - unmixing weights array returned by linear (ICA) decomposition % EEG.icawinv - inverse (ICA) weight matrix. Columns gives the projected % topographies of the components to the electrodes. % EEG.icaact - ICA activations matrix (components, frames, epochs) % Note: [] here means that 'compute_ica' option has bee set % to 0 under 'File > Memory options' In this case, % component activations are computed only as needed. % EEG.icasplinefile - location of the spline file used by headplot() to plot % component scalp maps in 3-D % EEG.chaninfo.icachansind - indices of channels used in the ICA decomposition % EEG.dipfit - array of structures containing component map dipole models % % Variables indicating membership of the dataset in a studyset: % EEG.subject - studyset subject code % EEG.group - studyset group code % EEG.condition - studyset experimental condition code % EEG.session - studyset session number % % Variables used for manual and semi-automatic data rejection: % EEG.specdata - data spectrum for every single trial % EEG.specica - data spectrum for every single trial % EEG.stats - statistics used for data rejection % EEG.stats.kurtc - component kurtosis values % EEG.stats.kurtg - global kurtosis of components % EEG.stats.kurta - kurtosis of accepted epochs % EEG.stats.kurtr - kurtosis of rejected epochs % EEG.stats.kurtd - kurtosis of spatial distribution % EEG.reject - statistics used for data rejection % EEG.reject.entropy - entropy of epochs % EEG.reject.entropyc - entropy of components % EEG.reject.threshold - rejection thresholds % EEG.reject.icareject - epochs rejected by ICA criteria % EEG.reject.gcompreject - rejected ICA components % EEG.reject.sigreject - epochs rejected by single-channel criteria % EEG.reject.elecreject - epochs rejected by raw data criteria % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab() % Copyright (C) 2001 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 % 01-25-02 reformated help & license -ad % 01-26-02 chandeg events and trial condition format -ad % 01-27-02 debug when trial condition is empty -ad % 02-15-02 remove icawinv recompute for pop_epoch -ad & ja % 02-16-02 remove last modification and test icawinv separatelly -ad % 02-16-02 empty event and epoch check -ad % 03-07-02 add the eeglab options -ad % 03-07-02 corrected typos and rate/point calculation -ad & ja % 03-15-02 add channel location reading & checking -ad % 03-15-02 add checking of ICA and epochs with pop_up windows -ad % 03-27-02 recorrected rate/point calculation -ad & sm function [EEG, res] = eeg_checkset( EEG, varargin ); msg = ''; res = 'no'; com = sprintf('EEG = eeg_checkset( EEG );'); if nargin < 1 help eeg_checkset; return; end; if isempty(EEG), return; end; if ~isfield(EEG, 'data'), return; end; % checking multiple datasets % -------------------------- if length(EEG) > 1 if nargin > 1 switch varargin{1} case 'epochconsist', % test epoch consistency % ---------------------- res = 'no'; datasettype = unique_bc( [ EEG.trials ] ); if datasettype(1) == 1 & length(datasettype) == 1, return; % continuous data elseif datasettype(1) == 1, return; % continuous and epoch data end; allpnts = unique_bc( [ EEG.pnts ] ); allxmin = unique_bc( [ EEG.xmin ] ); if length(allpnts) == 1 & length(allxmin) == 1, res = 'yes'; end; return; case 'chanconsist' % test channel number and name consistency % ---------------------------------------- res = 'yes'; chanlen = unique_bc( [ EEG.nbchan ] ); anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) ); if length(chanlen) == 1 & all(anyempty == 0) tmpchanlocs = EEG(1).chanlocs; channame1 = { tmpchanlocs.labels }; for i = 2:length(EEG) tmpchanlocs = EEG(i).chanlocs; channame2 = { tmpchanlocs.labels }; if length(intersect(channame1, channame2)) ~= length(channame1), res = 'no'; end; end; else res = 'no'; end; return; case 'icaconsist' % test ICA decomposition consistency % ---------------------------------- res = 'yes'; anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) ); if length(anyempty) == 1 & anyempty(1) == 0 ica1 = EEG(1).icawinv; for i = 2:length(EEG) if ~isequal(EEG(1).icawinv, EEG(i).icawinv) res = 'no'; end; end; else res = 'no'; end; return; end; end; end; % reading these option take time because % of disk access % -------------- eeglab_options; % standard checking % ----------------- ALLEEG = EEG; for inddataset = 1:length(ALLEEG) EEG = ALLEEG(inddataset); % additional checks % ----------------- res = -1; % error code if ~isempty( varargin) for index = 1:length( varargin ) switch varargin{ index } case 'data',; % already done at the top case 'contdata',; if EEG.trials > 1 errordlg2(strvcat('Error: function only works on continuous data'), 'Error'); return; end; case 'ica', if isempty(EEG.icaweights) errordlg2(strvcat('Error: no ICA decomposition. use menu "Tools > Run ICA" first.'), 'Error'); return; end; case 'epoch', if EEG.trials == 1 errordlg2(strvcat('Extract epochs before running that function', 'Use Tools > Extract epochs'), 'Error'); return end; case 'besa', if ~isfield(EEG, 'sources') errordlg2(strvcat('No dipole information', '1) Export component maps: Tools > Localize ... BESA > Export ...' ... , '2) Run BESA to localize the equivalent dipoles', ... '3) Import the BESA dipoles: Tools > Localize ... BESA > Import ...'), 'Error'); return end; case 'event', if isempty(EEG.event) errordlg2(strvcat('Requires events. You need to add events first.', ... 'Use "File > Import event info" or "File > Import epoch info"'), 'Error'); return; end; case 'chanloc', tmplocs = EEG.chanlocs; if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta })) errordlg2( strvcat('This functionality requires channel location information.', ... 'Enter the channel file name via "Edit > Edit dataset info".', ... 'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error'); return; end; case 'chanlocs_homogeneous', tmplocs = EEG.chanlocs; if isempty(tmplocs) || ~isfield(tmplocs, 'theta') || all(cellfun('isempty', { tmplocs.theta })) errordlg2( strvcat('This functionality requires channel location information.', ... 'Enter the channel file name via "Edit > Edit dataset info".', ... 'For channel file format, see ''>> help readlocs'' from the command line.'), 'Error'); return; end; if ~isfield(EEG.chanlocs, 'X') || isempty(EEG.chanlocs(1).X) EEG.chanlocs = convertlocs(EEG.chanlocs, 'topo2all'); res = [ inputname(1) ' = eeg_checkset(' inputname(1) ', ''chanlocs_homogeneous'' ); ' ]; end; case 'chanlocsize', if ~isempty(EEG.chanlocs) if length(EEG.chanlocs) > EEG.nbchan questdlg2(strvcat('Warning: there is one more electrode location than', ... 'data channels. EEGLAB will consider the last electrode to be the', ... 'common reference channel. If this is not the case, remove the', ... 'extra channel'), 'Warning', 'Ok', 'Ok'); end; end; case 'makeur', if ~isempty(EEG.event) if isfield(EEG.event, 'urevent'), EEG.event = rmfield(EEG.event, 'urevent'); disp('eeg_checkset note: re-creating the original event table (EEG.urevent)'); else disp('eeg_checkset note: creating the original event table (EEG.urevent)'); end; EEG.urevent = EEG.event; for index = 1:length(EEG.event) EEG.event(index).urevent = index; end; end; case 'checkur', if ~isempty(EEG.event) if isfield(EEG.event, 'urevent') & ~isempty(EEG.urevent) urlatencies = [ EEG.urevent.latency ]; [newlat tmpind] = sort(urlatencies); if ~isequal(newlat, urlatencies) EEG.urevent = EEG.urevent(tmpind); [tmp tmpind2] = sort(tmpind); for index = 1:length(EEG.event) EEG.event(index).urevent = tmpind2(EEG.event(index).urevent); end; end; end; end; case 'eventconsistency', [EEG res] = eeg_checkset(EEG); if isempty(EEG.event), return; end; % check events (slow) % ------------ if isfield(EEG.event, 'type') eventInds = arrayfun(@(x)isempty(x.type), EEG.event); if any(eventInds) if all(arrayfun(@(x)isnumeric(x.type), EEG.event)) for ind = find(eventInds), EEG.event(ind).type = NaN; end; else for ind = find(eventInds), EEG.event(ind).type = 'empty'; end; end; end; if ~all(arrayfun(@(x)ischar(x.type), EEG.event)) && ~all(arrayfun(@(x)isnumeric(x.type), EEG.event)) disp('Warning: converting all event types to strings'); for ind = 1:length(EEG.event) EEG.event(ind).type = num2str(EEG.event(ind).type); end; EEG = eeg_checkset(EEG, 'eventconsistency'); end; end; % remove the events which latency are out of boundary % --------------------------------------------------- if isfield(EEG.event, 'latency') if isfield(EEG.event, 'type') && ischar(EEG.event(1).type) if strcmpi(EEG.event(1).type, 'boundary') & isfield(EEG.event, 'duration') if EEG.event(1).duration < 1 EEG.event(1) = []; elseif EEG.event(1).latency > 0 & EEG.event(1).latency < 1 EEG.event(1).latency = 0.5; end; end; end; try, tmpevent = EEG.event; alllatencies = [ tmpevent.latency ]; catch, error('Checkset: error empty latency entry for new events added by user'); end; I1 = find(alllatencies < 0.5); I2 = find(alllatencies > EEG.pnts*EEG.trials+1); % The addition of 1 was included % because, if data epochs are extracted from -1 to % time 0, this allow to include the last event in % the last epoch (otherwise all epochs have an % event except the last one if (length(I1) + length(I2)) > 0 fprintf('eeg_checkset warning: %d/%d events had out-of-bounds latencies and were removed\n', ... length(I1) + length(I2), length(EEG.event)); EEG.event(union(I1, I2)) = []; end; end; if isempty(EEG.event), return; end; % save information for non latency fields updates % ----------------------------------------------- difffield = []; if ~isempty(EEG.event) && isfield(EEG.event, 'epoch') % remove fields with empty epochs % ------------------------------- removeevent = []; try, tmpevent = EEG.event; allepochs = [ tmpevent.epoch ]; removeevent = find( allepochs < 1 | allepochs > EEG.trials); if ~isempty(removeevent) disp([ 'eeg_checkset warning: ' int2str(length(removeevent)) ' event had invalid epoch numbers and were removed']); end; catch, for indexevent = 1:length(EEG.event) if isempty( EEG.event(indexevent).epoch ) || ~isnumeric(EEG.event(indexevent).epoch) ... | EEG.event(indexevent).epoch < 1 || EEG.event(indexevent).epoch > EEG.trials removeevent = [removeevent indexevent]; disp([ 'eeg_checkset warning: event ' int2str(indexevent) ' has an invalid epoch number: removed']); end; end; end; EEG.event(removeevent) = []; tmpevent = EEG.event; allepochs = [ tmpevent.epoch ]; % uniformize fields content for the different epochs % -------------------------------------------------- % THIS WAS REMOVED SINCE SOME FIELDS ARE ASSOCIATED WITH THE EVENT AND NOT WITH THE EPOCH % I PUT IT BACK, BUT IT DOES NOT ERASE NON-EMPTY VALUES difffield = fieldnames(EEG.event); difffield = difffield(~(strcmp(difffield,'latency')|strcmp(difffield,'epoch')|strcmp(difffield,'type'))); for index = 1:length(difffield) tmpevent = EEG.event; allvalues = { tmpevent.(difffield{index}) }; try valempt = cellfun('isempty', allvalues); catch valempt = mycellfun('isempty', allvalues); end; arraytmpinfo = cell(1,EEG.trials); % spetial case of duration % ------------------------ if strcmp( difffield{index}, 'duration') if any(valempt) fprintf(['eeg_checkset: found empty values for field ''' difffield{index} ... ''' (filling with 0)\n']); end; for indexevent = find(valempt) EEG.event(indexevent).duration = 0; end; else % get the field content % --------------------- indexevent = find(~valempt); arraytmpinfo(allepochs(indexevent)) = allvalues(indexevent); % uniformize content for all epochs % --------------------------------- indexevent = find(valempt); tmpevent = EEG.event; [tmpevent(indexevent).(difffield{index})] = arraytmpinfo{allepochs(indexevent)}; EEG.event = tmpevent; if any(valempt) fprintf(['eeg_checkset: found empty values for field ''' difffield{index} '''\n']); fprintf([' filling with values of other events in the same epochs\n']); end; end; end; end; if isempty(EEG.event), return; end; % uniformize fields (str or int) if necessary % ------------------------------------------- fnames = fieldnames(EEG.event); for fidx = 1:length(fnames) fname = fnames{fidx}; tmpevent = EEG.event; allvalues = { tmpevent.(fname) }; try % find indices of numeric values among values of this event property valreal = ~cellfun('isclass', allvalues, 'char'); catch valreal = mycellfun('isclass', allvalues, 'double'); end; format = 'ok'; if ~all(valreal) % all valreal ok format = 'str'; if all(valreal == 0) % all valreal=0 ok format = 'ok'; end; end; if strcmp(format, 'str') fprintf('eeg_checkset note: value format of event field ''%s'' made uniform\n', fname); % get the field content % --------------------- for indexevent = 1:length(EEG.event) if valreal(indexevent) EEG.event = setfield(EEG.event, { indexevent }, fname, num2str(allvalues{indexevent}) ); end; end; end; end; % check boundary events % --------------------- tmpevent = EEG.event; if isfield(tmpevent, 'type') && ~isnumeric(tmpevent(1).type) allEventTypes = { tmpevent.type }; boundsInd = strmatch('boundary', allEventTypes); if ~isempty(boundsInd), bounds = [ tmpevent(boundsInd).latency ]; % remove last event if necessary if EEG.trials==1;%this if block added by James Desjardins (Jan 13th, 2014) if round(bounds(end)-0.5+1) >= size(EEG.data,2), EEG.event(boundsInd(end)) = []; bounds(end) = []; end; % remove final boundary if any end % The first boundary below need to be kept for % urevent latency calculation % if bounds(1) < 0, EEG.event(bounds(1)) = []; end; % remove initial boundary if any indDoublet = find(bounds(2:end)-bounds(1:end-1)==0); if ~isempty(indDoublet) disp('Warning: duplicate boundary event removed'); for indBound = 1:length(indDoublet) EEG.event(boundsInd(indDoublet(indBound)+1)).duration = EEG.event(boundsInd(indDoublet(indBound)+1)).duration+EEG.event(boundsInd(indDoublet(indBound))).duration; end; EEG.event(boundsInd(indDoublet)) = []; end; end; end; if isempty(EEG.event), return; end; % check that numeric format is double (Matlab 7) % ----------------------------------- allfields = fieldnames(EEG.event); if ~isempty(EEG.event) for index = 1:length(allfields) tmpval = EEG.event(1).(allfields{index}); if isnumeric(tmpval) && ~isa(tmpval, 'double') for indexevent = 1:length(EEG.event) tmpval = getfield(EEG.event, { indexevent }, allfields{index} ); EEG.event = setfield(EEG.event, { indexevent }, allfields{index}, double(tmpval)); end; end; end; end; % check duration field, replace empty by 0 % ---------------------------------------- if isfield(EEG.event, 'duration') tmpevent = EEG.event; try, valempt = cellfun('isempty' , { tmpevent.duration }); catch, valempt = mycellfun('isempty', { tmpevent.duration }); end; if any(valempt), for index = find(valempt) EEG.event(index).duration = 0; end; end; end; % resort events % ------------- if isfield(EEG.event, 'latency') try, if isfield(EEG.event, 'epoch') TMPEEG = pop_editeventvals(EEG, 'sort', { 'epoch' 0 'latency' 0 }); else TMPEEG = pop_editeventvals(EEG, 'sort', { 'latency' 0 }); end; if ~isequal(TMPEEG.event, EEG.event) EEG = TMPEEG; disp('Event resorted by increasing latencies.'); end; catch, disp('eeg_checkset: problem when attempting to resort event latencies.'); end; end; % check latency of first event % ---------------------------- if ~isempty(EEG.event) if isfield(EEG.event, 'latency') if EEG.event(1).latency < 0.5 EEG.event(1).latency = 0.5; end; end; end; % build epoch structure % --------------------- try, if EEG.trials > 1 & ~isempty(EEG.event) % erase existing event-related fields % ------------------------------ if ~isfield(EEG,'epoch') EEG.epoch = []; end if ~isempty(EEG.epoch) if length(EEG.epoch) ~= EEG.trials disp('Warning: number of epoch entries does not match number of dataset trials;'); disp(' user-defined epoch entries will be erased.'); EEG.epoch = []; else fn = fieldnames(EEG.epoch); EEG.epoch = rmfield(EEG.epoch,fn(strncmp('event',fn,5))); end end % set event field % --------------- tmpevent = EEG.event; eventepoch = [tmpevent.epoch]; epochevent = cell(1,EEG.trials); destdata = epochevent; EEG.epoch(length(epochevent)).event = []; for k=1:length(epochevent) epochevent{k} = find(eventepoch==k); end tmpepoch = EEG.epoch; [tmpepoch.event] = epochevent{:}; EEG.epoch = tmpepoch; maxlen = max(cellfun(@length,epochevent)); % copy event information into the epoch array % ------------------------------------------- eventfields = fieldnames(EEG.event)'; eventfields = eventfields(~strcmp(eventfields,'epoch')); tmpevent = EEG.event; for k = 1:length(eventfields) fname = eventfields{k}; switch fname case 'latency' sourcedata = round(eeg_point2lat([tmpevent.(fname)],[tmpevent.epoch],EEG.srate, [EEG.xmin EEG.xmax]*1000, 1E-3) * 10^8 )/10^8; sourcedata = num2cell(sourcedata); case 'duration' sourcedata = num2cell([tmpevent.(fname)]/EEG.srate*1000); otherwise sourcedata = {tmpevent.(fname)}; end if maxlen == 1 destdata = cell(1,length(epochevent)); destdata(~cellfun('isempty',epochevent)) = sourcedata([epochevent{:}]); else for l=1:length(epochevent) destdata{l} = sourcedata(epochevent{l}); end end tmpepoch = EEG.epoch; [tmpepoch.(['event' fname])] = destdata{:}; EEG.epoch = tmpepoch; end end; catch, errordlg2(['Warning: minor problem encountered when generating' 10 ... 'the EEG.epoch structure (used only in user scripts)']); return; end; case { 'loaddata' 'savedata' 'chanconsist' 'icaconsist' 'epochconsist' }, res = ''; otherwise, error('eeg_checkset: unknown option'); end; end; end; res = []; % check name consistency % ---------------------- if ~isempty(EEG.setname) if ~ischar(EEG.setname) EEG.setname = ''; else if size(EEG.setname,1) > 1 disp('eeg_checkset warning: invalid dataset name, removed'); EEG.setname = ''; end; end; else EEG.setname = ''; end; % checking history and convert if necessary % ----------------------------------------- if isfield(EEG, 'history') & size(EEG.history,1) > 1 allcoms = cellstr(EEG.history); EEG.history = deblank(allcoms{1}); for index = 2:length(allcoms) EEG.history = [ EEG.history 10 deblank(allcoms{index}) ]; end; end; % read data if necessary % ---------------------- if ischar(EEG.data) & nargin > 1 if strcmpi(varargin{1}, 'loaddata') EEG.data = eeg_getdatact(EEG); end; end; % save data if necessary % ---------------------- if nargin > 1 % datfile available? % ------------------ datfile = 0; if isfield(EEG, 'datfile') if ~isempty(EEG.datfile) datfile = 1; end; end; % save data % --------- if strcmpi(varargin{1}, 'savedata') & option_storedisk error('eeg_checkset: cannot call savedata any more'); % the code below is deprecated if ~ischar(EEG.data) % not already saved disp('Writing previous dataset to disk...'); if datfile tmpdata = reshape(EEG.data, EEG.nbchan, EEG.pnts*EEG.trials); floatwrite( tmpdata', fullfile(EEG.filepath, EEG.datfile), 'ieee-le'); EEG.data = EEG.datfile; end; EEG.icaact = []; % saving dataset % -------------- filename = fullfile(EEG(1).filepath, EEG(1).filename); if ~ischar(EEG.data) & option_single, EEG.data = single(EEG.data); end; v = version; if str2num(v(1)) >= 7, save( filename, '-v6', '-mat', 'EEG'); % Matlab 7 else save( filename, '-mat', 'EEG'); end; if ~ischar(EEG.data), EEG.data = 'in set file'; end; res = sprintf('%s = eeg_checkset( %s, ''savedata'');', inputname(1), inputname(1)); end; end; end; % numerical format % ---------------- if isnumeric(EEG.data) v = version; EEG.icawinv = double(EEG.icawinv); % required for dipole fitting, otherwise it crashes EEG.icaweights = double(EEG.icaweights); EEG.icasphere = double(EEG.icasphere); if ~isempty(findstr(v, 'R11')) | ~isempty(findstr(v, 'R12')) | ~isempty(findstr(v, 'R13')) EEG.data = double(EEG.data); EEG.icaact = double(EEG.icaact); else try, if isa(EEG.data, 'double') & option_single EEG.data = single(EEG.data); EEG.icaact = single(EEG.icaact); end; catch, disp('WARNING: EEGLAB ran out of memory while converting dataset to single precision.'); disp(' Save dataset (preferably saving data to a separate file; see File > Memory options).'); disp(' Then reload it.'); end; end; end; % verify the type of the variables % -------------------------------- % data dimensions ------------------------- if isnumeric(EEG.data) && ~isempty(EEG.data) if ~isequal(size(EEG.data,1), EEG.nbchan) disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,1)) ... ') does not match the number of channels (' int2str(EEG.nbchan) '): corrected' ]); res = com; EEG.nbchan = size(EEG.data,1); end; if (ndims(EEG.data)) < 3 & (EEG.pnts > 1) if mod(size(EEG.data,2), EEG.pnts) ~= 0 if popask( [ 'eeg_checkset error: the number of frames does not divide the number of columns in the data.' 10 ... 'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the command line)']) error('eeg_checkset error: user abort'); %res = com; %EEG.pnts = size(EEG.data,2); %EEG = eeg_checkset(EEG); %return; else res = com; return; %error( 'eeg_checkset error: number of points does not divide the number of columns in data'); end; else if EEG.trials > 1 disp( 'eeg_checkset note: data array made 3-D'); res = com; end; if size(EEG.data,2) ~= EEG.pnts EEG.data = reshape(EEG.data, EEG.nbchan, EEG.pnts, size(EEG.data,2)/EEG.pnts); end; end; end; % size of data ----------- if size(EEG.data,3) ~= EEG.trials disp( ['eeg_checkset warning: 3rd dimension size of data (' int2str(size(EEG.data,3)) ... ') does not match the number of epochs (' int2str(EEG.trials) '), corrected' ]); res = com; EEG.trials = size(EEG.data,3); end; if size(EEG.data,2) ~= EEG.pnts disp( [ 'eeg_checkset warning: number of columns in data (' int2str(size(EEG.data,2)) ... ') does not match the number of points (' int2str(EEG.pnts) '): corrected' ]); res = com; EEG.pnts = size(EEG.data,2); end; end; % parameters consistency % ------------------------- if round(EEG.srate*(EEG.xmax-EEG.xmin)+1) ~= EEG.pnts fprintf( 'eeg_checkset note: upper time limit (xmax) adjusted so (xmax-xmin)*srate+1 = number of frames\n'); if EEG.srate == 0 EEG.srate = 1; end; EEG.xmax = (EEG.pnts-1)/EEG.srate+EEG.xmin; res = com; end; % deal with event arrays % ---------------------- if ~isfield(EEG, 'event'), EEG.event = []; res = com; end; if ~isempty(EEG.event) if EEG.trials > 1 & ~isfield(EEG.event, 'epoch') if popask( [ 'eeg_checkset error: the event info structure does not contain an ''epoch'' field.' ... 'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)']) error('eeg_checkset error(): user abort'); %res = com; %EEG.event = []; %EEG = eeg_checkset(EEG); %return; else res = com; return; %error('eeg_checkset error: no epoch field in event structure'); end; end; else EEG.event = []; end; if isempty(EEG.event) EEG.eventdescription = {}; end; if ~isfield(EEG, 'eventdescription') | ~iscell(EEG.eventdescription) EEG.eventdescription = cell(1, length(fieldnames(EEG.event))); res = com; else if ~isempty(EEG.event) if length(EEG.eventdescription) > length( fieldnames(EEG.event)) EEG.eventdescription = EEG.eventdescription(1:length( fieldnames(EEG.event))); elseif length(EEG.eventdescription) < length( fieldnames(EEG.event)) EEG.eventdescription(end+1:length( fieldnames(EEG.event))) = {''}; end; end; end; % create urevent if continuous data % --------------------------------- %if ~isempty(EEG.event) & ~isfield(EEG, 'urevent') % EEG.urevent = EEG.event; % disp('eeg_checkset note: creating the original event table (EEG.urevent)'); % for index = 1:length(EEG.event) % EEG.event(index).urevent = index; % end; %end; if isfield(EEG, 'urevent') & isfield(EEG.urevent, 'urevent') EEG.urevent = rmfield(EEG.urevent, 'urevent'); end; % deal with epoch arrays % ---------------------- if ~isfield(EEG, 'epoch'), EEG.epoch = []; res = com; end; % check if only one epoch % ----------------------- if EEG.trials == 1 if isfield(EEG.event, 'epoch') EEG.event = rmfield(EEG.event, 'epoch'); res = com; end; if ~isempty(EEG.epoch) EEG.epoch = []; res = com; end; end; if ~isfield(EEG, 'epochdescription'), EEG.epochdescription = {}; res = com; end; if ~isempty(EEG.epoch) if isstruct(EEG.epoch), l = length( EEG.epoch); else l = size( EEG.epoch, 2); end; if l ~= EEG.trials if popask( [ 'eeg_checkset error: the number of epoch indices in the epoch array/struct (' ... int2str(l) ') is different from the number of epochs in the data (' int2str(EEG.trials) ').' 10 ... 'Should EEGLAB attempt to abort operation ?' 10 '(press Cancel to fix the problem from the commandline)']) error('eeg_checkset error: user abort'); %res = com; %EEG.epoch = []; %EEG = eeg_checkset(EEG); %return; else res = com; return; %error('eeg_checkset error: epoch structure size invalid'); end; end; else EEG.epoch = []; end; % check ica % --------- if ~isfield(EEG, 'icachansind') if isempty(EEG.icaweights) EEG.icachansind = []; res = com; else EEG.icachansind = [1:EEG.nbchan]; res = com; end; elseif isempty(EEG.icachansind) if isempty(EEG.icaweights) EEG.icachansind = []; res = com; else EEG.icachansind = [1:EEG.nbchan]; res = com; end; end; if ~isempty(EEG.icasphere) if ~isempty(EEG.icaweights) if size(EEG.icaweights,2) ~= size(EEG.icasphere,1) if popask( [ 'eeg_checkset error: number of columns in weights array (' int2str(size(EEG.icaweights,2)) ')' 10 ... 'does not match the number of rows in the sphere array (' int2str(size(EEG.icasphere,1)) ')' 10 ... 'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)']) res = com; EEG.icasphere = []; EEG.icaweights = []; EEG = eeg_checkset(EEG); return; else error('eeg_checkset error: user abort'); res = com; return; %error('eeg_checkset error: invalid weight and sphere array sizes'); end; end; if isnumeric(EEG.data) if length(EEG.icachansind) ~= size(EEG.icasphere,2) if popask( [ 'eeg_checkset error: number of elements in ''icachansind'' (' int2str(length(EEG.icachansind)) ')' 10 ... 'does not match the number of columns in the sphere array (' int2str(size(EEG.icasphere,2)) ')' 10 ... 'Should EEGLAB remove ICA information ?' 10 '(press Cancel to fix the problem from the commandline)']) res = com; EEG.icasphere = []; EEG.icaweights = []; EEG = eeg_checkset(EEG); return; else error('eeg_checkset error: user abort'); res = com; return; %error('eeg_checkset error: invalid weight and sphere array sizes'); end; end; if isempty(EEG.icaact) | (size(EEG.icaact,1) ~= size(EEG.icaweights,1)) | (size(EEG.icaact,2) ~= size(EEG.data,2)) EEG.icaweights = double(EEG.icaweights); EEG.icawinv = double(EEG.icawinv); % scale ICA components to RMS microvolt if option_scaleicarms if ~isempty(EEG.icawinv) if mean(mean(abs(pinv(EEG.icaweights * EEG.icasphere)-EEG.icawinv))) < 0.0001 disp('Scaling components to RMS microvolt'); scaling = repmat(sqrt(mean(EEG(1).icawinv(:,:).^2))', [1 size(EEG.icaweights,2)]); EEG.etc.icaweights_beforerms = EEG.icaweights; EEG.etc.icasphere_beforerms = EEG.icasphere; EEG.icaweights = EEG.icaweights .* scaling; EEG.icawinv = pinv(EEG.icaweights * EEG.icasphere); end; end; end; if ~isempty(EEG.data) && option_computeica fprintf('eeg_checkset: recomputing the ICA activation matrix ...\n'); res = com; % Make compatible with Matlab 7 if any(isnan(EEG.data(:))) tmpdata = EEG.data(EEG.icachansind,:); fprintf('eeg_checkset: recomputing ICA ignoring NaN indices ...\n'); tmpindices = find(~sum(isnan(tmpdata))); % was: tmpindices = find(~isnan(EEG.data(1,:))); EEG.icaact = zeros(size(EEG.icaweights,1), size(tmpdata,2)); EEG.icaact(:) = NaN; EEG.icaact(:,tmpindices) = (EEG.icaweights*EEG.icasphere)*tmpdata(:,tmpindices); else EEG.icaact = (EEG.icaweights*EEG.icasphere)*EEG.data(EEG.icachansind,:); % automatically does single or double end; EEG.icaact = reshape( EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials); end; end; end; if isempty(EEG.icawinv) EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); % a priori same result as inv res = com; end; else disp( [ 'eeg_checkset warning: weights matrix cannot be empty if sphere matrix is not, correcting ...' ]); res = com; EEG.icasphere = []; end; if option_computeica if ~isempty(EEG.icaact) & ndims(EEG.icaact) < 3 & (EEG.trials > 1) disp( [ 'eeg_checkset note: independent component made 3-D' ]); res = com; EEG.icaact = reshape(EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials); end; else if ~isempty(EEG.icaact) fprintf('eeg_checkset: removing ICA activation matrix (as per edit options) ...\n'); end; EEG.icaact = []; end; else if ~isempty( EEG.icaweights ), EEG.icaweights = []; res = com; end; if ~isempty( EEG.icawinv ), EEG.icawinv = []; res = com; end; if ~isempty( EEG.icaact ), EEG.icaact = []; res = com; end; end; if isempty(EEG.icaact) EEG.icaact = []; end; % ------------- % check chanlocs % ------------- if ~isfield(EEG, 'chaninfo') EEG.chaninfo = []; end; if ~isempty( EEG.chanlocs ) % reference (use EEG structure) % --------- if ~isfield(EEG, 'ref'), EEG.ref = ''; end; if strcmpi(EEG.ref, 'averef') ref = 'average'; else ref = ''; end; if ~isfield( EEG.chanlocs, 'ref') EEG.chanlocs(1).ref = ref; end; charrefs = cellfun('isclass',{EEG.chanlocs.ref},'char'); if any(charrefs) ref = ''; end for tmpind = find(~charrefs) EEG.chanlocs(tmpind).ref = ref; end if ~isstruct( EEG.chanlocs) if exist( EEG.chanlocs ) ~= 2 disp( [ 'eeg_checkset warning: channel file does not exist or is not in Matlab path: filename removed from EEG struct' ]); EEG.chanlocs = []; res = com; else res = com; try, EEG.chanlocs = readlocs( EEG.chanlocs ); disp( [ 'eeg_checkset: channel file read' ]); catch, EEG.chanlocs = []; end; end; else if ~isfield(EEG.chanlocs,'labels') disp('eeg_checkset warning: no field label in channel location structure, removing it'); EEG.chanlocs = []; res = com; end; end; if isstruct( EEG.chanlocs) if length( EEG.chanlocs) ~= EEG.nbchan && length( EEG.chanlocs) ~= EEG.nbchan+1 && ~isempty(EEG.data) disp( [ 'eeg_checkset warning: number of channels different in data and channel file/struct: channel file/struct removed' ]); EEG.chanlocs = []; res = com; end; end; % force Nosedir to +X (done here because of DIPFIT) % ------------------- if isfield(EEG.chaninfo, 'nosedir') if strcmpi(EEG.chaninfo.nosedir, '+x') rotate = 0; elseif all(isfield(EEG.chanlocs,{'X','Y','theta','sph_theta'})) disp('EEG checkset note for expert users: Noze direction now set to default +X in EEG.chanlocs and EEG.dipfit.'); if strcmpi(EEG.chaninfo.nosedir, '+y') rotate = 270; elseif strcmpi(EEG.chaninfo.nosedir, '-x') rotate = 180; else rotate = 90; end; for index = 1:length(EEG.chanlocs) if ~isempty(EEG.chanlocs(index).theta) rotategrad = rotate/180*pi; coord = (EEG.chanlocs(index).Y + EEG.chanlocs(index).X*sqrt(-1))*exp(sqrt(-1)*-rotategrad); EEG.chanlocs(index).Y = real(coord); EEG.chanlocs(index).X = imag(coord); EEG.chanlocs(index).theta = EEG.chanlocs(index).theta -rotate; EEG.chanlocs(index).sph_theta = EEG.chanlocs(index).sph_theta+rotate; if EEG.chanlocs(index).theta <-180, EEG.chanlocs(index).theta =EEG.chanlocs(index).theta +360; end; if EEG.chanlocs(index).sph_theta>180 , EEG.chanlocs(index).sph_theta=EEG.chanlocs(index).sph_theta-360; end; end; end; if isfield(EEG, 'dipfit') if isfield(EEG.dipfit, 'coord_transform') if isempty(EEG.dipfit.coord_transform) EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1]; end; EEG.dipfit.coord_transform(6) = EEG.dipfit.coord_transform(6)+rotategrad; end; end; end; EEG.chaninfo.nosedir = '+X'; end; % general checking of channels % ---------------------------- EEG = eeg_checkchanlocs(EEG); if EEG.nbchan ~= length(EEG.chanlocs) EEG.chanlocs = []; EEG.chaninfo = []; disp('Warning: the size of the channel location structure does not match with'); disp(' number of channels. Channel information have been removed.'); end; end; EEG.chaninfo.icachansind = EEG.icachansind; % just a copy for programming convinience %if ~isfield(EEG, 'urchanlocs') % EEG.urchanlocs = EEG.chanlocs; % for index = 1:length(EEG.chanlocs) % EEG.chanlocs(index).urchan = index; % end; % disp('eeg_checkset note: creating backup chanlocs structure (urchanlocs)'); %end; % check reference % --------------- if ~isfield(EEG, 'ref') EEG.ref = 'common'; end; if ischar(EEG.ref) & strcmpi(EEG.ref, 'common') if length(EEG.chanlocs) > EEG.nbchan disp('Extra common reference electrode location detected'); EEG.ref = EEG.nbchan+1; end; end; % DIPFIT structure % ---------------- if ~isfield(EEG,'dipfit') || isempty(EEG.dipfit) EEG.dipfit = []; res = com; else try % check if dipfitdefs is present dipfitdefs; if isfield(EEG.dipfit, 'vol') & ~isfield(EEG.dipfit, 'hdmfile') if exist('pop_dipfit_settings') disp('Old DIPFIT structure detected: converting to DIPFIT 2 format'); EEG.dipfit.hdmfile = template_models(1).hdmfile; EEG.dipfit.coordformat = template_models(1).coordformat; EEG.dipfit.mrifile = template_models(1).mrifile; EEG.dipfit.chanfile = template_models(1).chanfile; EEG.dipfit.coord_transform = []; EEG.saved = 'no'; res = com; end; end; if isfield(EEG.dipfit, 'hdmfile') if length(EEG.dipfit.hdmfile) > 8 if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(1).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(1).hdmfile; end; if strcmpi(EEG.dipfit.hdmfile(end-8), template_models(2).hdmfile(end-8)), EEG.dipfit.hdmfile = template_models(2).hdmfile; end; end; if length(EEG.dipfit.mrifile) > 8 if strcmpi(EEG.dipfit.mrifile(end-8), template_models(1).mrifile(end-8)), EEG.dipfit.mrifile = template_models(1).mrifile; end; if strcmpi(EEG.dipfit.mrifile(end-8), template_models(2).mrifile(end-8)), EEG.dipfit.mrifile = template_models(2).mrifile; end; end; if length(EEG.dipfit.chanfile) > 8 if strcmpi(EEG.dipfit.chanfile(end-8), template_models(1).chanfile(end-8)), EEG.dipfit.chanfile = template_models(1).chanfile; end; if strcmpi(EEG.dipfit.chanfile(end-8), template_models(2).chanfile(end-8)), EEG.dipfit.chanfile = template_models(2).chanfile; end; end; end; if isfield(EEG.dipfit, 'coord_transform') if isempty(EEG.dipfit.coord_transform) EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1]; end; elseif ~isempty(EEG.dipfit) EEG.dipfit.coord_transform = [0 0 0 0 0 0 1 1 1]; end; catch e = lasterror; if ~strcmp(e.identifier,'MATLAB:UndefinedFunction') % if we got some error aside from dipfitdefs not being present, rethrow it rethrow(e); end end end; % check events (fast) % ------------ if isfield(EEG.event, 'type') tmpevent = EEG.event(1:min(length(EEG.event), 100)); if ~all(cellfun(@ischar, { tmpevent.type })) && ~all(cellfun(@isnumeric, { tmpevent.type })) disp('Warning: converting all event types to strings'); for ind = 1:length(EEG.event) EEG.event(ind).type = num2str(EEG.event(ind).type); end; EEG = eeg_checkset(EEG, 'eventconsistency'); end; end; % EEG.times (only for epoched datasets) % --------- if ~isfield(EEG, 'times') || isempty(EEG.times) || length(EEG.times) ~= EEG.pnts EEG.times = linspace(EEG.xmin*1000, EEG.xmax*1000, EEG.pnts); end; if ~isfield(EEG, 'history') EEG.history = ''; res = com; end; if ~isfield(EEG, 'splinefile') EEG.splinefile = ''; res = com; end; if ~isfield(EEG, 'icasplinefile') EEG.icasplinefile = ''; res = com; end; if ~isfield(EEG, 'saved') EEG.saved = 'no'; res = com; end; if ~isfield(EEG, 'subject') EEG.subject = ''; res = com; end; if ~isfield(EEG, 'condition') EEG.condition = ''; res = com; end; if ~isfield(EEG, 'group') EEG.group = ''; res = com; end; if ~isfield(EEG, 'session') EEG.session = []; res = com; end; if ~isfield(EEG, 'urchanlocs') EEG.urchanlocs = []; res = com; end; if ~isfield(EEG, 'specdata') EEG.specdata = []; res = com; end; if ~isfield(EEG, 'specicaact') EEG.specicaact = []; res = com; end; if ~isfield(EEG, 'comments') EEG.comments = ''; res = com; end; if ~isfield(EEG, 'etc' ) EEG.etc = []; res = com; end; if ~isfield(EEG, 'urevent' ) EEG.urevent = []; res = com; end; if ~isfield(EEG, 'ref') | isempty(EEG.ref) EEG.ref = 'common'; res = com; end; % create fields if absent % ----------------------- if ~isfield(EEG, 'reject') EEG.reject.rejjp = []; res = com; end; listf = { 'rejjp' 'rejkurt' 'rejmanual' 'rejthresh' 'rejconst', 'rejfreq' ... 'icarejjp' 'icarejkurt' 'icarejmanual' 'icarejthresh' 'icarejconst', 'icarejfreq'}; for index = 1:length(listf) name = listf{index}; elecfield = [name 'E']; if ~isfield(EEG.reject, elecfield), EEG.reject.(elecfield) = []; res = com; end; if ~isfield(EEG.reject, name) EEG.reject.(name) = []; res = com; elseif ~isempty(EEG.reject.(name)) && isempty(EEG.reject.(elecfield)) % check if electrode array is empty with rejection array is not nbchan = fastif(strcmp(name, 'ica'), size(EEG.icaweights,1), EEG.nbchan); EEG.reject = setfield(EEG.reject, elecfield, zeros(nbchan, length(getfield(EEG.reject, name)))); res = com; end; end; if ~isfield(EEG.reject, 'rejglobal') EEG.reject.rejglobal = []; res = com; end; if ~isfield(EEG.reject, 'rejglobalE') EEG.reject.rejglobalE = []; res = com; end; % default colors for rejection % ---------------------------- if ~isfield(EEG.reject, 'rejmanualcol') EEG.reject.rejmanualcol = [1.0000 1 0.783]; res = com; end; if ~isfield(EEG.reject, 'rejthreshcol') EEG.reject.rejthreshcol = [0.8487 1.0000 0.5008]; res = com; end; if ~isfield(EEG.reject, 'rejconstcol') EEG.reject.rejconstcol = [0.6940 1.0000 0.7008]; res = com; end; if ~isfield(EEG.reject, 'rejjpcol') EEG.reject.rejjpcol = [1.0000 0.6991 0.7537]; res = com; end; if ~isfield(EEG.reject, 'rejkurtcol') EEG.reject.rejkurtcol = [0.6880 0.7042 1.0000]; res = com; end; if ~isfield(EEG.reject, 'rejfreqcol') EEG.reject.rejfreqcol = [0.9596 0.7193 1.0000]; res = com; end; if ~isfield(EEG.reject, 'disprej') EEG.reject.disprej = { }; end; if ~isfield(EEG, 'stats') EEG.stats.jp = []; res = com; end; if ~isfield(EEG.stats, 'jp') EEG.stats.jp = []; res = com; end; if ~isfield(EEG.stats, 'jpE') EEG.stats.jpE = []; res = com; end; if ~isfield(EEG.stats, 'icajp') EEG.stats.icajp = []; res = com; end; if ~isfield(EEG.stats, 'icajpE') EEG.stats.icajpE = []; res = com; end; if ~isfield(EEG.stats, 'kurt') EEG.stats.kurt = []; res = com; end; if ~isfield(EEG.stats, 'kurtE') EEG.stats.kurtE = []; res = com; end; if ~isfield(EEG.stats, 'icakurt') EEG.stats.icakurt = []; res = com; end; if ~isfield(EEG.stats, 'icakurtE') EEG.stats.icakurtE = []; res = com; end; % component rejection % ------------------- if ~isfield(EEG.stats, 'compenta') EEG.stats.compenta = []; res = com; end; if ~isfield(EEG.stats, 'compentr') EEG.stats.compentr = []; res = com; end; if ~isfield(EEG.stats, 'compkurta') EEG.stats.compkurta = []; res = com; end; if ~isfield(EEG.stats, 'compkurtr') EEG.stats.compkurtr = []; res = com; end; if ~isfield(EEG.stats, 'compkurtdist') EEG.stats.compkurtdist = []; res = com; end; if ~isfield(EEG.reject, 'threshold') EEG.reject.threshold = [0.8 0.8 0.8]; res = com; end; if ~isfield(EEG.reject, 'threshentropy') EEG.reject.threshentropy = 600; res = com; end; if ~isfield(EEG.reject, 'threshkurtact') EEG.reject.threshkurtact = 600; res = com; end; if ~isfield(EEG.reject, 'threshkurtdist') EEG.reject.threshkurtdist = 600; res = com; end; if ~isfield(EEG.reject, 'gcompreject') EEG.reject.gcompreject = []; res = com; end; if length(EEG.reject.gcompreject) ~= size(EEG.icaweights,1) EEG.reject.gcompreject = zeros(1, size(EEG.icaweights,1)); end; % remove old fields % ----------------- if isfield(EEG, 'averef'), EEG = rmfield(EEG, 'averef'); end; if isfield(EEG, 'rt' ), EEG = rmfield(EEG, 'rt'); end; % store in new structure % ---------------------- if isstruct(EEG) if ~exist('ALLEEGNEW','var') ALLEEGNEW = EEG; else ALLEEGNEW(inddataset) = EEG; end; end; end; % recorder fields % --------------- fieldorder = { 'setname' ... 'filename' ... 'filepath' ... 'subject' ... 'group' ... 'condition' ... 'session' ... 'comments' ... 'nbchan' ... 'trials' ... 'pnts' ... 'srate' ... 'xmin' ... 'xmax' ... 'times' ... 'data' ... 'icaact' ... 'icawinv' ... 'icasphere' ... 'icaweights' ... 'icachansind' ... 'chanlocs' ... 'urchanlocs' ... 'chaninfo' ... 'ref' ... 'event' ... 'urevent' ... 'eventdescription' ... 'epoch' ... 'epochdescription' ... 'reject' ... 'stats' ... 'specdata' ... 'specicaact' ... 'splinefile' ... 'icasplinefile' ... 'dipfit' ... 'history' ... 'saved' ... 'etc' }; for fcell = fieldnames(EEG)' fname = fcell{1}; if ~any(strcmp(fieldorder,fname)) fieldorder{end+1} = fname; end end try ALLEEGNEW = orderfields(ALLEEGNEW, fieldorder); EEG = ALLEEGNEW; catch disp('Couldn''t order data set fields properly.'); end; if exist('ALLEEGNEW','var') EEG = ALLEEGNEW; end; if ~isa(EEG, 'eegobj') && option_eegobject EEG = eegobj(EEG); end; return; function num = popask( text ) ButtonName=questdlg2( text, ... 'Confirmation', 'Cancel', 'Yes','Yes'); switch lower(ButtonName), case 'cancel', num = 0; case 'yes', num = 1; end; function res = mycellfun(com, vals, classtype); res = zeros(1, length(vals)); switch com case 'isempty', for index = 1:length(vals), res(index) = isempty(vals{index}); end; case 'isclass' if strcmp(classtype, 'double') for index = 1:length(vals), res(index) = isnumeric(vals{index}); end; else error('unknown cellfun command'); end; otherwise error('unknown cellfun command'); end;
github
ZijingMao/baselineeegtest-master
ismember_bc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/ismember_bc.m
711
utf_8
565a06126820e316b2bf233d652bf24c
% ismember_bc - ismember backward compatible with Matlab versions prior to 2013a function [C,IA] = ismember_bc(A,B,varargin); errorFlag = error_bc; v = version; indp = find(v == '.'); v = str2num(v(1:indp(2)-1)); if v > 7.19, v = floor(v) + rem(v,1)/10; end; if nargin > 2 ind = strmatch('legacy', varargin); if ~isempty(ind) varargin(ind) = []; end; end; if v >= 7.14 [C,IA] = ismember(A,B,varargin{:},'legacy'); if errorFlag [C2,IA2] = ismember(A,B,varargin{:}); if (~isequal(C, C2) || ~isequal(IA, IA2)) warning('backward compatibility issue with call to ismember function'); end; end; else [C,IA] = ismember(A,B,varargin{:}); end;
github
ZijingMao/baselineeegtest-master
intersect_bc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/intersect_bc.m
752
utf_8
72bc774f899f5fb5e3b75d2c1ef99049
% intersect_bc - intersect backward compatible with Matlab versions prior to 2013a function [C,IA,IB] = intersect_bc(A,B,varargin); errorFlag = error_bc; v = version; indp = find(v == '.'); v = str2num(v(1:indp(2)-1)); if v > 7.19, v = floor(v) + rem(v,1)/10; end; if nargin > 2 ind = strmatch('legacy', varargin); if ~isempty(ind) varargin(ind) = []; end; end; if v >= 7.14 [C,IA,IB] = intersect(A,B,varargin{:},'legacy'); if errorFlag [C2,IA2,IB2] = intersect(A,B,varargin{:}); if (~isequal(C, C2) || ~isequal(IA, IA2) || ~isequal(IB, IB2)) warning('backward compatibility issue with call to intersect function'); end; end; else [C,IA,IB] = intersect(A,B,varargin{:}); end;
github
ZijingMao/baselineeegtest-master
plugin_getweb.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/plugin_getweb.m
6,337
utf_8
d6ad7bd9e33713cfe1317b4e55cd3c3f
function plugin = plugin_getweb(type, pluginOri, mode) if nargin < 1, help plugin_getweb; return; end; if nargin < 2, pluginOri = []; end; if nargin < 3, mode = 'merge'; end; % 'merge' or 'newlist' % convert plugin list format if necessary if isfield(pluginOri, 'plugin'), pluginOri = plugin_convert(pluginOri); end; try disp( [ 'Retreiving URL with ' type ' extensions...' ] ); if strcmpi(type, 'import') [tmp status] = plugin_urlread('http://sccn.ucsd.edu/wiki/Plugin_list_import'); else [tmp status] = plugin_urlread('http://sccn.ucsd.edu/wiki/Plugin_list_process'); end; catch, error('Cannot connect to the Internet to retrieve extension list'); end; % retreiving download statistics try disp( [ 'Retreiving download statistics...' ] ); [stats status] = plugin_urlread('http://sccn.ucsd.edu/eeglab/plugin_uploader/plugin_getcountall.php'); stats = textscan(stats, '%s%d%s%s'); catch, stats = {}; disp('Cannot connect to the Internet to retrieve statistics for extensions'); end; if status == 0 error('Cannot connect to the Internet to retrieve extension list'); end; % parse the web page % ------------------ try plugin = parseTable(tmp); catch error('Cannot parse extension list - please contact [email protected]'); end; % find correspondance with plugin list % ------------------------------------ if ~isempty(pluginOri) currentNames = lower({ pluginOri.name }); else currentNames = {}; end; allMatch = []; for iRow = 1:length(plugin) % fix links if isfield(plugin, 'zip'), plugin(iRow).zip = strrep(plugin(iRow).zip, '&amp;', '&'); end; % get number of downloads if ~isempty(stats) indMatch = strmatch(plugin(iRow).name, stats{1}, 'exact'); if ~isempty(indMatch) plugin(iRow).downloads = stats{2}(indMatch(1)); if length(stats) > 2 && ~isempty(stats{3}{indMatch(1)}) plugin(iRow).version = stats{3}{indMatch(1)}; plugin(iRow).zip = stats{4}{indMatch(1)}; end; else plugin(iRow).downloads = 0; end; else plugin(iRow).downloads = 0; end; % match with existiting plugins indMatch = strmatch(lower(plugin(iRow).name), currentNames, 'exact'); if isempty(indMatch) plugin(iRow).currentversion = '-'; plugin(iRow).installed = 0; plugin(iRow).installorupdate = 1; plugin(iRow).status = 'notinstalled'; else if length(indMatch) > 1 disp([ 'Warning: duplicate extension ' plugin(iRow).name ' instaled' ]); end; plugin(iRow).currentversion = pluginOri(indMatch).currentversion; plugin(iRow).foldername = pluginOri(indMatch).foldername; plugin(iRow).status = pluginOri(indMatch).status; plugin(iRow).installed = 1; if strcmpi(plugin(iRow).currentversion, plugin(iRow).version) plugin(iRow).installorupdate = 0; else plugin(iRow).installorupdate = 1; end; allMatch = [ allMatch indMatch(:)' ]; end; end; % put all the installed plugins first % ----------------------------------- if ~isempty(plugin) [tmp reorder] = sort([plugin.installed], 'descend'); plugin = plugin(reorder); % plugin(1).currentversion = '0.9'; % plugin(1).version = '1'; % plugin(1).foldername = 'test'; % plugin(1).installed = 1; % plugin(1).installorupdate = 1; % plugin(1).description = 'test'; % plugin(1).webdoc = 'test'; % plugin(1).name = 'test'; end; if strcmpi(mode, 'merge') && ~isempty(pluginOri) indices = setdiff([1:length(pluginOri)], allMatch); fields = fieldnames(pluginOri); lenPlugin = length(plugin); for indPlugin = 1:length(indices) for indField = 1:length(fields) value = getfield(pluginOri, { indices(indPlugin) }, fields{ indField }); plugin = setfield(plugin , { lenPlugin+indPlugin }, fields{ indField }, value); end; end; end; % parse the web table % =================== function plugin = parseTable(tmp); plugin = []; if isempty(tmp), return; end; % get table content % ----------------- tableBeg = findstr('Plug-in name', tmp); tableEnd = findstr('</table>', tmp(tableBeg:end)); tableContent = tmp(tableBeg:tableBeg+tableEnd-2); endFirstLine = findstr('</tr>', tableContent); tableContent = tableContent(endFirstLine(1)+5:end); % parse table entries % ------------------- posBegRow = findstr('<tr>' , tableContent); posEndRow = findstr('</tr>', tableContent); if length(posBegRow) ~= length(posEndRow) || isempty(posBegRow) error('Cannot connect to the Internet to retrieve plugin list'); end; for iRow = 1:length(posBegRow) rowContent = tableContent(posBegRow(iRow)+4:posEndRow(iRow)-1); posBegCol = findstr('<td>' , rowContent); posEndCol = findstr('</td>', rowContent); for iCol = 1:length(posBegCol) table{iRow,iCol} = rowContent(posBegCol(iCol)+4:posEndCol(iCol)-1); end; end; %% extract zip link and plugin name from first column % -------------------------------------------------- %href="http://www.unicog.org/pm/uploads/MEG/ADJUST_PLUGIN.zip" class="external text" title="http://www.unicog.org/pm/uploads/MEG/ADJUST_PLUGIN.zip" rel="nofollow">ADJUST PLUGIN</a></td for iRow = 1:size(table,1) % get link [plugin(iRow).name plugin(iRow).webdoc] = parsehttplink(table{iRow,1}); plugin(iRow).version = table{iRow,2}; tmp = deblank(table{iRow,3}(end:-1:1)); plugin(iRow).description = deblank(tmp(end:-1:1)); [tmp plugin(iRow).zip] = parsehttplink(table{iRow,4}); end; function [txt link] = parsehttplink(currentRow) openTag = find(currentRow == '<'); closeTag = find(currentRow == '>'); if isempty(openTag) link = ''; txt = currentRow; else % parse link link = currentRow(openTag(1)+1:closeTag(1)-1); hrefpos = findstr('href', link); link = link(hrefpos:end); quoteInd = find(link == '"'); link = link(quoteInd(1)+1:quoteInd(2)-1); for iTag = length(openTag):-1:1 currentRow(openTag(iTag):closeTag(iTag)) = []; end; txt = currentRow; end;
github
ZijingMao/baselineeegtest-master
eeg_checkchanlocs.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeg_checkchanlocs.m
8,655
utf_8
2664c683e10493731ebda7dfec52968f
% eeg_checkchanlocs() - Check the consistency of the channel locations structure % of an EEGLAB dataset. % % Usage: % >> EEG = eeg_checkchanlocs( EEG, 'key1', value1, 'key2', value2, ... ); % >> [chanlocs chaninfo] = eeg_checkchanlocs( chanlocs, chaninfo, 'key1', value1, 'key2', value2, ... ); % % Inputs: % EEG - EEG dataset % chanlocs - EEG.chanlocs structure % chaninfo - EEG.chaninfo structure % % Outputs: % EEG - new EEGLAB dataset with updated channel location structures % EEG.chanlocs, EEG.urchanlocs, EEG.chaninfo % chanlocs - updated channel location structure % chaninfo - updated chaninfo structure % % Author: Arnaud Delorme, SCCN/INC/UCSD, March 2, 2011 % Copyright (C) SCCN/INC/UCSD, March 2, 2011, [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 % Hey Arno -- this is a quick fix to make an analysis work for Makoto % I think the old version had a bug... function [chans, chaninfo, chanedit]= eeg_checkchanlocs(chans, chaninfo); if nargin < 1 help eeg_checkchanlocs; return; end; if nargin < 2 chaninfo = []; end; processingEEGstruct = 0; if isfield(chans, 'data') processingEEGstruct = 1; tmpEEG = chans; chans = tmpEEG.chanlocs; chaninfo = tmpEEG.chaninfo; end; if ~isfield(chans, 'datachan') [chanedit,dummy,complicated] = insertchans(chans, chaninfo); else chanedit = chans; complicated = true; end; nosevals = { '+X' '-X' '+Y' '-Y' }; if ~isfield(chaninfo, 'plotrad'), chaninfo.plotrad = []; end; if ~isfield(chaninfo, 'shrink'), chaninfo.shrink = []; end; if ~isfield(chaninfo, 'nosedir'), chaninfo.nosedir = nosevals{1}; end; % handles deprecated fields % ------------------------- plotrad = []; if isfield(chanedit, 'plotrad'), plotrad = chanedit(1).plotrad; chanedit = rmfield(chanedit, 'plotrad'); if isstr(plotrad) & ~isempty(str2num(plotrad)), plotrad = str2num(plotrad); end; chaninfo.plotrad = plotrad; end; if isfield(chanedit, 'shrink') && ~isempty(chanedit(1).shrink) shrinkorskirt = 1; if ~isstr(chanedit(1).shrink) plotrad = 0.5/(1-chanedit(1).shrink); % convert old values end; chanedit = rmfield(chanedit, 'shrink'); chaninfo.plotrad = plotrad; end; % set non-existent fields to [] % ----------------------------- fields = { 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' 'sph_radius' 'type' 'ref' 'urchan' }; fieldtype = { 'str' 'num' 'num' 'num' 'num' 'num' 'num' 'num' 'num' 'str' 'str' 'num' }; check_newfields = true; %length(fieldnames(chanedit)) < length(fields); if ~isempty(chanedit) for index = 1:length(fields) if check_newfields && ~isfield(chanedit, fields{index}) % new field % --------- if strcmpi(fieldtype{index}, 'num') chanedit = setfield(chanedit, {1}, fields{index}, []); else for indchan = 1:length(chanedit) chanedit = setfield(chanedit, {indchan}, fields{index}, ''); end; end; else % existing fields % --------------- allvals = {chanedit.(fields{index})}; if strcmpi(fieldtype{index}, 'num') if ~all(cellfun('isclass',allvals,'double')) numok = cellfun(@isnumeric, allvals); if any(numok == 0) for indConvert = find(numok == 0) chanedit = setfield(chanedit, {indConvert}, fields{index}, []); end; end; end else strok = cellfun('isclass', allvals,'char'); if strcmpi(fields{index}, 'labels'), prefix = 'E'; else prefix = ''; end; if any(strok == 0) for indConvert = find(strok == 0) try strval = [ prefix num2str(getfield(chanedit, {indConvert}, fields{index})) ]; chanedit = setfield(chanedit, {indConvert}, fields{index}, strval); catch chanedit = setfield(chanedit, {indConvert}, fields{index}, ''); end; end; end; end; end; end; end; if ~isequal(fieldnames(chanedit)',fields) try chanedit = orderfields(chanedit, fields); catch, end; end % check if duplicate channel label % -------------------------------- if isfield(chanedit, 'labels') tmp = sort({chanedit.labels}); if any(strcmp(tmp(1:end-1),tmp(2:end))) disp('Warning: some channels have the same label'); end end; % check for empty channel label % ----------------------------- if isfield(chanedit, 'labels') indEmpty = find(cellfun(@isempty, {chanedit.labels})); if ~isempty(indEmpty) tmpWarning = warning('backtrace'); warning backtrace off; warning('channel labels should not be empty, creating unique labels'); warning(tmpWarning); for index = indEmpty chanedit(index).labels = sprintf('E%d', index); end; end; end; % remove fields % ------------- if isfield(chanedit, 'sph_phi_besa' ), chanedit = rmfield(chanedit, 'sph_phi_besa'); end; if isfield(chanedit, 'sph_theta_besa'), chanedit = rmfield(chanedit, 'sph_theta_besa'); end; % reconstruct the chans structure % ------------------------------- if complicated [chans chaninfo.nodatchans] = getnodatchan( chanedit ); if ~isfield(chaninfo, 'nodatchans'), chaninfo.nodatchans = []; end; if isempty(chanedit) for iField = 1:length(fields) chanedit = setfield(chanedit, fields{iField}, []); end; end; else chans = rmfield(chanedit,'datachan'); chaninfo.nodatchans = []; end if processingEEGstruct tmpEEG.chanlocs = chans; tmpEEG.chaninfo = chaninfo; chans = tmpEEG; end; % --------------------------------------------- % separate data channels from non-data channels % --------------------------------------------- function [chans, fidsval] = getnodatchan(chans) if isfield(chans,'datachan') [chans(cellfun('isempty',{chans.datachan})).datachan] = deal(0); fids = [chans.datachan] == 0; fidsval = chans(fids); chans = rmfield(chans(~fids),'datachan'); else fids = []; end; % ---------------------------------------- % fuse data channels and non-data channels % ---------------------------------------- function [chans, chaninfo,complicated] = insertchans(chans, chaninfo, nchans) if nargin < 3, nchans = length(chans); end; [chans.datachan] = deal(1); complicated = false; % whether we need complicated treatment of datachans & co further down the road..... if isfield(chans,'type') mask = strcmpi({chans.type},'FID') | strcmpi({chans.type},'IGNORE'); if any(mask) [chans(mask).datachan] = deal(0); complicated = true; end end if length(chans) > nchans & nchans ~= 0 % reference at the end of the structure chans(end).datachan = 0; complicated = true; end; if isfield(chaninfo, 'nodatchans') if ~isempty(chaninfo.nodatchans) && isstruct(chaninfo.nodatchans) chanlen = length(chans); for index = 1:length(chaninfo.nodatchans) fields = fieldnames( chaninfo.nodatchans ); ind = chanlen+index; for f = 1:length( fields ) chans = setfield(chans, { ind }, fields{f}, getfield( chaninfo.nodatchans, { index }, fields{f})); end; chans(ind).datachan = 0; complicated = true; end; chaninfo = rmfield(chaninfo, 'nodatchans'); % put these channels first % ------------------------ % tmp = chans(chanlen+1:end); % chans(length(tmp)+1:end) = chans(1:end-length(tmp)); % chans(1:length(tmp)) = tmp; end; end;
github
ZijingMao/baselineeegtest-master
pop_editoptions.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/pop_editoptions.m
12,328
utf_8
640ce0d9927c2f7fa8fc7e1955a0c98e
% pop_editoptions() - Edit memory-saving eeglab() options. These are stored in % a file 'eeg_options.m'. With no argument, pop up a window % to allow the user to set/unset these options. Store % user choices in a new 'eeg_options.m' file in the % working directory. % % Usage: >> pop_editoptions; % >> pop_editoptions( 'key1', value1, 'key2', value2, ...); % % Graphic interface inputs: % "If set, keep at most one dataset in memory ..." - [checkbox] If set, EEGLAB will only retain the current % dataset in memory. All other datasets will be automatically % read and writen to disk. All EEGLAB functionalities are preserved % even for dataset stored on disk. % "If set, write data in same file as dataset ..." - [checkbox] Set -> dataset data (EEG.data) are % saved in the EEG structure in the standard Matlab dataset (.set) file. % Unset -> The EEG.data are saved as a transposed stream of 32-bit % floats in a separate binary file. As of Matlab 4.51, the order % of the data in the binary file is as in the transpose of EEG.data % (i.e., as in EEG.data', frames by channels). This allows quick % reading of single channels from the data, e.g. when comparing % channels across datasets. The stored files have the extension % .dat instead of the pre-4.51, non-transposed .fdt. Both file types % are read by the dataset load function. Command line equivalent is % option_savematlab. % "Precompute ICA activations" - [checkbox] If set, all the ICA activation % time courses are precomputed (this requires more RAM). % Command line equivalent: option_computeica. % "If set, remember old folder when reading dataset" - [checkbox] this option % is convinient if the file you are working on are not in the % current folder. % % Commandline keywords: % 'option_computeica' - [0|1] If 1, compute the ICA component activitations and % store them in a new variable. If 0, compute ICA activations % only when needed (& only partially, if possible) and do not % store the results). % NOTE: Turn OFF the options above when working with very large datasets or on % computers with limited memory. % 'option_savematlab' - [0|1] If 1, datasets are saved as single Matlab .set files. % If 0, dataset data are saved in separate 32-bit binary float % .dat files. See the corresponding GUI option above for details. % Outputs: % In the output workspace, variables 'option_computeica', % and 'option_savematlab' are updated, and a new 'eeg_options.m' file may be % written to the working directory. The copy of 'eeg_options.m' placed in your % working directory overwrites system defaults whenever EEGLAB operates in this % directory (assuming your working directory is in your MATLABPATH - see path()). % To adjust these options system-wide, edit the master "eeg_options.m" file in the % EEGLAB directory heirarchy. % % Author: Arnaud Delorme, SCCN / INC / UCSD, March 2002 % % See also: eeg_options(), eeg_readoptions() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 09 March 2002, [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_editoptions(varargin); com = ''; datasets_in_memory = 0; if nargin > 0 if ~isstr(varargin{1}) datasets_in_memory = varargin{1}; varargin = {}; end; end; % parse the eeg_options file % ---------------------------- eeglab_options; if iseeglabdeployed filename = fullfile(eeglabexefolder,'eeg_options.txt'); eegoptionbackup = fullfile(eeglabexefolder,'eeg_optionsbackup.txt'); else % folder for eeg_options file (also update the eeglab_options) if ~isempty(EEGOPTION_PATH) homefolder = EEGOPTION_PATH; elseif ispc if ~exist('evalc'), eval('evalc = @(x)(eval(x));'); end; homefolder = deblank(evalc('!echo %USERPROFILE%')); else homefolder = '~'; end; filename = fullfile(homefolder, 'eeg_options.m'); eegoptionbackup = which('eeg_optionsbackup.m'); end; fid = fopen( filename, 'r+'); % existing file storelocal = 0; if fid == -1 filepath = homefolder; filename = 'eeg_options.m'; fid = fopen( fullfile(filepath, filename), 'w'); % new file possible? if fid == -1 error([ 'Cannot write into HOME folder: ' homefolder 10 'You may specify another folder for the eeg_option.m' 10 'file by editing the icadefs.m file' ]); end; fclose(fid); delete(fullfile(filepath, filename)); % read variables values and description % -------------------------------------- [ header opt ] = eeg_readoptions( eegoptionbackup ); else [filepath filename ext] = fileparts(filename); filename = [ filename ext ]; fprintf('Using option file in directory %s\n', filepath); % read variables values and description % -------------------------------------- [ header opt ] = eeg_readoptions( eegoptionbackup ); [ header opt ] = eeg_readoptions( fid, opt ); % use opt from above as default end; if nargin < 2 geometry = { [6 1] }; tmpfile = fullfile(filepath, filename); cb_file = [ '[filename, filepath] = uiputfile(''eeg_options.txt'', ''Pick a folder to save option file'');' ... 'if filename(1) ~= 0,' ... ' filepath = fullfile(filepath, ''eeg_options.m'');' ... ' set(gcf, ''userdata'', filepath);' ... ' if length(filepath) > 100,' ... ' filepath = [ ''...'' filepath(end-100:end) ];' ... ' end;' ... ' set(findobj(gcf, ''tag'', ''filename''), ''string'', filepath);' ... 'end;' ... 'clear filepath;' ]; uilist = { ... { 'Style', 'text', 'string', '', 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', 'Set/Unset', 'fontweight', 'bold' } }; % add all fields to graphic interface % ----------------------------------- for index = 1:length(opt) % format the description to fit a help box % ---------------------------------------- descrip = { 'string', opt(index).description }; % strmultiline(description{ index }, 80, 10) }; % create the gui for this variable % -------------------------------- geometry = { geometry{:} [4 0.3 0.1] }; if strcmpi(opt(index).varname, 'option_storedisk') & datasets_in_memory cb_nomodif = [ 'set(gcbo, ''value'', ~get(gcbo, ''value''));' ... 'warndlg2(strvcat(''This option may only be modified when at most one dataset is stored in memory.''));' ]; elseif strcmpi(opt(index).varname, 'option_memmapdata') cb_nomodif = [ 'if get(gcbo, ''value''), warndlg2(strvcat(''Matlab memory is beta, use at your own risk'')); end;' ]; elseif strcmpi(opt(index).varname, 'option_donotusetoolboxes') cb_nomodif = [ 'if get(gcbo, ''value''), warndlg2([''You have selected the option to disable'' 10 ''Matlab toolboxes. Use with caution.'' 10 ''Matlab toolboxes will be removed from'' 10 ''your path. Unlicking this option later will not'' 10 ''add back the toolboxes. You will need'' 10 ''to add them back manually. If you are unsure'' 10 ''if you want to disable Matlab toolboxes'' 10 ''deselect the option now.'' ]); end;' ]; else cb_nomodif = ''; end; if ~isempty(opt(index).value) uilist = { uilist{:}, { 'Style', 'text', descrip{:}, 'horizontalalignment', 'left' }, ... { 'Style', 'checkbox', 'string', ' ', 'value', opt(index).value 'callback' cb_nomodif } { } }; else uilist = { uilist{:}, { 'Style', 'text', descrip{:}, 'fontweight' 'bold', 'horizontalalignment', 'left' }, ... { } { } }; end; end; % change option file uilist = { uilist{:} {} ... { 'Style', 'text', 'string', 'Option file:' 'fontweight', 'bold' }, ... { 'Style', 'text', 'string', tmpfile 'tag' 'filename' }, ... {} { 'Style', 'pushbutton', 'string', '...' 'callback' cb_file } }; geometry = { geometry{:} [1] [1 6 0.1 0.8] }; [results userdat ] = inputgui( geometry, uilist, 'pophelp(''pop_editoptions'');', 'Memory options - pop_editoptions()', ... [], 'normal'); if ~isempty(userdat) filepath = fileparts(userdat); args = { 'filename' filename }; end; if length(results) == 0, return; end; % decode inputs % ------------- args = {}; count = 1; for index = 1:length(opt) if ~isempty(opt(index).varname) args = { args{:}, opt(index).varname, results{count} }; count = count+1; end; end; else % no interactive inputs % --------------------- args = varargin; end; % change default folder option % ---------------------------- W_MAIN = findobj('tag', 'EEGLAB'); if ~isempty(W_MAIN) tmpuserdata = get(W_MAIN, 'userdata'); tmpuserdata{3} = filepath; set(W_MAIN, 'userdata', tmpuserdata); end; % decode inputs % ------------- for index = 1:2:length(args) ind = strmatch(args{index}, { opt.varname }, 'exact'); if isempty(ind) if strcmpi(args{index}, 'option_savematlab') disp('pop_editoptions: option_savematlab is obsolete, use option_savetwofiles instead'); ind = strmatch('option_savetwofiles', { opt.varname }, 'exact'); opt(ind).value = ~args{index+1}; else error(['Variable name ''' args{index} ''' is invalid']); end; else opt(ind).value = args{index+1}; end; end; % write to eeg_options file % ------------------------- fid = fopen( fullfile(filepath, filename), 'w'); addpath(filepath); if fid == -1 error('File writing error, check writing permission'); end; fprintf(fid, '%s\n', header); for index = 1:length(opt) if isempty(opt(index).varname) fprintf( fid, '%% %s\n', opt(index).description); else fprintf( fid, '%s = %d ; %% %s\n', opt(index).varname, opt(index).value, opt(index).description); end; end; fclose(fid); % clear it from the MATLAB function cache clear(fullfile(filepath,filename)); % generate the output text command % -------------------------------- com = 'pop_editoptions('; for index = 1:2:length(args) com = sprintf( '%s ''%s'', %d,', com, args{index}, args{index+1}); end; com = [com(1:end-1) ');']; clear functions % --------------------------- function chopedtext = choptext( tmptext ) chopedtext = ''; while length(tmptext) > 30 blanks = findstr( tmptext, ' '); [tmp I] = min( abs(blanks - 30) ); chopedtext = [ chopedtext ''' 10 ''' tmptext(1:blanks(I)) ]; tmptext = tmptext(blanks(I)+1:end); end; chopedtext = [ chopedtext ''' 10 ''' tmptext]; chopedtext = chopedtext(7:end); return; function num = popask( text ) ButtonName=questdlg2( text, ... 'Confirmation', 'Cancel', 'Yes','Yes'); switch lower(ButtonName), case 'cancel', num = 0; case 'yes', num = 1; end;
github
ZijingMao/baselineeegtest-master
pop_delset.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/pop_delset.m
2,422
utf_8
44b38052f003e12e39320b5613f097ae
% pop_delset() - Delete a dataset from the variable containing % all datasets. % % Usage: >> ALLEEG = pop_delset(ALLEEG, indices); % % Inputs: % ALLEEG - array of EEG datasets % indices - indices of datasets to delete. None -> a pop_up window asks % the user to choose. Index < 0 -> it's positive is given as % the default in the pop-up window (ex: -3 -> default 3). % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: pop_copyset(), eeglab() % Copyright (C) 2001 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 % load a set and store it in the current set % ------------------------------------------ function [ALLSET, command] = pop_delset(ALLSET, set_in); command = ''; if nargin < 1 help pop_delset; return; end; if isempty( ALLSET ) error('Cannot delete dataset. Restart eeglab to clear all dataset information'); return; end; if nargin < 2 | set_in < 0 % which set to delete % ----------------- promptstr = { 'Dataset(s) to delete:' }; if nargin == 2 inistr = { int2str(-set_in) }; else inistr = { '1' }; end; result = inputdlg2( promptstr, 'Delete dataset -- pop_delset()', 1, inistr, 'pop_delset'); size_result = size( result ); if size_result(1) == 0 return; end; set_in = eval( [ '[' result{1} ']' ] ); end; if isempty(set_in) return; end; A = fieldnames( ALLSET ); A(:,2) = cell(size(A)); A = A'; for i = set_in try ALLSET(i) = struct(A{:}); %ALLSET = setfield(ALLSET, {set_in}, A{:}, cell(size(A))); catch error('Error: no such dataset'); return; end; end; command = sprintf('%s = pop_delset( %s, [%s] );', inputname(1), inputname(1), int2str(set_in)); return;
github
ZijingMao/baselineeegtest-master
pop_rejmenu.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/pop_rejmenu.m
23,728
utf_8
6acbdd38985f06d47dd90f857a5d8679
% pop_rejmenu() - Main menu for rejecting trials in an EEG dataset % % Usage: >> pop_rejmenu(INEEG, typerej); % % Inputs: % INEEG - input dataset % typerej - data to reject on (0 = component activations; % 1 = raw electrode data). {Default: 1 = reject on raw data} % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab(), pop_eegplot(), pop_eegthresh, pop_rejtrend() % pop_rejkurt(), pop_jointprob(), pop_rejspec() % Copyright (C) 2001 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 pop_rejmenu( EEG, icacomp ); if icacomp == 0 if isempty( EEG.icasphere ) disp('Error: you must first run ICA on the data'); return; end; end; if icacomp == 1 rejtitle = 'Reject trials using data statistics - pop_rejmenu()'; tagmenu = 'rejtrialraw'; else rejtitle = 'Reject trials using component activity statistics - pop_rejmenu()'; tagmenu = 'rejtrialica'; end; if ~isempty( findobj('tag', tagmenu)) error('cannot open two identical windows; close the first one first'); end; figure('visible', 'off', 'numbertitle', 'off', 'name', rejtitle, 'tag', tagmenu); % definition of callbacks % ----------------------- checkstatus = [ 'rejstatus = get( findobj(''parent'', gcbf, ''tag'', ''rejstatus''), ''value'');' ... 'if rejstatus == 3,' ... ' EEG.reject.disprej = {};' ... ' if get( findobj(''parent'', gcbf, ''tag'', ''IManual''), ''value''), EEG.reject.disprej{1} = ''manual''; end;' ... ' if get( findobj(''parent'', gcbf, ''tag'', ''IThresh''), ''value''), EEG.reject.disprej{2} = ''thresh''; end;' ... ' if get( findobj(''parent'', gcbf, ''tag'', ''IConst''), ''value''), EEG.reject.disprej{3} = ''const''; end;' ... ' if get( findobj(''parent'', gcbf, ''tag'', ''IEnt''), ''value''), EEG.reject.disprej{4} = ''jp''; end;' ... ' if get( findobj(''parent'', gcbf, ''tag'', ''IKurt''), ''value''), EEG.reject.disprej{5} = ''kurt''; end;' ... ' if get( findobj(''parent'', gcbf, ''tag'', ''IFreq''), ''value''), EEG.reject.disprej{6} = ''freq''; end;' ... 'end;' ... 'rejstatus = rejstatus-1;' ]; % from 1-3 range, go to 0-2 range if icacomp, ICAPREFIX = ''; else ICAPREFIX = 'ica'; end; % tmp_comall is used when returning from eegplot tmp_comall = [ 'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ... '''''), ''''tag'''', ''''mantrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejmanual)));' ... 'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ... '''''), ''''tag'''', ''''threshtrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejthresh)));' ... 'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ... '''''), ''''tag'''', ''''freqtrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejfreq)));' ... 'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ... '''''), ''''tag'''', ''''consttrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejconst)));' ... 'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ... '''''), ''''tag'''', ''''enttrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejjp)));' ... 'set(findobj(''''parent'''', findobj(''''tag'''', ''''' tagmenu ... '''''), ''''tag'''', ''''kurttrial''''), ''''string'''', num2str(sum(EEG.reject.' ICAPREFIX 'rejkurt)));' ]; cb_manual = [ checkstatus ... 'pop_eegplot( EEG, ' int2str( icacomp ) ', rejstatus, 0,''' tmp_comall ''');' ... 'clear rejstatus;' ]; % ----------------------------------------------------- cb_compthresh = [ ' posthresh = get( findobj(''parent'', gcbf, ''tag'', ''threshpos''), ''string'' );' ... ' negthresh = get( findobj(''parent'', gcbf, ''tag'', ''threshneg''), ''string'' );' ... ' startime = get( findobj(''parent'', gcbf, ''tag'', ''threshstart''), ''string'' );' ... ' endtime = get( findobj(''parent'', gcbf, ''tag'', ''threshend''), ''string'' );' ... ' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''threshelec''), ''string'' );' ... checkstatus ... '[EEG Itmp LASTCOM] = pop_eegthresh( EEG,' int2str(icacomp) ... ', elecrange, negthresh, posthresh, str2num(startime)/1000, str2num(endtime)/1000, rejstatus, 0,''' tmp_comall ''');' ... 'EEG = eegh(LASTCOM, EEG);' ... 'clear com Itmp elecrange posthresh negthresh startime endtime rejstatus;' ]; % ' set(findobj(''parent'', gcbf, ''tag'', ''threshtrial''), ''string'', num2str(EEG.trials - length(Itmp)));' ... % 'eegh(LASTCOM);' ... % 'clear Itmp elecrange posthresh negthresh startime endtime rejstatus;' ]; % ----------------------------------------------------- cb_compfreq = [ ' posthresh = get( findobj(''parent'', gcbf, ''tag'', ''freqpos''), ''string'' );' ... ' negthresh = get( findobj(''parent'', gcbf, ''tag'', ''freqneg''), ''string'' );' ... ' startfreq = get( findobj(''parent'', gcbf, ''tag'', ''freqstart''), ''string'' );' ... ' endfreq = get( findobj(''parent'', gcbf, ''tag'', ''freqend''), ''string'' );' ... ' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''freqelec''), ''string'' );' ... checkstatus ... '[EEG Itmp LASTCOM] = pop_rejspec( EEG,' int2str(icacomp) ... ', elecrange, negthresh, posthresh, startfreq, endfreq, rejstatus, 0,''' tmp_comall ''');' ... 'EEG = eegh(LASTCOM, EEG);' ... 'clear Itmp elecrange posthresh negthresh startfreq endfreq rejstatus;' ]; % ----------------------------------------------------- cb_compconstrej = [ ' minslope = get( findobj(''parent'', gcbf, ''tag'', ''constpnts''), ''string'' );' ... ' minstd = get( findobj(''parent'', gcbf, ''tag'', ''conststd''), ''string'' );' ... ' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''constelec''), ''string'' );' ... checkstatus ... '[rej LASTCOM] = pop_rejtrend(EEG,' int2str(icacomp) ', elecrange, ''' ... int2str(EEG.pnts) ''', minslope, minstd, rejstatus, 0,''' tmp_comall ''');' ... 'EEG = eegh(LASTCOM, EEG);' ... 'clear rej elecrange minslope minstd rejstatus;' ]; % ----------------------------------------------------- cb_compenthead = [ ' locthresh = get( findobj(''parent'', gcbf, ''tag'', ''entloc''), ''string'' );', ... ' globthresh = get( findobj(''parent'', gcbf, ''tag'', ''entglob''), ''string'' );', ... ' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''entelec''), ''string'' );' ]; cb_compenttail = [ ' set( findobj(''parent'', gcbf, ''tag'', ''entloc''), ''string'', num2str(locthresh) );', ... ' set( findobj(''parent'', gcbf, ''tag'', ''entglob''), ''string'', num2str(globthresh) );', ... ' set( findobj(''parent'', gcbf, ''tag'', ''enttrial''), ''string'', num2str(nrej) );' ... 'EEG = eegh(LASTCOM, EEG);' ... 'clear nrej elecrange locthresh globthresh rejstatus;' ]; cb_compentplot = [ cb_compenthead ... '[EEG locthresh globthresh nrej LASTCOM] = pop_jointprob( EEG, ' int2str(icacomp) ... ', elecrange, locthresh, globthresh, 0, 0,''' tmp_comall ''');', ... cb_compenttail ]; cb_compentcalc = [ cb_compenthead ... '[EEG locthresh globthresh nrej LASTCOM] = pop_jointprob( EEG, ' int2str(icacomp) ... ', [ str2num(elecrange) ], str2num(locthresh), str2num(globthresh), 0, 0);', ... cb_compenttail ]; cb_compenteeg = [ cb_compenthead ... checkstatus ... '[EEG locthresh globthresh nrej LASTCOM] = pop_jointprob( EEG, ' int2str(icacomp) ... ', elecrange, locthresh, globthresh, rejstatus, 0, 1,''' tmp_comall ''');', ... cb_compenttail ]; % ----------------------------------------------------- cb_compkurthead =[ ' locthresh = get( findobj(''parent'', gcbf, ''tag'', ''kurtloc''), ''string'' );', ... ' globthresh = get( findobj(''parent'', gcbf, ''tag'', ''kurtglob''), ''string'' );', ... ' elecrange = get( findobj(''parent'', gcbf, ''tag'', ''kurtelec''), ''string'' );' ]; cb_compkurttail =[ ' set( findobj(''parent'', gcbf, ''tag'', ''kurtloc''), ''string'', num2str(locthresh) );', ... ' set( findobj(''parent'', gcbf, ''tag'', ''kurtglob''), ''string'', num2str(globthresh) );', ... ' set( findobj(''parent'', gcbf, ''tag'', ''kurttrial''), ''string'', num2str(nrej) );' ... 'EEG = eegh(LASTCOM, EEG);' ... 'clear nrej elecrange locthresh globthresh rejstatus;' ]; cb_compkurtplot = [ cb_compkurthead ... '[EEG locthresh globthresh nrej LASTCOM] = pop_rejkurt( EEG, ' int2str(icacomp) ... ', elecrange, locthresh, globthresh, 0, 0,''' tmp_comall ''');', ... cb_compkurttail ]; cb_compkurtcalc = [ cb_compkurthead ... '[EEG locthresh globthresh nrej LASTCOM] = pop_rejkurt( EEG, ' int2str(icacomp) ... ', [ str2num(elecrange) ], str2num(locthresh), str2num(globthresh), 0, 0);', ... cb_compkurttail ]; cb_compkurteeg = [ cb_compkurthead ... checkstatus ... '[EEG locthresh globthresh nrej LASTCOM] = pop_rejkurt( EEG, ' int2str(icacomp) ... ', elecrange, locthresh, globthresh, rejstatus, 0, 1,''' tmp_comall ''');', ... cb_compkurttail ]; % ----------------------------------------------------- cb_reject = [ 'set( findobj(''parent'', gcbf, ''tag'', ''rejstatus''), ''value'', 3);' ... % force status to 3 checkstatus ... '[EEG LASTCOM] = eeg_rejsuperpose(EEG,' int2str(icacomp) ',1,1,1,1,1,1,1); EEG = eegh(LASTCOM, EEG);' ... 'if isempty(find(EEG.reject.rejglobal)),' ... ' warndlg2(strvcat(''No epoch selected...'', ''When using thresholding, click update'',''marks in the EEG plotting window''));' ... 'else,' ... ' [EEG LASTCOM] = pop_rejepoch( EEG, EEG.reject.rejglobal, 1);' ... ' if ~isempty(LASTCOM), ' ... ' EEG = eegh(LASTCOM, EEG); [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET); eegh(LASTCOM);' ... ' end; eeglab redraw; close(gcbf);' ... 'end;' ]; cb_clear = [ 'close gcbf; EEG = rmfield( EEG, ''reject''); EEG.reject.rejmanual = [];' ... 'EEG=eeg_checkset(EEG); pop_rejmenu(' inputname(1) ',' int2str(icacomp) ');' ]; cb_close = [ 'close gcbf;' ... 'disp(''Marks stored in dataset'');' ... '[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);' ... 'eegh(''[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);'');']; lisboxoptions = { 'string', [ 'Show only the new trials marked for rejection by the measure selected above|' ... 'Show previous and new trials marked for rejection by the measure selected above|' ... 'Show all trials marked for rejection by the measure selected above or checked below'], 'tag', 'rejstatus', 'value', 1, 'callback', ... [ 'if get(gcbo, ''value'') == 3,' ... ' set(findobj(''parent'', gcbf, ''style'', ''checkbox''), ''enable'', ''on'');' ... 'else' ... ' set(findobj(''parent'', gcbf, ''style'', ''checkbox''), ''enable'', ''off'');' ... 'end;' ] }; chanliststr = [fastif(icacomp,'Electrode(s)','Component(s)') ]; chanlistval = fastif(icacomp, [ '1:' int2str(EEG.nbchan) ], [ '1:' int2str(size(EEG.icaweights,1)) ]); % assess previous rejections % -------------------------- sizeman = 0; sizethresh = 0; sizetrend = 0; sizejp = 0; sizekurt = 0; sizespec = 0; if icacomp == 1 if ~isempty(EEG.reject.rejmanual), sizeman = length(find(EEG.reject.rejmanual)); end; if ~isempty(EEG.reject.rejconst), sizetrend = length(find(EEG.reject.rejconst)); end; if ~isempty(EEG.reject.rejjp), sizejp = length(find(EEG.reject.rejjp)); end; if ~isempty(EEG.reject.rejkurt), sizekurt = length(find(EEG.reject.rejkurt)); end; if ~isempty(EEG.reject.rejfreq), sizespec = length(find(EEG.reject.rejfreq)); end; else if ~isempty(EEG.reject.icarejmanual), sizeman = length(find(EEG.reject.icarejmanual)); end; if ~isempty(EEG.reject.icarejconst), sizetrend = length(find(EEG.reject.icarejconst)); end; if ~isempty(EEG.reject.icarejjp), sizejp = length(find(EEG.reject.icarejjp)); end; if ~isempty(EEG.reject.icarejkurt), sizekurt = length(find(EEG.reject.icarejkurt)); end; if ~isempty(EEG.reject.icarejfreq), sizespec = length(find(EEG.reject.icarejfreq)); end; end; stdl = [0.25 1.2 0.8 1.2 0.8]; % standard line titl = [0.9 0.18 1.55]; % title line geometry = { [0.883 0.195 .2 .45 .4 .4] ... [1] titl stdl stdl stdl stdl ... [1] titl stdl stdl stdl ... [1] titl stdl stdl stdl ... [1] titl stdl stdl stdl ... [1] titl stdl stdl stdl stdl ... [1] [1] [1] [1 1 1] [1 1 1] ... [1] [1 1 1]}; listui = {{'Style', 'text', 'string', 'Mark trials by appearance', 'fontweight', 'bold' }, ... { 'Style', 'pushbutton', 'string', '', 'tag', 'butmanual', ... 'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejmanualcol); if length(tmpcolor) ~= 1,' ... 'EEG.reject.rejmanualcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] },... { } { 'Style', 'pushbutton', 'string', fastif(icacomp,'Scroll Data','Scroll Acts.'), 'callback', cb_manual }, ... { 'Style', 'text', 'string', 'Marked trials' }, ... { 'Style', 'text', 'string', int2str(sizeman), 'tag', 'mantrial' }, ... { }, ... ... % --------------------------------------------------------------------------- { 'Style', 'text', 'string', 'Find abnormal values', 'fontweight', 'bold' }, ... { 'Style', 'pushbutton', 'string', '', 'tag', 'butthresh', ... 'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejthreshcol); if length(tmpcolor) ~= 1,' ... 'EEG.reject.rejthreshcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },... ... { }, { 'Style', 'text', 'string', ['Upper limit(s) ' fastif(icacomp,'(uV)', '(std. dev.)')] }, ... { 'Style', 'edit', 'string', '25', 'tag', 'threshpos' }, ... { 'Style', 'text', 'string', ['Lower limit(s) ' fastif(icacomp,'(uV)', '(std. dev.)')] }, ... { 'Style', 'edit', 'string', '-25', 'tag', 'threshneg' }, ... ... { }, { 'Style', 'text', 'string', 'Start time(s) (ms)' }, ... { 'Style', 'edit', 'string', int2str(EEG.xmin*1000), 'tag', 'threshstart' }, ... { 'Style', 'text', 'string', 'Ending time(s) (ms)' }, ... { 'Style', 'edit', 'string', int2str(EEG.xmax*1000), 'tag', 'threshend' }, ... ... { }, { 'Style', 'text', 'string', chanliststr }, ... { 'Style', 'edit', 'string', chanlistval, 'tag', 'threshelec' }, ... { 'Style', 'text', 'string', 'Currently marked trials' }, ... { 'Style', 'text', 'string', int2str(sizethresh), 'tag', 'threshtrial' }, ... ... { }, { 'Style', 'pushbutton', 'string', 'Calc / Plot', 'callback', cb_compthresh }, ... { }, { },{ 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_eegthresh'');' }, ... ... % --------------------------------------------------------------------------- { }, { 'Style', 'text', 'string', 'Find abnormal trends', 'fontweight', 'bold' }, ... { 'Style', 'pushbutton', 'string', '', 'tag', 'buttrend', ... 'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejconstcol); if length(tmpcolor) ~= 1,' ... 'EEG.reject.rejconstcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },... ... { }, { 'Style', 'text', 'string', ['Max slope ' fastif(icacomp, ... '(uV/epoch)', ... '(std. dev./epoch)') ] }, ... { 'Style', 'edit', 'string', '50', 'tag', 'constpnts' }, ... { 'Style', 'text', 'string', 'R-squared limit (0 to 1)' }, ... { 'Style', 'edit', 'string', '0.3', 'tag', 'conststd' }, ... ... { }, { 'Style', 'text', 'string', chanliststr }, ... { 'Style', 'edit', 'string', chanlistval, 'tag', 'constelec' }, ... { 'Style', 'text', 'string', 'Currently marked trials' }, ... { 'Style', 'text', 'string', int2str(sizetrend), 'tag', 'consttrial' }, ... ... { }, { 'Style', 'pushbutton', 'string', 'Calc / Plot', 'callback', cb_compconstrej }, ... { }, { }, { 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_rejtrend'');' }, ... ... % --------------------------------------------------------------------------- { }, { 'Style', 'text', 'string', 'Find improbable data', 'fontweight', 'bold' }, ... { 'Style', 'pushbutton', 'string', '', 'tag', 'butjp', ... 'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejjpcol); if length(tmpcolor) ~= 1,' ... 'EEG.reject.rejjpcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },... ... { }, { 'Style', 'text', 'string', fastif(icacomp, 'Single-channel limit (std. dev.)', 'Single-comp. limit (std. dev.)') }, ... { 'Style', 'edit', 'string', fastif(icacomp, '5', '20'), 'tag', 'entloc' }, ... { 'Style', 'text', 'string', fastif(icacomp, 'All channels limit (std. dev.)', 'All comp. limit (std. dev.)') }, ... { 'Style', 'edit', 'string', '5', 'tag', 'entglob' }, ... ... { }, { 'Style', 'text', 'string', chanliststr }, ... { 'Style', 'edit', 'string', chanlistval, 'tag', 'entelec' }, ... { 'Style', 'text', 'string', 'Currently marked trials' }, ... { 'Style', 'text', 'string', int2str(sizejp), 'tag', 'enttrial' }, ... ... { }, { 'Style', 'pushbutton', 'string', 'Calculate', 'callback', cb_compentcalc }, ... { 'Style', 'pushbutton', 'string', 'Scroll Data', 'callback', cb_compenteeg }, ... { 'Style', 'pushbutton', 'string', 'PLOT', 'callback', cb_compentplot }, ... { 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_jointprob'');' }, ... ... % --------------------------------------------------------------------------- { }, { 'Style', 'text', 'string', 'Find abnormal distributions', 'fontweight', 'bold' }, ... { 'Style', 'pushbutton', 'string', '', 'tag', 'butkurt', ... 'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejkurtcol); if length(tmpcolor) ~= 1,' ... 'EEG.reject.rejkurtcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },... ... { }, { 'Style', 'text', 'string', fastif(icacomp, 'Single-channel limit (std. dev.)', 'Single-comp. limit (std. dev.)') }, ... { 'Style', 'edit', 'string', fastif(icacomp, '5', '20'), 'tag', 'kurtloc' }, ... { 'Style', 'text', 'string', fastif(icacomp, 'All channels limit (std. dev.)', 'All comp. limit (std. dev.)') }, ... { 'Style', 'edit', 'string', '5', 'tag', 'kurtglob' }, ... ... { }, { 'Style', 'text', 'string', chanliststr }, ... { 'Style', 'edit', 'string', chanlistval, 'tag', 'kurtelec' }, ... { 'Style', 'text', 'string', 'Currently marked trials' }, ... { 'Style', 'text', 'string', int2str(sizekurt), 'tag', 'kurttrial' }, ... ... { }, { 'Style', 'pushbutton', 'string', 'Calculate', 'callback', cb_compkurtcalc }, ... { 'Style', 'pushbutton', 'string', 'Scroll Data', 'callback', cb_compkurteeg }, ... { 'Style', 'pushbutton', 'string', 'PLOT', 'callback', cb_compkurtplot }, ... { 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_rejkurt'');' }, ... ... % --------------------------------------------------------------------------- { }, { 'Style', 'text', 'string', 'Find abnormal spectra (slow)', 'fontweight', 'bold' }, ... { 'Style', 'pushbutton', 'string', '', 'tag', 'butspec', ... 'callback', [ 'tmpcolor = uisetcolor(EEG.reject.rejfreqcol); if length(tmpcolor) ~= 1,' ... 'EEG.reject.rejfreqcol=tmpcolor; set(gcbo, ''backgroundcolor'', tmpcolor); end; clear tmpcolor;'] }, { },... ... { }, { 'Style', 'text', 'string', 'Upper limit(s) (dB)' }, ... { 'Style', 'edit', 'string', '25', 'tag', 'freqpos' }, ... { 'Style', 'text', 'string', 'Lower limit(s) (dB)' }, ... { 'Style', 'edit', 'string', '-25', 'tag', 'freqneg' }, ... ... { }, { 'Style', 'text', 'string', 'Low frequency(s) (Hz)' }, ... { 'Style', 'edit', 'string', '0', 'tag', 'freqstart' }, ... { 'Style', 'text', 'string', 'High frequency(s) (Hz)' }, ... { 'Style', 'edit', 'string', '50', 'tag', 'freqend' }, ... ... { }, { 'Style', 'text', 'string', chanliststr }, ... { 'Style', 'edit', 'string', chanlistval, 'tag', 'freqelec' }, ... { 'Style', 'text', 'string', 'Currently marked trials' }, ... { 'Style', 'text', 'string', int2str(sizespec), 'tag', 'freqtrial' }, ... ... { }, { 'Style', 'pushbutton', 'string', 'Calc / Plot', 'callback', cb_compfreq }, ... { }, { },{ 'Style', 'pushbutton', 'string', 'HELP', 'callback', 'pophelp(''pop_rejspec'');' }, ... ... {}, ... % --------------------------------------------------------------------------- ... { 'Style', 'text', 'string', 'Plotting options', 'fontweight', 'bold' }, ... { 'style', 'listbox', lisboxoptions{:}, 'value', 3 }, ... { 'style', 'checkbox', 'String', 'Abnormal appearance', 'tag', 'IManual', 'value', 1, ... 'callback', 'set(gcbo, ''value'', 1); disp(''This checkbox must be set so that you may mark/unmark data epochs'');'}, ... { 'style', 'checkbox', 'String', 'Abnormal values', 'tag', 'IThresh', 'value', 1}, ... { 'style', 'checkbox', 'String', 'Abnormal trends', 'tag', 'IConst', 'value', 1}, ... { 'style', 'checkbox', 'String', 'Improbable epochs', 'tag', 'IEnt', 'value', 1}, ... { 'style', 'checkbox', 'String', 'Abnormal distributions', 'tag', 'IKurt', 'value', 1}, ... { 'style', 'checkbox', 'String', 'Abnormal spectra', 'tag', 'IFreq', 'value', 1}, ... ... { }, ... { 'Style', 'pushbutton', 'string', 'CLOSE (KEEP MARKS)', 'callback', cb_close }, ... { 'Style', 'pushbutton', 'string', 'CLEAR ALL MARKS', 'callback', cb_clear }, ... { 'Style', 'pushbutton', 'string', 'REJECT MARKED TRIALS', 'callback', cb_reject }}; allh = supergui( gcf, geometry, [], listui{:}); % { 'style', 'checkbox', 'String', ['Include ' fastif(icacomp, 'ica data', 'raw data')], 'tag', 'IOthertype', 'value', 1}, { }, ... set(gcf, 'userdata', { allh }); set(findobj('parent', gcf', 'tag', 'butmanual'), 'backgroundcolor', EEG.reject.rejmanualcol); set(findobj('parent', gcf', 'tag', 'butthresh'), 'backgroundcolor', EEG.reject.rejthreshcol); set(findobj('parent', gcf', 'tag', 'buttrend'), 'backgroundcolor', EEG.reject.rejconstcol); set(findobj('parent', gcf', 'tag', 'butjp'), 'backgroundcolor', EEG.reject.rejjpcol); set(findobj('parent', gcf', 'tag', 'butkurt'), 'backgroundcolor', EEG.reject.rejkurtcol); set(findobj('parent', gcf', 'tag', 'butspec'), 'backgroundcolor', EEG.reject.rejfreqcol); set( findobj('parent', gcf, 'tag', 'rejstatus'), 'style', 'popup');
github
ZijingMao/baselineeegtest-master
plugin_extract.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/plugin_extract.m
13,547
utf_8
16601e654cdeb6f5eadeb41ab74eb6dd
function restartEeglabFlag = plugin_extract(type, pluginlist, page) if nargin < 3, page = 1; end; % type may be 'import' or 'process' restartEeglabFlag = false; pluginsPerPage = 15; % check the presence of unzip %str = evalc('!unzip'); %if length(str) < 200 % error([ '"unzip" could not be found. Instal unzip and make sure' 10 'it is accessible under Matlab by adding the program to' 10 'the path and typing "!unzip"' ]); %end; if ~isstruct(type) plugin = plugin_getweb(type, pluginlist, 'newlist'); % sort plugins by download score [tmp scoreOrder] = sort([ plugin.downloads ], 2, 'descend'); plugin = plugin(scoreOrder); else plugin = type; end; % select page allPlugins = plugin; numPlugin = length(plugin); moreThanOnePage = 0; if numPlugin > pluginsPerPage plugin = plugin(pluginsPerPage*(page-1)+1:min(length(plugin),pluginsPerPage*page)); moreThanOnePage = 1; end; % find which menu to show newInstallFlag = false; installedFlag = false; deactivatedFlag = false; for iPlugin = length(plugin):-1:1 if ~plugin(iPlugin).installed, newInstallFlag = true; end; if plugin(iPlugin).installed && ~strcmpi(plugin(iPlugin).status, 'deactivated'), installedFlag = true; end; if strcmpi(plugin(iPlugin).status, 'deactivated'), deactivatedFlag = true; end; end; uilist = {}; geom = {}; geomvert = []; pluginIndices = []; callback = [ 'tmptag = get(gcbo, ''tag'');' ... 'if tmptag(3) == ''1'', tmptag(3) = ''2''; else tmptag(3) = ''1''; end;' ... 'if get(gcbo, ''value''), set(findobj(gcbf, ''tag'', tmptag), ''value'', 0); end; clear tmptag;' ]; % ------------------ % plugins to install % ------------------ maxchar = 60; geom = {}; lineGeom = [ 0.28 0.28 0.95 0.6 0.6 3 0.35 ]; if newInstallFlag uilist = { {} { 'style' 'text' 'string' 'Extensions available for install on the internet' 'fontweight' 'bold' 'fontsize' 18 'tag' 'title' } }; uilist = { uilist{:} { 'style' 'text' 'string' 'I' 'tag' 'install' } { } ... { 'style' 'text' 'string' 'Plugin' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Vers.' 'tag' 'verweb' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Score' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Description' 'fontweight' 'bold' } {}}; geom = { [1 5.5] lineGeom }; geomvert = [1 1]; for iRow = 1:length(plugin) if ~plugin(iRow).installed && ~strcmpi(plugin(iRow).status, 'deactivated') % text for description description = plugin(iRow).description; if length(description) > maxchar+2 description = [ description(1:min(maxchar,length(description))) '...' ]; end; enableWebDoc = fastif(isempty(plugin(iRow).webdoc), 'off', 'on'); userdata = ''; if plugin(iRow).installed && plugin(iRow).installorupdate, userdata = 'colortored'; end; uilist = { uilist{:}, ... { 'style' 'checkbox' 'string' '' 'value' 0 'enable' 'on' }, ... { 'style' 'checkbox' 'string' '' 'visible' 'off' }, ... { 'style' 'text' 'string' plugin(iRow).name }, ... { 'style' 'text' 'string' plugin(iRow).version 'tag' 'latestversion' 'userdata' userdata }, ... { 'style' 'text' 'string' int2str(plugin(iRow).downloads) }, ... { 'style' 'text' 'string' description }, ... { 'style' 'pushbutton' 'string' 'Doc' 'enable' enableWebDoc 'callback' myweb(plugin(iRow).webdoc) } }; geom = { geom{:}, lineGeom }; geomvert = [ geomvert 1]; pluginIndices = [ pluginIndices iRow ]; end; end; end; % ----------------- % installed plugins % ----------------- if installedFlag uilist = { uilist{:} {} {} { 'style' 'text' 'string' 'Installed extensions' 'fontweight' 'bold' 'fontsize' 18 'tag' 'title' } }; uilist = { uilist{:} { 'style' 'text' 'string' 'I' 'tag' 'update' } ... { 'style' 'text' 'string' 'I' 'tag' 'deactivate' } ... { 'style' 'text' 'string' 'Plugin' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Vers.' 'tag' 'verweb' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Score' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Description' 'fontweight' 'bold' } {}}; geom = { geom{:} 1 [1 5.5] lineGeom }; geomvert = [geomvert 1 1 1]; for iRow = 1:length(plugin) if plugin(iRow).installed && ~strcmpi(plugin(iRow).status, 'deactivated') % text for description description = plugin(iRow).description; if length(description) > maxchar+2 description = [ description(1:min(maxchar,length(description))) '...' ]; end; enableWebDoc = fastif(isempty(plugin(iRow).webdoc), 'off', 'on'); userdata = ''; if plugin(iRow).installorupdate, textnew = [ 'Click update to install version ' plugin(iRow).version ' now available on the web' ]; userdata = 'colortored'; else textnew = description; end; uilist = { uilist{:}, ... { 'style' 'checkbox' 'string' '' 'value' 0 'enable' fastif(plugin(iRow).installorupdate, 'on', 'off') 'tag' [ 'cb1' int2str(iRow) ] 'callback' callback }, ... { 'style' 'checkbox' 'string' '' 'enable' 'on' 'tag' [ 'cb2' int2str(iRow) ] 'callback' callback }, ... { 'style' 'text' 'string' plugin(iRow).name }, ... { 'style' 'text' 'string' plugin(iRow).currentversion 'tag' 'latestversion'}, ... { 'style' 'text' 'string' int2str(plugin(iRow).downloads) }, ... { 'style' 'text' 'string' textnew 'userdata' userdata }, ... { 'style' 'pushbutton' 'string' 'Doc' 'enable' enableWebDoc 'callback' myweb(plugin(iRow).webdoc) } }; geom = { geom{:}, lineGeom }; geomvert = [ geomvert 1]; pluginIndices = [ pluginIndices iRow ]; end; end; end; % ------------------- % deactivated plugins % ------------------- %geom = { geom{:} 1 1 }; %geomvert = [geomvert 0.5 1]; %uilist = { uilist{:} {} { 'style' 'text' 'string' 'To manage deactivated plugins, use menu item File > Manage plugins > Manage deactivated plugins' } }; if deactivatedFlag uilist = { uilist{:} {} {} { 'style' 'text' 'string' 'List of deactivated extensions ' 'fontweight' 'bold' 'fontsize' 18 'tag' 'title' } }; uilist = { uilist{:} ... { 'style' 'text' 'string' 'I' 'tag' 'reactivate' } ... { 'style' 'text' 'string' 'I' 'tag' 'remove1' } ... { 'style' 'text' 'string' 'Plugin' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Vers.' 'tag' 'verweb' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Score' 'fontweight' 'bold' } ... { 'style' 'text' 'string' 'Description' 'fontweight' 'bold' } {}}; geom = { geom{:} 1 [1 5.5] lineGeom }; geomvert = [geomvert 1 1 1]; for iRow = 1:length(plugin) if strcmpi(plugin(iRow).status, 'deactivated') % text for description description = plugin(iRow).description; if length(description) > maxchar+2 description = [ description(1:min(maxchar,length(description))) '...' ]; end; userdata = ''; enableWebDoc = fastif(isempty(plugin(iRow).webdoc), 'off', 'on'); uilist = { uilist{:}, ... { 'style' 'checkbox' 'string' '' 'tag' [ 'cb1' int2str(iRow) ] 'callback' callback }, ... { 'style' 'checkbox' 'string' '' 'tag' [ 'cb2' int2str(iRow) ] 'callback' callback }, ... { 'style' 'text' 'string' plugin(iRow).name }, ... { 'style' 'text' 'string' plugin(iRow).version 'tag' 'latestversion' }, ... { 'style' 'text' 'string' int2str(plugin(iRow).downloads) }, ... { 'style' 'text' 'string' description }, ... { 'style' 'pushbutton' 'string' 'Doc' 'enable' enableWebDoc 'callback' myweb(plugin(iRow).webdoc) } }; geom = { geom{:}, lineGeom }; geomvert = [ geomvert 1]; pluginIndices = [ pluginIndices iRow ]; end; end; end; evalStr = [ 'uisettxt(gcf, ''update'' , ''Update'' , ''rotation'', 90, ''fontsize'', 14);' ... 'uisettxt(gcf, ''deactivate'' , ''Deactivate'' , ''rotation'', 90, ''fontsize'', 14);' ... 'uisettxt(gcf, ''install'' , ''Install'' , ''rotation'', 90, ''fontsize'', 14);' ... 'uisettxt(gcf, ''reactivate'' , ''Reactivate'' , ''rotation'', 90, ''fontsize'', 14);' ... 'uisettxt(gcf, ''remove1'' , ''Remove'' , ''rotation'', 90, ''fontsize'', 14);' ... 'set(findobj(gcf, ''tag'', ''title''), ''fontsize'', 16);' ... 'tmpobj = findobj(gcf, ''userdata'', ''colortored'');' ... 'set(tmpobj, ''Foregroundcolor'', [1 0 0]);' ... 'tmppos = get(gcf, ''position'');' ... 'set(gcf, ''position'', [tmppos(1:2) 800 tmppos(4)]);' ... 'clear tmpobj tmppos;' ... ]; if 1 % version with button if page == 1, enablePpage = 'off'; else enablePpage = 'on'; end; if page*pluginsPerPage > numPlugin, enableNpage = 'off'; else enableNpage = 'on'; end; callBackPpage = [ 'tmpobj = get(gcbf, ''userdata''); close gcbf; restartEeglabFlag = plugin_extract(tmpobj, [], ' int2str(page-1) '); clear tmpobj;' ]; callBackNpage = [ 'tmpobj = get(gcbf, ''userdata''); close gcbf; restartEeglabFlag = plugin_extract(tmpobj, [], ' int2str(page+1) '); clear tmpobj;' ]; uilist = { uilist{:}, {} { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', '< Prev. page', 'tag' 'ppage' 'callback', callBackPpage 'enable' enablePpage } }; uilist = { uilist{:}, { 'width' 80 'align' 'left' 'stickto' 'on', 'Style', 'pushbutton', 'string', 'Next page >', 'tag' 'npage' 'callback', callBackNpage 'enable' enableNpage } }; uilist = { uilist{:}, { 'width' 80 'align' 'right' 'Style', 'pushbutton', 'string', 'Cancel', 'tag' 'cancel' 'callback', 'close gcbf' } }; uilist = { uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'pushbutton', 'tag', 'ok', 'string', 'OK', 'callback', 'set(gcbo, ''userdata'', ''retuninginputui'');' } }; geom = { geom{:} [1] [1 1 1 1] }; geomvert = [ geomvert 1 1]; res = inputgui('uilist', uilist, 'geometry', geom, 'geomvert', geomvert, 'eval', evalStr, 'addbuttons', 'off', 'skipline', 'off', 'userdata', allPlugins); try, restartEeglabFlag = evalin('base', 'restartEeglabFlag;'); catch, end; evalin('base', 'clear restartEeglabFlag;'); else % no buttons res = inputgui('uilist', uilist, 'geometry', geom, 'geomvert', geomvert, 'eval', evalStr); end; if isempty(res), return; end; % decode inputs % ------------- for iRow = 1:length(pluginIndices) plugin(pluginIndices(iRow)).install = res{(iRow-1)*2+1}; plugin(pluginIndices(iRow)).remove = res{(iRow-1)*2+2}; end; % install plugins % --------------- firstPlugin = 1; for iRow = 1:length(plugin) if plugin(iRow).install restartEeglabFlag = true; if ~firstPlugin, disp('---------------------------------'); end; firstPlugin = 0; if strcmpi(plugin(iRow).status, 'deactivated') fprintf('Reactivating extension %s\n', plugin(iRow).name); plugin_reactivate(plugin(iRow).foldername); if plugin(iRow).installorupdate res = questdlg2([ 'Extension ' plugin(iRow).foldername ' has been reactivated but' 10 'a new version is available. Do you want to install it?' ], 'Warning', 'No', 'Yes', 'Yes'); if strcmpi(res, 'yes') plugin_deactivate(plugin(iRow).foldername); plugin_install(plugin(iRow).zip, plugin(iRow).name, plugin(iRow).version); plugin_remove(plugin(iRow).foldername); end; end; else if plugin(iRow).installed fprintf('Updating extension %s\n', plugin(iRow).name); plugin_deactivate(plugin(iRow).foldername); plugin_install(plugin(iRow).zip, plugin(iRow).name, plugin(iRow).version); plugin_remove(plugin(iRow).foldername); else fprintf('Installing extension %s\n', plugin(iRow).name); plugin_install(plugin(iRow).zip, plugin(iRow).name, plugin(iRow).version); end; end; elseif plugin(iRow).remove if ~firstPlugin, disp('---------------------------------'); end; firstPlugin = 0; restartEeglabFlag = true; if strcmpi(plugin(iRow).status, 'deactivated') fprintf('Removing extension %s\n', plugin(iRow).name); plugin_remove(plugin(iRow).foldername); else fprintf('Deactivating extension %s\n', plugin(iRow).name); plugin_deactivate(plugin(iRow).foldername); end; end; end; function str = myweb(url); %if isempty(strfind(url, 'wiki')) % str = [ 'web(''' url ''');' ]; %else str = [ 'web(''' url ''', ''-browser'');' ]; %end;
github
ZijingMao/baselineeegtest-master
eeg_store.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeg_store.m
5,423
utf_8
d4bd75d1e701aaaba164772acc07725e
% eeg_store() - store specified EEG dataset(s) in the ALLEG variable % containing all current datasets, after first checking % dataset consistency using eeg_checkset(). % % Usage: >> [ALLEEG EEG index] = eeg_store(ALLEEG, EEG); % >> [ALLEEG EEG index] = eeg_store(ALLEEG, EEG, index); % % Inputs: % ALLEEG - variable containing all current EEGLAB datasets % EEG - dataset(s) to store - usually the current dataset. % May also be an array of datasets; these will be % checked and stored separately in ALLEEG. % index - (optional), ALLEEG index (or indices) to use to store % the new dataset(s). If no index is given, eeg_store() % uses the lowest empty slot(s) in the ALLEEG array. % Outputs: % ALLEEG - array of all current datasets % EEG - EEG dataset (after syntax checking) % index - index of the new dataset % % Note: When 3 arguments are given, after checking the consistency of % the input dataset structures this function simply performs % >> ALLEEG(index) = EEG; % % Typical use: % >> [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG); % creates a new dataset in variable ALLEEG. % >> [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET); % overwrites the current dataset in variable ALLEEG. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeglab(), eeg_checkset(), eeg_retrieve() % Copyright (C) 2001 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 % uses the global variable EEG ALLEEG CURRENTSET % store set % ------------------ function [ALLEEG, EEG, storeSetIndex] = eeg_store(ALLEEG, EEG, storeSetIndex, varargin); % check parameter consistency % ------------------------------ if nargin >= 3 if length(EEG) ~= length(storeSetIndex) & storeSetIndex(1) ~= 0 error('Length of input dataset structure must equal the length of the index array'); end; end; % considering multiple datasets % ----------------------------- if length(EEG) > 1 TMPEEG = EEG; if nargin >= 3 & storeSetIndex(1) ~= 0 for index=1:length(TMPEEG) EEG = TMPEEG(index); tmpsaved = EEG.saved; if strcmpi(tmpsaved, 'justloaded'), tmpsaved = 'yes'; end; [ALLEEG, EEG] = eeg_store(ALLEEG, EEG, storeSetIndex(index), varargin{:}); ALLEEG(storeSetIndex(index)).saved = tmpsaved; TMPEEG(index).saved = tmpsaved; end; else for index=1:length(TMPEEG) EEG = TMPEEG(index); tmpsaved = EEG.saved; if strcmpi(tmpsaved, 'justloaded'), tmpsaved = 'yes'; end; [ALLEEG, EEG, storeSetIndex(index)] = eeg_store(ALLEEG, EEG); ALLEEG(storeSetIndex(index)).saved = tmpsaved; TMPEEG(index).saved = tmpsaved; end; end; EEG = TMPEEG; return; end; if nargin < 3 % creating new dataset % -> erasing file information % --------------------------- EEG.filename = ''; EEG.filepath = ''; EEG.datfile = ''; end; if isempty(varargin) % no text output and no check (study loading) [ EEG com ] = eeg_checkset(EEG); else com = ''; end; if nargin > 2, if storeSetIndex == 0 || strcmpi(EEG.saved, 'justloaded') EEG.saved = 'yes'; % just loaded else EEG.saved = 'no'; end; elseif strcmpi(EEG.saved, 'justloaded') EEG.saved = 'yes'; else EEG.saved = 'no'; end; EEG = eeg_hist(EEG, com); % find first free index % --------------------- findindex = 0; if nargin < 3, findindex = 1; elseif storeSetIndex == 0, findindex = 1; end; if findindex i = 1; while (i<2000) try if isempty(ALLEEG(i).data); storeSetIndex = i; i = 2000; end; i = i+1; catch storeSetIndex = i; i = 2000; end; end; if isempty(varargin) % no text output and no check fprintf('Creating a new ALLEEG dataset %d\n', storeSetIndex); end; else if isempty(storeSetIndex) | storeSetIndex == 0 storeSetIndex = 1; end; end; if ~isempty( ALLEEG ) try ALLEEG(storeSetIndex) = EEG; catch allfields = fieldnames( EEG ); for i=1:length( allfields ) eval( ['ALLEEG(' int2str(storeSetIndex) ').' allfields{i} ' = EEG.' allfields{i} ';' ]); end; if ~isfield(EEG, 'datfile') & isfield(ALLEEG, 'datfile') ALLEEG(storeSetIndex).datfile = ''; end; end; else ALLEEG = EEG; if storeSetIndex ~= 1 ALLEEG(storeSetIndex+1) = EEG; ALLEEG(1) = ALLEEG(storeSetIndex); % empty ALLEEG(storeSetIndex) = ALLEEG(storeSetIndex+1); ALLEEG = ALLEEG(1:storeSetIndex); end; end; return;
github
ZijingMao/baselineeegtest-master
eeg_eval.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeg_eval.m
4,224
utf_8
a33398d975e05e64806a16536fdcca32
% eeg_eval() - apply eeglab function to a collection of input datasets % % Usage: % >> OUTEEG = eeg_eval(funcname, INEEG, 'key1', value1, 'key2', value2 ...); % % Inputs: % funcname - [string] name of the function % INEEG - EEGLAB input dataset(s) % % Optional inputs % 'params' - [cell array] funcname parameters. % 'warning' - ['on'|'off'] warning pop-up window if several dataset % stored on disk that will be automatically overwritten. % Default is 'on'. % % Outputs: % OUTEEG - output dataset(s) % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2005 % % see also: eeglab() % Copyright (C) 2005 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 [EEG, com] = eeg_eval( funcname, EEG, varargin); com = ''; if nargin < 2 help eeg_eval; return; end; % check input parameters % ---------------------- g = finputcheck( varargin, { 'params' 'cell' {} {}; 'warning' 'string' { 'on','off' } 'on' }, 'eeg_eval'); if isstr(g), error(g); end; % warning pop up % -------------- eeglab_options; if strcmpi(g.warning, 'on') if ~option_storedisk res = questdlg2(strvcat( 'When processing multiple datasets, it is not', ... 'possible to enter new names for the newly created', ... 'datasets and old datasets are overwritten.', ... 'You may still cancel this operation though.'), ... 'Multiple dataset warning', 'Cancel', 'Proceed', 'Proceed'); else res = questdlg2( [ 'Data files on disk will be automatically overwritten.' 10 ... 'Are you sure you want to proceed with this operation?' ], ... 'Confirmation', 'Cancel', 'Proceed', 'Proceed'); end; switch lower(res), case 'cancel', return; case 'proceed',; end; end; % execute function % ---------------- v = version; if str2num(v(1)) == '5' % Matlab 5 command = [ 'TMPEEG = ' funcname '( TMPEEG, ' vararg2str(g.params) ');' ]; else eval( [ 'func = @' funcname ';' ] ); end; NEWEEG = []; for i = 1:length(EEG) fprintf('Processing group dataset %d of %d named: %s ****************\n', i, length(EEG), EEG(i).setname); TMPEEG = eeg_retrieve(EEG, i); if v(1) == '5', eval(command); % Matlab 5 else TMPEEG = feval(func, TMPEEG, g.params{:}); % Matlab 6 and higher end; TMPEEG = eeg_checkset(TMPEEG); TMPEEG.saved = 'no'; if option_storedisk TMPEEG = pop_saveset(TMPEEG, 'savemode', 'resave'); TMPEEG = update_datafield(TMPEEG); end; NEWEEG = eeg_store(NEWEEG, TMPEEG, i); if option_storedisk NEWEEG(i).saved = 'yes'; % eeg_store by default set it to no end; end; EEG = NEWEEG; % history % ------- if nargout > 1 com = sprintf('%s = %s( %s,%s);', funcname, inputname(2), funcname, inputname(2), vararg2str(g.params)); end; function EEG = update_datafield(EEG); if ~isfield(EEG, 'datfile'), EEG.datfile = ''; end; if ~isempty(EEG.datfile) EEG.data = EEG.datfile; else EEG.data = 'in set file'; end; EEG.icaact = [];
github
ZijingMao/baselineeegtest-master
eegh.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eegh.m
4,073
utf_8
71f03408b617f0adfa6816bce5a1adbd
% eegh() - history function. % % Usage: % >> eegh( arg ); % >> eegh( arg1, arg2 ); % % Inputs: % - With no argument, it return the command history. % - arg is a string: with a string argument it pulls the command % onto the stack. % - arg is a number>0: execute the element in the stack at the % required position. % - arg is a number<0: unstack the required number of elements % - arg is 0 : clear stack % - arg1 is 'find' and arg2 is a string, try to find the closest command % in the stack containing the string % - arg1 is a string and arg2 is a structure, also add the history to % the structure in filed 'history'. % % Global variables used: % LASTCOM - last command % ALLCOM - all the commands % % Author: Arnaud Delorme, SCCN/INC/UCSD, 2001 % % See also: % eeglab() (a graphical interface for eeg plotting, space frequency % decomposition, ICA, ... under Matlab for which this command % was designed). % Copyright (C) 2001 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 % To increase/decrease the maximum depth of the stack, edit the eeg_consts file function str = eegh( command, str ); mode = 1; % mode = 1, full print, mode = 0, truncated print global ALLCOM; %if nargin == 2 % fprintf('2: %s\n', command); %elseif nargin == 1 % fprintf('1: %s\n', command); %end; if nargin < 1 if isempty(ALLCOM) fprintf('No history\n'); else for index = 1:length(ALLCOM) if mode == 0, txt = ALLCOM{ index }; fprintf('%d: ', index); else txt = ALLCOM{ length(ALLCOM)-index+1 }; end; if (length(txt) > 72) & (mode == 0) fprintf('%s...\n', txt(1:70) ); else fprintf('%s\n', txt ); end; end; end; if nargout > 0 str = strvcat(ALLCOM); end; elseif nargin == 1 if isempty( command ) return; end; if isstr( command ) if ~isempty(ALLCOM) && isequal(ALLCOM{1}, command), return; end; if isempty(ALLCOM) ALLCOM = { command }; else ALLCOM = { command ALLCOM{:}}; end; global LASTCOM; LASTCOM = command; else if command == 0 ALLCOM = []; else if command < 0 ALLCOM = ALLCOM( -command+1:end ); % unstack elements else txt = ALLCOM{command}; if length(txt) > 72 fprintf('%s...\n', txt(1:70) ); else fprintf('%s\n', txt ); end; evalin( 'base', ALLCOM{command} ); % execute element eegh( ALLCOM{command} ); % add to history end; end; end; else % nargin == 2 if ~isstruct(str) if strcmp(command, 'find') for index = 1:length(ALLCOM) if ~isempty(findstr(ALLCOM{index}, str)) str = ALLCOM{index}; return; end; end; str = []; end; else % warning also some code present in eeg_store and pop_newset if ~isempty(ALLCOM) && isequal(ALLCOM{1}, command), return; end; eegh(command); % add to history if ~isempty(command) if length(str) == 1 str = eeg_hist(str, command); else for i = 1:length(str) str(i) = eeg_hist(str(i), [ '% multiple datasets command: ' command ]); end; end; end; end; end;
github
ZijingMao/baselineeegtest-master
eeglabexefolder.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeglabexefolder.m
1,076
utf_8
bea2b2d54e501ccc2c6e113759384061
% eeglabexefolder - return the exe folder for EEGLAB. This function is only % relevant for the compiled version of EEGLAB. % % Author: Arnaud Delorme, SCCN & CERCO, CNRS, 2008- % Copyright (C) 15 Feb 2002 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 str = eeglabexefolder; str = ctfroot; inds = find(str == filesep); str = str(1:inds(end)-1);
github
ZijingMao/baselineeegtest-master
eeg_hist.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeg_hist.m
1,405
utf_8
5da5613eba9f720215dbf40a723b2008
% eeg_hist() - history for EEGLAB dataset. % % Usage: % >> EEGOUT = eeg_hist( EEGIN, command ); % % Inputs: % EEGIN - input dataset % command - [string] eeglab command % % Global variables used: % EEGOUT - output dataset with updated history field % % Author: Arnaud Delorme, SCCN/INC/UCSD, Dec 2003 % % See also: eegh(), eeglab() % Copyright (C) 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 = eeg_hist( EEG, command ); if nargin < 2 help eeg_hist; end; if ~isfield(EEG, 'history') EEG.history = ''; end; if ~isempty(command) try EEG.history = [ EEG.history 10 command ]; catch EEG.history = strvcat(EEG.history, command); end; end;
github
ZijingMao/baselineeegtest-master
eeglab_error.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/eeglab_error.m
3,159
utf_8
52bd326118eafedfeaaa94a2741cbedc
% eeglab_error() - generate an eeglab error. % % Usage: >> eeglab_error; % % Inputs: none, simply capture the last error generated. % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2006- % % see also: eeglab() % Copyright (C) 2006 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 eeglab_error % handling errors % ---------------- tmplasterr = lasterr; [iseeglaberror tmplasterr header] = testeeglaberror(tmplasterr); ft_error = false; if iseeglaberror tmp = lasterror; % Add more information to eeglab errors JRI, RMC tmplasterr = sprintf('%s,\n\n (Error occurred in function %s() at line %d)',... tmplasterr, tmp.stack(1).name, tmp.stack(1).line); errordlg2(tmplasterr, header); else try tmp = lasterror; if length(tmp.stack(1).name) && all(tmp.stack(1).name(1:3) == 'ft_') ft_error = true; end; tmperr = [ 'EEGLAB error in function ' tmp.stack(1).name '() at line ' int2str(tmp.stack(1).line) ':' 10 10 lasterr ]; catch % Matlab 5 and when the stack is empty tmperr = [ 'EEGLAB error:' 10 10 tmplasterr ]; end; if ~ft_error tmperr = [ tmperr 10 10 'If you think this is a bug, please submit a detailed ' 10 ... 'description of how to reproduce the problem (and upload' 10 ... 'a small dataset) at http://sccn.ucsd.edu/eeglab/bugzilla' ]; else tmperr = [ tmperr 10 10 'This is a problem with FIELDTRIP. The Fieldtrip version you downloaded' 10 ... 'is corrupted. Please manually replace Fieldtrip with an earlier version' 10 ... 'and/or email the Fieldtrip developpers so they can fix the issue.' ]; end; errordlg2(tmperr, header); end; function [ val str header ] = testeeglaberror(str) header = 'EEGLAB error'; val = 0; try, if strcmp(str(1:5), 'Error'), val = 1; str = str(12:end); %Corrected extraction of function name, occurs after 'Error using ' JRI, RMC indendofline = find(str == 10); funcname = str(1:indendofline(1)-1); str = str(indendofline(1)+1:end); header = [ funcname ' error' ]; end; catch end;
github
ZijingMao/baselineeegtest-master
plugin_installstartup.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/adminfunc/plugin_installstartup.m
3,762
utf_8
37419d82594718647942d0ca8356c632
% plugin_installstartup() - install popular toolboxes when EEGLAB starts % % Usage: % >> restartEeglabFlag = plugin_installstartup; % pop up window % % Outputs: % restartEeglabFlag - [0|1] restart EEGLAB % % Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2013- % Copyright (C) 2013 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 restartEeglabFlag = plugin_installstartup % { 'style' 'checkbox' 'string' 'Neuroelectromagnetic Forward Head Modeling Toolbox (NFT): Advanced source localization tools - beta (Zeynep Akalin Acar, 100 Mb)' 'value' 1 'enable' 'on' } ... uilist = { { 'style' 'text' 'String' 'Download and install some popular third party EEGLAB plug-ins' 'fontweight', 'bold','tag', 'title'} ... { } ... { 'style' 'checkbox' 'string' 'Brain Vision Analyser data import plugin (40 Kb)' 'value' 1 'enable' 'on' } ... { 'style' 'checkbox' 'string' 'ANT data import plugin (800 Kb)' 'value' 1 'enable' 'on' } ... { 'style' 'checkbox' 'string' 'Measure Projection Toolbox (MPT) for ulti-subject ICA analysis (415 Mb)' 'value' 1 'enable' 'on' } ... { 'style' 'checkbox' 'string' 'Source Information Flow Toolbox (SIFT) for causal analysis of EEG sources (600 Mb)' 'value' 1 'enable' 'on' } ... { 'style' 'checkbox' 'string' 'BCILAB for real-time and offline BCI platform (200 Mb)' 'value' 1 'enable' 'on' } ... { 'style' 'checkbox' 'string' 'LIMO for linear analysis of MEEG data using single trials (2.5 Mb)' 'value' 1 'enable' 'on' } ... { } ... { 'style' 'radiobutton' 'string' 'Do not show this query again' 'value' 0 } ... {} ... { 'style' 'text' 'String' 'Note: manage plug-in tools using EEGLAB menu item, "File > Plug-ins > Manage plug-ins"' } ... {} ... { 'Style', 'pushbutton', 'string', 'Do not install now', 'tag' 'cancel' 'callback', 'set(gcbf, ''userdata'', ''cancel'');' } { } ... { 'Style', 'pushbutton', 'string', 'Install plugins now', 'tag', 'ok', 'callback', 'set(gcbf, ''userdata'', ''ok'');' } ... }; geomline = [1]; geom = { [1] [1] geomline geomline geomline geomline geomline geomline [1] geomline [1] [1] [1] [1 1 1]}; geomvert = [ 1 0.5 1 1 1 1 1 1 0.3 1 0.3 1 1 1]; %result = inputgui( 'geometry', geom, 'uilist', uilist, 'helpcom', 'pophelp(''plugin_installstartup'')', 'title', 'Install popular plugins', 'geomvert', geomvert, 'eval', evalstr); fig = figure('visible', 'off'); [tmp1 tmp2 handles] = supergui( 'geomhoriz', geom, 'uilist', uilist, 'title', 'Install popular plugins', 'geomvert', geomvert, 'fig', fig); %, 'eval', evalstr); set(findobj(fig, 'tag', 'title'), 'fontsize', 16); waitfor( fig, 'userdata'); % decode inputs handles results = cellfun(@(x)(get get(handles, 'value')
github
ZijingMao/baselineeegtest-master
topoplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/topoplot.m
70,346
utf_8
4c8f2e9da5704f953687a5b2315bef77
% topoplot() - plot a topographic map of a scalp data field in a 2-D circular view % (looking down at the top of the head) using interpolation on a fine % cartesian grid. Can also show specified channnel location(s), or return % an interpolated value at an arbitrary scalp location (see 'noplot'). % By default, channel locations below head center (arc_length 0.5) are % shown in a 'skirt' outside the cartoon head (see 'plotrad' and 'headrad' % options below). Nose is at top of plot; left is left; right is right. % Using option 'plotgrid', the plot may be one or more rectangular grids. % Usage: % >> topoplot(datavector, EEG.chanlocs); % plot a map using an EEG chanlocs structure % >> topoplot(datavector, 'my_chan.locs'); % read a channel locations file and plot a map % >> topoplot('example'); % give an example of an electrode location file % >> [h grid_or_val plotrad_or_grid, xmesh, ymesh]= ... % topoplot(datavector, chan_locs, 'Input1','Value1', ...); % Required Inputs: % datavector - single vector of channel values. Else, if a vector of selected subset % (int) channel numbers -> mark their location(s) using 'style' 'blank'. % chan_locs - name of an EEG electrode position file (>> topoplot example). % Else, an EEG.chanlocs structure (>> help readlocs or >> topoplot example) % Optional inputs: % 'maplimits' - 'absmax' -> scale map colors to +/- the absolute-max (makes green 0); % 'maxmin' -> scale colors to the data range (makes green mid-range); % [lo.hi] -> use user-definined lo/hi limits % {default: 'absmax'} % 'style' - 'map' -> plot colored map only % 'contour' -> plot contour lines only % 'both' -> plot both colored map and contour lines % 'fill' -> plot constant color between contour lines % 'blank' -> plot electrode locations only {default: 'both'} % 'electrodes' - 'on','off','labels','numbers','ptslabels','ptsnumbers'. To set the 'pts' % marker,,see 'Plot detail options' below. {default: 'on' -> mark electrode % locations with points ('.') unless more than 64 channels, then 'off'}. % 'plotchans' - [vector] channel numbers (indices) to use in making the head plot. % {default: [] -> plot all chans} % 'chantype' - cell array of channel type(s) to plot. Will also accept a single quoted % string type. Channel type for channel k is field EEG.chanlocs(k).type. % If present, overrides 'plotchans' and also 'chaninfo' with field % 'chantype'. Ex. 'EEG' or {'EEG','EOG'} {default: all, or 'plotchans' arg} % 'plotgrid' - [channels] Plot channel data in one or more rectangular grids, as % specified by [channels], a position matrix of channel numbers defining % the topographic locations of the channels in the grid. Zero values are % given the figure background color; negative integers, the color of the % polarity-reversed channel values. Ex: >> figure; ... % >> topoplot(values,'chanlocs','plotgrid',[11 12 0; 13 14 15]); % % Plot a (2,3) grid of data values from channels 11-15 with one empty % grid cell (top right) {default: no grid plot} % 'nosedir' - ['+X'|'-X'|'+Y'|'-Y'] direction of nose {default: '+X'} % 'chaninfo' - [struct] optional structure containing fields 'nosedir', 'plotrad' % and/or 'chantype'. See these (separate) field definitions above, below. % {default: nosedir +X, plotrad 0.5, all channels} % 'plotrad' - [0.15<=float<=1.0] plotting radius = max channel arc_length to plot. % See >> topoplot example. If plotrad > 0.5, chans with arc_length > 0.5 % (i.e. below ears-eyes) are plotted in a circular 'skirt' outside the % cartoon head. See 'intrad' below. {default: max(max(chanlocs.radius),0.5); % If the chanlocs structure includes a field chanlocs.plotrad, its value % is used by default}. % 'headrad' - [0.15<=float<=1.0] drawing radius (arc_length) for the cartoon head. % NOTE: Only headrad = 0.5 is anatomically correct! 0 -> don't draw head; % 'rim' -> show cartoon head at outer edge of the plot {default: 0.5} % 'intrad' - [0.15<=float<=1.0] radius of the scalp map interpolation area (square or % disk, see 'intsquare' below). Interpolate electrodes in this area and use % this limit to define boundaries of the scalp map interpolated data matrix % {default: max channel location radius} % 'intsquare' - ['on'|'off'] 'on' -> Interpolate values at electrodes located in the whole % square containing the (radius intrad) interpolation disk; 'off' -> Interpolate % values from electrodes shown in the interpolation disk only {default: 'on'}. % 'conv' - ['on'|'off'] Show map interpolation only out to the convext hull of % the electrode locations to minimize extrapolation. {default: 'off'} % 'noplot' - ['on'|'off'|[rad theta]] do not plot (but return interpolated data). % Else, if [rad theta] are coordinates of a (possibly missing) channel, % returns interpolated value for channel location. For more info, % see >> topoplot 'example' {default: 'off'} % 'verbose' - ['on'|'off'] comment on operations on command line {default: 'on'}. % % Plot detail options: % 'drawaxis' - ['on'|'off'] draw axis on the top left corner. % 'emarker' - Matlab marker char | {markerchar color size linewidth} char, else cell array % specifying the electrode 'pts' marker. Ex: {'s','r',32,1} -> 32-point solid % red square. {default: {'.','k',[],1} where marker size ([]) depends on the number % of channels plotted}. % 'emarker2' - {markchans}|{markchans marker color size linewidth} cell array specifying % an alternate marker for specified 'plotchans'. Ex: {[3 17],'s','g'} % {default: none, or if {markchans} only are specified, then {markchans,'o','r',10,1}} % 'hcolor' - color of the cartoon head. Use 'hcolor','none' to plot no head. {default: 'k' = black} % 'shading' - 'flat','interp' {default: 'flat'} % 'numcontour' - number of contour lines {default: 6} % 'contourvals' - values for contour {default: same as input values} % 'pmask' - values for masking topoplot. Array of zeros and 1 of the same size as the input % value array {default: []} % 'color' - color of the contours {default: dark grey} % 'whitebk ' - ('on'|'off') make the background color white (e.g., to print empty plotgrid channels) % {default: 'off'} % 'gridscale' - [int > 32] size (nrows) of interpolated scalp map data matrix {default: 67} % 'colormap' - (n,3) any size colormap {default: existing colormap} % 'circgrid' - [int > 100] number of elements (angles) in head and border circles {201} % 'emarkercolor' - cell array of colors for 'blank' option. % 'plotdisk' - ['on'|'off'] plot disk instead of dots for electrodefor 'blank' option. Size of disk % is controled by input values at each electrode. If an imaginary value is provided, % plot partial circle with red for the real value and blue for the imaginary one. % % Dipole plotting options: % 'dipole' - [xi yi xe ye ze] plot dipole on the top of the scalp map % from coordinate (xi,yi) to coordinates (xe,ye,ze) (dipole head % model has radius 1). If several rows, plot one dipole per row. % Coordinates returned by dipplot() may be used. Can accept % an EEG.dipfit.model structure (See >> help dipplot). % Ex: ,'dipole',EEG.dipfit.model(17) % Plot dipole(s) for comp. 17. % 'dipnorm' - ['on'|'off'] normalize dipole length {default: 'on'}. % 'diporient' - [-1|1] invert dipole orientation {default: 1}. % 'diplen' - [real] scale dipole length {default: 1}. % 'dipscale' - [real] scale dipole size {default: 1}. % 'dipsphere' - [real] size of the dipole sphere. {default: 85 mm}. % 'dipcolor' - [color] dipole color as Matlab code code or [r g b] vector % {default: 'k' = black}. % Outputs: % handle - handle of the colored surface.If % contour only is plotted, then is the handle of % the countourgroup. (If no surface or contour is plotted, % return "gca", the handle of the current plot) % grid_or_val - [matrix] the interpolated data image (with off-head points = NaN). % Else, single interpolated value at the specified 'noplot' arg channel % location ([rad theta]), if any. % plotrad_or_grid - IF grid image returned above, then the 'plotrad' radius of the grid. % Else, the grid image % xmesh, ymesh - x and y values of the returned grid (above) % % Chan_locs format: % See >> topoplot 'example' % % Examples: % % To plot channel locations only: % >> figure; topoplot([],EEG.chanlocs,'style','blank','electrodes','labelpoint','chaninfo',EEG.chaninfo); % % Notes: - To change the plot map masking ring to a new figure background color, % >> set(findobj(gca,'type','patch'),'facecolor',get(gcf,'color')) % - Topoplots may be rotated. From the commandline >> view([deg 90]) {default: [0 90]) % % Authors: Andy Spydell, Colin Humphries, Arnaud Delorme & Scott Makeig % CNL / Salk Institute, 8/1996-/10/2001; SCCN/INC/UCSD, Nov. 2001 - % % See also: timtopo(), envtopo() % Deprecated options: % 'shrink' - ['on'|'off'|'force'|factor] Deprecated. 'on' -> If max channel arc_length % > 0.5, shrink electrode coordinates towards vertex to plot all channels % by making max arc_length 0.5. 'force' -> Normalize arc_length % so the channel max is 0.5. factor -> Apply a specified shrink % factor (range (0,1) = shrink fraction). {default: 'off'} % 'electcolor' {'k'} ... electrode marking details and their {defaults}. % 'emarker' {'.'}|'emarkersize' {14}|'emarkersizemark' {40}|'efontsize' {var} - % electrode marking details and their {defaults}. % 'ecolor' - color of the electrode markers {default: 'k' = black} % 'interplimits' - ['electrodes'|'head'] 'electrodes'-> interpolate the electrode grid; % 'head'-> interpolate the whole disk {default: 'head'}. % Unimplemented future options: % Copyright (C) Colin Humphries & Scott Makeig, CNL / Salk Institute, Aug, 1996 % % 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 % Topoplot Version 2.1 % Early development history: % Begun by Andy Spydell and Scott Makeig, NHRC, 7-23-96 % 8-96 Revised by Colin Humphries, CNL / Salk Institute, La Jolla CA % -changed surf command to imagesc (faster) % -can now handle arbitrary scaling of electrode distances % -can now handle non integer angles in chan_locs % 4-4-97 Revised again by Colin Humphries, reformatted by SM % -added parameters % -changed chan_locs format % 2-26-98 Revised by Colin % -changed image back to surface command % -added fill and blank styles % -removed extra background colormap entry (now use any colormap) % -added parameters for electrode colors and labels % -now each topoplot axes use the caxis command again. % -removed OUTPUT parameter % 3-11-98 changed default emarkersize, improve help msg -sm % 5-24-01 made default emarkersize vary with number of channels -sm % 01-25-02 reformated help & license, added link -ad % 03-15-02 added readlocs and the use of eloc input structure -ad % 03-25-02 added 'labelpoint' options and allow Values=[] -ad &sm % 03-25-02 added details to "Unknown parameter" warning -sm & ad function [handle,Zi,grid,Xi,Yi] = topoplot(Values,loc_file,varargin) % %%%%%%%%%%%%%%%%%%%%%%%% Set defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % icadefs % read defaults MAXTOPOPLOTCHANS and DEFAULT_ELOC and BACKCOLOR if ~exist('BACKCOLOR') % if icadefs.m does not define BACKCOLOR BACKCOLOR = [.93 .96 1]; % EEGLAB standard end whitebk = 'off'; % by default, make gridplot background color = EEGLAB screen background color persistent warningInterp; plotgrid = 'off'; plotchans = []; noplot = 'off'; handle = []; Zi = []; chanval = NaN; rmax = 0.5; % actual head radius - Don't change this! INTERPLIMITS = 'head'; % head, electrodes INTSQUARE = 'on'; % default, interpolate electrodes located though the whole square containing % the plotting disk default_intrad = 1; % indicator for (no) specified intrad MAPLIMITS = 'absmax'; % absmax, maxmin, [values] GRID_SCALE = 67; % plot map on a 67X67 grid CIRCGRID = 201; % number of angles to use in drawing circles AXHEADFAC = 1.3; % head to axes scaling factor CONTOURNUM = 6; % number of contour levels to plot STYLE = 'both'; % default 'style': both,straight,fill,contour,blank HEADCOLOR = [0 0 0]; % default head color (black) CCOLOR = [0.2 0.2 0.2]; % default contour color ELECTRODES = []; % default 'electrodes': on|off|label - set below MAXDEFAULTSHOWLOCS = 64;% if more channels than this, don't show electrode locations by default EMARKER = '.'; % mark electrode locations with small disks ECOLOR = [0 0 0]; % default electrode color = black EMARKERSIZE = []; % default depends on number of electrodes, set in code EMARKERLINEWIDTH = 1; % default edge linewidth for emarkers EMARKERSIZE1CHAN = 20; % default selected channel location marker size EMARKERCOLOR1CHAN = 'red'; % selected channel location marker color EMARKER2CHANS = []; % mark subset of electrode locations with small disks EMARKER2 = 'o'; % mark subset of electrode locations with small disks EMARKER2COLOR = 'r'; % mark subset of electrode locations with small disks EMARKERSIZE2 = 10; % default selected channel location marker size EMARKER2LINEWIDTH = 1; EFSIZE = get(0,'DefaultAxesFontSize'); % use current default fontsize for electrode labels HLINEWIDTH = 2; % default linewidth for head, nose, ears BLANKINGRINGWIDTH = .035;% width of the blanking ring HEADRINGWIDTH = .007;% width of the cartoon head ring SHADING = 'flat'; % default 'shading': flat|interp shrinkfactor = []; % shrink mode (dprecated) intrad = []; % default interpolation square is to outermost electrode (<=1.0) plotrad = []; % plotting radius ([] = auto, based on outermost channel location) headrad = []; % default plotting radius for cartoon head is 0.5 squeezefac = 1.0; MINPLOTRAD = 0.15; % can't make a topoplot with smaller plotrad (contours fail) VERBOSE = 'off'; MASKSURF = 'off'; CONVHULL = 'off'; % dont mask outside the electrodes convex hull DRAWAXIS = 'off'; PLOTDISK = 'off'; CHOOSECHANTYPE = 0; ContourVals = Values; PMASKFLAG = 0; COLORARRAY = { [1 0 0] [0.5 0 0] [0 0 0] }; %COLORARRAY2 = { [1 0 0] [0.5 0 0] [0 0 0] }; gb = [0 0]; COLORARRAY2 = { [gb 0] [gb 1/4] [gb 2/4] [gb 3/4] [gb 1] }; %%%%%% Dipole defaults %%%%%%%%%%%% DIPOLE = []; DIPNORM = 'on'; DIPSPHERE = 85; DIPLEN = 1; DIPSCALE = 1; DIPORIENT = 1; DIPCOLOR = [0 0 0]; NOSEDIR = '+X'; CHANINFO = []; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%% Handle arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if nargin< 1 help topoplot; return end % calling topoplot from Fieldtrip % ------------------------------- fieldtrip = 0; if nargin < 2, loc_file = []; end; if isstruct(Values) | ~isstruct(loc_file), fieldtrip == 1; end; if isstr(loc_file), if exist(loc_file) ~= 2, fieldtrip == 1; end; end; if fieldtrip error('Wrong calling format, are you trying to use the topoplot Fieldtrip function?'); end; nargs = nargin; if nargs == 1 if isstr(Values) if any(strcmp(lower(Values),{'example','demo'})) fprintf(['This is an example of an electrode location file,\n',... 'an ascii file consisting of the following four columns:\n',... ' channel_number degrees arc_length channel_name\n\n',... 'Example:\n',... ' 1 -18 .352 Fp1 \n',... ' 2 18 .352 Fp2 \n',... ' 5 -90 .181 C3 \n',... ' 6 90 .181 C4 \n',... ' 7 -90 .500 A1 \n',... ' 8 90 .500 A2 \n',... ' 9 -142 .231 P3 \n',... '10 142 .231 P4 \n',... '11 0 .181 Fz \n',... '12 0 0 Cz \n',... '13 180 .181 Pz \n\n',... ... 'In topoplot() coordinates, 0 deg. points to the nose, positive\n',... 'angles point to the right hemisphere, and negative to the left.\n',... 'The model head sphere has a circumference of 2; the vertex\n',... '(Cz) has arc_length 0. Locations with arc_length > 0.5 are below\n',... 'head center and are plotted outside the head cartoon.\n',... 'Option plotrad controls how much of this lower-head "skirt" is shown.\n',... 'Option headrad controls if and where the cartoon head will be drawn.\n',... 'Option intrad controls how many channels will be included in the interpolation.\n',... ]) return end end end if nargs < 2 loc_file = DEFAULT_ELOC; if ~exist(loc_file) fprintf('default locations file "%s" not found - specify chan_locs in topoplot() call.\n',loc_file) error(' ') end end if isempty(loc_file) loc_file = 0; end if isnumeric(loc_file) & loc_file == 0 loc_file = DEFAULT_ELOC; end if nargs > 2 if ~(round(nargs/2) == nargs/2) error('Odd number of input arguments??') end for i = 1:2:length(varargin) Param = varargin{i}; Value = varargin{i+1}; if ~isstr(Param) error('Flag arguments must be strings') end Param = lower(Param); switch Param case 'conv' CONVHULL = lower(Value); if ~strcmp(CONVHULL,'on') & ~strcmp(CONVHULL,'off') error('Value of ''conv'' must be ''on'' or ''off''.'); end case 'colormap' if size(Value,2)~=3 error('Colormap must be a n x 3 matrix') end colormap(Value) case 'plotdisk' PLOTDISK = lower(Value); if ~strcmp(PLOTDISK,'on') & ~strcmp(PLOTDISK,'off') error('Value of ''plotdisk'' must be ''on'' or ''off''.'); end case 'intsquare' INTSQUARE = lower(Value); if ~strcmp(INTSQUARE,'on') & ~strcmp(INTSQUARE,'off') error('Value of ''intsquare'' must be ''on'' or ''off''.'); end case 'emarkercolors' COLORARRAY = Value; case {'interplimits','headlimits'} if ~isstr(Value) error('''interplimits'' value must be a string') end Value = lower(Value); if ~strcmp(Value,'electrodes') & ~strcmp(Value,'head') error('Incorrect value for interplimits') end INTERPLIMITS = Value; case 'verbose' VERBOSE = Value; case 'nosedir' NOSEDIR = Value; if isempty(strmatch(lower(NOSEDIR), { '+x', '-x', '+y', '-y' })) error('Invalid nose direction'); end; case 'chaninfo' CHANINFO = Value; if isfield(CHANINFO, 'nosedir'), NOSEDIR = CHANINFO.nosedir; end; if isfield(CHANINFO, 'shrink' ), shrinkfactor = CHANINFO.shrink; end; if isfield(CHANINFO, 'plotrad') & isempty(plotrad), plotrad = CHANINFO.plotrad; end; if isfield(CHANINFO, 'chantype') chantype = CHANINFO.chantype; if ischar(chantype), chantype = cellstr(chantype); end CHOOSECHANTYPE = 1; end case 'chantype' chantype = Value; CHOOSECHANTYPE = 1; if ischar(chantype), chantype = cellstr(chantype); end if ~iscell(chantype), error('chantype must be cell array. e.g. {''EEG'', ''EOG''}'); end case 'drawaxis' DRAWAXIS = Value; case 'maplimits' MAPLIMITS = Value; case 'masksurf' MASKSURF = Value; case 'circgrid' CIRCGRID = Value; if isstr(CIRCGRID) | CIRCGRID<100 error('''circgrid'' value must be an int > 100'); end case 'style' STYLE = lower(Value); case 'numcontour' CONTOURNUM = Value; case 'electrodes' ELECTRODES = lower(Value); if strcmpi(ELECTRODES,'pointlabels') | strcmpi(ELECTRODES,'ptslabels') ... | strcmpi(ELECTRODES,'labelspts') | strcmpi(ELECTRODES,'ptlabels') ... | strcmpi(ELECTRODES,'labelpts') ELECTRODES = 'labelpoint'; % backwards compatability elseif strcmpi(ELECTRODES,'pointnumbers') | strcmpi(ELECTRODES,'ptsnumbers') ... | strcmpi(ELECTRODES,'numberspts') | strcmpi(ELECTRODES,'ptnumbers') ... | strcmpi(ELECTRODES,'numberpts') | strcmpi(ELECTRODES,'ptsnums') ... | strcmpi(ELECTRODES,'numspts') ELECTRODES = 'numpoint'; % backwards compatability elseif strcmpi(ELECTRODES,'nums') ELECTRODES = 'numbers'; % backwards compatability elseif strcmpi(ELECTRODES,'pts') ELECTRODES = 'on'; % backwards compatability elseif ~strcmp(ELECTRODES,'off') ... & ~strcmpi(ELECTRODES,'on') ... & ~strcmp(ELECTRODES,'labels') ... & ~strcmpi(ELECTRODES,'numbers') ... & ~strcmpi(ELECTRODES,'labelpoint') ... & ~strcmpi(ELECTRODES,'numpoint') error('Unknown value for keyword ''electrodes'''); end case 'dipole' DIPOLE = Value; case 'dipsphere' DIPSPHERE = Value; case 'dipnorm' DIPNORM = Value; case 'diplen' DIPLEN = Value; case 'dipscale' DIPSCALE = Value; case 'contourvals' ContourVals = Value; case 'pmask' ContourVals = Value; PMASKFLAG = 1; case 'diporient' DIPORIENT = Value; case 'dipcolor' DIPCOLOR = Value; case 'emarker' if ischar(Value) EMARKER = Value; elseif ~iscell(Value) | length(Value) > 4 error('''emarker'' argument must be a cell array {marker color size linewidth}') else EMARKER = Value{1}; end if length(Value) > 1 ECOLOR = Value{2}; end if length(Value) > 2 EMARKERSIZE = Value{3}; end if length(Value) > 3 EMARKERLINEWIDTH = Value{4}; end case 'emarker2' if ~iscell(Value) | length(Value) > 5 error('''emarker2'' argument must be a cell array {chans marker color size linewidth}') end EMARKER2CHANS = abs(Value{1}); % ignore channels < 0 if length(Value) > 1 EMARKER2 = Value{2}; end if length(Value) > 2 EMARKER2COLOR = Value{3}; end if length(Value) > 3 EMARKERSIZE2 = Value{4}; end if length(Value) > 4 EMARKER2LINEWIDTH = Value{5}; end case 'shrink' shrinkfactor = Value; case 'intrad' intrad = Value; if isstr(intrad) | (intrad < MINPLOTRAD | intrad > 1) error('intrad argument should be a number between 0.15 and 1.0'); end case 'plotrad' plotrad = Value; if isstr(plotrad) | (plotrad < MINPLOTRAD | plotrad > 1) error('plotrad argument should be a number between 0.15 and 1.0'); end case 'headrad' headrad = Value; if isstr(headrad) & ( strcmpi(headrad,'off') | strcmpi(headrad,'none') ) headrad = 0; % undocumented 'no head' alternatives end if isempty(headrad) % [] -> none also headrad = 0; end if ~isstr(headrad) if ~(headrad==0) & (headrad < MINPLOTRAD | headrad>1) error('bad value for headrad'); end elseif ~strcmpi(headrad,'rim') error('bad value for headrad'); end case {'headcolor','hcolor'} HEADCOLOR = Value; case {'contourcolor','ccolor'} CCOLOR = Value; case {'electcolor','ecolor'} ECOLOR = Value; case {'emarkersize','emsize'} EMARKERSIZE = Value; case {'emarkersize1chan','emarkersizemark'} EMARKERSIZE1CHAN= Value; case {'efontsize','efsize'} EFSIZE = Value; case 'shading' SHADING = lower(Value); if ~any(strcmp(SHADING,{'flat','interp'})) error('Invalid shading parameter') end if strcmpi(SHADING,'interp') && isempty(warningInterp) warning('Using interpolated shading in scalp topographies prevent to export them as vectorized figures'); warningInterp = 1; end; case 'noplot' noplot = Value; if ~isstr(noplot) if length(noplot) ~= 2 error('''noplot'' location should be [radius, angle]') else chanrad = noplot(1); chantheta = noplot(2); noplot = 'on'; end end case 'gridscale' GRID_SCALE = Value; if isstr(GRID_SCALE) | GRID_SCALE ~= round(GRID_SCALE) | GRID_SCALE < 32 error('''gridscale'' value must be integer > 32.'); end case {'plotgrid','gridplot'} plotgrid = 'on'; gridchans = Value; case 'plotchans' plotchans = Value(:); if find(plotchans<=0) error('''plotchans'' values must be > 0'); end % if max(abs(plotchans))>max(Values) | max(abs(plotchans))>length(Values) -sm ??? case {'whitebk','whiteback','forprint'} whitebk = Value; otherwise error(['Unknown input parameter ''' Param ''' ???']) end end end if strcmpi(whitebk, 'on') BACKCOLOR = [ 1 1 1 ]; end; if isempty(find(strcmp(varargin,'colormap'))) cmap = colormap(DEFAULT_COLORMAP); else cmap = colormap; end cmaplen = size(cmap,1); if strcmp(STYLE,'blank') % else if Values holds numbers of channels to mark if length(Values) < length(loc_file) ContourVals = zeros(1,length(loc_file)); ContourVals(Values) = 1; Values = ContourVals; end; end; % %%%%%%%%%%%%%%%%%%%%%%%%%%% test args for plotting an electrode grid %%%%%%%%%%%%%%%%%%%%%% % if strcmp(plotgrid,'on') STYLE = 'grid'; gchans = sort(find(abs(gridchans(:))>0)); % if setdiff(gchans,unique(gchans)) % fprintf('topoplot() warning: ''plotgrid'' channel matrix has duplicate channels\n'); % end if ~isempty(plotchans) if intersect(gchans,abs(plotchans)) fprintf('topoplot() warning: ''plotgrid'' and ''plotchans'' have channels in common\n'); end end end % %%%%%%%%%%%%%%%%%%%%%%%%%%% misc arg tests %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isempty(ELECTRODES) % if electrode labeling not specified if length(Values) > MAXDEFAULTSHOWLOCS % if more channels than default max ELECTRODES = 'off'; % don't show electrodes else % else if fewer chans, ELECTRODES = 'on'; % do end end if isempty(Values) STYLE = 'blank'; end [r,c] = size(Values); if r>1 & c>1, error('input data must be a single vector'); end Values = Values(:); % make Values a column vector ContourVals = ContourVals(:); % values for contour if ~isempty(intrad) & ~isempty(plotrad) & intrad < plotrad error('intrad must be >= plotrad'); end if ~strcmpi(STYLE,'grid') % if not plot grid only % %%%%%%%%%%%%%%%%%%%% Read the channel location information %%%%%%%%%%%%%%%%%%%%%%%% % if isstr(loc_file) [tmpeloc labels Th Rd indices] = readlocs( loc_file); elseif isstruct(loc_file) % a locs struct [tmpeloc labels Th Rd indices] = readlocs( loc_file ); % Note: Th and Rd correspond to indices channels-with-coordinates only else error('loc_file must be a EEG.locs struct or locs filename'); end Th = pi/180*Th; % convert degrees to radians allchansind = 1:length(Th); if ~isempty(plotchans) if max(plotchans) > length(Th) error('''plotchans'' values must be <= max channel index'); end end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% channels to plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty(plotchans) plotchans = intersect_bc(plotchans, indices); end; if ~isempty(Values) & ~strcmpi( STYLE, 'blank') & isempty(plotchans) plotchans = indices; end if isempty(plotchans) & strcmpi( STYLE, 'blank') plotchans = indices; end % %%%%%%%%%%%%%%%%%%%%%%%%%%% filter for channel type(s), if specified %%%%%%%%%%%%%%%%%%%%% % if CHOOSECHANTYPE, newplotchans = eeg_chantype(loc_file,chantype); plotchans = intersect_bc(newplotchans, plotchans); end % %%%%%%%%%%%%%%%%%%%%%%%%%%% filter channels used for components %%%%%%%%%%%%%%%%%%%%% % if isfield(CHANINFO, 'icachansind') & ~isempty(Values) & length(Values) ~= length(tmpeloc) % test if ICA component % --------------------- if length(CHANINFO.icachansind) == length(Values) % if only a subset of channels are to be plotted % and ICA components also use a subject of channel % we must find the new indices for these channels plotchans = intersect_bc(CHANINFO.icachansind, plotchans); tmpvals = zeros(1, length(tmpeloc)); tmpvals(CHANINFO.icachansind) = Values; Values = tmpvals; tmpvals = zeros(1, length(tmpeloc)); tmpvals(CHANINFO.icachansind) = ContourVals; ContourVals = tmpvals; end; end; % %%%%%%%%%%%%%%%%%%% last channel is reference? %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if length(tmpeloc) == length(Values) + 1 % remove last channel if necessary % (common reference channel) if plotchans(end) == length(tmpeloc) plotchans(end) = []; end; end; % %%%%%%%%%%%%%%%%%%% remove infinite and NaN values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if length(Values) > 1 inds = union_bc(find(isnan(Values)), find(isinf(Values))); % NaN and Inf values plotchans = setdiff_bc(plotchans, inds); end; if strcmp(plotgrid,'on') plotchans = setxor(plotchans,gchans); % remove grid chans from head plotchans end [x,y] = pol2cart(Th,Rd); % transform electrode locations from polar to cartesian coordinates plotchans = abs(plotchans); % reverse indicated channel polarities allchansind = allchansind(plotchans); Th = Th(plotchans); Rd = Rd(plotchans); x = x(plotchans); y = y(plotchans); labels = labels(plotchans); % remove labels for electrodes without locations labels = strvcat(labels); % make a label string matrix if ~isempty(Values) & length(Values) > 1 Values = Values(plotchans); ContourVals = ContourVals(plotchans); end; % %%%%%%%%%%%%%%%%%% Read plotting radius from chanlocs %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isempty(plotrad) & isfield(tmpeloc, 'plotrad'), plotrad = tmpeloc(1).plotrad; if isstr(plotrad) % plotrad shouldn't be a string plotrad = str2num(plotrad) % just checking end if plotrad < MINPLOTRAD | plotrad > 1.0 fprintf('Bad value (%g) for plotrad.\n',plotrad); error(' '); end if strcmpi(VERBOSE,'on') & ~isempty(plotrad) fprintf('Plotting radius plotrad (%g) set from EEG.chanlocs.\n',plotrad); end end; if isempty(plotrad) plotrad = min(1.0,max(Rd)*1.02); % default: just outside the outermost electrode location plotrad = max(plotrad,0.5); % default: plot out to the 0.5 head boundary end % don't plot channels with Rd > 1 (below head) if isempty(intrad) default_intrad = 1; % indicator for (no) specified intrad intrad = min(1.0,max(Rd)*1.02); % default: just outside the outermost electrode location else default_intrad = 0; % indicator for (no) specified intrad if plotrad > intrad plotrad = intrad; end end % don't interpolate channels with Rd > 1 (below head) if isstr(plotrad) | plotrad < MINPLOTRAD | plotrad > 1.0 error('plotrad must be between 0.15 and 1.0'); end % %%%%%%%%%%%%%%%%%%%%%%% Set radius of head cartoon %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isempty(headrad) % never set -> defaults if plotrad >= rmax headrad = rmax; % (anatomically correct) else % if plotrad < rmax headrad = 0; % don't plot head if strcmpi(VERBOSE, 'on') fprintf('topoplot(): not plotting cartoon head since plotrad (%5.4g) < 0.5\n',... plotrad); end end elseif strcmpi(headrad,'rim') % force plotting at rim of map headrad = plotrad; end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Shrink mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty(shrinkfactor) | isfield(tmpeloc, 'shrink'), if isempty(shrinkfactor) & isfield(tmpeloc, 'shrink'), shrinkfactor = tmpeloc(1).shrink; if strcmpi(VERBOSE,'on') if isstr(shrinkfactor) fprintf('Automatically shrinking coordinates to lie above the head perimter.\n'); else fprintf('Automatically shrinking coordinates by %3.2f\n', shrinkfactor); end; end end; if isstr(shrinkfactor) if strcmpi(shrinkfactor, 'on') | strcmpi(shrinkfactor, 'force') | strcmpi(shrinkfactor, 'auto') if abs(headrad-rmax) > 1e-2 fprintf(' NOTE -> the head cartoon will NOT accurately indicate the actual electrode locations\n'); end if strcmpi(VERBOSE,'on') fprintf(' Shrink flag -> plotting cartoon head at plotrad\n'); end headrad = plotrad; % plot head around outer electrodes, no matter if 0.5 or not end else % apply shrinkfactor plotrad = rmax/(1-shrinkfactor); headrad = plotrad; % make deprecated 'shrink' mode plot if strcmpi(VERBOSE,'on') fprintf(' %g%% shrink applied.'); if abs(headrad-rmax) > 1e-2 fprintf(' Warning: With this "shrink" setting, the cartoon head will NOT be anatomically correct.\n'); else fprintf('\n'); end end end end; % if shrink % %%%%%%%%%%%%%%%%% Issue warning if headrad ~= rmax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if headrad ~= 0.5 & strcmpi(VERBOSE, 'on') fprintf(' NB: Plotting map using ''plotrad'' %-4.3g,',plotrad); fprintf( ' ''headrad'' %-4.3g\n',headrad); fprintf('Warning: The plotting radius of the cartoon head is NOT anatomically correct (0.5).\n') end % %%%%%%%%%%%%%%%%%%%%% Find plotting channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pltchans = find(Rd <= plotrad); % plot channels inside plotting circle if strcmpi(INTSQUARE,'on') % interpolate channels in the radius intrad square intchans = find(x <= intrad & y <= intrad); % interpolate and plot channels inside interpolation square else intchans = find(Rd <= intrad); % interpolate channels in the radius intrad circle only end % %%%%%%%%%%%%%%%%%%%%% Eliminate channels not plotted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % allx = x; ally = y; intchans; % interpolate using only the 'intchans' channels pltchans; % plot using only indicated 'plotchans' channels if length(pltchans) < length(Rd) & strcmpi(VERBOSE, 'on') fprintf('Interpolating %d and plotting %d of the %d scalp electrodes.\n', ... length(intchans),length(pltchans),length(Rd)); end; % fprintf('topoplot(): plotting %d channels\n',length(pltchans)); if ~isempty(EMARKER2CHANS) if strcmpi(STYLE,'blank') error('emarker2 not defined for style ''blank'' - use marking channel numbers in place of data'); else % mark1chans and mark2chans are subsets of pltchans for markers 1 and 2 [tmp1 mark1chans tmp2] = setxor(pltchans,EMARKER2CHANS); [tmp3 tmp4 mark2chans] = intersect_bc(EMARKER2CHANS,pltchans); end end if ~isempty(Values) if length(Values) == length(Th) % if as many map Values as channel locs intValues = Values(intchans); intContourVals = ContourVals(intchans); Values = Values(pltchans); ContourVals = ContourVals(pltchans); end; end; % now channel parameters and values all refer to plotting channels only allchansind = allchansind(pltchans); intTh = Th(intchans); % eliminate channels outside the interpolation area intRd = Rd(intchans); intx = x(intchans); inty = y(intchans); Th = Th(pltchans); % eliminate channels outside the plotting area Rd = Rd(pltchans); x = x(pltchans); y = y(pltchans); labels= labels(pltchans,:); % %%%%%%%%%%%%%%% Squeeze channel locations to <= rmax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % squeezefac = rmax/plotrad; intRd = intRd*squeezefac; % squeeze electrode arc_lengths towards the vertex Rd = Rd*squeezefac; % squeeze electrode arc_lengths towards the vertex % to plot all inside the head cartoon intx = intx*squeezefac; inty = inty*squeezefac; x = x*squeezefac; y = y*squeezefac; allx = allx*squeezefac; ally = ally*squeezefac; % Note: Now outermost channel will be plotted just inside rmax else % if strcmpi(STYLE,'grid') intx = rmax; inty=rmax; end % if ~strcmpi(STYLE,'grid') % %%%%%%%%%%%%%%%% rotate channels based on chaninfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(lower(NOSEDIR), '+x') rotate = 0; else if strcmpi(lower(NOSEDIR), '+y') rotate = 3*pi/2; elseif strcmpi(lower(NOSEDIR), '-x') rotate = pi; else rotate = pi/2; end; allcoords = (inty + intx*sqrt(-1))*exp(sqrt(-1)*rotate); intx = imag(allcoords); inty = real(allcoords); allcoords = (ally + allx*sqrt(-1))*exp(sqrt(-1)*rotate); allx = imag(allcoords); ally = real(allcoords); allcoords = (y + x*sqrt(-1))*exp(sqrt(-1)*rotate); x = imag(allcoords); y = real(allcoords); end; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Make the plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~strcmpi(STYLE,'blank') % if draw interpolated scalp map if ~strcmpi(STYLE,'grid') % not a rectangular channel grid % %%%%%%%%%%%%%%%% Find limits for interpolation %%%%%%%%%%%%%%%%%%%%%%%%%%%% % if default_intrad % if no specified intrad if strcmpi(INTERPLIMITS,'head') % intrad is 'head' xmin = min(-rmax,min(intx)); xmax = max(rmax,max(intx)); ymin = min(-rmax,min(inty)); ymax = max(rmax,max(inty)); else % INTERPLIMITS = rectangle containing electrodes -- DEPRECATED OPTION! xmin = max(-rmax,min(intx)); xmax = min(rmax,max(intx)); ymin = max(-rmax,min(inty)); ymax = min(rmax,max(inty)); end else % some other intrad specified xmin = -intrad*squeezefac; xmax = intrad*squeezefac; % use the specified intrad value ymin = -intrad*squeezefac; ymax = intrad*squeezefac; end % %%%%%%%%%%%%%%%%%%%%%%% Interpolate scalp map data %%%%%%%%%%%%%%%%%%%%%%%% % xi = linspace(xmin,xmax,GRID_SCALE); % x-axis description (row vector) yi = linspace(ymin,ymax,GRID_SCALE); % y-axis description (row vector) try [Xi,Yi,Zi] = griddata(inty,intx,double(intValues),yi',xi,'v4'); % interpolate data [Xi,Yi,ZiC] = griddata(inty,intx,double(intContourVals),yi',xi,'v4'); % interpolate data catch, [Xi,Yi,Zi] = griddata(inty,intx,intValues',yi,xi'); % interpolate data (Octave) [Xi,Yi,ZiC] = griddata(inty,intx,intContourVals',yi,xi'); % interpolate data end; % %%%%%%%%%%%%%%%%%%%%%%% Mask out data outside the head %%%%%%%%%%%%%%%%%%%%% % mask = (sqrt(Xi.^2 + Yi.^2) <= rmax); % mask outside the plotting circle ii = find(mask == 0); Zi(ii) = NaN; % mask non-plotting voxels with NaNs ZiC(ii) = NaN; % mask non-plotting voxels with NaNs grid = plotrad; % unless 'noplot', then 3rd output arg is plotrad % %%%%%%%%%% Return interpolated value at designated scalp location %%%%%%%%%% % if exist('chanrad') % optional first argument to 'noplot' chantheta = (chantheta/360)*2*pi; chancoords = round(ceil(GRID_SCALE/2)+GRID_SCALE/2*2*chanrad*[cos(-chantheta),... -sin(-chantheta)]); if chancoords(1)<1 ... | chancoords(1) > GRID_SCALE ... | chancoords(2)<1 ... | chancoords(2)>GRID_SCALE error('designated ''noplot'' channel out of bounds') else chanval = Zi(chancoords(1),chancoords(2)); grid = Zi; Zi = chanval; % return interpolated value instead of Zi end end % %%%%%%%%%%%%%%%%%%%%%%%%%% Return interpolated image only %%%%%%%%%%%%%%%%% % if strcmpi(noplot, 'on') if strcmpi(VERBOSE,'on') fprintf('topoplot(): no plot requested.\n') end return; end % %%%%%%%%%%%%%%%%%%%%%%% Calculate colormap limits %%%%%%%%%%%%%%%%%%%%%%%%%% % if isstr(MAPLIMITS) if strcmp(MAPLIMITS,'absmax') amax = max(max(abs(Zi))); amin = -amax; elseif strcmp(MAPLIMITS,'maxmin') | strcmp(MAPLIMITS,'minmax') amin = min(min(Zi)); amax = max(max(Zi)); else error('unknown ''maplimits'' value.'); end elseif length(MAPLIMITS) == 2 amin = MAPLIMITS(1); amax = MAPLIMITS(2); else error('unknown ''maplimits'' value'); end delta = xi(2)-xi(1); % length of grid entry end % if ~strcmpi(STYLE,'grid') % %%%%%%%%%%%%%%%%%%%%%%%%%% Scale the axes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %cla % clear current axis hold on h = gca; % uses current axes % instead of default larger AXHEADFAC if squeezefac<0.92 & plotrad-headrad > 0.05 % (size of head in axes) AXHEADFAC = 1.05; % do not leave room for external ears if head cartoon % shrunk enough by the 'skirt' option end set(gca,'Xlim',[-rmax rmax]*AXHEADFAC,'Ylim',[-rmax rmax]*AXHEADFAC); % specify size of head axes in gca unsh = (GRID_SCALE+1)/GRID_SCALE; % un-shrink the effects of 'interp' SHADING % %%%%%%%%%%%%%%%%%%%%%%%% Plot grid only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(STYLE,'grid') % plot grid only % % The goal below is to make the grid cells square - not yet achieved in all cases? -sm % g1 = size(gridchans,1); g2 = size(gridchans,2); gmax = max([g1 g2]); Xi = linspace(-rmax*g2/gmax,rmax*g2/gmax,g1+1); Xi = Xi+rmax/g1; Xi = Xi(1:end-1); Yi = linspace(-rmax*g1/gmax,rmax*g1/gmax,g2+1); Yi = Yi+rmax/g2; Yi = Yi(1:end-1); Yi = Yi(end:-1:1); % by trial and error! % %%%%%%%%%%% collect the gridchans values %%%%%%%%%%%%%%%%%%%%%%%%%%% % gridvalues = zeros(size(gridchans)); for j=1:size(gridchans,1) for k=1:size(gridchans,2) gc = gridchans(j,k); if gc > 0 gridvalues(j,k) = Values(gc); elseif gc < 0 gridvalues(j,k) = -Values(gc); else gridvalues(j,k) = nan; % not-a-number = no value end end end % %%%%%%%%%%% reset color limits for grid plot %%%%%%%%%%%%%%%%%%%%%%%%% % if isstr(MAPLIMITS) if strcmp(MAPLIMITS,'maxmin') | strcmp(MAPLIMITS,'minmax') amin = min(min(gridvalues(~isnan(gridvalues)))); amax = max(max(gridvalues(~isnan(gridvalues)))); elseif strcmp(MAPLIMITS,'absmax') % 11/21/2005 Toby edit % This should now work as specified. Before it only crashed (using % "plotgrid" and "maplimits>absmax" options). amax = max(max(abs(gridvalues(~isnan(gridvalues))))); amin = -amax; %amin = -max(max(abs([amin amax]))); %amax = max(max(abs([amin amax]))); else error('unknown ''maplimits'' value'); end elseif length(MAPLIMITS) == 2 amin = MAPLIMITS(1); amax = MAPLIMITS(2); else error('unknown ''maplimits'' value'); end % %%%%%%%%%% explicitly compute grid colors, allowing BACKCOLOR %%%%%% % gridvalues = 1+floor(cmaplen*(gridvalues-amin)/(amax-amin)); gridvalues(find(gridvalues == cmaplen+1)) = cmaplen; gridcolors = zeros([size(gridvalues),3]); for j=1:size(gridchans,1) for k=1:size(gridchans,2) if ~isnan(gridvalues(j,k)) gridcolors(j,k,:) = cmap(gridvalues(j,k),:); else if strcmpi(whitebk,'off') gridcolors(j,k,:) = BACKCOLOR; % gridchans == 0 -> background color % This allows the plot to show 'space' between separate sub-grids or strips else % 'on' gridcolors(j,k,:) = [1 1 1]; BACKCOLOR; % gridchans == 0 -> white for printing end end end end % %%%%%%%%%% draw the gridplot image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % handle=imagesc(Xi,Yi,gridcolors); % plot grid with explicit colors axis square % %%%%%%%%%%%%%%%%%%%%%%%% Plot map contours only %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % elseif strcmp(STYLE,'contour') % plot surface contours only [cls chs] = contour(Xi,Yi,ZiC,CONTOURNUM,'k'); handle = chs; % handle to a contourgroup object % for h=chs, set(h,'color',CCOLOR); end % %%%%%%%%%%%%%%%%%%%%%%%% Else plot map and contours %%%%%%%%%%%%%%%%%%%%%%%%% % elseif strcmp(STYLE,'both') % plot interpolated surface and surface contours if strcmp(SHADING,'interp') tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi))-0.1,Zi,... 'EdgeColor','none','FaceColor',SHADING); else % SHADING == 'flat' tmph = surface(Xi-delta/2,Yi-delta/2,zeros(size(Zi))-0.1,Zi,... 'EdgeColor','none','FaceColor',SHADING); end if strcmpi(MASKSURF, 'on') set(tmph, 'visible', 'off'); handle = tmph; end; warning off; if ~PMASKFLAG [cls chs] = contour(Xi,Yi,ZiC,CONTOURNUM,'k'); else ZiC(find(ZiC > 0.5 )) = NaN; [cls chs] = contourf(Xi,Yi,ZiC,0,'k'); subh = get(chs, 'children'); for indsubh = 1:length(subh) numfaces = size(get(subh(indsubh), 'XData'),1); set(subh(indsubh), 'FaceVertexCData', ones(numfaces,3), 'Cdatamapping', 'direct', 'facealpha', 0.5, 'linewidth', 2); end; end; handle = tmph; % surface handle for h=chs, set(h,'color',CCOLOR); end warning on; % %%%%%%%%%%%%%%%%%%%%%%%% Else plot map only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % elseif strcmp(STYLE,'straight') | strcmp(STYLE,'map') % 'straight' was former arg if strcmp(SHADING,'interp') % 'interp' mode is shifted somehow... but how? tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi)),Zi,'EdgeColor','none',... 'FaceColor',SHADING); else tmph = surface(Xi-delta/2,Yi-delta/2,zeros(size(Zi)),Zi,'EdgeColor','none',... 'FaceColor',SHADING); end if strcmpi(MASKSURF, 'on') set(tmph, 'visible', 'off'); handle = tmph; end; handle = tmph; % surface handle % %%%%%%%%%%%%%%%%%% Else fill contours with uniform colors %%%%%%%%%%%%%%%%%% % elseif strcmp(STYLE,'fill') [cls chs] = contourf(Xi,Yi,Zi,CONTOURNUM,'k'); handle = chs; % handle to a contourgroup object % for h=chs, set(h,'color',CCOLOR); end % <- 'not line objects.' Why does 'both' work above??? else error('Invalid style') end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Set color axis %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % caxis([amin amax]); % set coloraxis % 7/30/2014 Ramon: +-5% for the color limits were added cax_sgn = sign([amin amax]); % getting sign caxis([amin+cax_sgn(1)*(0.05*abs(amin)) amax+cax_sgn(2)*(0.05*abs(amax))]); % Adding 5% to the color limits else % if STYLE 'blank' % %%%%%%%%%%%%%%%%%%%%%%% Draw blank head %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(noplot, 'on') if strcmpi(VERBOSE,'on') fprintf('topoplot(): no plot requested.\n') end return; end %cla hold on set(gca,'Xlim',[-rmax rmax]*AXHEADFAC,'Ylim',[-rmax rmax]*AXHEADFAC) % pos = get(gca,'position'); % fprintf('Current axes size %g,%g\n',pos(3),pos(4)); if strcmp(ELECTRODES,'labelpoint') | strcmp(ELECTRODES,'numpoint') text(-0.6,-0.6, ... [ int2str(length(Rd)) ' of ' int2str(length(tmpeloc)) ' electrode locations shown']); text(-0.6,-0.7, [ 'Click on electrodes to toggle name/number']); tl = title('Channel locations'); set(tl, 'fontweight', 'bold'); end; end % STYLE 'blank' if exist('handle') ~= 1 handle = gca; end; if ~strcmpi(STYLE,'grid') % if not plot grid only % %%%%%%%%%%%%%%%%%%% Plot filled ring to mask jagged grid boundary %%%%%%%%%%%%%%%%%%%%%%%%%%% % hwidth = HEADRINGWIDTH; % width of head ring hin = squeezefac*headrad*(1- hwidth/2); % inner head ring radius if strcmp(SHADING,'interp') rwidth = BLANKINGRINGWIDTH*1.3; % width of blanking outer ring else rwidth = BLANKINGRINGWIDTH; % width of blanking outer ring end rin = rmax*(1-rwidth/2); % inner ring radius if hin>rin rin = hin; % dont blank inside the head ring end if strcmp(CONVHULL,'on') %%%%%%%%% mask outside the convex hull of the electrodes %%%%%%%%% cnv = convhull(allx,ally); cnvfac = round(CIRCGRID/length(cnv)); % spline interpolate the convex hull if cnvfac < 1, cnvfac=1; end; CIRCGRID = cnvfac*length(cnv); startangle = atan2(allx(cnv(1)),ally(cnv(1))); circ = linspace(0+startangle,2*pi+startangle,CIRCGRID); rx = sin(circ); ry = cos(circ); allx = allx(:)'; % make x (elec locations; + to nose) a row vector ally = ally(:)'; % make y (elec locations, + to r? ear) a row vector erad = sqrt(allx(cnv).^2+ally(cnv).^2); % convert to polar coordinates eang = atan2(allx(cnv),ally(cnv)); eang = unwrap(eang); eradi =spline(linspace(0,1,3*length(cnv)), [erad erad erad], ... linspace(0,1,3*length(cnv)*cnvfac)); eangi =spline(linspace(0,1,3*length(cnv)), [eang+2*pi eang eang-2*pi], ... linspace(0,1,3*length(cnv)*cnvfac)); xx = eradi.*sin(eangi); % convert back to rect coordinates yy = eradi.*cos(eangi); yy = yy(CIRCGRID+1:2*CIRCGRID); xx = xx(CIRCGRID+1:2*CIRCGRID); eangi = eangi(CIRCGRID+1:2*CIRCGRID); eradi = eradi(CIRCGRID+1:2*CIRCGRID); xx = xx*1.02; yy = yy*1.02; % extend spline outside electrode marks splrad = sqrt(xx.^2+yy.^2); % arc radius of spline points (yy,xx) oob = find(splrad >= rin); % enforce an upper bound on xx,yy xx(oob) = rin*xx(oob)./splrad(oob); % max radius = rin yy(oob) = rin*yy(oob)./splrad(oob); % max radius = rin splrad = sqrt(xx.^2+yy.^2); % arc radius of spline points (yy,xx) oob = find(splrad < hin); % don't let splrad be inside the head cartoon xx(oob) = hin*xx(oob)./splrad(oob); % min radius = hin yy(oob) = hin*yy(oob)./splrad(oob); % min radius = hin ringy = [[ry(:)' ry(1) ]*(rin+rwidth) yy yy(1)]; ringx = [[rx(:)' rx(1) ]*(rin+rwidth) xx xx(1)]; ringh2= patch(ringy,ringx,ones(size(ringy)),BACKCOLOR,'edgecolor','none'); hold on % plot(ry*rmax,rx*rmax,'b') % debugging line else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% mask the jagged border around rmax %%%%%%%%%%%%%%%5%%%%%% circ = linspace(0,2*pi,CIRCGRID); rx = sin(circ); ry = cos(circ); ringx = [[rx(:)' rx(1) ]*(rin+rwidth) [rx(:)' rx(1)]*rin]; ringy = [[ry(:)' ry(1) ]*(rin+rwidth) [ry(:)' ry(1)]*rin]; if ~strcmpi(STYLE,'blank') ringh= patch(ringx,ringy,0.01*ones(size(ringx)),BACKCOLOR,'edgecolor','none'); hold on end % plot(ry*rmax,rx*rmax,'b') % debugging line end %f1= fill(rin*[rx rX],rin*[ry rY],BACKCOLOR,'edgecolor',BACKCOLOR); hold on %f2= fill(rin*[rx rX*(1+rwidth)],rin*[ry rY*(1+rwidth)],BACKCOLOR,'edgecolor',BACKCOLOR); % Former line-style border smoothing - width did not scale with plot % brdr=plot(1.015*cos(circ).*rmax,1.015*sin(circ).*rmax,... % old line-based method % 'color',HEADCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % plot skirt outline % set(brdr,'color',BACKCOLOR,'linewidth',HLINEWIDTH + 4); % hide the disk edge jaggies % %%%%%%%%%%%%%%%%%%%%%%%%% Plot cartoon head, ears, nose %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if headrad > 0 % if cartoon head to be plotted % %%%%%%%%%%%%%%%%%%% Plot head outline %%%%%%%%%%%%%%%%%%%%%%%%%%% % headx = [[rx(:)' rx(1) ]*(hin+hwidth) [rx(:)' rx(1)]*hin]; heady = [[ry(:)' ry(1) ]*(hin+hwidth) [ry(:)' ry(1)]*hin]; if ~isstr(HEADCOLOR) | ~strcmpi(HEADCOLOR,'none') %ringh= patch(headx,heady,ones(size(headx)),HEADCOLOR,'edgecolor',HEADCOLOR,'linewidth', HLINEWIDTH); hold on headx = [rx(:)' rx(1)]*hin; heady = [ry(:)' ry(1)]*hin; ringh= plot(headx,heady); set(ringh, 'color',HEADCOLOR,'linewidth', HLINEWIDTH); hold on end % rx = sin(circ); rX = rx(end:-1:1); % ry = cos(circ); rY = ry(end:-1:1); % for k=2:2:CIRCGRID % rx(k) = rx(k)*(1+hwidth); % ry(k) = ry(k)*(1+hwidth); % end % f3= fill(hin*[rx rX],hin*[ry rY],HEADCOLOR,'edgecolor',HEADCOLOR); hold on % f4= fill(hin*[rx rX*(1+hwidth)],hin*[ry rY*(1+hwidth)],HEADCOLOR,'edgecolor',HEADCOLOR); % Former line-style head % plot(cos(circ).*squeezefac*headrad,sin(circ).*squeezefac*headrad,... % 'color',HEADCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % plot head outline % %%%%%%%%%%%%%%%%%%% Plot ears and nose %%%%%%%%%%%%%%%%%%%%%%%%%%% % base = rmax-.0046; basex = 0.18*rmax; % nose width tip = 1.15*rmax; tiphw = .04*rmax; % nose tip half width tipr = .01*rmax; % nose tip rounding q = .04; % ear lengthening EarX = [.497-.005 .510 .518 .5299 .5419 .54 .547 .532 .510 .489-.005]; % rmax = 0.5 EarY = [q+.0555 q+.0775 q+.0783 q+.0746 q+.0555 -.0055 -.0932 -.1313 -.1384 -.1199]; sf = headrad/plotrad; % squeeze the model ears and nose % by this factor if ~isstr(HEADCOLOR) | ~strcmpi(HEADCOLOR,'none') plot3([basex;tiphw;0;-tiphw;-basex]*sf,[base;tip-tipr;tip;tip-tipr;base]*sf,... 2*ones(size([basex;tiphw;0;-tiphw;-basex])),... 'Color',HEADCOLOR,'LineWidth',HLINEWIDTH); % plot nose plot3(EarX*sf,EarY*sf,2*ones(size(EarX)),'color',HEADCOLOR,'LineWidth',HLINEWIDTH) % plot left ear plot3(-EarX*sf,EarY*sf,2*ones(size(EarY)),'color',HEADCOLOR,'LineWidth',HLINEWIDTH) % plot right ear end end % % %%%%%%%%%%%%%%%%%%% Show electrode information %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plotax = gca; axis square % make plotax square axis off pos = get(gca,'position'); xlm = get(gca,'xlim'); ylm = get(gca,'ylim'); % textax = axes('position',pos,'xlim',xlm,'ylim',ylm); % make new axes so clicking numbers <-> labels % will work inside head cartoon patch % axes(textax); axis square % make textax square pos = get(gca,'position'); set(plotax,'position',pos); xlm = get(gca,'xlim'); set(plotax,'xlim',xlm); ylm = get(gca,'ylim'); set(plotax,'ylim',ylm); % copy position and axis limits again axis equal; set(gca, 'xlim', [-0.525 0.525]); set(plotax, 'xlim', [-0.525 0.525]); set(gca, 'ylim', [-0.525 0.525]); set(plotax, 'ylim', [-0.525 0.525]); %get(textax,'pos') % test if equal! %get(plotax,'pos') %get(textax,'xlim') %get(plotax,'xlim') %get(textax,'ylim') %get(plotax,'ylim') if isempty(EMARKERSIZE) EMARKERSIZE = 10; if length(y)>=160 EMARKERSIZE = 3; elseif length(y)>=128 EMARKERSIZE = 3; elseif length(y)>=100 EMARKERSIZE = 3; elseif length(y)>=80 EMARKERSIZE = 4; elseif length(y)>=64 EMARKERSIZE = 5; elseif length(y)>=48 EMARKERSIZE = 6; elseif length(y)>=32 EMARKERSIZE = 8; end end % %%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations only %%%%%%%%%%%%%%%%%%%%%%%%%% % ELECTRODE_HEIGHT = 2.1; % z value for plotting electrode information (above the surf) if strcmp(ELECTRODES,'on') % plot electrodes as spots if isempty(EMARKER2CHANS) hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,... EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH); else % plot markers for normal chans and EMARKER2CHANS separately hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,... EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH); hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,... EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2); end % %%%%%%%%%%%%%%%%%%%%%%%% Print electrode labels only %%%%%%%%%%%%%%%%%%%%%%%%%%%% % elseif strcmp(ELECTRODES,'labels') % print electrode names (labels) for i = 1:size(labels,1) text(double(y(i)),double(x(i)),... ELECTRODE_HEIGHT,labels(i,:),'HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',ECOLOR,... 'FontSize',EFSIZE) end % %%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations plus labels %%%%%%%%%%%%%%%%%%% % elseif strcmp(ELECTRODES,'labelpoint') if isempty(EMARKER2CHANS) hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,... EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH); else hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,... EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH); hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,... EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2); end for i = 1:size(labels,1) hh(i) = text(double(y(i)+0.01),double(x(i)),... ELECTRODE_HEIGHT,labels(i,:),'HorizontalAlignment','left',... 'VerticalAlignment','middle','Color', ECOLOR,'userdata', num2str(allchansind(i)), ... 'FontSize',EFSIZE, 'buttondownfcn', ... ['tmpstr = get(gco, ''userdata'');'... 'set(gco, ''userdata'', get(gco, ''string''));' ... 'set(gco, ''string'', tmpstr); clear tmpstr;'] ); end % %%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations plus numbers %%%%%%%%%%%%%%%%%%% % elseif strcmp(ELECTRODES,'numpoint') if isempty(EMARKER2CHANS) hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,... EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH); else hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,... EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH); hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,... EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2); end for i = 1:size(labels,1) hh(i) = text(double(y(i)+0.01),double(x(i)),... ELECTRODE_HEIGHT,num2str(allchansind(i)),'HorizontalAlignment','left',... 'VerticalAlignment','middle','Color', ECOLOR,'userdata', labels(i,:) , ... 'FontSize',EFSIZE, 'buttondownfcn', ... ['tmpstr = get(gco, ''userdata'');'... 'set(gco, ''userdata'', get(gco, ''string''));' ... 'set(gco, ''string'', tmpstr); clear tmpstr;'] ); end % %%%%%%%%%%%%%%%%%%%%%% Print electrode numbers only %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % elseif strcmp(ELECTRODES,'numbers') for i = 1:size(labels,1) text(double(y(i)),double(x(i)),... ELECTRODE_HEIGHT,int2str(allchansind(i)),'HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',ECOLOR,... 'FontSize',EFSIZE) end % %%%%%%%%%%%%%%%%%%%%%% Mark emarker2 electrodes only %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % elseif strcmp(ELECTRODES,'off') & ~isempty(EMARKER2CHANS) hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,... EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2); end % %%%%%%%% Mark specified electrode locations with red filled disks %%%%%%%%%%%%%%%%%%%%%% % try, if strcmpi(STYLE,'blank') % if mark-selected-channel-locations mode for kk = 1:length(1:length(x)) if abs(Values(kk)) if PLOTDISK angleRatio = real(Values(kk))/(real(Values(kk))+imag(Values(kk)))*360; radius = real(Values(kk))+imag(Values(kk)); allradius = [0.02 0.03 0.037 0.044 0.05]; radius = allradius(radius); hp2 = disk(y(kk),x(kk),radius, [1 0 0], 0 , angleRatio, 16); if angleRatio ~= 360 hp2 = disk(y(kk),x(kk),radius, [0 0 1], angleRatio, 360, 16); end; else tmpcolor = COLORARRAY{max(1,min(Values(kk), length(COLORARRAY)))}; hp2 = plot3(y(kk),x(kk),ELECTRODE_HEIGHT,EMARKER,'Color', tmpcolor, 'markersize', EMARKERSIZE1CHAN); hp2 = disk(y(kk),x(kk),0.04, tmpcolor, 0, 360, 10); end; end; end end catch, end; % %%%%%%%%%%%%%%%%%%%%%%%%%%% Plot dipole(s) on the scalp map %%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty(DIPOLE) hold on; tmp = DIPOLE; if isstruct(DIPOLE) if ~isfield(tmp,'posxyz') error('dipole structure is not an EEG.dipfit.model') end DIPOLE = []; % Note: invert x and y from dipplot usage DIPOLE(:,1) = -tmp.posxyz(:,2)/DIPSPHERE; % -y -> x DIPOLE(:,2) = tmp.posxyz(:,1)/DIPSPHERE; % x -> y DIPOLE(:,3) = -tmp.momxyz(:,2); DIPOLE(:,4) = tmp.momxyz(:,1); else DIPOLE(:,1) = -tmp(:,2); % same for vector input DIPOLE(:,2) = tmp(:,1); DIPOLE(:,3) = -tmp(:,4); DIPOLE(:,4) = tmp(:,3); end; for index = 1:size(DIPOLE,1) if ~any(DIPOLE(index,:)) DIPOLE(index,:) = []; end end; DIPOLE(:,1:4) = DIPOLE(:,1:4)*rmax*(rmax/plotrad); % scale radius from 1 -> rmax (0.5) DIPOLE(:,3:end) = (DIPOLE(:,3:end))*rmax/100000*(rmax/plotrad); if strcmpi(DIPNORM, 'on') for index = 1:size(DIPOLE,1) DIPOLE(index,3:4) = DIPOLE(index,3:4)/norm(DIPOLE(index,3:end))*0.2; end; end; DIPOLE(:, 3:4) = DIPORIENT*DIPOLE(:, 3:4)*DIPLEN; PLOT_DIPOLE=1; if sum(DIPOLE(1,3:4).^2) <= 0.00001 if strcmpi(VERBOSE,'on') fprintf('Note: dipole is length 0 - not plotted\n') end PLOT_DIPOLE = 0; end if 0 % sum(DIPOLE(1,1:2).^2) > plotrad if strcmpi(VERBOSE,'on') fprintf('Note: dipole is outside plotting area - not plotted\n') end PLOT_DIPOLE = 0; end if PLOT_DIPOLE for index = 1:size(DIPOLE,1) hh = plot( DIPOLE(index, 1), DIPOLE(index, 2), '.'); set(hh, 'color', DIPCOLOR, 'markersize', DIPSCALE*30); hh = line( [DIPOLE(index, 1) DIPOLE(index, 1)+DIPOLE(index, 3)]', ... [DIPOLE(index, 2) DIPOLE(index, 2)+DIPOLE(index, 4)]',[10 10]); set(hh, 'color', DIPCOLOR, 'linewidth', DIPSCALE*30/7); end; end; end; end % if ~ 'gridplot' % %%%%%%%%%%%%% Plot axis orientation %%%%%%%%%%%%%%%%%%%% % if strcmpi(DRAWAXIS, 'on') axes('position', [0 0.85 0.08 0.1]); axis off; coordend1 = sqrt(-1)*3; coordend2 = -3; coordend1 = coordend1*exp(sqrt(-1)*rotate); coordend2 = coordend2*exp(sqrt(-1)*rotate); line([5 5+round(real(coordend1))]', [5 5+round(imag(coordend1))]', 'color', 'k'); line([5 5+round(real(coordend2))]', [5 5+round(imag(coordend2))]', 'color', 'k'); if round(real(coordend2))<0 text( 5+round(real(coordend2))*1.2, 5+round(imag(coordend2))*1.2-2, '+Y'); else text( 5+round(real(coordend2))*1.2, 5+round(imag(coordend2))*1.2, '+Y'); end; if round(real(coordend1))<0 text( 5+round(real(coordend1))*1.2, 5+round(imag(coordend1))*1.2+1.5, '+X'); else text( 5+round(real(coordend1))*1.2, 5+round(imag(coordend1))*1.2, '+X'); end; set(gca, 'xlim', [0 10], 'ylim', [0 10]); end; % %%%%%%%%%%%%% Set EEGLAB background color to match head border %%%%%%%%%%%%%%%%%%%%%%%% % try, set(gcf, 'color', BACKCOLOR); catch, end; hold off axis off return % %%%%%%%%%%%%% Draw circle %%%%%%%%%%%%%%%%%%%%%%%% % function h2 = disk(X, Y, radius, colorfill, oriangle, endangle, segments) A = linspace(oriangle/180*pi, endangle/180*pi, segments-1); if endangle-oriangle == 360 A = linspace(oriangle/180*pi, endangle/180*pi, segments); h2 = patch( [X + cos(A)*radius(1)], [Y + sin(A)*radius(end)], zeros(1,segments)+3, colorfill); else A = linspace(oriangle/180*pi, endangle/180*pi, segments-1); h2 = patch( [X X + cos(A)*radius(1)], [Y Y + sin(A)*radius(end)], zeros(1,segments)+3, colorfill); end; set(h2, 'FaceColor', colorfill); set(h2, 'EdgeColor', 'none');
github
ZijingMao/baselineeegtest-master
readegilocs.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readegilocs.m
2,898
utf_8
db357ca683b59cbb87ff64dc2cc5bb0b
% readegilocs() - look up locations for EGI EEG dataset. % % Usage: % >> EEG = readegilocs(EEG); % >> EEG = readegilocs(EEG, fileloc); % % Inputs: % EEG - EEGLAB data structure % % Optional input: % fileloc - EGI channel location file % % Outputs: % EEG - EEGLAB data structure with channel location structure % % Author: Arnaud Delorme, SCCN/UCSD % % See also: pop_readegi(), readegi() % Copyright (C) 12 Nov 2002 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 EEG = readegilocs(EEG, fileloc); if nargin < 1 help readegilocs; return; end; % importing channel locations % --------------------------- found = 1; if nargin < 2 switch EEG.nbchan case { 32 33 }, fileloc = 'GSN-HydroCel-32.sfp'; case { 64 65 }, fileloc = 'GSN65v2_0.sfp'; case { 128 129 }, fileloc = 'GSN129.sfp'; case { 256 257 }, fileloc = 'GSN-HydroCel-257.sfp'; otherwise, found = 0; end; end; if found fprintf('EGI channel location automatically detected %s ********* WARNING please check that this the proper file\n', fileloc); if EEG.nbchan == 64 || EEG.nbchan == 65 || EEG.nbchan == 256 || EEG.nbchan == 257 fprintf( [ 'Warning: this function assumes you have a 64-channel system Version 2\n' ... ' if this is not the case, update the channel location with the proper file' ]); end; % remove the last channel for 33 channels peeglab = fileparts(which('eeglab.m')); fileloc = fullfile(peeglab, 'sample_locs', fileloc); locs = readlocs(fileloc); locs(1).type = 'FID'; locs(2).type = 'FID'; locs(3).type = 'FID'; locs(end).type = 'REF'; if EEG.nbchan == 256 || EEG.nbchan == 257 if EEG.nbchan == 256 chaninfo.nodatchans = locs([end]); locs([end]) = []; end; elseif mod(EEG.nbchan,2) == 0, chaninfo.nodatchans = locs([1 2 3 end]); locs([1 2 3 end]) = []; else chaninfo.nodatchans = locs([1 2 3]); locs([1 2 3]) = []; end; % remove reference chaninfo.filename = fileloc; EEG.chanlocs = locs; EEG.urchanlocs = locs; EEG.chaninfo = chaninfo; end;
github
ZijingMao/baselineeegtest-master
eyelike.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eyelike.m
748
utf_8
83fb00bb12b75f143a88314e92ebe31f
% eyelike() - calculate a permutation matrix P and a scaling (diagonal) maxtrix S % such that S*P*E is eyelike (so permutation acts on the rows of E). % E must be a square matrix. % Usage: % >> [eyelike, S, P] = eyelike(E); % % Author: Benjamin Blankertz ([email protected]) 3/2/00 function [eyelikeres, S, P]= eyelike(E) [N, M]= size(E); if N ~= M fprintf('eyeLike(): input matrix must be square.\n'); return end R= E./repmat(sum(abs(E),2),1,N); Rabs= abs(R); P= zeros(N); for n=1:N [so, si]= sort(-Rabs(:)); [chosenV, chosenH]= ind2sub([N N], si(1)); P(chosenH,chosenV)= 1; Rabs(chosenV,:)= repmat(-inf, 1, N); Rabs(:,chosenH)= repmat(-inf, N, 1); end S= diag(1./diag(P*E)); eyelikeres= S*P*E;
github
ZijingMao/baselineeegtest-master
trial2eegplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/trial2eegplot.m
1,822
utf_8
5c1c543407f5710d59e780a95904b9d5
% trial2eegplot() - convert eeglab format to eeplot format of rejection window % % Usage: % >> eegplotarray = trial2eegplot(rej, rejE, points, color); % % Inputs: % rej - rejection vector (0 and 1) with one value per trial % rejE - electrode rejection array (size nb_elec x trials) also % made of 0 and 1. % points - number of points per trials % color - color of the windows for eegplot() % % Outputs: % eegplotarray - array defining windows which is compatible with % the function eegplot() % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eegtresh(), eeglab(), eegplot(), pop_rejepoch() % Copyright (C) 2001 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 rejeegplot = trial2eegplot( rej, rejE, pnts, color) rej = find(rej>0); rejE = rejE(:, rej)'; rejeegplot = zeros(length(rej), size(rejE,2)+5); rejeegplot(:, 6:end) = rejE; rejeegplot(:, 1) = (rej(:)-1)*pnts; rejeegplot(:, 2) = rej(:)*pnts-1; rejeegplot(:, 3:5) = ones(size(rejeegplot,1),1)*color; return
github
ZijingMao/baselineeegtest-master
eegplot2event.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eegplot2event.m
2,932
utf_8
f36ca0fc4d6df10d0b3f83cc6f657f74
% eegplot2event() - convert EEGPLOT rejections into events % compatible with the eeg_eegrej function for rejecting % continuous portions of datasets. % % Usage: % >> [events] = eegplot2event( eegplotrej, type, colorin, colorout ); % % Inputs: % eegplotrej - EEGPLOT output (TMPREJ; see eegplot for more details) % type - type of the event. Default -1. % colorin - only extract rejection of specific colors (here a n x 3 % array must be given). Default: extract all rejections. % colorout - do not extract rejection of specified colors. % % Outputs: % events - array of events compatible with the eeg_eegrej function % for rejecting continuous portions of datasets. % % Example: % NEWEEG = eeg_eegrej(EEG,eegplot2event(TMPREJ, -1)); % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eegplot(), eeg_multieegplot(), eegplot2trial(), eeglab() % Copyright (C) 2001 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 events = eegplot2event( TMPREJ, type, color, colorout ) if nargin < 1 help eegplot2event; return; end; if nargin < 2 type = -1; end; % only take into account specific colors % -------------------------------------- if exist('color') == 1 for index = 1:size(color,1) tmpcol1 = TMPREJ(:,3) + 255*TMPREJ(:,4) + 255*255*TMPREJ(:,5); tmpcol2 = color(index,1)+255*color(index,2)+255*255*color(index,3); I = find( tmpcol1 == tmpcol2); if isempty(I) fprintf('Warning: color [%d %d %d] not found\n', ... color(index,1), color(index,2), color(index,3)); end; TMPREJ = TMPREJ(I,:); end; end; % remove other specific colors % ---------------------------- if exist('colorout') == 1 for index = 1:size(colorout,1) tmpcol1 = TMPREJ(:,3) + 255*TMPREJ(:,4) + 255*255*TMPREJ(:,5); tmpcol2 = colorout(index,1)+255*colorout(index,2)+255*255*colorout(index,3); I = find( tmpcol1 ~= tmpcol2); TMPREJ = TMPREJ(I,:); end; end; events = []; if ~isempty(TMPREJ) events = TMPREJ(:,1:5); events = [ type*ones(size(events,1), 1) ones(size(events,1), 1) round(events(:,1:2)) events(:,3:5)]; end; return;
github
ZijingMao/baselineeegtest-master
celltomat.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/celltomat.m
1,264
utf_8
2c99b2d1c464697b97f856035aa819f6
% celltomat() - convert cell array to matrix % % Usage: >> M = celltomat( C ); % % Author: Arnaud Delorme, CNL / Salk Institute, Jan 25 2002 % % Note: This function overloads the neuralnet toolbox function CELLTOMAT, % but does not have all its capacities. Delete this version if you have % the toolbox. % Copyright (C) Jan 25 2002 Arnaud Delorme, CNL / Salk Institute % % 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 = celltomat( C, varargin ); if nargin < 1 help celltomat; return; end; M = zeros(size(C)); for i=1:size(C,1) for j=1:size(C,2) M(i,j) = C{i,j}; end; end;
github
ZijingMao/baselineeegtest-master
matsel.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/matsel.m
3,756
utf_8
3779008d46e2601576fba59179f48a0c
% matsel() - select rows, columns, and epochs from given multi-epoch data matrix % % Usage: % >> [dataout] = matsel(data,frames,framelist); % >> [dataout] = matsel(data,frames,framelist,chanlist); % >> [dataout] = matsel(data,frames,framelist,chanlist,epochlist); % % Inputs: % data - input data matrix (chans,frames*epochs) % frames - frames (data columns) per epoch (0 -> frames*epochs) % framelist - list of frames per epoch to select (0 -> 1:frames) % chanlist - list of chans to select (0 -> 1:chans) % epochlist - list of epochs to select (0 -> 1:epochs) % % Note: The size of dataout is (length(chanlist), length(framelist)*length(epochlist)) % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 5-21-96 % Copyright (C) 5-21-96 Scott Makeig, 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 % 5-25-96 added chanlist, epochlist -sm % 10-05-97 added out of bounds tests for chanlist and framelist -sm % 02-04-00 truncate to epochs*frames if necessary -sm % 01-25-02 reformated help & license -ad function [dataout] = matsel(data,frames,framelist,chanlist,epochlist) if nargin<1 help matsel return end [chans framestot] = size(data); if isempty(data) fprintf('matsel(): empty data matrix!?\n') help matsel return end if nargin < 5, epochlist = 0; end if nargin < 4, chanlist = 0; end if nargin < 3, fprintf('matsel(): needs at least 3 arguments.\n\n'); return end if frames == 0, frames = framestot; end if framelist == 0, framelist = [1:frames]; end framesout = length(framelist); if isempty(chanlist) | chanlist == 0, chanlist = [1:chans]; end chansout = length(chanlist); epochs = floor(framestot/frames); if epochs*frames ~= framestot fprintf('matsel(): data length %d was not a multiple of %d frames.\n',... framestot,frames); data = data(:,1:epochs*frames); end if isempty(epochlist) | epochlist == 0, epochlist = [1:epochs]; end epochsout = length(epochlist); if max(epochlist)>epochs fprintf('matsel() error: max index in epochlist (%d) > epochs in data (%d)\n',... max(epochlist),epochs); return end if max(framelist)>frames fprintf('matsel() error: max index in framelist (%d) > frames per epoch (%d)\n',... max(framelist),frames); return end if min(framelist)<1 fprintf('matsel() error: framelist min (%d) < 1\n', min(framelist)); return end if min(epochlist)<1 fprintf('matsel() error: epochlist min (%d) < 1\n', min(epochlist)); return end if max(chanlist)>chans fprintf('matsel() error: chanlist max (%d) > chans (%d)\n',... max(chanlist),chans); return end if min(chanlist)<1 fprintf('matsel() error: chanlist min (%d) <1\n',... min(chanlist)); return end dataout = zeros(chansout,framesout*epochsout); for e=1:epochsout dataout(:,framesout*(e-1)+1:framesout*e) = ... data(chanlist,framelist+(epochlist(e)-1)*frames); end
github
ZijingMao/baselineeegtest-master
axcopy.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/axcopy.m
3,176
utf_8
f425a07736a8472959fc9760a6f78f8f
% axcopy() - Copy a Matlab figure axis and its graphic objects to a new pop-up window % using the left mouse button. % % Usage: >> axcopy % >> axcopy(fig) % >> axcopy('noticks') % >> axcopy(fig, command) % % Notes: % 1) Clicking the left mouse button on a Matlab figure axis copies the graphic objects % in the axis to a new (pop-up) figure window. % 2) Option 'noticks' does not make x and y tickloabelmodes 'auto' in the pop-up. % 2) The command option is an optional string that is evaluated in the new window % when it pops up. This allows the user to customize the pop-up display. % 3) Deleting the pop-up window containing the copied axis leaves the selected axis % as the current graphic axis (gca). % Authors: Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000 % Copyright (C) 2000 Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, 3-16-00 % % 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 % requires copyaxes.m % 4-2-00 added 'noticks' -sm % 01-25-02 reformated help & license -ad % 02-16-02 debuged exist('fig') -> exist('fig') == 1 -ad % 02-16-02 added the ignore parent size option -ad % 03-11-02 remove size option and added command option -ad function axcopy(fig, command) if (exist('fig') == 1) & strcmp(fig,'noticks') noticks = 1; if nargin> 1 shift else fig = []; end end if ~(exist('fig') ==1) | isempty(fig) | fig == 0 fig = gcf; end if ~strcmpi(get(fig, 'type'), 'axes') hndl= findobj('parent',fig,'type','axes'); else hndl=fig; end; offidx=[]; if exist('command') ~= 1 comstr = 'copyaxis'; else command_dbl = double(command); comstr = double(['copyaxis(''' char(command_dbl) ''')']); end; for a=1:length(hndl) % make all axes visible allobjs = findobj('parent',hndl(a)); for index = 1:length(allobjs) if isempty(get(allobjs(index), 'ButtonDownFcn')) set(allobjs(index), 'ButtonDownFcn', char(comstr)); end; end; end if ~strcmpi(get(fig, 'type'), 'axes') figure(fig); else figure(get(fig, 'parent')); end; if exist('command') ~= 1 set(hndl(a),'ButtonDownFcn','copyaxis'); else % set(hndl,'ButtonDownFcn',['copyaxis(''' command ''')']); comstr = double(['copyaxis(''' char(command_dbl) ''')']); set(hndl,'ButtonDownFcn',char(comstr)); end; %set(hndl,'ButtonDownFcn','copyaxis'); %if ~exist('noticks') %axis on %set(gca,'xticklabelmode','auto') %set(gca,'yticklabelmode','auto') %end
github
ZijingMao/baselineeegtest-master
eegthresh.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/eegthresh.m
4,674
utf_8
b6eb3049ae5ed15cfe382dd6b942d0ab
% eegthresh() - classical trial rejection rejection using a threshold on % the raw signal % % Usage: % >> [Iin, Iout, newsignal, elec] = eegthresh( signal, frames, ... % elecs, negthresh, posthresh, timerange, starttime, entime) % % Inputs: % signal - signal 2D, channels x (frames*sweeps) or 3D channels x % frames x sweeps % frames - number of points per epoch % elecs - [e1 e2 ...] electrodes (number) to take into % consideration for rejection % negthresh - negative threshold limit in mV (can be an array if % several electrodes; if less numbe of values than number % of electrodes the last value is used for the remaining % electrodes) % posthresh - positive threshold limit in mV (same syntax as % negthresh) % timerange - [mintime maxtime] timerange limit in second % starttime - starting time limit in second (same syntax as % negthresh) % endtime - ending time limit in second (same syntax as negthresh) % % Outputs: % Iin - Indexes of sweeps not rejected % Iout - Indexes of sweeps rejected % newsignal - signal after % sweeps rejection (same number of dimension as signal) % elec - electrode that served for the rejection (array of 0 and % 1, same number of column as Iout, rows=number of % electrodes) % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: pop_eegthresh(), eeglab() % Copyright (C) 2001 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 [Iin, Iout, newsignal, elec] = eegthresh( signal, pnts, electrodes, negthresh, posthresh, timerange, starttime, endtime); if nargin < 7 help eegthresh; return; end; if starttime < timerange(1) disp('eegthresh: starting point out of range, adjusted'); startime = timerange(1); end; if endtime > timerange(2) disp('eegthresh: ending point out of range, adjusted'); endtime = timerange(2); end; % complete thresholds values if necessary %---------------------------------------- if size(posthresh,2) < size(electrodes,2) posthresh = [ posthresh posthresh(end)*ones(1,size(electrodes,2)-size(posthresh,2))]; end; if size(negthresh,2) < size(electrodes,2) negthresh = [ negthresh negthresh(end)*ones(1,size(electrodes,2)-size(negthresh,2))]; end; % complete timeselect values if necessary %---------------------------------------- if size(starttime,2) < size(electrodes,2) starttime = [ starttime starttime(end)*ones(1,size(electrodes,2)-size(starttime,2))]; end; if size(endtime,2) < size(electrodes,2) endtime = [ endtime endtime(end)*ones(1,size(electrodes,2)-size(endtime,2))]; end; % find the maximum for each trial %-------------------------------- sweeps = size(signal(1,:),2)/pnts; signal = reshape(signal(electrodes,:), size(electrodes(:),1), pnts, sweeps); % reject the selected trials %--------------------------- elec = zeros(size(electrodes(:),1), sweeps); allelec = zeros(1, sweeps); for indexe = 1:size(electrodes(:),1) % transform the time range % ------------------------ framelowlimit = max(1,floor((starttime(indexe)-timerange(1))/(timerange(2)-timerange(1))*(pnts-1))+1); framehighlimit = floor((endtime(indexe) -timerange(1))/(timerange(2)-timerange(1))*(pnts-1))+1; % remove outliers % --------------- sigtmp = squeeze(signal(indexe,framelowlimit:framehighlimit,:)); sigmax = max(sigtmp, [], 1); sigmin = min(sigtmp, [], 1); elec(indexe,:) = ( sigmin < negthresh(indexe) ) | ( sigmax > posthresh(indexe) ); allelec = allelec | elec(indexe,:); end; Iout = find( allelec == 1 ); Iin = find( allelec == 0 ); elec = elec(:,Iout); % reject the selected trials %--------------------------- newsignal = reshape(signal, size(signal,1), pnts, sweeps); if ~isempty(Iin) newsignal = newsignal(:,:,Iin); if ndims(signal) == 2 newsignal = newsignal(:,:); end; else newsignal = []; end; return;
github
ZijingMao/baselineeegtest-master
qqdiagram.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/qqdiagram.m
4,745
utf_8
f9f838e5edd084613e8c54cb85cbb56f
% qqdiagram() - Empirical quantile-quantile diagram. % % Description: % The quantiles (percentiles) of the input distribution Y are plotted (Y-axis) % against the corresponding quantiles of the input distribution X. % If only X is given, the corresponding quantiles are plotted (Y-axis) % against the quantiles of a Gaussian distribution ('Normal plot'). % Two black dots indicate the lower and upper quartiles. % If the data in X and Y belong the same distribution the plot will be linear. % In this case,the red and black reference lines (.-.-.-.-) will overlap. % This will be true also if the data in X and Y belong to two distributions with % the same shape, one distribution being rescaled and shifted with respect to the % other. % If only X is given, a line is plotted to indicate the mean of X, and a segment % is plotted to indicate the standard deviation of X. If the data in X are normally % distributed, the red and black reference lines (.-.-.-.-) will overlap. % % Usage: % >> ah = qqdiagram( x, y, pk ); % % Inputs: % x - vector of observations % % Optional inputs: % y - second vector of observation to compare the first to % pk - the empirical quantiles will be estimated at the values in pk [0..1] % % Author: Luca Finelli, CNL / Salk Institute - SCCN, 20 August 2002 % % Reference: Stahel W., Statistische Datenanalyse, Vieweg, Braunschweig/Wiesbaden, 1995 % % See also: % quantile(), signalstat(), eeglab() % Copyright (C) 2002 Luca Finelli, Salk/SCCN, La Jolla, CA % % Reference: Stahel, W. Statistische Datenanalyse, Vieweg, Braunschweig/Wiesbaden 1995 % % 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 qqdiagram( x , y, pk ) if nargin < 1 help qqdiagram; return; end; if (nargin == 3 & (any(pk > 1) | any(pk < 0))) error('qqdiagram(): elements in pk must be between 0 and 1'); end if nargin==1 y=x; nn=max(1000,10*length(y))+1; x=randn(1,nn); end if nargin < 3 nx=sum(~isnan(x)); ny=sum(~isnan(y)); k=min(nx,ny); pk=((1:k) - 0.5) ./ k; % values to estimate the empirical quantiles at else k=length(pk); end if nx==k xx=sort(x(~isnan(x))); else xx=quantile(x(~isnan(x)),pk); end if ny==k yy=sort(y(~isnan(y))); else yy=quantile(y(~isnan(y)),pk); end % QQ diagram plot(xx,yy,'+') hold on % x-axis range maxx=max(xx); minx=min(xx); rangex=maxx-minx; xmin=minx-rangex/50; xmax=maxx+rangex/50; % Quartiles xqrt1=quantile(x,0.25); xqrt3=quantile(x,0.75); yqrt1=quantile(y,0.25); yqrt3=quantile(y,0.75); plot([xqrt1 xqrt3],[yqrt1 yqrt3],'k-','LineWidth',2); % IQR range % Drawing the line sigma=(yqrt3-yqrt1)/(xqrt3-xqrt1); cy=(yqrt1 + yqrt3)/2; if nargin ==1 maxy=max(y); miny=min(y); rangey=maxy-miny; ymin=miny-rangey/50; ymax=maxy+rangey/50; plot([(miny-cy)/sigma (maxy-cy)/sigma],[miny maxy],'r-.') % the line % For normally distributed data, the slope of the plot line % is equal to the ratio of the standard deviation of the distributions plot([0 (maxy-mean(y))/std(y)],[mean(y) maxy],'k-.') % the ideal line xlim=get(gca,'XLim'); plot([1 1],[ymin mean(y)+std(y)],'k--') plot([1 1],[mean(y) mean(y)+std(y)],'k-','LineWidth',2) % textx = 1.0; % texty = mean(y)+3.0*rangey/50.0; % text(double(textx), double(texty),' St. Dev.','horizontalalignment','center') set(gca,'xtick',get(gca,'xtick')); % show that vertical line is at 1 sd plot([0 0],[ymin mean(y)],'k--') plot(xlim,[mean(y) mean(y)],'k--') % text(double(xlim(1)), double(mean(y)+rangey/50),'Mean X') plot([xqrt1 xqrt3],[yqrt1 yqrt3],'k.','MarkerSize',10) set(gca,'XLim',[xmin xmax],'YLim',[ymin ymax]) xlabel('Standard Normal Quantiles') ylabel('X Quantiles') else cx=(xqrt1 + xqrt3)/2; maxy=cy+sigma*(max(x)-cx); miny=cy-sigma*(cx-min(x)); plot([min(x) max(x)],[miny maxy],'r-.'); % the line xlabel('X Quantiles'); ylabel('Y Quantiles'); end
github
ZijingMao/baselineeegtest-master
loaddat.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/loaddat.m
1,775
utf_8
7d7aa4df464e400f37de47be51520ea6
% loaddat() - loading neuroscan format data file into matlab. % % Usage: % >> [typeeeg, rt, response, n] = loaddat( filename ); % % Inputs: % filename - input Neuroscan .dat file % % Outputs: % typeeeg - type of the sweeps % rt - reaction time of the subject % response - response of the subject % n - number of sweeps % % See also: loadeeg() % Copyright (C) 2001 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 [tmptypeeeg, tmprt, tmpresponseeeg, n] = loaddat( FILENAME) if nargin<1 fprintf('Not enought arguments\n'); help loaddat return; end; BOOL='int16'; ULONG='int32'; FLOAT='float32'; fid=fopen(FILENAME,'r','ieee-le'); if fid<0 fprintf(2,['Error LOADEEG: File ' FILENAME ' not found\n']); return; end; % skip the first 20 lines % ----------------------- for index=1:20 fgetl(fid); end; % read the matrix % --------------- tmpMat = fscanf(fid, '%f', [5, inf]); tmptypeeeg = tmpMat(3,:); tmpresponseeeg = tmpMat(4,:); tmprt = tmpMat(5,:); n = size( tmpMat, 2); fclose(fid); return;
github
ZijingMao/baselineeegtest-master
cbar.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/cbar.m
6,086
utf_8
e3d146edc925c770080882bdfcedc39b
% cbar() - Display full or partial color bar % % Usage: % >> cbar % create a vertical cbar on the right side of a figure % >> cbar(type) % specify direction as 'vert' or 'horiz' % >> cbar(type,colors) % specify which colormap colors to plot % else % >> cbar(axhandle) % specify the axes to draw cbar in % % >> h = cbar(type|axhandle,colors, minmax, grad) % % Inputs: % type - ['vert'|'horiz'] direction of the cbar {default: 'vert') % ELSE axhandle = handle of axes to draw the cbar % colors - vector of colormap indices to display, or integer to truncate upper % limit by. % (int n -> display colors [1:end-n]) {default: 0} % minmax - [min, max] range of values to label on colorbar % grad - [integer] number of tick labels. {default: 5}. % % Example: % >> colormap('default') % default colormap is 64-color 'jet' % >> cbar('vert',33:64); % plot a vertical cbar colored green->red % % useful for showing >0 (warm) and 0 (green) % % values only in a green=0 plot % % Author: Colin Humphries, Arnaud Delorme, CNL / Salk Institute, Feb. 1998- % % See also: colorbar() % Copyright (C) Colin Humphries, CNL / Salk Institute, Feb. 1998 % % 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 % 12-13-98 added minmax arg -Scott Makeig % 01-25-02 reformated help & license, added links -ad function [handle]=cbar(arg,colors,minmax, grad) if nargin < 2 colors = 0; end posscale = 'off'; if nargin < 1 arg = 'vert'; ax = []; else if isempty(arg) arg = 0; end if arg(1) == 0 ax = []; arg = 'vert'; elseif strcmpi(arg, 'pos') ax = []; arg = 'vert'; posscale = 'on'; else if ischar(arg) ax = []; else ax = arg; arg = []; end end end if nargin>2 if size(minmax,1) ~= 1 | size(minmax,2) ~= 2 help cbar fprintf('cbar() : minmax arg must be [min,max]\n'); return end end if nargin < 4 grad = 5; end; %obj = findobj('tag','cbar','parent',gcf); %if ~isempty(obj) & ~isempty(arg) % arg = []; % ax = obj; %end try icadefs; catch warning('cbar.m unable to find icadefs.m'); end %%%%%%%%%%%%%%%%%%%%%%%%%%% % Choose colorbar position %%%%%%%%%%%%%%%%%%%%%%%%%%% if (length(colors) == 1) & (colors == 0) t = caxis; else t = [0 1]; end if ~isempty(arg) if strcmp(arg,'vert') cax = gca; pos = get(cax,'Position'); stripe = 0.04; edge = 0.01; space = .02; % set(cax,'Position',[pos(1) pos(2) pos(3)*(1-stripe-edge-space) pos(4)]) % rect = [pos(1)+(1-stripe-edge)*pos(3) pos(2) stripe*pos(3) pos(4)]; set(cax,'Position',[pos(1) pos(2) pos(3) pos(4)]) rect = [pos(1)+pos(3)+space pos(2) stripe*pos(3) pos(4)]; ax = axes('Position', rect); elseif strcmp(arg,'horiz') cax = gca; pos = get(cax,'Position'); stripe = 0.075; space = .1; set(cax,'Position',... [pos(1) pos(2)+(stripe+space)*pos(4) pos(3) (1-stripe-space)*pos(4)]) rect = [pos(1) pos(2) pos(3) stripe*pos(4)]; ax = axes('Position', rect); end else pos = get(ax,'Position'); if pos(3) > pos(4) arg = 'horiz'; else arg = 'vert'; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Draw colorbar using image() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if exist('DEFAULT_COLORMAP', 'var') map = colormap(DEFAULT_COLORMAP); else map = colormap; end n = size(map,1); if length(colors) == 1 if strcmp(arg,'vert') if strcmpi(posscale, 'on') image([0 1],[0 t(2)],[ceil(n/2):n-colors]'); else image([0 1],t,[1:n-colors]'); end; set(ax,'xticklabelmode','manual') set(ax,'xticklabel',[],'YAxisLocation','right') else image(t,[0 1],[1:n-colors]); set(ax,'yticklabelmode','manual') set(ax,'yticklabel',[],'YAxisLocation','right') end set(ax,'Ydir','normal','YAxisLocation','right') else % length > 1 if max(colors) > n error('Color vector excedes size of colormap') end if strcmp(arg,'vert') image([0 1],t,[colors]'); set(ax,'xticklabelmode','manual') set(ax,'xticklabel',[]) else image([0 1],t,[colors]); set(ax,'yticklabelmode','manual') set(ax,'yticklabel',[],'YAxisLocation','right') end set(ax,'Ydir','normal','YAxisLocation','right') end %%%%%%%%%%%%%%%%%%%%%%%%% % Adjust cbar ticklabels %%%%%%%%%%%%%%%%%%%%%%%%% if nargin > 2 if strcmp(arg,'vert') Cax = get(ax,'Ylim'); else Cax = get(ax,'Xlim'); end; CBTicks = [Cax(1):(Cax(2)-Cax(1))/(grad-1):Cax(2)]; % caxis tick positions CBLabels = [minmax(1):(minmax(2)-minmax(1))/(grad-1):minmax(2)]; % tick labels dec = floor(log10(max(abs(minmax)))); % decade of largest abs value CBLabels = ([minmax]* [ linspace(1,0, grad);linspace(0, 1, grad)]); %[1.0 .75 .50 .25 0.0; 0.0 .25 .50 .75 1.0]); if dec<1 CBLabels = round(CBLabels*10^(1-dec))*10^(dec-1); elseif dec == 1 CBLabels = round(CBLabels*10^(2-dec))*10^(dec-2); else CBLabels = round(CBLabels); end % minmax % CBTicks % CBLabels if strcmp(arg,'vert') set(ax,'Ytick',CBTicks); set(ax,'Yticklabel',CBLabels); else set(ax,'Xtick',CBTicks); set(ax,'Xticklabel',CBLabels); end end handle = ax; %%%%%%%%%%%%%%%%%% % Adjust cbar tag %%%%%%%%%%%%%%%%%% set(ax,'tag','cbar'); if exist('DEFAULT_COLORMAP', 'var') colormap(DEFAULT_COLORMAP); end
github
ZijingMao/baselineeegtest-master
readlocs.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/readlocs.m
33,881
utf_8
7e1d85669932dffeca11a8fad52e02ca
% readlocs() - read electrode location coordinates and other information from a file. % Several standard file formats are supported. Users may also specify % a custom column format. Defined format examples are given below % (see File Formats). % Usage: % >> eloc = readlocs( filename ); % >> EEG.chanlocs = readlocs( filename, 'key', 'val', ... ); % >> [eloc, labels, theta, radius, indices] = ... % readlocs( filename, 'key', 'val', ... ); % Inputs: % filename - Name of the file containing the electrode locations % {default: 2-D polar coordinates} (see >> help topoplot ) % % Optional inputs: % 'filetype' - ['loc'|'sph'|'sfp'|'xyz'|'asc'|'polhemus'|'besa'|'chanedit'|'custom'] % Type of the file to read. By default the file type is determined % using the file extension (see below under File Formats), % 'loc' an EEGLAB 2-D polar coordinates channel locations file % Coordinates are theta and radius (see definitions below). % 'sph' Matlab spherical coordinates (Note: spherical % coordinates used by Matlab functions are different % from spherical coordinates used by BESA - see below). % 'sfp' EGI Cartesian coordinates (NOT Matlab Cartesian - see below). % 'xyz' Matlab/EEGLAB Cartesian coordinates (NOT EGI Cartesian). % z is toward nose; y is toward left ear; z is toward vertex % 'asc' Neuroscan polar coordinates. % 'polhemus' or 'polhemusx' - Polhemus electrode location file recorded % with 'X' on sensor pointing to subject (see below and readelp()). % 'polhemusy' - Polhemus electrode location file recorded with % 'Y' on sensor pointing to subject (see below and readelp()). % 'besa' BESA-'.elp' spherical coordinates. (Not MATLAB spherical - % see below). % 'chanedit' - EEGLAB channel location file created by pop_chanedit(). % 'custom' - Ascii file with columns in user-defined 'format' (see below). % 'importmode' - ['eeglab'|'native'] for location files containing 3-D cartesian electrode % coordinates, import either in EEGLAB format (nose pointing toward +X). % This may not always be possible since EEGLAB might not be able to % determine the nose direction for scanned electrode files. 'native' import % original carthesian coordinates (user can then specify the position of % the nose when calling the topoplot() function; in EEGLAB the position % of the nose is stored in the EEG.chaninfo structure). {default 'eeglab'} % 'format' - [cell array] Format of a 'custom' channel location file (see above). % {default: if no file type is defined. The cell array contains % labels defining the meaning of each column of the input file. % 'channum' [positive integer] channel number. % 'labels' [string] channel name (no spaces). % 'theta' [real degrees] 2-D angle in polar coordinates. % positive => rotating from nose (0) toward left ear % 'radius' [real] radius for 2-D polar coords; 0.5 is the head % disk radius and limit for topoplot() plotting). % 'X' [real] Matlab-Cartesian X coordinate (to nose). % 'Y' [real] Matlab-Cartesian Y coordinate (to left ear). % 'Z' [real] Matlab-Cartesian Z coordinate (to vertex). % '-X','-Y','-Z' Matlab-Cartesian coordinates pointing opposite % to the above. % 'sph_theta' [real degrees] Matlab spherical horizontal angle. % positive => rotating from nose (0) toward left ear. % 'sph_phi' [real degrees] Matlab spherical elevation angle. % positive => rotating from horizontal (0) upwards. % 'sph_radius' [real] distance from head center (unused). % 'sph_phi_besa' [real degrees] BESA phi angle from vertical. % positive => rotating from vertex (0) towards right ear. % 'sph_theta_besa' [real degrees] BESA theta horiz/azimuthal angle. % positive => rotating from right ear (0) toward nose. % 'ignore' ignore column}. % The input file may also contain other channel information fields. % 'type' channel type: 'EEG', 'MEG', 'EMG', 'ECG', others ... % 'calib' [real near 1.0] channel calibration value. % 'gain' [real > 1] channel gain. % 'custom1' custom field #1. % 'custom2', 'custom3', 'custom4', etc. more custom fields % 'skiplines' - [integer] Number of header lines to skip (in 'custom' file types only). % Note: Characters on a line following '%' will be treated as comments. % 'readchans' - [integer array] indices of electrodes to read. {default: all} % 'center' - [(1,3) real array or 'auto'] center of xyz coordinates for conversion % to spherical or polar, Specify the center of the sphere here, or 'auto'. % This uses the center of the sphere that best fits all the electrode % locations read. {default: [0 0 0]} % Outputs: % eloc - structure containing the channel names and locations (if present). % It has three fields: 'eloc.labels', 'eloc.theta' and 'eloc.radius' % identical in meaning to the EEGLAB struct 'EEG.chanlocs'. % labels - cell array of strings giving the names of the electrodes. NOTE: Unlike the % three outputs below, includes labels of channels *without* location info. % theta - vector (in degrees) of polar angles of the electrode locations. % radius - vector of polar-coordinate radii (arc_lengths) of the electrode locations % indices - indices, k, of channels with non-empty 'locs(k).theta' coordinate % % File formats: % If 'filetype' is unspecified, the file extension determines its type. % % '.loc' or '.locs' or '.eloc': % polar coordinates. Notes: angles in degrees: % right ear is 90; left ear -90; head disk radius is 0.5. % Fields: N angle radius label % Sample: 1 -18 .511 Fp1 % 2 18 .511 Fp2 % 3 -90 .256 C3 % 4 90 .256 C4 % ... % Note: In previous releases, channel labels had to contain exactly % four characters (spaces replaced by '.'). This format still works, % though dots are no longer required. % '.sph': % Matlab spherical coordinates. Notes: theta is the azimuthal/horizontal angle % in deg.: 0 is toward nose, 90 rotated to left ear. Following this, performs % the elevation (phi). Angles in degrees. % Fields: N theta phi label % Sample: 1 18 -2 Fp1 % 2 -18 -2 Fp2 % 3 90 44 C3 % 4 -90 44 C4 % ... % '.elc': % Cartesian 3-D electrode coordinates scanned using the EETrak software. % See readeetraklocs(). % '.elp': % Polhemus-.'elp' Cartesian coordinates. By default, an .elp extension is read % as PolhemusX-elp in which 'X' on the Polhemus sensor is pointed toward the % subject. Polhemus files are not in columnar format (see readelp()). % '.elp': % BESA-'.elp' spherical coordinates: Need to specify 'filetype','besa'. % The elevation angle (phi) is measured from the vertical axis. Positive % rotation is toward right ear. Next, perform azimuthal/horizontal rotation % (theta): 0 is toward right ear; 90 is toward nose, -90 toward occiput. % Angles are in degrees. If labels are absent or weights are given in % a last column, readlocs() adjusts for this. Default labels are E1, E2, ... % Fields: Type label phi theta % Sample: EEG Fp1 -92 -72 % EEG Fp2 92 72 % EEG C3 -46 0 % EEG C4 46 0 % ... % '.xyz': % Matlab/EEGLAB Cartesian coordinates. Here. x is towards the nose, % y is towards the left ear, and z towards the vertex. Note that the first % column (x) is -Y in a Matlab 3-D plot, the second column (y) is X in a % matlab 3-D plot, and the third column (z) is Z. % Fields: channum x y z label % Sample: 1 .950 .308 -.035 Fp1 % 2 .950 -.308 -.035 Fp2 % 3 0 .719 .695 C3 % 4 0 -.719 .695 C4 % ... % '.asc', '.dat': % Neuroscan-.'asc' or '.dat' Cartesian polar coordinates text file. % '.sfp': % BESA/EGI-xyz Cartesian coordinates. Notes: For EGI, x is toward right ear, % y is toward the nose, z is toward the vertex. EEGLAB converts EGI % Cartesian coordinates to Matlab/EEGLAB xyz coordinates. % Fields: label x y z % Sample: Fp1 -.308 .950 -.035 % Fp2 .308 .950 -.035 % C3 -.719 0 .695 % C4 .719 0 .695 % ... % '.ced': % ASCII file saved by pop_chanedit(). Contains multiple MATLAB/EEGLAB formats. % Cartesian coordinates are as in the 'xyz' format (above). % Fields: channum label theta radius x y z sph_theta sph_phi ... % Sample: 1 Fp1 -18 .511 .950 .308 -.035 18 -2 ... % 2 Fp2 18 .511 .950 -.308 -.035 -18 -2 ... % 3 C3 -90 .256 0 .719 .695 90 44 ... % 4 C4 90 .256 0 -.719 .695 -90 44 ... % ... % The last columns of the file may contain any other defined fields (gain, % calib, type, custom). % % Fieldtrip structure: % If a Fieltrip structure is given as input, an EEGLAB % chanlocs structure is returned % % Author: Arnaud Delorme, Salk Institute, 8 Dec 2002 % % See also: readelp(), writelocs(), topo2sph(), sph2topo(), sph2cart() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 28 Feb 2002 % % 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 [eloc, labels, theta, radius, indices] = readlocs( filename, varargin ); if nargin < 1 help readlocs; return; end; % NOTE: To add a new channel format: % ---------------------------------- % 1) Add a new element to the structure 'chanformat' (see 'ADD NEW FORMATS HERE' below): % 2) Enter a format 'type' for the new file format, % 3) Enter a (short) 'typestring' description of the format % 4) Enter a longer format 'description' (possibly multiline, see ex. (1) below) % 5) Enter format file column labels in the 'importformat' field (see ex. (2) below) % 6) Enter the number of header lines to skip (if any) in the 'skipline' field % 7) Document the new channel format in the help message above. % 8) After testing, please send the new version of readloca.m to us % at [email protected] with a sample locs file. % The 'chanformat' structure is also used (automatically) by the writelocs() % and pop_readlocs() functions. You do not need to edit these functions. chanformat(1).type = 'polhemus'; chanformat(1).typestring = 'Polhemus native .elp file'; chanformat(1).description = [ 'Polhemus native coordinate file containing scanned electrode positions. ' ... 'User must select the direction ' ... 'for the nose after importing the data file.' ]; chanformat(1).importformat = 'readelp() function'; % --------------------------------------------------------------------------------------------------- chanformat(2).type = 'besa'; chanformat(2).typestring = 'BESA spherical .elp file'; chanformat(2).description = [ 'BESA spherical coordinate file. Note that BESA spherical coordinates ' ... 'are different from Matlab spherical coordinates' ]; chanformat(2).skipline = 0; % some BESA files do not have headers chanformat(2).importformat = { 'type' 'labels' 'sph_theta_besa' 'sph_phi_besa' 'sph_radius' }; % --------------------------------------------------------------------------------------------------- chanformat(3).type = 'xyz'; chanformat(3).typestring = 'Matlab .xyz file'; chanformat(3).description = [ 'Standard 3-D cartesian coordinate files with electrode labels in ' ... 'the first column and X, Y, and Z coordinates in columns 2, 3, and 4' ]; chanformat(3).importformat = { 'channum' '-Y' 'X' 'Z' 'labels'}; % --------------------------------------------------------------------------------------------------- chanformat(4).type = 'sfp'; chanformat(4).typestring = 'BESA or EGI 3-D cartesian .sfp file'; chanformat(4).description = [ 'Standard BESA 3-D cartesian coordinate files with electrode labels in ' ... 'the first column and X, Y, and Z coordinates in columns 2, 3, and 4.' ... 'Coordinates are re-oriented to fit the EEGLAB standard of having the ' ... 'nose along the +X axis.' ]; chanformat(4).importformat = { 'labels' '-Y' 'X' 'Z' }; chanformat(4).skipline = 0; % --------------------------------------------------------------------------------------------------- chanformat(5).type = 'loc'; chanformat(5).typestring = 'EEGLAB polar .loc file'; chanformat(5).description = [ 'EEGLAB polar .loc file' ]; chanformat(5).importformat = { 'channum' 'theta' 'radius' 'labels' }; % --------------------------------------------------------------------------------------------------- chanformat(6).type = 'sph'; chanformat(6).typestring = 'Matlab .sph spherical file'; chanformat(6).description = [ 'Standard 3-D spherical coordinate files in Matlab format' ]; chanformat(6).importformat = { 'channum' 'sph_theta' 'sph_phi' 'labels' }; % --------------------------------------------------------------------------------------------------- chanformat(7).type = 'asc'; chanformat(7).typestring = 'Neuroscan polar .asc file'; chanformat(7).description = [ 'Neuroscan polar .asc file, automatically recentered to fit EEGLAB standard' ... 'of having ''Cz'' at (0,0).' ]; chanformat(7).importformat = 'readneurolocs'; % --------------------------------------------------------------------------------------------------- chanformat(8).type = 'dat'; chanformat(8).typestring = 'Neuroscan 3-D .dat file'; chanformat(8).description = [ 'Neuroscan 3-D cartesian .dat file. Coordinates are re-oriented to fit ' ... 'the EEGLAB standard of having the nose along the +X axis.' ]; chanformat(8).importformat = 'readneurolocs'; % --------------------------------------------------------------------------------------------------- chanformat(9).type = 'elc'; chanformat(9).typestring = 'ASA .elc 3-D file'; chanformat(9).description = [ 'ASA .elc 3-D coordinate file containing scanned electrode positions. ' ... 'User must select the direction ' ... 'for the nose after importing the data file.' ]; chanformat(9).importformat = 'readeetraklocs'; % --------------------------------------------------------------------------------------------------- chanformat(10).type = 'chanedit'; chanformat(10).typestring = 'EEGLAB complete 3-D file'; chanformat(10).description = [ 'EEGLAB file containing polar, cartesian 3-D, and spherical 3-D ' ... 'electrode locations.' ]; chanformat(10).importformat = { 'channum' 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' ... 'sph_radius' 'type' }; chanformat(10).skipline = 1; % --------------------------------------------------------------------------------------------------- chanformat(11).type = 'custom'; chanformat(11).typestring = 'Custom file format'; chanformat(11).description = 'Custom ASCII file format where user can define content for each file columns.'; chanformat(11).importformat = ''; % --------------------------------------------------------------------------------------------------- % ----- ADD MORE FORMATS HERE ----------------------------------------------------------------------- % --------------------------------------------------------------------------------------------------- listcolformat = { 'labels' 'channum' 'theta' 'radius' 'sph_theta' 'sph_phi' ... 'sph_radius' 'sph_theta_besa' 'sph_phi_besa' 'gain' 'calib' 'type' ... 'X' 'Y' 'Z' '-X' '-Y' '-Z' 'custom1' 'custom2' 'custom3' 'custom4' 'ignore' 'not def' }; % ---------------------------------- % special mode for getting the info % ---------------------------------- if isstr(filename) & strcmp(filename, 'getinfos') eloc = chanformat; labels = listcolformat; return; end; g = finputcheck( varargin, ... { 'filetype' 'string' {} ''; 'importmode' 'string' { 'eeglab','native' } 'eeglab'; 'defaultelp' 'string' { 'besa','polhemus' } 'polhemus'; 'skiplines' 'integer' [0 Inf] []; 'elecind' 'integer' [1 Inf] []; 'format' 'cell' [] {} }, 'readlocs'); if isstr(g), error(g); end; if ~isempty(g.format), g.filetype = 'custom'; end; if isstr(filename) % format auto detection % -------------------- if strcmpi(g.filetype, 'autodetect'), g.filetype = ''; end; g.filetype = strtok(g.filetype); periods = find(filename == '.'); fileextension = filename(periods(end)+1:end); g.filetype = lower(g.filetype); if isempty(g.filetype) switch lower(fileextension), case {'loc' 'locs' 'eloc'}, g.filetype = 'loc'; % 5/27/2014 Ramon: 'eloc' option introduced. case 'xyz', g.filetype = 'xyz'; fprintf( [ 'WARNING: Matlab Cartesian coord. file extension (".xyz") detected.\n' ... 'If importing EGI Cartesian coords, force type "sfp" instead.\n'] ); case 'sph', g.filetype = 'sph'; case 'ced', g.filetype = 'chanedit'; case 'elp', g.filetype = g.defaultelp; case 'asc', g.filetype = 'asc'; case 'dat', g.filetype = 'dat'; case 'elc', g.filetype = 'elc'; case 'eps', g.filetype = 'besa'; case 'sfp', g.filetype = 'sfp'; otherwise, g.filetype = ''; end; fprintf('readlocs(): ''%s'' format assumed from file extension\n', g.filetype); else if strcmpi(g.filetype, 'locs'), g.filetype = 'loc'; end if strcmpi(g.filetype, 'eloc'), g.filetype = 'loc'; end end; % assign format from filetype % --------------------------- if ~isempty(g.filetype) & ~strcmpi(g.filetype, 'custom') ... & ~strcmpi(g.filetype, 'asc') & ~strcmpi(g.filetype, 'elc') & ~strcmpi(g.filetype, 'dat') indexformat = strmatch(lower(g.filetype), { chanformat.type }, 'exact'); g.format = chanformat(indexformat).importformat; if isempty(g.skiplines) g.skiplines = chanformat(indexformat).skipline; end; if isempty(g.filetype) error( ['readlocs() error: The filetype cannot be detected from the \n' ... ' file extension, and custom format not specified']); end; end; % import file % ----------- if strcmp(g.filetype, 'asc') | strcmp(g.filetype, 'dat') eloc = readneurolocs( filename ); eloc = rmfield(eloc, 'sph_theta'); % for the conversion below eloc = rmfield(eloc, 'sph_theta_besa'); % for the conversion below if isfield(eloc, 'type') for index = 1:length(eloc) type = eloc(index).type; if type == 69, eloc(index).type = 'EEG'; elseif type == 88, eloc(index).type = 'REF'; elseif type >= 76 & type <= 82, eloc(index).type = 'FID'; else eloc(index).type = num2str(eloc(index).type); end; end; end; elseif strcmp(g.filetype, 'elc') eloc = readeetraklocs( filename ); %eloc = read_asa_elc( filename ); % from fieldtrip %eloc = struct('labels', eloc.label, 'X', mattocell(eloc.pnt(:,1)'), 'Y', ... % mattocell(eloc.pnt(:,2)'), 'Z', mattocell(eloc.pnt(:,3)')); eloc = convertlocs(eloc, 'cart2all'); eloc = rmfield(eloc, 'sph_theta'); % for the conversion below eloc = rmfield(eloc, 'sph_theta_besa'); % for the conversion below elseif strcmp(lower(g.filetype(1:end-1)), 'polhemus') | ... strcmp(g.filetype, 'polhemus') try, [eloc labels X Y Z]= readelp( filename ); if strcmp(g.filetype, 'polhemusy') tmp = X; X = Y; Y = tmp; end; for index = 1:length( eloc ) eloc(index).X = X(index); eloc(index).Y = Y(index); eloc(index).Z = Z(index); end; catch, disp('readlocs(): Could not read Polhemus coords. Trying to read BESA .elp file.'); [eloc, labels, theta, radius, indices] = readlocs( filename, 'defaultelp', 'besa', varargin{:} ); end; else % importing file % -------------- if isempty(g.skiplines), g.skiplines = 0; end; if strcmpi(g.filetype, 'chanedit') array = loadtxt( filename, 'delim', 9, 'skipline', g.skiplines, 'blankcell', 'off'); else array = load_file_or_array( filename, g.skiplines); end; if size(array,2) < length(g.format) fprintf(['readlocs() warning: Fewer columns in the input than expected.\n' ... ' See >> help readlocs\n']); elseif size(array,2) > length(g.format) fprintf(['readlocs() warning: More columns in the input than expected.\n' ... ' See >> help readlocs\n']); end; % removing lines BESA % ------------------- if isempty(array{1,2}) disp('BESA header detected, skipping three lines...'); array = load_file_or_array( filename, g.skiplines-1); if isempty(array{1,2}) array = load_file_or_array( filename, g.skiplines-1); end; end; % xyz format, is the first col absent % ----------------------------------- if strcmp(g.filetype, 'xyz') if size(array, 2) == 4 array(:, 2:5) = array(:, 1:4); end; end; % removing comments and empty lines % --------------------------------- indexbeg = 1; while isempty(array{indexbeg,1}) | ... (isstr(array{indexbeg,1}) & array{indexbeg,1}(1) == '%' ) indexbeg = indexbeg+1; end; array = array(indexbeg:end,:); % converting file % --------------- for indexcol = 1:min(size(array,2), length(g.format)) [str mult] = checkformat(g.format{indexcol}); for indexrow = 1:size( array, 1) if mult ~= 1 eval ( [ 'eloc(indexrow).' str '= -array{indexrow, indexcol};' ]); else eval ( [ 'eloc(indexrow).' str '= array{indexrow, indexcol};' ]); end; end; end; end; % handling BESA coordinates % ------------------------- if isfield(eloc, 'sph_theta_besa') if isfield(eloc, 'type') if isnumeric(eloc(1).type) disp('BESA format detected ( Theta | Phi )'); for index = 1:length(eloc) eloc(index).sph_phi_besa = eloc(index).labels; eloc(index).sph_theta_besa = eloc(index).type; eloc(index).labels = ''; eloc(index).type = ''; end; eloc = rmfield(eloc, 'labels'); end; end; if isfield(eloc, 'labels') if isnumeric(eloc(1).labels) disp('BESA format detected ( Elec | Theta | Phi )'); for index = 1:length(eloc) eloc(index).sph_phi_besa = eloc(index).sph_theta_besa; eloc(index).sph_theta_besa = eloc(index).labels; eloc(index).labels = eloc(index).type; eloc(index).type = ''; eloc(index).radius = 1; end; end; end; try eloc = convertlocs(eloc, 'sphbesa2all'); eloc = convertlocs(eloc, 'topo2all'); % problem with some EGI files (not BESA files) catch, disp('Warning: coordinate conversion failed'); end; fprintf('Readlocs: BESA spherical coords. converted, now deleting BESA fields\n'); fprintf(' to avoid confusion (these fields can be exported, though)\n'); eloc = rmfield(eloc, 'sph_phi_besa'); eloc = rmfield(eloc, 'sph_theta_besa'); % converting XYZ coordinates to polar % ----------------------------------- elseif isfield(eloc, 'sph_theta') try eloc = convertlocs(eloc, 'sph2all'); catch, disp('Warning: coordinate conversion failed'); end; elseif isfield(eloc, 'X') try eloc = convertlocs(eloc, 'cart2all'); catch, disp('Warning: coordinate conversion failed'); end; else try eloc = convertlocs(eloc, 'topo2all'); catch, disp('Warning: coordinate conversion failed'); end; end; % inserting labels if no labels % ----------------------------- if ~isfield(eloc, 'labels') fprintf('readlocs(): Inserting electrode labels automatically.\n'); for index = 1:length(eloc) eloc(index).labels = [ 'E' int2str(index) ]; end; else % remove trailing '.' for index = 1:length(eloc) if isstr(eloc(index).labels) tmpdots = find( eloc(index).labels == '.' ); eloc(index).labels(tmpdots) = []; end; end; end; % resorting electrodes if number not-sorted % ----------------------------------------- if isfield(eloc, 'channum') if ~isnumeric(eloc(1).channum) error('Channel numbers must be numeric'); end; allchannum = [ eloc.channum ]; if any( sort(allchannum) ~= allchannum ) fprintf('readlocs(): Re-sorting channel numbers based on ''channum'' column indices\n'); [tmp newindices] = sort(allchannum); eloc = eloc(newindices); end; eloc = rmfield(eloc, 'channum'); end; else if isstruct(filename) % detect Fieldtrip structure and convert it % ----------------------------------------- if isfield(filename, 'pnt') neweloc = []; for index = 1:length(filename.label) neweloc(index).labels = filename.label{index}; neweloc(index).X = filename.pnt(index,1); neweloc(index).Y = filename.pnt(index,2); neweloc(index).Z = filename.pnt(index,3); end; eloc = neweloc; eloc = convertlocs(eloc, 'cart2all'); else eloc = filename; end; else disp('readlocs(): input variable must be a string or a structure'); end; end; if ~isempty(g.elecind) eloc = eloc(g.elecind); end; if nargout > 2 if isfield(eloc, 'theta') tmptheta = { eloc.theta }; % check which channels have (polar) coordinates set else tmptheta = cell(1,length(eloc)); end; if isfield(eloc, 'theta') tmpx = { eloc.X }; % check which channels have (polar) coordinates set else tmpx = cell(1,length(eloc)); end; indices = find(~cellfun('isempty', tmptheta)); indices = intersect_bc(find(~cellfun('isempty', tmpx)), indices); indices = sort(indices); indbad = setdiff_bc(1:length(eloc), indices); tmptheta(indbad) = { NaN }; theta = [ tmptheta{:} ]; end; if nargout > 3 if isfield(eloc, 'theta') tmprad = { eloc.radius }; % check which channels have (polar) coordinates set else tmprad = cell(1,length(eloc)); end; tmprad(indbad) = { NaN }; radius = [ tmprad{:} ]; end; %tmpnum = find(~cellfun('isclass', { eloc.labels }, 'char')); %disp('Converting channel labels to string'); for index = 1:length(eloc) if ~isstr(eloc(index).labels) eloc(index).labels = int2str(eloc(index).labels); end; end; labels = { eloc.labels }; if isfield(eloc, 'ignore') eloc = rmfield(eloc, 'ignore'); end; % process fiducials if any % ------------------------ fidnames = { 'nz' 'lpa' 'rpa' 'nasion' 'left' 'right' 'nazion' 'fidnz' 'fidt9' 'fidt10' 'cms' 'drl' }; for index = 1:length(fidnames) ind = strmatch(fidnames{index}, lower(labels), 'exact'); if ~isempty(ind), eloc(ind).type = 'FID'; end; end; return; % interpret the variable name % --------------------------- function array = load_file_or_array( varname, skiplines ); if isempty(skiplines), skiplines = 0; end; if exist( varname ) == 2 array = loadtxt(varname,'verbose','off','skipline',skiplines,'blankcell','off'); else % variable in the global workspace % -------------------------- try, array = evalin('base', varname); catch, error('readlocs(): cannot find the named file or variable, check syntax'); end; end; return; % check field format % ------------------ function [str, mult] = checkformat(str) mult = 1; if strcmpi(str, 'labels'), str = lower(str); return; end; if strcmpi(str, 'channum'), str = lower(str); return; end; if strcmpi(str, 'theta'), str = lower(str); return; end; if strcmpi(str, 'radius'), str = lower(str); return; end; if strcmpi(str, 'ignore'), str = lower(str); return; end; if strcmpi(str, 'sph_theta'), str = lower(str); return; end; if strcmpi(str, 'sph_phi'), str = lower(str); return; end; if strcmpi(str, 'sph_radius'), str = lower(str); return; end; if strcmpi(str, 'sph_theta_besa'), str = lower(str); return; end; if strcmpi(str, 'sph_phi_besa'), str = lower(str); return; end; if strcmpi(str, 'gain'), str = lower(str); return; end; if strcmpi(str, 'calib'), str = lower(str); return; end; if strcmpi(str, 'type') , str = lower(str); return; end; if strcmpi(str, 'X'), str = upper(str); return; end; if strcmpi(str, 'Y'), str = upper(str); return; end; if strcmpi(str, 'Z'), str = upper(str); return; end; if strcmpi(str, '-X'), str = upper(str(2:end)); mult = -1; return; end; if strcmpi(str, '-Y'), str = upper(str(2:end)); mult = -1; return; end; if strcmpi(str, '-Z'), str = upper(str(2:end)); mult = -1; return; end; if strcmpi(str, 'custom1'), return; end; if strcmpi(str, 'custom2'), return; end; if strcmpi(str, 'custom3'), return; end; if strcmpi(str, 'custom4'), return; end; error(['readlocs(): undefined field ''' str '''']);
github
ZijingMao/baselineeegtest-master
erpimage.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/sigprocfunc/erpimage.m
157,376
utf_8
deef1ab9cf000fdabbc8e026c72c4366
% erpimage() - Plot a colored image of a collection of single-trial data epochs, optionally % sorted on and/or aligned to an input sorting variable and smoothed across % trials with a Gaussian weighted moving-average. (To return event-aligned data % without plotting, use eegalign()). Optionally sort trials on value, amplitude % or phase within a specified latency window. Optionally plot the ERP mean % and std. dev.and moving-window spectral amplitude and inter-trial coherence % at aselected or peak frequency. Optionally 'time warp' the single trial % time-domain (potential) or power data to align the plotted data to a series % of events with varying latencies that occur in each trial. Click on % individual figures parts to examine them separately and zoom (using axcopy()). % Usage: % >> figure; erpimage(data,[],times); % image trials as colored lines in input order % % >> figure; [outdata,outvar,outtrials,limits,axhndls, ... % erp,amps,cohers,cohsig,ampsig,outamps,... % phsangls,phsamp,sortidx,erpsig] ... % = erpimage(data,sortvar,times,'title',avewidth,decimate,... % 'key', 'val', ...); % use options % Required input: % data = [vector or matrix] Single-channel input data to image. % Formats (1,frames*trials) or (frames,trials) % % Optional ordered inputs {with defaults}: % % sortvar = [vector | []] Variable to sort epochs on (length(sortvar) = nepochs) % Example: sortvar may by subject response time in each epoch (in ms) % {default|[]: plot in input order} % times = [vector | []] vector of latencies (in ms) for each epoch time point. % Else [startms ntimes srate] = [start latency (ms), time points % (=frames) per epoch, sampling rate (Hz)]. Else [] -> 0:nframes-1 % {default: []} % 'title' = ['string'] Plot title {default: none} % avewidth = [positive scalar (may be non-integer)]. If avg_type is set to 'boxcar' % (the default), this is the number of trials used to smooth % (vertically) with a moving-average. If avg_type is set to % 'Gaussian,' this is the standard deviation (in units of % trials) of the Gaussian window used to smooth (vertically) % with a moving-average. Gaussian window extends three % standard deviations below and three standard deviations above window % center (trials beyond window are not incorporated into average). {default: no % smoothing} % decimate = Factor to decimate|interpolate ntrials by (may be non-integer) % Else, if this is large (> sqrt(ntrials)), output this many epochs. % {default|0->1} % % Optional unordered 'keyword',argument pairs: % % Re-align data epochs: % 'align' = [latency] Time-lock data to sortvar. Plot sortvar at given latency % (in ms). Else Inf -> plot sortvar at median sortvar latency % {default: do not align} % 'timewarp' = {[events], [warpms], {colors}} Time warp ERP, amplitude and phase % time-courses before smoothing. 'events' is a matrix whose columns % specify the latencies (in ms) at which a series of successive events occur % in each trial. 'warpms' is an optional vector of latencies (in ms) to which % the series of events should be time locked. (Note: Epoch start and end % should not be declared as events or warpms}. If 'warpms' is absent or [], % the median of each 'events' column will be used. {colors} contains a % list of Matlab linestyles to use for vertical lines marking the occurrence % of the time warped events. If '', no line will be drawn for this event % column. If fewer colors than event columns, cycles through the given color % labels. Note: Not compatible with 'vert' (below). % 'renorm' = ['yes'|'no'| formula] Normalize sorting variable to epoch % latency range and plot. 'yes'= autoscale. formula must be a linear % transformation in the format 'a*x+b' % Example of formula: '3*x+2'. {default: 'no'} % If sorting by string values like event type, suggested formulas for: % letter string: '1000*x', number string: '30000*x-1500' % 'noplot' = ['on'|'off'] Do not plot sortvar {default: Plot sortvar if in times range} % 'NoShow' = ['on'|'off'] Do not plot erpimage, simply return outputs {default: 'off'} % % Sort data epochs: % 'nosort' = ['on'|'off'] Do not sort data epochs. {default: Sort data epochs by % sortvar (see sortvar input above)} % 'replace_ties' = ['yes'|'no'] Replace trials with the same value of % sortvar with the mean of those trials. Only works if sorting trials % by sortvar. {default: 'no'} % 'valsort' = [startms endms direction] Sort data on (mean) value % between startms and (optional) endms. Direction is 1 or -1. % If -1, plot max-value epoch at bottom {default: sort on sortvar} % 'phasesort' = [ms_center prct freq maxfreq topphase] Sort epochs by phase in % a 3-cycle window centered at latency ms_center (ms). % Percentile (prct) in range [0,100] gives percent of trials % to reject for (too) low amplitude. Else, if in range [-100,0], % percent of trials to reject for (too) high amplitude; % freq (Hz) is the phase-sorting frequency. With optional % maxfreq, sort by phase at freq of max power in the data in % the range [freq,maxfreq] (Note: 'phasesort' arg freq overrides % the frequency specified in 'coher'). With optional topphase, % sort by phase, putting topphase (degrees, in range [-180,180]) % at the top of the image. Note: 'phasesort' now uses circular % smoothing. Use 'cycles' (below) for wavelet length. % {default: [0 25 8 13 180]} % 'ampsort' = [center_ms prcnt freq maxfreq] Sort epochs by amplitude. % (See 'phasesort' above). If ms_center is 'Inf', then sorting % is by mean power across the time window specified by 'sortwin' % below. If third arg, freq, is < 0, sort by mean power in the range % [ abs(freq) maxfreq ]. % 'sortwin' = [start_ms end_ms] If center_ms == Inf in 'ampsort' arg (above), sorts % by mean amplitude across window centers shifted from start_ms % to end_ms by 10 ms. % 'showwin' = ['on'|'off'] Show sorting window behind ERP trace. {default: 'off'} % % Plot time-varying spectral amplitude instead of potential: % 'plotamps' = ['on'|'off'] Image amplitudes at each trial and latency instead of % potential values. Note: Currently requires 'coher' (below) with alpha signif. % Use 'cycles' (see below) > (its default) 3 for better frequency specificity, % {default: plot potential, not amplitudes, with no minimum}. The average power % (in log space) before time 0 is automatically removed. Note that the % 'baseline' parameter has no effect on 'plotamps'. Instead use % change "baselinedb" or "basedB" in the 'limits' parameter. By default % the baseline is removed before time 0. % % Specify plot parameters: % 'limits' = [lotime hitime minerp maxerp lodB hidB locoher hicoher basedB] % Plot axes limits. Can use NaN (or nan, but not Nan) for missing items % and omit late items. Use last input, basedB, to set the % baseline dB amplitude in 'plotamps' plots {default: from data} % 'sortvar_limits' = [min max] minimum and maximum sorting variable % values to image. This only affects visualization of % ERPimage and ERPs (not smoothing). Cannot be used % if sorting by any factor besides sortvar (e.g., % phase). % 'signif' = [lo_dB, hi_dB, coher_signif_level] Use precomputed significance % thresholds (as from outputs ampsig, cohsig) to save time. {default: none} % 'caxis' = [lo hi] Set color axis limits. Else [fraction] Set caxis limits at % (+/-)fraction*max(abs(data)) {default: symmetrical in dB, based on data limits} % % Add epoch-mean ERP to plot: % 'erp' = ['on'|'off'|1|2|3|4] Plot ERP time average of the trials below the % image. If 'on' or 1, a single ERP (the mean of all trials) is shown. If 2, % two ERPs (super and sub median trials) are shown. If 3, the trials are split into % tertiles and their three ERPs are shown. If 4, the trials are split into quartiles % and four ERPs are shown. Note, if you want negative voltage plotted up, change YDIR % to -1 in icadefs.m. If 'erpalpha' option is used, any values of 'erp' greater than % 1 will be reset to 1. {default no ERP plotted} % 'erpalpha' = [alpha] Visualizes two-sided significance threshold (i.e., a two-tailed test) for the % null hypothesis of a zero mean, symmetric distribution (range: [.001 0.1]). Thresholds % are determined via a permutation test. Requires 'erp' to be a value other than 'off'. % If 'erp' is set to a value greater than 1, it is reset to 1 to increase plot readability. % {default: no alpha significance thresholds plotted} % 'erpstd' = ['on'|'off'] Plot ERP +/- stdev. Requires 'erp' {default: no std. dev. plotted} % 'erp_grid' = If 'erp_grid' is added as an option voltage axis dashed grid lines will be % added to the ERP plot to facilitate judging ERP amplitude % 'rmerp' = ['on'|'off'] Subtract the average ERP from each trial before processing {default: no} % % Add time/frequency information: % 'coher' = [freq] Plot ERP average plus mean amplitude & coherence at freq (Hz) % Else [minfrq maxfrq] = same, but select frequency with max power in % given range. (Note: the 'phasesort' freq (above) overwrites these % parameters). Else [minfrq maxfrq alpha] = plot coher. signif. level line % at probability alpha (range: [0,0.1]) {default: no coher, no alpha level} % 'srate' = [freq] Specify the data sampling rate in Hz for amp/coher (if not % implicit in third arg, times) {default: as defined in icadefs.m} % 'cycles' = [float] Number of cycles in the wavelet time/frequency decomposition {default: 3} % % Add plot features: % 'cbar' = ['on'|'off'] Plot color bar to right of ERP-image {default no} % 'cbar_title' = [string] The title for the color bar (e.g., '\muV' for % microvolts). % 'topo' = {map,chan_locs,eloc_info} Plot a 2-D scalp map at upper left of image. % map may be a single integer, representing the plotted data channel, % or a vector of scalp map channel values. chan_locs may be a channel locations % file or a chanlocs structure (EEG.chanlocs). See '>> topoplot example' % eloc_info (EEG.chaninfo), if empty ([]) or absent, implies the 'X' direction % points towards the nose and all channels are plotted {default: no scalp map} % 'spec' = [loHz,hiHz] Plot the mean data spectrum at upper right of image. % 'specaxis' = ['log'|'lin] Use 'lin' for linear spectrum frequency scaling, % else 'log' for log scaling {default: 'log'} % 'horz' = [epochs_vector] Plot horizontal lines at specified epoch numbers. % 'vert' = [times_vector] Plot vertical dashed lines at specified latencies % 'auxvar' = [size(nvars,ntrials) matrix] Plot auxiliary variable(s) for each trial % as separate traces. Else, 'auxvar',{[matrix],{colorstrings}} % to specify N trace colors. Ex: colorstrings = {'r','bo-','','k:'} % (see also: 'vert' and 'timewarp' above). {default: none} % 'sortvarpercent' = [float vector] Plot percentiles for the sorting variable % for instance, [0.1 0.5 0.9] plots the 10th percentile, the median % and the 90th percentile. % Plot options: % 'noxlabel' = ['on'|'off'] Do not plot "Time (ms)" on the bottom x-axis % 'yerplabel' = ['string'] ERP ordinate axis label (default is ERP). Print uV with '\muV' % 'avg_type' = ['boxcar'|'Gaussian'] The type of moving average used to smooth % the data. 'Boxcar' smoothes the data by simply taking the mean of % a certain number of trials above and below each trial. % 'Gaussian' does the same but first weights the trials % according to a Gaussian distribution (e.g., nearby trials % receive greater weight). The Gaussian is better than the % boxcar in that it rather evenly filters out high frequency % vertical components in the ERPimage. See 'avewidth' argument % description for more information. {default: boxcar} % 'img_trialax_label' = ['string'] The label of the axis corresponding to trials in the ERPimage % (e.g., 'Reaction Time'). Note, if img_trialax_label is set to something % besides 'Trials' or [], the tick marks on this axis will be set in units % of the sorting variable. This is a useful alternative to plotting the % sorting variable when the sorting variable is not in milliseconds. This % option is not effective if sorting by amplitude, phase, or EEG value. {default: 'Trials'} % 'img_trialax_ticks' = Vector of sorting variable values at which tick marks (e.g., [300 350 400 450] % for reaction time in msec) will appear on the trial axis of the erpimage. Tick mark % values should be given in units img_trialax_label (e.g., 'Trials' or msec). % This option is not effective if sorting by amplitude, phase, or EEG value. % {default: automatic} % 'baseline' = [low_boundary high_boundary] a time window (in msec) whose mean amplitude in % each trial will be removed from each trial (e.g., [-100 0]) after filtering. % Useful in conjunction with 'filt' option to re-basline trials after they have been % filtered. Not necessary if data have already been baselined and erpimage % processing does not affect baseline amplitude {default: no further baselining % of data}. % 'baselinedb' = [low_boundary high_boundary] a time window (in msec) whose mean amplitude in % each trial will be removed from each trial (e.g., [-100 0]). Use basedB in limits % to remove a fixed value. Default is time before 0. If you do not want to use a % baseline for amplitude plotting, enter a NaN value. % 'filt' = [low_boundary high_boundary] a two element vector indicating the frequency % cut-offs for a 3rd order Butterworth filter that will be applied to each % trial of data. If low_boundary=0, the filter is a low pass filter. If % high_boundary=srate/2, then the filter is a high pass filter. If both % boundaries are between 0 and srate/2, then the filter is a bandpass filter. % If both boundaries are between 0 and -srate/2, then the filter is a bandstop % filter (with boundaries equal to the absolute values of low_boundary and % high_boundary). Note, using this option requires the 'srate' option to be % specified and the signal processing toolbox function butter.m. You should % probably use the 'baseline' option as well since the mean prestimulus baseline % may no longer be 0 after the filter is applied {default: no filtering} % % Optional outputs: % outdata = (times,epochsout) data matrix (after smoothing) % outvar = (1,epochsout) actual values trials are sorted on (after smoothing). % if 'sortvarpercent' is used, this variable contains a cell array with % { sorted_values { sorted_percent1 ... sorted_percentN } } % outtrials = (1,epochsout) smoothed trial numbers % limits = (1,10) array, 1-9 as in 'limits' above, then analysis frequency (Hz) % axhndls = vector of 1-7 plot axes handles (img,cbar,erp,amp,coh,topo,spec) % erp = plotted ERP average % amps = mean amplitude time course % coher = mean inter-trial phase coherence time course % cohsig = coherence significance level % ampsig = amplitude significance levels [lo high] % outamps = matrix of imaged amplitudes (from option 'plotamps') % phsangls = vector of sorted trial phases at the phase-sorting frequency % phsamp = vector of sorted trial amplitudes at the phase-sorting frequency % sortidx = indices of input data epochs in the sorting order % erpsig = trial average significance levels [2,frames] % % Example: >> figure; % erpimage(data,RTs,[-400 256 256],'Test',1,1,... % 'erp','cbar','vert',-350); % Plots an ERP-image of 1-s data epochs sampled at 256 Hz, sorted by RTs, with % title ('Test'), and sorted epochs not smoothed or decimated (1,1). Overplots % the (unsmoothed) RT latencies on the colored ERP-image. Also plots the % epoch-mean (ERP), a color bar, and a dashed vertical line at -350 ms. % % Authors: Scott Makeig, Tzyy-Ping Jung & Arnaud Delorme, % CNL/Salk Institute, La Jolla, 3-2-1998 - % % See also: phasecoher, rmbase, cbar, movav % Copyright (C) Scott Makeig & Tzyy-Ping Jung, CNL / Salk Institute, La Jolla 3-2-98 % % 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 % Uses external toolbox functions: phasecoher(), rmbase(), cbar(), movav() % Uses included functions: plot1trace(), phasedet() % UNIMPLEMENTED - 'allcohers',[data2] -> image the coherences at each latency & epoch. % Requires arg 'coher' with alpha significance. % Shows projection on grand mean coherence vector at each latency % and trial. {default: no} %% LOG COMMENTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data,outsort,outtrials,limits,axhndls,erp,amps,cohers,cohsig,ampsig,allamps,phaseangles,phsamp,sortidx,erpsig] = erpimage(data,sortvar,times,titl,avewidth,decfactor,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12,arg13,arg14,arg15,arg16,arg17,arg18,arg19,arg20,arg21,arg22,arg23,arg24,arg25,arg26,arg27,arg28,arg29,arg30,arg31,arg32,arg33,arg34,arg35,arg36,arg37,arg38,arg39,arg40,arg41,arg42,arg43,arg44,arg45,arg46,arg47,arg48,arg49,arg50,arg51,arg52,arg53,arg54,arg55,arg56,arg57,arg58,arg59,arg60,arg61,arg62,arg63,arg64,arg65,arg66) % %% %%%%%%%%%%%%%%%%% Define defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Initialize optional output variables: warning off; erp = []; amps = []; cohers = []; cohsig = []; ampsig = []; allamps = []; phaseangles = []; phsamp = []; sortidx = []; auxvar = []; erpsig = []; winloc = [];winlocs = []; timeStretchColors = {}; YES = 1; % logical variables NO = 0; DEFAULT_BASELINE_END = 0; % ms TIMEX = 1; % 1 -> plot time on x-axis; % 0 -> plot trials on x-axis BACKCOLOR = [0.8 0.8 0.8]; % grey background try, icadefs; catch, end; % read BACKCOLOR for plot from defs file (edit this) % read DEFAULT_SRATE for coher,phase,allamps, etc. % read YDIR for plotting ERP % Fix plotting text and line style parameters SORTWIDTH = 2.5; % Linewidth of plotted sortvar ZEROWIDTH = 3.0; % Linewidth of vertical 0 line VERTWIDTH = 2.5; % Linewidth of optional vertical lines HORZWIDTH = 2.1; % Linewidth of optional vertical lines SIGNIFWIDTH = 1.9; % Linewidth of red significance lines for amp, coher DOTSTYLE = 'k--'; % line style to use for vetical dotted/dashed lines LINESTYLE = '-'; % solid line LABELFONT = 10; % font sizes for axis labels, tick labels TICKFONT = 10; PLOT_HEIGHT = 0.2; % fraction of y dim taken up by each time series axes YGAP = 0.03; % fraction gap between time axes YEXPAND = 1.3; % expansion factor for y-axis about erp, amp data limits DEFAULT_SDEV = 1/7; % smooth trials with this window size by default if Gaussian window DEFAULT_AVEWIDTH = 1; % smooth trials with this window size by default DEFAULT_DECFACTOR = 1; % decimate by this factor by default DEFAULT_CYCLES = 3; % use this many cycles in amp,coher computation window cycles = DEFAULT_CYCLES; DEFAULT_CBAR = NO;% do not plot color bar by default DEFAULT_PHARGS = [0 25 8 13]; % Default arguments for phase sorting DEFAULT_ALPHA = 0.01; alpha = 0; % default alpha level for coherence significance MIN_ERPALPHA = 0.001; % significance bounds for ERP MAX_ERPALPHA = 0.1; NoShowVar = NO; % show sortvar by default Nosort = NO; % sort on sortvar by default Caxflag = NO; % use default caxis by default timestretchflag = NO; % Added -JH mvavg_type='boxcar'; % use the original rectangular moving average -DG erp_grid = NO; % add y-tick grids to ERP plot -DG cbar_title = []; % title to add above ERPimage color bar (e.g., '\muV') -DG img_ylab = 'Trials'; % make the ERPimage y-axis in units of the sorting variable -DG img_ytick_lab = []; % the values at which tick marks will appear on the trial axis of the ERPimage (the y-axis by default). %Note, this is in units of the sorting variable if img_ylab~='Trials', otherwise it is in units of trials -DG baseline = []; %time window of each trial whose mean amp will be used to baseline the trial -DG baselinedb = []; %time window of each trial whose mean power will be used to baseline the trial flt=[]; %frequency domain filter parameters -DG sortvar_limits=[]; %plotting limits for sorting variable/trials; limits only affect visualization, not smoothing -DG replace_ties = NO; %if YES, trials with the exact same value of a sorting variable will be replaced by their average -DG erp_vltg_ticks=[]; %if non-empty, these are the voltage axis ticks for the ERP plot Caxis = []; caxfraction = []; Coherflag = NO; % don't compute or show amp,coher by default Cohsigflag= NO; % default: do not compute coherence significance Allampsflag=NO; % don't image the amplitudes by default Allcohersflag=NO; % don't image the coherence amplitudes by default Topoflag = NO; % don't plot a topoplot in upper left Specflag = NO; % don't plot a spectrum in upper right SpecAxisflag = NO; % don't change the default spectrum axis type from default SpecAxis = 'log'; % default log frequency spectrum axis (if Specflag) Erpflag = NO; % don't show erp average by default Erpstdflag= NO; Erpalphaflag= NO; Alignflag = NO; % don't align data to sortvar by default Colorbar = NO; % if YES, plot a colorbar to right of erp image Limitflag = NO; % plot whole times range by default Phaseflag = NO; % don't sort by phase Ampflag = NO; % don't sort by amplitude Sortwinflag = NO; % sort by amplitude over a window Valflag = NO; % don't sort by value Srateflag = NO; % srate not given Vertflag = NO; Horzflag = NO; titleflag = NO; NoShowflag = NO; Renormflag = NO; Showwin = NO; yerplabel = 'ERP'; yerplabelflag = NO; verttimes = []; horzepochs = []; NoTimeflag= NO; % by default DO print "Time (ms)" below bottom axis Signifflag= NO; % compute significance instead of receiving it Auxvarflag= NO; plotmodeflag= NO; plotmode = 'normal'; Cycleflag = NO; signifs = NaN; coherfreq = nan; % amp/coher-calculating frequency freq = 0; % phase-sorting frequency srate = DEFAULT_SRATE; % from icadefs.m aligntime = nan; timelimits= nan; topomap = []; % topo map vector lospecHz = []; % spec lo frequency topphase = 180; % default top phase for 'phase' option renorm = 'no'; NoShow = 'no'; Rmerp = 'no'; percentiles = []; percentileflag = NO; erp_ptiles = 1; minerp = NaN; % default limits maxerp = NaN; minamp = NaN; maxamp = NaN; mincoh = NaN; maxcoh = NaN; baseamp =NaN; allamps = []; % default return ax1 = NaN; % default axes handles axcb = NaN; ax2 = NaN; ax3 = NaN; ax4 = NaN; timeStretchRef = []; timeStretchMarks = []; tsurdata = []; % time-stretched data before smoothing (for timestretched-erp computation) % If time-stretching is off, this variable remains empty % %% %%%%%%%%%%%%%%%%% Test, fill in commandline args %%%%%%%%%%%%%%%%%%%%%%%%%%%% % if nargin < 1 help erpimage return end data = squeeze(data); if nargin < 3 | isempty(times) if size(data,1)==1 || size(data,2)==1 fprintf('\nerpimage(): either input a times vector or make data size = (frames,trials).\n') return end times = 1:size(data,1); NoTimesPassed= 1; end if nargin < 2 | isempty(sortvar) sortvar = 1:size(data,2); NoShowVar = 1; % don't plot the dummy sortvar end framestot = size(data,1)*size(data,2); ntrials = length(sortvar); if ntrials < 2 help erpimage fprintf('\nerpimage(): too few trials.\n'); return end frames = floor(framestot/ntrials); if frames*ntrials ~= framestot help erpimage fprintf(... '\nerpimage(); length of sortvar doesn''t divide number of data elements??\n') return end if nargin < 6 decfactor = 0; end if nargin < 5 avewidth = DEFAULT_AVEWIDTH; end if nargin<4 titl = ''; % default no title end if nargin<3 times = NO; end if (length(times) == 1) | (times == NO), % make default times times = 0:frames-1; srate = 1000*(length(times)-1)/(times(length(times))-times(1)); fprintf('Using sampling rate %g Hz.\n',srate); elseif length(times) == 3 mintime = times(1); frames = times(2); srate = times(3); times = mintime:1000/srate:mintime+(frames-1)*1000/srate; fprintf('Using sampling rate %g Hz.\n',srate); else % Note: might use default srate read from icadefs here... srate = 1000*(length(times)-1)/(times(end)-times(1)); end if length(times) ~= frames fprintf(... '\nerpimage(): length(data)(%d) ~= length(sortvar)(%d) * length(times)(%d).\n\n',... framestot, length(sortvar), length(times)); return end if decfactor == 0, decfactor = DEFAULT_DECFACTOR; elseif decfactor > ntrials fprintf('Setting variable decfactor to max %d.\n',ntrials) decfactor = ntrials; end % %% %%%%%%%%%%%%%%% Collect optional args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if nargin > 6 flagargs = []; a = 6; while a < nargin % for each remaining Arg a = a + 1; Arg = eval(['arg' int2str(a-6)]); if Caxflag == YES if size(Arg,1) ~= 1 || size(Arg,2) > 2 help erpimage fprintf('\nerpimage(): caxis arg must be a scalar or (1,2) vector.\n'); return end if size(Arg,2) == 2 Caxis = Arg; else caxfraction = Arg; end Caxflag = NO; elseif timestretchflag == YES % Added -JH timeStretchMarks = Arg{1}; timeStretchMarks = round(1+(timeStretchMarks-times(1))*srate/1000); % convert from ms to frames -sm [smc smr] = find(diff(timeStretchMarks') < 0); if ~isempty(smr) fprintf('\nerpimage(): Timewarp event latencies not in ascending order in trial %d.\n',smr) return end timeStretchMarks = [ ... repmat(1, [size(timeStretchMarks,1), 1]), ...% Epoch begins timeStretchMarks, ... repmat(length(times), [size(timeStretchMarks,1), 1])]; % Epoch ends if length(Arg) < 2 || isempty(Arg{2}) timeStretchRef = median(timeStretchMarks); else timeStretchRef = Arg{2}; timeStretchRef = round(1+(timeStretchRef-times(1))*srate/1000); % convert from ms to frames -sm timeStretchRef = [1 timeStretchRef length(times)]; % add epoch beginning, end end if length(Arg) < 3 || isempty(Arg{3}) timeStretchColors = {}; else timeStretchColors = Arg{3}; end fprintf('The %d events specified in each trial will be time warped to latencies:',length(timeStretchRef)-2); fprintf(' %.0f', times(1)+1000*(timeStretchRef(2:end-1)-1)/srate); % converted from frames to ms -sm fprintf(' ms\n'); timestretchflag = NO; elseif Coherflag == YES if length(Arg) > 3 || length(Arg) < 1 help erpimage fprintf('\nerpimage(): coher arg must be size <= 3.\n'); return end coherfreq = Arg(1); if size(Arg,2) == 1 coherfreq = Arg(1); else coherfreq = Arg(1:2); end; if size(Arg,2) == 3 Cohsigflag = YES; alpha = Arg(3); if alpha < 0 || alpha > 0.1 fprintf('\nerpimage(): alpha value %g out of bounds.\n',alpha); return end end Coherflag = NO; Erpflag = YES; % plot amp, coher below erp time series elseif Topoflag == YES; if length(Arg) < 2 help erpimage fprintf('\nerpimage(): topo arg must be a list of length 2 or 3.\n'); return end topomap = Arg{1}; eloc_file = Arg{2}; if length(Arg) > 2, eloc_info = Arg{3}; else eloc_info = []; end; Topoflag = NO; elseif Specflag == YES; if length(Arg) ~= 2 error('\nerpimage(): ''spec'' flag argument must be a numeric array of length 2.\n'); return end lospecHz = Arg(1); hispecHz = Arg(2); Specflag = NO; elseif SpecAxisflag == YES; SpecAxis = Arg; if ~strcmpi(SpecAxis,'lin') && ~strcmpi(SpecAxis,'log') error('\nerpimage(): spectrum axis type must be ''lin'' or ''log''.\n'); return end if strcmpi(SpecAxis,'lin') SpecAxis = 'linear'; % convert to MATLAB Xscale keyword end SpecAxisflag = NO; elseif Renormflag == YES renorm = Arg; Renormflag = NO; elseif NoShowflag == YES NoShow = Arg; if strcmpi(NoShow, 'off'), NoShow = 'no'; end; NoShowflag = NO; elseif Alignflag == YES aligntime = Arg; Alignflag = NO; elseif percentileflag == YES percentiles = Arg; percentileflag = NO; elseif Limitflag == YES % [lotime hitime loerp hierp loamp hiamp locoher hicoher] if size(Arg,1) ~= 1 || size(Arg,2) < 2 || size(Arg,2) > 9 help erpimage fprintf('\nerpimage(): limits arg must be a vector sized (1,2<->9).\n'); return end if ~isnan(Arg(1)) & (Arg(2) <= Arg(1)) help erpimage fprintf('\nerpimage(): time limits out of order or out of range.\n'); return end if Arg(1) < min(times) Arg(1) = min(times); fprintf('Adjusting mintime limit to first data value %g\n',min(times)); end if Arg(2) > max(times) Arg(2) = max(times); fprintf('Adjusting maxtime limit to last data value %g\n',max(times)); end timelimits = Arg(1:2); if length(Arg)> 2 minerp = Arg(3); end if length(Arg)> 3 maxerp = Arg(4); end if ~isnan(maxerp) & maxerp <= minerp help erpimage fprintf('\nerpimage(): erp limits args out of order.\n'); return end if length(Arg)> 4 minamp = Arg(5); end if length(Arg)> 5 maxamp = Arg(6); end if maxamp <= minamp help erpimage fprintf('\nerpimage(): amp limits args out of order.\n'); return end if length(Arg)> 6 mincoh = Arg(7); end if length(Arg)> 7 maxcoh = Arg(8); end if maxcoh <= mincoh help erpimage fprintf('\nerpimage(): coh limits args out of order.\n'); return end if length(Arg)>8 baseamp = Arg(9); % for 'allamps' end Limitflag = NO; elseif Srateflag == YES srate = Arg(1); Srateflag = NO; elseif Cycleflag == YES cycles = Arg; Cycleflag = NO; elseif Auxvarflag == YES; if isa(Arg,'cell')==YES && length(Arg)==2 auxvar = Arg{1}; auxcolors = Arg{2}; elseif isa(Arg,'cell')==YES fprintf('\nerpimage(): auxvars argument must be a matrix or length-2 cell array.\n'); return else auxvar = Arg; % no auxcolors specified end [xr,xc] = size(auxvar); lns = length(sortvar); if xr ~= lns && xc ~= lns error('\nerpimage(): auxvar columns different from the number of epochs in data'); elseif xr == lns && xc ~= lns auxvar = auxvar'; % exchange rows/cols end Auxvarflag = NO; elseif Vertflag == YES verttimes = Arg; Vertflag = NO; elseif Horzflag == YES horzepochs = Arg; Horzflag = NO; elseif yerplabelflag == YES yerplabel = Arg; yerplabelflag = NO; elseif Signifflag == YES signifs = Arg; % [low_amp hi_amp coher] if length(signifs) ~= 3 fprintf('\nerpimage(): signif arg [%g] must have 3 values\n',Arg); return end Signifflag = NO; elseif Allcohersflag == YES data2=Arg; if size(data2) ~= size(data) fprintf('\nerpimage(): allcohers data matrix must be the same size as data.\n'); return end Allcohersflag = NO; elseif Phaseflag == YES n = length(Arg); if n > 5 error('\nerpimage(): Too many arguments for keyword ''phasesort'''); end phargs = Arg; if phargs(3) < 0 error('\nerpimage(): Invalid negative frequency argument for keyword ''phasesort'''); end if n>=4 if phargs(4) < 0 error('\nerpimage(): Invalid negative argument for keyword ''phasesort'''); end end if min(phargs(1)) < times(1) | max(phargs(1)) > times(end) error('\nerpimage(): time for phase sorting filter out of bound.'); end if phargs(2) >= 100 | phargs(2) < -100 error('\nerpimage(): %-argument for keyword ''phasesort'' must be (-100;100)'); end if length(phargs) >= 4 & phargs(3) > phargs(4) error('\nerpimage(): Phase sorting frequency range must be increasing.'); end if length(phargs) == 5 topphase = phargs(5); end Phaseflag = NO; elseif Sortwinflag == YES % 'ampsort' mean amplitude over a time window n = length(Arg); sortwinarg = Arg; if n > 2 error('\nerpimage(): Too many arguments for keyword ''sortwin'''); end if min(sortwinarg(1)) < times(1) | max(sortwinarg(1)) > times(end) error('\nerpimage(): start time for value sorting out of bounds.'); end if n > 1 if min(sortwinarg(2)) < times(1) | max(sortwinarg(2)) > times(end) error('\nerpimage(): end time for value sorting out of bounds.'); end end if n > 1 & sortwinarg(1) > sortwinarg(2) error('\nerpimage(): Value sorting time range must be increasing.'); end Sortwinflag = NO; elseif Ampflag == YES % 'ampsort',[center_time,prcnt_reject,minfreq,maxfreq] n = length(Arg); if n > 4 error('\nerpimage(): Too many arguments for keyword ''ampsort'''); end ampargs = Arg; % if ampargs(3) < 0 % error('\nerpimage(): Invalid negative argument for keyword ''ampsort'''); % end if n>=4 if ampargs(4) < 0 error('\nerpimage(): Invalid negative argument for keyword ''ampsort'''); end end if ~isinf(ampargs(1)) if min(ampargs(1)) < times(1) | max(ampargs(1)) > times(end) error('\nerpimage(): time for amplitude sorting filter out of bounds.'); end end if ampargs(2) >= 100 | ampargs(2) < -100 error('\nerpimage(): percentile argument for keyword ''ampsort'' must be (-100;100)'); end if length(ampargs) == 4 & abs(ampargs(3)) > abs(ampargs(4)) error('\nerpimage(): Amplitude sorting frequency range must be increasing.'); end Ampflag = NO; elseif Valflag == YES % sort by potential value in a given window % Usage: 'valsort',[mintime,maxtime,direction] n = length(Arg); if n > 3 error('\nerpimage(): Too many arguments for keyword ''valsort'''); end valargs = Arg; if min(valargs(1)) < times(1) | max(valargs(1)) > times(end) error('\nerpimage(): start time for value sorting out of bounds.'); end if n > 1 if min(valargs(2)) < times(1) | max(valargs(2)) > times(end) error('\nerpimage(): end time for value sorting out of bounds.'); end end if n > 1 & valargs(1) > valargs(2) error('\nerpimage(): Value sorting time range must be increasing.'); end if n==3 & (~isnumeric(valargs(3)) | valargs(3)==0) error('\nerpimage(): Value sorting direction must be +1 or -1.'); end Valflag = NO; elseif plotmodeflag == YES plotmode = Arg; plotmodeflag = NO; elseif titleflag == YES titl = Arg; titleflag = NO; elseif Erpalphaflag == YES erpalpha = Arg(1); if erpalpha < MIN_ERPALPHA | erpalpha > MAX_ERPALPHA fprintf('\nerpimage(): erpalpha value is out of bounds [%g, %g]\n',... MIN_ERPALPHA,MAX_ERPALPHA); return end Erpalphaflag = NO; % ----------------------------------------------------------------------- % ----------------------------------------------------------------------- % ----------------------------------------------------------------------- elseif strcmpi(Arg,'avg_type') if a < nargin, a=a+1; Arg = eval(['arg' int2str(a-6)]); if strcmpi(Arg, 'Gaussian'), mvavg_type='gaussian'; elseif strcmpi(Arg, 'Boxcar'), mvavg_type='boxcar'; else error('\nerpimage(): Invalid value for optional argument ''avg_type''.'); end; else error('\nerpimage(): Optional argument ''avg_type'' needs to be assigned a value.'); end elseif strcmp(Arg,'nosort') Nosort = YES; if a < nargin, Arg = eval(['arg' int2str(a+1-6)]); if strcmpi(Arg, 'on'), Nosort = YES; a = a+1; elseif strcmpi(Arg, 'off') Nosort = NO; a = a+1; end; end; elseif strcmp(Arg,'showwin') Showwin = YES; if a < nargin, Arg = eval(['arg' int2str(a+1-6)]); if strcmpi(Arg, 'on'), Showwin = YES; a = a+1; elseif strcmpi(Arg, 'off') Showwin = NO; a = a+1; end; end; elseif strcmp(Arg,'noplot') % elseif strcmp(Arg,'NoShow') % by Luca & Ramon NoShowVar = YES; if a < nargin, Arg = eval(['arg' int2str(a+1-6)]); if strcmpi(Arg, 'on'), NoShowVar = YES; a = a+1; elseif strcmpi(Arg, 'off'), NoShowVar = NO; a = a+1; end; end; elseif strcmpi(Arg,'replace_ties') if a < nargin, a = a+1; temp = eval(['arg' int2str(a-6)]); if strcmpi(temp,'on'), replace_ties = YES; elseif strcmpi(temp,'off') replace_ties = NO; else error('\nerpimage(): Argument ''replace_ties'' needs to be followed by the string ''on'' or ''off''.'); end else error('\nerpimage(): Argument ''replace_ties'' needs to be followed by the string ''on'' or ''off''.'); end elseif strcmpi(Arg,'sortvar_limits') if a < nargin, a = a+1; sortvar_limits = eval(['arg' int2str(a-6)]); if ischar(sortvar_limits) || length(sortvar_limits)~=2 error('\nerpimage(): Argument ''sortvar_limits'' needs to be followed by a two element vector.'); end else error('\nerpimage(): Argument ''sortvar_limits'' needs to be followed by a two element vector.'); end elseif strcmpi(Arg,'erp') Erpflag = YES; erp_ptiles=1; if a < nargin, Arg = eval(['arg' int2str(a+1-6)]); if strcmpi(Arg, 'on'), Erpflag = YES; erp_ptiles=1; a = a+1; elseif strcmpi(Arg, 'off') Erpflag = NO; a = a+1; elseif strcmpi(Arg,'1') | (Arg==1) Erplag = YES; erp_ptiles=1; a=a+1; elseif strcmpi(Arg,'2') | (Arg==2) Erplag = YES; erp_ptiles=2; a=a+1; elseif strcmpi(Arg,'3') | (Arg==3) Erplag = YES; erp_ptiles=3; a=a+1; elseif strcmpi(Arg,'4') | (Arg==4) Erplag = YES; erp_ptiles=4; a=a+1; end; end; elseif strcmpi(Arg,'rmerp') Rmerp = 'yes'; if a < nargin, Arg = eval(['arg' int2str(a+1-6)]); if strcmpi(Arg, 'on'), Rmerp = 'yes'; a = a+1; elseif strcmpi(Arg, 'off') Rmerp = 'no'; a = a+1; end; end; elseif strcmp(Arg,'cbar') | strcmp(Arg,'colorbar') Colorbar = YES; if a < nargin, Arg = eval(['arg' int2str(a+1-6)]); if strcmpi(Arg, 'on'), Colorbar = YES; a = a+1; elseif strcmpi(Arg, 'off') Colorbar = NO; a = a+1; end; end; elseif (strcmp(Arg,'allamps') | strcmp(Arg,'plotamps')) Allampsflag = YES; if a < nargin, Arg = eval(['arg' int2str(a+1-6)]); if strcmpi(Arg, 'on'), Allampsflag = YES; a = a+1; elseif strcmpi(Arg, 'off') Allampsflag = NO; a = a+1; end; end; elseif strcmpi(Arg,'erpstd') Erpstdflag = YES; if a < nargin, Arg = eval(['arg' int2str(a+1-6)]); if strcmpi(Arg, 'on'), Erpstdflag = YES; a = a+1; elseif strcmpi(Arg, 'off') Erpstdflag = NO; a = a+1; end; end; elseif strcmp(Arg,'noxlabel') | strcmp(Arg,'noxlabels') | strcmp(Arg,'nox') NoTimeflag = YES; if a < nargin, Arg = eval(['arg' int2str(a+1-6)]); if strcmpi(Arg, 'on'), NoTimeflag = YES; a = a+1; elseif strcmpi(Arg, 'off') NoTimeflag = NO; a = a+1; end; end; elseif strcmp(Arg,'plotmode') plotmodeflag = YES; elseif strcmp(Arg,'sortvarpercent') percentileflag = YES; elseif strcmp(Arg,'renorm') Renormflag = YES; elseif strcmp(Arg,'NoShow') NoShowflag = YES; elseif strcmp(Arg,'caxis') Caxflag = YES; elseif strcmp(Arg,'title') titleflag = YES; elseif strcmp(Arg,'coher') Coherflag = YES; elseif strcmp(Arg,'timestretch') | strcmp(Arg,'timewarp') % Added -JH timestretchflag = YES; elseif strcmp(Arg,'allcohers') Allcohersflag = YES; elseif strcmp(Arg,'topo') | strcmp(Arg,'topoplot') Topoflag = YES; elseif strcmp(Arg,'spec') | strcmp(Arg,'spectrum') Specflag = YES; elseif strcmp(Arg,'Specaxis') || strcmp(Arg,'specaxis') || strcmp(Arg,'SpecAxis') SpecAxisflag = YES; elseif strcmpi(Arg,'erpalpha') Erpalphaflag = YES; elseif strcmp(Arg,'align') Alignflag = YES; elseif strcmp(Arg,'limits') Limitflag = YES; elseif (strcmp(Arg,'phase') | strcmp(Arg,'phasesort')) Phaseflag = YES; elseif strcmp(Arg,'ampsort') Ampflag = YES; elseif strcmp(Arg,'sortwin') Sortwinflag = YES; elseif strcmp(Arg,'valsort') Valflag = YES; elseif strcmp(Arg,'auxvar') Auxvarflag = YES; elseif strcmp(Arg,'cycles') Cycleflag = YES; elseif strcmpi(Arg,'yerplabel') yerplabelflag = YES; elseif strcmpi(Arg,'srate') Srateflag = YES; elseif strcmpi(Arg,'erp_grid') erp_grid = YES; elseif strcmpi(Arg,'baseline') if a < nargin, a = a+1; baseline = eval(['arg' int2str(a-6)]); else error('\nerpimage(): Argument ''baseline'' needs to be followed by a two element vector.'); end elseif strcmpi(Arg,'baselinedb') if a < nargin, a = a+1; baselinedb = eval(['arg' int2str(a-6)]); if length(baselinedb) > 2, error('''baselinedb'' need to be a 2 argument vector'); end; else error('\nerpimage(): Argument ''baselinedb'' needs to be followed by a two element vector.'); end elseif strcmpi(Arg,'filt') if a < nargin, a = a+1; flt = eval(['arg' int2str(a-6)]); else error('\nerpimage(): Argument ''filt'' needs to be followed by a two element vector.'); end elseif strcmpi(Arg,'erp_vltg_ticks') if a < nargin, a = a+1; erp_vltg_ticks=eval(['arg' int2str(a-6)]); else error('\nerpimage(): Argument ''erp_vltg_ticks'' needs to be followed by a vector.'); end elseif strcmpi(Arg,'img_trialax_label') if a < nargin, a = a+1; img_ylab = eval(['arg' int2str(a-6)]); else error('\nerpimage(): Argument ''img_trialax_label'' needs to be followed by a string.'); end; elseif strcmpi(Arg,'img_trialax_ticks') if a < nargin, a = a+1; img_ytick_lab = eval(['arg' int2str(a-6)]); else error('\nerpimage(): Argument ''img_trialax_ticks'' needs to be followed by a vector of values at which tick marks will appear.'); end; elseif strcmpi(Arg,'cbar_title') if a < nargin, a = a+1; cbar_title = eval(['arg' int2str(a-6)]); else error('\nerpimage(): Argument ''cbar_title'' needs to be followed by a string.'); end; elseif strcmp(Arg,'vert') || strcmp(Arg,'verttimes') Vertflag = YES; elseif strcmp(Arg,'horz') || strcmp(Arg,'horiz') || strcmp(Arg,'horizontal') Horzflag = YES; elseif strcmp(Arg,'signif') || strcmp(Arg,'signifs') || strcmp(Arg,'sig') || strcmp(Arg,'sigs') Signifflag = YES; else help erpimage if isstr(Arg) fprintf('\nerpimage(): unknown arg %s\n',Arg); else fprintf('\nerpimage(): unknown arg %d, size(%d,%d)\n',a,size(Arg,1),size(Arg,2)); end return end end % Arg end if exist('img_ylab','var') || exist('img_ytick_lab','var'), oops=0; if exist('phargs','var'), fprintf('********* Warning *********\n'); fprintf('Options ''img_ylab'' and ''img_ytick_lab'' have no effect when sorting by phase.\n'); oops=0; elseif exist('valargs','var'), fprintf('********* Warning *********\n'); fprintf('Options ''img_ylab'' and ''img_ytick_lab'' have no effect when sorting by EEG voltage.\n'); oops=0; elseif exist('ampargs','var'), fprintf('********* Warning *********\n'); fprintf('Options ''img_ylab'' and ''img_ytick_lab'' have no effect when sorting by frequency amplitude.\n'); oops=0; end if oops img_ylab=[]; img_ytick_lab=[]; end end if Caxflag == YES ... |Coherflag == YES ... |Alignflag == YES ... |Limitflag == YES help erpimage fprintf('\nerpimage(): missing option arg.\n') return end if (Allampsflag | exist('data2')) & ( any(isnan(coherfreq)) | ~Cohsigflag ) fprintf('\nerpimage(): allamps and allcohers flags require coher freq, srate, and cohsig.\n'); return end if Allampsflag & exist('data2') fprintf('\nerpimage(): cannot image both allamps and allcohers.\n'); return end if ~exist('srate') | srate <= 0 fprintf('\nerpimage(): Data srate must be specified and > 0.\n'); return end if ~isempty(auxvar) % whos auxvar if size(auxvar,1) ~= ntrials & size(auxvar,2) ~= ntrials fprintf('\nerpimage(): auxvar size should be (N,ntrials), e.g., (N,%d)\n',... ntrials); return end if size(auxvar,1) == ntrials & size(auxvar,2) ~= ntrials % make (N,frames) auxvar = auxvar'; end if size(auxvar,2) ~= ntrials fprintf('\nerpimage(): auxvar size should be (N,ntrials), e.g., (N,%d)\n',... ntrials); return end if exist('auxcolors')==YES % if specified if isa(auxcolors,'cell')==NO % if auxcolors is not a cell array fprintf(... '\nerpimage(): auxcolors argument to auxvar flag must be a cell array.\n'); return end end elseif exist('timeStretchRef') & ~isempty(timeStretchRef) if ~isnan(aligntime) fprintf(['\nerpimage(): options "align" and ' ... '"timewarp" are not compatiable.\n']); return; end if ~isempty(timeStretchColors) if length(timeStretchColors) < length(timeStretchRef) nColors = length(timeStretchColors); for k=nColors+1:length(timeStretchRef)-2 timeStretchColors = { timeStretchColors{:} timeStretchColors{1+rem(k-1,nColors)}}; end end timeStretchColors = {'' timeStretchColors{:} ''}; else timeStretchColors = { 'k--'}; for k=2:length(timeStretchRef) timeStretchColors = { timeStretchColors{:} 'k--'}; end end auxvarInd = 1-strcmp('',timeStretchColors); % indicate which lines to draw newauxvars = ((timeStretchRef(find(auxvarInd))-1)/srate+times(1)/1000) * 1000; % convert back to ms fprintf('Overwriting vert with auxvar\n'); verttimes = [newauxvars']; verttimesColors = {timeStretchColors{find(auxvarInd)}}; newauxvars = repmat(newauxvars, [1 ntrials]); if isempty(auxvar) % Initialize auxvar & auxcolors % auxvar = newauxvars; auxcolors = {timeStretchColors{find(auxvarInd)}}; else % Append auxvar & auxcolors if ~exist('auxcolors') % Fill with default color (k-- for now) auxcolors = {}; for j=1:size(auxvar,1) auxcolors{end+1} = 'k--'; end end for j=find(auxvarInd) auxcolors{end+1} = timeStretchColors{j}; end auxvar = [auxvar; newauxvars]; end end % No need to turn off ERP anymore; we now time-stretch potentials % separately (see tsurdata below) so the (warped) ERP is actually meaningful if exist('phargs') if phargs(3) > srate/2 fprintf(... '\nerpimage(): Phase-sorting frequency (%g Hz) must be less than Nyquist rate (%g Hz).',... phargs(3),srate/2); end if frames < cycles*srate/phargs(3) fprintf('\nerpimage(): phase-sorting freq. (%g) too low: epoch length < %d cycles.\n',... phargs(3),cycles); return end if length(phargs)==4 & phargs(4) > srate/2 phargs(4) = srate/2; end if length(phargs)==5 & (phargs(5)>180 | phargs(5) < -180) fprintf('\nerpimage(): coher topphase (%g) out of range.\n',topphase); return end end if exist('ampargs') if abs(ampargs(3)) > srate/2 fprintf(... '\nerpimage(): amplitude-sorting frequency (%g Hz) must be less than Nyquist rate (%g Hz).',... abs(ampargs(3)),srate/2); end if frames < cycles*srate/abs(ampargs(3)) fprintf('\nerpimage(): amplitude-sorting freq. (%g) too low: epoch length < %d cycles.\n',... abs(ampargs(3)),cycles); return end if length(ampargs)==4 & abs(ampargs(4)) > srate/2 ampargs(4) = srate/2; fprintf('> Reducing max ''ampsort'' frequency to Nyquist rate (%g Hz)\n',srate/2) end end if ~any(isnan(coherfreq)) if coherfreq(1) <= 0 | srate <= 0 fprintf('\nerpimage(): coher frequency (%g) out of range.\n',coherfreq(1)); return end if coherfreq(end) > srate/2 | srate <= 0 fprintf('\nerpimage(): coher frequency (%g) out of range.\n',coherfreq(end)); return end if frames < cycles*srate/coherfreq(1) fprintf('\nerpimage(): coher freq. (%g) too low: epoch length < %d cycles.\n',... coherfreq(1),cycles); return end end if isnan(timelimits) timelimits = [min(times) max(times)]; end if ~isstr(aligntime) & ~isnan(aligntime) if ~isinf(aligntime) ... & (aligntime < timelimits(1) | aligntime > timelimits(2)) help erpimage fprintf('\nerpimage(): requested align time outside of time limits.\n'); return end end % %% %%%%%%%%%%%%%% Replace nan's with 0s %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nans = find(isnan(data)); if length(nans) fprintf('Replaced %d nan in data with 0s.\n'); data(nans) = 0; end % %% %%%%%%%%%%%% Reshape data to (frames,ntrials) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if size(data,2) ~= ntrials if size(data,1)>1 % fprintf('frames %d, ntrials %d length(data) %d\n',frames,ntrials,length(data)); data=reshape(data,1,frames*ntrials); end data=reshape(data,frames,ntrials); end fprintf('Plotting input data as %d epochs of %d frames sampled at %3.1f Hz.\n',... ntrials,frames,srate); % %% %%%%%%%%%%%% Reshape data2 to (frames,ntrials) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if exist('data2') == 1 if size(data2,2) ~= ntrials if size(data2,1)>1 data2=reshape(data2,1,frames*ntrials); end data2=reshape(data2,frames,ntrials); end end % %% %%%%%%%%%%%%% if sortvar=NaN, remove lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -ad % if any(isnan(sortvar)) nanlocs = find(isnan(sortvar)); fprintf('Removing %d trials with NaN sortvar values.\n', length(nanlocs)); data(:,nanlocs) = []; sortvar(nanlocs) = []; if exist('data2') == 1 data2(:,nanlocs) = []; end; if ~isempty(auxvar) auxvar(:,nanlocs) = []; end if ~isempty(verttimes) if size(verttimes,1) == ntrials verttimes(nanlocs,:) = []; end; end; ntrials = size(data,2); if ntrials <= 1, close(gcf); error('\nerpimage(): Too few trials'); end; end; %% Create moving average window %% if strcmpi(mvavg_type,'Gaussian'), %construct Gaussian window to weight trials if avewidth == 0, avewidth = DEFAULT_SDEV; elseif avewidth < 1, help erpimage fprintf('\nerpimage(): Variable avewidth cannot be < 1.\n') fprintf('\nerpimage(): avewidth needs to be a positive integer.\n') return end wt_wind=exp(-0.5*([-3*avewidth:3*avewidth]/avewidth).^2)'; wt_wind=wt_wind/sum(wt_wind); %normalize to unit sum avewidth=length(wt_wind); if avewidth > ntrials avewidth=floor((ntrials-1)/6); if avewidth==0, avewidth=DEFAULT_SDEV; %should be a window with one time point (smallest possible) end wt_wind=exp(-0.5*([-3*avewidth:3*avewidth]/avewidth).^2)'; wt_wind=wt_wind/sum(wt_wind); fprintf('avewidth is too big for this number of trials.\n'); fprintf('Changing avewidth to maximum possible size: %d\n',avewidth); avewidth=length(wt_wind); end else %construct rectangular "boxcar" window to equally weight trials within %window if avewidth == 0, avewidth = DEFAULT_AVEWIDTH; elseif avewidth < 1 help erpimage fprintf('\nerpimage(): Variable avewidth cannot be < 1.\n') return elseif avewidth > ntrials fprintf('Setting variable avewidth to max %d.\n',ntrials) avewidth = ntrials; end wt_wind=ones(1,avewidth)/avewidth; end %% Filter data with Butterworth filter (if requested) %%%%%%%%%%%% % if ~isempty(flt) %error check if length(flt)~=2, error('\nerpimage(): ''filt'' parameter argument should be a two element vector.'); elseif max(flt)>(srate/2), error('\nerpimage(): ''filt'' parameters need to be less than or equal to sampling rate/2 (i.e., %f).',srate/2); elseif (flt(2)==(srate/2)) && (flt(1)==0), error('\nerpimage(): If second element of ''filt'' parameter is srate/2, then the first element must be greater than 0.'); elseif abs(flt(2))<=abs(flt(1)), error('\nerpimage(): Second element of ''filt'' parameters must be greater than first in absolute value.'); elseif (flt(1)<0) || (flt(2)<0), if (flt(1)>=0) || (flt(2)>=0), error('\nerpimage(): BOTH parameters of ''filt'' need to be greater than or equal to zero OR need to be negative.'); end if min(flt)<=(-srate/2), error('\nerpimage(): ''filt'' parameters need to be greater than sampling rate/2 (i.e., -%f) when creating a stop band.',srate/2); end end fprintf('\nFiltering data with 3rd order Butterworth filter: '); if (flt(1)==0), %lowpass filter the data [B A]=butter(3,flt(2)*2/srate,'low'); fprintf('lowpass at %.0f Hz\n',flt(2)); elseif (flt(2)==(srate/2)), %highpass filter the data [B A]=butter(3,flt(1)*2/srate,'high'); fprintf('highpass at %.0f Hz\n',flt(1)); elseif (flt(1)<0) %bandstop filter the data flt=-flt; [B A]=butter(3,flt*2/srate,'stop'); fprintf('stopband from %.0f to %.0f Hz\n',flt(1),flt(2)); else %bandpass filter the data [B A]=butter(3,flt*2/srate); fprintf('bandpass from %.0f to %.0f Hz\n',flt(1),flt(2)); end s=size(data); for trial=1:s(2), data(:,trial)=filtfilt(B,A,double(data(:,trial))); end if isempty(baseline) fprintf('Note, you might want to re-baseline the data using the erpimage ''baseline'' option.\n\n'); end end %% Mean Baseline Each Trial (if requested) %% if ~isempty(baseline), %check argument values for errors if baseline(2)<baseline(1), error('\nerpimage(): First element of ''baseline'' argument needs to be less than or equal to second argument.'); elseif baseline(2)<times(1), error('\nerpimage(): Second element of ''baseline'' argument needs to be greater than or equal to epoch start time %.1f.',times(1)); elseif baseline(1)>times(end), error('\nerpimage(): First element of ''baseline'' argument needs to be less than or equal to epoch end time %.1f.',times(end)); end %convert msec into time points if baseline(1)<times(1), strt_pt=1; else strt_pt=find_crspnd_pt(baseline(1),times,1:length(times)); strt_pt=ceil(strt_pt); end if baseline(end)>times(end), end_pt=length(times); else end_pt=find_crspnd_pt(baseline(2),times,1:length(times)); end_pt=floor(end_pt); end fprintf('\nRemoving pre-stimulus mean baseline from %.1f to %.1f msec.\n\n',times(strt_pt),times(end_pt)); bsln_mn=mean(data(strt_pt:end_pt,:),1); data=data-repmat(bsln_mn,length(times),1); end % %% %%%%%%%%%%%%%%%%% Renormalize sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % switch lower(renorm) case 'yes', disp('\nerpimage warning: *** sorting variable renormalized ***'); sortvar = (sortvar-min(sortvar)) / (max(sortvar) - min(sortvar)) * ... 0.5 * (max(times) - min(times)) + min(times) + 0.4*(max(times) - min(times)); case 'no',; otherwise, if ~isempty(renorm) locx = findstr('x', lower(renorm)); if length(locx) ~= 1, error('\nerpimage: unrecognized renormalizing formula'); end; eval( [ 'sortvar =' renorm(1:locx-1) 'sortvar' renorm(locx+1:end) ';'] ); end; end; % %% %%%%%%%%%%%%%%%%% Align data to sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isstr(aligntime) | ~isnan(aligntime) if ~isstr(aligntime) & isinf(aligntime) aligntime= median(sortvar); fprintf('Aligning data to median sortvar.\n'); % Alternative below: trimmed median - ignore top/bottom 5% % ssv = sort(sortvar); % ssv = 'sorted sortvar' % aligntime= median(ssv(ceil(ntrials/20)):floor(19*ntrials/20)); end if ~isstr(aligntime) fprintf('Realigned sortvar plotted at %g ms.\n',aligntime); aligndata=zeros(frames,ntrials); % begin with matrix of zeros() shifts = zeros(1,ntrials); for t=1:ntrials, %%%%%%%%% foreach trial %%%%%%%%% shft = round((aligntime-sortvar(t))*srate/1000); shifts(t) = shft; if shft>0, % shift right if frames-shft > 0 aligndata(shft+1:frames,t)=data(1:frames-shft,t); else fprintf('No aligned data for epoch %d - shift (%d frames) too large.\n',t,shft); end elseif shft < 0 % shift left if frames+shft > 0 aligndata(1:frames+shft,t)=data(1-shft:frames,t); else fprintf('No aligned data for epoch %d - shift (%d frames) too large.\n',t,shft); end else % shft == 0 aligndata(:,t) = data(:,t); end end % end trial if ~isempty(auxvar) auxvar = auxvar+shifts; end; fprintf('Shifted epochs by %d to %d frames.\n',min(shifts),max(shifts)); data = aligndata; % now data is aligned to sortvar else aligntime = str2num(aligntime); if isinf(aligntime), aligntime= median(sortvar); end; end; end % %% %%%%%%%%%%%%%%%%%%%% Remove the ERP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(Rmerp, 'yes') data = data - repmat(nan_mean(data')', [1 size(data,2)]); end; % %% %%%%%%%%%%%%% Sort the data trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if exist('phargs') == 1 % if phase-sort the data trials if length(phargs) >= 4 & phargs(3) ~= phargs(4) % find max frequency % in specified band if exist('psd') == 2 % requires Signal Processing Toolbox fprintf('Computing data spectrum using psd().\n'); [pxx,freqs] = psd(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0); else % EEGLAB native work-around fprintf('Computing data spectrum using spec().\n'); [pxx,freqs] = spec(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0); end; % gf = gcf; % figure;plot(freqs,pxx); %xx=axis; %axis([phargs(3) phargs(4) xx(3) xx(4)]); %figure(gf); pxx = 10*log10(pxx); n = find(freqs >= phargs(3) & freqs <= phargs(4)); if ~length(n) freq = (phargs(3)+phargs(4))/2; end [dummy maxx] = max(pxx(n)); freq = freqs(n(maxx)); else freq = phargs(3); % else use specified frequency end fprintf('Sorting trials on phase at %.2g Hz.\n',freq); [amps, cohers, cohsig, ampsig, allamps, allphs] = ... phasecoher(data,length(times),srate,freq,cycles,0, ... [], [], timeStretchRef, timeStretchMarks); phwin = phargs(1); [dummy minx] = min(abs(times-phwin)); % closest time to requested winlen = floor(cycles*srate/freq); winloc = minx-linspace(floor(winlen/2), floor(-winlen/2), winlen+1); tmprange = find(winloc>0 & winloc<=frames); winloc = winloc(tmprange); % sorting window times winlocs = winloc; % %%%%%%%%%%%%%%%%%%%% Compute phsamp and phaseangles %%%%%%%%%%%%%%%%%%%% % % $$$ [phaseangles phsamp] = phasedet(data,frames,srate,winloc,freq); phaseangles = allphs(minx,:); phsamp = allamps(minx,:); % $$$ % hist(phaseangles,50); % $$$ % return % $$$ % $$$ % % $$$ % Print facts on commandline %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % $$$ % % $$$ if length(tmprange) ~= winlen+1 % $$$ filtersize = cycles * length(tmprange) / (winlen+1); % $$$ timecenter = median(winloc)/srate*1000+times(1); % center of window in ms % $$$ phaseangles = phaseangles + 2*pi*(timecenter-phargs(1))*freq; % $$$ fprintf('Sorting data epochs by phase at frequency %2.1f Hz: \n', freq); % $$$ fprintf(... % $$$ ' Data time limits reached -> now uses a %1.1f cycles (%1.0f ms) window centered at %1.0f ms\n', ... % $$$ filtersize, 1000/freq*filtersize, timecenter); % $$$ fprintf(... % $$$ ' Filter length is %d; Phase has been linearly interpolated to latency at %1.0f ms.\n', ... % $$$ length(winloc), phargs(1)); % $$$ else % $$$ fprintf(... % $$$ 'Sorting data epochs by phase at %2.1f Hz in a %1.1f-cycle (%1.0f ms) window centered at %1.0f ms.\n',... % $$$ freq,cycles,1000/freq*cycles,times(minx)); % $$$ fprintf('Phase is computed using a wavelet of %d frames.\n',length(winloc)); % $$$ end; % % Reject small (or large) phsamp trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % phargs(2) = phargs(2)/100; % convert rejection rate from % to fraction amprej = phargs(2); [tmp ampsortidx] = sort(phsamp); % sort amplitudes if amprej>=0 ampsortidx = ampsortidx(ceil(amprej*length(ampsortidx))+1:end); % if amprej==0, select all trials fprintf('Retaining %d epochs (%g percent) with largest power at the analysis frequency,\n',... length(ampsortidx),100*(1-amprej)); else % amprej < 0 amprej = 1+amprej; % subtract from end ampsortidx = ampsortidx(1:floor(amprej*length(ampsortidx))); fprintf('Retaining %d epochs (%g percent) with smallest power at the analysis frequency,\n',... length(ampsortidx),amprej*100); end % % Remove low|high-amplitude trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % data = data(:,ampsortidx); % amp-sort the data, removing rejected-amp trials phsamp = phsamp(ampsortidx); % amp-sort the amps phaseangles = phaseangles(ampsortidx); % amp-sort the phaseangles sortvar = sortvar(ampsortidx); % amp-sort the trial indices ntrials = length(ampsortidx); % number of trials retained if ~isempty(auxvar) auxvar = auxvar(:,ampsortidx); end if ~isempty(timeStretchMarks) timeStretchMarks = timeStretchMarks(:,ampsortidx); end % % Sort remaining data by phase angle %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % phaseangles = -phaseangles; topphase = (topphase/360)*2*pi; % convert from degrees to radians ip = find(phaseangles>topphase); phaseangles(ip) = phaseangles(ip)-2*pi; % rotate so topphase at top of plot [phaseangles sortidx] = sort(phaseangles); % sort trials on (rotated) phase data = data(:,sortidx); % sort data by phase phsamp = phsamp(sortidx); % sort amps by phase sortvar = sortvar(sortidx); % sort input sortvar by phase if ~isempty(auxvar) auxvar = auxvar(:,sortidx); end if ~isempty(timeStretchMarks) timeStretchMarks = timeStretchMarks(:,sortidx); end phaseangles = -phaseangles; % Note: phsangles now descend from pi % TEST auxvar = 360 + (1000/256)*(256/5)*phaseangles/(2*pi); % plot phase+360 in ms for test fprintf('Size of data = [%d,%d]\n',size(data,1),size(data,2)); sortidx = ampsortidx(sortidx); % return original trial indices in final sorted order % % %%%%%%%%%%%%%%% Sort data by amplitude %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % elseif exist('ampargs') == 1 % if amplitude-sort if length(ampargs) == 4 % find max frequency in specified band if exist('psd') == 2 fprintf('Computing data spectrum using psd().\n'); [pxx,freqs] = psd(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0); else fprintf('Computing data spectrum using spec().\n'); [pxx,freqs] = spec(data(:),max(1024, pow2(ceil(log2(frames)))),srate,frames,0); end; pxx = 10*log10(pxx); if ampargs(3) == ampargs(4) [freq n] = min(abs(freqs - ampargs(3))); else n = find(freqs >= abs(ampargs(3)) & freqs <= abs(ampargs(4))); end; if ~length(n) freq = mean([abs(ampargs(3)),abs(ampargs(4))]); end if ampargs(3)>=0 [dummy maxx] = max(pxx(n)); freq = freqs(n(maxx)); % use the highest-power frequency else freq = freqs(n); % use all frequencies in the specified range end else freq = abs(ampargs(3)); % else use specified frequency end if length(freq) == 1 fprintf('Sorting data epochs by amplitude at frequency %2.1f Hz \n', freq); else fprintf('Sorting data epochs by amplitude at %d frequencies (%2.1f Hz to %.1f Hz) \n',... length(freq),freq(1),freq(end)); end SPECWININCR = 10; % make spectral sorting time windows increment by 10 ms if isinf(ampargs(1)) ampwins = sortwinarg(1):SPECWININCR:sortwinarg(2); else ampwins = ampargs(1); end if ~isinf(ampargs(1)) % single time given if length(freq) == 1 fprintf(' in a %1.1f-cycle (%1.0f ms) time window centered at %1.0f ms.\n',... cycles,1000/freq(1)*cycles,ampargs(1)); else fprintf(' in %1.1f-cycle (%1.0f-%1.0f ms) time windows centered at %1.0f ms.\n',... cycles,1000/freq(1)*cycles,1000/freq(end)*cycles,ampargs(1)); end else % range of times [dummy sortwin_st ] = min(abs(times-ampwins(1))); [dummy sortwin_end] = min(abs(times-ampwins(end))); if length(freq) == 1 fprintf(' in %d %1.1f-cycle (%1.0f ms) time windows centered from %1.0f to %1.0f ms.\n',... length(ampwins),cycles,1000/freq(1)*cycles,times(sortwin_st),times(sortwin_end)); else fprintf(' in %d %1.1f-cycle (%1.0f-%1.0f ms) time windows centered from %1.0f to %1.0f ms.\n',... length(ampwins),cycles,1000/freq(1)*cycles,1000/freq(end)*cycles,times(sortwin_st),times(sortwin_end)); end end phsamps = 0; %%%%%%%%%%%%%%%%%%%%%%%%%% sort by (mean) amplitude %%%%%%%%%%%%%%%%%%%%%%%%%% minxs = []; for f = 1:length(freq) % use one or range of frequencies frq = freq(f); [amps, cohers, cohsig, ampsig, allamps, allphs] = ... phasecoher(data,length(times),srate,frq,cycles,0, ... [], [], timeStretchRef, timeStretchMarks); for ampwin = ampwins [dummy minx] = min(abs(times-ampwin)); % find nearest time point to requested minxs = [minxs minx]; winlen = floor(cycles*srate/frq); % winloc = minx-[winlen:-1:0]; % ending time version winloc = minx-linspace(floor(winlen/2), floor(-winlen/2), winlen+1); tmprange = find(winloc>0 & winloc<=frames); winloc = winloc(tmprange); % sorting window frames if f==1 winlocs = [winlocs;winloc]; % store tme windows end % $$$ [phaseangles phsamp] = phasedet(data,frames,srate,winloc,frq); % $$$ phsamps = phsamps+phsamps; % accumulate amplitudes across 'sortwin' phaseangles = allphs(minx,:); phsamps = phsamps+allamps(minx,:); % accumulate amplitudes across 'sortwin' end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if length(tmprange) ~= winlen+1 % ????????? filtersize = cycles * length(tmprange) / (winlen+1); timecenter = median(winloc)/srate*1000+times(1); % center of window in ms phaseangles = phaseangles + 2*pi*(timecenter-ampargs(1))*freq(end); fprintf(... ' Data time limits reached -> now uses a %1.1f cycles (%1.0f ms) window centered at %1.0f ms\n', ... filtersize, 1000/freq(1)*filtersize, timecenter); fprintf(... ' Wavelet length is %d; Phase has been linearly interpolated to latency et %1.0f ms.\n', ... length(winloc(1,:)), ampargs(1)); end if length(freq) == 1 fprintf('Amplitudes are computed using a wavelet of %d frames.\n',length(winloc(1,:))); end % % Reject small (or large) phsamp trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ampargs(2) = ampargs(2)/100; % convert rejection rate from % to fraction [tmp n] = sort(phsamps); % sort amplitudes if ampargs(2)>=0 n = n(ceil(ampargs(2)*length(n))+1:end); % if rej 0, select all trials fprintf('Retaining %d epochs (%g percent) with largest power at the analysis frequency,\n',... length(n),100*(1-ampargs(2))); else % ampargs(2) < 0 ampargs(2) = 1+ampargs(2); % subtract from end n = n(1:floor(ampargs(2)*length(n))); fprintf(... 'Retaining %d epochs (%g percent) with smallest power at the analysis frequency,\n',... length(n),ampargs(2)*100); end % % Remove low|high-amplitude trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % data = data(:,n); % amp-sort the data, removing rejected-amp trials phsamps = phsamps(n); % amp-sort the amps phaseangles = phaseangles(n); % amp-sort the phaseangles sortvar = sortvar(n); % amp-sort the trial indices ntrials = length(n); % number of trials retained if ~isempty(auxvar) auxvar = auxvar(:,n); end % % Sort remaining data by amplitude %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % [phsamps sortidx] = sort(phsamps); % sort trials on amplitude data = data(:,sortidx); % sort data by amp phaseangles = phaseangles(sortidx); % sort angles by amp sortvar = sortvar(sortidx); % sort input sortvar by amp if ~isempty(auxvar) auxvar = auxvar(:,sortidx); end fprintf('Size of data = [%d,%d]\n',size(data,1),size(data,2)); sortidx = n(sortidx); % return original trial indices in final sorted order % %%%%%%%%%%%%%%%%%%%%%% Don't Sort trials %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % elseif Nosort == YES fprintf('Not sorting data on input sortvar.\n'); sortidx = 1:ntrials; % %%%%%%%%%%%%%%%%%%%%%% Sort trials on (mean) value %%%%%%%%%%%%%%%%%%%%%%%%%%%% % elseif exist('valargs') [sttime stframe] = min(abs(times-valargs(1))); sttime = times(stframe); if length(valargs)>1 [endtime endframe] = min(abs(times-valargs(2))); endtime = times(endframe); else endframe = stframe; endtime = times(endframe); end if length(valargs)==1 || sttime == endtime fprintf('Sorting data on value at time %4.0f ms.\n',sttime); elseif length(valargs)>1 fprintf('Sorting data on mean value between %4.0f and %4.0f ms.\n',... sttime,endtime); end if endframe>stframe sortval = mean(data(stframe:endframe,:)); else sortval = data(stframe,:); end [sortval,sortidx] = sort(sortval); if length(valargs)>2 if valargs(3) <0 sortidx = sortidx(end:-1:1); % plot largest values on top % if direction < 0 end end data = data(:,sortidx); sortvar = sortvar(sortidx); % sort input sortvar by amp if ~isempty(auxvar) auxvar = auxvar(:,sortidx); end if ~isempty(phaseangles) phaseangles = phaseangles(sortidx); % sort angles by amp end winloc = [stframe,endframe]; winlocs = winloc; % %%%%%%%%%%%%%%%%%%%%%% Sort trials on sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % else fprintf('Sorting data on input sortvar.\n'); [sortvar,sortidx] = sort(sortvar); data = data(:,sortidx); if ~isempty(auxvar) auxvar = auxvar(:,sortidx); end uni_svar=unique_bc(sortvar); n_ties=0; tie_dist=zeros(1,length(uni_svar)); loop_ct=0; for tie_loop=uni_svar, ids=find(sortvar==tie_loop); n_ids=length(ids); if n_ids>1, if replace_ties==YES, mn=mean(data(:,ids),2); data(:,ids)=repmat(mn,1,n_ids); if ~isempty(auxvar) mn=mean(auxvar(:,ids),2); auxvar(:,ids) = repmat(mn,1,n_ids); end end n_ties=n_ties+n_ids; loop_ct=loop_ct+1; tie_dist(loop_ct)=n_ids; end end fprintf('%.2f%c of the trials (i.e., %d out of %d) have the same sortvar value as at least one other trial.\n', ... 100*n_ties/length(sortvar),37,n_ties,length(sortvar)); fprintf('Distribution of number ties per unique value of sortvar:\n'); if exist('prctile') try fprintf('Min: %d, 25th ptile: %d, Median: %d, 75th ptile: %d, Max: %d\n',min(tie_dist),round(prctile(tie_dist,25)), ... round(median(tie_dist)),round(prctile(tie_dist,75)),max(tie_dist)); catch end; end; if replace_ties==YES, fprintf('Trials with tied sorting values will be replaced by their mean.\n'); end fprintf('\n'); end %if max(sortvar)<0 % fprintf('Changing the sign of sortvar: making it positive.\n'); % sortvar = -sortvar; %end % %% %%%%%%%%%%%%%%%%% Adjust decfactor if phargs or ampargs %%%%%%%%%%%%%%%%%%%%% % if decfactor < 0 decfactor = -decfactor; invdec = 1; else invdec = 0; end; if decfactor > sqrt(ntrials) % if large, output this many trials n = 1:ntrials; if exist('phargs') & length(phargs)>1 if phargs(2)>0 n = n(ceil(phargs(2)*ntrials)+1:end); % trials after rejection elseif phargs(2)<0 n = n(1:floor(phargs(2)*length(n))); % trials after rejection end elseif exist('ampargs') & length(ampargs)>1 if ampargs(2)>0 n = n(ceil(ampargs(2)*ntrials)+1:end); % trials after rejection elseif ampargs(2)<0 n = n(1:floor(ampargs(2)*length(n))); % trials after rejection end end if invdec decfactor = (length(n)-avewidth)/decfactor; else decfactor = length(n)/decfactor; end; end if ~isreal(decfactor), decfactor = imag(decfactor); end; % %% %%%%%%%%%%%%%%%% Smooth data using moving average %%%%%%%%%%%%%%%%%%%%%%%%%%% % urdata = data; % save data to compute amp, coher on unsmoothed data if ~Allampsflag & ~exist('data2') % if imaging potential, if length(timeStretchRef) > 0 & length(timeStretchMarks) > 0 % % Perform time-stretching here -JH %%%%%%%%%%%%%%%% % for t=1:size(data,2) M = timewarp(timeStretchMarks(t,:)', timeStretchRef'); data(:,t) = M*data(:,t); end end tsurdata = data; % Time-stretching ends here %%%%%%%%%%%%%% if avewidth > 1 || decfactor > 1 if Nosort == YES fprintf('Smoothing the data using a window width of %g epochs ',avewidth); else fprintf('Smoothing the sorted epochs with a %g-epoch moving window.',... avewidth); end fprintf('\n'); fprintf(' and a decimation factor of %g\n',decfactor); if ~exist('phargs') % if not phase-sorted trials [data,outtrials] = movav(data,1:ntrials,avewidth,decfactor,[],[],wt_wind); % Note: movav() here sorts using square window [outsort,outtrials] = movav(sortvar,1:ntrials,avewidth,decfactor,[],[],wt_wind); else % if phase-sorted trials, use circular / wrap-around smoothing backhalf = floor(avewidth/2); fronthalf = floor((avewidth-1)/2); if avewidth > 2 [data,outtrials] = movav([data(:,[(end-backhalf+1):end]),... data,... data(:,[1:fronthalf])],... [1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind); [outsort,outtrials] = movav([sortvar((end-backhalf+1):end),... sortvar,... sortvar(1:fronthalf)],... 1:(ntrials+backhalf+fronthalf),avewidth,decfactor,[],[],wt_wind); % Shift elements of outtrials so the first element is 1 outtrials = outtrials - outtrials(1) + 1; else % avewidth==2 [data,outtrials] = movav([data(:,end),data],... [1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind); % Note: movav() here sorts using square window [outsort,outtrials] = movav([sortvar(end) sortvar],... 1:(ntrials+1),avewidth,decfactor,[],[],wt_wind); % Shift elements of outtrials so the first element is 1 outtrials = outtrials - outtrials(1) + 1; end end for index=1:length(percentiles) outpercent{index} = compute_percentile( sortvar, percentiles(index), outtrials, avewidth); end; if ~isempty(auxvar) if ~exist('phargs') % if not phase-sorted trials [auxvar,tmp] = movav(auxvar,1:ntrials,avewidth,decfactor,[],[],wt_wind); else % if phase-sorted trials if avewidth>2 [auxvar,tmp] = movav([auxvar(:,[(end-backhalf+1):end]),... auxvar,... auxvar(:,[1:fronthalf])],... [1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind); % Shift elements of tmp so the first element is 1 tmp = tmp - tmp(1) + 1; else % avewidth==2 [auxvar,tmp] = movav([auxvar(:,end),auxvar],[1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind); % Shift elements of tmp so the first element is 1 tmp = tmp - tmp(1) + 1; end end end % if ~isempty(sortvar_limits), % fprintf('Output data will be %d frames by %d smoothed trials.\n',... % frames,length(outtrials)); % fprintf('Outtrials: %3.2f to %4.2f\n',min(outtrials),max(outtrials)); % end else % don't smooth outtrials = 1:ntrials; outsort = sortvar; end % %%%%%%%%%%%%%%%%%%%%%%%%% Find color axis limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty(Caxis) mindat = Caxis(1); maxdat = Caxis(2); fprintf('Using the specified caxis range of [%g,%g].\n', mindat, maxdat); else mindat = min(min(data)); maxdat = max(max(data)); maxdat = max(abs([mindat maxdat])); % make symmetrical about 0 mindat = -maxdat; if ~isempty(caxfraction) adjmax = (1-caxfraction)/2*(maxdat-mindat); mindat = mindat+adjmax; maxdat = maxdat-adjmax; fprintf(... 'The caxis range will be %g times the sym. abs. data range -> [%g,%g].\n',... caxfraction,mindat,maxdat); else fprintf(... 'The caxis range will be the sym. abs. data range -> [%g,%g].\n',... mindat,maxdat); end end end % if ~Allampsflag & ~exist('data2') % %% %%%%%%%%%%%%%%%%%%%%%%%% Set time limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isnan(timelimits(1)) timelimits = [min(times) max(times)]; end fprintf('Data will be plotted between %g and %g ms.\n',timelimits(1),timelimits(2)); % %% %%%%%%%%%%% Image the aligned/sorted/smoothed data %%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(NoShow, 'no') if ~any(isnan(coherfreq)) % if plot three time axes image_loy = 3*PLOT_HEIGHT; elseif Erpflag == YES % elseif if plot only one time axes image_loy = 1*PLOT_HEIGHT; else % else plot erp-image only image_loy = 0*PLOT_HEIGHT; end gcapos=get(gca,'Position'); delete(gca) if isempty(topomap) image_top = 1; else image_top = 0.9; end ax1=axes('Position',... [gcapos(1) gcapos(2)+image_loy*gcapos(4) ... gcapos(3) (image_top-image_loy)*gcapos(4)]); end; ind = isnan(data); % find nan's in data [i j]=find(ind==1); if ~isempty(i) data(i,j) = 0; % plot shifted nan data as 0 (=green) end % %% %%%%%%%%%%% Determine coherence freqeuncy %%%%%%%%%%%%%%%%%%%%%%%%%% % if length(coherfreq) == 2 & coherfreq(1) ~= coherfreq(2) & freq <= 0 % find max frequency in specified band - should use Matlab pwelch()? if exist('psd') == 2 % from Signal Processing Toolbox [pxx,tmpfreq] = psd(urdata(:),max(1024,pow2(ceil(log2(frames)))),srate,frames,0); else % substitute from EEGLAB [pxx,tmpfreq] = spec(urdata(:),max(1024,pow2(ceil(log2(frames)))),srate,frames,0); end; pxx = 10*log10(pxx); n = find(tmpfreq >= coherfreq(1) & tmpfreq <= coherfreq(2)); % [tmpfreq(n) pxx(n)] % coherfreqs = coherfreq; % save for debugging spectrum plotting if ~length(n) coherfreq = coherfreq(1); end [dummy maxx] = max(pxx(n)); coherfreq = tmpfreq(n(maxx)); else coherfreq = coherfreq(1); end if ~Allampsflag & ~exist('data2') %%%%%%%% Plot ERP image %%%%%%%%%% %Stretch the data array % $$$ keyboard; if strcmpi(NoShow, 'no') if TIMEX h_eim=imagesc(times,outtrials,data',[mindat,maxdat]);% plot time on x-axis set(gca,'Ydir','normal'); axis([timelimits(1) timelimits(2) ... min(outtrials) max(outtrials)]); else h_eim=imagesc(outtrials,times,data,[mindat,maxdat]); % plot trials on x-axis axis([min(outtrials) max(outtrials)... timelimits(1) timelimits(2)]); end try colormap(DEFAULT_COLORMAP); catch, end; hold on drawnow end; elseif Allampsflag %%%%%%%%%%%%%%%% Plot allamps instead of data %%%%%%%%%%%%%% if freq > 0 coherfreq = mean(freq); % use phase-sort frequency end if ~isnan(signifs) % plot received significance levels fprintf(['Computing and plotting received ERSP and ITC signif. ' ... 'levels...\n']); [amps,cohers,cohsig,ampsig,allamps] = ... phasecoher(urdata,length(times),srate,coherfreq,cycles,0, ... [], [], timeStretchRef, timeStretchMarks); % Note: need to receive cohsig and ampsig to get allamps <--- ampsig = signifs([1 2]); % assume these already in dB cohsig = signifs(3); elseif alpha>0 % compute significance levels fprintf('Computing and plotting %g ERSP and ITC signif. level...\n',alpha); [amps,cohers,cohsig,ampsig,allamps] = ... phasecoher(urdata,length(times),srate,coherfreq, ... cycles, alpha, [], [], ... timeStretchRef, timeStretchMarks'); % Note: need to receive cohsig and ampsig to get allamps fprintf('Coherence significance level: %g\n',cohsig); else % no plotting of significance [amps,cohers,cohsig,ampsig,allamps] = ... phasecoher(urdata,length(times),srate,coherfreq, ... cycles,0,[], [], timeStretchRef, timeStretchMarks); % Note: need to receive cohsig and ampsig to get allamps end % fprintf('#1 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2)); base = find(times<=DEFAULT_BASELINE_END); if length(base)<2 base = 1:floor(length(times)/4); % default first quarter-epoch end fprintf('Using %g to %g ms as amplitude baseline.\n',... times(1),times(base(end))); % fprintf('#2 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2)); % fprintf('Subtracting the mean baseline log amplitude \n'); %fprintf('Subtracting the mean baseline log amplitude %g\n',baseall); % allamps = allamps./baseall; % fprintf('#3 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2)); if avewidth > 1 || decfactor > 1 if Nosort == YES fprintf(... 'Smoothing the amplitude epochs using a window width of %g epochs ',... avewidth); else % sort trials fprintf(... 'Smoothing the sorted amplitude epochs with a %g-epoch moving window.',... avewidth); end fprintf('\n'); fprintf(' and a decimation factor of %g\n',decfactor); %fprintf('4 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2)); if exist('phargs') % if phase-sorted trials, use circular/wrap-around smoothing backhalf = floor(avewidth/2); fronthalf = floor((avewidth-1)/2); if avewidth > 2 [allamps,outtrials] = movav([allamps(:,[(end-backhalf+1):end]),... allamps,... allamps(:,[1:fronthalf])],... [1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind); % Note: sort using square window [outsort,outtrials] = movav([sortvar((end-backhalf+1):end),... sortvar,... sortvar(1:fronthalf)],... 1:(ntrials+backhalf+fronthalf),avewidth,decfactor,[],[],wt_wind); % Shift elements of outtrials so the first element is 1 outtrials = outtrials - outtrials(1) + 1; if ~isempty(auxvar) [auxvar,tmp] = movav([auxvar(:,[(end-backhalf+1):end]),... auxvar,... auxvar(:,[1:fronthalf])],... [1:(ntrials+backhalf+fronthalf)],avewidth,decfactor,[],[],wt_wind); % Shift elements of outtrials so the first element is 1 outtrials = outtrials - outtrials(1) + 1; end else % avewidth==2 [allamps,outtrials] = movav([allamps(:,end),allamps],... [1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind); % Note: sort using square window [outsort,outtrials] = movav([sortvar(end) sortvar],... 1:(ntrials+1),avewidth,decfactor,[],[],wt_wind); % Shift elements of outtrials so the first element is 1 outtrials = outtrials - outtrials(1) + 1; [auxvar,tmp] = movav([auxvar(:,end),auxvar],[1:(ntrials+1)],avewidth,decfactor,[],[],wt_wind); % Shift elements of tmp so the first element is 1 tmp = tmp - tmp(1) + 1; end else % if trials not phase sorted, no wrap-around [allamps,outtrials] = movav(allamps,1:ntrials,avewidth,decfactor,[],[],wt_wind); %fprintf('5 Size of allamps = [%d %d]\n',size(allamps,1),size(allamps,2)); [outsort,outtrials] = movav(sortvar,1:ntrials,avewidth,decfactor,[],[],wt_wind); if ~isempty(auxvar) [auxvar,tmp] = movav(auxvar,1:ntrials,avewidth,decfactor,[],[],wt_wind); end end for index=1:length(percentiles) outpercent{index} = compute_percentile( sortvar, percentiles(index), outtrials, avewidth); end; fprintf('Output allamps data will be %d frames by %d smoothed trials.\n',... frames,length(outtrials)); else % if no smoothing outtrials = 1:ntrials; outsort = sortvar; end allamps = 20*log10(allamps); % convert allamps to dB amps = 20*log10(amps); % convert latency mean amps to dB ampsig = 20*log10(ampsig); % convert amplitude signif thresholds to dB if alpha>0 fprintf('Amplitude significance levels: [%g %g] dB\n',ampsig(1),ampsig(2)); end if isnan(baseamp) % if not specified in 'limits' [amps,baseamp] = rmbase(amps,length(times),base); % subtract the dB baseline (baseamp) % amps are the means at each latency allamps = allamps - baseamp; % subtract dB baseline from allamps % amplitude ampsig = ampsig - baseamp; % subtract dB baseline from ampsig else % if baseamp specified in 'limits' (as last argument 'basedB', see help) amps = amps-baseamp; % use specified (log) baseamp allamps = allamps - baseamp; % subtract dB baseline if isnan(signifs); ampsig = ampsig-baseamp; % subtract dB baseline end end % %%%%%%%%%%%%%%%%%%%%%%%%% Find color axis limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty(Caxis) mindat = Caxis(1); maxdat = Caxis(2); fprintf('Using the specified caxis range of [%g,%g].\n',... mindat,maxdat); else % Changed -JH % 0.8 is Scott's suggestion to make the erp image show small % variations better maxdat = 0.8 * max(max(abs(allamps))); mindat = -maxdat; % $$$ mindat = min(min(allamps)); % $$$ maxdat = max(max(allamps)); % $$$ maxdat = max(abs([mindat maxdat])); % make symmetrical about 0 % $$$ mindat = -maxdat; if ~isempty(caxfraction) adjmax = (1-caxfraction)/2*(maxdat-mindat); mindat = mindat+adjmax; maxdat = maxdat-adjmax; fprintf(... 'The caxis range will be %g times the sym. abs. data range -> [%g,%g].\n',... caxfraction,mindat,maxdat); else fprintf(... 'The caxis range will be the sym. abs. data range -> [%g,%g].\n',... mindat,maxdat); end end % %%%%%%%%%%%%%%%%%%%%% Image amplitudes at coherfreq %%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(NoShow, 'no') fprintf('Plotting amplitudes at freq %g Hz instead of potentials.\n',coherfreq); if TIMEX imagesc(times,outtrials,allamps',[mindat,maxdat]);% plot time on x-axis set(gca,'Ydir','normal'); axis([timelimits(1) timelimits(2) ... min(outtrials) max(outtrials)]); else imagesc(outtrials,times,allamps,[mindat,maxdat]); % plot trials on x-axis axis([min(outtrials) max(outtrials)... timelimits(1) timelimits(2)]); end try colormap(DEFAULT_COLORMAP); catch, end; drawnow hold on end; data = allamps; elseif exist('data2') %%%%%% Plot allcohers instead of data %%%%%%%%%%%%%%%%%%% %%%%%%%%% UNDOCUMENTED AND DEPRECATED OPTION %%%%%%%%%%%% if freq > 0 coherfreq = mean(freq); % use phase-sort frequency end if alpha>0 fprintf('Computing and plotting %g coherence significance level...\n',alpha); % [amps,cohers,cohsig,ampsig,allcohers] = ... % crosscoher(urdata,data2,length(times),srate,coherfreq,cycles,alpha); fprintf('Inter-Trial Coherence significance level: %g\n',cohsig); fprintf('Amplitude significance levels: [%g %g]\n',ampsig(1),ampsig(2)); else % [amps,cohers,cohsig,ampsig,allcohers] = ... % crosscoher(urdata,data2,length(times),srate,coherfreq,cycles,0); end if ~exist('allcohers') fprintf('\nerpimage(): allcohers not returned....\n') return end allamps = allcohers; % output variable % fprintf('Size allcohers = (%d, %d)\n',size(allcohers,1),size(allcohers,2)); % fprintf('#1 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2)); base = find(times<=0); if length(base)<2 base = 1:floor(length(times)/4); % default first quarter-epoch end amps = 20*(log10(amps) - log10(mean(amps))); % convert to dB %amps = 20*log10(amps); % convert to dB ampsig = 20*(log10(ampsig) - log10(mean(amps))); % convert to dB %ampsig = 20*log10(ampsig); % convert to dB if isnan(baseamp) [amps,baseamp] = rmbase(amps,length(times),base); % remove baseline else amps = amps - baseamp; end % fprintf('#2 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2)); if avewidth > 1 || decfactor > 1 if Nosort == YES fprintf(... 'Smoothing the amplitude epochs using a window width of %g epochs '... ,avewidth); else fprintf(... 'Smoothing the sorted amplitude epochs with a %g-epoch moving window.'... ,avewidth); end fprintf('\n'); fprintf(' and a decimation factor of %g\n',decfactor); % fprintf('4 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2)); [allcohers,outtrials] = movav(allcohers,1:ntrials,avewidth,decfactor,[],[],wt_wind); % fprintf('5 Size of allcohers = [%d %d]\n',size(allcohers,1),size(allcohers,2)); [outsort,outtrials] = movav(sortvar,1:ntrials,avewidth,decfactor,[],[],wt_wind); % fprintf('Output data will be %d frames by %d smoothed trials.\n',... % frames,length(outtrials)); else outtrials = 1:ntrials; outsort = sortvar; end % %%%%%%%%%%%%%%%%%%%%%%%%% Find color axis limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty(Caxis) mindat = Caxis(1); maxdat = Caxis(2); fprintf('Using the specified caxis range of [%g,%g].\n',... mindat,maxdat); else mindat = -1; maxdat = 1 fprintf(... 'The caxis range will be the sym. abs. data range [%g,%g].\n',... mindat,maxdat); end % %%%%%%%%%%%%%%%%%%%%% Image coherences at coherfreq %%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(NoShow, 'no') fprintf('Plotting coherences at freq %g Hz instead of potentials.\n',coherfreq); if TIMEX imagesc(times,outtrials,allcohers',[mindat,maxdat]);% plot time on x-axis set(gca,'Ydir','normal'); axis([timelimits(1) timelimits(2) ... min(outtrials) max(outtrials)]); else imagesc(outtrials,times,allcohers,[mindat,maxdat]); % plot trials on x-axis axis([min(outtrials) max(outtrials)... timelimits(1) timelimits(2)]); end try colormap(DEFAULT_COLORMAP); catch, end; drawnow hold on end; end %Change limits on ERPimage y-axis if requested if ~isempty(sortvar_limits) if exist('phargs','var'), fprintf('********* Warning *********\n'); fprintf('Specifying sorting variable limits has no effect when sorting by phase.\n'); elseif exist('valargs','var'), fprintf('********* Warning *********\n'); fprintf('Specifying sorting variable limits has no effect when sorting by mean EEG voltage.\n'); elseif exist('ampargs','var'), fprintf('********* Warning *********\n'); fprintf('Specifying sorting variable limits has no effect when sorting by frequency amp.\n'); else v=axis; img_mn=find_crspnd_pt(sortvar_limits(1),outsort,outtrials); if isempty(img_mn), img_mn=1; sortvar_limits(1)=outsort(1); end img_mx=find_crspnd_pt(sortvar_limits(2),outsort,outtrials); if isempty(img_mx), img_mx=length(outsort); sortvar_limits(2)=outsort(img_mx); end axis([v(1:2) img_mn img_mx]); id1=find(sortvar>=sortvar_limits(1)); id2=find(sortvar<=sortvar_limits(2)); id=intersect_bc(id1,id2); fprintf('%d epochs fall within sortvar limits.\n',length(id)); urdata=urdata(:,id); if ~isempty(tsurdata), tsurdata=tsurdata(:,id); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%% End plot image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(NoShow, 'no') v=axis; fprintf('Output data will be %d frames by %d smoothed trials.\n',... frames,v(4)-v(3)+1); fprintf('Outtrials: %3.2f to %4.2f\n',v(3),v(4)); end; % %%%%%%%%%%%%%%%%%%%%% Compute y-axis tick values and labels (if requested) %%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(NoShow, 'no') if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials') %make ERPimage y-tick labels in units of sorting variable if isempty(sortvar_limits), mn=min(outsort); mx=max(outsort); else mn=sortvar_limits(1); mx=sortvar_limits(2); end ord=orderofmag(mx-mn); rng_rnd=round([mn mx]/ord)*ord; if isempty(img_ytick_lab) img_ytick_lab=[rng_rnd(1):ord:rng_rnd(2)]; in_range=find((img_ytick_lab>=mn) & (img_ytick_lab<=mx)); img_ytick_lab=img_ytick_lab(in_range); else img_ytick_lab=unique_bc(img_ytick_lab); %make sure it is sorted in_range=find((img_ytick_lab>=mn) & (img_ytick_lab<=mx)); if length(img_ytick_lab)~=length(in_range), fprintf('\n***Warning***\n'); fprintf('''img_trialax_ticks'' exceed smoothed sorting variable values. Max/min values are %f/%f.\n\n',mn,mx); img_ytick_lab=img_ytick_lab(in_range); end end n_tick=length(img_ytick_lab); img_ytick=zeros(1,n_tick); for tickloop=1:n_tick, img_ytick(tickloop)=find_crspnd_pt(img_ytick_lab(tickloop),outsort,outtrials); end elseif ~isempty(img_ylab), %make ERPimage y-tick labels in units of Trials if isempty(img_ytick_lab) v=axis; %note: sorting variable limits have already been used to determine range of ERPimage y-axis mn=v(3); mx=v(4); ord=orderofmag(mx-mn); rng_rnd=round([mn mx]/ord)*ord; img_ytick=[rng_rnd(1):ord:rng_rnd(2)]; in_range=find((img_ytick>=mn) & (img_ytick<=mx)); img_ytick=img_ytick(in_range); else img_ytick=img_ytick_lab; end end end; %% %%%%%%%%%%%%%%%%%%%%%%%%% plot vert lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(verttimes) if size(verttimes,1) ~= 1 & size(verttimes,2) == 1 & size(verttimes,1) ~= ntrials verttimes = verttimes'; end if size(verttimes,1) ~= 1 & size(verttimes,1) ~= ntrials fprintf('\nerpimage(): vert arg matrix must have 1 or %d rows\n',ntrials); return end; if strcmpi(NoShow, 'no') if size(verttimes,1) == 1 fprintf('Plotting %d lines at times: ',size(verttimes,2)); else fprintf('Plotting %d traces starting at times: ',size(verttimes,2)); end for vt = verttimes % for each column fprintf('%g ',vt(1)); if isnan(aligntime) % if NOT re-aligned data if TIMEX % overplot vt on image if length(vt)==1 mydotstyle = DOTSTYLE; if exist('auxcolors') & ... length(verttimes) == length(auxcolors) mydotstyle = auxcolors{find(verttimes == vt)}; end plot([vt vt],[0 max(outtrials)],mydotstyle,'Linewidth',VERTWIDTH); elseif length(vt)==ntrials [outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind); plot(outvt,outtrials,DOTSTYLE,'Linewidth',VERTWIDTH); end else if length(vt)==1 plot([0 max(outtrials)],[vt vt],DOTSTYLE,'Linewidth',VERTWIDTH); elseif length(vt)==ntrials [outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind); plot(outtrials,outvt,DOTSTYLE,'Linewidth',VERTWIDTH); end end else % re-aligned data if TIMEX % overplot vt on image if length(vt)==ntrials [outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind); plot(aligntime+outvt-outsort,outtrials,DOTSTYLE,'LineWidth',VERTWIDTH); elseif length(vt)==1 plot(aligntime+vt-outsort,outtrials,DOTSTYLE,'LineWidth',VERTWIDTH); end else if length(vt)==ntrials [outvt,ix] = movav(vt,1:ntrials,avewidth,decfactor,[],[],wt_wind); plot(outtrials,aligntime+outvt-outsort,DOTSTYLE,'LineWidth',VERTWIDTH); elseif length(vt)==1 plot(outtrials,aligntime+vt-outsort,DOTSTYLE,'LineWidth',VERTWIDTH); end end end end %end fprintf('\n'); end; end % %% %%%%%%%%%%%%%%%%%%%%%%%%% plot horizontal ('horz') lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty(horzepochs) if size(horzepochs,1) > 1 & size(horzepochs,1) > 1 fprintf('\nerpimage(): horz arg must be a vector\n'); return end; if strcmpi(NoShow, 'no') if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials'), %trial axis in units of sorting variable mx=max(outsort); mn=min(outsort); fprintf('Plotting %d lines at epochs corresponding to sorting variable values: ',length(horzepochs)); for he = horzepochs % for each horizontal line fprintf('%g ',he); %find trial number corresponding to this value of sorting %variable: if (he>mn) && (he<mx) he_ep=find_crspnd_pt(he,outsort,outtrials); if TIMEX % overplot he_ep on image plot([timelimits(1) timelimits(2)],[he_ep he_ep],LINESTYLE,'Linewidth',HORZWIDTH); else plot([he_ep he_ep], [timelimits(1) timelimits(2)],LINESTYLE,'Linewidth',HORZWIDTH); end end end else %trial axis in units of trials fprintf('Plotting %d lines at epochs: ',length(horzepochs)); for he = horzepochs % for each horizontal line fprintf('%g ',he); if TIMEX % overplot he on image plot([timelimits(1) timelimits(2)],[he he],LINESTYLE,'Linewidth',HORZWIDTH); else plot([he he], [timelimits(1) timelimits(2)],LINESTYLE,'Linewidth',HORZWIDTH); end end end fprintf('\n'); end; end if strcmpi(NoShow, 'no') set(gca,'FontSize',TICKFONT) hold on; end; % %% %%%%%%%%% plot vertical line at 0 or align time %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(NoShow, 'no') if ~isnan(aligntime) % if trials time-aligned if times(1) <= aligntime & times(frames) >= aligntime plot([aligntime aligntime],[min(outtrials) max(outtrials)],... 'k','Linewidth',ZEROWIDTH); % plot vertical line at time 0 % plot vertical line at aligntime end else % trials not time-aligned if times(1) <= 0 & times(frames) >= 0 plot([0 0],[min(outtrials) max(outtrials)],... 'k','Linewidth',ZEROWIDTH); % plot smoothed sortwvar end end end; if strcmpi(NoShow, 'no') & ( min(outsort) < timelimits(1) ... |max(outsort) > timelimits(2)) ur_outsort = outsort; % store the pre-adjusted values fprintf('Not all sortvar values within time vector limits: \n') fprintf(' outliers will be shown at nearest limit.\n'); i = find(outsort< timelimits(1)); outsort(i) = timelimits(1); i = find(outsort> timelimits(2)); outsort(i) = timelimits(2); end if strcmpi(NoShow, 'no') if TIMEX if Nosort == YES l=ylabel(img_ylab); if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials') set(gca,'ytick',img_ytick,'yticklabel',img_ytick_lab); end else if exist('phargs','var') l=ylabel('Phase-sorted Trials'); elseif exist('ampargs','var') l=ylabel('Amplitude-sorted Trials'); elseif exist('valargs','var') l=ylabel('Voltage-sorted Trials'); else l=ylabel(img_ylab); if ~isempty(img_ylab) set(gca,'ytick',img_ytick); end if ~strcmpi(img_ylab,'Trials') set(gca,'yticklabel',img_ytick_lab); end end end else % if switch x<->y axes if Nosort == YES & NoTimeflag==NO l=xlabel(img_ylab); if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials') set(gca,'xtick',img_ytick,'xticklabel',img_ytick_lab); end else if exist('phargs') l=ylabel('Phase-sorted Trials'); elseif NoTimeflag == NO l=xlabel('Sorted Trials'); else l=xlabel(img_ylab); if ~isempty(img_ylab) && ~strcmpi(img_ylab,'Trials') set(gca,'xtick',img_ytick,'xticklabel',img_ytick_lab); end end end end set(l,'FontSize',LABELFONT); if ~strcmpi(plotmode, 'topo') t=title(titl); set(t,'FontSize',LABELFONT); else NAME_OFFSETX = 0.1; NAME_OFFSETY = 0.2; xx = xlim; xmin = xx(1); xdiff = xx(2)-xx(1); xpos = double(xmin+NAME_OFFSETX*xdiff); yy = ylim; ymax = yy(2); ydiff = yy(2)-yy(1); ypos = double(ymax-NAME_OFFSETY*ydiff); t=text(xpos, ypos,titl); axis off; end; set(gca,'Box','off'); set(gca,'Fontsize',TICKFONT); set(gca,'color',BACKCOLOR); if Erpflag == NO & NoTimeflag == NO if exist('NoTimesPassed')~=1 l=xlabel('Time (ms)'); else l=xlabel('Frames'); end set(l,'Fontsize',LABELFONT); end end; % %% %%%%%%%%%%%%%%%%%% Overplot sortvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(NoShow, 'no') if NoShowVar == YES fprintf('Not overplotting sorted sortvar on data.\n'); elseif isnan(aligntime) % plot sortvar on un-aligned data if Nosort == NO; fprintf('Overplotting sorted sortvar on data.\n'); end hold on; if TIMEX % overplot sortvar plot(outsort,outtrials,'k','LineWidth',SORTWIDTH); else plot(outtrials,outsort,'k','LineWidth',SORTWIDTH); end drawnow else % plot re-aligned zeros on sortvar-aligned data if Nosort == NO; fprintf('Overplotting sorted sortvar on data.\n'); end hold on; if TIMEX % overplot re-aligned 0 time on image plot([aligntime aligntime],[min(outtrials) max(outtrials)],... 'k','LineWidth',SORTWIDTH); else plot([[min(outtrials) max(outtrials)],aligntime aligntime],... 'k','LineWidth',SORTWIDTH); end fprintf('Overplotting realigned times-zero on data.\n'); hold on; if TIMEX % overplot realigned sortvar on image plot(0+aligntime-outsort,outtrials,'k','LineWidth',ZEROWIDTH); else plot(0+outtrials,aligntime-outsort,'k','LineWidth',ZEROWIDTH); end drawnow end end; % %% %%%%%%%%%%%%%%%%%% Overplot auxvar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(NoShow, 'no') if ~isempty(auxvar) fprintf('Overplotting auxvar(s) on data.\n'); hold on; auxtrials = outtrials(:)' ; % make row vector if exist('auxcolors')~=1 % If no auxcolors specified auxcolors = cell(1,size(auxvar,1)); for c=1:size(auxvar,1) auxcolors(c) = {'k'}; % plot auxvars as black trace(s) end end if length(auxcolors) < size(auxvar,1) nauxColors = length(auxcolors); for k=nauxColors+1:size(auxvar,1) auxcolors = { auxcolors{:} auxcolors{1+rem(k-1,nauxColors)}}; end end for c=1:size(auxvar,1) auxcolor = auxcolors{c}; if ~isempty(auxcolor) if isnan(aligntime) % plot auxvar on un-aligned data if TIMEX % overplot auxvar plot(auxvar(c,:)',auxtrials',auxcolor,'LineWidth',SORTWIDTH); else plot(auxtrials',auxvar(c,:)',auxcolor,'LineWidth',SORTWIDTH); end drawnow else % plot re-aligned zeros on sortvar-aligned data if TIMEX % overplot realigned 0-time on image plot(auxvar(c,:)',auxtrials',auxcolor,'LineWidth',ZEROWIDTH); else plot(0+auxtrials',aligntime-auxvar(c,:)',auxcolor,'LineWidth',ZEROWIDTH); end drawnow end % aligntime end % if auxcolor end % c end % auxvar if exist('outpercent') for index = 1:length(outpercent) if isnan(aligntime) % plot auxvar on un-aligned data plot(outpercent{index},outtrials,'k','LineWidth',SORTWIDTH); else plot(aligntime-outpercent{index},outtrials,'k','LineWidth',SORTWIDTH); end; end; end; end; % %% %%%%%%%%%%%%%%%%%%%%%% Plot colorbar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(NoShow, 'no') if Colorbar == YES pos=get(ax1,'Position'); axcb=axes('Position',... [pos(1)+pos(3)+0.02 pos(2) ... 0.03 pos(4)]); cbar(axcb,0,[mindat,maxdat]); % plot colorbar to right of image title(cbar_title); set(axcb,'fontsize',TICKFONT,'xtick',[]); % drawnow axes(ax1); % reset current axes to the erpimage end end; % %% %%%%%%%%%%%%%%%%%%%%% Compute ERP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % erp = []; if Erpflag == YES if exist('erpalpha') if erp_ptiles>1, fprintf(['\nOnly plotting one ERP (i.e., not plotting ERPs from %d percentile splits) ' ... 'because ''erpalpha'' option was chosen. You can''t plot both.\n\n'],erp_ptiles) end [erp erpsig] = nan_mean(fastif(length(tsurdata) > 0, tsurdata',urdata'), ... erpalpha); fprintf(' Mean ERP (p<%g) significance threshold: +/-%g\n', ... erpalpha,mean(erpsig)); else %potentially make ERPs of 50%, 33%, or 25% split of trials n_trials=size(urdata,2); trials_step=round(n_trials/erp_ptiles); erp=zeros(erp_ptiles,size(urdata,1)); for ploop=1:erp_ptiles, ptile_trials=[1:trials_step]+(ploop-1)*trials_step; if max(ptile_trials)>n_trials, ptile_trials=ptile_trials(1):n_trials; end if length(tsurdata) > 0 erp(ploop,:) = nan_mean(tsurdata(:,ptile_trials)'); else erp(ploop,:) = nan_mean(urdata(:,ptile_trials)'); end; end % else %orig line %[erp] = nan_mean(fastif(length(tsurdata) > 0, tsurdata', urdata')); %end end % compute average ERP, ignoring nan's end; if Erpflag == YES & strcmpi(NoShow, 'no') axes(ax1); % reset current axes to the erpimage xtick = get(ax1,'Xtick'); % remember x-axis tick locations xticklabel = get(ax1,'Xticklabel'); % remember x-axis tick locations set(ax1, 'xticklabel', []); widthxticklabel = size(xticklabel,2); xticklabel = cellstr(xticklabel); for tmpindex = 1:length(xticklabel) if length(xticklabel{tmpindex}) < widthxticklabel spaces = char(ones(1,ceil((widthxticklabel-length(xticklabel{tmpindex}))/2) )*32); xticklabel{tmpindex} = [spaces xticklabel{tmpindex}]; end; end; xticklabel = strvcat(xticklabel); if Erpstdflag == YES stdev = nan_std(urdata'); end; % %%%%%% Plot ERP time series below image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isnan(maxerp) fac = 10; maxerp = 0; while maxerp == 0 maxerp = round(fac*YEXPAND*max(erp))/fac; % minimal decimal places fac = 10*fac; end if Erpstdflag == YES fac = fac/10; maxerp = max(maxerp, round(fac*YEXPAND*max(erp+stdev))/fac); end; if ~isempty(erpsig) erpsig = [erpsig;-1*erpsig]; maxerp = max(maxerp, round(fac*YEXPAND*max(erpsig))/fac); end maxerp=max(maxerp); end if isnan(minerp) fac = 1; minerp = 0; while minerp == 0 minerp = round(fac*YEXPAND*min(erp))/fac; % minimal decimal places fac = 10*fac; end if Erpstdflag == YES fac = fac/10; minerp = min(minerp, round(fac*YEXPAND*min(erp-stdev))/fac); end; if ~isempty(erpsig) minerp = min(minerp, round(fac*YEXPAND*min(erpsig))/fac); end minerp=min(minerp); end limit = [timelimits(1:2) minerp maxerp]; if ~isnan(coherfreq) set(ax1,'Xticklabel',[]); % remove tick labels from bottom of image ax2=axes('Position',... [gcapos(1) gcapos(2)+2/3*image_loy*gcapos(4) ... gcapos(3) (image_loy/3-YGAP)*gcapos(4)]); else ax2=axes('Position',... [gcapos(1) gcapos(2) ... gcapos(3) image_loy*gcapos(4)]); end fprintf('Plotting the ERP trace below the ERP image\n'); if Erpstdflag == YES if Showwin tmph = plot1trace(ax2,times,erp,limit,[],stdev,times(winlocs),erp_grid,erp_vltg_ticks); % plot ERP +/-stdev else tmph = plot1trace(ax2,times,erp,limit, [], stdev,[],erp_grid,erp_vltg_ticks); % plot ERP +/-stdev end elseif ~isempty('erpsig') if Showwin tmph = plot1trace(ax2,times,erp,limit,erpsig,[],times(winlocs),erp_grid,erp_vltg_ticks); % plot ERP and 0+/-alpha threshold else tmph = plot1trace(ax2,times,erp,limit,erpsig,[],[],erp_grid,erp_vltg_ticks); % plot ERP and 0+/-alpha threshold end else % plot ERP alone - no significance or std dev plotted if Showwin tmph = plot1trace(ax2,times,erp,limit,[],[],times(winlocs),erp_grid,erp_vltg_ticks); % plot ERP alone else tmph = plot1trace(ax2,times,erp,limit,[],[],[],erp_grid,erp_vltg_ticks); % plot ERP alone end end; if ~isnan(aligntime) line([aligntime aligntime],[limit(3:4)*1.1],'Color','k','LineWidth',ZEROWIDTH); % x=median sort value line([0 0],[limit(3:4)*1.1],'Color','k','LineWidth',ZEROWIDTH); % x=median sort value % remove y axis if length(tmph) > 1 delete(tmph(end)); end; end set(ax2,'Xtick',xtick); % use same Xticks as erpimage above if ~isnan(coherfreq) set(ax2,'Xticklabel',[]); % remove tick labels from ERP x-axis else % bottom axis set(ax2,'Xticklabel',xticklabel); % add ticklabels to ERP x-axis end if isnan(coherfreq) % if no amp and coher plots below . . . if TIMEX & NoTimeflag == NO if exist('NoTimesPassed')~=1 l=xlabel('Time (ms)'); else l=xlabel('Frames'); end set(l,'FontSize',LABELFONT); % $$$ else % $$$ if exist('NoTimesPassed')~=1 % $$$ l=ylabel('Time (ms)'); % $$$ else % $$$ l=ylabel('Frames'); % $$$ end % $$$ set(l,'FontSize',LABELFONT); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% plot vert lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(verttimes) if size(verttimes,1) == ntrials vts=sort(verttimes); vts = vts(ceil(ntrials/2),:); % plot median verttimes values if a matrix else vts = verttimes(:)'; % make verttimes a row vector end for vt = vts if isnan(aligntime) if TIMEX % overplot vt on ERP mydotstyle = DOTSTYLE; if exist('auxcolors') & ... length(verttimes) == length(verttimesColors) mydotstyle = verttimesColors{find(verttimes == vt)}; end plot([vt vt],[limit(3:4)],mydotstyle,'Linewidth',VERTWIDTH); else plot([min(outtrials) max(outtrials)],[limit(3:4)],DOTSTYLE,... 'Linewidth',VERTWIDTH); end else if TIMEX % overplot realigned vt on ERP plot(repmat(median(aligntime+vt-outsort),1,2),[limit(3),limit(4)],... DOTSTYLE,'LineWidth',VERTWIDTH); else plot([limit(3),limit(4)],repmat(median(aligntime+vt-outsort),1,2),... DOTSTYLE,'LineWidth',VERTWIDTH); end end end end limit = double(limit); ydelta = double(1/10*(limit(2)-limit(1))); ytextoffset = double(limit(1)-1.1*ydelta); ynumoffset = double(limit(1)-0.3*ydelta); % double for Matlab 7 %Far left axis max and min labels not needed now that there are tick %marks %t=text(ynumoffset,0.7*limit(3), num2str(limit(3))); %set(t,'HorizontalAlignment','right','FontSize',TICKFONT) %t=text(ynumoffset,0.7*limit(4), num2str(limit(4))); %set(t,'HorizontalAlignment','right','FontSize',TICKFONT) ynum = 0.7*(limit(3)+limit(4))/2; t=text(ytextoffset,ynum,yerplabel,'Rotation',90); set(t,'HorizontalAlignment','center','FontSize',LABELFONT) if ~exist('YDIR') error('\nerpimage(): Default YDIR not read from ''icadefs.m'''); end if YDIR == 1 set(ax2,'ydir','normal') else set(ax2,'ydir','reverse') end set(ax2,'Fontsize',TICKFONT); set(ax2,'Box','off','color',BACKCOLOR); drawnow end % %% %%%%%%%%%%%%%%%%%%% Plot amp, coher time series %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isnan(coherfreq) if freq > 0 coherfreq = mean(freq); % use phase-sort frequency end % %%%%%% Plot amp axis below ERP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~Allampsflag %%%% don't repeat computation if already done for 'allamps' fprintf('Computing and plotting amplitude at %g Hz.\n',coherfreq); if ~isnan(signifs) | Cohsigflag==NO % don't compute or plot signif. levels [amps,cohers] = phasecoher(urdata,size(times,2),srate,coherfreq,cycles); if ~isnan(signifs) ampsig = signifs([1 2]); fprintf('Using supplied amplitude significance levels: [%g,%g]\n',... ampsig(1),ampsig(2)); cohsig = signifs(3); fprintf('Using supplied coherence significance level: %g\n',cohsig); end else % compute amps, cohers with significance fprintf(... 'Computing and plotting %g coherence significance level at %g Hz...\n',... alpha, coherfreq); [amps,cohers,cohsig,ampsig] = ... phasecoher(urdata,size(times,2),srate,coherfreq,cycles,alpha); fprintf('Coherence significance level: %g\n',cohsig); ampsig = 20*log10(ampsig); % convert to dB end amps = 20*log10(amps); % convert to dB if isnan(baseamp) % if baseamp not specified in 'limits' if ~isempty(baselinedb) && isnan(baselinedb(1)) disp('Not removing amplitude baseline'); else if isempty(baselinedb) baselinedb = [times(1) DEFAULT_BASELINE_END]; end; base = find(times >= baselinedb(1) & times<=baselinedb(end)); % use default baseline end point (ms) if length(base)<2 base = 1:floor(length(times)/4); % default first quarter-epoch fprintf('Using %g to %g ms as amplitude baseline.\n',... times(1),times(base(end))); end [amps,baseamp] = rmbase(amps,length(times),base); % remove dB baseline fprintf('Removed baseline amplitude of %d dB for plotting.\n',baseamp); end; else % if 'basedB' specified in 'limits' (in dB) fprintf('Removing specified baseline amplitude of %d dB for plotting.\n',... baseamp); amps = amps-baseamp; % remove specified dB baseline end fprintf('Data amplitude levels: [%g %g] dB\n',min(amps),max(amps)); if alpha>0 % if computed significance levels ampsig = ampsig - baseamp; fprintf('Data amplitude significance levels: [%g %g] dB\n',ampsig(1),ampsig(2)); end end % ~Allampsflag if strcmpi(NoShow, 'no') axis('off') % rm ERP axes axis and labels v=axis; minampERP=v(3); maxampERP=v(4); if ~exist('ynumoffset') limit = [timelimits(1:2) -max(abs([minampERP maxampERP])) max(abs([minampERP maxampERP]))]; limit = double(limit); ydelta = double(1/10*(limit(2)-limit(1))); ytextoffset = double(limit(1)-1.1*ydelta); ynumoffset = double(limit(1)-0.3*ydelta); % double for Matlab 7 end t=text(double(ynumoffset),double(maxampERP),num2str(maxampERP,3)); set(t,'HorizontalAlignment','right','FontSize',TICKFONT); t=text(double(ynumoffset),double(minampERP), num2str(minampERP,3)); set(t,'HorizontalAlignment','right','FontSize',TICKFONT); ax3=axes('Position',... [gcapos(1) gcapos(2)+1/3*image_loy*gcapos(4) ... gcapos(3) (image_loy/3-YGAP)*gcapos(4)]); if isnan(maxamp) % if not specified fac = 1; maxamp = 0; while maxamp == 0 maxamp = floor(YEXPAND*fac*max(amps))/fac; % minimal decimal place fac = 10*fac; end maxamp = maxamp + 10/fac; if Cohsigflag if ampsig(2)>maxamp if ampsig(2)>0 maxamp = 1.01*(ampsig(2)); else maxamp = 0.99*(ampsig(2)); end end end end if isnan(maxamp), maxamp = 0; end % In case the above iteration went on % until fac = Inf and maxamp = NaN again. if isnan(minamp) % if not specified fac = 1; minamp = 0; while minamp == 0 minamp = floor(YEXPAND*fac*max(-amps))/fac; % minimal decimal place fac = 10*fac; end minamp = minamp + 10/fac; minamp = -minamp; if Cohsigflag if ampsig(1)< minamp if ampsig(1)<0 minamp = 1.01*(ampsig(1)); else minamp = 0.99*(ampsig(1)); end end end end if isnan(minamp), minamp = 0; end % In case the above iteration went on % until fac = Inf and minamp = NaN again. fprintf('Plotting the ERSP amplitude trace below the ERP\n'); fprintf('Min, max plotting amplitudes: [%g, %g] dB\n',minamp,maxamp); fprintf(' relative to baseamp: %g dB\n',baseamp); if Cohsigflag ampsiglims = [repmat(ampsig(1)-mean(ampsig),1,length(times))]; ampsiglims = [ampsiglims;-1*ampsiglims]; plot1trace(ax3,times,amps,[timelimits minamp(1) maxamp(1)],ampsiglims,[],[],0); % plot AMP else plot1trace(ax3,times,amps,[timelimits minamp(1) maxamp(1)],[],[],[],0); % plot AMP end if ~isnan(aligntime) line([aligntime aligntime],[minamp(1) maxamp(1)]*1.1,'Color','k'); % x=median sort value end if exist('xtick') % Added -JH set(ax3,'Xtick',xtick); end set(ax3,'Xticklabel',[]); % remove tick labels from bottom of image set(ax3,'Yticklabel',[]); % remove tick labels from left of image set(ax3,'YColor',BACKCOLOR); axis('off'); set(ax3,'Box','off','color',BACKCOLOR); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% plot vert marks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(verttimes) if size(verttimes,1) == ntrials vts=sort(verttimes); vts = vts(ceil(ntrials/2),:); % plot median values if a matrix else vts=verttimes(:)'; end for vt = vts if isnan(aligntime) if TIMEX % overplot vt on amp mydotstyle = DOTSTYLE; if exist('auxcolors') & ... length(verttimes) == length(verttimesColors) mydotstyle = verttimesColors{find(verttimes == vt)}; end plot([vt vt],[minamp(1) maxamp(1)],mydotstyle,... 'Linewidth',VERTWIDTH); else plot([min(outtrials) max(outtrials)],[minamp(1) maxamp(1)], ... DOTSTYLE,... 'Linewidth',VERTWIDTH); end else if TIMEX % overplot realigned vt on amp plot(repmat(median(aligntime+vt-outsort),1,2), ... [minamp(1),maxamp(1)],DOTSTYLE,... 'LineWidth',VERTWIDTH); else plot([minamp,maxamp],repmat(median(aligntime+vt-outsort),1,2), ... DOTSTYLE,... 'LineWidth',VERTWIDTH); end end end end if 0 % Cohsigflag % plot amplitude significance levels hold on plot([timelimits(1) timelimits(2)],[ampsig(1) ampsig(1)] - mean(ampsig),'r',... 'linewidth',SIGNIFWIDTH); plot([timelimits(1) timelimits(2)],[ampsig(2) ampsig(2)] - mean(ampsig),'r',... 'linewidth',SIGNIFWIDTH); end if ~exist('ynumoffset') limit = [timelimits(1:2) -max(abs([minamp maxamp])) max(abs([minamp maxamp]))]; limit = double(limit); ydelta = double(1/10*(limit(2)-limit(1))); ytextoffset = double(limit(1)-1.1*ydelta); ynumoffset = double(limit(1)-0.3*ydelta); % double for Matlab 7 end t=text(ynumoffset,maxamp, num2str(maxamp,3)); set(t,'HorizontalAlignment','right','FontSize',TICKFONT); t=text(ynumoffset,0, num2str(0)); set(t,'HorizontalAlignment','right','FontSize',TICKFONT); t=text(ynumoffset,minamp, num2str(minamp,3)); set(t,'HorizontalAlignment','right','FontSize',TICKFONT); t=text(ytextoffset,(maxamp+minamp)/2,'ERSP','Rotation',90); set(t,'HorizontalAlignment','center','FontSize',LABELFONT); axtmp = axis; dbtxt= text(1/13*(axtmp(2)-axtmp(1))+axtmp(1), ... 11/13*(axtmp(4)-axtmp(3))+axtmp(3), ... [num2str(baseamp,4) ' dB']); set(dbtxt,'fontsize',TICKFONT); drawnow; set(ax3, 'xlim', timelimits); set(ax3, 'ylim', [minamp(1) maxamp(1)]); % %%%%%% Make coher axis below amp %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ax4=axes('Position',... [gcapos(1) gcapos(2) ... gcapos(3) (image_loy/3-YGAP)*gcapos(4)]); if isnan(maxcoh) fac = 1; maxcoh = 0; while maxcoh == 0 maxcoh = floor(YEXPAND*fac*max(cohers))/fac; % minimal decimal place fac = 10*fac; end maxcoh = maxcoh + 10/fac; if maxcoh>1 maxcoh=1; % absolute limit end end if isnan(mincoh) mincoh = 0; end fprintf('Plotting the ITC trace below the ERSP\n'); if Cohsigflag % plot coherence significance level cohsiglims = [repmat(cohsig,1,length(times));zeros(1,length(times))]; coh_handle = plot1trace(ax4,times,cohers,[timelimits mincoh maxcoh],cohsiglims,[],[],0); % plot COHER, fill sorting window else coh_handle = plot1trace(ax4,times,cohers,[timelimits mincoh maxcoh],[],[],[],0); % plot COHER end if ~isnan(aligntime) line([aligntime aligntime],[[mincoh maxcoh]*1.1],'Color','k'); % x=median sort value end % set(ax4,'Xticklabel',[]); % remove tick labels from bottom of % image if exist('xtick') set(ax4,'Xtick',xtick); set(ax4,'Xticklabel',xticklabel); end set(ax4,'Ytick',[]); set(ax4,'Yticklabel',[]); % remove tick labels from left of image set(ax4,'YColor',BACKCOLOR); if ~isempty(verttimes) if size(verttimes,1) == ntrials vts=sort(verttimes); vts = vts(ceil(ntrials/2),:); % plot median values if a matrix else vts = verttimes(:)'; % make verttimes a row vector end for vt = vts if isnan(aligntime) if TIMEX % overplot vt on coher mydotstyle = DOTSTYLE; if exist('auxcolors') & ... length(verttimes) == length(verttimesColors) mydotstyle = verttimesColors{find(verttimes == vt)}; end plot([vt vt],[mincoh maxcoh],mydotstyle,'Linewidth',VERTWIDTH); else plot([min(outtrials) max(outtrials)],... [mincoh maxcoh],DOTSTYLE,'Linewidth',VERTWIDTH); end else if TIMEX % overplot realigned vt on coher plot(repmat(median(aligntime+vt-outsort),1,2),... [mincoh,maxcoh],DOTSTYLE,'LineWidth',VERTWIDTH); else plot([mincoh,maxcoh],repmat(median(aligntime+vt-outsort),1,2),... DOTSTYLE,'LineWidth',VERTWIDTH); end end end end t=text(ynumoffset,0, num2str(0)); set(t,'HorizontalAlignment','right','FontSize',TICKFONT); t=text(ynumoffset,maxcoh, num2str(maxcoh)); set(t,'HorizontalAlignment','right','FontSize',TICKFONT); t=text(ytextoffset,maxcoh/2,'ITC','Rotation',90); set(t,'HorizontalAlignment','center','FontSize',LABELFONT); drawnow %if Cohsigflag % plot coherence significance level %hold on %plot([timelimits(1) timelimits(2)],[cohsig cohsig],'r',... %'linewidth',SIGNIFWIDTH); %end set(ax4,'Box','off','color',BACKCOLOR); set(ax4,'Fontsize',TICKFONT); if NoTimeflag==NO if exist('NoTimesPassed')~=1 l=xlabel('Time (ms)'); else l=xlabel('Frames'); end set(l,'Fontsize',LABELFONT); end axtmp = axis; hztxt=text(10/13*(axtmp(2)-axtmp(1))+axtmp(1), ... 8/13*(axtmp(4)-axtmp(3))+axtmp(3), ... [num2str(coherfreq,4) ' Hz']); set(hztxt,'fontsize',TICKFONT); end;% NoShow else amps = []; % null outputs unless coherfreq specified cohers = []; end if VERS >= 8.04 axhndls = {ax1 axcb ax2 ax3 ax4}; else axhndls = [ax1 axcb ax2 ax3 ax4]; end if exist('ur_outsort') outsort = ur_outsort; % restore outsort clipped values, if any end if nargout<1 data = []; % don't spew out data if no args out and no ; end % %% %%%%%%%%%%%%% Plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(topomap)) & strcmpi(NoShow, 'no') h(12)=axes('Position',... [gcapos(1)+0.10*gcapos(3) gcapos(2)+0.92*gcapos(4),... 0.20*gcapos(3) 0.14*gcapos(4)]); % h(12) = subplot('Position',[.10 .86 .20 .14]); fprintf('Plotting a topo map in upper left.\n'); eloc_info.plotrad = []; if length(topomap) == 1 try topoplot(topomap,eloc_file,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', eloc_info); catch fprintf('topoplot() plotting failed.\n'); end; else try topoplot(topomap,eloc_file,'electrodes','off', 'chaninfo', eloc_info); catch fprintf('topoplot() plotting failed.\n'); end; end; axis('square') if VERS >= 8.04 axhndls = {axhndls h(12)}; else axhndls = [axhndls h(12)]; end end % %% %%%%%%%%%%%%% Plot a spectrum %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SPECFONT = 10; if (~isempty(lospecHz)) && strcmpi(NoShow, 'no') h(13)=axes('Position',... [gcapos(1)+0.82*gcapos(3) ... gcapos(2)+0.96*gcapos(4),... 0.15*gcapos(3)*(0.8/gcapos(3))^0.5 ... 0.10*gcapos(4)*(0.8/gcapos(4))^0.5]); % h(13) = subplot('Position',[.75 .88 .15 .10]); fprintf('Plotting the data spectrum in upper right.\n'); winlength = frames; if winlength > 512 for k=2:5 if rem(winlength,k) == 0 break end end winlength = winlength/k; end % [Pxx, Pxxc, F] = PSD(X,NFFT,Fs,WINDOW,NOVERLAP,P) if exist('psd') == 2 [Pxx,F] = psd(reshape(urdata,1,size(urdata,1)*size(urdata,2)),... max(1024,pow2(ceil(log2(frames)))),srate,frames,0,0.05); % [Pxx,F] = psd(reshape(urdata,1,size(urdata,1)*size(urdata,2)),512,srate,winlength,0,0.05); else [Pxx,F] = spec(reshape(urdata,1,size(urdata,1)*size(urdata,2)),... max(1024,pow2(ceil(log2(frames)))),srate,frames,0); % [Pxx,F] = spec(reshape(urdata,1,size(urdata,1)*size(urdata,2)),512,srate,winlength,0); end; plot(F,10*log10(Pxx)); goodfs = find(F>= lospecHz & F <= hispecHz); maxgfs = max(10*log10(Pxx(goodfs))); mingfs = min(10*log10(Pxx(goodfs))); axis('square') axis([lospecHz hispecHz mingfs-1 maxgfs+1]); set(h(13),'Box','off','color',BACKCOLOR); set(h(13),'Fontsize',SPECFONT); set(h(13),'Xscale',SpecAxis); % added 'log' or 'linear' freq axis scaling -SM 5/31/12 l=ylabel('dB'); set(l,'Fontsize',SPECFONT); if ~isnan(coherfreq) hold on; plot([coherfreq,coherfreq],[mingfs maxgfs],'r'); end if VERS >= 8.04 axhndls = {axhndls h(13)}; else axhndls = [axhndls h(13)]; end end % %% %%%%%%%%%%%%% save plotting limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % limits = [min(times) max(times) minerp maxerp minamp maxamp mincoh maxcoh]; limits = [limits baseamp coherfreq]; % add coherfreq to output limits array % %% %%%%%%%%%%%%% turn on axcopy() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(NoShow, 'no') axcopy(gcf); % eegstr = 'img=get(gca,''''children''''); if (strcmp(img(end),''''type''''),''''image''''), img=get(img(end),''''CData''''); times=get(img(end),''''Xdata''''); clf; args = [''''limits'''' '''','''' times(1) '''','''' times(end)]; if exist(''''EEG'''')==1, args = [args '''','''' ''''srate'''' '''','''' EEG.srate]; end eegplot(img,args); end'; % axcopy(gcf,eegstr); end; % returning outsort if exist('outpercent') outsort = { outsort outpercent }; end; fprintf('Done.\n\n'); % %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%% End erpimage() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(NoShow, 'no') axes('position',gcapos); axis off end; warning on; return % %% %%%%%%%%%%%%%%%%% function plot1trace() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function [plot_handle] = plot1trace(ax,times,trace,axlimits,signif,stdev,winlocs,erp_grid,erp_vltg_ticks) %function [plot_handle] = plot1trace(ax,times,trace,axlimits,signif,stdev,winlocs,erp_grid,erp_vltg_ticks) % If signif is [], plot trace +/- stdev % Else if signif, plot trace and signif(1,:)&signif(2,:) fill. % Else, plot trace alone. % If winlocs not [], plot grey back image(s) in sort window % winlocs(1,1)-> winlocs(1,end) (ms) % ... % winlocs(end,1)-> winlocs(end,end) (ms) FILLCOLOR = [.66 .76 1]; WINFILLCOLOR = [.88 .92 1]; ERPDATAWIDTH = 2; ERPZEROWIDTH = 2; axes(ax); if nargin<9, erp_vltg_ticks=[]; %if erp_vltg_ticks is not empty, those will be the ticks used on the y-axis (voltage axis for ERPs) end if ~isempty(winlocs) for k=1:size(winlocs,1) winloc = winlocs(k,:); fillwinx = [winloc winloc(end:-1:1)]; hannwin = makehanning(length(winloc)); hannwin = hannwin./max(hannwin); % make max = 1 hannwin = hannwin(:)'; % make row vector if ~isempty(axlimits) & sum(isnan(axlimits))==0 % fillwiny = [repmat(axlimits(3),1,length(winloc)) repmat(axlimits(4),1,length(winloc))]; fillwiny = [hannwin*axlimits(3) hannwin*axlimits(4)]; else % fillwiny = [repmat(min(trace)*1.1,1,length(winloc)) repmat(max(trace)*1.1,1,length(winloc))]; fillwiny = [hannwin*2*min(trace) hannwin*2*max(trace)]; end fillwh = fill(fillwinx,fillwiny, WINFILLCOLOR); hold on % plot 0+alpha set(fillwh,'edgecolor',WINFILLCOLOR-[.00 .00 0]); % make edges NOT highlighted end end if ~isempty(signif);% (2,times) array giving upper and lower signif limits filltimes = [times times(end:-1:1)]; if size(signif,1) ~=2 | size(signif,2) ~= length(times) fprintf('plot1trace(): signif array must be size (2,frames)\n') return end fillsignif = [signif(1,:) signif(2,end:-1:1)]; fillh = fill(filltimes,fillsignif, FILLCOLOR); hold on % plot 0+alpha set(fillh,'edgecolor',FILLCOLOR-[.02 .02 0]); % make edges slightly highlighted % [plot_handle] = plot(times,signif, 'r','LineWidth',1); hold on % plot 0+alpha % [plot_handle] = plot(times,-1*signif, 'r','LineWidth',1); hold on % plot 0-alpha end if ~isempty(stdev) [st1] = plot(times,trace+stdev, 'r--','LineWidth',1); hold on % plot trace+stdev [st2] = plot(times,trace-stdev, 'r--','LineWidth',1); hold on % plot trace-stdev end %linestyles={'r','m','c','b'}; % 'LineStyle',linestyles{traceloop}); hold on linecolor={[0 0 1],[.25 0 .75],[.75 0 .25],[1 0 0]}; plot_handle=zeros(1,size(trace,1)); for traceloop=1:size(trace,1), [plot_handle(traceloop)] = plot(times,trace(traceloop,:),'LineWidth',ERPDATAWIDTH, ... 'color',linecolor{traceloop}); hold on end %Assume that multiple traces are equally sized divisions of data switch size(trace,1), case 2 legend('Lower 50%','Higher 50%'); case 3 legend('Lowest 33%','Middle 33%','Highest 33%'); case 4 legend('Lowest 25%','2nd Lowest 25%','3rd Lowest 25%','Highest 25%'); end if ~isempty(axlimits) && sum(isnan(axlimits))==0 if axlimits(2)>axlimits(1) && axlimits(4)>axlimits(3) axis([axlimits(1:2) 1.1*axlimits(3:4)]) end l1=line([axlimits(1:2)],[0 0], 'Color','k',... 'linewidth',ERPZEROWIDTH); % y=zero-line timebar=0; l2=line([1 1]*timebar,axlimits(3:4)*1.1,'Color','k',... 'linewidth',ERPZEROWIDTH); % x=zero-line %y-ticks if isempty(erp_vltg_ticks), shrunk_ylimits=axlimits(3:4)*.8; ystep=(shrunk_ylimits(2)-shrunk_ylimits(1))/4; if ystep>1, ystep=round(ystep); else ord=orderofmag(ystep); ystep=round(ystep/ord)*ord; end if (sign(shrunk_ylimits(2))*sign(shrunk_ylimits(1)))==1, %y shrunk_ylimits don't include 0 erp_yticks=shrunk_ylimits(1):ystep:shrunk_ylimits(2); else %y limits include 0 % erp_yticks=0:ystep:shrunk_ylimits(2); %ensures 0 is a tick point % erp_yticks=[erp_yticks [0:-ystep:shrunk_ylimits(1)]]; erp_yticks=0:ystep:axlimits(4); %ensures 0 is a tick point erp_yticks=[erp_yticks [0:-ystep:axlimits(3)]]; end if erp_grid, set(gca,'ytick',unique(erp_yticks),'ygrid','on'); else set(gca,'ytick',unique(erp_yticks)); end else set(gca,'ytick',erp_vltg_ticks); end end %make ERP traces on top kids=get(gca,'children')'; for hndl_loop=plot_handle, id=find(kids==hndl_loop); kids(id)=[]; kids=[hndl_loop kids]; end set(gca,'children',kids'); plot_handle=[plot_handle l1 l2]; % %% %%%%%%%%%%%%%%%%% function phasedet() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % phasedet() - function used in erpimage.m % Constructs a complex filter at frequency freq % function [ang,amp,win] = phasedet(data,frames,srate,nwin,freq) % Typical values: % frames = 768; % srate = 256; % Hz % nwin = [200:300]; % freq = 10; % Hz data = reshape(data,[frames prod(size(data))/frames]); % number of cycles depends on window size % number of cycles automatically reduced if smaller window % Note: as the number of cycles changes, the frequency shifts % a little -- this should be fixed win = exp(2i*pi*freq(:)*[1:length(nwin)]/srate); win = win .* repmat(makehanning(length(nwin))',length(freq),1); %tmp =gcf; figure; plot(real(win)); figure(tmp); %fprintf('ANY NAN ************************* %d\n', any(any(isnan( data(nwin,:))))); tmpdata = data(nwin,:) - repmat(mean(data(nwin,:), 1), [size(data,1) 1]); resp = win * tmpdata; ang = angle(resp); amp = abs(resp); % %% %%%%%%%%%%%% function prctle() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function prctl = prctle(data,pc); % return percentile of a distribution [prows pcols] = size(pc); if prows ~= 1 & pcols ~= 1 error('\nerpimage(): pc must be a scalar or a vector.'); end if any(pc > 100) | any(pc < 0) error('\nerpimage(): pc must be between 0 and 100'); end [i,j] = size(data); sortdata = sort(data); if i==1 | j==1 % if data is a vector i = max(i,j); j = 1; if i == 1, fprintf(' prctle() note: input data is a single scalar!\n') y = data*ones(length(pc),1); % if data is scalar, return it return; end sortdata = sortdata(:); end pt = [0 100*((1:i)-0.5)./i 100]; sortdata = [min(data); sortdata; max(data)]; prctl = interp1(pt,sortdata,pc); % %% %%%%%%%%%%%%%%%%%%%%% function nan_mean() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % nan_mean() - Take the column means of a matrix, ignoring NaN values. % Return significance bounds if alpha (0 < alpha< <1) is given. % function [out, outalpha] = nan_mean(in,alpha) NPERM = 500; intrials = size(in,1); inframes = size(in,2); nans = find(isnan(in)); in(nans) = 0; sums = sum(in); nonnans = ones(size(in)); nonnans(nans) = 0; nonnans = sum(nonnans); nononnans = find(nonnans==0); nonnans(nononnans) = 1; out = sum(in)./nonnans; outalpha = []; if nargin>1 if NPERM < round(3/alpha) NPERM = round(3/alpha); end fprintf('Performing a permuration test using %d permutations to determine ERP significance thresholds... ',NPERM); permerps = zeros(NPERM,inframes); for n=1:NPERM signs = sign(randn(1,intrials)'-0.5); permerps(n,:) = sum(repmat(signs,1,inframes).*in)./nonnans; if ~rem(n,50) fprintf('%d ',n); end end fprintf('\n'); permerps = sort(abs(permerps)); alpha_bnd = floor(2*alpha*NPERM); % two-sided probability threshold outalpha = permerps(end-alpha_bnd,:); end out(nononnans) = NaN; % %% %%%%%%%%%%%%%%%%%%%%% function nan_std() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function out = nan_std(in) nans = find(isnan(in)); in(nans) = 0; nonnans = ones(size(in)); nonnans(nans) = 0; nonnans = sum(nonnans); nononnans = find(nonnans==0); nonnans(nononnans) = 1; out = sqrt((sum(in.^2)-sum(in).^2./nonnans)./(nonnans-1)); out(nononnans) = NaN; % symmetric hanning function function w = makehanning(n) if ~rem(n,2) w = 0.5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = 0.5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end % %% %%%%%%%%%%%%%%%%%%%%% function compute_percentile() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function outpercent = compute_percentile(sortvar, percent, outtrials, winsize); ntrials = length(sortvar); outtrials=round(outtrials); sortvar = [ sortvar sortvar sortvar ]; winvals = [round(-winsize/2):round(winsize/2)]; outpercent = zeros(size(outtrials)); for index = 1:length(outtrials) sortvarval = sortvar(outtrials(index)+ntrials+winvals); sortvarval = sort(sortvarval); outpercent(index) = sortvarval(round((length(winvals)-1)*percent)+1); end; % %% %%%%%%%%%%%%%%%%%%%%% function orderofmag() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function ord=orderofmag(val) %function ord=orderofmag(val) % % Returns the order of magnitude of the value of 'val' in multiples of 10 % (e.g., 10^-1, 10^0, 10^1, 10^2, etc ...) % used for computing erpimage trial axis tick labels as an alternative for % plotting sorting variable val=abs(val); if val>=1 ord=1; val=floor(val/10); while val>=1, ord=ord*10; val=floor(val/10); end return; else ord=1/10; val=val*10; while val<1, ord=ord/10; val=val*10; end return; end % %% %%%%%%%%%%%%%%%%%%%%% function find_crspnd_pt() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function y_pt=find_crspnd_pt(targ,vals,outtrials) %function id=find_crspnd_pt(targ,vals,outtrials) % % Inputs: % targ - desired value of sorting variable % vals - a vector of observed sorting variables (possibly smoothed) % outtrials - a vector of y-axis values corresponding to trials in the % ERPimage (this will just be 1:n_trials if there's no % smoothing) % % Output: % y_pt - y-axis value (in units of trials) corresponding to "targ". % If "targ" matches more than one y-axis pt, the median point is % returned. If "targ" falls between two points, y_pt is linearly % interpolated. % % Note: targ and vals should be in the same units (e.g., milliseconds) %find closest point above abv=find(vals>=targ); if isempty(abv), %point lies outside of vals range, can't interpolate y_pt=[]; return end abv=abv(1); %find closest point below blw=find(vals<=targ); if isempty(blw), %point lies outside of vals range, can't interpolate y_pt=[]; return end blw=blw(end); if (vals(abv)==vals(blw)), %exact match ids=find(vals==targ); y_pt=median(outtrials(ids)); else %interpolate point %lst squares inear regression B=regress([outtrials(abv) outtrials(blw)]',[ones(2,1) [vals(abv) vals(blw)]']); %predict outtrial point from target value y_pt=[1 targ]*B; end