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
convolve.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/convolve.m
1,721
utf_8
9bced09132932ed26fd7caf0d6d760f7
% convolve() - convolve two matrices (normalize by the sum of convolved % elements to compensate for border effects). % % Usage: % >> r = convolve( a, b ); % % Inputs: % a - first input vector % b - second input vector % % Outputs: % r - result of the convolution % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: conv2(), conv() % 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 R = convolve( A, B ) % size of B must be odd % convolve A and B (normalize by the sum of convolved elements) % ------------------------------------------------------------- R = zeros( size(A) ); for index = 1:length(A) sumconvo = 0; for indexB = 1:length(B) indexconvo = indexB-1-round(length(B)/2); indexA = index + indexconvo+1; if indexA > 0 & indexA <= length(A) R(index) = R(index) + B(indexB)*A(indexA); sumconvo = sumconvo + B(indexB); end; end; R(index) = R(index) / sumconvo; end; return;
github
ZijingMao/baselineeegtest-master
textgui.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/textgui.m
6,446
utf_8
d4e6f305686806a2d18faf7a89d49999
% textgui() - make sliding vertical window. This window contain text % with optional function calls at each line. % % Usage: % >> textgui( commandnames, helparray, 'key', 'val' ...); % % Inputs: % commandnames - name of the commands. Either char array or cell % array of char. All style are 'pushbuttons' exept % for empty commands. % helparray - cell array of commands to execute for each menu % (default is empty) % % Optional inputs: % 'title' - window title % 'fontweight' - font weight. Single value or cell array of value for each line. % 'fontsize' - font size. Single value or cell array of value for each line. % 'fontname' - font name. Single value or cell array of value for each line. % 'linesperpage' - number of line per page. Default is 20. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % Example: % textgui({ 'function1' 'function2' }, {'hthelp(''function1'')' []}); % % this function will call a pop_up window with one button on % % 'function1' which will call the help of this function. % % 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 tmp = textgui( textmenu, helparray, varargin); XBORDERS = 0; % pixels TOPORDINATE = 1.09; TOPLINES = 2; if nargin < 1 help textgui; return; end; if nargin <2 helparray = cell(1, length( textmenu )); end; % optional parameters % ------------------- if nargin >2 for i = 1:length(varargin) if iscell(varargin{i}), varargin(i) = { varargin(i) }; end; end; g=struct(varargin{:}); else g = []; end; try, g.title; catch, g.title = ''; end; try, g.fontname; catch, g.fontname = 'courier'; end; try, g.fontsize; catch, g.fontsize = 12; end; try, g.fontweight; catch, g.fontweight = 'normal'; end; try, g.linesperpage; catch, g.linesperpage = 20; end; if isempty( helparray ) helparray = cell(1,200); else tmpcell = cell(1,200); helparray = { helparray{:} tmpcell{:} }; end; % number of elements % ------------------ if iscell(textmenu) nblines = length(textmenu); else nblines = size(textmenu,1); end; % generating the main figure % -------------------------- fig = figure('position', [100 100 800 25*15], 'menubar', 'none', 'numbertitle', 'off', 'name', 'Help', 'color', 'w'); pos = get(gca,'position'); % plot relative to current axes q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]./100; % generating cell arrays % ---------------------- if isstr(g.fontname), tmp1(1:nblines) = {g.fontname}; g.fontname = tmp1; end; if isnumeric(g.fontsize), tmp2(1:nblines) = {g.fontsize}; g.fontsize = tmp2; end; if isstr(g.fontweight), tmp3(1:nblines) = {g.fontweight}; g.fontweight = tmp3; end; switch g.fontname{1} case 'courrier', CHAR_WIDTH = 11; % pixels case 'times', CHAR_WIDTH = 11; % pixels otherwise, CHAR_WIDTH = 11; end; topordi = TOPORDINATE; if ~isempty(g.title) addlines = size(g.title,1)+1+TOPLINES; if nblines+addlines < g.linesperpage divider = g.linesperpage; else divider = nblines+addlines; end; ordinate = topordi-topordi*TOPLINES/divider; currentheight = topordi/divider; for index=1:size(g.title,1) ordinate = topordi-topordi*(TOPLINES+index-1)/divider; h = text( -0.1, ordinate, g.title(index,:), 'unit', 'normalized', 'horizontalalignment', 'left', ... 'fontname', g.fontname{1}, 'fontsize', g.fontsize{1},'fontweight', fastif(index ==1, 'bold', ... 'normal'), 'interpreter', 'none' ); end; %h = uicontrol( gcf, 'unit', 'normalized', 'style', 'text', 'backgroundcolor', get(gcf, 'color'), 'horizontalalignment', 'left', ... % 'position', [-0.1 ordinate 1.1 currentheight].*s*100+q, 'string', g.title, ... % 'fontsize', g.fontsize{1}+1, 'fontweight', 'bold', 'fontname', g.fontname{1}); else addlines = TOPLINES; if nblines+addlines < g.linesperpage divider = g.linesperpage; else divider = nblines+addlines; end; end; maxlen = size(g.title,2); for i=1:nblines if iscell(textmenu) tmptext = textmenu{i}; else tmptext = textmenu(i,:); end; ordinate = topordi-topordi*(i-1+addlines)/divider; currentheight = topordi/divider; if isempty(helparray{i}) h = text( -0.1, ordinate, tmptext, 'unit', 'normalized', 'horizontalalignment', 'left', ... 'fontname', g.fontname{i}, 'fontsize', g.fontsize{i},'fontweight', g.fontweight{i}, 'interpreter', 'none' ); % h = uicontrol( gcf, 'unit', 'normalized', 'style', 'text', 'backgroundcolor', get(gcf, 'color'), 'horizontalalignment', 'left', ... % 'position', [-0.1 ordinate 1.1 currentheight].*s*100+q, 'string', tmptext, 'fontname', g.fontname{i}, 'fontsize', g.fontsize{i},'fontweight', g.fontweight{i} ); else h = text( -0.1, ordinate, tmptext, 'unit', 'normalized', 'color', 'b', 'horizontalalignment', 'left', ... 'fontname', g.fontname{i}, 'buttondownfcn', helparray{i}, 'fontsize', g.fontsize{i},'fontweight', g.fontweight{i}, 'interpreter', 'none' ); % h = uicontrol( gcf, 'callback', helparray{i}, 'unit','normalized', 'style', 'pushbutton', 'horizontalalignment', 'left', ... % 'position', [-0.1 ordinate 1.1 currentheight].*s*100+q, 'string', tmptext, 'fontname', g.fontname{i}, 'fontsize', g.fontsize{i},'fontweight', g.fontweight{i}); end; maxlen = max(maxlen, length(tmptext)); end; pos = get(gcf, 'position'); set(gcf, 'position', [pos(1:2) maxlen*CHAR_WIDTH+2*XBORDERS 400]); % = findobj('parent', gcf); %set(h, 'fontname', 'courier'); if nblines+addlines < g.linesperpage zooming = 1; else zooming = (nblines+addlines)/g.linesperpage; end; slider(gcf, 0, 1, 1, zooming, 0); axis off;
github
ZijingMao/baselineeegtest-master
kmeans_st.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/kmeans_st.m
8,156
utf_8
8dec33b3e9581d7f84c4deb47caa720d
% KMEANS: K-means clustering of n points into k clusters so that the % within-cluster sum of squares is minimized. Based on Algorithm % AS136, which seeks a local optimum such that no movement of a % point from one cluster to another will reduced the within-cluster % sum of squares. Tends to find spherical clusters. % Not globally optimal against all partitions, which is an NP-complete % problem; thus allows for multiple restarts. % % Usage: [centr,clst,sse] = kmeans(X,k,restarts) % % X = [n x p] data matrix. % k = number of desired clusters. % restarts = optional number of restarts, after finding a new minimum % sse, needed to end search [default=0]. % -------------------------------------------------------------------- % centr = [k x p] matrix of cluster centroids. % clst = [n x 1] vector of cluster memberships. % sse = total within-cluster sum of squared deviations. % % Hartigan,JA & MA Wong. 1979. Algorithm AS 136: A k-means clustering % algorithm. Appl. Stat. 200:100-108. % Milligan,G.W. & L. Sokol. 1980. A two-stage clustering algorithm with % robustness recovery characteristics. Educational and Psychological % Measurement 40:755-759. % RE Strauss, 8/26/98 % 8/21/99 - changed misc statements for Matlab v5. % 10/14/00 - use means() rather than mean() to update cluster centers; % remove references to TRUE and FALSE. function [centr,clst,sse] = kmeans_st(X,k,restarts) if (nargin<3) restarts = []; end; if (isempty(restarts)) restarts = 0; end; [n,p] = size(X); if (k<1 | k>n) error('KMEANS: k out of range 1-N'); end; max_iter = 50; highval = 10e8; upgma_flag = 1; % Do UPGMA first time thru % Repeat optimization until have 'restart' attempts with no better solution restart_iter = restarts + 1; best_sse = highval; while (restart_iter > 0) restart_iter = restart_iter - 1; c1 = zeros(n,1); c2 = c1; clst = c1; nclst = zeros(k,1); % Estimate initial cluster centers via UPGMA the first time, and randomly % thereafter. if (upgma_flag) % If UPGMA, upgma_flag = 0; dist = eucl(X); % All interpoint distances topo = upgma(dist,[],0); % UPGMA dendrogram topology grp = [1:n]'; % Identify obs in each of k grps for step = 1:(n-k) t1 = topo(step,1); t2 = topo(step,2); t3 = topo(step,3); indx = find(grp==t1); grp(indx) = t3 * ones(length(indx),1); indx = find(grp==t2); grp(indx) = t3 * ones(length(indx),1); end; grpid = uniquef(grp); % Unique group identifiers centr = zeros(k,p); for kk = 1:length(grpid); % Calculate group centroids g = grpid(kk); indx = find(grp == g); Xk = X(indx,:); if (size(Xk,1)>1) centr(kk,:) = mean(Xk); else centr(kk,:) = Xk; end; end; else % Else if randomized, rndprm = randperm(n); % Pull out random set of points centr = X(rndprm(1:k),:); end; % For each point i, find its two closest centers, c1(i) and c2(i), and % assign it to c1(i) dist = zeros(n,k); for kk = 1:k % Dists to centers of all clusters dist(:,kk) = eucl(X,centr(kk,:)); end; [d,indx] = sort(dist'); % Sort points separately c1 = indx(1,:)'; c2 = indx(2,:)'; % Update cluster centers to be the centroids of points contained within them for kk = 1:k indx = find(c1==kk); len_indx = length(indx); % if (len_indx>1) % centr(kk,:) = mean(X(indx,:)); % else % centr(kk,:) = X(indx,:); % end; centr(kk,:) = means(X(indx,:)); nclst(kk) = len_indx; end; % Initialize working matrices live = ones(k,1); R1 = zeros(n,1); R2 = zeros(k,1); adj1 = nclst ./ (nclst+1); adj2 = nclst ./ (nclst-1+eps); update = n * ones(k,1); for i = 1:n % Adjusted dist from each pt to own cluster center R1(i) = adj2(c1(i)) * eucl(X(i,:),centr(c1(i),:))^2; end; % Iterate iter = 0; while ((iter < max_iter) & (any(live))) iter = iter+1; % Optimal-transfer stage i = 0; while ((i<n) & any(live)) % Cycle thru points i = i+1; update = update-1; % Decrement cluster update counters L1 = c1(i); % Pt i is in cluster L1 if (nclst(L1)>1) % If point i is not sole member of L1, R2 = adj1(L1) .* eucl(centr,X(i,:)).^2; % Dists from pt to cluster centers if (live(L1)) % If L1 is in live set, R2(L1) = highval; % find min R2 over all clusters [r2min,L2] = min(R2); else % If L1 is not in live set, indx = find(~live); % find min R2 over live clusters only R2([L1;indx]) = highval * ones(length(indx)+1,1); [r2min,L2] = min(R2); end; if (r2min >= R1(i)) % No reallocation necessary c2(i) = L2; else % Else reallocate pt to new cluster c1(i) = L2; c2(i) = L1; for kk = [L1,L2] % Recalc cluster centers and sizes indx = find(c1==kk); len_indx = length(indx); if (len_indx>1) centr(kk,:) = mean(X(indx,:)); else centr(kk,:) = X(indx,:); end; nclst(kk) = len_indx; end; adj1([L1,L2]) = nclst([L1,L2]) ./ (nclst([L1,L2])+1); adj2([L1,L2]) = nclst([L1,L2]) ./ (nclst([L1,L2])-1+eps); R1(i) = adj2(c1(i)) * eucl(X(i,:),centr(c1(i),:))^2; live([L1,L2]) = [1,1]; % Put into live set update([L1,L2]) = [n,n]; % Reinitialize update counters end; end; % if nclst(L1)>1 indx = find(update<1); % Remove clusters from live set if (~isempty(indx)) % that haven't been recently updated live(indx) = zeros(length(indx),1); end; end; % while (i<n & any(live)) if (any(live)) % Quick transfer stage for i = 1:n % Cycle thru points L1 = c1(i); L2 = c2(i); if (any(live([L1,L2])) & nclst(L1)>1) R2 = adj1(L2) .* eucl(centr(L2,:),X(i,:)).^2; % Dists from pt to L2 center if (R1>=R2) temp = c1(i); % Switch L1 & L2 c1(i) = c2(i); c2(i) = temp; for kk = [L1,L2] % Recalc cluster centers and sizes indx = find(c1==kk); centr(kk,:) = mean(X(indx,:)); nclst(kk) = length(indx); end; adj1([L1,L2]) = nclst([L1,L2]) ./ (nclst([L1,L2])+1); adj2([L1,L2]) = nclst([L1,L2]) ./ (nclst([L1,L2])-1+eps); R1(i) = adj2(c1(i)) * eucl(X(i,:),centr(c1(i),:))^2; live([L1,L2]) = [1,1]; % Put into live set update([L1,L2]) = [n,n]; % Reinitialize update counters end; end; end; end; % if any(live) end; % while iter<max_iter & any(live) sse = 0; % Calc final total sum-of-squares for i=1:n sse = sse + eucl(X(i,:),centr(c1(i),:))^2; end; if (sse < best_sse) % Update best solution so far best_sse = sse; best_c1 = c1; best_centr = centr; restart_iter = restarts; end; end; % while (restart_iter > 0) clst = best_c1; centr = best_centr; sse = best_sse; return;
github
ZijingMao/baselineeegtest-master
caliper.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/caliper.m
6,421
utf_8
a3602aa087935fa1182c2455a6e8d7ef
% caliper() - Measure a set of spatial components of a given data epoch relative to % a reference epoch and decomposition. % Usage: % >> [amp,window]=caliper(newepoch,refepoch,weights,compnums,filtnums,times,'noplot'); % % Inputs: % newepoch = (nchannels,ntimes) new data epoch % refepoch = a (nchannels,ntimes) reference data epoch % weights = (nchannels,ncomponents) unmixing matrix (e.g., ICA weights*sphere) % compnums = vector of component numbers to return amplitudes for {def|0: all} % filtnums = [srate highpass lowpass] filter limits for refepoch {def|0: allpass} % times = [start_ms end_ms] epoch latency limits, else latencies vector {def|0: 0:EEG.pnts-1} % 'noplot' = produce no plots {default: plots windows for the first <=3 components} % % Outputs: % amps = (1,length(compnums)) vector of mean signed component rms amplitudes % windows = (length(compnums)),length(times)) matrix of tapering windows used % % Notes: % Function caliper() works as follows: First the reference epoch is decomposed using % the given weight matrix (may be ICA, PCA, or etc). Next, the time course of the % main lobe of the activation in the reference epoch (from max to 1st min, forward % and backward in time from abs max, optionally after bandpass filtering) is used % to window the new epoch. Then, the windowed new epoch is decomposed by the same % weight matrix, and signed rms amplitude (across the channels) is returned of the % projection of each of the specified component numbers integrated across the windowed % epoch. If not otherwise specified, plots the windows for the first <= 3 components listed. % % Example: Given a grand mean response epoch and weight matrix, it can be used % to measure amps of grand mean components in single-subject averages. % % Authors: Scott Makeig & Marissa Westerfield, SCCN/INC/UCSD, La Jolla, 11/2000 % Copyright (C) 11/2000 Scott Makeig & Marissa Westerfield,, SCCN/INC/UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % Edit History: % 12/05/00 -- added fig showing data, ref activation, and window vector -mw % 12/19/00 -- adjusted new icaproj() args -sm % 01-25-02 reformated help & license -ad function [amps,windows] = caliper(newepoch,refepoch,weights,compnums,filtnums,times,noplot) if nargin < 3 help caliper return end if nargin<4 compnums = 0; end nchans = size(newepoch,1); ntimes = size(newepoch,2); if compnums(1) == 0 | isempty(compnums(1)) compnums = 1:nchans; end if min(compnums) < 1 | max(compnums) > size(weights,2) help caliper return end if nargin<5 filtnums = []; else if isempty(filtnums) filtnums = []; elseif length(filtnums)==1 & filtnums(1)==0 filtnums = []; elseif length(filtnums) ~= 3 fprintf('\ncaliper(): filter parameters (filtnums) must have length 3.\n') return end end if nargin< 6 | isempty(times) | (length(times)==1 & times(1)==0) times = 0:ntimes-1; else if length(times) ~= ntimes if length(times) ~= 2 fprintf('caliper(): times argument should be [startms endms] or vector.\n') return else times = times(1):(times(2)-times(1))/(ntimes-1):times(2); times = times(1:ntimes); end end end if nargin < 7 noplot = 0; else noplot = 1; end refact = weights(compnums,:)*refepoch; % size (length(compnums),ntimes) newact = weights(compnums,:)*newepoch; if length(filtnums) == 3 if ~exist('eegfilt') fprintf('caliper(): function eegfilt() not found - not filtering refepoch.\n'); else try refact = eegfilt(refact,filtnums(1),filtnums(2),filtnums(3)); catch fprintf('\n%s',lasterr) return end end end if size(weights,1) == size(weights,2) winv = inv(weights); else winv = pinv(weights); end winvrms = sqrt(mean(winv.*winv)); % map rms amplitudes amps = []; windows = []; n = 1; % component index for c=compnums if floor(c) ~= c help caliper fprintf('\ncaliper(): component numbers must be integers.\n') return end [lobemax i] = max(abs(refact(n,:))); f = i+1; oldact = lobemax; while f>0 & f<=ntimes & abs(refact(n,f)) < oldact oldact = abs(refact(n,f)); f = f+1; end % f is now one past end of "main lobe" lobeend = f-1; f = i-1; oldact = lobemax; while f>0 & f<=ntimes & abs(refact(n,f)) < oldact oldact = abs(refact(n,f)); f = f-1; end % f is now one past start of "main lobe" lobestart = f+1; refact(n,1:lobestart) = zeros(1,length(1:lobestart)); refact(n,lobeend:end) = zeros(1,length(lobeend:ntimes)); windows = [windows; refact(n,:)]; refnorm = sum(refact(n,:)); if abs(refnorm)<1e-25 fprintf('caliper(): near-zero activation for component %d - returning NaN amp.\n',c) amps = [amps NaN]; else refact(n,:) = refact(n,:)/refnorm; % make reference epoch window sum to 1 amps = [amps winvrms(c)*sum(refact(n,:).*newact(n,:))]; end n = n+1; if ~noplot & n <= 4 %%% only plot out at most the first 3 components refproj = icaproj(refepoch,weights,c); refproj = env(refproj); windproj = winv(:,c)*(refact(n-1,:)*refnorm); windproj = env(windproj); figure; plot(times,newepoch(2:nchans,:),'g'); hold on;h=plot(times,newepoch(1,:),'g'); hold on;h=plot(times,newepoch(1,:),'g',... times,refproj(1,:),'b',... times,windproj(1,:),'r','LineWidth',2); hold on;plot(times,refproj(2,:),'b',times,windproj(2,:),'r','LineWidth',2); set(h(1),'linewidth',1); legend(h,'new data','comp. act.','window'); title(['Component ',int2str(c),'; rms amplitude = ',num2str(amps(n-1))],... 'FontSize',14); ylabel('Potential (uV)'); end; %% endif end % c
github
ZijingMao/baselineeegtest-master
help2html2.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/help2html2.m
16,616
utf_8
0b84a93365f77c167a0f2096b04d0f30
% help2html() - Convert a Matlab m-file help-message header into an .html help file % % Usage: % >> linktext = help2html( filein, fileout, 'key1', val1, 'key2', val2 ...); % % Inputs: % filein - input filename (with .m extension) % fileout - output filename (if empty, generated automatically) % % Optional inputs: % 'header' - command to insert in the header (i.e. javascript % declaration or meta-tags). {default: none}. % 'footer' - command to insert at the end of the .html file (e.g., % back button). {default: none}. % 'refcall' - syntax to call references. {default: '%s.html'} For % javascript function uses 'javascript:funcname(''%s.js'')' % 'font' - font name % 'background' - background tag (i.e. '<body BACKGROUND="img.jpg">'). % {default: none}. % 'outputlink' - html command text to link to the generated .html page. % Must contain two '%s' symbols to the function title % and to the function link. % Ex: ... href="%s.html" ... {default: standard .html href}. % 'outputtext' - Text used in the outputlink. {default: the function % name} % 'outputonly' - ['on'|'off'] Only generate the linktext {default: 'off'} % % Output: % fileout - .html file written to disk % linktext - html-text link to the output file % % M-file format: % The following lines describe the header format of an m-file function % to allow .html help file generation. Characters '-' and ':' are used % explicitly by the function for parsing. % %% function_name() - description line 1 %% description line 2 %% etc. %% %% Title1: %% descriptor1 - text line 1 %% text line 2 %% descriptor2 - [type] text line 1 %% "descriptor 3" - text line 1 (see notes) %% etc. %% %% Title2: %% text line 1 [...](see notes) %% text line 2 %% %% See also: %% function1(), function2() % % Author: Arnaud Delorme, Salk Institute 2001 % % Notes: 1) The text lines below Title2 are considered as is (i.e., % preserving Matlab carriage returns) unless there is a % Matlab continuation cue ('...'). In this case, lines are % contcatenated. As below 'Title1', all text lines following % each descriptor (i.e., single_word followed by '-' or '=' % or multiple quoted words followed by a '-' or '=') % are concatenated. % 2) The pattern 'function()' is detected and is printed in bold % if it is the first function descriptor. Otherwise, % it is used as a web link to the .html function file % 'function.html' if this exists. % 3) If a 'function.jpg' image file (with same 'function' name) exists, % the image is inserted into the function .html file following % the function description. If the .jpg file is absent, the function % checks for the presence of a .gif file. % 4) Lines beginning by '%%' are not interpreted and will be printed as is. % 5) if [type] is present in a "descriptor2 - [type] text line 1" % type is bolded. % 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 [linktext,allvars,alltext] = help2html( filename, htmlfile, varargin) if nargin < 1 help help2html; return; end; if nargin <3 g = []; else g = struct( varargin{:});; end; try, g.font; catch, g.font = 'Helvetica'; end; g.functionname = [ '<FONT FACE="' g.font '"><FONT SIZE =+2><B>%s</B></FONT></FONT>' ]; g.description = [ '<FONT FACE="' g.font '">%s</FONT>' ]; g.title = [ '<FONT FACE="' g.font '"><FONT SIZE =+1><B>%s</B></FONT></FONT>' ]; g.var = [ '<DIV ALIGN=RIGHT><FONT FACE="' g.font '"><I>%s&nbsp;&nbsp;&nbsp;</I></FONT></DIV>' ]; g.vartext = [ '<FONT FACE="' g.font '">%s</FONT>' ]; g.text = [ '<FONT FACE="' g.font '">%s</FONT>' ]; g.normrow = '<tr VALIGN=TOP NOSAVE>'; g.normcol1 = '<td VALIGN=TOP NOSAVE>'; g.normcol2 = '<td VALIGN=BOTTOM NOSAVE>'; g.doublecol = '<td ALIGN=CENTER COLSPAN="2" NOSAVE>'; g.seefile = [ '<FONT FACE="' g.font '">See the matlab file <A HREF="%s" target="_blank">%s</A> (may require other functions)</FONT><BR><BR>' ]; try, g.outputonly; catch, g.outputonly = 'off'; end; try, g.background; catch, g.background = ''; end; try, g.header; catch, g.header = ''; end; try, g.footer; catch, g.footer = ''; end; try, g.refcall; catch, g.refcall = '%s.html'; end; try, g.outputlink; catch, g.outputlink = [ g.normrow g.normcol1 '<FONT FACE="' g.font '"><A HREF="%s.html">%s.html</A></td>' g.normcol2 '%s</FONT></td></tr>' ]; end; g.footer = [ '<FONT FACE="' g.font '">' g.footer '</FONT>' ]; if nargin < 1 help help2html; return; end; % output file % ----------- if nargin < 2 | isempty(htmlfile); indexdot = findstr( filename, '.'); if isempty(indexdot), indexdot = length(filename)+1; end; htmlfile = [ filename(1:indexdot(end)-1) '.html' ]; else indexdot = findstr( filename, '.'); end; % open files % ---------- fid = fopen( filename, 'r'); if fid == -1 error('Input file not found'); end; if ~strcmp(g.outputonly, 'on') fo = fopen(htmlfile, 'w'); if fo == -1 error('Cannot open output file'); end; % write header % ------------ fprintf(fo, '<HTML><HEAD>%s</HEAD><BODY>\n%s\n<table WIDTH="100%%" NOSAVE>\n', g.header, g.background); 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); else vartext = []; end; varname = []; else % not a title % ------------ % scan lines [tok1 strrm] = mystrtok( str ); [tok2 strrm] = strtok( strrm ); if ~isempty(tok2) & ( tok2 == '-' | tok2 == '=') % new variable newvar = 1; oldvarname = varname; oldvartext = vartext; if ~maindescription varname = formatstr( tok1, g.refcall); else varname = tok1; end; strrm = deblank(strrm); % remove tail blanks strrm = deblank(strrm(end:-1:1)); % remove initial blanks strrm = formatstr( strrm(end:-1:1), g.refcall); 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 ); if isempty(vartext) vartext = str; else if ~isempty(varname) vartext = [ vartext ' ' str]; % espace if in array else if all(vartext( end-2:end) == '.') vartext = [ deblank2(vartext(1:end-3)) ' ' str]; % espace if '...' else vartext = [ vartext '<BR>' 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' ], finalformat(oldvartext)); else if ~isempty(oldvartext) fprintf( fo, [ g.normcol2 g.text '</td></tr>\n' ], finalformat(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; % generate the output command % --------------------------- try, g.outputtext; catch, g.outputtext = ''; end; if isempty(g.outputtext), g.outputtext = filename(1:indexdot(end)-1); end; linktext = sprintf( g.outputlink, g.outputtext, filename(1:indexdot(end)-1), maintext ); if strcmp(g.outputonly, 'on') fclose(fid); return; end; 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 = []; imagename1 = [ htmlfile( 1:findstr( htmlfile, functioname )-1) functioname '.jpg' ]; imagename2 = [ htmlfile( 1:findstr( htmlfile, functioname )-1) functioname '.gif' ]; if exist( imagename2 ), imagename = imagename2; end; if exist( imagename1 ), imagename = imagename1; end; if ~isempty(imagename) % do not make link if the file does not exist imageinfo = imfinfo(imagename); if imageinfo.Width < 600 fprintf(fo, [ g.normrow g.doublecol ... '<CENTER><BR><A HREF="' imagename '" target="_blank"><img SRC=' imagename ... '></A></CENTER></td></tr>' ]); else fprintf(fo, [ g.normrow g.doublecol ... '<CENTER><BR><A HREF="' imagename '" target="_blank"><img SRC=' imagename ... ' width=600></A></CENTER></td></tr>' ]); end; 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' ], finalformat(oldvartext)); else if ~isempty(oldvartext) fprintf( fo, [ g.normcol2 g.text '</td></tr>\n' ], finalformat(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; fprintf( fo, [ '</table>\n<BR>' g.seefile '%s</BODY></HTML>'], lower(filename), filename, g.footer); fclose( fid ); fclose( fo ); 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; % final formating function str = finalformat(str); % bold text in bracket if just in the beginning tmploc = sort(union(find(str == '['), find(str == ']'))); if ~isempty(tmploc) & str(1) == '[' if mod(length(tmploc),2) ~= 0, str, error('Opening but no closing bracket'); end; tmploc = tmploc(1:2); str = [ str(1:tmploc(1)) '<b>' str(tmploc(1)+1:tmploc(2)-1) '</b>' str(tmploc(2):end) ]; end; %tmploc = find(str == '"'); %if ~isempty(tmploc) % if mod(length(tmploc),2) ~= 0, str, error('Opening but no closing parenthesis'); end; % for index = length(tmploc):-2:1 % str = [ str(1:tmploc(index-1)-1) '<b>' str(tmploc(index-1)+1:tmploc(index)-1) '</b>' str(tmploc(index)+1:end) ]; % end; %end; function tokout = functionformat( tokin, refcall ); tokout = tokin; % default [test, realtokin, tail, beg] = 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)]; % concatenate filename and extension %disp(filename) if exist( filename ) % do not make link if the file does not exist tokout = sprintf( [ beg '<A HREF="' refcall '">%s</A>' tail ' ' ], realtokin, realtokin ); end; end; return; function [test, realtokin, tail, beg] = testfunc1( tokin ) % test if is string is 'function()[,]' test = 0; realtokin = ''; tail = ''; beg = ''; if ~isempty( findstr( tokin, '()' ) ) if length(tokin)<3, return; end; realtokin = tokin( 1:findstr( tokin, '()' )-1); if length(realtokin) < (length(tokin)-2) tail = tokin(end); else tail = []; end; test = 1; if realtokin(1) == '(', realtokin = realtokin(2:end); beg = '('; end; if realtokin(1) == ',', realtokin = realtokin(2:end); beg = ','; end; 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; function [tok, str] = mystrtok(str) [tok str] = strtok(str); if tok(1) == '"' while tok(end) ~= '"' [tok2 str] = strtok(str); if isempty(tok2), tok, error('can not find closing quote ''"'' in previous text'); end; tok = [tok ' ' tok2]; end; end;
github
ZijingMao/baselineeegtest-master
getallmenus.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/getallmenus.m
2,254
utf_8
757fe9c0de1f75dd78ee6012bb2c3ddf
% getallmenus() - get all submenus of a window or a menu and return % a tree. % % Usage: % >> [tree nb] = getallmenus( handler ); % % Inputs: % handler - handler of the window or of a menu % % Outputs: % tree - text output % nb - number of elements in the tree % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % 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 [txt, nb, labels] = getallmenus( handler, level ) NBBLANK = 6; % number of blank for each submenu input if nargin < 1 help getallmenus; return; end; if nargin < 2 level = 0; end; txt = ''; nb = 0; labels = {}; allmenu = findobj('parent', handler, 'type', 'uimenu'); allmenu = allmenu(end:-1:1); if ~isempty(allmenu) for i=1:length( allmenu ); [txtmp nbtmp tmplab] = getallmenus(allmenu(i), level+1); txtmp = [ blanks(level*NBBLANK) txtmp ]; txt = [ txtmp txt ]; labels = { tmplab labels{:} }; nb = nb+nbtmp; end; end; try txt = [ get(handler, 'Label') 10 txt ]; nb = nb+1; catch, end; if isempty(labels) labels = { nb }; end; % transform into array of text % ---------------------------- if nargin < 2 txt = [10 txt]; newtext = zeros(1000, 1000); maxlength = 0; lines = find( txt == 10 ); for index = 1:length(lines)-1 tmptext = txt(lines(index)+1:lines(index+1)-1); if maxlength < length( tmptext ), maxlength = length( tmptext ); end; newtext(index, 1:length(tmptext)) = tmptext; end; txt = char( newtext(1:index+1, 1:maxlength) ); end; return;
github
ZijingMao/baselineeegtest-master
eeg_regepochs.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/eeg_regepochs.m
6,723
utf_8
68a8bef2b1f7b22c806d132a4c322cc6
% eeg_regepochs() - Convert a continuous dataset into consecutive epochs of % a specified regular length by adding dummy events of type % and epoch the data around these events. Alternatively % only insert events for extracting these epochs. % May be used to split up continuous data for % artifact rejection followed by ICA decomposition. % The computed EEG.icaweights and EEG.icasphere matrices % may then be exported to the continuous dataset and/or % to its epoched descendents. % Usage: % >> EEGout = eeg_regepochs(EEG); % use defaults % >> EEGout = eeg_regepochs(EEG, 'key', val, ...); % % Required input: % EEG - EEG continuous data structure (EEG.trials = 1) % % Optional inputs: % 'recurrence' - [in s] the regular recurrence interval of the dummy % events used as time-locking events for the % consecutive epochs {default: 1 s} % 'limits' - [minsec maxsec] latencies relative to the time-locking % events to use as epoch boundaries. Stated epoch length % will be reduced by one data point to avoid overlaps % {default: [0 recurrence_interval]} % 'rmbase' - [NaN|latency] remove baseline (s). NaN does not remove % baseline. 0 remove the pre-0 baseline. To % remove the full epoch baseline, enter a value % larger than the upper epoch limit. Default is 0. % 'eventtype' - [string] name for the event type. Default is 'X' % 'extractepochs' - ['on'|'off'] extract data epochs ('on') or simply % insert events ('off'). Default is 'on'. % % Outputs: % EEGout - the input EEG structure separated into consecutive % epochs. % % See also: pop_editeventvals(), pop_epoch(), rmbase(); % % Authors: Hilit Serby, Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, Sep 02, 2005 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, Sep 02, 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 EEG = eeg_regepochs(EEG, varargin) if nargin < 1 help eeg_regepochs; return; end; if length(EEG) > 1 EEG = pop_mergeset(EEG, [1:length(EEG)]); end; % test input variables % -------------------- if ~isstruct(EEG) | ~isfield(EEG,'event') error('first argument must be an EEG structure') elseif EEG.trials > 1 error('input dataset must be continuous data (1 epoch)'); end if nargin > 1 && ~isstr(varargin{1}) options = {}; if nargin >= 2, options = { options{:} 'recurrence' varargin{1} }; end; if nargin >= 3, options = { options{:} 'limits' varargin{2} }; end; if nargin >= 4, options = { options{:} 'rmbase' varargin{3} }; end; else options = varargin; end; g = finputcheck(options, { 'recurrence' 'real' [] 1; 'limits' 'real' [] [0 1]; 'rmbase' 'real' [] 0; 'eventtype' 'string' {} 'X'; 'extractepochs' 'string' { 'on','off' } 'on' }, 'eeg_regepochs'); if isstr(g), error(g); end; if g.recurrence < 0 | g.recurrence > EEG.xmax error('recurrence_interval out of bounds'); end if nargin < 3 g.limits = [0 g.recurrence]; end if length(g.limits) ~= 2 | g.limits(2) <= g.limits(1) error('epoch limits must be a 2-vector [minsec maxsec]') end % calculate number of events to add % --------------------------------- bg = 0; % beginning of data en = EEG.xmax; % end of data in sec nu = floor(EEG.xmax/g.recurrence); % number of type 'X' events to add and epoch on % bg = EEG.event(1).latency/EEG.srate; % time in sec of first event % en = EEG.event(end).latency/EEG.srate; % time in sec of last event % nu = length((bg+g.recurrence):g.recurrence:(en-g.recurrence)); % number of 'X' events, one every 'g.recurrence' sec if nu < 1 error('specified recurrence_interval too long') end % print info on commandline % ------------------------- eplength = g.limits(2)-g.limits(1); fprintf('The input dataset will be split into %d epochs of %g s\n',nu,eplength); fprintf('Epochs will overlap by %2.0f%%.\n',(eplength-g.recurrence)/eplength*100); % insert events and urevents at the end of the current (ur)event tables % --------------------------------------------------------------------- fprintf('Inserting %d type ''%s'' events: ', nu, g.eventtype); nevents = length(EEG.event); % convert all event types to strings for k = 1:nevents EEG.event(k).type = num2str(EEG.event(k).type); end nurevents = length(EEG.urevent); for k = 1:nu if rem(k,40) fprintf('.') else fprintf('%d',k) end if k==40 | ( k>40 & ~rem(k-40,70)) fprintf('\n'); end EEG.event(nevents+k).type = g.eventtype; EEG.event(nevents+k).latency = g.recurrence*(k-1)*EEG.srate+1; EEG.urevent(nurevents+k).type = g.eventtype; EEG.urevent(nurevents+k).latency = g.recurrence*(k-1)*EEG.srate+1; EEG.event(nevents+k).urevent = nurevents+k; end fprintf('\n'); % sort the events based on their latency % -------------------------------------- fprintf('Sorting the event table.\n'); EEG = pop_editeventvals( EEG, 'sort', {'latency' 0}); % split the dataset into epochs % ------------------------------ if strcmpi(g.extractepochs, 'on') fprintf('Splitting the data into %d %2.2f-s epochs\n',nu,eplength); setname = sprintf('%s - %g-s epochs', EEG.setname, g.recurrence); EEG = pop_epoch( EEG, { g.eventtype }, g.limits, 'newname', ... setname, 'epochinfo', 'yes'); % baseline zero the epochs % ------------------------ if ~isnan(g.rmbase) && g.limits(1) < g.rmbase fprintf('Removing the pre %3.2f second baseline mean of each epoch.\n', g.rmbase); EEG = pop_rmbase( EEG, [g.limits(1) g.rmbase]*1000); end end;
github
ZijingMao/baselineeegtest-master
eegplotold.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/eegplotold.m
33,034
utf_8
f08480f9c8c3fcde09afda52f574a1f3
% eegplotold() - display data in a horizontal scrolling fashion % with (optional) gui controls (version 2.3) % Usage: % >> eegplotold(data,srate,spacing,eloc_file,windowlength,title) % >> eegplotold('noui',data,srate,spacing,eloc_file,startpoint,color) % % Inputs: % data - Input data matrix (chans,timepoints) % srate - Sampling rate in Hz {default|0: 256 Hz} % spacing - Space between channels (default|0: max(data)-min(data)) % eloc_file - Electrode filename as in >> topoplot example % [] -> no labels; default|0 -> integers 1:nchans % vector of integers -> channel numbers % windowlength - Number of seconds of EEG displayed {default 10 s} % color - EEG plot color {default black/white} % 'noui' - Display eeg in current axes without user controls % % Author: Colin Humphries, CNL, Salk Institute, La Jolla, 5/98 % % See also: eegplot(), eegplotgold(), eegplotsold() % Copyright (C) Colin Humphries, CNL, Salk Institute 3/97 from eegplotold() % % 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 % Runs under Matlab 5.0+ (not supported for Matlab 4) % % RCS-recorded version number, date, editor and comments % $Log: eegplotold.m,v $ % Revision 1.3 2007/02/24 02:42:37 toby % added auto-log line % % % Edit History: % 5-14-98 v2.1 fixed bug for small-variance data -ch % 1-31-00 v2.2 exchanged meaning of > and >>, < and << -sm % 8-15-00 v2.3 turned on SPACING_EYE and added int vector input for eloc_file -sm % 12-16-00 added undocumented figure position arg (if not 'noui') -sm % 01-25-02 reformated help & license, added links -ad function [outvar1] = eegplotold(data,p1,p2,p3,p4,p5,p6) % Defaults (can be re-defined): DEFAULT_ELOC_FILE = 0; % Default electrode name file % [] - none, 0 - numbered, or filename DEFAULT_SAMPLE_RATE = 256; % Samplerate DEFAULT_PLOT_COLOR = 'k'; % EEG line color DEFAULT_AXIS_BGCOLOR = [.8 .8 .8];% EEG Axes Background Color DEFAULT_FIG_COLOR = [.8 .8 .8]; % Figure Background Color DEFAULT_AXIS_COLOR = 'k'; % X-axis, Y-axis Color, text Color DEFAULT_WINLENGTH = 10; % Number of seconds of EEG displayed DEFAULT_GRID_SPACING = 1; % Grid lines every n seconds DEFAULT_GRID_STYLE = '-'; % Grid line style YAXIS_NEG = 'off'; % 'off' = positive up DEFAULT_NOUI_PLOT_COLOR = 'k'; % EEG line color for noui option % 0 - 1st color in AxesColorOrder DEFAULT_TITLEVAL = 2; % Default title % string, 2 - variable name, 0 - none SPACING_EYE = 'on'; % spacing I on/off SPACING_UNITS_STRING = '\muV'; % optional units for spacing I Ex. uV DEFAULT_AXES_POSITION = [0.0964286 0.15 0.842 0.788095]; % dimensions of main EEG axes if nargin<1 help eegplotold return end % %%%%%%%%%%%%%%%%%%%%%%%% % Setup inputs % %%%%%%%%%%%%%%%%%%%%%%%% if ~isstr(data) % If NOT a 'noui' call or a callback from uicontrols if nargin == 7 % undocumented feature - allows position to be specd. posn = p6; else posn = NaN; end % if strcmp(YAXIS_NEG,'on') % data = -data; % end if nargin < 6 titleval = 0; else titleval = p5; end if nargin < 5 winlength = 0; else winlength = p4; end if nargin < 4 eloc_file = DEFAULT_ELOC_FILE; else eloc_file = p3; end if nargin < 3 spacing = 0; else spacing = p2; end if nargin < 2 Fs = 0; else Fs = p1; end if isempty(titleval) titleval = 0; end if isempty(winlength) winlength = 0; end if isempty(spacing) spacing = 0; end if isempty(Fs) Fs = 0; end [chans,frames] = size(data); if winlength == 0 winlength = DEFAULT_WINLENGTH; % Set window length end if ischar(eloc_file) % Read in electrode names fid = fopen(eloc_file); % Read file if fid < 1 error('error opening electrode file') end YLabels = fscanf(fid,'%d %f %f%s',[7 128]); fclose(fid); YLabels = char(YLabels(4:7,:)'); ii = find(YLabels == '.'); YLabels(ii) = ' '; YLabels = flipud(str2mat(YLabels,' ')); elseif length(eloc_file) == chans YLabels = num2str(eloc_file'); elseif length(eloc_file) == 1 & eloc_file(1) == 0 YLabels = num2str((1:chans)'); % Use numbers else YLabels = []; % no labels used end YLabels = flipud(str2mat(YLabels,' ')); if spacing == 0 spacing = (max(max(data')-min(data'))); % Set spacing to max/min data if spacing > 10 spacing = round(spacing); end end if titleval == 0 titleval = DEFAULT_TITLEVAL; % Set title value end if Fs == 0 Fs = DEFAULT_SAMPLE_RATE; % Set samplerate end % %%%%%%%%%%%%%%%%%%%%%%%% % Prepare figure and axes % %%%%%%%%%%%%%%%%%%%%%%%% if isnan(posn) % no user-supplied position vector figh = figure('UserData',[winlength Fs],... 'Color',DEFAULT_FIG_COLOR,... 'MenuBar','none','tag','eegplotold'); else figh = figure('UserData',[winlength Fs],... 'Color',DEFAULT_FIG_COLOR,... 'MenuBar','none','tag','eegplotold','Position',posn); end %entry ax1 = axes('tag','eegaxis','parent',figh,... 'userdata',data,... 'Position',DEFAULT_AXES_POSITION,... 'Box','on','xgrid','on',... 'gridlinestyle',DEFAULT_GRID_STYLE,... 'Xlim',[0 winlength*Fs],... 'xtick',[0:Fs*DEFAULT_GRID_SPACING:winlength*Fs],... 'Ylim',[0 (chans+1)*spacing],... 'YTick',[0:spacing:chans*spacing],... 'YTickLabel',YLabels,... 'XTickLabel',num2str((0:DEFAULT_GRID_SPACING:winlength)'),... 'TickLength',[.005 .005],... 'Color',DEFAULT_AXIS_BGCOLOR,... 'XColor',DEFAULT_AXIS_COLOR,... 'YColor',DEFAULT_AXIS_COLOR); if isstr(titleval) % plot title title(titleval) elseif titleval == 2 title(inputname(1)) end % %%%%%%%%%%%%%%%%%%%%%%%%% % Set up uicontrols % %%%%%%%%%%%%%%%%%%%%%%%%% % Four move buttons: << < > >> u(1) = uicontrol('Parent',figh, ... 'Units','points', ... 'Position',[49.1294 12.7059 50.8235 16.9412], ... 'Tag','Pushbutton1',... 'string','<<',... 'Callback','eegplotold(''drawp'',1)'); u(2) = uicontrol('Parent',figh, ... 'Units','points', ... 'Position',[105.953 12.7059 33.0353 16.9412], ... 'Tag','Pushbutton2',... 'string','<',... 'Callback','eegplotold(''drawp'',2)'); u(3) = uicontrol('Parent',figh, ... 'Units','points', ... 'Position',[195.882 12.7059 33.8824 16.9412], ... 'Tag','Pushbutton3',... 'string','>',... 'Callback','eegplotold(''drawp'',3)'); u(4) = uicontrol('Parent',figh, ... 'Units','points', ... 'Position',[235.765 12.7059 50.8235 16.9412], ... 'Tag','Pushbutton4',... 'string','>>',... 'Callback','eegplotold(''drawp'',4)'); % Text edit fields: EPosition ESpacing u(5) = uicontrol('Parent',figh, ... 'Units','points', ... 'BackgroundColor',[1 1 1], ... 'Position',[144.988 10.1647 44.8941 19.4824], ... 'Style','edit', ... 'Tag','EPosition',... 'string','0',... 'Callback','eegplotold(''drawp'',0)'); u(6) = uicontrol('Parent',figh, ... 'Units','points', ... 'BackgroundColor',[1 1 1], ... 'Position',[379.482-30 11.8 46.5882 19.5], ... 'Style','edit', ... 'Tag','ESpacing',... 'string',num2str(spacing),... 'Callback','eegplotold(''draws'',0)'); % ESpacing buttons: + - u(7) = uicontrol('Parent',figh, ... 'Units','points', ... 'Position',[435-30 22.9 22 13.5], ... 'Tag','Pushbutton5',... 'string','+',... 'FontSize',8,... 'Callback','eegplotold(''draws'',1)'); u(8) = uicontrol('Parent',figh, ... 'Units','points', ... 'Position',[435-30 6.7 22 13.5], ... 'Tag','Pushbutton6',... 'string','-',... 'FontSize',8,... 'Callback','eegplotold(''draws'',2)'); set(u,'Units','Normalized') % %%%%%%%%%%%%%%%%%%%%%%%%%%% % Set up uimenus % %%%%%%%%%%%%%%%%%%%%%%%%%%% % Figure Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% m(7) = uimenu('Parent',figh,'Label','Figure'); m(8) = uimenu('Parent',m(7),'Label','Orientation'); uimenu('Parent',m(7),'Label','Close',... 'Callback','delete(gcbf)') % Portrait %%%%%%%% timestring = ['[OBJ1,FIG1] = gcbo;',... 'PANT1 = get(OBJ1,''parent'');',... 'OBJ2 = findobj(''tag'',''orient'',''parent'',PANT1);',... 'set(OBJ2,''checked'',''off'');',... 'set(OBJ1,''checked'',''on'');',... 'set(FIG1,''PaperOrientation'',''portrait'');',... 'clear OBJ1 FIG1 OBJ2 PANT1;']; uimenu('Parent',m(8),'Label','Portrait','checked',... 'on','tag','orient','callback',timestring) % Landscape %%%%%%% timestring = ['[OBJ1,FIG1] = gcbo;',... 'PANT1 = get(OBJ1,''parent'');',... 'OBJ2 = findobj(''tag'',''orient'',''parent'',PANT1);',... 'set(OBJ2,''checked'',''off'');',... 'set(OBJ1,''checked'',''on'');',... 'set(FIG1,''PaperOrientation'',''landscape'');',... 'clear OBJ1 FIG1 OBJ2 PANT1;']; uimenu('Parent',m(8),'Label','Landscape','checked',... 'off','tag','orient','callback',timestring) % Display Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% m(1) = uimenu('Parent',figh,... 'Label','Display'); % X grid %%%%%%%%%%%% m(3) = uimenu('Parent',m(1),'Label','X Grid'); timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''xgrid'',''on'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(3),'Label','on','Callback',timestring) timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''xgrid'',''off'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(3),'Label','off','Callback',timestring) % Y grid %%%%%%%%%%%%% m(4) = uimenu('Parent',m(1),'Label','Y Grid'); timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''ygrid'',''on'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(4),'Label','on','Callback',timestring) timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''ygrid'',''off'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(4),'Label','off','Callback',timestring) % Grid Style %%%%%%%%% m(5) = uimenu('Parent',m(1),'Label','Grid Style'); timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''gridlinestyle'',''--'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(5),'Label','- -','Callback',timestring) timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''gridlinestyle'',''-.'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(5),'Label','_ .','Callback',timestring) timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''gridlinestyle'','':'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(5),'Label','. .','Callback',timestring) timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''gridlinestyle'',''-'');',... 'clear FIGH AXESH;']; uimenu('Parent',m(5),'Label','__','Callback',timestring) % Scale Eye %%%%%%%%% timestring = ['[OBJ1,FIG1] = gcbo;',... 'eegplotold(''scaleeye'',OBJ1,FIG1);',... 'clear OBJ1 FIG1;']; m(7) = uimenu('Parent',m(1),'Label','Scale I','Callback',timestring); % Title %%%%%%%%%%%% uimenu('Parent',m(1),'Label','Title','Callback','eegplotold(''title'')') % Settings Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% m(2) = uimenu('Parent',figh,... 'Label','Settings'); % Window %%%%%%%%%%%% uimenu('Parent',m(2),'Label','Window',... 'Callback','eegplotold(''window'')') % Samplerate %%%%%%%% uimenu('Parent',m(2),'Label','Samplerate',... 'Callback','eegplotold(''samplerate'')') % Electrodes %%%%%%%% m(6) = uimenu('Parent',m(2),'Label','Electrodes'); timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'set(AXESH,''YTickLabel'',[]);',... 'clear FIGH AXESH;']; uimenu('Parent',m(6),'Label','none','Callback',timestring) timestring = ['FIGH = gcbf;',... 'AXESH = findobj(''tag'',''eegaxis'',''parent'',FIGH);',... 'YTICK = get(AXESH,''YTick'');',... 'YTICK = length(YTICK);',... 'set(AXESH,''YTickLabel'',flipud(str2mat(num2str((1:YTICK-1)''),'' '')));',... 'clear FIGH AXESH YTICK;']; uimenu('Parent',m(6),'Label','numbered','Callback',timestring) uimenu('Parent',m(6),'Label','load file',... 'Callback','eegplotold(''loadelect'');') % %%%%%%%%%%%%%%%%%%%%%%%%%% % Plot EEG Data % %%%%%%%%%%%%%%%%%%%%%%%%%% meandata = mean(data(:,1:round(min(frames,winlength*Fs)))'); axes(ax1) hold on for i = 1:chans plot(data(chans-i+1,... 1:round(min(frames,winlength*Fs)))-meandata(chans-i+1)+i*spacing,... 'color',DEFAULT_PLOT_COLOR) end % %%%%%%%%%%%%%%%%%%%%%%%%%% % Plot Spacing I % %%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(SPACING_EYE,'on') YLim = get(ax1,'Ylim'); A = DEFAULT_AXES_POSITION; axes('Position',[A(1)+A(3) A(2) 1-A(1)-A(3) A(4)],... 'Visible','off','Ylim',YLim,'tag','eyeaxes') axis manual Xl = [.3 .6 .45 .45 .3 .6]; Yl = [spacing*2 spacing*2 spacing*2 spacing*1 spacing*1 spacing*1]; line(Xl,Yl,'color',DEFAULT_AXIS_COLOR,'clipping','off',... 'tag','eyeline') text(.5,YLim(2)/23+Yl(1),num2str(spacing,4),... 'HorizontalAlignment','center','FontSize',10,... 'tag','thescale') if strcmp(YAXIS_NEG,'off') text(Xl(2)+.1,Yl(1),'+','HorizontalAlignment','left',... 'verticalalignment','middle') text(Xl(2)+.1,Yl(4),'-','HorizontalAlignment','left',... 'verticalalignment','middle') else text(Xl(2)+.1,Yl(4),'+','HorizontalAlignment','left',... 'verticalalignment','middle') text(Xl(2)+.1,Yl(1),'-','HorizontalAlignment','left',... 'verticalalignment','middle') end if ~isempty(SPACING_UNITS_STRING) text(.5,-YLim(2)/23+Yl(4),SPACING_UNITS_STRING,... 'HorizontalAlignment','center','FontSize',10) end set(m(7),'checked','on') elseif strcmp(SPACING_EYE,'off') YLim = get(ax1,'Ylim'); A = DEFAULT_AXES_POSITION; axes('Position',[A(1)+A(3) A(2) 1-A(1)-A(3) A(4)],... 'Visible','off','Ylim',YLim,'tag','eyeaxes') axis manual set(m(7),'checked','off') end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % End Main Function % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else switch data case 'drawp' % Redraw EEG and change position figh = gcbf; % figure handle if strcmp(get(figh,'tag'),'dialog') figh = get(figh,'UserData'); end ax1 = findobj('tag','eegaxis','parent',figh); % axes handle EPosition = findobj('tag','EPosition','parent',figh); % ui handle ESpacing = findobj('tag','ESpacing','parent',figh); % ui handle data = get(ax1,'UserData'); % Data (Note: this could also be global) timestr = get(EPosition,'string'); % current position % if timestr == 'end' % time = ceil(frames/Fs)-winlength; % fprintf('timestr = %s\n',timestr); % else time = str2num(timestr); % current position % end spacing = str2num(get(ESpacing,'string')); % current spacing winlength = get(figh,'UserData'); Fs = winlength(2); % samplerate winlength = winlength(1); % window length [chans,frames] = size(data); if p1 == 1 time = time-winlength; % << subtract one window length elseif p1 == 2 time = time-1; % < subtract one second elseif p1 == 3 time = time+1; % > add one second elseif p1 == 4 time = time+winlength; % >> add one window length end time = max(0,min(time,ceil(frames/Fs)-winlength)); set(EPosition,'string',num2str(time)) % Update edit box % keyboard % Plot data and update axes meandata = mean(data(:,round(time*Fs+1):round(min((time+winlength)*Fs,... frames)))'); axes(ax1) cla for i = 1:chans plot(data(chans-i+1,round(time*Fs+1):round(min((time+winlength)*Fs,... frames)))-meandata(chans-i+1)+i*spacing,... 'color',DEFAULT_PLOT_COLOR,'clipping','off') end set(ax1,'XTickLabel',... num2str((time:DEFAULT_GRID_SPACING:time+winlength)'),... 'Xlim',[0 winlength*Fs],... 'XTick',[0:Fs*DEFAULT_GRID_SPACING:winlength*Fs]) case 'draws' % Redraw EEG and change scale figh = gcbf; % figure handle ax1 = findobj('tag','eegaxis','parent',figh); % axes handle EPosition = findobj('tag','EPosition','parent',figh); % ui handle ESpacing = findobj('tag','ESpacing','parent',figh); % ui handle data = get(ax1,'UserData'); % data time = str2num(get(EPosition,'string')); % current position spacing = str2num(get(ESpacing,'string')); % current spacing winlength = get(figh,'UserData'); if isempty(spacing) | isempty(time) return % return if valid numbers are not in the edit boxes end Fs = winlength(2); % samplerate winlength = winlength(1); % window length orgspacing = round(max(max(data')-min(data'))); % original spacing [chans,frames] = size(data); if p1 == 1 spacing = spacing + .05*orgspacing; % increase spacing (5%) elseif p1 == 2 spacing = max(0,spacing-.05*orgspacing); % decrease spacing (5%) if spacing == 0 spacing = spacing + .05*orgspacing; end end set(ESpacing,'string',num2str(spacing,4)) % update edit box % plot data and update axes meandata = mean(data(:,round(time*Fs+1):round(min((time+winlength)*Fs,... frames)))'); axes(ax1) cla for i = 1:chans plot(data(chans-i+1,... round(time*Fs+1):round(min((time+winlength)*Fs,... frames)))-meandata(chans-i+1)+i*spacing,... 'color',DEFAULT_PLOT_COLOR,'clipping','off') end set(ax1,'YLim',[0 (chans+1)*spacing],... 'YTick',[0:spacing:chans*spacing]) % update scaling eye if it exists eyeaxes = findobj('tag','eyeaxes','parent',figh); if ~isempty(eyeaxes) eyetext = findobj('type','text','parent',eyeaxes,'tag','thescale'); set(eyetext,'string',num2str(spacing,4)) end case 'window' % get new window length with dialog box fig = gcbf; oldwinlen = get(fig,'UserData'); pos = get(fig,'Position'); figx = 400; figy = 200; fhand = figure('Units','pixels',... 'Position',... [pos(1)+pos(3)/2-figx/2 pos(2)+pos(4)/2-figy/2 figx figy],... 'Resize','off','CloseRequestFcn','','menubar','none',... 'numbertitle','off','tag','dialog','userdata',fig); uicolor = get(fhand,'Color'); uicontrol('Style','Text','Units','Pixels',... 'String','Enter new window length(secs):',... 'Position',[20 figy-40 300 25],'HorizontalAlignment','left',... 'BackgroundColor',uicolor,'FontSize',14) timestring = ['[OBJ1,FIGH1] = gcbo;',... 'FIH0 = get(OBJ1,''UserData'');',... 'AXH0 = findobj(''tag'',''eegaxis'',''parent'',FIH0);',... 'WLEN = str2num(get(OBJ1,''String''));',... 'if ~isempty(WLEN);',... 'UDATA = get(FIH0,''UserData'');',... 'UDATA(1) = WLEN;',... 'set(FIH0,''UserData'',UDATA);',... 'eegplotold(''drawp'',0);',... 'delete(FIGH1);',... 'end;',... 'clear OBJ1 FIGH1 FIH0 AXH0 WLEN UDATA;']; ui1 = uicontrol('Style','Edit','Units','Pixels',... 'FontSize',12,... 'Position',[120 figy-100 70 30],... 'Callback',timestring,'UserData',fig,... 'String',num2str(oldwinlen(1))); timestring = ['[OBJ1,FIGH1] = gcbo;',... 'FIH0 = get(OBJ1,''UserData'');',... 'AXH0 = findobj(''tag'',''eegaxis'',''parent'',FIH0(1));',... 'SRAT = str2num(get(FIH0(2),''String''));',... 'if ~isempty(SRAT);',... 'UDATA = get(FIH0(1),''UserData'');',... 'UDATA(2) = SRAT;',... 'set(FIH0(1),''UserData'',UDATA);',... 'eegplotold(''drawp'',0);',... 'delete(FIGH1);',... 'end;',... 'clear OBJ1 FIGH1 FIH0 AXH0 SRAT UDATA;']; uicontrol('Style','PushButton','Units','Pixels',... 'String','OK','FontSize',14,... 'Position',[figx/4-20 10 65 30],... 'Callback',timestring,'UserData',[fig,ui1]) TIMESTRING = ['[OBJ1,FIGH1] = gcbo;',... 'delete(FIGH1);',... 'clear OBJ1 FIGH1;']; uicontrol('Style','PushButton','Units','Pixels',... 'String','Cancel','FontSize',14,... 'Position',[3*figx/4-20 10 65 30],... 'Callback',TIMESTRING) case 'samplerate' % Get new samplerate fig = gcbf; oldsrate = get(fig,'UserData'); pos = get(fig,'Position'); figx = 400; figy = 200; fhand = figure('Units','pixels',... 'Position',... [pos(1)+pos(3)/2-figx/2 pos(2)+pos(4)/2-figy/2 figx figy],... 'Resize','off','CloseRequestFcn','','menubar','none',... 'numbertitle','off','tag','dialog','userdata',fig); uicolor = get(fhand,'Color'); uicontrol('Style','Text','Units','Pixels',... 'String','Enter new samplerate:',... 'Position',[20 figy-40 300 25],'HorizontalAlignment','left',... 'BackgroundColor',uicolor,'FontSize',14) timestring = ['[OBJ1,FIGH1] = gcbo;',... 'FIH0 = get(OBJ1,''UserData'');',... 'AXH0 = findobj(''tag'',''eegaxis'',''parent'',FIH0);',... 'SRAT = str2num(get(OBJ1,''String''));',... 'if ~isempty(SRAT);',... 'UDATA = get(FIH0,''UserData'');',... 'UDATA(2) = SRAT;',... 'set(FIH0,''UserData'',UDATA);',... 'eegplotold(''drawp'',0);',... 'delete(FIGH1);',... 'end;',... 'clear OBJ1 FIGH1 FIH0 AXH0 SRAT UDATA;']; ui1 = uicontrol('Style','Edit','Units','Pixels',... 'FontSize',12,... 'Position',[120 figy-100 70 30],... 'Callback',timestring,'UserData',fig,... 'String',num2str(oldsrate(2))); timestring = ['[OBJ1,FIGH1] = gcbo;',... 'FIH0 = get(OBJ1,''UserData'');',... 'AXH0 = findobj(''tag'',''eegaxis'',''parent'',FIH0(1));',... 'SRAT = str2num(get(FIH0(2),''String''));',... 'if ~isempty(SRAT);',... 'UDATA = get(FIH0(1),''UserData'');',... 'UDATA(2) = SRAT;',... 'set(FIH0(1),''UserData'',UDATA);',... 'eegplotold(''drawp'',0);',... 'delete(FIGH1);',... 'end;',... 'clear OBJ1 FIGH1 FIH0 AXH0 SRAT UDATA;']; uicontrol('Style','PushButton','Units','Pixels',... 'String','OK','FontSize',14,... 'Position',[figx/4-20 10 65 30],... 'Callback',timestring,'UserData',[fig,ui1]) TIMESTRING = ['[OBJ1,FIGH1] = gcbo;',... 'delete(FIGH1);',... 'clear OBJ1 FIGH1;']; uicontrol('Style','PushButton','Units','Pixels',... 'String','Cancel','FontSize',14,... 'Position',[3*figx/4-20 10 65 30],... 'Callback',TIMESTRING) case 'loadelect' % load electrode file fig = gcbf; pos = get(fig,'Position'); figx = 400; figy = 200; fhand = figure('Units','pixels',... 'Position',... [pos(1)+pos(3)/2-figx/2 pos(2)+pos(4)/2-figy/2 figx figy],... 'Resize','off','CloseRequestFcn','','menubar','none',... 'numbertitle','off','tag','dialog','userdata',fig); uicolor = get(fhand,'Color'); uicontrol('Style','Text','Units','Pixels',... 'String','Enter electrode file name:',... 'Position',[20 figy-40 300 25],'HorizontalAlignment','left',... 'BackgroundColor',uicolor,'FontSize',14) ui1 = uicontrol('Style','Edit','Units','Pixels',... 'FontSize',12,... 'HorizontalAlignment','left',... 'Position',[120 figy-100 210 30],... 'UserData',fig,'tag','electedit'); TIMESTRING = ['[OBJ1,FIGH1] = gcbo;',... 'delete(FIGH1);',... 'clear OBJ1 FIGH1;']; uicontrol('Style','PushButton','Units','Pixels',... 'String','Cancel','FontSize',14,... 'Position',[3*figx/4-20 10 65 30],... 'Callback',TIMESTRING) timestring = ['[OBJ1,FIGH1] = gcbo;',... 'OBJ2 = findobj(''tag'',''electedit'');',... 'LAB1 = get(OBJ2,''string'');',... 'FIH0 = get(OBJ1,''UserData'');',... 'AXH0 = findobj(''tag'',''eegaxis'',''parent'',FIH0);',... 'OUT1 = eegplotold(''setelect'',LAB1,AXH0);',... 'if (OUT1);',... 'delete(FIGH1);',... 'end;',... 'clear OBJ1 FIGH1 LAB1 OBJ2 FIH0 AXH0 OUT1;']; uicontrol('Style','PushButton','Units','Pixels',... 'String','OK','FontSize',14,... 'Position',[figx/4-20 10 65 30],... 'Callback',timestring,'UserData',fig) timestring = ['OBJ2 = findobj(''tag'',''electedit'');',... '[LAB1,LAB2] = uigetfile(''*'',''Electrode File'');',... 'if (isstr(LAB1) & isstr(LAB2));',... 'set(OBJ2,''string'',[LAB2,LAB1]);',... 'end;',... 'clear OBJ2 LAB1 LAB2;']; uicontrol('Style','PushButton','Units','Pixels',... 'String','Browse','FontSize',14,... 'Position',[figx/2-20 10 65 30],'UserData',fig,... 'Callback',timestring) case 'setelect' % Set electrodes eloc_file = p1; axeshand = p2; outvar1 = 1; if isempty(eloc_file) outvar1 = 0; return end fid = fopen(eloc_file); if fid < 1 fprintf('Cannot open electrode file.\n\n') outvar1 = 0; return end YLabels = fscanf(fid,'%d %f %f %s',[7 128]); if isempty(YLabels) fprintf('Error reading electrode file.\n\n') outvar1 = 0; return end fclose(fid); YLabels = char(YLabels(4:7,:)'); ii = find(YLabels == '.'); YLabels(ii) = ' '; YLabels = flipud(str2mat(YLabels,' ')); set(axeshand,'YTickLabel',YLabels) case 'title' % Get new title fig = gcbf; % oldsrate = get(fig,'UserData'); eegaxis = findobj('tag','eegaxis','parent',fig); oldtitle = get(eegaxis,'title'); oldtitle = get(oldtitle,'string'); pos = get(fig,'Position'); figx = 400; figy = 200; fhand = figure('Units','pixels',... 'Position',... [pos(1)+pos(3)/2-figx/2 pos(2)+pos(4)/2-figy/2 figx figy],... 'Resize','off','CloseRequestFcn','','menubar','none',... 'numbertitle','off','tag','dialog','userdata',fig); uicolor = get(fhand,'Color'); uicontrol('Style','Text','Units','Pixels',... 'String','Enter new title:',... 'Position',[20 figy-40 300 25],'HorizontalAlignment','left',... 'BackgroundColor',uicolor,'FontSize',14) timestring = ['[OBJ1,FIGH1] = gcbo;',... 'FIH0 = get(OBJ1,''UserData'');',... 'AXH0 = findobj(''tag'',''eegaxis'',''parent'',FIH0);',... 'SRAT = get(OBJ1,''String'');',... 'AXTH0 = get(AXH0,''title'');',... 'if ~isempty(SRAT);',... 'set(AXTH0,''string'',SRAT);',... 'end;',... 'delete(FIGH1);',... 'clear OBJ1 AXTH0 FIGH1 FIH0 AXH0 SRAT UDATA;']; ui1 = uicontrol('Style','Edit','Units','Pixels',... 'FontSize',12,... 'Position',[120 figy-100 3*70 30],... 'Callback',timestring,'UserData',fig,... 'String',oldtitle); timestring = ['[OBJ1,FIGH1] = gcbo;',... 'FIH0 = get(OBJ1,''UserData'');',... 'AXH0 = findobj(''tag'',''eegaxis'',''parent'',FIH0(1));',... 'SRAT = get(FIH0(2),''String'');',... 'AXTH0 = get(AXH0,''title'');',... 'set(AXTH0,''string'',SRAT);',... 'delete(FIGH1);',... 'clear OBJ1 AXTH0 FIGH1 FIH0 AXH0 SRAT UDATA;']; uicontrol('Style','PushButton','Units','Pixels',... 'String','OK','FontSize',14,... 'Position',[figx/4-20 10 65 30],... 'Callback',timestring,'UserData',[fig,ui1]) TIMESTRING = ['[OBJ1,FIGH1] = gcbo;',... 'delete(FIGH1);',... 'clear OBJ1 FIGH1;']; uicontrol('Style','PushButton','Units','Pixels',... 'String','Cancel','FontSize',14,... 'Position',[3*figx/4-20 10 65 30],... 'Callback',TIMESTRING) case 'scaleeye' % Turn scale I on/off obj = p1; figh = p2; % figh = get(obj,'Parent'); toggle = get(obj,'checked'); if strcmp(toggle,'on') eyeaxes = findobj('tag','eyeaxes','parent',figh); children = get(eyeaxes,'children'); delete(children) set(obj,'checked','off') elseif strcmp(toggle,'off') eyeaxes = findobj('tag','eyeaxes','parent',figh); ESpacing = findobj('tag','ESpacing','parent',figh); spacing = str2num(get(ESpacing,'string')); axes(eyeaxes) YLim = get(eyeaxes,'Ylim'); Xl = [.35 .65 .5 .5 .35 .65]; Yl = [spacing*2 spacing*2 spacing*2 spacing*1 spacing*1 spacing*1]; line(Xl,Yl,'color',DEFAULT_AXIS_COLOR,'clipping','off',... 'tag','eyeline') text(.5,YLim(2)/23+Yl(1),num2str(spacing,4),... 'HorizontalAlignment','center','FontSize',10,... 'tag','thescale') if strcmp(YAXIS_NEG,'off') text(Xl(2)+.1,Yl(1),'+','HorizontalAlignment','left',... 'verticalalignment','middle') text(Xl(2)+.1,Yl(4),'-','HorizontalAlignment','left',... 'verticalalignment','middle') else text(Xl(2)+.1,Yl(4),'+','HorizontalAlignment','left',... 'verticalalignment','middle') text(Xl(2)+.1,Yl(1),'-','HorizontalAlignment','left',... 'verticalalignment','middle') end if ~isempty(SPACING_UNITS_STRING) text(.5,-YLim(2)/23+Yl(4),SPACING_UNITS_STRING,... 'HorizontalAlignment','center','FontSize',10) end set(obj,'checked','on') end case 'noui' % Plott EEG without ui controls data = p1; % usage: eegplotold(data,Fs,spacing,eloc_file,startpoint,color) [chans,frames] = size(data); nargs = nargin; if nargs < 7 plotcolor = 0; else plotcolor = p6; end if nargs < 6 starts = 0; else starts = p5; end if nargs < 5 eloc_file = DEFAULT_ELOC_FILE; else eloc_file = p4; end if nargs < 4 spacing = 0; else spacing = p3; end if nargs < 3 Fs = 0; else Fs = p2; end if isempty(plotcolor) plotcolor = 0; end if isempty(spacing) spacing = 0; end if isempty(Fs) Fs = 0; end if isempty(starts) starts = 0; end if spacing == 0 spacing = max(max(data')-min(data')); end if spacing == 0 spacing = 1; end; if Fs == 0 Fs = DEFAULT_SAMPLE_RATE; end range = floor(frames/Fs); axhandle = gca; if plotcolor == 0 if DEFAULT_NOUI_PLOT_COLOR == 0 colorord = get(axhandle,'ColorOrder'); plotcolor = colorord(1,:); else plotcolor = DEFAULT_NOUI_PLOT_COLOR; end end if ~isempty(eloc_file) if eloc_file == 0 YLabels = num2str((1:chans)'); elseif ischar('eloc_file') fid = fopen(eloc_file); if fid < 1 error('error opening electrode file') end YLabels = fscanf(fid,'%d %f %f %s',[7 128]); fclose(fid); YLabels = char(YLabels(4:7,:)'); ii = find(YLabels == '.'); YLabels(ii) = ' '; else YLabels = num2str(eloc_file)'; end YLabels = flipud(str2mat(YLabels,' ')); else YLabels = []; end set(axhandle,'xgrid','on','GridLineStyle','-',... 'Box','on','YTickLabel',YLabels,... 'ytick',[0:spacing:chans*spacing],... 'Ylim',[0 (chans+1)*spacing],... 'xtick',[0:Fs:range*Fs],... 'Xlim',[0 frames],... 'XTickLabel',num2str((0:1:range)'+starts)) meandata = mean(data'); axes(axhandle) hold on for i = 1:chans plot(data(chans-i+1,:)-meandata(chans-i+1)+i*spacing,'color',plotcolor) end otherwise error(['Error - invalid eegplotold() parameter: ',data]) end end
github
ZijingMao/baselineeegtest-master
chanproj.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/chanproj.m
7,033
utf_8
3944e3a2db15df4da52766d602a832d0
% chanproj() - make a detailed plot of data returned from plotproj() % for given channel. Returns the data plotted. % Usage: % >> [chandata] = chanproj(projdata,chan); % >> [chandata] = chanproj(projdata,chan,ncomps,framelist,limits,title,colors); % % Inputs: % projdata = data returned from plotproj() % chan = single channel to plot % ncomps = number of component projections in projdata % % Optional: % framelist = data frames to plot per epoch Ex: [1:128] (0|def -> all) % limits = [xmin xmax ymin ymax] (x's in msec) % (0, or y's 0 -> data limits) % title = fairly short single-quoted 'plot title' (0|def -> chan) % colors = file of color codes, 3 chars per line (NB: '.' = space) % (0|def -> white is original data) % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 1996 % Copyright (C) 1996 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 % 11-30-96 Scott Makeig CNL / Salk Institute, La Jolla as plotprojchan.m % 03-19-97 changed var() to diag(cov()) -sm % 03-26-97 fix (== -> =) -sm % 04-03-97 allow framelist to be a col vector, allow 32 traces, fix pvaf, made % ncomps mandatory -sm % 04-04-97 shortened name to chanproj() -sm % 05-20-97 added read of icadefs.m -sm % 11-05-97 disallowed white traces unless default axis color is white -sm & ch % 11-13-97 rm'ed errcode variable -sm % 12-08-97 added LineWidth 2 to data trace, changed whole plot color to BACKCOLOR -sm % 01-25-02 reformated help & license -ad function [chandata] = chanproj(projdata,chan,ncomps,framelist,limits,titl,colorfile) icadefs; % read default MAXPLOTDATACHANS if nargin < 7, colorfile =0; end if nargin < 6, titl = 0; end if nargin < 5, limits = 0; end if nargin < 4, framelist = 0; end if nargin < 3, fprintf('chanproj(): requires at least three arguments.\n\n'); help chanproj return end [chans,framestot] = size(projdata); frames = fix(framestot/(ncomps+1)); if ncomps < 1 | frames*(ncomps+1) ~= framestot, fprintf(... 'chanproj(): data length (%d) not a multiple of ncomps (%d).\n',... framestot,ncomps); return end; if chan> chans, fprintf(... 'chanproj(): specified channel (%d) cannot be > than nchans (%d).\n',... chan,chans); return else chandata = projdata(chan,:); epochs = fix(length(chandata)/frames); end; if epochs > MAXPLOTDATACHANS fprintf(... 'chanproj(): maximum number of traces to plot is %d\n',... MAXPLOTDATACHANS); return end if framestot~=epochs*frames, fprintf('chanproj(): projdata is wrong length.\n'); % exit return end % %%%%%%%%%%%%%%%% Find or read plot limits %%%%%%%%%%%%%%%%%%%%%%%%%%% % if limits==0, xmin=0;xmax=0;ymin=0;ymax=0; else if length(limits)~=4, fprintf( ... 'chanproj():^G limits should be 0 or an array [xmin xmax ymin ymax].\n'); return end; xmin = limits(1); xmax = limits(2); ymin = limits(3); ymax = limits(4); end; if xmin == 0 & xmax == 0, x = [0:frames-1]; xmin = 0; xmax = frames-1; else dx = (xmax-xmin)/(frames-1); x=xmin*ones(1,frames)+dx*(0:frames-1); % construct x-values end; if ymax == 0 & ymin == 0, ymax=max(max(projdata(chan,:))); ymin=min(min(projdata(chan,:))); end % %%%%% Reshape the projdata for plotting and returning to user %%%%%%%%% % chandata=reshape(chandata,frames,epochs); chandata=chandata'; if framelist ==0, framelist = [1:frames]; % default end if size(framelist,2)==1, if size(framelist,1)>1, framelist = framelist'; else fprintf(... 'chanproj(): framelist should be a vector of frames to plot per epoch.\n'); return end end if framelist(1)<1 | framelist(length(framelist))>frames, fprintf('chanproj(): framelist values must be between 1-%d.\n',frames); return else chandata=chandata(:,framelist); end % %%%%%%%%%%%%%%%%%%% Read the color names %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if colorfile ~=0, if ~ischar(colorfile) fprintf('chanproj(); color file name must be a string.\n'); return end cid = fopen(colorfile,'r'); if cid <3, fprintf('chanproj(): cannot open file %s.\n',colorfile); return end; colors = fscanf(cid,'%s',[3 MAXPLOTDATACHANS]); colors = colors'; [r c] = size(colors); for i=1:r for j=1:c if colors(i,j)=='.', colors(i,j)=' '; end; end; end; else % default color order - no yellow colors =['w ';'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 ';'r ';'b ';'g ';'c ';'m ';'r ']; end; % % Make vector of x-values % x=[xmin:(xmax-xmin)/(frames-1):xmax+0.00001]; xmin=x(framelist(1)); xmax=x(framelist(length(framelist))); x = x(framelist(1):framelist(length(framelist))); % %%%%%%%%% Compute percentage of variance accounted for %%%%%%%%%%%%%% % if epochs>1, sumdata = zeros(1,length(framelist)); for e=2:epochs sumdata= sumdata + chandata(e,:); % sum the component projections end sigvar = diag(cov(chandata(1,:)')); difvar = diag(cov(((chandata(1,:)-sumdata)'))); % percent variance accounted for pvaf = round(100.0*(1.0-difvar/sigvar)); end % %%%%%%%%%%%%%%%%%%%%%% Plot traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fprintf('chanproj(): Drawing trace '); for e=1:epochs, fprintf ('%d ',e); set(gcf,'Color',BACKCOLOR); % set the background color to grey set(gca,'Color','none'); % set the axis color = figure color if e==1 plot(x,chandata(e,:),colors(e),'LineWidth',2); % plot it! else plot(x,chandata(e,:),colors(e),'LineWidth',1); % plot it! end hold on; end; fprintf('\n'); % %%%%%%%%%%%%%%%%%%%% Fix axis limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % axis([xmin xmax ymin-0.1*(ymax-ymin) ymax+0.1*(ymax-ymin)]); % %%%%%%%%%%%%%%%%%%% Add title and labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if titl==0, titl = ['channel ' int2str(chan)]; end titl = [ titl ' (p.v.a.f. ' int2str(pvaf) '%)' ]; title(titl); xlabel('Time (msec)'); ylabel('Potential (uV)');
github
ZijingMao/baselineeegtest-master
zica.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/zica.m
3,366
utf_8
0daa4d2de301c49787f0d7e9e070ffb9
% zica() - Z-transform of ICA activations; useful for studying component SNR % % Usage: >> [zact,basesd,maz,mazc,mazf] = zica(activations,frames,baseframes) % % Inputs: % activations - activations matrix produced by runica() % frames - frames per epoch {0|default -> length(activations)} % baseframes - vector of frames in z-defining baseline period {default frames} % % Outputs: % zact - activations z-scaled and reorded in reverse order of max abs % basesd - standard deviations in each activation row (reverse ordered) % maz - maximum absolute z-value for each activation row (rev ordered) % mazc - component indices of the reverse-sorted max abs z-values % (this is the act -> zact reordering) % mazf - frame indices of the max abs z-values (reverse ordered) % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 2-25-98 % % See also: runica() function [zact,basesd,maxabsz,maxc,maxabszf] = zica(activations,frames,baseframes) % Copyright (C) 2-25-98 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 % 3-2-98 added frames variable -sm % 1-25-01 put revsort subfunction in the core of the zica program -ad % 01-25-02 reformated help & license, added link -ad if nargin<1 help zica return end [chans,framestot] = size(activations); if nargin < 3 baseframes = 0; end if nargin < 2 frames = 0; end if frames == 0 frames = framestot; end if baseframes == 0 baseframes = 1:frames end epochs = floor(framestot/frames); if frames*epochs ~= framestot fprintf('zica(): indicated frames does not divide data length.\n'); return end if length(baseframes) < 3 fprintf('\n zica() - too few baseframes (%d).\n',length(baseframes)); help zica return end if min(baseframes) < 1 | max(baseframes) > frames fprintf('\n zica() - baseframes out of range.\n'); help zica return end baselength = length(baseframes); baseact = zeros(epochs*baselength,chans); for e=1:epochs baseact((e-1)*baselength+1:e*baselength,:) = ... matsel(activations,frames,baseframes,0,e)'; end basesd = sqrt(covary(baseact)); zact = activations./(basesd'*ones(1,framestot)); [maxabsz,maxabszf] = sort(abs(zact')); maxabsz = maxabsz(frames,:); maxabszf = maxabszf(frames,:); % % reorder outputs in reverse order of max abs z [maxabsz,maxc] = revsort(maxabsz); zact = zact(maxc,:); basesd = basesd(maxc); maxabszf = maxabszf(maxc); % revsort - reverse sort columns (biggest 1st, ...) function [out,i] = revsort(in) if size(in,1) == 1 in = in'; % make column vector end [out,i] = sort(in); out = out(size(in,1):-1:1,:); i = i(size(in,1):-1:1,:); return;
github
ZijingMao/baselineeegtest-master
rotatematlab.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/rotatematlab.m
180
utf_8
1d0c90aba89a0dd6de52d0081b4ad3dd
% This function calls the Matlab rotate function % This prevents the issue with the function in the private folder of Dipfit function rotatematlab(varargin) rotate(varargin{:});
github
ZijingMao/baselineeegtest-master
del2map.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/del2map.m
3,940
utf_8
0e518801cfa22cd909a1faa406f9cf7d
% del2map() - compute the discrete laplacian of an EEG distribution. % % Usage: % >> [ laplac ] = del2map( map, filename, draw ); % % Inputs: % map - level of activity (size: nbChannel) % filename - filename (.loc file) countaining the coordinates % of the electrodes, or array countaining complex positions % draw - integer, if not nul draw the gradient (default:0) % % Output: % laplac - laplacian map. If the input values are in microV and the % the sensors placement are in mm, the output values are % returned in microV/mm^2. In order to use current density % units like milliamps/mm2, you would need to know skin % conductance information, which as far as we know is not % really known with enough accuracy to be worthwhile. % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % Thanks Ramesh Srinivasan and Tom Campbell for the discussion % on laplacian output units. % 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 [ laplac, sumLaplac2D ] = del2map( map, filename, draw ) if nargin < 2 help del2map; return; end; % process several maps if size(map,2) > 1 if size(map,1) > 1 for index = 1:size(map,2) laplac(:,index) = del2map( map(:,index), filename); end; return; else map = map'; end; end; MAXCHANS = size(map,1); GRID_SCALE = 2*MAXCHANS+5; % Read the channel file % --------------------- if ischar( filename ) | isstruct( filename ) [tmp lb Th Rd] = readlocs(filename); Th = pi/180*Th; % convert degrees to rads [x,y] = pol2cart(Th,Rd); else x = real(filename); y = imag(filename); if exist('draw') == 1 & draw ~= 0 line( [(x-0.01)' (x+0.01)']', [(y-0.01)' (y+0.01)']'); line( [(x+0.01)' (x-0.01)']', [(y-0.01)' (y+0.01)']'); end; end; % locates nearest position of electrod in the grid % ------------------------------------------------ xi = linspace(-0.5,0.5,GRID_SCALE); % x-axis description (row vector) yi = linspace(-0.5,0.5,GRID_SCALE); % y-axis description (row vector) for i=1:MAXCHANS [useless_var horizidx(i)] = min(abs(x(i) - xi)); % find pointers to electrode [useless_var vertidx(i)] = min(abs(y(i) - yi)); % positions in Zi end; % Compute gradient % ---------------- sumLaplac2D = zeros(GRID_SCALE, GRID_SCALE); for i=1:size(map,2) [Xi,Yi,Zi] = griddata(y,x,map(:,i),yi',xi, 'v4'); % interpolate data laplac2D = del2(Zi); positions = horizidx + (vertidx-1)*GRID_SCALE; laplac(:,i) = laplac2D(positions(:)); sumLaplac2D = sumLaplac2D + laplac2D; % Draw gradient % ------------- if exist('draw') == 1 & draw ~= 0 if size(map,2) > 1 subplot(ceil(sqrt(size(map,2))), ceil(sqrt(size(map,2))), i); end; plot(y, x, 'x', 'Color', 'black', 'markersize', 5); hold on contour(Xi, Yi, laplac2D); hold off; %line( [(x-0.01)' (x+0.01)']', [(y-0.01)' (y+0.01)']', 'Color','black'); %line( [(x+0.01)' (x-0.01)']', [(y-0.01)' (y+0.01)']', 'Color','black'); title( int2str(i) ); end; end; % return;
github
ZijingMao/baselineeegtest-master
readlocsold.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/readlocsold.m
3,560
utf_8
55da540b1b04dfe07379075941625ac1
% readlocsold() - Read electrode locations file in style of topoplot() or headplot(). % Output channel information is ordered by channel numbers. % % Usage: >> [nums labels th r x y] = readlocsold(locfile);% {default, polar 2-D} % >> [nums labels th r x y] = readlocsold(locfile,'polar'); % 2-D % >> [nums labels x y z] = readlocsold(locfile,'spherical'); % 3-D % >> [nums labels x y z] = readlocsold(locfile,'cartesian'); % 3-D % Input: % locfile = 'filename' of electrode location file. % loctype = File type:'polar' 2-D {default}. See >> topoplot example % 'spherical' 3-D. See >> headplot example % 'cartesian' 3-D. See >> headplot cartesian % Outputs: % nums = ordered channel numbers (from locfile) % labels = Matrix of 4-char channel labels (nchannels,4) % 2-D: r,th = polar coordinates of each electrode (th in radians) % x,y = 2-D Cartesian coordinates (from pol2cart()) % 3-D: x,y,z = 3-D Cartesian coordinates (normalized, |x,y,z| = 1) % Scott Makeig, CNL / Salk Institute, La Jolla CA 3/01 % code from topoplot() function [channums,labels,o1,o2,o3,o4] = readlocsold(loc_file,loctype) verbose = 0; if nargin<2 loctype = 'polar'; % default file type end icadefs if nargin<1 loc_file = DEFAULT_ELOC; end fid = fopen(loc_file); if fid<1, fprintf('readlocsold(): cannot open electrode location file (%s).\n',loc_file); return end if strcmp(loctype,'spherical')| strcmp(loctype,'polar') A = fscanf(fid,'%d %f %f %s',[7 Inf]); elseif strcmp(loctype,'cartesian') A = fscanf(fid,'%d %f %f %f %s',[8 Inf]); else fprintf('readlocsold(): unknown electrode location file type %s.\n',loctype); return end fclose(fid); A = A'; channums = A(:,1); [channums csi] = sort(channums); if strcmp(loctype,'cartesian') labels = setstr(A(csi,5:8)); else labels = setstr(A(csi,4:7)); end idx = find(labels == '.'); % some labels have dots labels(idx) = setstr(abs(' ')*ones(size(idx))); % replace them with spaces badchars = find(double(labels)<32|double(labels)>127); if ~isempty(badchars) fprintf(... 'readlocsold(): Bad label(s) read - Each label must have 4 chars (. => space)\n'); return end for c=1:length(channums) if labels(c,3)== ' ' & labels(c,4)== ' ' labels(c,[2 3]) = labels(c,[1 2]); labels(c,1) = ' '; % move 1|2-letter labels to middle of string end end if strcmp(loctype,'polar') th = pi/180*A(csi,2); % convert degrees to radians rad = A(csi,3); o2 = rad; o1 = th; [x,y] = pol2cart(th,rad); % transform from polar to cartesian coordinates o3 = x; o4 = y; elseif strcmp(loctype,'spherical') th = pi/180*A(csi,2); phi = pi/180*A(csi,3); x = sin(th).*cos(phi); y = sin(th).*sin(phi); z = cos(th); o1 = x; o2 =y; o3 = z; elseif strcmp(loctype,'cartesian') x = A(csi,2); y = A(csi,3); z = A(csi,4); dists = sqrt(x.^2+y.^2+z.^2); x = y./dists; % normalize [x y z] vector lengths to 1 y = y./dists; z = z./dists; o1 = x; o2 =y; o3 = z; end if verbose fprintf('Location data for %d electrodes read from file %s.\n',... size(A,1),loc_file); end if nargout<1 fprintf('\n'); for c=1:length(channums) if strcmp(loctype,'polar') fprintf(' %d %s %4.3f %4.3f %4.3f %4.3f\n',... channums(c),labels(c,:),rad(c),th(c),x(c),y(c)); end end fprintf('\n'); o1 = []; o2=[]; o3=[]; o4=[]; labels = []; end
github
ZijingMao/baselineeegtest-master
crossfreq.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/crossfreq.m
15,218
utf_8
a9ff87c9098280c7729af6c878a8fd45
% crossfreq() - compute cross-frequency coherences. Power of first input % correlation with phase of second. % % Usage: % >> crossfreq(x,y,srate); % >> [coh,timesout,freqsout1,freqsout2,cohboot] ... % = crossfreq(x,y,srate,'key1', 'val1', 'key2', val2' ...); % Inputs: % x = [float array] 2-D data array of size (times,trials) or % 3-D (1,times,trials) % y = [float array] 2-D or 3-d data array % srate = data sampling rate (Hz) % % Most important optional inputs % 'mode' = ['amp_amp'|'amp_phase'|'phase_phase'] correlation mode % is either amplitude-amplitude ('amp_amp'), amplitude % and phase ('amp_phase') and phase-phase ('phase_phase'). % Default is 'amp_phase'. % 'method' = ['mod'|'corrsin'|'corrcos'] modulation method ('mod') % or correlation of amplitude with sine or cosine of % angle (see ref). % 'freqs' = [min max] frequency limits. Default [minfreq 50], % minfreq being determined by the number of data points, % cycles and sampling frequency. Use 0 for minimum frequency % to compute default minfreq. You may also enter an % array of frequencies for the spectral decomposition % (for FFT, closest computed frequency will be returned; use % 'padratio' to change FFT freq. resolution). % 'freqs2' = [float array] array of frequencies for the second % argument. 'freqs' is used for the first argument. % By default it is the same as 'freqs'. % 'wavelet' = 0 -> Use FFTs (with constant window length) { Default } % = >0 -> Number of cycles in each analysis wavelet % = [cycles expfactor] -> if 0 < expfactor < 1, the number % of wavelet cycles expands with frequency from cycles % If expfactor = 1, no expansion; if = 0, constant % window length (as in FFT) {default wavelet: 0} % = [cycles array] -> cycle for each frequency. Size of array % must be the same as the number of frequencies % {default cycles: 0} % 'wavelet2' = same as 'wavelet' for the second argument. Default is % same as cycles. Note that if the lowest frequency for X % and Y are different and cycle is [cycles expfactor], it % may result in discrepencies in the number of cycles at % the same frequencies for X and Y. % 'ntimesout' = Number of output times (int<frames-winframes). Enter a % negative value [-S] to subsample original time by S. % 'timesout' = Enter an array to obtain spectral decomposition at % specific time values (note: algorithm find closest time % point in data and this might result in an unevenly spaced % time array). Overwrite 'ntimesout'. {def: automatic} % 'tlimits' = [min max] time limits in ms. % % Optional Detrending: % 'detrend' = ['on'|'off'], Linearly detrend each data epoch {'off'} % 'rmerp' = ['on'|'off'], Remove epoch mean from data epochs {'off'} % % Optional FFT/DFT Parameters: % 'winsize' = If cycles==0: data subwindow length (fastest, 2^n<frames); % If cycles >0: *longest* window length to use. This % determines the lowest output frequency. Note that this % parameter is overwritten if the minimum frequency has been set % manually and requires a longer time window {~frames/8} % 'padratio' = FFT-length/winframes (2^k) {2} % Multiplies the number of output frequencies by dividing % their spacing (standard FFT padding). When cycles~=0, % frequency spacing is divided by padratio. % 'nfreqs' = number of output frequencies. For FFT, closest computed % frequency will be returned. Overwrite 'padratio' effects % for wavelets. Default: use 'padratio'. % 'freqscale' = ['log'|'linear'] frequency scale. Default is 'linear'. % Note that for obtaining 'log' spaced freqs using FFT, % closest correspondant frequencies in the 'linear' space % are returned. % 'subitc' = ['on'|'off'] subtract stimulus locked Inter-Trial Coherence % (ITC) from x and y. This computes the 'intrinsic' coherence % x and y not arising from common synchronization to % experimental events. See notes. {default: 'off'} % 'itctype' = ['coher'|'phasecoher'] For use with 'subitc', see timef() % for more details {default: 'phasecoher'}. % 'subwin' = [min max] sub time window in ms (this windowing is % performed after the spectral decomposition). % 'lowmem' = ['on'|'off'] compute frequency, by frequency to save % memory. Default 'off'. % % Optional Bootstrap Parameters: % 'alpha' = If non-0, compute two-tailed bootstrap significance prob. % level. Show non-signif. output values as green. {0} % 'naccu' = Number of bootstrap replications to accumulate. Note that % naccu might be automatically increate depending on the % value for 'alpha' {250} % 'baseboot' = Bootstrap baseline subtract time window in ms. If only one % is entered, baseline is from beginning of data to this % value. Note: you must specify 'tlimits' for bootstrap {0} % 'boottype' = ['times'|'timestrials'|'trials'] Bootstrap type: Either % shuffle windows ('times') or windows and trials ('timestrials') % or trials only using a separate bootstrap for each time window % ('trials'). Option 'times' is not recommended but requires less % memory {default 'timestrials'} % 'rboot' = Input bootstrap coherence limits (e.g., from crossfreq()) % The bootstrap type should be identical to that used % to obtain the input limits. {default: compute from data} % % Optional Plotting Parameters: % 'title' = Optional figure title {none} % 'vert' = [times_vector] plot vertical dashed lines at specified % times in ms. Can also be a cell array specifying line aspect. % I.e. { { 0 'color' 'b' 'linewidth' 2 } {1000 'color' 'r' }} % would draw two lines, one blue thick line at latency 0 and one % thin red line at latency 1000. % 'newfig' = ['on'|'off'] Create new figure for difference plots {'on'} % % Outputs: % crossfcoh = Matrix (nfreqs1,nfreqs2,timesout) of coherence (complex). % Use 20*log(abs(crossfcoh)) to vizualize log spectral diffs. % timesout = Vector of output times (window centers) (ms). % freqsout1 = Vector of frequency bin centers for first argument (Hz). % freqsout2 = Vector of frequency bin centers for second argument (Hz). % cohboot = Matrix (nfreqs1,nfreqs2,2) of p-value coher signif. % values. if 'boottype' is 'trials', % (nfreqs1,nfreqs2,timesout,2) % alltfX = single trial spectral decomposition of X % alltfY = single trial spectral decomposition of Y % % Author: Arnaud Delorme & Scott Makeig, SCCN/INC, UCSD 2003- % % Ref: Testing for Nested Oscilations (2008) J Neuro Methods 174(1):50-61 % % See also: timefreq(), crossf() % Copyright (C) 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 [crossfcoh, timesout1, freqs1, freqs2, cohboot, alltfX, alltfY] = ... crossfreq(X, Y, srate, varargin); if nargin < 1 help crossfreq; return; end; % deal with 3-D inputs % -------------------- if ndims(X) == 3, X = reshape(X, size(X,2), size(X,3)); end; if ndims(Y) == 3, Y = reshape(Y, size(Y,2), size(Y,3)); end; frame = size(X,2); g = finputcheck(varargin, ... { 'alpha' 'real' [0 0.2] []; 'baseboot' 'float' [] 0; 'boottype' 'string' {'times','trials','timestrials'} 'timestrials'; 'detrend' 'string' {'on','off'} 'off'; 'freqs' 'real' [0 Inf] [0 srate/2]; 'freqs2' 'real' [0 Inf] []; 'freqscale' 'string' { 'linear','log' } 'linear'; 'itctype' 'string' {'phasecoher','phasecoher2','coher'} 'phasecoher'; 'nfreqs' 'integer' [0 Inf] []; 'lowmem' 'string' {'on','off'} 'off'; 'mode' 'string' { 'amp_amp','amp_phase','phase_phase' } 'amp_phase'; 'method' 'string' { 'mod','corrsin','corrcos' } 'mod'; 'naccu' 'integer' [1 Inf] 250; 'newfig' 'string' {'on','off'} 'on'; 'padratio' 'integer' [1 Inf] 2; 'rmerp' 'string' {'on','off'} 'off'; 'rboot' 'real' [] []; 'subitc' 'string' {'on','off'} 'off'; 'subwin' 'real' [] []; ... 'timesout' 'real' [] []; ... 'ntimesout' 'integer' [] 200; ... 'tlimits' 'real' [] [0 frame/srate]; 'title' 'string' [] ''; 'vert' { 'real','cell' } [] []; 'wavelet' 'real' [0 Inf] 0; 'wavelet2' 'real' [0 Inf] []; 'winsize' 'integer' [0 Inf] max(pow2(nextpow2(frame)-3),4) }, 'crossfreq'); if isstr(g), error(g); end; % more defaults % ------------- if isempty(g.wavelet2), g.wavelet2 = g.wavelet; end; if isempty(g.freqs2), g.freqs2 = g.freqs; end; % remove ERP if necessary % ----------------------- X = squeeze(X); Y = squeeze(Y);X = squeeze(X); trials = size(X,2); if strcmpi(g.rmerp, 'on') X = X - repmat(mean(X,2), [1 trials]); Y = Y - repmat(mean(Y,2), [1 trials]); end; % perform timefreq decomposition % ------------------------------ [alltfX freqs1 timesout1] = timefreq(X, srate, 'ntimesout', g.ntimesout, 'timesout', g.timesout, 'winsize', g.winsize, ... 'tlimits', g.tlimits, 'detrend', g.detrend, 'itctype', g.itctype, ... 'subitc', g.subitc, 'wavelet', g.wavelet, 'padratio', g.padratio, ... 'freqs', g.freqs, 'freqscale', g.freqscale, 'nfreqs', g.nfreqs); [alltfY freqs2 timesout2] = timefreq(Y, srate, 'ntimesout', g.ntimesout, 'timesout', g.timesout, 'winsize', g.winsize, ... 'tlimits', g.tlimits, 'detrend', g.detrend, 'itctype', g.itctype, ... 'subitc', g.subitc, 'wavelet', g.wavelet2, 'padratio', g.padratio, ... 'freqs', g.freqs2, 'freqscale', g.freqscale, 'nfreqs', g.nfreqs); % check time limits % ----------------- if ~isempty(g.subwin) ind1 = find(timesout1 > g.subwin(1) & timesout1 < g.subwin(2)); ind2 = find(timesout2 > g.subwin(1) & timesout2 < g.subwin(2)); alltfX = alltfX(:, ind1, :); alltfY = alltfY(:, ind2, :); timesout1 = timesout1(ind1); timesout2 = timesout2(ind2); end; if length(timesout1) ~= length(timesout2) | any( timesout1 ~= timesout2) disp('Warning: Time points are different for X and Y. Use ''timesout'' to specify common time points'); disp('Searching for common points'); [vals ind1 ind2 ] = intersect_bc(timesout1, timesout2); if length(vals) < 10, error('Less than 10 common data points'); end; timesout1 = vals; timesout2 = vals; alltfX = alltfX(:, ind1, :); alltfY = alltfY(:, ind2, :); end; % scan accross frequency and time % ------------------------------- if isempty(g.alpha) disp('Warning: if significance mask is not applied, result might be slightly') disp('different (since angle is not made uniform and amplitude interpolated)') end; cohboot =[]; for find1 = 1:length(freqs1) for find2 = 1:length(freqs2) for ti = 1:length(timesout1) % get data % -------- tmpalltfx = squeeze(alltfX(find1,ti,:)); tmpalltfy = squeeze(alltfY(find2,ti,:)); if ~isempty(g.alpha) tmpalltfy = angle(tmpalltfy); tmpalltfx = abs( tmpalltfx); [ tmp cohboot(find1,find2,ti,:) newamp newangle ] = ... bootcircle(tmpalltfx, tmpalltfy, 'naccu', g.naccu); crossfcoh(find1,find2,ti) = sum ( newamp .* exp(j*newangle) ); else tmpalltfy = angle(tmpalltfy); tmpalltfx = abs( tmpalltfx); if strcmpi(g.method, 'mod') crossfcoh(find1,find2,ti) = sum( tmpalltfx .* exp(j*tmpalltfy) ); elseif strcmpi(g.method, 'corrsin') tmp = corrcoef( sin(tmpalltfy), tmpalltfx); crossfcoh(find1,find2,ti) = tmp(2); else tmp = corrcoef( cos(tmpalltfy), tmpalltfx); crossfcoh(find1,find2,ti) = tmp(2); end; end; end; end; end;
github
ZijingMao/baselineeegtest-master
upgma.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/upgma.m
3,664
utf_8
2bbad43f658a73df320ccccb6256d938
% UPGMA: Unweighted pair-group hierarchical cluster analysis of a distance % matrix. Produces plot of dendrogram. To bootstrap cluster support, % see cluster(). % % Usage: [topology,support] = upgma(dist,{labels},{doplot},{fontsize}) % % dist = [n x n] symmetric distance matrix. % labels = optional [n x q] matrix of group labels for dendrogram. % doplot = optional boolean flag indicating, if present and true, that % graphical dendrogram output is to be produced % [default = true]. % fontsize = optional font size for labels [default = 10]. % ----------------------------------------------------------------------- % topology = [(n-1) x 4] matrix summarizing dendrogram topology: % col 1 = 1st OTU/cluster being grouped at current step % col 2 = 2nd OTU/cluster % col 3 = ID of cluster being produced % col 4 = distance at node % support = [(n-2) x (n-1)] matrix, with one row for all but the base % node, specifying group membership (support) at each node. % % To boostrap cluster support, see cluster(). % RE Strauss, 5/27/96 % 9/7/99 - miscellaneous changes for Matlab v5. % 9/24/01 - check diagonal elements against eps rather than zero. % 3/14/04 - changed 'suppress' flag to 'doplot'. function [topology,support] = upgma(dist,labels,doplot,fontsize) if (nargin < 2) labels = []; end; if (nargin < 3) doplot = []; end; if (nargin < 4) fontsize = []; end; suprt = 0; if (nargout > 1) suprt = 1; end; if (isempty(doplot)) doplot = 1; end; [n,p] = size(dist); if (n~=p | any(diag(dist)>eps)) dist error(' UPGMA: input matrix is not a distance matrix.'); end; if (~isempty(labels)) if (size(labels,1)~=n) error(' UPGMA: numbers of taxa and taxon labels do not match.'); end; end; clstsize = ones(1,n); % Number of elements in clusters/otus id = 1:n; % Cluster IDs topology = zeros(n-1,4); % Output dendrogram-topology matrix plug = 10e6; dist = dist + eye(n)*plug; % Replace diagonal with plugs for step = 1:(n-1) % Clustering steps min_dist = min(dist(:)); % Find minimum pairwise distance [ii,jj] = find(dist==min_dist); % Find location of minimum k = 1; % Use first identified minimum while (ii(k)>jj(k)) % for which i<j k = k+1; if k > length(ii) ,keyboard;end; end; i = ii(k); j = jj(k); if (id(i)<id(j)) topology(step,:) = [id(i) id(j) n+step min_dist]; else topology(step,:) = [id(j) id(i) n+step min_dist]; end; id(i) = n+step; dist(i,j) = plug; dist(j,i) = plug; new_clstsize = clstsize(i) + clstsize(j); alpha_i = clstsize(i) / new_clstsize; alpha_j = clstsize(j) / new_clstsize; clstsize(i) = new_clstsize; for k = 1:n % For all other clusters/OTUs, if (k~=i & k~=j) % adjust distances to new cluster dist(k,i) = alpha_i * dist(k,i) + alpha_j * dist(k,j); dist(i,k) = alpha_i * dist(i,k) + alpha_j * dist(j,k); dist(k,j) = plug; dist(j,k) = plug; end; end; end; % for step if (doplot) % Plot dendrogram dendplot(topology,labels,fontsize); end; if (suprt) % Specify group membership at nodes support = clstsupt(topology); end; return;
github
ZijingMao/baselineeegtest-master
mapcorr.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/mapcorr.m
6,842
utf_8
4dc2783fce24c7d3b647bb2d2cac4436
% mapcorr() - Find matching rows in two matrices and their corrs. % Uses the Hungarian (default), VAM, or maxcorr assignment methods. % (Follow with matperm() to permute and sign x -> y). % % Finds correlation of maximum common subset of channels (using % channel location files to match channel labels.) Thus, number % of channels can differ in x and y. % % Usage: % >> [corr,indx,indy,corrs] = matcorr(x,y,ch1,ch2); % >> [corr,indx,indy,corrs] = matcorr(x,y,ch1,ch2,rmmean,method,weighting); % % Inputs: % x = first input matrix. Row are difference components and columns % the channels for these components. % y = matrix with same number of columns (channels) as x % ch1 = channel locations file for x % ch2 = channel locations file for y % % Optional inputs: % rmmean = When present and non-zero, remove row means prior to correlation % {default: 0} % method = Method used to find assignments. % 0= Hungarian Method - maximize sum of abs corrs {default: 2} % 1= Vogel's Assignment Method -find pairs in order of max contrast % 2= Max Abs Corr Method - find pairs in order of max abs corr % Note that the methods 0 and 1 require matrices to be square. % weighting = An optional weighting matrix size(weighting) = size(corrs) that % weights the corrs matrix before pair assignment {def: 0/[]->ones()} % Outputs: % corr = a column vector of correlation coefficients between % best-correlating rows of matrice x and y % indx = a column vector containing the index of the maximum % abs-correlated x row in descending order of abs corr % (no duplications) % indy = a column vector containing the index of the maximum % abs-correlated row of y in descending order of abs corr % (no duplications) % corrs = an optional square matrix of row-correlation coefficients % between matrices x and y % % Note: outputs are sorted by abs(corr) % % Authors: Scott Makeig & Sigurd Enghoff, SCCN/INC/UCSD, La Jolla, 11-30-96 % Copyright (C) 11-30-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 % 2007/03/20 02:33:48 arno, Andreas fix % 2003/09/04 23:21:06 scott, changed default matching method to Max Abs Corr % 04-22-99 Re-written using VAM by Sigurd Enghoff, CNL/Salk % 04-30-99 Added revision of algorthm loop by SE -sm % 05-25-99 Added Hungarian method assignment by SE % 06-15-99 Maximum correlation method reinstated by SE % 08-02-99 Made order of outpus match help msg -sm % 02-16-00 Fixed order of corr output under VAM added method explanations, % and returned corr signs in abs max method -sm % 01-25-02 reformated help & license, added links -ad % Uses function hungarian.m function [corr,indx,indy,corrs] = mapcorr(x,y,ch1,ch2,rmmean,method,weighting) % if nargin < 4 help matcorr return end if nargin < 6 method = 2; % default: Max Abs Corr - select successive best abs(corr) pairs end [m,n] = size(x); [p,q] = size(y); m = min(m,p); if m~=n | p~=q if nargin>5 & method~=2 fprintf('matcorr(): Matrices are not square: using max abs corr method (2).\n'); end method = 2; % Can accept non-square matrices end if nargin < 5 | isempty(rmmean) rmmean = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if rmmean x = x - mean(x')'*ones(1,n); % optionally remove means y = y - mean(y')'*ones(1,n); end for i = 1:m for j = 1:p corrs(i,j) = compcorr(x(i,:)',ch1,y(j,:)',ch2); end end %dx = sum(x'.^2); %dy = sum(y'.^2); %dx(find(dx==0)) = 1; %dy(find(dy==0)) = 1; %corrs = x*y'./sqrt(dx'*dy); if nargin > 6 & ~isempty(weighting) & norm(weighting) > 0, if any(size(corrs) ~= size(weighting)) fprintf('matcorr(): weighting matrix size must match that of corrs\n.') return else corrs = corrs.*weighting; end end cc = abs(corrs); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch method case 0 ass = hungarian(-cc); % Performs Hungarian algorithm matching idx1 = sub2ind(size(cc),ass,1:m); [dummy idx2] = sort(-cc(idx1)); corr = corrs(idx1); corr = corr(idx2)'; indy = [1:m]'; indx = ass(idx2)'; indy = indy(idx2); case 1 % Implements the VAM assignment method indx = zeros(m,1); indy = zeros(m,1); corr = zeros(m,1); for i=1:m, [sx ix] = sort(cc); % Looks for maximum salience along a row/column [sy iy] = sort(cc'); % rather than maximum correlation. [sxx ixx] = max(sx(end,:)-sx(end-1,:)); [syy iyy] = max(sy(end,:)-sy(end-1,:)); if sxx == syy if sxx == 0 & syy == 0 [sxx ixx] = max((sx(end,:)-sx(end-1,:)) .* sx(end,:)); [syy iyy] = max((sy(end,:)-sy(end-1,:)) .* sy(end,:)); else sxx = sx(end,ixx); % takes care of identical vectors syy = sy(end,iyy); % and zero vectors end end if sxx > syy indx(i) = ix(end,ixx); indy(i) = ixx; else indx(i) = iyy; indy(i) = iy(end,iyy); end cc(indx(i),:) = -1; cc(:,indy(i)) = -1; end i = sub2ind(size(corrs),indx,indy); corr = corrs(i); [tmp j] = sort(-abs(corr)); % re-sort by abs(correlation) corr = corr(j); indx = indx(j); indy = indy(j); case 2 % match successive max(abs(corr)) pairs indx = zeros(size(cc,1),1); indy = zeros(size(cc,1),1); corr = zeros(size(cc,1),1); for i = 1:size(cc,1) [tmp j] = max(cc(:)); % [corr(i) j] = max(cc(:)); [indx(i) indy(i)] = ind2sub(size(cc),j); corr(i) = corrs(indx(i),indy(i)); cc(indx(i),:) = -1; % remove from contention cc(:,indy(i)) = -1; end otherwise error('Unknown method'); end function corr = compcorr(a1,ch1,a2,ch2) n1 = length(a1); n2 = length(a2); %if n1 < n2 cnt = 0; corr = 0; for i = 1:n1 for j = 1:n2 if strcmp(ch1(i).labels,ch2(j).labels) cnt = cnt+1; b1(cnt,1) = a1(i); b2(cnt,1) = a2(j); end end end b1 = b1 / norm(b1); b2 = b2 / norm(b2); corr = b1'*b2;
github
ZijingMao/baselineeegtest-master
uniqe_cell_string.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/uniqe_cell_string.m
637
utf_8
4db73f96310fef763282d550920e9d65
function uniqueStrings = uniqe_cell_string(c) % uniqe string from a cell-array containing only strings, ignores all % non-strings. nonStringCells = []; for i=1:length(c) % remove non-string cells if ~strcmp(class(c{i}),'char') nonStringCells = [nonStringCells i]; end; end; c(nonStringCells) = []; uniqueStrings = {}; for i=1:length(c) % remove non-string cells if ~isAlreadyEncountered(c{i}, uniqueStrings); uniqueStrings{end+1} = c{i}; end; end; function result = isAlreadyEncountered(s, u) result = false; for i=1:length(u) if strcmp(u{i}, s) result = true; end; end;
github
ZijingMao/baselineeegtest-master
make_timewarp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/make_timewarp.m
9,686
utf_8
248333ed7e02db8061c3f52067e368ff
% make_timewarp() - Select a subset of epochs containing a given event sequence, and return % a matrix of latencies for time warping the selected epochs to a common % timebase in newtimef(). Events in the given sequence may be further % restricted to those with specified event field values. % Usage: % >> timeWarp = make_timewarp(EEG, eventSequence, 'key1',value1, % 'key2',value2,...); % % Inputs: % EEG - dataset structure % eventSequence - cell array containing a sequence of event type strings. % For example, to select epochs containing a 'movement Onset' % event followed by a 'movement peak', use % {'movement Onset' 'movement peak'} % The output timeWarp matrix will contain the epoch latencies % of the two events for each selected epoch. % % Optional inputs (in 'key', value format): % 'baselineLatency' - (ms) the minimum acceptable epoch latency for the first % event in the sequence {default: 0} % 'eventConditions' - cell array specifying conditions on event fields. % For example, for a sequence consisting of two % events with (velocity) fields vx and vy, use % {vx>0' 'vx>0 && vy<1'} % To accept events unconditionally, use empty strings, % for example {'vx>0','',''} {default: no conditions} % 'maxSTDForAbsolute' - (positive number of std. devs.) Remove epochs containing events % whose latencies are more than this number of standard deviations % from the mean in the selected epochs. {default: Inf -> no removal} % 'maxSTDForRelative' - (positive number of std. devs.) Remove epochs containing inter-event % latency differences larger or smaller than this number of standard deviations % from the mean in the selected epochs. {default: Inf -> no removal} % Outputs: % timeWarp - a structure with latencies (time-warp matrix with fields % timeWarp.latencies - an (N, M) timewarp matrix for use in newtimef() % where N = number of selected epochs containing the specified sequence, % M = number of events in specified event sequence. % timeWarp.epochs - a (1, M) vector giving the index of epochs with the % specified sequence. Only these epochs should be passed to newtimef(). % timeWarp.eventSequence - same as the 'eventSequence' input variable. % Example: % % Create a timewarp matrix for a sequence of events, first an event of type 'movement Onset' followed by % % a 'movement peak' event, with event fields vx and vy: % % >> timeWarp = make_timewarp(EEG, {'movement Onset' 'movement% peak'},'baselineLatency', 0 ... % ,'eventConditions', {'vx>0' 'vx>0 && vy<1'}); % % % To remove events with latencies more than 3 standard deviations from the mean OR 2 std. devs. % % from the mean inter-event difference: % % >> timeWarp = make_timewarp(EEG, {'movement Onset' 'movement peak'},'baselineLatency', 0, ... % 'eventConditions', {'vx>0' 'vx>0 && vy<1'},'maxSTDForAbsolute', 3,'maxSTDForRelative', 2); % % Author: Nima Bigdely Shamlo, SCCN/INC/UCSD, 2008 % See also: show_events(), newtimef() function timeWarpStructure = make_timewarp(EEG, eventSequence, varargin) inputKeyValues = finputcheck(varargin, ... {'baselineLatency' 'real' [] 0; ... 'eventConditions' 'cell' {} {} ; ... 'maxSTDForAbsolute' 'real' [0 Inf] Inf; ... 'maxSTDForRelative' 'real' [0 Inf] Inf... }); baselineLatency = []; maxSTDForAbsolute = 0; maxSTDForRelative = 0; eventConditions = []; % place key values into function workspace variables inputKeyValuesFields = fieldnames(inputKeyValues); for i=1:length(inputKeyValuesFields) eval([inputKeyValuesFields{i} '= inputKeyValues.' inputKeyValuesFields{i} ';']); end; if length(eventConditions) < length(eventSequence) for i = (length(eventConditions)+1):length(eventSequence) eventConditions{i} = ''; end; end; epochsIsAcceptable = ones(1, length(EEG.epoch)); for epochNumber = 1:length(EEG.epoch) eventNameID = 1; minimumLatency = baselineLatency; timeWarp{epochNumber} = []; while eventNameID <= length(eventSequence) % go tthrought event names and find the event that comes after a certain event with correct type and higher latency firstLatency = eventsOfCertainTypeAfterCertainLatencyInEpoch(EEG.epoch(epochNumber), eventSequence{eventNameID}, minimumLatency, eventConditions{eventNameID}); if isempty(firstLatency) % means there were no events, so the epoch is not acceptable break; else timeWarp{epochNumber} = [timeWarp{epochNumber}; firstLatency]; minimumLatency = firstLatency; eventNameID = eventNameID + 1; end; end; if length(timeWarp{epochNumber}) < length(eventSequence) epochsIsAcceptable(epochNumber) = false; end; end; acceptableEpochs = find(epochsIsAcceptable); if isempty(acceptableEpochs) timeWarp = {}; % no epoch meet the criteria else timeWarp = cell2mat(timeWarp(acceptableEpochs)); rejectedEpochesBasedOnLateny = union_bc(rejectEventsBasedOnAbsoluteLatency(timeWarp), rejectEventsBasedOnRelativeLatency(timeWarp)); timeWarp(:,rejectedEpochesBasedOnLateny) = []; acceptableEpochs(rejectedEpochesBasedOnLateny) = []; end; % since latencies and accepted epochs always have to be together, we put them in one structure timeWarpStructure.latencies = timeWarp'; % make it suitable for newtimef() if isempty(timeWarpStructure.latencies) % when empty, it becomes a {} instead of [], so we change it to [] timeWarpStructure.latencies = []; end; timeWarpStructure.epochs = acceptableEpochs; timeWarpStructure.eventSequence = eventSequence; function rejectedBasedOnLateny = rejectEventsBasedOnRelativeLatency(timeWarp) % remeve epochs in which the time warped event is further than n % standard deviations to mean of latency distance between events timeWarpDiff = diff(timeWarp); rejectedBasedOnLateny = []; for eventNumber = 1:size(timeWarpDiff, 1) rejectedBasedOnLateny = [rejectedBasedOnLateny find(abs(timeWarpDiff(eventNumber, :)- mean(timeWarpDiff(eventNumber, :))) > maxSTDForRelative * std(timeWarpDiff(eventNumber, :)))]; end; rejectedEpochesBasedOnLateny = unique_bc(rejectedBasedOnLateny); end function rejectedBasedOnLateny = rejectEventsBasedOnAbsoluteLatency(timeWarp) % remeve instances in which the time warped event is further than n % standard deviations to mean rejectedBasedOnLateny = []; for eventNumber = 1:size(timeWarp, 1) rejectedBasedOnLateny = [rejectedBasedOnLateny find(abs(timeWarp(eventNumber, :)- mean(timeWarp(eventNumber, :))) > maxSTDForAbsolute* std(timeWarp(eventNumber, :)))]; end; rejectedEpochesBasedOnLateny = unique_bc(rejectedBasedOnLateny); end function [firstLatency resultEventNumbers] = eventsOfCertainTypeAfterCertainLatencyInEpoch(epoch, certainEventType, certainLatency, certainCondition) resultEventNumbers = []; firstLatency = []; % first event latency that meets the critria for eventNumber = 1:length(epoch.eventtype) % if strcmp(certainEventType, epoch.eventtype(eventNumber)) && epoch.eventlatency{eventNumber} >= certainLatency && eventMeetsCondition(epoch, eventNumber, certainCondition) if eventIsOfType(epoch.eventtype(eventNumber), certainEventType) && epoch.eventlatency{eventNumber} >= certainLatency && eventMeetsCondition(epoch, eventNumber, certainCondition) resultEventNumbers = [resultEventNumbers eventNumber]; if isempty(firstLatency) firstLatency = epoch.eventlatency{eventNumber}; end; end; end; end function result = eventMeetsCondition(epoch, eventNumber, condition) if strcmp(condition,'') || strcmp(condition,'true') result = true; else % get the name thatis before themfor field in the epoch, then remove 'event' name epochField = fieldnames(epoch); for i=1:length(epochField) epochField{i} = strrep(epochField{i},'event',''); % remove event from the beginning of field names condition = strrep(condition, epochField{i}, ['cell2mat(epoch.event' epochField{i} '(' num2str(eventNumber) '))' ]); end; result = eval(condition); end; end function result = eventIsOfType(eventStr, types) % if events are numbers, turn them into strings before comparison if ischar(types) if iscell(eventStr) && isnumeric(cell2mat(eventStr)) eventStr = num2str(cell2mat(eventStr)); end; result = strcmp(eventStr, types); else % it must be a cell of strs result = false; for i=1:length(types) result = result || strcmp(eventStr, types{i}); end; end; end end
github
ZijingMao/baselineeegtest-master
fieldtrip2eeglab.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/fieldtrip2eeglab.m
1,269
utf_8
442a73a6c0d6090b20bc0444bad3aba7
% load data file ('dataf') preprocessed with fieldtrip % and show in eeglab viewer % % This function is provided as is. It only works for some specific type of % data. This is a simple function to help the developer and by no mean % an all purpose function. function [EEG] = fieldtrip2eeglab(dataf) [ALLEEG EEG CURRENTSET ALLCOM] = eeglab; if exist(dataf,'file') load(dataf) end % load chanlocs.mat % EEG.chanlocs = chanlocs; EEG.chanlocs = []; for i=1:size(data.trial,2) EEG.data(:,:,i) = single(data.trial{i}); end EEG.setname = dataf; %data.cfg.dataset; EEG.filename = ''; EEG.filepath = ''; EEG.subject = ''; EEG.group = ''; EEG.condition = ''; EEG.session = []; EEG.comments = 'preprocessed with fieldtrip'; EEG.nbchan = size(data.trial{1},1); EEG.trials = size(data.trial,2); EEG.pnts = size(data.trial{1},2); EEG.srate = data.fsample; EEG.xmin = data.time{1}(1); EEG.xmax = data.time{1}(end); EEG.times = data.time{1}; EEG.ref = []; %'common'; EEG.event = []; EEG.epoch = []; EEG.icawinv = []; EEG.icasphere = []; EEG.icaweights = []; EEG.icaact = []; EEG.saved = 'no'; [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG); eeglab redraw pop_eegplot( EEG, 1, 1, 1);
github
ZijingMao/baselineeegtest-master
rmart.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/rmart.m
6,530
utf_8
f8a4b6645ed700ac44e8b0933750ef36
% rmart() - Remove eye artifacts from EEG data using regression with % multiple time lags. Each channel is first made mean-zero. % After JL Kenemans et al., Psychophysiology 28:114-21, 1991. % % Usage: >> rmart('datafile','outfile',nchans,chanlist,eogchan,[threshold]) % Example: >> rmart('noisy.floats','clean.floats',31,[2:31],7) % % Input: datafile - input float data file, multiplexed by channel % outfile - name of output float data file % nchans - number of channels in datafile % chanlist - indices of EEG channel(s) to process (1,...,nchans) % eogchan - regressing channel indices(s) (1,...,nchans) % threshold- abs threshold value to trigger regression {def|0 -> 80} % % Output: Writes [length(chanlist),size(data,2)] floats to 'outfile' % % Note: Regression epoch length and number of lags are set in the script. % Some machines may require a new byte_order value in the script. % note that runica() -> icaproj() should give better results! See % Jung et al., Psychophysiology 111:1745-58, 2000. % % Author: Tzyy-Ping Jung, SCCN/INC/UCSD, La Jolla, 1997 % Copyright (C) 1997 Tzyy-Ping Jung, 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 % 2-22-97 Tzyy-Ping Jung CNL/Salk Institute, La Jolla, CA % 2-24-97 Formatted for ICA package release -Scott Makeig % 12-10-97 Changed name from rmartifact to rmart for toolbox inclusion -sm % 12-11-97 Adapted to read/write a float matrix -sm & sw % 09-14-00 Added comments and help -sm % 01-25-02 reformated help & license -ad function rmart(datafile,outfile,nchans,chanlist,eogchan,threshold) if nargin < 5 help rmart return end % % The following parameters may be fine-tuned for a data set % DEF_THRESHOLD = 80; % trigger regression on blocks exceeding this (default) epoch = 80; % remove artifacts in successive blocks of this length nlags = 40; % perform multiple regression filtering of this length byte_order = 'b';% (machine-dependent) byte order code for fopen(); MAKE_MEAN_ZERO = 1 % 1/0 flag removing mean offset from each channel fprintf('Performing artifact regression on data in %s.\n',datafile); if nargin<6 threshold = 0; end if threshold == 0, threshold = DEF_THRESHOLD; end fprintf('Regression threshold %g.\n',threshold); % % Read the input data % [fid,msg]=fopen(datafile,'r',byte_order); % open datafile if fid < 3, fprintf('rmart() - could not open data file: %s\n',msg); exit 1 end data=(fread(fid,'float'))'; status=fclose('all'); if rem(length(data),nchans) == 0 % check length fprintf('rmart() - data length not divisible by %d chans.\n',nchans); return end data = reshape(data,nchans,length(data)/nchans); [chans,frames] = size(data); fprintf('Data of size [%d,%d] read.\n',chans,frames); eog = data(eogchan,:); data = data(chanlist,:); procchans = length(chanlist); fprintf('Regression epoch length %d frames.\n',epoch); fprintf('Using %d regression lags.\n',nlags); if length(eogchan)> 1 fprintf('Processing %d of %d channels using %d EOG channels.\n',... procchans,chans,length(eogchan)); else fprintf('Processing %d of %d channels using EOG channel %d.\n',... procchans,chans,eogchan); end % % Process the data % for i=1:procchans chan = chanlist(i); idx=[]; frame=1+epoch/2+nlags/2; if MAKE_MEAN_ZERO data(chan,:) = data(chan,:) - mean(data(chan,:)); % make mean-zero end % Search the EOG & EEG records for values above threshold, % Selected frame numbers are registered in the variable "idx". % The entries in "idx" are at least epoch apart to avoid double % compensation (regression) on the same portion of the EEG data. while frame <= length(eog)-epoch/2-nlags/2, % foreach epoch in channel stop = min(frame+epoch-1,eogframes); tmp= ... find( abs(eog(frame:stop)) >= threshold ... | abs(data(chan,frame:stop)) >= threshold); % find beyond-threshold values if length(tmp) ~= 0 mark = tmp(1)+frame-1; if length(idx) ~= 0 if mark-idx(length(idx)) < epoch, idx=[idx idx(length(idx))+epoch]; % To guarantee idx(i) & idx(i-1) % are at least EPOCH points apart frame = idx(length(idx))+epoch/2; else idx=[idx mark]; frame = mark + epoch/2; end else idx=[idx mark]; frame = mark + epoch/2; end else frame=frame+epoch; end end % while % For each registered frame, take "epoch" points % surrounding it from the EEG, and "epoch + lag" points % from the EOG channel. Then perform multivariate % linear regression on EEG channel. for j=1:length(idx); art=ones(1,epoch); eogtmp=eog(idx(j)-epoch/2-nlags/2:idx(j)+epoch/2-1+nlags/2); % Collect EOG data from lag/2 points before to lag/2 points % after the regression window. for J=nlags:-1:1, art=[art ; eogtmp(J:J+epoch-1)]; end eegtmp=data(chan,idx(j)-epoch/2:idx(j)+epoch/2-1); eegeog=eegtmp*art'; % perform the regression here eogeog=art*art'; b=eegeog/eogeog; eegtmp=eegtmp-b*art; data(chan,idx(j)-epoch/2:idx(j)+epoch/2-1)=eegtmp; end % j end % i % % Write output file % [fid,msg]=fopen(outfile,'w',byte_order); if fid < 3 fprintf('rmart() - could not open output file: %s\n',msg); return end count = fwrite(fid,data,'float'); if count == procchans*frames, fprintf('Output file "%s" written, size = [%d,%d] \n\n',... outfile,procchans,frames); else fprintf('rmart(): Output file "%s" written, SIZE ONLY [%d,%g]\n',... outfile,procchans,count/procchans); end fclose('all');
github
ZijingMao/baselineeegtest-master
vectdata.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/vectdata.m
4,693
utf_8
e2d5960f3405659d0cdcb6645ef43835
% vectdata() - vector data interpolation with optional moving % average. % % Usage: % >> [interparray timesout] = vectdata( array, timesin, 'key', 'val', ... ); % % Inputs: % array - 1-D or 2-D float array. If 2-D, the second dimension % only is interpolated. % timesin - [float vector] time point indices. Same dimension as % the interpolated dimension in array. % % Optional inputs % 'timesout' - [float vector] time point indices for interpolating % data. % 'method' - method for interpolation % 'linear' -> Triangle-based linear interpolation (default). % 'cubic' -> Triangle-based cubic interpolation. % 'nearest' -> Nearest neighbor interpolation. % 'v4' -> MATLAB 4 griddata method. % 'average' - [real] moving average in the dimension of timesin % note that extreme values might be inacurate (see 'borders'). % Default none or []. % 'avgtype' - ['const'|'gauss'] use a const value when averaging (array of % ones) or a gaussian window. Default is 'const'. % 'border' - ['on'|'off'] correct border effect when smoothing. % default is 'off'. % % Outputs: % interparray - interpolated array % timesout - output time points % % Author: Arnaud Delorme, CNL / Salk Institute, 20 Oct 2002 % % See also: griddata() % Copyright (C) 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 [interparray, timesout] = vectdata( array, timevect, varargin ); if nargin < 3 help vectdata; return; end; g = finputcheck( varargin, { 'timesout' 'real' [] []; 'average' 'real' [] []; 'gauss' 'real' [] []; 'border' 'string' { 'on','off' } 'off'; 'avgtype' 'string' { 'const','gauss' } 'const'; 'method' 'string' { 'linear','cubic','nearest','v4' } 'linear'}); if isstr(g), error(g); end; if size(array,2) == 1 array = transpose(array); end; if ~isempty(g.average) timediff = timevect(2:end) -timevect(1:end-1); if any( (timediff - mean(timediff)) > 1e-8 ) % not uniform values fprintf('Data has to be interpolated uniformly for moving average\n'); minspace = mean(timediff); newtimevect = linspace(timevect(1), timevect(end), ceil((timevect(end)-timevect(1))/minspace)); array = interpolate( array, timevect, newtimevect, g.method); timevect = newtimevect; end; oldavg = g.average; g.average = round(g.average/(timevect(2)-timevect(1))); if oldavg ~= g.average fprintf('Moving average updated from %3.2f to %3.2f (=%d points)\n', ... oldavg, g.average*(timevect(2)-timevect(1)), g.average); end; if strcmpi(g.border, 'on') if strcmpi(g.avgtype, 'const') array = convolve(array, ones(1, g.average)); else convolution = gauss2d(1,g.average,1,round(0.15*g.average)); array = convolve(array, convolution); end; else if strcmpi(g.avgtype, 'const') array = conv2(array, ones(1, g.average)/g.average, 'same'); else convolution = gauss2d(1,g.average,1,round(0.15*g.average)); array = conv2(array, convolution/sum(convolution), 'same'); end; end; end; interparray = interpolate( array, timevect, g.timesout, g.method); timesout = g.timesout; % interpolation function % ---------------------- function [interparray] = interpolate( array, timesin, timesout, method); interparray = zeros(size(array,1), length(timesout)); for index = 1:size(array,1) tmpa = [array(index,:) ; array(index,:)]; [Xi,Yi,Zi] = griddata(timesin, [1 2]', tmpa, timesout, [1 2]', method); % Interpolate data interparray(index,:) = Zi(1,:); end;
github
ZijingMao/baselineeegtest-master
matperm.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/matperm.m
2,919
utf_8
697c96bef1109a7011a0d4781bfbedc3
% matperm() - transpose and sign rows of x to match y (run after matcorr() ) % % Usage: >> [permx indperm] = matperm(x,y,indx,indy,corr); % % Inputs: % x = first input matrix % y = matrix with same number of columns as x % indx = column containing row indices for x (from matcorr()) % indy = column containing row indices for y (from matcorr()) % corr = column of correlations between indexed rows of x,y (from matcorr()) % (used only for its signs, +/-) % Outputs: % permx = the matrix x permuted and signed according to (indx, indy,corr) % to best match y. Rows of 0s added to x to match size of y if nec. % indperm = permutation index turning x into y; % % Authors: Scott Makeig, Sigurd Enghoff & Tzyy-Ping Jung % SCCN/INC/UCSD, La Jolla, 2000 % Copyright (C) 1996 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 % 04-22-99 Adjusted for fixes and speed by Sigurd Enghoff & Tzyy-Ping Jung % 01-25-02 Reformated help & license, added links -ad function [permx,indperm]= matperm(x,y,indx,indy,corr) [m,n] = size(x); [p,q] = size(y); [ix,z] = size(indx); [iy,z] = size(indy); oldm = m; errcode=0; if ix ~= iy | p ~= iy, fprintf('matperm: indx and indy must be column vectors, same height as y.\n'); errcode=1 end; if n~=q, fprintf('matperm(): two matrices must be same number of columns.\n'); errcode=2; else if m<p, x = [x;zeros(p-m,n)]; % add rows to x to match height of y p=m; elseif p<m, y = [y;zeros(m-p,n)]; % add rows to y to match height of x m=p; end; end; if errcode==0, % % Return the row permutation of matrix x most correlated with matrix y: % plus the resulting permutation index % indperm = [1:length(indx)]'; % column vector [1 2 ...nrows] permx = x(indx,:); indperm = indperm(indx,:); ydni(indy) = 1:length(indy); permx = permx(ydni,:);% put x in y row-order indperm = indperm(ydni,:); permx = permx.*(sgn(corr(ydni))*ones(1,size(permx,2))); % make x signs agree with y permx = permx(1:oldm,:); % throw out bottom rows if % they were added to match y indperm = indperm(1:oldm,:); end; return function vals=sgn(data) vals = 2*(data>=0)-1; return
github
ZijingMao/baselineeegtest-master
varimax.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/varimax.m
4,437
utf_8
d87cb189d37524e4920c2f9ad9c41aa4
% varimax() - Perform orthogonal Varimax rotation on rows of a data % matrix. % % Usage: >> V = varimax(data); % >> [V,rotdata] = varimax(data,tol); % >> [V,rotdata] = varimax(data,tol,'noreorder') % % Inputs: % data - data matrix % tol - set the termination tolerance to tol {default: 1e-4} % 'noreorder' - Perform the rotation without component reorientation % or reordering by size. This suppression is desirable % when doing a q-mode analysis. {default|0|[] -> reorder} % Outputs: % V - orthogonal rotation matrix, hence % rotdata - rotated matrix, rotdata = V*data; % % Author: Sigurd Enghoff - CNL / Salk Institute, La Jolla 6/18/98 % % See also: runica(), pcasvd(), promax() % Copyright (C) Sigurd Enghoff - CNL / Salk Institute, La Jolla 6/18/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 % Reference: % Henry F. Kaiser (1958) The Varimx criterion for % analytic rotation in factor analysis. Pychometrika 23:187-200. % % modified to return V alone by Scott Makeig, 6/23/98 % 01-25-02 reformated help & license, added link -ad function [V,data] = varimax(data,tol,reorder) if nargin < 1 help varimax return end DEFAULT_TOL = 1e-4; % default tolerance, for use in stopping the iteration DEFAULT_REORDER = 1; % default to reordering the output rows by size % and adjusting their sign to be rms positive. MAX_ITERATIONS = 50; % Default qrtr = .25; % fixed value if nargin < 3 reorder = DEFAULT_REORDER; elseif isempty(reorder) | reorder == 0 reorder = 1; % set default else reorder = strcmp('reorder',reorder); end if nargin < 2 tol = 0; end if tol == 0 tol = DEFAULT_TOL; end if ischar(tol) fprintf('varimax(): tol must be a number > 0\n'); help varimax return end eps1 = tol; % varimax toler eps2 = tol; V = eye(size(data,1)); % do unto 'V' what is done to data crit = [sum(sum(data'.^4)-sum(data'.^2).^2/size(data,2)) 0]; inoim = 0; iflip = 1; ict = 0; fprintf(... 'Finding the orthogonal Varimax rotation using delta tolerance %d...\n',... eps1); while inoim < 2 & ict < MAX_ITERATIONS & iflip, iflip = 0; for j = 1:size(data,1)-1, for k = j+1:size(data,1), u = data(j,:).^2-data(k,:).^2; v = 2*data(j,:).*data(k,:); a = sum(u); b = sum(v); c = sum(u.^2-v.^2); d = sum(u.*v); fden = size(data,2)*c + b^2 - a^2; fnum = 2 * (size(data,2)*d - a*b); if abs(fnum) > eps1*abs(fden) iflip = 1; angl = qrtr*atan2(fnum,fden); tmp = cos(angl)*V(j,:)+sin(angl)*V(k,:); V(k,:) = -sin(angl)*V(j,:)+cos(angl)*V(k,:); V(j,:) = tmp; tmp = cos(angl)*data(j,:)+sin(angl)*data(k,:); data(k,:) = -sin(angl)*data(j,:)+cos(angl)*data(k,:); data(j,:) = tmp; end end end crit = [sum(sum(data'.^4)-sum(data'.^2).^2/size(data,2)) crit(1)]; inoim = inoim + 1; ict = ict + 1; fprintf('#%d - delta = %g\n',ict,(crit(1)-crit(2))/crit(1)); if (crit(1) - crit(2)) / crit(1) > eps2 inoim = 0; end end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if reorder fprintf('Reordering rows...'); [fnorm index] = sort(sum(data'.^2)); V = V .* ((2 * (sum(data') > 0) - 1)' * ones(1, size(V,2))); data = data .* ((2 * (sum(data') > 0) - 1)' * ones(1, size(data,2))); V = V(fliplr(index),:); data = data(fliplr(index),:); fprintf('\n'); else fprintf('Not reordering rows.\n'); end
github
ZijingMao/baselineeegtest-master
pcsquash.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/pcsquash.m
2,802
utf_8
9e0a0372b72b09c731ef70785b8ce862
% pcsquash() - compress data using Principal Component Analysis (PCA) % into a principal component subspace. To project back % into the original channel space, use pcexpand() % % Usage: % >> [eigenvectors,eigenvalues] = pcsquash(data,ncomps); % >> [eigenvectors,eigenvalues,compressed,datamean] ... % = pcsquash(data,ncomps); % % Inputs: % data = (chans,frames) each row is a channel, each column a time point % ncomps = numbers of components to retain % % Outputs: % eigenvectors = square matrix of (column) eigenvectors % eigenvalues = vector of associated eigenvalues % compressed = data compressed into space of the ncomps eigenvectors % with largest eigenvalues (ncomps,frames) % Note that >> compressed = eigenvectors(:,1:ncomps)'*data; % datamean = input data channel (row) means (used internally) % % Author: Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, La Jolla, 6-97 % % See also: pcexpand(), svd() % Copyright (C) 2000 Tzyy-Ping Jung & 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 % 01-25-02 reformated help & license, added links -ad function [EigenVectors,EigenValues,Compressed,Datamean]=pcsquash(matrix,ncomps) if nargin < 1 help pcsquash return end if nargin < 2 ncomps = 0; end if ncomps == 0 ncomps = size(matrix,1); end if ncomps < 1 help pcsquash return end data = matrix'; % transpose data [n,p]=size(data); % now p chans,n time points if ncomps > p fprintf('pcsquash(): components must be <= number of data rows (%d).\n',p); return; end Datamean = mean(data,1); % remove column (channel) means data = data-ones(n,1)*Datamean; % remove column (channel) means out=data'*data/n; [V,D] = eig(out); % get eigenvectors/eigenvalues diag(D); [eigenval,index] = sort(diag(D)); index=rot90(rot90(index)); EigenValues=rot90(rot90(eigenval))'; EigenVectors=V(:,index); if nargout >= 3 Compressed = EigenVectors(:,1:ncomps)'*data'; end
github
ZijingMao/baselineeegtest-master
nan_std.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/nan_std.m
1,304
utf_8
d53859297282cc1d957ec0f2cc0b3617
% nan_std() - std, not considering NaN values % % Usage: std across the first dimension % Author: Arnaud Delorme, CNL / Salk Institute, Sept 2003 % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function out = nan_std(in) if nargin < 1 help nan_std; return; end; nans = find(isnan(in)); in(nans) = 0; nonnans = ones(size(in)); nonnans(nans) = 0; nonnans = sum(nonnans); nononnans = find(nonnans==0); nonnans(nononnans) = NaN; out = sqrt((sum(in.^2)-sum(in).^2./nonnans)./(nonnans-1)); out(nononnans) = NaN;
github
ZijingMao/baselineeegtest-master
plotproj.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/plotproj.m
5,772
utf_8
a22a956e9c31d1ee84c4bbb5a663cd53
% plotproj() - plot projections of one or more ICA components along with % the original data (returns the data plotted) % % Usage: % >> [projdata] = plotproj(data,weights,compnums); % >> [projdata] = plotproj(data,weights,compnums, ... % title,limits,chanlist,channames,colors); % % Inputs: % data = single epoch of runica() input data (chans,frames) % weights = unmixing matrix (=weights*sphere) % compnums = vector of component numbers to project and plot % % Optional inputs: % title = 'fairly short plot title' {0 -> 'plotproj()'} % limits = [xmin xmax ymin ymax] (x's in msec) % {0, or both y's 0 -> data limits} % chanlist = list of data channels to plot {0 -> all} % channames = channel location file or structure (see readlocs()) % colors = file of color codes, 3 chars per line ('.' = space) % {0 -> default color order (black/white first)} % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 05-01-96 % % See also: plotdata() % Without color arg, reads filename for PROJCOLORS from icadefs.m % Copyright (C) 05-01-96 from plotdata() 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 % 05-25-96 added chanlist, nargin tests, rearranged variable order -sm % 07-29-96 debugged, added chanlist channames option -sm % 10-26-96 added test for column of compnums -sm % 02-18-97 improved usage message -sm % 02-19-97 merged versions -sm % 03-19-97 changed var() to diag(cov()), use datamean arg instead of frames/baseframes -sm % 04-24-97 tested datamean for 1-epoch; replaced cov() with mean-squares -sm % 05-20-97 read icadefs for PROJCOLORS & MAXPLOTDATACHANS -sm % 06-05-97 use arbitrary chanlist as default channames -sm % 06-07-97 changed order of args to conform to runica -sm % 06-12-97 made sumdata(chanlist in line 159 below -sm % 07-23-97 removed datamean from args; let mean distribut4e over components -sm % 09-09-97 corrected write out line " summing " -sm % 10-31-97 removed errcode var -sm % 11-05-97 added test for channames when chanlist ~= 1:length(chanlist) -sm & ch % 12-19-00 adjusted new icaproj() args -sm % 01-12-01 removed sphere arg -sm % 01-25-02 reformated help & license, added links -ad function [projdata] = plotproj(data,weights,compnums,titl,limits,chanlist,channels,colors); icadefs % read default PROJCOLORS & MAXPLOTDATACHANS variables from icadefs.m DEFAULT_TITLE = 'plotproj()'; % % Substitute for missing arguments % if nargin < 8, colors = 'white1st.col'; elseif colors==0, colors = 'white1st.col'; end if nargin < 7, channels = 0; end if nargin < 6 chanlist = 0; end if nargin < 5, limits = 0; end if nargin < 4, titl = 0; end if titl==0, titl = DEFAULT_TITLE; end if nargin < 3, fprintf('plotproj(): must have at least four arguments.\n\n'); help plotproj return end % % Test data size % [chans,framestot] = size(data); frames = framestot; % assume one epoch [wr,wc] = size(weights); if wc ~= chans fprintf('plotproj(): sizes of weights and data incompatible.\n\n'); return end % % Substitute for 0 arguments % if chanlist == 0, chanlist = [1:chans]; end; if compnums == 0, compnums = [1:wr]; end; if size(compnums,1)>1, % handle column of compnums ! compnums = compnums'; end; if length(compnums) > 256, fprintf('plotproj(): cannot plot more than %d channels of data at once.\n',256); return end; if channels ~= 0 % if chan name file given if ~all(chanlist == [1:length(chanlist)]) fprintf('plotproj(): Cannot read an arbitrary chanlist of channel names.\n'); return end end if channels==0, channels = chanlist; end if max(compnums)>wr, fprintf(... '\n plotproj(): Component index (%d) > number of components (%d).\n', ... max(compnums),wr); return end fprintf('Reconstructing (%d chan, %d frame) data summing %d components.\n', ... chans,frames,length(compnums)); % % Compute projected data for single components % projdata = data(chanlist,:); fprintf('plotproj(): Projecting component(s) '); for s=compnums, % for each component fprintf('%d ',s); proj = icaproj(data,weights,s); % let offsets distribute projdata = [projdata proj(chanlist,:)]; % append projected data onto projdata % size(projdata) = [length(chanlist) framestot*(length(compnums)+1)] end; fprintf('\n'); % % Compute percentage of variance accounted for % sumdata = icaproj(data,weights,compnums);% let offsets distribute sigmssq = mean(sum(data(chanlist,:).*data(chanlist,:))); data(chanlist,:) = data(chanlist,:) - sumdata(chanlist,:); difmssq = mean(sum(data(chanlist,:).*data(chanlist,:))); pvaf = round(100.0*(1.0-difmssq/sigmssq)); % percent variance accounted for rtitl = ['(p.v.a.f. ' int2str(pvaf) '%)']; % % Make the plot % plotdata(projdata,length(data),limits,titl,channels,colors,rtitl); % make the plot
github
ZijingMao/baselineeegtest-master
numdim.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/numdim.m
2,007
utf_8
220904d43bdb749aef158ee0bdef4040
% numdim() - estimate a lower bound on the (minimum) number of discrete sources % in the data via their second-order statistics. % Usage: % >> num = numdim( data ); % % Inputs: % data - 2-D data (nchannel x npoints) % % Outputs: % num - number of sources (estimated from second order measures) % % References: % WACKERMANN, J. 1996. Beyond mapping: estimating complexity % of multichannel EEG recordings. Acta Neurobiologiae % Experimentalis, 56, 197-208. % WACKERMANN, J. 1999. Towards a quantitative characterization % of functional states of the brain: from non-linear methodology % to the global linear description. International Journal of % Psychophysiology, 34, 65-80. % % Author: Arnaud Delorme, CNL / Salk Institute, 23 January 2003 % Copyright (C) 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 lambda = numdim( a ) if nargin < 1 help numdim; return; end; % Akaike, Identification toolbox (linear identification) a = a'; b = a'*a/100; % correlation [v d] = eig(b); %det(d-b); % checking l = diag(d); l = l/sum(l); lambda = real(exp(-sum(l.*log(l)))); return; % testing by duplicating columns a = rand(100,5)*2-1; a = [a a]; numdim( a )
github
ZijingMao/baselineeegtest-master
eeg_ms2f.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/eeg_ms2f.m
623
utf_8
bf8ab362a73704ef273b03319ce179c0
% eeg_ms2f() - convert epoch latency in ms to nearest epoch frame number % % Usage: % >> outf = eeg_ms2f(EEG,ms); % Inputs: % EEG - EEGLAB data set structure % ms - epoch latency in milliseconds % Output: % outf - nearest epoch frame to the specified epoch latency % % Author: Scott Makeig, SCCN/INC, 12/05 function outf = eeg_ms2f(EEG,ms) ms = ms/1000; if ms < EEG.xmin | ms > EEG.xmax error('time out of range'); end outf = 1+round((EEG.pnts-1)*(ms-EEG.xmin)/(EEG.xmax-EEG.xmin)); % else % [tmp outf] = min(abs(EEG.times-ms));
github
ZijingMao/baselineeegtest-master
compsort.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/compsort.m
8,288
utf_8
43da793b46f111b7671ea6db2e79e699
% compsort() - reorder ICA components, first largest to smallest by the size % of their maximum variance in the single-component projections, % then (if specified) the nlargest component projections are % reordered by the (within-epoch) time point at which they reach % their max variance. % % Usage: % >> [windex,maxvar,maxframe,maxepoch,maxmap] ... % = compsort(data,weights,sphere,datamean, ... % frames,nlargest,chanlist); % Inputs: % data = (chans,frames*epochs) the input data set decomposed by runica() % weights = ica weight matrix returned by runica() % sphere = sphering matrix returned by runica() % % Optional: % datamean = means removed from each row*epoch in runica() % (Note: 0 -> input data means are distributed among components % : 1 -> input data means are removed from the components (default)) % frames = frames per epoch in data (0 -> all) % nlargest = number of largest ICA components to order by latency to max var % (other returned in reverse order of variance) (0 -> none) % chanlist = list of channel numbers to sort on (0 -> all) % % Outputs: % windex = permuted order of rows in output weights (1-chans) % maxvar = maximum variance of projected components (in perm. order) % maxframe = frame of maximum variance (1-frames) (in perm. order) % maxepoch = epoch number of frame of maxvar (1-nepochs) (in perm. order) % maxmap = projected scalp map at max (in perm. order) % % Authors: Scott Makeig, SCCN/INC/UCSD, La Jolla, 1996 % % See also: runica() % Copyright (C) 1996 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 % 11-30-96 as compsort.m % 12-19-96 moved def of epochs below default frames def -sm % 02-18-97 added chanlist -sm % 03-11-97 added default chanlist=0 -> all chans, fixed datamean and var() -sm % 03-17-97 made nlargest default -> nlargest=0 -sm % 04-03-97 fixed problems and removed permweights, permcomps outputs -sm % 04-04-97 shortened name to compsort() -sm % 06-05-97 corrected variance computation -sm % 06-07-97 changed order of args to conform to runica -sm % 06-10-97 fixed recent bug in maxvar order -sm % 07-23-97 made datamean==0 distribute means among components -sm % 08-04-97 added datamean=1 option -sm % 01-25-02 reformated help & license, added links -ad function [windex,maxvar,maxframe,maxepoch,maxmap] = compsort(data,weights,sphere,datamean,frames,nlargest,chanlist) if nargin<3, fprintf('compsort(): needs at least three arguments.\n\n'); help compsort return end [chans,framestot] = size(data); if framestot==0, fprintf('Gcompsort(): cannot process an empty data array.\n'); return end; [srows,scols] = size(sphere); [wrows,wcols] = size(weights); if nargin<7, chanlist = [1:chans]; end if chanlist==0, chanlist = [1:chans]; end if length(chanlist)~=chans & wrows<chans, % if non-square weight matrix fprintf('compsort(): chanlist not allowed with non-square weights.\n'); return end if size(chanlist,1)>1 chanlist = chanlist'; % make a row vector end if size(chanlist,1)>1 fprintf('compsort(): chanlist must be a vector.\n'); return end if nargin<6, nlargest=0; end; if nargin<5, frames = 0; end; if nargin<4, datamean = 1; end; if frames ==0, frames = framestot; end epochs = framestot/frames; % activations = (wrows,wcols)x(srows,scols)x(chans,framestot) if chans ~= scols | srows ~= wcols, fprintf('compsort(): input data dimensions do not match.\n'); fprintf(... ' i.e., Either chans %d ~= sphere cols %d or sphere rows %d ~= weights cols %d\n',... chans,scols,srows,wcols); return end if wrows ~= chans & nlargest ~= 0 & nlargest ~= wrows, fprintf(... 'compsort(): cannot project components back to order by size - nchans ~= ncomponents.\n'); return end if floor(framestot/frames)*frames ~= framestot fprintf(... 'compsort(): input data frames does not divide data length.\n'); return end if nlargest > wrows, fprintf(... 'compsort(): there are only %d rows in the weight matrix.\n',wrows); return end if epochs ~= floor(epochs), fprintf(... 'compsort(): input frames does not subdivide data length.\n'); return end % %%%%%%%%%%%%%%%%%%%% Reorder weight matrix %%%%%%%%%%%%%%%%%%%%% % if datamean == 1, data = data - mean(data')'*ones(1,framestot); % remove channel means elseif datamean~=0, % remove given means if size(datamean,2) ~= epochs | size(datamean,1) ~= chans, fprintf('compsort(): datamean must be 0, 1, or (chans,epochs)\n'); return end for e=1:epochs data(:,(e-1)*frames+1:e*frames) = data(:,(e-1)*frames+1:e*frames)... - datamean(:,e)*ones(1,frames); end end % compute mean data matrix inherited from runica() comps = weights*sphere*data; % Note: distributes means if datamean==0 maxvar = zeros(wrows,1); % size of the projections maxframe = zeros(wrows,1); % frame of the abs(max) projection maxepoch = zeros(wrows,1); % epoch of the abs(max) projection maxmap = zeros(wrows,chans); % leave 0s unless weights is square if chans==wrows, icainv = inv(weights*sphere); fprintf('Computing projected variance for all %d components:\n',wrows); for s=1:wrows fprintf('%d ',s); % construct single-component data matrix % project to scalp compproj = icainv(:,s)*comps(s,:); compv = zeros(frames*epochs,1); compv = (sum(compproj(chanlist,:).*compproj(chanlist,:)))' ... /(length(chanlist)-1); [m,mi] = max(compv); % find max variance maxvar(s) = m; maxframe(s)=rem(mi,frames); % count from beginning of each epoch! maxepoch(s)=floor(mi/frames)+1;% record epoch number of max if maxframe(s)==0, % if max var is in last frame . . . maxframe(s) = frames; maxepoch(s) = maxepoch(s)-1; end maxmap(:,s) = compproj(:,mi); % record scalp projection at max(var(proj)) end else % weight matrix is non-square, sort components by latency only fprintf('compsort() - non-square weights - finding max latencies.\n'); for s=1:wrows compv = comps(s).*comps(s,:)'; % get variance analogues at each time point [m,mi] = max(abs(compv)'); % find abs(max)'s maxvar(s) = m; maxframe(s)=rem(mi,frames); % count from beginning of each epoch! maxepoch(s)=floor(mi/frames)+1;% record epoch number of max if maxframe(s)==0, % if max var is in last frame . . . maxframe(s) = frames; maxepoch(s) = maxepoch(s)-1; end end end fprintf('\n'); [maxvar windex] = sort(maxvar');% sort components by relative size windex = windex(wrows:-1:1)'; % reverse order maxvar = maxvar(wrows:-1:1)'; % make each returned vector a column vector % Note: maxvar reordered by sort() above maxframe = maxframe(windex); % reorder maxframes maxepoch = maxepoch(windex); % reorder maxepoch maxmap = maxmap(:,windex); % reorder maxmap columns if nlargest>0, fprintf('Ordering largest %d components by frame of abs(max): ',nlargest); [m mfi] = sort(maxframe(1:nlargest)); % sort by frame order windex(1:nlargest) = windex(mfi); maxframe(1:nlargest) = m; maxvar(1:nlargest) = maxvar(mfi); maxepoch(1:nlargest) = maxepoch(mfi); maxmap(:,1:nlargest) = maxmap(:,mfi); % reorder largest maxmap columns fprintf('\n'); end
github
ZijingMao/baselineeegtest-master
compheads.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/compheads.m
6,160
utf_8
96edaf4aa50c50ccb4f752823d03b1d4
% compheads() - plot multiple topoplot() maps of ICA component topographies % % Usage: % >> compheads(winv,'spline_file',compnos,'title',rowscols,labels,view) % % Inputs: % winv - Inverse weight matrix = EEG scalp maps. Each column is a % map; the rows correspond to the electrode positions % defined in the eloc_file. Normally, winv = inv(weights*sphere). % spline_file - Name of the eloctrode position file in BESA spherical coords. % compnos - Vector telling which (order of) component maps to show % Indices <0 tell compheads() to invert a map; = 0 leave blank subplot % Example [1 0 -2 3 0 -6] {default|0 -> 1:columns_in_winv} % 'title' - Title string for each page {default|0 -> 'ICA Component Maps'} % rowscols - Vector of the form [m,n] where m is total vertical tiles and n % is horizontal tiles per page. If the number of maps exceeds m*n, % multiple figures will be produced {def|0 -> one near-square page}. % labels - Vector of numbers or a matrix of strings to use as labels for % each map {default|0 -> 1:ncolumns_in_winv} % view - topoplot() view, either [az el] or keyword ('top',...) % See >> help topoplot() for options. % % Note: Map scaling is to +/-max(abs(data); green = 0 % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 4-28-1998 % % See also: topoplot() % Copyright (C) 4-28-98 from compmap.m 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 % 01-25-02 reformated help & license, added links -ad function compheads(Winv,eloc_file,compnos,titleval,pagesize,srclabels,view) if nargin<1 help compheads return end [chans, frames] = size (Winv); DEFAULT_TITLE = 'ICA Component Maps'; DEFAULT_EFILE = 'chan_file'; NUMCONTOUR = 5; % topoplot() style settings OUTPUT = 'screen'; % default: 'screen' for screen colors, % 'printer' for printer colors STYLE = 'both'; INTERPLIMITS = 'head'; MAPLIMITS = 'absmax'; SQUARE = 1; % 1/0 flag making topoplot() asex square -> round heads %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check inputs and set defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% printlabel = OUTPUT; % default set above if nargin < 7 view = [-127 30]; end if nargin < 6 srclabels = 0; end if nargin < 5 pagesize = 0; end if nargin < 4 titleval = 0; end if nargin < 3 compnos = 0; end if nargin < 2 eloc_file = 0; end if srclabels == 0 srclabels = []; end if titleval == 0; titleval = DEFAULT_TITLE; end if compnos == 0 compnos = (1:frames); end if pagesize == 0 numsources = length(compnos); DEFAULT_PAGE_SIZE = ... [floor(sqrt(numsources)) ceil(numsources/floor(sqrt(numsources)))]; m = DEFAULT_PAGE_SIZE(1); n = DEFAULT_PAGE_SIZE(2); elseif length(pagesize) ==1 help compheads return else m = pagesize(1); n = pagesize(2); end if eloc_file == 0 eloc_file = DEFAULT_EFILE; end totalsources = length(compnos); if ~isempty(srclabels) if ~ischar(srclabels(1,1)) % if numbers if size(srclabels,1) == 1 srclabels = srclabels'; end end if size(srclabels,1) ~= totalsources, fprintf('compheads(): numbers of components and component labels do not agree.\n'); return end end pages = ceil(totalsources/(m*n)); if pages > 1 fprintf('compheads(): will create %d figures of %d by %d maps: ',... pages,m,n); end pos = get(gcf,'Position'); off = [ 25 -25 0 0]; % position offsets for multiple figures fid = fopen(eloc_file); if fid<1, fprintf('compheads()^G: cannot open eloc_file (%s).\n',eloc_file); return end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%% plot the maps %%%%%%%%%%%%%%%%%%%%%%% for i = (1:pages) if i > 1 figure('Position',pos+(i-1)*off); % place figures in right-downward stack end set(gcf,'Color','w') %CJH - set background color to white if (totalsources > i*m*n) sbreak = n*m; else sbreak = totalsources - (i-1)*m*n; end for j = (1:sbreak) % maps on this page comp = j+(i-1)*m*n; % compno index if compnos(comp)~=0 if compnos(comp)>0 source_var = Winv(:,compnos(comp))'; % plot map elseif compnos(comp)<0 source_var = -1*Winv(:,-1*compnos(comp))'; % invert map end subplot(m,n,j) headplot(source_var,eloc_file,'electrodes','off','view',view); %topoplot(source_var,eloc_file,'style',STYLE,... % 'numcontour',NUMCONTOUR,'interplimits',INTERPLIMITS,... % 'maplimits',MAPLIMITS); % draw map if SQUARE, axis('square'); end if isempty(srclabels) t=title(int2str(compnos(comp))); set(t,'FontSize',16); else if ischar(srclabels) t=title(srclabels(comp,:)); set(t,'FontSize',16); else t=title(num2str(srclabels(comp))); set(t,'FontSize',16); end end drawnow % draw one map at a time end end ax = axes('Units','Normal','Position',[.5 .04 .32 .05],'Visible','Off'); colorbar(ax) axval = axis; Xlim = get(ax,'Xlim'); set(ax,'XTick',(Xlim(2)+Xlim(1))/2) set(gca,'XTickLabel','0') set(gca,'XTickMode','manual') axbig = axes('Units','Normalized','Position',[0 0 1 1],'Visible','off'); t1 = text(.25,.070,titleval,'HorizontalAlignment','center','FontSize',14); if pages > 1 fprintf('%d ',i); end end if pages > 1 fprintf('\n'); end
github
ZijingMao/baselineeegtest-master
logspec.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/logspec.m
4,318
utf_8
233385ae8dbccb9910ad8e624d8d7244
% logspec() - plot mean log power spectra of submitted data on loglog scale % using plotdata() or plottopo() formats % % Usage: % >> [spectra,freqs] = logspec(data,frames,srate); % >> [spectra,freqs] = logspec(data,frames,srate,'title',... % [loHz-hiHz],'chan_locs',rm_mean); % Inputs: % data = input data (chans,frames*epochs) % frames = data samples per epoch {default length(data)} % srate = data sampling rate in Hz {default 256 Hz}; % 'title' = plot title {default: none} % [loHz-hiHz] = [loHz hiHz] plotting limits % {default: [srate/fftlength srate/2]} % 'chan_locs' = channel location file (ala topoplot()) % Else [rows cols] to plot data in a grid array % rm_mean = [0/1] 1 -> remove log mean spectrum from all % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 11-07-97 % % See also: plotdata(), plottopo() % Copyright (C) 11-07-97 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 % Changed plotdata() below to plottopo() 11/12/99 -sm % Mentioned new grid array option 12/22/99 -sm % 01-25-02 reformated help & license, added links -ad function [spectra,freqs] = logspec(data,frames,srate,titl,Hzlimits,chanlocs,rmmean) if nargin < 1 help logspec return end [rows,cols] = size(data); icadefs % read plotdata chan limit if rows > MAXPLOTDATACHANS fprintf('logspec(): max plotdata() channels is %d.\n',MAXPLOTDATACHANS); return end if rows < 2 fprintf('logspec(): min plotdata() channels is %d.\n',2); return end if nargin<7 rmmean = 0; % default end if nargin < 5 Hzlimits = 0; end if nargin < 4 titl = ' '; end if nargin < 3 srate = 256; end if nargin < 2, frames = cols; end epochs = fix(cols/frames); if epochs*frames ~= cols fprintf('logspec() - frames does not divide data length.\n'); return end fftlength = 2^floor(log(frames)/log(2)); spectra = zeros(rows,epochs*fftlength/2); f2 = fftlength/2; dB = 10/log(10); if length(Hzlimits) < 2 Hzlimits = [srate/fftlength srate/2]; end if Hzlimits(2) <= Hzlimits(1) help logspec return end for e=1:epochs for r=1:rows, [Pxx,freqs] = psd(data(r,(e-1)*frames+1:e*frames),fftlength,srate,... fftlength,fftlength/4); spectra(r,(e-1)*f2+1:e*f2) = Pxx(2:f2+1)'; % omit DC bin end end clf freqs = freqs(2:f2+1); fsi = find(freqs >= Hzlimits(1) & freqs <= Hzlimits(2)); minf = freqs(fsi(1)); maxf = freqs(fsi(length(fsi))); nfs = length(fsi); showspec = zeros(rows,length(fsi)*epochs); for e = 1:epochs showspec(:,(e-1)*nfs+1:e*nfs) = dB*log(spectra(:,(e-1)*f2+fsi)); end % minspec = min(min(showspec)); % showspec = showspec-minspec; % make minimum 0 dB showspec = blockave(showspec,nfs); % meanspec = mean(showspec); % showspec = showspec - ones(rows,1)*meanspec; % >> plotdata(data,frames,limits,title,channames,colors,rtitle) % diff = 0; % MINUEND = 6; % for r=1:rows % diff = diff - MINUEND; % showspec(r,:) = showspec(r<:)-diff; % end % semilogx(freqs(fsi),showspec'); % ax = axis; % axis([minf maxf ax(3) ax(4)]); % title(titl); if nargin<6 % >> plotdata(data,frames,limits,title,channames,colors,rtitle,ydir) if rmmean showspec = showspec - ones(rows,1)*mean(showspec); end plotdata(showspec,nfs,[minf maxf 0 0],titl); else % >> plottopo(data,'chan_locs',frames,limits,title,channels,axsize,colors,ydir) if rmmean showspec = showspec - ones(rows,1)*mean(showspec); end plottopo(showspec,chanlocs,nfs,[minf maxf 0 0],titl); end ax = get(gcf,'children'); for a = ax set(a,'XScale','log') end
github
ZijingMao/baselineeegtest-master
tftopo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/tftopo.m
25,337
utf_8
4bf52bc66340b8d734d55dbc8d8fccee
% tftopo() - Generate a figure showing a selected or representative image (e.g., % an ERSP, ITC or ERP-image) from a supplied set of images, one for each % scalp channel. Then, plot topoplot() scalp maps of value distributions % at specified (time, frequency) image points. Else, image the signed % (selected) between-channel std(). Inputs may be outputs of % timef(), crossf(), or erpimage(). % Usage: % >> tftopo(tfdata,times,freqs, 'key1', 'val1', 'key2', val2' ...) % Inputs: % tfdata = Set of time/freq images, one for each channel. Matrix dims: % (time,freq,chans). Else, (time,freq,chans,subjects) for grand mean % RMS plotting. % times = Vector of image (x-value) times in msec, from timef()). % freqs = Vector of image (y-value) frequencies in Hz, from timef()). % % Optional inputs: % 'timefreqs' = Array of time/frequency points at which to plot topoplot() maps. % Size: (nrows,2), each row given the [ms Hz] location % of one point. Or size (nrows,4), each row given [min_ms % max_ms min_hz max_hz]. % 'showchan' = [integer] Channel number of the tfdata to image. Else 0 to image % the (median-signed) RMS values across channels. {default: 0} % 'chanlocs' = ['string'|structure] Electrode locations file (for format, see % >> topoplot example) or EEG.chanlocs structure {default: none} % 'limits' = Vector of plotting limits [minms maxms minhz maxhz mincaxis maxcaxis] % May omit final vales, or use NaN's to use the input data limits. % Ex: [nan nan -100 400]; % 'signifs' = (times,freqs) Matrix of significance level(s) (e.g., from timef()) % to zero out non-signif. tfdata points. Matrix size must be % ([1|2], freqs, chans, subjects) % if using the same threshold for all time points at each frequency, or % ([1|2], freqs, times, chans, subjects). % If first dimension is of size 1, data are assumed to contain % positive values only {default: none} % 'sigthresh' = [K L] After masking time-frequency decomposition using the 'signifs' % array (above), concatenate (time,freq) values for which no more than % K electrodes have non-0 (significant) values. If several subjects, % the second value L is used to concatenate subjects in the same way. % {default: [1 1]} % 'selchans' = Channels to include in the topoplot() scalp maps (and image values) % {default: all} % 'smooth' = [pow2] magnification and smoothing factor. power of 2 (default: 1}. % 'mode' = ['rms'|'ave'] ('rms') return root-mean-square, else ('ave') average % power {default: 'rms' } % 'logfreq' = ['on'|'off'|'native'] plot log frequencies {default: 'off'} % 'native' means that the input is already in log frequencies % 'vert' = [times vector] (in msec) plot vertical dashed lines at specified times % {default: 0} % 'ylabel' = [string] label for the ordinate axis. Default is % "Frequency (Hz)" % 'shiftimgs' = [response_times_vector] shift time/frequency images from several % subjects by each subject's response time {default: no shift} % 'title' = [quoted_string] plot title (default: provided_string). % 'cbar' = ['on'|'off'] plot color bar {default: 'on'} % 'cmode' = ['common'|'separate'] 'common' or 'separate' color axis for each % topoplot {default: 'common'} % 'plotscalponly' = [x,y] location (e.g. msec,hz). Plot one scalp map only; no % time-frequency image. % 'events' = [real array] plot event latencies. The number of event % must be the same as the number of "frequecies". % 'verbose' = ['on'|'off'] comment on operations on command line {default: 'on'}. % 'axcopy' = ['on'|'off'] creates a copy of the figure axis and its graphic objects in a new pop-up window % using the left mouse button {default: 'on'}.. % 'denseLogTicks' = ['on'|'off'] creates denser labels on log freuqncy axis {default: 'off'} % % Notes: % 1) Additional topoplot() optional arguments can be used. % 2) In the topoplot maps, average power (not masked by significance) is used % instead of the (signed and masked) root-mean-square (RMS) values used in the image. % 3) If tfdata from several subjects is used (via a 4-D tfdata input), RMS power is first % computed across electrodes, then across the subjects. % % Authors: Scott Makeig, Arnaud Delorme & Marissa Westerfield, SCCN/INC/UCSD, La Jolla, 3/01 % % See also: timef(), topoplot(), spectopo(), timtopo(), envtopo(), changeunits() % hidden parameter: 'shiftimgs' = array with one value per subject for shifting in time the % time/freq images. Had to be inserted in tftopo because % the shift happen after the smoothing % Copyright (C) Scott Makeig, Arnaud Delorme & Marissa Westerfield, SCCN/INC/UCSD, % La Jolla, 3/01 % % 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 tfave = tftopo(tfdata,times,freqs,varargin); %timefreqs,showchan,chanlocs,limits,signifs,selchans) LINECOLOR= 'k'; LINEWIDTH = 2; ZEROLINEWIDTH = 2.8; if nargin<3 help tftopo return end icadefs_flag = 1; try icadefs; catch warning('icadefs.m can not be located in the path'); icadefs_flag = 0 ; end if ~icadefs_flag AXES_FONTSIZE = 10; PLOT_LINEWIDTH = 2; end % reshape tfdata % -------------- if length(size(tfdata))==2 if size(tfdata,1) ~= length(freqs), tfdata = tfdata'; end; nchans = round(size(tfdata,2)/length(times)); tfdata = reshape(tfdata, size(tfdata,1), length(times), nchans); elseif length(size(tfdata))>=3 nchans = size(tfdata,3); else help tftopo return end tfdataori = mean(tfdata,4); % for topoplot % test inputs % ----------- % 'key' 'val' sequence fieldlist = { 'chanlocs' { 'string','struct' } [] '' ; 'limits' 'real' [] [nan nan nan nan nan nan]; 'logfreq' 'string' {'on','off','native'} 'off'; 'cbar' 'string' {'on','off' } 'on'; 'mode' 'string' { 'ave','rms' } 'rms'; 'title' 'string' [] ''; 'verbose' 'string' {'on','off' } 'on'; 'axcopy' 'string' {'on','off' } 'on'; 'cmode' 'string' {'common','separate' } 'common'; 'selchans' 'integer' [1 nchans] [1:nchans]; 'shiftimgs' 'real' [] []; 'plotscalponly' 'real' [] []; 'events' 'real' [] []; 'showchan' 'integer' [0 nchans] 0 ; 'signifs' 'real' [] []; 'sigthresh' 'integer' [1 Inf] [1 1]; 'smooth' 'real' [0 Inf] 1; 'timefreqs' 'real' [] []; 'ylabel' 'string' {} 'Frequency (Hz)'; 'vert' 'real' [times(1) times(end)] [min(max(0, times(1)), times(end))]; 'denseLogTicks' 'string' {'on','off'} 'off' }; [g varargin] = finputcheck( varargin, fieldlist, 'tftopo', 'ignore'); if isstr(g), error(g); end; % setting more defaults % --------------------- if length(times) ~= size(tfdata,2) fprintf('tftopo(): tfdata columns must be a multiple of the length of times (%d)\n',... length(times)); return end if length(g.showchan) > 1 error('tftopo(): showchan must be a single number'); end; if length(g.limits)<1 | isnan(g.limits(1)) g.limits(1) = times(1); end if length(g.limits)<2 | isnan(g.limits(2)) g.limits(2) = times(end); end if length(g.limits)<3 | isnan(g.limits(3)) g.limits(3) = freqs(1); end if length(g.limits)<4 | isnan(g.limits(4)) g.limits(4) = freqs(end); end if length(g.limits)<5 | isnan(g.limits(5)) % default caxis plotting limits g.limits(5) = -max(abs(tfdata(:))); mincax = g.limits(5); end if length(g.limits)<6 | isnan(g.limits(6)) defaultlim = 1; if exist('mincax') g.limits(6) = -mincax; % avoid recalculation else g.limits(6) = max(abs(tfdata(:))); end else defaultlim = 0; end if length(g.sigthresh) == 1 g.sigthresh(2) = 1; end; if g.sigthresh(1) > nchans error('tftopo(): ''sigthresh'' first number must be less than or equal to the number of channels'); end; if g.sigthresh(2) > size(tfdata,4) error('tftopo(): ''sigthresh'' second number must be less than or equal to the number of subjects'); end; if ~isempty(g.signifs) if size(g.signifs,1) > 2 | size(g.signifs,2) ~= size(tfdata,1)| ... (size(g.signifs,3) ~= size(tfdata,3) & size(g.signifs,4) ~= size(tfdata,3)) fprintf('tftopo(): error in ''signifs'' array size not compatible with data size, trying to transpose.\n'); g.signifs = permute(g.signifs, [2 1 3 4]); if size(g.signifs,1) > 2 | size(g.signifs,2) ~= size(tfdata,1)| ... (size(g.signifs,3) ~= size(tfdata,3) & size(g.signifs,4) ~= size(tfdata,3)) fprintf('tftopo(): ''signifs'' still the wrong size.\n'); return end; end end; if length(g.selchans) ~= nchans, selchans_opt = { 'plotchans' g.selchans }; else selchans_opt = { }; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % process time/freq data points %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(g.timefreqs) if size(g.timefreqs,2) == 2 g.timefreqs(:,3) = g.timefreqs(:,2); g.timefreqs(:,4) = g.timefreqs(:,2); g.timefreqs(:,2) = g.timefreqs(:,1); end; if isempty(g.chanlocs) error('tftopo(): ''chanlocs'' must be defined to plot time/freq points'); end; if min(min(g.timefreqs(:,[3 4])))<min(freqs) fprintf('tftopo(): selected plotting frequency %g out of range.\n',min(min(g.timefreqs(:,[3 4])))); return end if max(max(g.timefreqs(:,[3 4])))>max(freqs) fprintf('tftopo(): selected plotting frequency %g out of range.\n',max(max(g.timefreqs(:,[3 4])))); return end if min(min(g.timefreqs(:,[1 2])))<min(times) fprintf('tftopo(): selected plotting time %g out of range.\n',min(min(g.timefreqs(:,[1 2])))); return end if max(max(g.timefreqs(:,[1 2])))>max(times) fprintf('tftopo(): selected plotting time %g out of range.\n',max(max(g.timefreqs(:,[1 2])))); return end if 0 % USE USER-SUPPLIED SCALP MAP ORDER. A GOOD ALGORITHM FOR SELECTING % g.timefreqs POINT ORDER GIVING MAX UNCROSSED LINES IS DIFFICULT! [tmp tfi] = sort(g.timefreqs(:,1)); % sort on times tmp = g.timefreqs; for t=1:size(g.timefreqs,1) g.timefreqs(t,:) = tmp(tfi(t),:); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Compute timefreqs point indices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% tfpoints = size(g.timefreqs,1); for f=1:tfpoints [tmp fi1] = min(abs(freqs-g.timefreqs(f,3))); [tmp fi2] = min(abs(freqs-g.timefreqs(f,4))); freqidx{f}=[fi1:fi2]; end for f=1:tfpoints [tmp fi1] = min(abs(times-g.timefreqs(f,1))); [tmp fi2] = min(abs(times-g.timefreqs(f,2))); timeidx{f}=[fi1:fi2]; end else tfpoints = 0; end; % only plot one scalp map % ----------------------- if ~isempty(g.plotscalponly) [tmp fi] = min(abs(freqs-g.plotscalponly(2))); [tmp ti] = min(abs(times-g.plotscalponly(1))); scalpmap = squeeze(tfdataori(fi, ti, :)); if ~isempty(varargin) topoplot(scalpmap,g.chanlocs,'electrodes','on', selchans_opt{:}, varargin{:}); else topoplot(scalpmap,g.chanlocs,'electrodes','on', selchans_opt{:}); end; % 'interlimits','electrodes') axis square; hold on tl=title([int2str(g.plotscalponly(2)),' ms, ',int2str(g.plotscalponly(1)),' Hz']); set(tl,'fontsize',AXES_FONTSIZE+3); % 13 return; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Zero out non-significant image features %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% range = g.limits(6)-g.limits(5); cc = jet(256); if ~isempty(g.signifs) if strcmpi(g.verbose, 'on') fprintf('Applying ''signifs'' mask by zeroing non-significant values\n'); end for subject = 1:size(tfdata,4) for elec = 1:size(tfdata,3) if size(g.signifs,1) == 2 if ndims(g.signifs) > ndims(tfdata) tmpfilt = (tfdata(:,:,elec,subject) >= squeeze(g.signifs(2,:,:,elec, subject))') | ... (tfdata(:,:,elec,subject) <= squeeze(g.signifs(1,:,:,elec, subject))'); else tmpfilt = (tfdata(:,:,elec,subject) >= repmat(g.signifs(2,:,elec, subject)', [1 size(tfdata,2)])) | ... (tfdata(:,:,elec,subject) <= repmat(g.signifs(1,:,elec, subject)', [1 size(tfdata,2)])); end; else if ndims(g.signifs) > ndims(tfdata) tmpfilt = (tfdata(:,:,elec,subject) >= squeeze(g.signifs(1,:,:,elec, subject))'); else tmpfilt = (tfdata(:,:,elec,subject) >= repmat(g.signifs(1,:,elec, subject)', [1 size(tfdata,2)])); end; end; tfdata(:,:,elec,subject) = tfdata(:,:,elec,subject) .* tmpfilt; end; end; end; %%%%%%%%%%%%%%%% % magnify inputs %%%%%%%%%%%%%%%% if g.smooth ~= 1 if strcmpi(g.verbose, 'on'), fprintf('Smoothing...\n'); end for index = 1:round(log2(g.smooth)) [tfdata times freqs] = magnifytwice(tfdata, times, freqs); end; end; %%%%%%%%%%%%%%%%%%%%%%%% % Shift time/freq images %%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(g.shiftimgs) timestep = times(2) - times(1); for S = 1:size(tfdata,4) nbsteps = round(g.shiftimgs(S)/timestep); if strcmpi(g.verbose, 'on'), fprintf('Shifing images of subect %d by %3.3f ms or %d time steps\n', S, g.shiftimgs(S), nbsteps); end if nbsteps < 0, tfdata(:,-nbsteps+1:end,:,S) = tfdata(:,1:end+nbsteps,:,S); else tfdata(:,1:end-nbsteps,:,S) = tfdata(:,nbsteps+1:end,:,S); end; end; end; %%%%%%%%%%%%%%%%%%%%%%%%% % Adjust plotting limits %%%%%%%%%%%%%%%%%%%%%%%%% [tmp minfreqidx] = min(abs(g.limits(3)-freqs)); % adjust min frequency g.limits(3) = freqs(minfreqidx); [tmp maxfreqidx] = min(abs(g.limits(4)-freqs)); % adjust max frequency g.limits(4) = freqs(maxfreqidx); [tmp mintimeidx] = min(abs(g.limits(1)-times)); % adjust min time g.limits(1) = times(mintimeidx); [tmp maxtimeidx] = min(abs(g.limits(2)-times)); % adjust max time g.limits(2) = times(maxtimeidx); mmidx = [mintimeidx maxtimeidx minfreqidx maxfreqidx]; %colormap('jet'); %c = colormap; %cc = zeros(256,3); %if size(c,1)==64 % for i=1:3 % cc(:,i) = interp(c(:,i),4); % end %else % cc=c; %nd %cc(find(cc<0))=0; %cc(find(cc>1))=1; %if exist('g.signif') % minnull = round(256*(g.signif(1)-g.limits(5))/range); % if minnull<1 % minnull = 1; % end % maxnull = round(256*(g.signif(2)-g.limits(5))/range); % if maxnull>256 % maxnull = 256; % end % nullrange = minnull:maxnull; % cc(nullrange,:) = repmat(cc(128,:),length(nullrange),1); %end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot tfdata image for specified channel or selchans std() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% axis off; colormap(cc); curax = gca; % current plot axes to plot into if tfpoints ~= 0 plotdim = max(1+floor(tfpoints/2),4); % number of topoplots on top of image imgax = sbplot(plotdim,plotdim,[plotdim*(plotdim-1)+1,2*plotdim-1],'ax',curax); else imgax = curax; end; tftimes = mmidx(1):mmidx(2); tffreqs = mmidx(3):mmidx(4); if g.showchan>0 % -> image showchan data tfave = tfdata(tffreqs, tftimes,g.showchan); else % g.showchan==0 -> image std() of selchans tfdat = tfdata(tffreqs,tftimes,g.selchans,:); % average across electrodes if strcmpi(g.verbose, 'on'), fprintf('Applying RMS across channels (mask for at least %d non-zeros values at each time/freq)\n', g.sigthresh(1)); end tfdat = avedata(tfdat, 3, g.sigthresh(1), g.mode); % if several subject, first (RMS) averaging across subjects if size(tfdata,4) > 1 if strcmpi(g.verbose, 'on'), fprintf('Applying RMS across subjects (mask for at least %d non-zeros values at each time/freq)\n', g.sigthresh(2)); end tfdat = avedata(tfdat, 4, g.sigthresh(2), g.mode); end; tfave = tfdat; if defaultlim g.limits(6) = max(max(abs(tfave))); g.limits(5) = -g.limits(6); % make symmetrical end; end if ~isreal(tfave(1)), tfave = abs(tfave); end; if strcmpi(g.logfreq, 'on'), logimagesc(times(tftimes),freqs(tffreqs),tfave); axis([g.limits(1) g.limits(2) log(g.limits(3)), log(g.limits(4))]); elseif strcmpi(g.logfreq, 'native'), imagesc(times(tftimes),log(freqs(tffreqs)),tfave); axis([g.limits(1:2) log(g.limits(3:4))]); if g.denseLogTicks minTick = min(ylim); maxTick = max(ylim); set(gca,'ytick',linspace(minTick, maxTick,50)); end; tmpval = get(gca,'yticklabel'); if iscell(tmpval) ft = str2num(cell2mat(tmpval)); % MATLAB version >= 8.04 else ft = str2num(tmpval); % MATLAB version < 8.04 end 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); inds = unique_bc(round(exp(linspace(log(1), log(length(ft)))))); set(gca,'ytick',ftick(inds(1:2:end))); set(gca,'yticklabel', num2str(ft(inds(1:2:end)))); else imagesc(times(tftimes),freqs(tffreqs),tfave); axis([g.limits(1:4)]); end; caxis([g.limits(5:6)]); hold on; %%%%%%%%%%%%%%%%%%%%%%%%%% % Title and vertical lines %%%%%%%%%%%%%%%%%%%%%%%%%% axes(imgax) xl=xlabel('Time (ms)'); set(xl,'fontsize',AXES_FONTSIZE+2);%12 set(gca,'yaxislocation','left') if g.showchan>0 % tl=title(['Channel ',int2str(g.showchan)]); % set(tl,'fontsize',14); else if isempty(g.title) if strcmpi(g.mode, 'rms') tl=title(['Signed channel rms']); else tl=title(['Signed channel average']); end; else tl = title(g.title); end set(tl,'fontsize',AXES_FONTSIZE + 2); %12 set(tl,'fontweigh','normal'); end yl=ylabel(g.ylabel); set(yl,'fontsize',AXES_FONTSIZE + 2); %12 set(gca,'fontsize',AXES_FONTSIZE + 2); %12 set(gca,'ydir','normal'); for indtime = g.vert tmpy = ylim; htmp = plot([indtime indtime],tmpy,[LINECOLOR ':']); set(htmp,'linewidth',PLOT_LINEWIDTH) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot topoplot maps at specified timefreqs points %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(g.events) tmpy = ylim; yvals = linspace(tmpy(1), tmpy(2), length(g.events)); plot(g.events, yvals, 'k', 'linewidth', 2); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot topoplot maps at specified timefreqs points %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(g.timefreqs) wholeax = sbplot(1,1,1,'ax',curax); topoaxes = zeros(1,tfpoints); for n=1:tfpoints if n<=plotdim topoaxes(n)=sbplot(plotdim,plotdim,n,'ax',curax); else topoaxes(n)=sbplot(plotdim,plotdim,plotdim*(n+1-plotdim),'ax',curax); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot connecting lines using changeunits() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% tmptimefreq = [ mean(g.timefreqs(n,[1 2])) mean(g.timefreqs(n,[3 4])) ]; if strcmpi(g.logfreq, 'off') from = changeunits(tmptimefreq,imgax,wholeax); else from = changeunits([tmptimefreq(1) log(tmptimefreq(2))],imgax,wholeax); end; to = changeunits([0.5,0.5],topoaxes(n),wholeax); axes(wholeax); plot([from(1) to(1)],[from(2) to(2)],LINECOLOR,'linewidth',LINEWIDTH); hold on mk=plot(from(1),from(2),[LINECOLOR 'o'],'markersize',9); set(mk,'markerfacecolor',LINECOLOR); axis([0 1 0 1]); axis off; end endcaxis = 0; for n=1:tfpoints %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot scalp map using topoplot() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% axes(topoaxes(n)); scalpmap = squeeze(mean(mean(tfdataori(freqidx{n},timeidx{n},:),1),2)); %topoplot(scalpmap,g.chanlocs,'maplimits',[g.limits(5) g.limits(6)],... % 'electrodes','on'); if ~isempty(varargin) topoplot(scalpmap,g.chanlocs,'electrodes','on', selchans_opt{:}, varargin{:}); else topoplot(scalpmap,g.chanlocs,'electrodes','on', selchans_opt{:}); end; % 'interlimits','electrodes') axis square; hold on if g.timefreqs(n,1) == g.timefreqs(n,2) tl=title([int2str(g.timefreqs(n,1)),' ms, ',int2str(g.timefreqs(n,3)),' Hz']); else tl=title([int2str(g.timefreqs(n,1)) '-' int2str(g.timefreqs(n,2)) 'ms, ' ... int2str(g.timefreqs(n,3)) '-' int2str(g.timefreqs(n,4)) ' Hz']); end; set(tl,'fontsize',AXES_FONTSIZE + 3); %13 endcaxis = max(endcaxis,max(abs(caxis))); %caxis([g.limits(5:6)]); end; if strcmpi(g.cmode, 'common') for n=1:tfpoints axes(topoaxes(n)); caxis([-endcaxis endcaxis]); if n==tfpoints & strcmpi(g.cbar, 'on') % & (mod(tfpoints,2)~=0) % image color bar by last map cb=cbar; pos = get(cb,'position'); set(cb,'position',[pos(1:2) 0.023 pos(4)]); end drawnow end end; end; if g.showchan>0 & ~isempty(g.chanlocs) sbplot(4,4,1,'ax',imgax); topoplot(g.showchan,g.chanlocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10 ); axis('square'); end if strcmpi(g.axcopy, 'on') if strcmpi(g.logfreq, 'native'), com = [ '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));' ]; axcopy(gcf, com); % turn on axis copying on mouse click else axcopy; % turn on axis copying on mouse click end; end %%%%%%%%%%%%%%%%%%%%%%%% embedded functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tfdat = avedata(tfdat, dim, thresh, mode) tfsign = sign(mean(tfdat,dim)); tfmask = sum(tfdat ~= 0,dim) >= thresh; if strcmpi(mode, 'rms') tfdat = tfmask.*tfsign.*sqrt(mean(tfdat.*tfdat,dim)); % std of all channels else tfdat = tfmask.*mean(tfdat,dim); % std of all channels end; function [tfdatnew, times, freqs] = magnifytwice(tfdat, times, freqs); indicetimes = [floor(1:0.5:size(tfdat,1)) size(tfdat,1)]; indicefreqs = [floor(1:0.5:size(tfdat,2)) size(tfdat,2)]; tfdatnew = tfdat(indicetimes, indicefreqs, :, :); times = linspace(times(1), times(end), size(tfdat,2)*2); freqs = linspace(freqs(1), freqs(end), size(tfdat,1)*2); % smoothing gauss2 = gauss2d(3,3); for S = 1:size(tfdat,4) for elec = 1:size(tfdat,3) tfdatnew(:,:,elec,S) = conv2(tfdatnew(:,:,elec,S), gauss2, 'same'); end; end; %tfdatnew = convn(tfdatnew, gauss2, 'same'); % is equivalent to the loop for slowlier
github
ZijingMao/baselineeegtest-master
compplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/compplot.m
5,162
utf_8
07cf31546d5dbdf48bfb29cba43e9408
% compplot() - plot a data epoch and maps its scalp topography at a given time % % Usage: To plot the projection of an ICA component onto the scalp % >> projdata = icaproj(data,weights,compindex); % % then >> compplot(projdata); % % else to plot an EEG epoch with a topoplot at one selected time point % >> compplot(data,plotframe,chan_file,xstart,srate,title, splinefile); % % Inputs: % data = data returned from icaproj() *ELSE* any EEG/ERP data epoch % plotframe = frame to plot topographically {default|0 -> frame of max(var())} % 'chan_file' = chan file, see >> topoplot example {def|0 -> 'chan_file'} % xstart = start time in seconds {default|0 -> 0} % srate = data sampling rate in Hz {default|0 -> 256 Hz} % 'title' = plot title {default|0 -> none} % splinefile = headplot spline file (optional) for 3-d head image {default: none} % % Authors: Colin Humphries & Scott Makeig, SCCN/INC/UCSD, CNL / Salk Institute, 1997 % % See also: icaproj() % Copyright (C) 2000 Colin Humphries & Scott Makeig, SCCN/INC/UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 6-07-97 changed order of args in icaproj above -sm % Revised for Matlab 5.0.0.4064 11/97 -ch & sm % 2-18-98 added undocumented headplot() option -sm % 3-09-98 added check for chan_file -sm % 3-18-98 use new eegplot('noui') -sm % 7-25-98 make sure length(hkids) >= 3 on line 122 ff -sm % 12-19-00 updated icaproj() call in help msg -sm % 1-24-01 corrected input error in header -ad % 01-25-02 reformated help & license, added links -ad function M = compplot(data,plotframe,chan_file,xstart,srate,titl,spline_file) if nargin < 1 help compplot return end [chans,frames] = size(data); icadefs; % read DEFAULT_SRATE if nargin < 7 spline_file = nan; end if nargin < 6, titl = ''; % DEFAULT TITLE end if nargin < 5 srate = 0; end if nargin < 4 xstart = 0; % DEFAULT START TIME end if nargin < 3 chan_file = 'chan_file'; % DEFAULT CHAN_FILE end if chan_file == 0, chan_file = 'chan_file'; % DEFAULT CHAN_FILE end if nargin < 2 plotframe = 0; end if plotframe == 0 [mx plotframe] = max(mean(data.*data)); % default plotting frame has max variance end if plotframe > frames fprintf('Plot frame %d is > frames in data (%d)\n',plotframe,frames); return end fprintf('Topoplot will show frame %d\n',plotframe); if nargin < 1 help compplot end if srate==0, srate = DEFAULT_SRATE; end clf % clear the current figure set(gcf,'Color',BACKCOLOR); % set the background color axe = axes('Units','Normalized','Position',[.75 .12 .2 .8]); set(gca,'Color','none'); % >> eegplot('noui',data,srate,spacing,eloc_file,startsec,color) eegplot('noui',-data(:,xstart*srate+1:end),srate,0,chan_file,0,'r') plottime = xstart + (plotframe-1)/srate; timetext = num2str(plottime,'%4.3f'); set(gca,'XTick',plotframe,'XtickLabel',timetext) %%CJH set(gca,'Color','none'); limits = get(gca,'Ylim'); set(gca,'GridLineStyle',':') set(gca,'Xgrid','off') set(gca,'Ygrid','on') % axes(axe) plottime = xstart + (plotframe-1)/srate; l1 = line([plotframe plotframe],limits,'color','b'); % was [plottime plottime] fid = fopen(chan_file); % check whether topoplot will find chan_fil if fid<1, fprintf('topoplot()^G: cannot open eloc_file (%s).\n',chan_file); return end axcolor = get(gcf,'Color'); axt = axes('Units','Normalized','Position',[.00 .10 .75 .80],'Color',axcolor); axes(axt) % topoplot axes cla if isnan(spline_file) topoplot(data(:,plotframe),chan_file,'style','both'); else headplot(data(:,plotframe),spline_file); end text(0.00,0.70,titl,'FontSize',14,'HorizontalAlignment','Center'); axt = axes('Units','Normalized','Position',[.05 .05 .055 .18]); % colorbar axes h=cbar(axt); % hkids=get(h,'children'); % delno = 3; % if delno > length(hkids) % delno = length(hkids); % end % for i=1:delno % delete(hkids(i)); % end axis(axis) set(h,'XTickLabel',[]); HYLIM = get(h,'YLim'); %%CJH set(h,'YTick',[HYLIM(1) (HYLIM(1)+HYLIM(2))/2 HYLIM(2)]) %%CJH set(h,'YTickLabel',['-';'0';'+']); %%CJH set(h,'YTickMode','manual'); axt = axes('Units','Normalized','Position',[0 0 1 1],... 'Visible','Off','Fontsize',16); % topoplot axes axes(axt) timetext = [ 't = ',num2str(plottime) ' s']; text(0.16,0.09,timetext,'FontSize',14); text(0.85,0.04,'Time (sec)','FontSize',14,'HorizontalAlignment','Center');
github
ZijingMao/baselineeegtest-master
gradmap.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/gradmap.m
3,370
utf_8
98c074ff6b72e6334c66c7e0ee2d3a31
% gradmap() - compute the gradient of an EEG spatial distribution. % % Usage: % >> [gradX, gradY ] = gradmap( map, filename, draw ) % % Inputs: % map - level of activity (size: nbelectrodes x nbChannel) % filename - filename (.loc file) countaining the coordinates % of the electrodes, or array countaining complex positions % Can also be a EEGLAB channel structure. % draw - integer, if not nul draw the gradient (default:0) % % Output: % gradX - gradient over X % gradY - gradient over Y (use cart2pol to get polar coordinates) % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % This section bastardizes topoplot.m in order to get gradient maps % for all of the component maps brought back from ClusMapSpec.m % This is done to improve the clustering results. % 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 [gradx, grady] = gradmap( map, filename, draw ) if nargin < 2 help gradmap; return; end; MAXCHANS = size(map,1); GRID_SCALE = 2*MAXCHANS+5; % Read the channel file % --------------------- if isnumeric( filename ) x = real(filename); y = imag(filename); else tmploc = readlocs( filename); fe = find(cellfun('isempty', { tmploc.theta })); tmploc(fe) = []; map(fe,:) = []; [x,y] = pol2cart( [ tmploc.theta ]/180*pi , [ tmploc.radius ] ); end; % locates nearest position of electrod in the grid % ------------------------------------------------ xi = linspace(-0.5,0.5,GRID_SCALE); % x-axis description (row vector) yi = linspace(-0.5,0.5,GRID_SCALE); % y-axis description (row vector) horizidx=zeros(1, MAXCHANS); %preallocation vertidx=zeros(1, MAXCHANS); % preallocation for i=1:MAXCHANS [useless_var horizidx(i)] = min(abs(y(i) - xi)); % find pointers to electrode [useless_var vertidx(i)] = min(abs(x(i) - yi)); % positions in Zi end; draw = 1; % Compute gradient % ---------------- for i=1:size(map,2) [Xi,Yi,Zi] = griddata(y,x,map(:,i),yi',xi, 'v4'); % interpolate data [FX,FY] = gradient(Zi); positions = horizidx + (vertidx-1)*GRID_SCALE; gradx(:,i) = FX(positions(:)); grady(:,i) = FY(positions(:)); % Draw gradient % ------------- if exist('draw') if exist('imresize') subplot(ceil(sqrt(size(map,2))), ceil(sqrt(size(map,2))), i); contour(imresize(Zi,0.5)); hold on quiver(imresize(FX, 0.5), imresize(FY, 0.5)); hold off else disp('Warning: cannot plot because imresize function is missing (image processing toolbox)'); end; end; end; return;
github
ZijingMao/baselineeegtest-master
fillcurves.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/fillcurves.m
3,697
utf_8
45bdc3bae6abe81f3eb865ff508ed4aa
% fillcurves() - fill the space between 2 curves % % Usage: % h=fillcurves( Y1, Y2); % h=fillcurves( X, Y1, Y2, color, transparent[0 to 1]); % % Example: % a = rand(1, 50); % b = rand(1, 50)+2; b(10) = NaN; % figure; fillcurves([51:100], a, b); % % Author: A. Delorme, SCCN, INC, UCSD/CERCO, CNRS % 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 h = fillcurves(X, Y1, Y2, color, transparent, legends) if nargin < 2 help fillcurves; return; end; if nargin < 3 Y2 = Y1; Y1 = X; X = [1:length(Y1)]; end; if nargin < 4 || isempty(color) color = { 'r' 'b' 'g' 'c' }; elseif ~iscell(color) color = { color }; end; if nargin < 5 transparent = 0.5; end; X1 = X(:)'; X2 = X(:)'; % remove NaNs tmpnan1 = find(isnan(Y1)); tmpnan2 = find(isnan(Y2)); Y1(tmpnan1) = []; X1(tmpnan1) = []; Y2(tmpnan2) = []; X2(tmpnan2) = []; % remove 0s if log scale if strcmpi(get(gca, 'yscale'), 'log') tmp1 = find(~Y1); tmp2 = find(~Y2); Y1(tmp1) = []; X1(tmp1) = []; Y2(tmp2) = []; X2(tmp2) = []; end; % multiple curve plot % ------------------- if size(Y1,1) ~= 1 && size(Y1,2) ~= 1 for index = 1:size(Y1,2) fillcurves(X, Y1(:,index)', Y2(:,index)', color{index}, transparent); hold on; end; yl = ylim; xl = xlim; line([xl(1) xl(1)]+(xl(2)-xl(1))/2000, yl, 'color', 'k'); line(xl, [yl(1) yl(1)]+(yl(2)-yl(1))/2000, 'color', 'k'); % write legend and add transparency to it % --------------------------------------- if nargin > 5 h = legend(legends); hh = get(h, 'children'); for index = 1:length(hh) fields = get(hh(index)); if isfield(fields, 'FaceAlpha'); numfaces = size(get(hh(index), 'Vertices'),1); set(hh(index), 'FaceVertexCData', repmat([1 1 1], [numfaces 1]), 'Cdatamapping', 'direct', 'facealpha', transparent, 'edgecolor', 'none'); end; end; end; return; end; % plot % ---- allpointsx = [X1 X2(end:-1:1)]'; allpointsy = [Y1 Y2(end:-1:1)]'; h = fill(allpointsx, allpointsy, color{1}); set(h, 'edgecolor', color{1}); xlim([ X(1) X(end) ]); if transparent numfaces = size(get(h, 'Vertices'),1); set(h, 'FaceVertexCData', repmat([1 1 1], [numfaces 1]), 'Cdatamapping', 'direct', 'facealpha', transparent, 'edgecolor', 'none'); end; % replot lines at boundaries % -------------------------- parent = dbstack; if length(parent) == 1 || ~strcmpi(parent(2).name, 'fillcurves') yl = ylim; xl = xlim; line([xl(1) xl(1)]+(xl(2)-xl(1))/2000, yl, 'color', 'k'); line(xl, [yl(1) yl(1)]+(yl(2)-yl(1))/2000, 'color', 'k'); end;
github
ZijingMao/baselineeegtest-master
timefrq.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/timefrq.m
13,419
utf_8
ad65c647dd826b2a55590fc457103cb5
% timefrq() - progressive Power Spectral Density estimates on a single % EEG channel using out-of-bounds and muscle activity rejection % tests. Uses Matlab FFT-based psd(). % Usage: % >> [Power,frqs,times,rejections] = timefrq(data,srate,subwindow); % >> [Power,frqs,times,rejections] = ... % timefrq(data,subwindow,fftwindow,substep, ... % epochstep,overlap,srate,nfreqs, ... % rejthresh,minmuscle,maxmuscle,musthresh); % % Inputs: % data = single-channel (1,frames) EEG data {none} % srate = data sampling rate (Hz) {256 Hz} % subwindow = subepoch data length per psd() {<=256} % % fftwindow = subepoch FFT window length after zero-padding % (determines freq bin width) {subwindow} % substep = subepoch step interval in frames {subwindow/4} % epochstep = output epoch step in frames {subwindow*2} % overlap = overlap between output epochs in frames {subwindow*2} % total epoch length is (overlap+epochstep) % nfreqs = nfreqs to output (2:nfreqs+1), no DC {fftwindow/4} % rejthresh = abs() rejection threshold for subepochs {off} % If in (0,1) == percentage of data to reject; else % reject subepochs reaching > the given abs value. % minmuscle = lower bound of muscle band (Hz) {30 Hz} % maxmuscle = upper bound of muscle band (Hz) {50 Hz} % musthresh = mean muscle-band power rejection threshold % (no percentile option) {off} % % Note: frequency of resulting rejections in tty output % ('o'=out-of-bounds rejection;'+' = muscle band rejection) % % Outputs: % Power - time-frequency transform of data (nfreqs,data_epochs) % frqs - frequency bin centers (in Hz) [DC bin not returned] % times - midpoints of the output analysis epochs (in sec.) % rejections - 8-element vector of rejection statistics = % [rejthresh,musthresh,goodepochs,badepochs,subacc,subrej,oobrej,musrej] % * rejthresh = out-of-bounds abs rejection threshold % * musthresh = muscle-band power rejection threshold % * goodepochs,badepochs = numbers of epochs accepted/rejected % * subacc,subrej = numbers of subepochs accepted/rejected % * oobrej,musrej = numbers of subepochs rejected for oob/muscle % % Authors: Tzyy-Ping Jung & Scott Makeig, SCCN/INC/UCSD, La Jolla, 10/1/97 % % See also: timef() % Copyright (C) 10/1/97 Tzyy-Ping Jung & 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 % 11-17-97 added rejections vector output -sm % 01-25-02 reformated help & license, added links -ad function [Power,frqs,times,rejections] = timefrq(data,subwindow,fftwindow,substep,epochstep,overlap,srate,nfreqs,rejthresh,minmuscle,maxmuscle,musclethresh); MINMUSCLE = 30; % Hz MAXMUSCLE = 50; % Hz DEFAULT_SRATE = 256; % Hz MIN_SUBWINDOW = 8; MAX_SUBWINDOW = 256; MINSUBEPOCHS = 3; % min number of non-rejected subepochs to median-average SURFPLOT = 1; % flag to make a surf(|) plot of the time*freq results HISTPLOT = 0; % flag to plot the EEG histogram OOB = 1e22; % out-of-bounds large number if nargin<1 help timefrq return end [chans,frames] = size(data); if chans>1, fprintf('timefrq(): data must be one-channel.\n'); help timefrq return end if nargin < 12 musclethresh = 0; end if musclethresh==0, musclethresh = OOB; % DEFAULT end if nargin < 11 maxmuscle = 0; end if maxmuscle==0, maxmuscle = MAXMUSCLE; % DEFAULT end if nargin < 10 minmuscle = 0; end if minmuscle==0, minmuscle = MINMUSCLE; % DEFAULT end if nargin < 9 rejthresh = 0; end if rejthresh==0, rejthresh = OOB; % DEFAULT end if nargin < 8 nfreqs = 0; end if nargin < 7 srate = 0; end if srate==0, srate = DEFAULT_SRATE; end if nargin < 6 overlap = 0; end if nargin < 5, epochstep =0; end if nargin < 4, substep =0; end if nargin < 3 fftwindow =0; end if nargin < 2, subwindow = 0; end if subwindow==0, subwindow = 2^round((log(frames/64)/log(2))); % DEFAULT if subwindow > MAX_SUBWINDOW, fprintf('timefrq() - reducing subwindow length to %d.\n',subwindow); subwindow = MAX_SUBWINDOW; end end if subwindow < MIN_SUBWINDOW fprintf('timefrq() - subwindow length (%d) too short.\n',subwindow); return end if fftwindow==0, fftwindow=subwindow; % DEFAULT end if fftwindow < subwindow fprintf('timefrq() - fftwindow length (%d) too short.\n',fftwindow); return end if substep==0, substep=round(subwindow/4); % DEFAULT end if substep < 1 fprintf('timefrq() - substep length (%d) too short.\n',substep); return end if epochstep==0, epochstep=subwindow*2; % DEFAULT end if epochstep < 1 fprintf('timefrq() - epochstep length (%d) too short.\n',epochstep); return end if overlap==0, overlap=subwindow*2; % DEFAULT end if overlap > epochstep fprintf('timefrq() - overlap (%d) too large.\n',overlap); return end if nfreqs==0, nfreqs=floor(fftwindow/2); % DEFAULT end if nfreqs > floor(fftwindow/2) fprintf('timefrq() - nfreqs (%d) too large.\n',nfreqs); return end % %%%%%%%%%%%%%%% Compute rejection threshold from percentile %%%%%%%%%%%%%%% % if rejthresh > 0 & rejthresh < 1.0, disp yes data = data - mean(data); % make data mean-zero fprintf('Sorting mean-zeroed data to compute rejection threshold...\n'); sortdat = sort(abs(data)); rejpc = 1.0-rejthresh; idx = max(1,round(rejpc*frames)); rejthresh = sortdat(idx); titl = [ 'Out-of-bounds rejection threshold is +/-' ... num2str(rejthresh) ... ' (' num2str(100*rejpc) ' %ile)']; if HISTPLOT % %%%%%%%%%%%%%% Plot data histogram %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % figure; % plot figure for reference hist(data,50); % histogram with 50 bins hold on; ax = axis; % get current axis limits axis([ax(1) ax(2) ax(3) frames/50]); % see side bins clearly plot([rejthresh rejthresh],[0 1e10],'g'); plot([-rejthresh -rejthresh],[0 1e10],'g'); title(titl); else fprintf('%s\n',titl); fprintf('timefrq(): data histogram plotting disabled.\n'); end end if nfreqs > fftwindow/2 fprintf('fftwindow of %d will output only %d frequencies.\n',... fftwindow,fftwindow/2); return elseif nfreqs<1 help timefrq fprintf('Number of output frequencies must be >=1.\n'); return end Power=zeros(nfreqs+1,floor(frames/epochstep)); % don't use a final partial epoch badepochs=0; % epochs rejected totacc = 0; % subepochs accepted totrej = 0; % subepochs rejected musrej = 0; % subepochs rejected for muscle artifact oobrej = 0; % subepochs rejected for out-of-bounds values firstpsd = 1; % logical variable zcol = zeros(fftwindow/2+1,1); % column of zeros % %%%%%%%%%%%%%%%%%%%%%%%% Print header info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % start = 1; stop=min(epochstep,frames); fprintf('\nMoving power spectrum will use epochs of %d frames\n',... epochstep+overlap) fprintf('output at intervals of %d frames.\n',epochstep); fprintf('Each epoch is composed of %d subepochs of %d frames\n',... floor((epochstep+overlap+1-subwindow)/substep), subwindow); fprintf('starting at %d-frame intervals', substep); if fftwindow>subwindow, fprintf(' and zero-padded to %d frames\n',fftwindow); else fprintf('.\n') end fprintf(... 'Rejection criteria: "o" out-of-bounds (>%g), "+" muscle activity (>%g)\n',... rejthresh,musclethresh); % %%%%%%%%%%%%%%%%%%%%% Process data epochs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % times = zeros(1,1+floor((frames-subwindow)/epochstep)); frqs = zeros(1,nfreqs+1); % initialize in case no valid psd returns ptmpzeros=zeros(fftwindow/2+1,ceil((stop-start+1)/substep)); epoch = 0; % epoch counter for I=1:epochstep:frames-subwindow ; % for each epoch . . . epoch=epoch+1; start=max(1,I-overlap); stop=min(I+epochstep+overlap-1,frames); times(epoch) = round((stop+start)/2); % midpoint of data epoch % %%%%%%%%%%%%%%%%%%%%%%%%%% Process subepochs %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % tmp=data(start:stop); % copy data subepoch subepoch=0; % subepoch counter rej = 0; % initialize subepoch rejections counter ptmp=ptmpzeros; % start with zeros for j=1:substep:stop-start+1-subwindow , % for each subepoch . . . subepoch=subepoch+1; % idx=find(abs(tmp(j:min(j+subwindow-1,stop-start+1))) <= rejthresh); % if length(idx) > subwindow/2 | subepoch == 1 idx=find(abs(tmp(j:min(j+subwindow-1,stop-start+1))) > rejthresh); if length(idx) == 0 % If no point in subepoch out of bounds datwin = tmp(j:j+subwindow-1)-mean(tmp(j:j+subwindow-1)); % get 1 power est. for subepoch. [ptmp(:,subepoch),frqs]=psd(datwin,fftwindow,srate,hanning(subwindow),0); if firstpsd > 0 % On very first subepoch muscle = find(frqs>=minmuscle & frqs<=maxmuscle); firstpsd = 0; % compute muscle band frequency bins. end if mean(ptmp(muscle,subepoch))>musclethresh rej = rej+1; fprintf('+') % If muscle-band out of bounds musrej = musrej+1; if subepoch > 1 ptmp(:,subepoch)=ptmp(:,subepoch-1); % reject for muscle noise. else ptmp(:,subepoch)=zcol; % set back to zeros end end else % some data value out of bounds rej = rej+1;fprintf('o') % so reject for out of bounds oobrej = oobrej+1; if subepoch > 1 ptmp(:,subepoch)=ptmp(:,subepoch-1); end end end % end of subepochs k = 1; while ptmp(:,k) == zcol % while subepoch power values all zeros . . . % sum(ptmp(:,k)) k = k+1; if k > subepoch, break end end if rej>0, fprintf('\n'); fprintf(' epoch %d: %d of %d subepochs rejected ',epoch,rej,subepoch); totrej = totrej+rej; totacc = totacc+(subepoch-rej); else fprintf('.'); end if k>subepoch fprintf('(no non-zero subepochs)\n',k); elseif k>1 fprintf('(first non-zero subepoch %d)\n',k); elseif rej>0 fprintf('\n') end if k<= subepoch & subepoch-rej >= MINSUBEPOCHS Power(:,epoch)=[median(ptmp(1:nfreqs+1,k:subepoch)')]'; % omit initial zero cols elseif epoch > 1 Power(:,epoch) = Power(:,epoch-1); fprintf ('') badepochs = badepochs+1; end end % end epochs Power = Power(2:nfreqs+1,:); % omit DC power bin frqs = frqs(2:nfreqs+1); % omit DC power bin times = times/srate; % convert to seconds if length(times)>1 time_interval = times(2)-times(1); else time_interval = 0; end if nargout>3, rejections = [rejthresh,musclethresh,epoch-badepochs,badepochs,... totacc,totrej,oobrej,musrej]; end if epoch<1 fprintf('No epochs processed: too little data.\n'); return end % %%%%%%%%%%%%%%%% Print trailer info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fprintf('\nTotal of %d epochs processed (%d rejected).\n',... epoch,badepochs); fprintf('Output is %d freqs by %d epochs.\n',... nfreqs,length(times)); fprintf('Output epoch length %d frames (%g secs).\n', ... epochstep+overlap,(epochstep+overlap)/srate); fprintf('Output interval %d frames (%g secs).\n', ... epochstep,time_interval); fprintf('First and last time points: %g and %g secs.\n',... times(1),times(length(times))); % %%%%%%%%%%%%%%% Make surf() plot of time-frequency distribution %%%%%% % if nfreqs>1 & epoch>1 & SURFPLOT if min(min(Power))>0 fprintf('Plot shows dB log(Power) - Power output is not log scaled.\n'); off = [50 -50 0 0]; % successive figure offset in pixels pos = get(gcf,'Position'); figure('Position',pos+off); % make the 2nd plot offset from the 1st surf(times,frqs,10*log(Power)/log(10)) view([0 90]); % top view xlabel('Time (sec)') ylabel('Frequency (Hz)') shading interp title('timefrq()'); c=colorbar; t=axes('Position',[0 0 1 1],'Visible','off'); text(0.85,0.08,'dB','Parent',t); else fprintf('Some or all output Power estimates were zero - too many rejections?\n'); end end
github
ZijingMao/baselineeegtest-master
imagescloglog.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/imagescloglog.m
4,970
utf_8
88feced6e3b718c968cee7ee9cce24f6
% imagescloglog() - make an imagesc(0) plot with log y-axis and % x-axis values % % Usage: >> imagescloglog(times,freqs,data); % Usage: >> imagescloglog(times,freqs,data,clim,xticks,yticks,'key','val',...); % % Inputs: % times = vector of x-axis values (LOG spaced) % freqs = vector of y-axis values (LOG spaced) % data = matrix of size (freqs,times) % % Optional inputs: % clim = optional color limit % xticks = graduation for x axis % yticks = graduation for y axis % ... = 'key', 'val' properties for figure % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 4/2003 % Copyright (C) 4/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 imagescloglog(times,freqs,data,clim, xticks, yticks, varargin) if size(data,1) ~= length(freqs) fprintf('logfreq(): data matrix must have %d rows!\n',length(freqs)); return end if size(data,2) ~= length(times) fprintf('logfreq(): data matrix must have %d columns!\n',length(times)); return end if min(freqs)<= 0 fprintf('logfreq(): frequencies must be > 0!\n'); return end try, icadefs; catch, warning('Using MATLAB default colormap'); end steplog = log(times(2))-log(times(1)); % same for all points realborders = [exp(log(times(1))-steplog/2) exp(log(times(end))+steplog/2)]; newtimes = linspace(realborders(1), realborders(2), length(times)); % regressing 3 times border = mean(newtimes(2:end)-newtimes(1:end-1))/2; % automatically added to the borders in imagesc newtimes = linspace(realborders(1)+border, realborders(2)-border, length(times)); border = mean(newtimes(2:end)-newtimes(1:end-1))/2; % automatically added to the borders in imagesc newtimes = linspace(realborders(1)+border, realborders(2)-border, length(times)); border = mean(newtimes(2:end)-newtimes(1:end-1))/2; % automatically added to the borders in imagesc newtimes = linspace(realborders(1)+border, realborders(2)-border, length(times)); % problem with log images in Matlab: border are automatically added % to account for half of the width of a line: but they are added as % if the data was linear. The commands below compensate for this effect steplog = log(freqs(2))-log(freqs(1)); % same for all points realborders = [exp(log(freqs(1))-steplog/2) exp(log(freqs(end))+steplog/2)]; newfreqs = linspace(realborders(1), realborders(2), length(freqs)); % regressing 3 times border = mean(newfreqs(2:end)-newfreqs(1:end-1))/2; % automatically added to the borders in imagesc newfreqs = linspace(realborders(1)+border, realborders(2)-border, length(freqs)); border = mean(newfreqs(2:end)-newfreqs(1:end-1))/2; % automatically added to the borders in imagesc newfreqs = linspace(realborders(1)+border, realborders(2)-border, length(freqs)); border = mean(newfreqs(2:end)-newfreqs(1:end-1))/2; % automatically added to the borders in imagesc newfreqs = linspace(realborders(1)+border, realborders(2)-border, length(freqs)); if nargin == 4 & ~isempty(clim) imagesc(newtimes,newfreqs,data,clim); else imagesc(newtimes,newfreqs,data); end; set(gca, 'yscale', 'log', 'xscale', 'log'); try colormap(DEFAULT_COLORMAP); catch, end; % puting ticks % ------------ if nargin >= 5 divs = xticks; else divs = linspace(log(times(1)), log(times(end)), 10); divs = ceil(exp(divs)); divs = unique_bc(divs); % ceil is critical here, round might misalign % out-of border label with within border ticks end; set(gca, 'xtickmode', 'manual'); set(gca, 'xtick', divs); if nargin >= 6 divs = yticks; else divs = linspace(log(freqs(1)), log(freqs(end)), 10); divs = ceil(exp(divs)); divs = unique_bc(divs); % ceil is critical here, round might misalign % out-of border label with within border ticks end; set(gca, 'ytickmode', 'manual'); set(gca, 'ytick', divs); % additional properties % --------------------- set(gca, 'yminortick', 'off', 'xaxislocation', 'bottom', 'box', 'off', 'ticklength', [0.03 0], 'tickdir','out', 'color', 'none'); if ~isempty(varargin) set(gca, varargin{:}); end;
github
ZijingMao/baselineeegtest-master
envproj.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/envproj.m
12,184
utf_8
39c255194bd438d2939c0ab3b8c748d1
% envproj() - plot envelopes of projections of selected ICA component % projections against envelope of the original data % % Usage: >> [envdata] = envproj(data,weights,compnums); % >> [envdata] = envproj(data,weights,compnums, ... % title,limits,chanlist,compnames,colors); % Inputs: % data = runica() input data (chans,frames) <- best one epoch only! % weights = unmixing weight matrix (runica() weights*sphere) % compnums = list of component numbers to project and plot % % Optional inputs: % title = 'fairly short plot title' (in quotes) (0 -> none) % limits = [xmin xmax ymin ymax] (x's in msec) % (0 or both y's 0 -> [min max]) % chanlist = list of data channels to use for max/min (0 -> all) % compnames = file of component labels (exactly 5 chars per line, % trailing '.' = space) (default|0 -> compnums) % colors = file of color codes, 3 chars per line ('.' = space) % (0 -> default color order (black/white first)) % % Output: % envdata = [2,(frames*length(compnums)+1)] envelopes of data, comps. % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 1/1997 % % See also: envtopo() % Copyright (C) 01-23-97 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 % 03-19-97 use datamean instead of frames/baseframes, diag(cov()) for var() -sm % 04-03-97 changed name to envproj() -sm % 05-20-97 used sum-of-squares for var instead of diag() to allow long data % read MAXPLOTDATACHANS from icadefs.m -sm % 06-07-97 changed order of args to conform to runica -sm % 06-18-97 read MAXENVPLOTCHANS instead of MAXPLOTDATACHANS -sm % 07-23-97 dropped datamean from args; mean is distributed among components -sm % 10-11-97 range of max/min for default ylimits over chanlist only! -sm % 11-05-97 disallowed white lines unless axis color is white -sm & ch % 11-13-97 rm'd errorcode variable to improve limits handling -sm % 11-18-97 added legend to plot; varied line types -sm % 11-30-97 added f=figure below to keep previous plot from being altered -sm % 12-01-97 added thicker lines for data envelope -sm % 12-08-97 debugged thicker lines for data envelope -sm % 12-10-97 changed f=figure below to f=gcf to avoid matlab bug (gcf confusion) -sm % 12-10-97 implemented compnames arg -sm % 12-13-97 took out compnames=compnames'; bug -sm % 02-06-98 added 'show-largest' feature to legend when numcomps > 7 -sm % 02-09-98 fixed numcomps bug -sm % 02-12-98 test for outofbounds compnums early -sm % 04-28-98 made to work for rectangular weights -sm % 06-05-98 made NEG_UP optional -sm % 02-22-99 added FILL mode default when numcomps==1 -sm % 03-14-99 made envelope finding code more efficient -sm % 12-19-00 updated icaproj() args -sm % 01-25-02 reformated help & license, added links -ad function [envdata] = envproj(data,weights,compnums,titl,limits,chanlist,compnames,colors) FILL = 1; % 1; % 1 = fill in component envelope unless ncomps>1 DATA_LINEWIDTH = 1.5; % 2 COMP_LINEWIDTH = 1.5; % 1 MAXENVPLOTCHANS = 256; if nargin < 3, help envproj fprintf('envproj(): must have at least three arguments.\n'); return end icadefs % load ENVCOLORS & MAXENVPLOTCHANS default variables MAX_LEG = 7; % maximum number of component line types to label in legend NEG_UP = 0; % 1 = plot negative up % %%%%%%%%%%%% Substitute for omitted arguments %%%%%%%%%%%%%%%%%%%%%%%% % if nargin < 8, colors = 'envproj.col'; elseif colors(1)==0, colors = 'envproj.col'; end [chans,frames] = size(data); if nargin < 7 compnames = 0; end if nargin < 6 chanlist = 0; end if nargin < 5, limits = 0; end if nargin < 4, titl = 0; end % %%%%%%%%%%%%%%%%%%%%%%%% Test data size %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % [wr,wc] = size(weights); % %%%%%%%%%%%%%%%% Substitute for zero arguments %%%%%%%%%%%%%%%%%%%%%%%%% % if chanlist == 0, chanlist = [1:chans]; end; if compnums == 0, compnums = [1:wr]; end; if size(compnums,1)>1, % handle column of compnums ! compnums = compnums'; end; numcomps = length(compnums); if numcomps > MAXENVPLOTCHANS, fprintf(... 'envproj(): cannot plot more than %d channels of data at once.\n',... MAXENVPLOTCHANS); return end; if max(compnums)>wr fprintf('\nenvproj(): Component index %d out of bounds (1:%d).\n',... max(compnums),wr); return end if min(compnums)<1, fprintf('\nenvproj(): Component index %d out of bounds (1:%d).\n',... min(compnums),wr); return end if FILL>0 & numcomps == 1 FILL = 1; else FILL = 0; end % %%%%%%%%%%%%%%%%%%%% Read and adjust limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if limits==0, xmin=0;xmax=1; ymin=min(min(data(chanlist,:))); ymax=max(max(data(chanlist,:))); else if length(limits)~=4, fprintf( ... 'envproj(): limits should be 0 or an array [xmin xmax ymin ymax].\n'); return end; if limits(1,1) == 0 & limits(1,2) ==0, xmin=0; xmax=0; else xmin = limits(1,1); xmax = limits(1,2); end; if limits(1,3) == 0 & limits(1,4) ==0, ymin=0; ymax=0; else ymin = limits(1,3); ymax = limits(1,4); end; end; if xmax == 0 & xmin == 0, x = (0:1:frames-1); xmin = 0; xmax = frames-1; else dx = (xmax-xmin)/(frames-1); x=xmin*ones(1,frames)+dx*(0:frames-1); % construct x-values end; if ymax == 0 & ymin == 0, ymax=max(max(data(chanlist,:))); ymin=min(min(data(chanlist,:))); end % %%%%%%%%%%%%%%%%%%%% Read the color names %%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isstr(colors) fprintf('envproj(): color file name must be a string.\n'); return end cid = fopen(colors,'r'); if cid <3, fprintf('envproj(): cannot open file %s.\n',colors); return else colors = fscanf(cid,'%s',[3 MAXENVPLOTCHANS]); colors = colors'; [r c] = size(colors); for i=1:r for j=1:c if colors(i,j)=='.', colors(i,j)=' '; end; end; end; end; [rr cc] = size(colors); % %%%%%%%%%%%% Compute projected data for single components %%%%%%%%%%%%% % projdata = [data(chanlist,:)]; envdata = [min(projdata); max(projdata)]; % begin with envelope of data fprintf('envproj(): Projecting component(s) '); maxvars = zeros(1,length(compnums)); n=1; for c=compnums, % for each component fprintf('%d ',c); % [icaproj] = icaproj(data,weights,compindex); % new arg order 12/00 proj = icaproj(data,weights,c); % let offsets be % distributed among comps. [val,i] = max(sum(proj.*proj)); % find max variance maxvars(n) = val; proj = proj(chanlist,:); projdata = [projdata proj]; envtmp = [ min(proj) ; max(proj)]; envdata = [envdata envtmp]; % append envelope of projected data sets onto envdata % Note: size(envdata) = [length(chanlist) frames*(numcomps+1)] n = n+1; end; fprintf('\n'); % %%%%%%%%%%%%%%%%%%%%%%%% Make the plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~isstr(titl) if titl==0, titl = ' '; else fprintf('envproj(): titl unrecognized.\n'); return end end set(gcf,'Color',BACKCOLOR); % set the background color set(gca,'Color','none'); % set the axis color to the background color if NEG_UP set(gca,'Ydir','reverse'); end n = 1; H = zeros(1,numcomps+1); for c=1:numcomps+1; % % Plot envelopes % if n <= 6 if n == 1 % thick lines, store H for legend() H(n)=plot(x,envdata(1,(c-1)*frames+1:c*frames)',... colors(c),'Linewidth',DATA_LINEWIDTH); hold on; plot(x,envdata(2,(c-1)*frames+1:c*frames)',... colors(c),'Linewidth',DATA_LINEWIDTH); else if FILL fillx = [x x(frames:-1:1)]; filly = [envdata(1,(c-1)*frames+1:c*frames) ... envdata(2,c*frames:-1:(c-1)*frames+1)]; i = find(isnan(filly)==1); if ~isempty(i) fprintf('Replacing %d NaNs in envelope with 0s.\n',length(i)/2); filly(i)=0; end H(n) = fill(fillx,filly,colors(c)); else H(n)= plot(x,envdata(1,(c-1)*frames+1:c*frames)',... colors(c),'Linewidth',COMP_LINEWIDTH); hold on; plot(x,envdata(2,(c-1)*frames+1:c*frames)',... colors(c),'Linewidth',COMP_LINEWIDTH); end end else H(n)= plot(x,envdata(1,(c-1)*frames+1:c*frames)',... colors(c),'LineStyle',':','LineWidth',DATA_LINEWIDTH); hold on; plot(x,envdata(2,(c-1)*frames+1:c*frames)',... colors(c),'LineStyle',':','LineWidth',DATA_LINEWIDTH); end n = n+1; end set(gca,'Color','none'); % set the axis color to the background color l=xlabel('Time (ms)'); % xaxis label set(l,'FontSize',14); l=ylabel('Potential (uV)'); % yaxis label set(l,'FontSize',14); if xmax > 0 & xmin < 0 plot([0 0],[ymin ymax],'k','linewidth',1.5); % plot vertical line at time 0 end if ymax ~= 0 |ymin~= 0, axis([min(x),max(x),ymin,ymax]); else axis([min(x),max(x),min(envdata(1,:)'),max(envdata(2,:)')]); end legtext = [ 'Data ' ]; if compnames(1) ~= 0 pid = fopen(compnames,'r'); if pid < 3 fprintf('envproj(): file %s not found.\n',compnames); return end compnames = fscanf(pid,'%s',[5 numcomps]); compnames = [ ['Data.']' compnames]; compnames = compnames'; if size(compnames,1) ~= numcomps+1 fprintf('envproj(): no. of compnames must equal no. of compnums.\n'); return end for c=1:5 % remove padding with .'s for r = 1:size(compnames,1) if compnames(r,c) == '.' compnames(r,c) = ' '; end end end legtext = compnames; else legtext = ['Data']; for c = compnums legtext = strvcat(legtext,int2str(c)); end end if numcomps<MAX_LEG+1 if FILL <= 0 % no legend in FILL mode l=legend(H,legtext,0); % plot legend end else fprintf('Finding largest components for legend...\n'); [maxvars,i] = sort(maxvars); maxvars = maxvars(length(maxvars):-1:1); % sort large-to-small i= i(length(i):-1:1); H = [H(1) H(i+1)]; H = H(1:MAX_LEG+1); legtext = [legtext(1,:);legtext(i+1,:)]; legtext = legtext(1:MAX_LEG+1,:); legend(H,legtext,0); % MAX_LEG largest-peaked comps end set(gca,'FontSize',12); fprintf('If desired, use mouse to move legend or >> delete(legend).\n'); % %%%%%%%%%%%%% Compute percentage of variance accounted for %%%%%%%%%%%% % sumdata = zeros(length(chanlist),frames); for e=2:numcomps+1, % sum the component activities sumdata = sumdata + projdata(:,(e-1)*frames+1:e*frames); end sigssqr = sum(data(chanlist,:).*data(chanlist,:))/(length(chanlist)-1); dif = data(chanlist,:)-sumdata; difssqr = sum(dif.*dif)/(length(chanlist)-1); pvaf = round(100.0*(1.0-difssqr/sigssqr)); % % variance accounted for rtitl = ['(' int2str(pvaf) '%)']; %titl = [titl ' ' rtitl]; t=title(titl); % plot title set(t,'FontSize',14);
github
ZijingMao/baselineeegtest-master
difftopo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/difftopo.m
2,957
utf_8
65dc45bf74bc5bcc5cc398b529f2d026
% difftopo - compute and plot component decomposition for the difference ERP % between two EEG datasets. Plots into the current axis (gca); % plot into a new empty figure as below. % Usage: % >> figure; difftopo(ALLEEG,eeg1,eeg2,interval); % Inputs: % ALLEEG - array of leaded EEG datasets % eeg1 - index of subtrahend (+) dataset % eeg2 - index of minuend (-) dataset % interval - [minms maxms] latency interval in which to find % and plot largest contributing components {default: whole epoch} % limits - [stms endms] latenc plotting limits (in ms) {default|0: whole epoch} % subcomps - array of component indices to remove from data % (e.g. eye movement components) {default|0: none} % % Outputs: none % % Author: Scott Makeig, SCCN/INC/UCSD 3/28/05 % Copyright (C) Scott Makeig, SCCN/INC/UCSD 3/28/05 % % 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 difftopo(ALLEEG,eeg1,eeg2,interval,limits,subcomps); if nargin < 3 help difftopo return end if eeg1 < 1 | eeg1 > length(ALLEEG) help difftopo return end if eeg2 < 1 | eeg2 > length(ALLEEG) help difftopo return end if eeg1 == eeg2 help difftopo return end if ndims(ALLEEG(eeg1).data) ~=3 | ndims(ALLEEG(eeg2).data) ~=3 error('EEG datasets must be epoched data'); end if nargin < 4 interval = [ALLEEG(eeg1).xmin*999.9 ALLEEG(eeg1).xmax*999.9]; end if nargin < 5 limits = 0; % [ALLEEG(eeg1).xmin*1000 ALLEEG(eeg1).xmax*1000]; end if nargin < 6 subcomps = []; end if ~isfield(ALLEEG(eeg1),'icaweights') error('EEG datasets must have icaweights'); end if length(interval) ~= 2 help difftopo return end if ALLEEG(eeg1).pnts ~= ALLEEG(eeg1).pnts error('EEG datasets must have the same number of frames per epoch'); end set(gcf,'Name','difftopo()'); diff = mean(ALLEEG(eeg1).data,3) - mean(ALLEEG(eeg2).data,3); plottitle = [ ALLEEG(eeg1).setname ' - ' ALLEEG(eeg2).setname]; envtopo(diff,ALLEEG(eeg1).icaweights*ALLEEG(eeg1).icasphere,... 'chanlocs',ALLEEG(eeg1).chanlocs, ... 'timerange',[ALLEEG(eeg1).xmin*1000 ALLEEG(eeg1).xmax*1000],... 'limits',limits,... 'limcontrib',interval,... 'title',plottitle, ... 'subcomps',subcomps);
github
ZijingMao/baselineeegtest-master
testica.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/testica.m
8,781
utf_8
d0cf00d8dae57fbf21e94fd22542c1bf
% testica() - Test the runica() function's ability to separate synthetic sources. % Use the input variables to estimate the (best) decomposition accuracy % for a given data set size. % Usage: % >> testica(channels,frames); % No return variable -> plot results % >> [testresult] = testica(channels,frames,sources,exppow,shape); % % Return variable -> return results with no plots % Inputs: % channels = number of simulated data channels {no default} % frames = number of simulated time points {no default} % sources = number of simulated quasi-independent sources {default: =channels} % exppow = exponential power for scaling size of the sources (0->all equal) % {default: -0.05 -> Ex: 14 sources scaled between 1.0 and 0.24} % shape = varies monotonically with kurtosis of the simulated sources % {default: 1.2 -> source kurtosis near 1 (super-Gaussian>0)} % % Authors: Scott Makeig & Te-Won Lee, SCCN/INC/UCSD, La Jolla, 2-27-1997 % % See also: runica() % Copyright (C) 2-27-97 Scott Makeig & Te-Won Lee, 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 % 2-28-97 added source, shape and exppow parameters, kurtosis -sm % 4-03-97 shortened name to testica() -sm % 4-14-97 changed call to runica() to use new variable order -sm % 4-16-97 prints max and min abs corr -sm % 7-10-97 changed to newrunica(), added surf() plot -sm % 7-30-97 altered runica() call to fit version 3.0 -sm % 3-02-00 replaced idit() call with call to Benjamin Blankertz' eyeLike() -sm % 3-08-00 added kurt and exppow plots, changed defaults, added plot labels -sm % 01-25-02 reformated help & license, added links -ad function [testresult] = testica(channels,frames,sources,exppow,shape) icadefs; % read BACKCOLOR % Default runica() parameter values: block = 0; % default block size lrate = 0; % default starting lrate adeg = 0; % default annealing threshold maxsteps = 0; % default sphereflag = 'on'; % default yes, perform sphering stop = 0.000001; % default stopping wchange % Defaults: default_chans = 31; default_frames = 10000; % default sources = channels default_exppow = -0.05; default_shape = 1.2; plotflag = 1; try, plotflag = ismatlab; catch, end; if nargin<2 help testica return end if nargin<5 shape = default_shape; end if nargin<4 exppow = default_exppow; end if nargin<3, sources = 0; end if nargin<2 frames = 0; end if nargin < 1 channels = 0; end if frames == 0, frames = default_frames; end if channels == 0, channels = default_chans; end if sources == 0, sources = channels; end if sources < channels, fprintf('testica() - sources must be >= channels.\n'); exit 1 end % Generate artificial super-Gaussian sources: fprintf('\n Testing runica() using %d simulated sources.\n\n',sources); fprintf('Computing %d simulated source activations of length %d ...\n', ... sources,frames); fprintf('Simulated source strengths: %4.3f to %4.3f.\n', ... 1.0, exp(exppow*(channels-1))); exppowers = zeros(1,channels); exppowers(1) = 1.0; for s=1:sources exppowers(s) = exp(exppow*(s-1)); end % Synthesize random source activations super=randn(sources,frames).*(exppowers'*ones(1,frames)); super=sign(super).*abs(super.^shape); % make super-Gaussian if shape > 1 % fprintf('Size of super = %d,%d\n',size(super,1),size(super,2)); if frames > 40 && plotflag figure pos = get(gcf,'position'); off = [40 -40 0 0]; % succeeding figure screen position offsets hist(super(1,:),round(frames/20)); tt=title('Amplitude distribution of source 1'); set(tt,'fontsize',14); xlm=get(gca,'xlim'); ylm=get(gca,'ylim'); kurttext = ['Kurtosis = ' num2str(kurt(super(1,:)),3)]; tp=[xlm;ylm]*[0.25;0.75]; kt=text(tp(1),tp(2),kurttext); set(kt,'fontsize',13); set(kt,'horizontalalignment','center'); else fprintf('Not plotting source amplitude histogram: data length too small.\n') end if nargout == 0 && plotflag input('Hit enter to view source strengths: '); fprintf('\n') if frames <= 40 figure pos = get(gcf,'position'); else figure('position',pos+off); end plot(1:sources,exppowers); hold on;plot(1:sources,exppowers,'r^'); set(gca,'xlim',[0 sources+1]); set(gca,'ylim',[0 1]); xt=title(['Relative source amplitudes (exppow = ' num2str(exppow,3) ')']); set(xt,'fontsize',14); axl=xlabel('Source Number'); ayl=ylabel('Relative Amplitude'); set(axl,'fontsize',14); set(ayl,'fontsize',14); end k = kurt(super'); % find kurtosis of rows of super maxkurt = max(k); minkurt=min(k); fprintf('Simulated source kurtosis: %4.3f to %4.3f.\n',minkurt,maxkurt); tmp = corrcoef(super'); i = find(tmp<1); minoff = min(abs(tmp(i))); maxoff = max(abs(tmp(i))); fprintf('Absolute correlations between sources range from %5.4f to %5.4f\n', ... minoff,maxoff); fprintf('Mixing the simulated sources into %d channels ...\n',channels); forward = randn(channels,sources); % random forward mixing matrix data = forward*super; % these are the simulated observed data if nargout == 0 input('Hit enter to start ICA decomposition: ') fprintf('\n') end fprintf('Decomposing the resulting simulated data using runica() ...\n'); [weights,sphere,compvars,bias,signs,lrates,activations] = runica(data, ... 'block',block, ... 'lrate',lrate, ... 'nochange',stop, ... 'annealdeg',adeg, ... 'maxsteps',maxsteps, ... 'sphering',sphereflag, 'weights',eye(channels)); fprintf('ICA decomposition complete.\n'); % Alternatively, activations = icaact(data,weights,sphere,datamean); fprintf('\nScaling and row-permuting the resulting performance matrix ...\n') testid = weights*sphere*forward(:,1:channels); % if separation were complete, this % would be a scaled and row-permuted % identity matrix testresult = eyelike(testid); % permute output matrix rows to rememble eye() % using Benjamin Blankertz eyeLike() - 3/2/00 % testresult = idit(testid); % permute output matrix rows to rememble eye() % scale to make max column elements all = 1 tmp = corrcoef(activations'); i = find(tmp<1); maxoff = max(abs(tmp(i))); minoff = min(abs(tmp(i))); fprintf('Absolute activation correlations between %5.4f and %5.4f\n',minoff,maxoff); i = find(testresult<1); % find maximum abs off-diagonal value maxoff = max(abs(testresult(i))); meanoff = mean(abs(testresult(i))); if sources > channels, fprintf('The returned matrix measures the separation'); fprintf('of the largest %d simulated sources,\n',channels); end fprintf('Perfect separation would return an identity matrix.\n'); fprintf('Max absolute off-diagonal value in the returned matrix: %f\n',maxoff); fprintf('Mean absolute off-diagonal value in the returned matrix: %f\n',meanoff); [corr,indx,indy,corrs] = matcorr(activations,super); fprintf('Absolute corrs between best-matching source and activation\n'); fprintf(' component pairs range from %5.4f to %5.4f\n', ... abs(corr(1)),abs(corr(length(corr)))); if nargout == 0 fprintf('\nView the results:\n'); fprintf('Use mouse to rotate the image.\n'); end if ~plotflag, return; end; figure('Position',pos+2*off); set(gcf,'Color',BACKCOLOR); surf(testresult); % plot the resulting ~identity matrix st=title('Results: Test of ICA Separation'); set(st,'fontsize',14) sxl=xlabel('Source Out'); set(sxl,'fontsize',14); syl=ylabel('Source In'); set(syl,'fontsize',14); szl=zlabel('Relative Recovery'); set(szl,'fontsize',14); view(-52,50); axis('auto'); if max(max(abs(testresult)))>1 fprintf('NOTE: Some sources not recovered well.\n'); fprintf('Restricting plot z-limits to: [-1,1]\n'); set(gca,'zlim',[-1 1]); end rotate3d if nargout == 0 testresult = []; end
github
ZijingMao/baselineeegtest-master
promax.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/promax.m
4,345
utf_8
82f2ef61454eb31fd54b2edd42f8cc47
% promax() - perform Promax oblique rotation after orthogonal Varimax % rotation of the rows of the input data. A method for % linear decomposition by "rotating to simple structure." % Usage: % >> [R] = promax(data,ncomps); % >> [R,V] = promax(data,ncomps,maxit); % % Inputs: % data - Promax operates on rows of the input data matrix % ncomps - operate on the N largest PCA components (default|0 -> all) % maxit - maximum number of iterations {default|0 -> 5} % % Outputs: % R - is the non-orthogonal Promax rotation matrix % i.e., >> promax_rotated_data = R*data; % V - is the orthogonal Varimax rotation matrix % i.e., >> varimax_rotated_data = V*data; % % Author: Colin Humphries, CNL / Salk Institute, 1998 % % See also: runica() % Copyright (C) Colin Humphries, CNL / Salk Institute, June 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 % formatted and modified to return V by Scott Makeig, 6/23/98 % reset maxit default to 5, added ncomps -sm 7/8/98 % 01-25-02 reformated help & license, added links -ad % % Reference: % % Hendrickson AE and White PO (1964) Promax: A quick method for rotation % to oblique simple structure, Br J of Stat Psych, X:xxx-xxx. function [R,V] = promax(data,ncomps,maxit) v = version; indp = find(v == '.'); v = str2num(v(1:indp(2)-1)); if v >= 8.1 disp('Note: for some unknown reason, this function does not return') disp(' NaN for a singular matrix under Matlab 2013a and later versions.') disp(' Promax on other matrices seems to as in previous revisions though.'); end; DEFAULT_POWER = 4; DEFAULT_TOLERANCE = 1e-5; MAX_ITERATIONS = 5; NEAR_ZERO = 1e-8; powr = DEFAULT_POWER; tol = DEFAULT_TOLERANCE; if nargin < 1 help promax return end if isempty(data) help promax return end if nargin < 2 ncomps = 0; end chans = size(data,1) if ncomps == 0 ncomps = chans end if ncomps > chans error(sprintf('promax(): components must be <= number of data rows (%d).\n',chans)); end if nargin < 3 maxit = 0; end if maxit == 0 maxit = MAX_ITERATIONS; end if ncomps < chans [eigenvectors,eigenvalues,compressed,datamean] = pcsquash(data,ncomps); data = compressed; clear compressed; eigenvectors = eigenvectors(:,1:ncomps); % make non-square eigenwts = pinv(eigenvectors); % find forward (non-square) weight matrix end R = varimax(data); % run Varimax on the (projected) data B = R*data; % compute rotated data V = R; % save Varimax matrix as V if ncomps < chans V = V*eigenwts; % include PCA reduction matrix end B = B'; % transpose R = R'; cont = 1; fprintf(... 'Finding oblique Promax rotation using exponent %g and tolerance %g\n',... powr,tol) it = 1; Pz = zeros(size(B)); while cont & it <= maxit P = Pz; ii = find(abs(B) > NEAR_ZERO); % avoid division by 0 P(ii) = (abs(B(ii).^(powr+1)))./B(ii); tmp = inv(B'*B)*B'*P; tmp = normalcol(tmp); Rn = R*tmp; B = B*tmp; distnew = dot(Rn(:),R(:)); if it > 1 delta = abs(distnew-distold); if delta < tol cont = 0; end fprintf('#%d delta %f\n',it,delta) if isnan(delta) cont = 0; end end R = Rn; distold = distnew; it = it+1; end B = B'; R = R'; if ncomps < chans R = R*eigenwts; % include the pcsquash() compression end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function n=normalcol(m) if isempty(m) fprintf('normalcol() has empty input!\n'); return end [mr,mc] = size(m); n = sqrt(ones./sum(m.*m)); n = ones(mr,1)*n; n = n.*m;
github
ZijingMao/baselineeegtest-master
eegplotsold.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/eegplotsold.m
7,020
utf_8
391a73c20463597978977b106bb495f5
% eegplotsold() - display data in a clinical format without scrolling % % Usage: % >> eegplotsold(data, srate, 'chanfile', 'title', ... % yscaling, epoch, linecolor,xstart,vertmark) % % Inputs: % data - data matrix (chans,frames) % srate - EEG sampling rate in Hz (0 -> 256 Hz) % 'chanfile' - file of channel info, topoplot() style, (0 -> chan nos) % 'title' - plot title string {0 -> 'eegplotsold()'} % yscaling - initial y scaling factor (0 -> 300) % epoch - how many seconds to display in window (0 -> 10 sec) % linecolor - color of eeg (0 -> 'y') % xstart - start time of the data {0 -> 0} % vertmark - vector of frames to mark with vertical lines {0 -> none} % % Author: Colin Humphries, CNL, Salk Institute, La Jolla, 3/97 % % See also: eegplot(), eegplotold(), eegplotgold() % Copyright (C) Colin Humphries, CNL, Salk Institute 3/97 from eegplotold() % % 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 % 05-01-97 added xstart argument -sm % 05-20-97 added read of icadefs.m % 06-12-97 EPOCH -> epoch line 71 below -sm % 8-10-97 Clarified chanfile type -sm % 12-08-97 Added isstr(titleval) test -sm % 02-09-98 legnth(data)->size(data,2) -sm % 01-25-02 reformated help & license, added links -ad %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = eegplotsold(data, srate, channamefile, titleval, yscaling, epoch, linecolor,xstart,vertmark) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Define defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% icadefs; % read MAXEEGPLOTCHANS, DEFAULT_SRATE, DEFAULT_EPOCH from icadefs.m if nargin < 1 help eegplotsold % print usage message PLOT_TIME = 10; data = 0.5*randn(8,floor(DEFAULT_SRATE*PLOT_TIME*2)); titleval = ['eegplotsold() example - random noise']; % show example plot end [chans,frames] = size(data); %size of data matrix % set initial spacing DEFAULT_SPACING = max(max(data')-min(data')); % spacing_var/20 = microvolts/millimeter with 21 channels % for n channels: 21/n * spacing_var/20 = microvolts/mm % for clinical data. DEFAULT_PLOTTIME = 10; % default 10 seconds per window DEFAULT_TITLE = 'eegplotsold()'; errorcode=0; % initialize error indicator %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Allow for different numbers of arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin < 9, vertmark = 0; end if nargin < 8, xstart = 0; end if nargin < 7 linecolor = 'y'; % DEFAULT LINECOLOR end if linecolor == 0, linecolor = 'y'; % DEFAULT LINECOLOR end if nargin < 6 PLOT_TIME = 0; else PLOT_TIME = epoch; end if nargin < 5 spacing_var = 0; else spacing_var = yscaling; end if spacing_var == 0 spacing_var = DEFAULT_SPACING; end if nargin < 4 titleval = DEFAULT_TITLE; end if ~isstr(titleval) if titleval == 0 titleval = DEFAULT_TITLE; else help eegplotsold return end end if nargin < 3 channamefile = 0; end if nargin < 2 srate = DEFAULT_SRATE; end if srate == 0, srate = DEFAULT_SRATE; end; if PLOT_TIME == 0 PLOT_TIME = ceil(frames/srate); if PLOT_TIME > DEFAULT_EPOCH PLOT_TIME = DEFAULT_EPOCH; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Define internal variables %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% maxtime = frames / srate; %size of matrix in seconds %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Read the channel names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if channamefile ~=0, % read file of channel names chid = fopen(channamefile,'r'); if chid <3, fprintf('plotdata: cannot open file %s.\n',channamefile); errorcode=2; channamefile = 0; else % fprintf('Chan info file %s opened\n',channamefile); end; if errorcode==0, channames = fscanf(chid,'%d %f %f %s',[7 MAXEEGPLOTCHANS]); channames = channames'; channames = setstr(channames(:,4:7)); % convert ints to chars [r c] = size(channames); for i=1:r for j=1:c if channames(i,j)=='.', channames(i,j)=' '; % convert dots to spaces end; end; end; % fprintf('%d channel names read from file.\n',r); if (r>chans) fprintf('Using first %d names.\n',chans); channames = channames(1:chans,:); end; if (r<chans) fprintf('Only %d channel names read.\n',r); end; end; end if channamefile ==0, % plot channel numbers channames = []; for c=1:chans if c<10, numeric = [' ' int2str(c)]; % four-character fields else numeric = [' ' int2str(c)]; end channames = [channames;numeric]; end; end; % setting channames channames = str2mat(channames, ' '); % add padding element to Y labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Make matrix of x-tick labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Xlab = num2str(0); % for j = 1:1:PLOT_TIME % Q = num2str(0+j); % Xlab = str2mat(Xlab, Q); % end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Set Graph Characteristics %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% hold on; set (gca, 'xgrid', 'on') % Xaxis gridlines only set (gca, 'GridLineStyle','-') % Solid grid lines % set (gca, 'XTickLabel', Xlab) % Use Xlab for tick labels % set (gca, 'XTick', 0*srate:1.0*srate:PLOT_TIME*srate) set (gca, 'Box', 'on') set (gca, 'Ytick', 0:spacing_var:chans*spacing_var) % ytick spacing on channels set (gca, 'TickLength', [0.02 0.02]) title(titleval) % title is titleval axis([xstart xstart+PLOT_TIME 0 (chans+1)*spacing_var]); set (gca, 'YTickLabels', flipud(channames),'FontSize',14) % write channel names % Matlab-5 requires YTickLabels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot the selected EEG data epoch %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% xx = xstart:1/srate:xstart+PLOT_TIME-0.9/srate; % x-values xx = xx(:,1:size(data,2)); for i = 1:chans F = data(chans-i+1,:); F = F - mean(F) + i*spacing_var; % add offset to y-values plot (xx,F,'clipping','off','Color',linecolor); % channel plot with x-values end if xstart<0 & xstart+PLOT_TIME > 0 linetime = round(-xstart/srate); line ([linetime linetime],[1e10,-1e10]); end if vertmark ~= 0, for mark = vertmark, linetime = xstart + (mark-1)/srate; line ([linetime linetime],[-1e10,1e10],'Color','y','LineStyle',':'); end end
github
ZijingMao/baselineeegtest-master
show_events.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/show_events.m
7,188
utf_8
d36cd636e2fbb7e2a1aeab8faef8155d
% show_events() - Display events in epochs. Events selected by % make_timewarp() function can be optionally highlighted. % Each epoch is visualized as a row in the output image with % events marked by colored rectangles. % % Usage: % >> im = show_events(EEG, 'key1',value1,'key2',value2,...); % % Inputs: % % EEG - dataset structure. % % % Optional inputs (in 'key', value format): % % 'eventThicknessCoef' - (positive number) adjust the thickness of event % markers in the image. The default value is 1. % Lower values reduce thickness and higher values % increase it. For example, to decrease event % rectangle width by half, set this parameter to % 0.5. {default: 1} % 'eventNames' - a cell array containing names of events to be % displayed. Order and repetition are ignored. % {default: all events if timeWarp is not provided) % % 'timeWarp' - a structure with latencies (time-warp matrix % for newtimef function) and epochs with correct % sequence created by make_timewarp() function. % the subsets {default: false|0) % Outputs: % % im - color (RGB) image showing events of interest in % epochs. % % Example: % % % To display all events in data structure EEG % >> show_events(EEG); % % % To highlight events selected by make_timewarp() function with thin % % event markers % >> show_events(EEG, 'eventThicknessCoef', 0.5, 'eventNames', timeWarp.eventSequence, % 'timeWarp', timeWarp); % % Version 1.1 % Author: Nima Bigdely Shamlo, SCCN/INC/UCSD, 2008 % See also: make_timewarp(), newtimef() function im = show_events(EEG, varargin) %% check inputs EEG = change_events_to_string(EEG); inputKeyValues = finputcheck(varargin, ... {'eventThicknessCoef' 'real' [0 Inf] 1; ... 'eventNames' 'cell' {} {} ; ... 'timeWarp' 'struct' [] struct([]); ... }); eventThicknessCoef = 0; eventNames = {}; timeWarp=[]; % place key values into function workspace variables inputKeyValuesFields = fieldnames(inputKeyValues); for i=1:length(inputKeyValuesFields) eval([inputKeyValuesFields{i} '= inputKeyValues.' inputKeyValuesFields{i} ';']); end; if length(eventNames) == 0 if length(timeWarp) == 0 eventNames = []; for i=1:length(EEG.epoch) eventNames = [eventNames EEG.epoch(i).eventtype]; end; else for i=1:length(timeWarp.eventSequence) if ischar(timeWarp.eventSequence{i}) eventNames = [eventNames timeWarp.eventSequence{i}]; else % in case it is a cell of strings for j=1:length(timeWarp.eventSequence{i}) eventNames = [eventNames timeWarp.eventSequence{i}{j}]; end; end end; % eventNames = timeWarp.eventSequence; % if event names is not provided only show timeWarp events end end; if length(timeWarp) == 0 timeWarp=[]; timeWarp.latencies = []; timeWarp.epochs = 1:length(EEG.epoch); end; %% set image parameters imWidth = 300*4; imHeight = 240*4; im = double(zeros(imHeight, imWidth, 3)); %% find latencies for events of interest in each epoch uniqueEventNames = uniqe_cell_string(eventNames); for epochNumber = 1:length(EEG.epoch) for eventNumber = 1:length(uniqueEventNames) ids = find(strcmp(EEG.epoch(epochNumber).eventtype,uniqueEventNames{eventNumber})); % index for events with this type in the current epoch latency{epochNumber, eventNumber} = cell2mat(EEG.epoch(epochNumber).eventlatency(ids)); end; end; %% find a good default value for event marker width based on quantiles % of inter-event latencies. intervals = []; for i=1:size(latency,1) intervals = [intervals diff(sort(cell2mat(latency(i,:)),'ascend'))]; %#ok<AGROW> end; if isempty(intervals) eventLineWidth = 0.05*eventThicknessCoef; else eventLineWidth = round(eventThicknessCoef * 0.5 * imWidth * -quantile(-intervals,0.8) / ((EEG.xmax - EEG.xmin)*1000)); end; %% place colored rectangle block o image to display events eventColors = lines(length(uniqueEventNames)); for epochNumber = 1:length(EEG.epoch) for eventNumber = 1:length(uniqueEventNames) for eventInstanceNumber = 1:length(latency{epochNumber, eventNumber}) startHeight = max(1,round((epochNumber - 1) * imHeight/ length(EEG.epoch))); endHeight = min(imHeight, round((epochNumber) * imHeight/ length(EEG.epoch))); startWidth = max(1,round(-eventLineWidth/2 + imWidth * (latency{epochNumber, eventNumber}(eventInstanceNumber) - (EEG.xmin*1000))/ ((EEG.xmax - EEG.xmin)*1000))); endWidth = min(imWidth,startWidth + eventLineWidth); colorForEvent = eventColorBasedOnTypeAndAcceptance(eventColors, eventNumber, epochNumber, latency{epochNumber, eventNumber}(eventInstanceNumber), timeWarp); for c = 1:3 % to make sure the highlighted events are not overwritten by other events in the image, we use 'max' and give the brightest color priority im(startHeight:endHeight,startWidth:endWidth,c) = max(im(startHeight:endHeight,startWidth:endWidth,c), colorForEvent(c)); end; end; end; end; %% plot image with legend and axis labels figure; hold on; for i=1:length(uniqueEventNames) plot([0 0],rand * [0 0],'Color',eventColors(i,:),'linewidth',10); uniqueEventNames{i} = strrep(uniqueEventNames{i},'_','-'); % replace _ with - so it is displayed correctly in the legend end; legend(uniqueEventNames, 'Location', 'NorthWest'); image(round([EEG.xmin*1000 EEG.xmax*1000 ]), [1 length(EEG.epoch)],im); xlim(round([EEG.xmin*1000 EEG.xmax*1000 ])) ylim([1 length(EEG.epoch)]) axis normal; xlabel('Latency', 'fontsize',16); xlabel('Latency', 'fontsize',16); ylabel('Epochs', 'fontsize',16); if nargout == 0 % supress output if not requested clear im ; end; function color = eventColorBasedOnTypeAndAcceptance(eventColors, eventNumber, epochNumber, eventLatency,timeWarp) accepted = ismember_bc(epochNumber, timeWarp.epochs); if ~isempty(timeWarp.latencies) matchedEpoch = find(timeWarp.epochs == epochNumber); accepted = accepted && ~isempty(find(timeWarp.latencies(matchedEpoch,:) == eventLatency, 1)); end; color = eventColors(eventNumber,:); if ~accepted color = color*0.3; % dim the color of unaccepted events. end; function EEG = change_events_to_string(EEG) needChange = false; for i=1:length(EEG.event) if ~ischar(EEG.event(i).type) EEG.event(i).type = num2str( EEG.event(i).type ); needChange = true; end; end; if needChange for e=1:length(EEG.epoch) for i=1:length(EEG.epoch(e).eventtype) EEG.epoch(e).eventtype(i) = {num2str(cell2mat(EEG.epoch(e).eventtype(i)))}; end; end; end;
github
ZijingMao/baselineeegtest-master
crossfold.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/crossfold.m
19,968
utf_8
33b019ccc97af482fda0f0b153baab64
% crossf() - Returns estimates and plot of event-related coherence (ERC) changes % between data from two input channels. The lower panel gives the % coherent phase difference between the processes. In this panel, for Ex. % -90 degrees (blue) means xdata leads ydata by a quarter cycle. % 90 degrees (orange) means ydata leads xdata by a quarter cycle. % Click on each subplot to view separately and zoom in/out. % % Function description: % Uses EITHER fixed-window, zero-padded FFTs (faster) OR constant-Q % 0-padded DFTs (better sensitivity), both Hanning-tapered. Output % frequency spacing is the lowest frequency (srate/winsize) divided % by the padratio. % % If number of output arguments > 4, then bootstrap statistics are % computed (from a distribution of 200 (NACCU) surrogate baseline % data epochs) for the baseline epoch, and non-significant features % of the output plots are zeroed (e.g., plotted in green). Baseline % epoch is all windows with center times < 0 (MAX_BASELN) % % If number of output arguments > 5, coherency angles (lags) at % significant coherency (time,frequency) points are plotted as well. % % Usage: % >> [coh,mcoh,timesout,freqsout,cohboot,cohangles] = crossf(xdata,ydata,... % frames,tlimits,titl, ... % srate,cycles,winsize,timesout,... % padratio,maxfreq,alpha,verts); % % Inputs: % xdata = first single-channel (1,frames*nepochs) data {none} % ydata = second single-channel (1,frames*nepochs) data {none} % frames = frames per epoch {768} % tlimits = epoch time limits (ms) [mintime maxtime]{-1000 2000} % titl = figure title {none} % srate = data sampling rate (Hz) {256} % cycles = >0 -> number of cycles in each analysis window (slower) % =0 -> use FFT (constant window length) {0} % winsize = cycles==0: data subwindow length (2^k<frames) % cycles >0: *longest* window length to use; % determines the lowest output frequency {~frames/8} % timesout = number of output times (int<frames-winsize){200} % padratio = FFT-length/winsize (2^k) {2} % Multiplies the number of output frequencies. % maxfreq = maximum frequency to plot (Hz) {50} % alpha = Two-tailed bootstrap signif. probability {0.02} % Sets n.s. plotted output values to green (0). % NOTE that it requires at least FIVE output arguments! % verts = times of vertical lines (other than time 0) {none} % caxma = color axis maximum (magnitude) {default: from data} % % Outputs: % coh = between-channel coherency changes (nfreqs,timesout) % mcoh = vector of mean baseline coherence at each frequency % timesout = vector of output times (subwindow centers) in ms. % freqsout = vector of frequency bin centers in Hz. % cohboot = [2,nfreqs] matrix of [lower;upper] coh significance diffs. % cohangle = coherency angles (nfreqs,timesout) % % Note: when cycles==0, nfreqs is total number of FFT frequencies. % % Authors: Sigurd Enghoff & Scott Makeig, SCCN/INC/UCSD, La Jolla, 1998 % % See also: timef() % Copyright (C) 8/1/98 Sigurd Enghoff & Scott Makeig, SCCN/INC/UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 11-20-98 defined LINEWIDTH constant -sm % 04-01-99 made number of frequencies consistent -se % 06-29-99 fixed constant-Q freq indexing -se % 08-13-99 added cohangle plotting -sm % 08-20-99 made bootstrap more efficient -sm % 08-24-99 allow nan values introduced by possible eventlock() preproc. -sm % 03-16-00 added lead/lag interpretation to help msg - sm & eric visser % 03-16-00 added axcopy() feature -sm & tpj % 04-20-00 fixed Rangle sign for wavelets, added verts array -sm % 01-22-01 corrected help msg when nargin<2 -sm & arno delorme % 01-25-02 reformated help & license, added links -ad function [R,mbase,times,freqs,Rboot,Rangle,Rsignif] = crossf(X,Y,epoch,timelim,ftitle,Fs,varwin,winsize,nwin,oversmp,maxfreq,alpha,verts,caxmax) % Constants set here: MAX_BASELN = 0; % Windows with center times < this are in baseline. NACCU = 200; % Number of sub-windows to accumulate if nargin>13 COH_CAXIS_LIMIT = caxmax; else COH_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value end % giving symmetric +/- caxis limits. AXES_FONT = 10; LINEWIDTH = 2; TITLE_FONT = 8; ANGLEUNITS = 'deg'; % angle plotting units - 'ms' or 'deg' % Commandline arg defaults: DEFAULT_EPOCH = 768; % Frames per epoch DEFAULT_TIMELIM = [-1000 2000]; % Time range of epochs (ms) DEFAULT_FS = 256; % Sampling frequency (Hz) DEFAULT_NWIN = 200; % Number of windows = horizontal resolution DEFAULT_VARWIN = 0; % Fixed window length or base on cycles. % =0: fix window length to nwin % >0: set window length equal varwin cycles % bounded above by winsize, also determines % the min. freq. to be computed. DEFAULT_OVERSMP = 2; % Number of times to oversample = vertical resolution DEFAULT_MAXFREQ = 50; % Maximum frequency to display (Hz) DEFAULT_TITLE = ''; % Figure title DEFAULT_ALPHA = 0.02; % Default two-sided significance probability threshold MARGIN = 0.12; % width of marginal plots DEFAULT_VERTS = []; % default no vertical lines if (nargin < 2) help crossf return end if (min(size(X))~=1 | length(X)<2) fprintf('crossf(): xdata must be a row or column vector.\n'); return elseif (min(size(Y))~=1 | length(Y)<2) fprintf('crossf(): ydata must be a row or column vector.\n'); return elseif (length(X) ~= length(Y)) fprintf('crossf(): xdata and ydata must have same length.\n'); return end if (nargin < 3) epoch = DEFAULT_EPOCH; elseif (~isnumeric(epoch) | length(epoch)~=1 | epoch~=round(epoch)) fprintf('crossf(): Value of frames must be an integer.\n'); return elseif (epoch <= 0) fprintf('crossf(): Value of frames must be positive.\n'); return elseif (rem(length(X),epoch) ~= 0) fprintf('crossf(): Length of data vectors must be divisible by frames.\n'); return end if (nargin < 4) timelim = DEFAULT_TIMELIM; elseif (~isnumeric(timelim) | sum(size(timelim))~=3) error('crossf(): Value of tlimits must be a vector containing two numbers.'); elseif (timelim(1) >= timelim(2)) error('crossf(): tlimits interval must be [min,max].'); end if (nargin < 5) ftitle = DEFAULT_TITLE; elseif (~ischar(ftitle)) error('crossf(): Plot title argument must be a quoted string.'); end if (nargin < 6) Fs = DEFAULT_FS; elseif (~isnumeric(Fs) | length(Fs)~=1) error('crossf(): Value of srate must be a number.'); elseif (Fs <= 0) error('crossf(): Value of srate must be positive.'); end if (nargin < 7) varwin = DEFAULT_VARWIN; elseif (~isnumeric(varwin) | length(varwin)~=1) error('crossf(): Value of cycles must be a number.'); elseif (varwin < MAX_BASELN) error('crossf(): Value of cycles must be either zero or positive.'); end if (nargin < 8) winsize = max(pow2(nextpow2(epoch)-3),4); elseif (~isnumeric(winsize) | length(winsize)~=1 | winsize~=round(winsize)) error('crossf(): Value of winsize must be an integer number.'); elseif (winsize <= 0) error('crossf(): Value of winsize must be positive.'); elseif (varwin == 0 & pow2(nextpow2(winsize)) ~= winsize) error('crossf(): Value of winsize must be an integer power of two [1,2,4,8,16,...]'); elseif (winsize > epoch) error('crossf(): Value of winsize must be less than epoch length.'); end if (nargin < 9) nwin = DEFAULT_NWIN; elseif (~isnumeric(nwin) | length(nwin)~=1 | nwin~=round(nwin)) error('crossf(): Value of nwin must be an integer number.'); elseif (nwin <= 0) error('crossf(): Value of nwin must be positive.'); end if (nwin > epoch-winsize) error('crossf(): Value of nwin must be <= epoch-winsize.'); end if (nargin < 10) oversmp = DEFAULT_OVERSMP; elseif (~isnumeric(oversmp) | length(oversmp)~=1 | oversmp~=round(oversmp)) error('crossf(): Value of oversmp must be an integer number.'); elseif (oversmp <= 0) error('crossf(): Value of oversmp must be positive.'); elseif (pow2(nextpow2(oversmp)) ~= oversmp) error('crossf(): Value of oversmp must be an integer power of two [1,2,4,8,16,...]'); end if (nargin < 11) maxfreq = DEFAULT_MAXFREQ; elseif (~isnumeric(maxfreq) | length(maxfreq)~=1) error('crossf(): Value of maxfreq must be a number.'); elseif (maxfreq <= 0) error('crossf(): Value of maxfreq must be positive.'); end if (nargin < 12) alpha = DEFAULT_ALPHA; elseif (~isnumeric(alpha) | length(alpha)~=1) error('crossf(): Value of alpha must be a number.'); elseif (round(NACCU*alpha) < 2 | alpha > .5) fprintf('crossf(): Value of alpha must be in the range (~0,0.5]'); return else if round(NACCU*alpha)<1, alpha = 1/NACCU; fprintf(... 'Using alpha = %0.3f. To decrease, must raise NACCU in source code.\n',... alpha); end end if (nargin < 13) verts = DEFAULT_VERTS; end if (varwin == 0) % FFT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% freqs = Fs/winsize*[1:2/oversmp:winsize]/2; win = hanning(winsize); R = zeros(oversmp*winsize/2,nwin); RR = zeros(oversmp*winsize/2,nwin); Rboot = zeros(oversmp*winsize/2,NACCU); else % wavelet DFT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% freqs = Fs*varwin/winsize*[2:2/oversmp:winsize]/2; win = dftfilt(winsize,maxfreq/Fs,varwin,oversmp,1); R = zeros(size(win,2),nwin); RR = zeros(size(win,2),nwin); Rboot = zeros(size(win,2),NACCU); end wintime = 500*winsize/Fs; times = timelim(1)+wintime:(timelim(2)-timelim(1)-2*wintime)/(nwin-1):timelim(2)-wintime; baseln = find(times < 0); dispf = find(freqs <= maxfreq); stp = (epoch-winsize)/(nwin-1); trials = length(X)/epoch; fprintf('\nComputing the Event-Related Cross-Coherence image\n'); fprintf(' based on %d trials of %d frames sampled at %g Hz.\n',... trials,epoch,Fs); fprintf('Trial timebase is %d ms before to %d ms after the stimulus\n',... timelim(1),timelim(2)); fprintf('The frequency range displayed is %g-%g Hz.\n',min(dispf),maxfreq); if varwin==0 fprintf('The data window size is %d samples (%g ms).\n',winsize,2*wintime); fprintf('The FFT length is %d samples\n',winsize*oversmp); else fprintf('The window size is %d cycles.\n',varwin); fprintf('The maximum window size is %d samples (%g ms).\n',winsize,2*wintime); end fprintf('The window is applied %d times\n',nwin); fprintf(' with an average step size of %g samples (%g ms).\n',... stp,1000*stp/Fs); fprintf('Results are oversampled %d times.\n',oversmp); if nargout>4 fprintf('Bootstrap confidence limits will be computed based on alpha = %g\n',... alpha); else fprintf('Bootstrap confidence limits will NOT be computed.\n'); end if nargout>5 fprintf(['Coherence angles will be imaged in ',ANGLEUNITS,' and saved.\n']); end fprintf('\nProcessing trial (of %d):',trials); firstboot = 1; Rn=zeros(1,nwin); X = X(:)'; % make X and Y column vectors Y = Y(:)'; for t=1:trials, if (rem(t,10) == 0) fprintf(' %d',t); end if rem(t,120) == 0 fprintf('\n'); end for j=1:nwin, % for each time window tmpX = X([1:winsize]+floor((j-1)*stp)+(t-1)*epoch); tmpY = Y([1:winsize]+floor((j-1)*stp)+(t-1)*epoch); if ~any(isnan(tmpX)) tmpX = tmpX - mean(tmpX); tmpY = tmpY - mean(tmpY); if varwin == 0 % use FFTs tmpX = win .* tmpX(:); tmpY = win .* tmpY(:); tmpX = fft(tmpX,oversmp*winsize); tmpY = fft(tmpY,oversmp*winsize); tmpX = tmpX(2:oversmp*winsize/2+1); tmpY = tmpY(2:oversmp*winsize/2+1); else tmpX = win' * tmpX(:); tmpY = win' * tmpY(:); end if nargout > 4 if firstboot==1 tmpsX = repmat(nan,length(tmpX),nwin); tmpsY = repmat(nan,length(tmpY),nwin); firstboot = 0; end tmpsX(:,j) = tmpX; tmpsY(:,j) = tmpY; end RR(:,j) = tmpX.*conj(tmpY) ./ (abs(tmpX).*abs(tmpY)); % complex coher. R(:,j) = R(:,j) + RR(:,j); Rn(j) = Rn(j)+1; end % ~any(isnan()) end % time window if (nargout > 4) % get NACCU bootstrap estimates for each trial j=1; while j<=NACCU s = ceil(rand([1 2])*nwin); % random ints [1,nwin] tmpX = tmpsX(:,s(1)); tmpY = tmpsY(:,s(2)); if ~any(isnan(tmpX)) & ~any(isnan(tmpY)) RR = tmpX.*conj(tmpY) ./ (abs(tmpX).*abs(tmpY)); % complex coher. Rboot(:,j) = Rboot(:,j) + RR; j = j+1; end end end end % t = trial fprintf('\nNow plotting...\n'); Rangle = angle(R); if varwin ~= 0 Rangle = -Rangle; % make lead/lag the same for FFT and wavelet analysis end R = abs(R) ./ (ones(size(R,1),1)*Rn); % coherence magnitude Rraw = R; % raw coherence values mbase = mean(R(:,baseln)'); % mean baseline coherence magnitude % R = R - repmat(mbase',[1 nwin]);% remove baseline mean if (nargout > 4) % bootstrap i = round(NACCU*alpha); Rboot = abs(Rboot) / trials; % normalize bootstrap magnitude to [0,1] Rboot = sort(Rboot'); Rsignif = mean(Rboot(NACCU-i+1:NACCU,:)); % significance levels for Rraw % Rboot = [mean(Rboot(1:i,:))-mbase ; mean(Rboot(NACCU-i+1:NACCU,:))-mbase]; Rboot = [mean(Rboot(1:i,:)) ; mean(Rboot(NACCU-i+1:NACCU,:))]; end % NOTE: above, mean ????? set(gcf,'DefaultAxesFontSize',AXES_FONT) colormap(jet(256)); pos = get(gca,'position'); % plot relative to current axes q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; axis('off') if nargout>5 % image coherence lag as well as coherence magnitude ybase = 0.5; subheight = 0.4; MARGIN = MARGIN*0.75; else ybase = 0.0; subheight = 0.9; end % % Image the coherence [% perturbations] % RR = R; if (nargout > 4) % zero out (and 'green out') nonsignif. R values RR(find((RR > repmat(Rboot(1,:)',[1 nwin])) ... & (RR < repmat(Rboot(2,:)',[1 nwin])))) = 0; end if (nargout > 5) % zero out nonsignif. Rraw values Rraw(find(repmat(Rsignif',[1,size(Rraw,2)])>=Rraw))=0; end if COH_CAXIS_LIMIT == 0 coh_caxis = max(max(R(dispf,:)))*[-1 1]; else coh_caxis = COH_CAXIS_LIMIT*[-1 1]; end h(6) = axes('Units','Normalized',... 'Position',[MARGIN ybase+MARGIN 0.9-MARGIN subheight].*s+q); map=hsv(300); % install circular color map - green=0, yellow, orng, red, violet = max % cyan, blue, violet = min map = flipud([map(251:end,:);map(1:250,:)]); map(151,:) = map(151,:)*0.9; % tone down the (0=) green! colormap(map); imagesc(times,freqs(dispf),RR(dispf,:),coh_caxis); % plot the coherence image set(h(6),'Units','Normalized',... 'Position',[MARGIN ybase+MARGIN 0.9-MARGIN subheight].*s+q); hold on plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',LINEWIDTH) for i=1:length(verts) plot([verts(i) verts(i)],[0 freqs(max(dispf))],'--m','LineWidth',LINEWIDTH); end; hold off set(h(6),'YTickLabel',[],'YTick',[]) set(h(6),'XTickLabel',[],'XTick',[]) title('Event-Related Coherence') h(8) = axes('Position',[.92 ybase+MARGIN .05 subheight].*s+q); cbar(h(8),151:300,[0 coh_caxis(2)]); % use only positive colors (gyorv) % for coherences % % Plot delta-mean min and max coherence at each time point on bottom of image % h(10) = axes('Units','Normalized','Position',[MARGIN ybase 0.9-MARGIN MARGIN].*s+q); Emax = max(R(dispf,:)); % mean coherence at each time point Emin = min(R(dispf,:)); % mean coherence at each time point plot(times,Emax,'b'); hold on plot(times,Emin,'b'); plot([times(1) times(length(times))],[0 0],'LineWidth',0.7); plot([0 0],[-500 500],'--m','LineWidth',LINEWIDTH); for i=1:length(verts) plot([verts(i) verts(i)],[-500 500],'--m','LineWidth',LINEWIDTH); end; axis([min(times) max(times) 0 max(Emax)*1.2]) tick = get(h(10),'YTick'); set(h(10),'YTick',[tick(1) ; tick(length(tick))]) set(h(10),'YAxisLocation','right') midpos = get(h(10),'Position'); if nargout<6 xlabel('Time (ms)') end ylabel('coh.') % % Plot mean baseline coherence at each freq on left side of image % h(11) = axes('Units','Normalized','Position',[0 ybase+MARGIN MARGIN subheight].*s+q); E = mbase(dispf); % baseline mean coherence at each frequency if (nargout > 4) % plot bootstrap significance limits (base mean +/-) plot(freqs(dispf),E,'m','LineWidth',LINEWIDTH); % plot mbase hold on % plot(freqs(dispf),Rboot(:,dispf)+[E;E],'g','LineWidth',LINEWIDTH); plot(freqs(dispf),Rboot([1 2],dispf),'g','LineWidth',LINEWIDTH); plot(freqs(dispf),Rsignif(dispf),'k:','LineWidth',LINEWIDTH); axis([freqs(1) freqs(max(dispf)) 0 max([E Rsignif])*1.2]); else % plot marginal mean coherence only plot(freqs(dispf),E,'LineWidth',LINEWIDTH); % axis([freqs(1) freqs(max(dispf)) min(E)-max(E)/3 max(E)+max(E)/3]); if ~isnan(max(E)) axis([freqs(1) freqs(max(dispf)) 0 max(E)*1.2]); end; end tick = get(h(11),'YTick'); set(h(11),'YTick',[tick(1) ; tick(length(tick))]) set(h(11),'View',[90 90]) xlabel('Freq. (Hz)') ylabel('coh.') if (length(ftitle) > 0) % plot title axes('Position',pos,'Visible','Off'); h(12) = text(-.05,1.01,ftitle); set(h(12),'VerticalAlignment','bottom') set(h(12),'HorizontalAlignment','left') set(h(12),'FontSize',TITLE_FONT) end % % Plot coherence time lags in bottom panel % if nargout>5 h(13) = axes('Units','Normalized','Position',[MARGIN MARGIN 0.9-MARGIN subheight].*s+q); if strcmp(ANGLEUNITS,'ms') % convert to ms Rangle = (Rangle/(2*pi)).*repmat(1000./freqs(dispf)',1,length(times)); maxangle = max(max(abs(Rangle))); else Rangle = Rangle*180/pi; % convert to degrees maxangle = 180; % use full-cycle plotting end Rangle(find(Rraw==0)) = 0; % set angle at non-signif coher points to 0 imagesc(times,freqs(dispf),Rangle(dispf,:),[-maxangle maxangle]); % plot the hold on % coherence phase angles plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',LINEWIDTH); % zero-time line for i=1:length(verts) plot([verts(i) verts(i)],[0 freqs(max(dispf))],'--m','LineWidth',LINEWIDTH); end; pos13 = get(h(13),'Position'); set(h(13),'Position',[pos13(1) pos13(2) midpos(3) pos13(4)]); ylabel('Freq. (Hz)') xlabel('Time (ms)') h(14)=axes('Position',[.92 MARGIN .05 subheight].*s+q); cbar(h(14),0,[-maxangle maxangle]); % two-sided colorbar if (length(ftitle) > 0) % plot title axes('Position',pos,'Visible','Off'); h(13) = text(-.05,1.01,ftitle); set(h(13),'VerticalAlignment','bottom') set(h(13),'HorizontalAlignment','left') set(h(13),'FontSize',TITLE_FONT) end end axcopy(gcf);
github
ZijingMao/baselineeegtest-master
fastregress.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/fastregress.m
1,517
utf_8
e2c1ad4eeb288b3c052addc163562af2
% fastregress - perform fast regression and return p-value % % Usage: % [ypred, alpha, rsq, B] = myregress(x, y, plotflag); % % Inputs % y - y values % x - x values % plotflag - [0|1] plot regression % % Outputs % ypred - y prediction % alpha - significance level % R^2 - r square % slope - slope of the fit % % Arnaud Delorme, 25 Feb 2003 function [ypred, alpha, rsq, B] = fastregress(x, y, ploting); if nargin < 1 help fastregress; return; end; % this part is useless but still works %B=polyfit(x, y, 1); % B is the slope %ypred = polyval(B,x); % predictions %dev = y - mean(y); % deviations - measure of spread %SST = sum(dev.^2); % total variation to be accounted for %resid = y - ypred; % residuals - measure of mismatch %SSE = sum(resid.^2); % variation NOT accounted for %rsq = 1 - SSE/SST; % percent of error explained % see the page http://www.facstaff.bucknell.edu/maneval/help211/fitting.html [B,BINT,R,RINT,STATS] = regress(y(:), [ones(length(x),1) x(:)]); alpha = STATS(3); rsq = STATS(1); %note that we also have %ypred = [ones(size(x,2),1) x(:)]*B; ypred = x*B(2) + B(1); % B(1) contain the offset, B(2) the slope B = B(2); if nargin > 2 hold on; [ynew tmp] = sort(ypred); xnew = x(tmp); plot(xnew, ynew, 'r'); legend(sprintf('R^2=%f', rsq), sprintf('p =%f', alpha)); end;
github
ZijingMao/baselineeegtest-master
rmsave.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/rmsave.m
723
utf_8
a701a295277a4b69da6facca32c0fc41
% rmsave() - return the RMS in each channel, epoch % % Usage: % >> ave = rmsave(data,frames); % Scott Makeig, CNL/Salk Institute, La Jolla, 9/98 function ave = rmsave(data,frames) if nargin<1 help rmsave return end if nargin<2 frames = size(data,2); data = reshape(data, size(data,1), size(data,2)*size(data,3)); end; chans = size(data,1); datalength = size(data,2); if rem(datalength,frames) fprintf('frames should divide data length.\n'); return end if frames < 1 fprintf('frames should be > 1.\n'); return end epochs = datalength/frames; ave = zeros(chans,epochs); i=1; while i<= epochs dat = matsel(data,frames,0,0,i); dat = dat.*dat; ave(:,i) = sqrt(mean(dat'))'; i = i+1; end
github
ZijingMao/baselineeegtest-master
read_rdf.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/read_rdf.m
1,904
utf_8
e9f06b48010db91ad052b73482eb6e32
% read_rdf() - read RDF-formatted EEG files. % % Usage: % >> [eeg,ev,header] = read_rdf(filename); % % Inputs: % filename - EEG data file in RDF format % % Outputs: % eeg - eeg data (array in size of [chan_no timepoint]; % ev - event structure % ev.sample_offset[] - event offsets in samples % from the first sample (0) % ev.event_code[] - event codes (integers) % header - data structure for header information % header.ch_no - number of channels % header.sample_no - number of samples % Notes: % % Authors: Jeng-Ren Duann, CNL/Salk & INC/UCSD, 2002-12-12 % with help from Andrey Vankov, creator of the RDF file format. function [eeg,ev,header] = read_rdf(filename) if nargin < 1 help read_rdf; return; end; eeg = []; ev = []; header = []; fp = fopen(filename,'rb','ieee-le'); if fp == -1, disp('read_RDF(): Cannot open data file...!'); return; end fseek(fp,6,-1); header.ch_no = fread(fp,1,'uint16'); cnt = 0; ev_cnt = 0; while(~feof(fp)), tag = fread(fp,1,'uint32'); if length(tag) == 0, break; end if tag == hex2dec('f0aa55'), cnt = cnt + 1; disp(['block ' num2str(cnt) ' found']); % read ch_no and block length fseek(fp,2,0); ch_no = fread(fp,1,'uint16'); block_size = power(2,fread(fp,1,'uint16')); % read events fseek(fp,62,0); for i=1:110, samp_off = fread(fp,1,'char'); cond_code = fread(fp,1,'char'); ev_code = fread(fp,1,'uint16'); if samp_off ~= 0, ev_cnt = ev_cnt + 1; ev(ev_cnt).sample_offset = samp_off + (cnt-1)*128; ev(ev_cnt).event_code = ev_code; end end data = fread(fp,ch_no*block_size,'int16'); data = reshape(data,ch_no,block_size); eeg = [eeg data]; end end fclose(fp); header.sample_no = size(eeg,2);
github
ZijingMao/baselineeegtest-master
hist2.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/hist2.m
2,077
utf_8
e482d20c2cf737a382391c4f4063eed7
% hist2() - draw superimposed histograms % % Usage: % >> hist2(data1, data2, bins); % % Inputs: % data1 - data to plot first process % data2 - data to plot second process % % Optional inputs: % bins - vector of bin center % % Author: Arnaud Delorme (SCCN, UCSD) % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % draw superimposed histograms % --------------- function hist2(data1, data2, bins); if nargin < 1 help hist2; return; end; if nargin < 3 bins = linspace(min(min(data1), min(data2)), max(max(data1), max(data2)), 100); elseif length(bins) == 1 bins = linspace(min(min(data1), min(data2)), max(max(data1), max(data2)), bins); end; hist(data1, bins); hold on; hist(data2, bins); %figure; hist( [ measure{:,5} ], 20); %hold on; hist([ measure{:,2} ], 20); c = get(gca, 'children'); numfaces = size(get(c(1), 'Vertices'),1); set(c(1), 'FaceVertexCData', repmat([1 0 0], [numfaces 1]), 'Cdatamapping', 'direct', 'facealpha', 0.5, 'edgecolor', 'none'); numfaces = size(get(c(2), 'Vertices'),1); set(c(2), 'FaceVertexCData', repmat([0 0 1], [numfaces 1]), 'Cdatamapping', 'direct', 'facealpha', 0.5, 'edgecolor', 'none'); ylabel('Number of values'); xlim([bins(1) bins(end)]); yl = ylim; xl = xlim; line([xl(1) xl(1)]+(xl(2)-xl(1))/2000, yl, 'color', 'k'); line(xl, [yl(1) yl(1)]+(yl(2)-yl(1))/2000, 'color', 'k');
github
ZijingMao/baselineeegtest-master
erpregoutfunc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/erpregoutfunc.m
1,315
utf_8
028d72b1a69b5f79ce7f9c6a5f00b554
% erpregoutfunc() - sub function of erpregout() used to regress % out the ERP from the data % % Usage: % totdiff = erpregout(fact, data, erp); % % Inputs: % fact - factor % data - [float] 1-D data (time points). % erp - [float] 1-D data (time points). % % Outputs: % totdif - residual difference % % Author: Arnaud Delorme, Salk, SCCN, UCSD, CA, April 29, 2004 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 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 totdiff = erpregoutfunc(fact, data, erp); totdiff = mean(abs(data - fact*erp));
github
ZijingMao/baselineeegtest-master
dprime.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/dprime.m
22,037
utf_8
4af65f989db5375361e682677d16b31f
% DPRIME - Signal-detection theory sensitivity measure. % % d = dprime(pHit,pFA) % [d,beta] = dprime(pHit,pFA) % % PHIT and PFA are numerical arrays of the same shape. % PHIT is the proportion of "Hits": P(Yes|Signal) % PFA is the proportion of "False Alarms": P(Yes|Noise) % All numbers involved must be between 0 and 1. % The function calculates the d-prime measure for each <H,FA> pair. % The criterion value BETA can also be requested. % Requires MATLAB's Statistical Toolbox. % % References: % * Green, D. M. & Swets, J. A. (1974). Signal Detection Theory and % Psychophysics (2nd Ed.). Huntington, NY: Robert Krieger Publ.Co. % * Macmillan, Neil A. & Creelman, C. Douglas (2005). Detection Theory: % A User's Guide (2nd Ed.). Lawrence Erlbaum Associates. % % See also NORMINV, NORMPDF. % Original coding by Alexander Petrov, Ohio State University. % $Revision: 1.2 $ $Date: 2009-02-09 10:49:29 $ % % Part of the utils toolbox version 1.1 for MATLAB version 5 and up. % http://alexpetrov.com/softw/utils/ % Copyright (c) Alexander Petrov 1999-2006, http://alexpetrov.com % Please read the LICENSE and NO WARRANTY statement: % GNU Public License for the UTILS Toolbox % % ============================================================================== % % IN BRIEF % ======== % % This document refers to all Matlab scripts and documentation (referred % to collectively here as "the software") contained in the "utils toolbox" % by Alexander Petrov 1999-2006, http://alexpetrov.com/softw/utils/ % % The software is freely available and freely redistributable, according % to the conditions of the Gnu General Public License (below). You may not % distribute the software, in whole or in part, in conjunction with % proprietary code. That means you ONLY have my permission to distribute a % program that uses my code IF you also make freely available (under the % terms of the Gnu GPL) the source code for your whole project. You may % not pass on the software to another party in its current form or any % altered, embellished or reduced form, without acknowledging the author % and including a copy of this license. % % The software 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 (reproduced below), and the Free Software Foundation % website (http://www.fsf.org) for more details. % % Please notify the author, via the website, of any bugs, notes, comments % or suggested changes, particularly of any useful changes you may have % made to your own copy of the software. % % Alex Petrov, December 2006 % % ============================================================================== % % GNU GENERAL PUBLIC LICENSE % ========================== % % Version 2, June 1991 % Copyright (C) 1989, 1991 Free Software Foundation, Inc. % 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % Everyone is permitted to copy and distribute verbatim copies % of this license document, but changing it is not allowed. % % % Preamble % ======== % % The licenses for most software are designed to take away your % freedom to share and change it. By contrast, the GNU General Public % License is intended to guarantee your freedom to share and change free % software--to make sure the software is free for all its users. This % General Public License applies to most of the Free Software % Foundation's software and to any other program whose authors commit to % using it. (Some other Free Software Foundation software is covered by % the GNU Library General Public License instead.) You can apply it to % your programs, too. % % When we speak of free software, we are referring to freedom, not % price. Our General Public Licenses are designed to make sure that you % have the freedom to distribute copies of free software (and charge for % this service if you wish), that you receive source code or can get it % if you want it, that you can change the software or use pieces of it % in new free programs; and that you know you can do these things. % % To protect your rights, we need to make restrictions that forbid % anyone to deny you these rights or to ask you to surrender the rights. % These restrictions translate to certain responsibilities for you if you % distribute copies of the software, or if you modify it. % % For example, if you distribute copies of such a program, whether % gratis or for a fee, you must give the recipients all the rights that % you have. You must make sure that they, too, receive or can get the % source code. And you must show them these terms so they know their % rights. % % We protect your rights with two steps: (1) copyright the software, and % (2) offer you this license which gives you legal permission to copy, % distribute and/or modify the software. % % Also, for each author's protection and ours, we want to make certain % that everyone understands that there is no warranty for this free % software. If the software is modified by someone else and passed on, we % want its recipients to know that what they have is not the original, so % that any problems introduced by others will not reflect on the original % authors' reputations. % % Finally, any free program is threatened constantly by software % patents. We wish to avoid the danger that redistributors of a free % program will individually obtain patent licenses, in effect making the % program proprietary. To prevent this, we have made it clear that any % patent must be licensed for everyone's free use or not licensed at all. % % The precise terms and conditions for copying, distribution and % modification follow. % % % GNU GENERAL PUBLIC LICENSE % ========================== % TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION % =============================================================== % % 0. This License applies to any program or other work which contains % a notice placed by the copyright holder saying it may be distributed % under the terms of this General Public License. The "Program", below, % refers to any such program or work, and a "work based on the Program" % means either the Program or any derivative work under copyright law: % that is to say, a work containing the Program or a portion of it, % either verbatim or with modifications and/or translated into another % language. (Hereinafter, translation is included without limitation in % the term "modification".) Each licensee is addressed as "you". % % Activities other than copying, distribution and modification are not % covered by this License; they are outside its scope. The act of % running the Program is not restricted, and the output from the Program % is covered only if its contents constitute a work based on the % Program (independent of having been made by running the Program). % Whether that is true depends on what the Program does. % % 1. You may copy and distribute verbatim copies of the Program's % source code as you receive it, in any medium, provided that you % conspicuously and appropriately publish on each copy an appropriate % copyright notice and disclaimer of warranty; keep intact all the % notices that refer to this License and to the absence of any warranty; % and give any other recipients of the Program a copy of this License % along with the Program. % % You may charge a fee for the physical act of transferring a copy, and % you may at your option offer warranty protection in exchange for a fee. % % 2. You may modify your copy or copies of the Program or any portion % of it, thus forming a work based on the Program, and copy and % distribute such modifications or work under the terms of Section 1 % above, provided that you also meet all of these conditions: % % a) You must cause the modified files to carry prominent notices % stating that you changed the files and the date of any change. % % b) You must cause any work that you distribute or publish, that in % whole or in part contains or is derived from the Program or any % part thereof, to be licensed as a whole at no charge to all third % parties under the terms of this License. % % c) If the modified program normally reads commands interactively % when run, you must cause it, when started running for such % interactive use in the most ordinary way, to print or display an % announcement including an appropriate copyright notice and a % notice that there is no warranty (or else, saying that you provide % a warranty) and that users may redistribute the program under % these conditions, and telling the user how to view a copy of this % License. (Exception: if the Program itself is interactive but % does not normally print such an announcement, your work based on % the Program is not required to print an announcement.) % % These requirements apply to the modified work as a whole. If % identifiable sections of that work are not derived from the Program, % and can be reasonably considered independent and separate works in % themselves, then this License, and its terms, do not apply to those % sections when you distribute them as separate works. But when you % distribute the same sections as part of a whole which is a work based % on the Program, the distribution of the whole must be on the terms of % this License, whose permissions for other licensees extend to the % entire whole, and thus to each and every part regardless of who wrote it. % % Thus, it is not the intent of this section to claim rights or contest % your rights to work written entirely by you; rather, the intent is to % exercise the right to control the distribution of derivative or % collective works based on the Program. % % In addition, mere aggregation of another work not based on the Program % with the Program (or with a work based on the Program) on a volume of % a storage or distribution medium does not bring the other work under % the scope of this License. % % 3. You may copy and distribute the Program (or a work based on it, % under Section 2) in object code or executable form under the terms of % Sections 1 and 2 above provided that you also do one of the following: % % a) Accompany it with the complete corresponding machine-readable % source code, which must be distributed under the terms of Sections % 1 and 2 above on a medium customarily used for software interchange; or, % % b) Accompany it with a written offer, valid for at least three % years, to give any third party, for a charge no more than your % cost of physically performing source distribution, a complete % machine-readable copy of the corresponding source code, to be % distributed under the terms of Sections 1 and 2 above on a medium % customarily used for software interchange; or, % % c) Accompany it with the information you received as to the offer % to distribute corresponding source code. (This alternative is % allowed only for noncommercial distribution and only if you % received the program in object code or executable form with such % an offer, in accord with Subsection b above.) % % The source code for a work means the preferred form of the work for % making modifications to it. For an executable work, complete source % code means all the source code for all modules it contains, plus any % associated interface definition files, plus the scripts used to % control compilation and installation of the executable. However, as a % special exception, the source code distributed need not include % anything that is normally distributed (in either source or binary % form) with the major components (compiler, kernel, and so on) of the % operating system on which the executable runs, unless that component % itself accompanies the executable. % % If distribution of executable or object code is made by offering % access to copy from a designated place, then offering equivalent % access to copy the source code from the same place counts as % distribution of the source code, even though third parties are not % compelled to copy the source along with the object code. % % 4. You may not copy, modify, sublicense, or distribute the Program % except as expressly provided under this License. Any attempt % otherwise to copy, modify, sublicense or distribute the Program is % void, and will automatically terminate your rights under this License. % However, parties who have received copies, or rights, from you under % this License will not have their licenses terminated so long as such % parties remain in full compliance. % % 5. You are not required to accept this License, since you have not % signed it. However, nothing else grants you permission to modify or % distribute the Program or its derivative works. These actions are % prohibited by law if you do not accept this License. Therefore, by % modifying or distributing the Program (or any work based on the % Program), you indicate your acceptance of this License to do so, and % all its terms and conditions for copying, distributing or modifying % the Program or works based on it. % % 6. Each time you redistribute the Program (or any work based on the % Program), the recipient automatically receives a license from the % original licensor to copy, distribute or modify the Program subject to % these terms and conditions. You may not impose any further % restrictions on the recipients' exercise of the rights granted herein. % You are not responsible for enforcing compliance by third parties to % this License. % % 7. If, as a consequence of a court judgment or allegation of patent % infringement or for any other reason (not limited to patent issues), % conditions are imposed on you (whether by court order, agreement or % otherwise) that contradict the conditions of this License, they do not % excuse you from the conditions of this License. If you cannot % distribute so as to satisfy simultaneously your obligations under this % License and any other pertinent obligations, then as a consequence you % may not distribute the Program at all. For example, if a patent % license would not permit royalty-free redistribution of the Program by % all those who receive copies directly or indirectly through you, then % the only way you could satisfy both it and this License would be to % refrain entirely from distribution of the Program. % % If any portion of this section is held invalid or unenforceable under % any particular circumstance, the balance of the section is intended to % apply and the section as a whole is intended to apply in other % circumstances. % % It is not the purpose of this section to induce you to infringe any % patents or other property right claims or to contest validity of any % such claims; this section has the sole purpose of protecting the % integrity of the free software distribution system, which is % implemented by public license practices. Many people have made % generous contributions to the wide range of software distributed % through that system in reliance on consistent application of that % system; it is up to the author/donor to decide if he or she is willing % to distribute software through any other system and a licensee cannot % impose that choice. % % This section is intended to make thoroughly clear what is believed to % be a consequence of the rest of this License. % % 8. If the distribution and/or use of the Program is restricted in % certain countries either by patents or by copyrighted interfaces, the % original copyright holder who places the Program under this License % may add an explicit geographical distribution limitation excluding % those countries, so that distribution is permitted only in or among % countries not thus excluded. In such case, this License incorporates % the limitation as if written in the body of this License. % % 9. The Free Software Foundation may publish revised and/or new versions % of the General Public License from time to time. Such new versions will % be similar in spirit to the present version, but may differ in detail to % address new problems or concerns. % % Each version is given a distinguishing version number. If the Program % specifies a version number of this License which applies to it and "any % later version", you have the option of following the terms and conditions % either of that version or of any later version published by the Free % Software Foundation. If the Program does not specify a version number of % this License, you may choose any version ever published by the Free Software % Foundation. % % 10. If you wish to incorporate parts of the Program into other free % programs whose distribution conditions are different, write to the author % to ask for permission. For software which is copyrighted by the Free % Software Foundation, write to the Free Software Foundation; we sometimes % make exceptions for this. Our decision will be guided by the two goals % of preserving the free status of all derivatives of our free software and % of promoting the sharing and reuse of software generally. % % NO WARRANTY: % % 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY % FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN % OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES % PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED % OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS % TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE % PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, % REPAIR OR CORRECTION. % % 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING % WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR % REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, % INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING % OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED % TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY % YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER % PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE % POSSIBILITY OF SUCH DAMAGES. % % END OF TERMS AND CONDITIONS % % % How to Apply These Terms to Your New Programs % ============================================= % % If you develop a new program, and you want it to be of the greatest % possible use to the public, the best way to achieve this is to make it % free software which everyone can redistribute and change under these terms. % % To do so, attach the following notices to the program. It is safest % to attach them to the start of each source file to most effectively % convey the exclusion of warranty; and each file should have at least % the "copyright" line and a pointer to where the full notice is found. % % <one line to give the program's name and a brief idea of what it does.> % Copyright (C) <year> <name of author> % % 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 % % % Also add information on how to contact you by electronic and paper mail. % % If the program is interactive, make it output a short notice like this % when it starts in an interactive mode: % % Gnomovision version 69, Copyright (C) year name of author % Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. % This is free software, and you are welcome to redistribute it % under certain conditions; type `show c' for details. % % The hypothetical commands `show w' and `show c' should show the appropriate % parts of the General Public License. Of course, the commands you use may % be called something other than `show w' and `show c'; they could even be % mouse-clicks or menu items--whatever suits your program. % % You should also get your employer (if you work as a programmer) or your % school, if any, to sign a "copyright disclaimer" for the program, if % necessary. Here is a sample; alter the names: % % Yoyodyne, Inc., hereby disclaims all copyright interest in the program % `Gnomovision' (which makes passes at compilers) written by James Hacker. % % <signature of Ty Coon>, 1 April 1989 % Ty Coon, President of Vice % % This General Public License does not permit incorporating your program into % proprietary programs. If your program is a subroutine library, you may % consider it more useful to permit linking proprietary applications with the % library. If this is what you want to do, use the GNU Library General % Public License instead of this License. % % ============================================================================== function [d,beta] = dprime(pHit,pFA) %-- Convert to Z scores, no error checking zHit = norminv(pHit) ; zFA = norminv(pFA) ; %-- Calculate d-prime d = zHit - zFA ; %-- If requested, calculate BETA if (nargout > 1) yHit = normpdf(zHit) ; yFA = normpdf(zFA) ; beta = yHit ./ yFA ; end %% Return DPRIME and possibly BETA %%%%%% End of file DPRIME.M
github
ZijingMao/baselineeegtest-master
setfont.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/setfont.m
3,688
utf_8
8ce4efce63ece1dbc7e024a86dd41a60
% setfont() - Change all the fonts properties of a figure. % % Usage: % >> newdata = setfont( handle, 'key', 'val'); % >> [newdata chlab] = setfont( handle, 'key' , 'val', ... ); % >> [newdata chlab] = setfont( handle, 'handletype', handletypevalue, 'key' , 'val', ... ); % % Inputs: % handle - [gcf,gca] figure or plot handle % 'handletype' - ['xlabels'|'ylabels'|'titles'|'axis'|'strings'] only apply % formating to selected category. Note that this has to be the % first optional input. % properties - 'key', 'val' properties for the figure % % Exemple: % setfont(gcf, 'fontweight', 'normal', 'fontsize', 14); % % Author: Arnaud Delorme, CNL / Salk Institute - SCCN, 25 Oct 2002 % Copyright (C) 2003 Arnaud Delorme, CNL / Salk Institute - SCCN, La Jolla % % 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 setfont(fig, varargin); if nargin < 1 help setfont; return; end; if strcmpi(varargin{1}, 'handletype') label = varargin{2}; varargin = varargin(3:end); else label = ''; end; [hx, hy, hti, hgca, hstr] = findallobjects(fig); % select a specified category % --------------------------- if isempty(label) h = [hx, hy, hti, hgca, hstr]; else switch lower(label), case 'xlabels', h =hx; case 'ylabels', h =hy; case 'titles', h =hti; case 'axis', h =hgca; case 'strings', h =hstr; otherwise, error('Unrecognized ''labels'''); end; end; % apply formating % --------------- for index = 1:length(h) isaxis = 0; try, get(h(index), 'xtick'); isaxis = 1; catch, end; if isaxis set(h(index), 'XTickLabelMode', 'manual', 'XTickMode', 'manual'); set(h(index), 'YTickLabelMode', 'manual', 'YTickMode', 'manual'); end; for tmpprop = 1:2:length(varargin) if strcmpi(varargin{tmpprop}, 'color') & isaxis set(h(index), 'xcolor', varargin{tmpprop+1}, ... 'ycolor', varargin{tmpprop+1}, ... 'zcolor', varargin{tmpprop+1}); else try, set(h(index), varargin{tmpprop}, varargin{tmpprop+1}); catch, end; end; end; end; function [hx, hy, hti, hgca, hstr] = findallobjects(fig); handles = findobj(fig)'; hx = []; hy = []; hti = []; hgca = []; hstr = []; for index = 1:length(handles) try, hx = [ hx get(handles(index), 'xlabel') ]; catch, end; try, hy = [ hy get(handles(index), 'ylabel') ]; catch, end; try, hti = [ hti get(handles(index), 'title') ]; catch, end; try, get(handles(index), 'xtick'); hgca = [ hgca handles(index) ]; catch, end; try, get(handles(index), 'string'); hstr = [ hstr handles(index) ]; catch, end; end;
github
ZijingMao/baselineeegtest-master
makeelec.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/makeelec.m
4,102
utf_8
9b8707861db861dad7e9c657c46b011c
% makeelec() - subroutine to make electrode file in eegplot() % % Usage: >> makeelec(chans) % >> [channames] = makeelec(chans) % % Inputs: % chans - number of channels % % Author: Colin Humprhies, CNL / Salk Institute, 1996 % % See also: eegplot() % Copyright (C) Colin Humphries, 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 % 01-25-02 reformated help & license, added links -ad function channames = makeelec(chans); global is_done_pressed is_done_pressed = 0; lines = ceil(chans/2); fh = 180 + chans*12; fl = 400; figure('Units','Pixels','Position',[400 200 fl fh]) fighandle = gcf; axes('Units','Pixels','Position',[0 0 fl fh],'Visible','off','Xlim',[0 fl],'Ylim',[0 fh]); text(fl/2,fh-20,'Make Electrode-File','HorizontalAlignment','Center','Fontsize',14) titleb = uicontrol('Units','Pixels','Style','Edit','Position',... [fl/2 fh-60 .4*fl 20],'UserData',0,'HorizontalAlignment','left'); text(fl/2-20,fh-50,'Filename:','HorizontalAlignment','Right') text(fl/2,fh-75,'Electrodes','HorizontalAlignment','center') %line([fl*.2 fl*.8],[fh-85 fh-85],'color','w') for i = 1:chans k = 2*ceil(i/2); if (i==k) ede(i,:) = uicontrol('Units','Pixels','Style','Edit',... 'Position',[fl*.65 fh-90-k*12 fl*.15 20],'UserData',i,'HorizontalAlignment','left'); text(fl*.65-15,fh-90-k*12+10,num2str(i),'HorizontalAlignment','right') else ede(i,:) = uicontrol('Units','Pixels','Style','Edit',... 'Position',[fl*.2 fh-90-k*12 fl*.15 20],'UserData',i,'HorizontalAlignment','left'); text(fl*.2-15,fh-90-k*12+10,num2str(i),'HorizontalAlignment','right') end end TIMESTRING = ['chans1973 = get(gco,''UserData'');','OH1973 = findobj(''Style'',''edit'',''UserData'',0);','FILENAME1973 = get(OH1973,''string'');','if isempty(FILENAME1973);','fprintf(''Filename Missing'');','else;','channames1973 = zeros(chans1973,6);','for i1973 = 1:chans1973;','Aa1973 = findobj(''Style'',''edit'',''UserData'',i1973);','elabel1973 = get(Aa1973,''string'');','channames1973(i1973,6-length(elabel1973)+1:6) = elabel1973;','end;','for i1973 = 1:length(channames1973(:));','if channames1973(i1973) == 0;','channames1973(i1973) = ''.'';','end;','end;','FID1973 = fopen(FILENAME1973,''w'');','fprintf(FID1973,''%s'',channames1973'');','fclose(FID1973);','fprintf(''Saving file'');','end;','clear chans1973 OH1973 FILENAME1973 Aa1973 elabel1973 ii1973 FID1973 channames1973 i1973;']; saveb = uicontrol('Units','Pixels','Style','PushButton','Position',[fl/10 20 fl*.15 25],'String','Save','UserData',chans,'Callback',TIMESTRING); TIMESTRING = ['global is_done_pressed;','is_done_pressed = 1;','clear is_done_pressed']; closeb = uicontrol('Units','Pixels','Style','PushButton','Position',... [fl*.45 20 fl*.15 25],'String','Done','Callback',TIMESTRING); TIMESTRING = ['global is_done_pressed;','is_done_pressed = 2;','clear is_done_pressed']; cancelb = uicontrol('Units','Pixels','Style','PushButton','Position',... [fl*.75 20 fl*.15 25],'String','Cancel','Callback',TIMESTRING); while(is_done_pressed == 0) drawnow; end if is_done_pressed == 1 channames = []; for i = 1:chans a = findobj('Style','edit','UserData',i); elabel = get(a,'string'); channames = str2mat(channames,elabel); end channames = str2mat(channames,' '); else channames = []; end delete(fighandle) clear is_done_pressed
github
ZijingMao/baselineeegtest-master
gradplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/gradplot.m
5,524
utf_8
06af207aeee2691a8ac50369845dfc65
% gradplot() - Compute the gradient of EEG scalp map(s) on a square grid % % Usage: % >> [gradX, gradY] = gradplot(maps,eloc_file,draw) % Inputs: % maps - Activity levels, size (nelectrodes,nmaps) % eloc_file - Electrode location filename (.loc file) containing electrode % - coordinates (For format, see >> topoplot example) % draw - If defined, draw the gradient map(s) {default: no} % % Outputs: % gradX - Gradients in X direction % gradY - Gradients in Y directions % % Note: Use cart2pol() to convert to polar (amp, direction) coordinates). % % Authors: Marissa Westerfield & Arnaud Delorme, CNL/Salk Institute, La Jolla 3/10/01 % % See also: topoplot(), lapplot() % Copyright (C) 3/10/01 Marissa Westerfield & Arnaud Delorme, CNL/Salk Institute, La Jolla % % 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, added links -ad function [gradx, grady] = gradplot( map, locs_file, draw ) if nargin < 2 help gradplot; return; end; NCHANS = size(map,1); GRID_SCALE = 2*NCHANS+5; MAX_RADIUS = 0.5; % -------------------------------- % Read the electrode location file % -------------------------------- if isstr(locs_file) % a locs file [tmpeloc labels Th Rd ind] = readlocs(locs_file,'filetype', ... 'loc'); [x,y] = pol2cart(Th/180*pi,Rd); % See Bug 149 % [x,y] = pol2cart(Th,Rd); elseif isstruct(locs_file) % a locs struct [tmpeloc labels Th Rd ind] = readlocs(locs_file); if max(abs(Rd))>0.5 fprintf('gradplot(): Shrinking electrode arc_lengths from (max) %4.3f to (max) 0.5\n',... max(abs(Rd))); Rd = Rd/(2*max(abs(Rd))); % shrink to max radius = 0.5 end [x,y] = pol2cart(Th,Rd); if length(x) ~= NCHANS fprintf(... 'gradplot(): channels in locs file (%d) ~= channels in maps (%d)\n', ... length(x), NCHANS); return end else % what is this complex number format ??? -sm x = real(locs_file); y = imag(locs_file); end; % ------------------------------------------------ % Locate nearest position of electrode in the grid % ------------------------------------------------ xi = linspace(-0.5,0.5,GRID_SCALE); % x-axis description (row vector) yi = linspace(-0.5,0.5,GRID_SCALE); % y-axis description (row vector) delta = xi(2)-xi(1); % length of grid entry horizidx=zeros(1, NCHANS); %preallocation vertidx=zeros(1, NCHANS); % preallocation for c=1:NCHANS [useless_var horizidx(c)] = min(abs(y(c) - xi)); % find pointers to electrode [useless_var vertidx(c)] = min(abs(x(c) - yi)); % positions in Zi end; % ------------------- % Compute gradient(s) % ------------------- for m=1:size(map,2) [Xi,Yi,Zi] = griddata(y,x,map(:,m),yi',xi, 'v4'); % interpolate data [FX,FY] = gradient(Zi); positions = horizidx + (vertidx-1)*GRID_SCALE; gradx(:,m) = FX(positions(:)); grady(:,m) = FY(positions(:)); % ---------------- % Draw gradient(s) % ---------------- if exist('draw') % Take data within head mask = (sqrt(Xi.^2+Yi.^2) <= MAX_RADIUS); mask = find(mask==0); Zi(mask) = NaN; FX(mask) = NaN; FY(mask) = NaN; width = max(Xi)-min(Xi); subplot(ceil(sqrt(size(map,2))), ceil(sqrt(size(map,2))), m); % surface(1+width*(0.5+Xi-delta/2),... % 1+width*(0.5+Yi-delta/2),... % zeros(size(Zi)),Zi,'EdgeColor','none',... % 'FaceColor','flat'); hold on contour(imresize(Zi,0.5)); hold on quiver(imresize(FX, 0.5), imresize(FY, 0.5)); title(['Map ' int2str(m)]); % %%% Draw Head %%%% ax = axis; width = ax(2)-ax(1); expansion = 0.3; axis([ax(1)-expansion ax(2)+expansion ax(3)-expansion ax(4)+expansion]) steps = 0:2*pi/100:2*pi; basex = .18*MAX_RADIUS; tip = MAX_RADIUS*1.15; base = MAX_RADIUS-.004; EarX = [.497 .510 .518 .5299 .5419 .54 .547 .532 .510 .489]; EarY = [.0555 .0775 .0783 .0746 .0555 -.0055 -.0932 -.1313 -.1384 -.1199]; HCOLOR = 'k'; HLINEWIDTH = 1.8; % Plot Head, Ears, Nose hold on plot(1+width/2+cos(steps).*MAX_RADIUS*width,... 1+width/2+sin(steps).*MAX_RADIUS*width,... 'color',HCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % head plot(1+width/2+[.18*MAX_RADIUS*width;0;-.18*MAX_RADIUS*width],... 1+width/2+[base;tip;base]*width,... 'Color',HCOLOR,'LineWidth',HLINEWIDTH); % nose plot(1+width/2+EarX*width,... 1+width/2+EarY*width,... 'color',HCOLOR,'LineWidth',HLINEWIDTH) % l ear plot(1+width/2-EarX*width,... 1+width/2+EarY*width,... 'color',HCOLOR,'LineWidth',HLINEWIDTH) % r ear hold off axis off end; end; return;
github
ZijingMao/baselineeegtest-master
std_comppol.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_comppol.m
2,105
utf_8
90c72a999241b33865a1419e64117e0f
% std_comppol() - inverse component polarity in a component cluster % % Usage: [compout pol] = std_comppol(compin); % % Inputs: % compin - component scalp maps, one per column. % % Outputs: % compout - component scalp maps some of them with inverted % polarities, one per column. % pol - logical vector of component with inverted % polarities (same length as the number of rows in % compin) % % Author: Arnaud Delorme & Hilit Serby, SCCN, INC, UCSD, 2004 % Copyright (C) 2004 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 [compin, pol] = std_comppol(compin); if nargin < 1 help std_comppol; return; end; % remove the NaN % -------------- for index = 1:size(compin,2) compin(isnan(compin(:,index)),:) =[]; end; % run several iterations % ---------------------- pol = ones(1,size(compin,2)); for repeat=1:3 compave = mean(compin,2); for index = 1:size(compin,2) % remove diagonal and put 0 and 1 % ------------------------------- if ~all(compin(:,index) == 0) r = corrcoef(compave, compin(:,index) ); else r = zeros(2,2); end; % invert component polarities % --------------------------- if r(2) < 0 compin(:,index) = -compin(:,index); pol(index) = -pol(index); end; end; end;
github
ZijingMao/baselineeegtest-master
std_readdata.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readdata.m
32,955
utf_8
dec4496e7d4fbed868b76072fa81e3fe
% std_readdata() - LEGACY FUNCTION, SHOULD NOT BE USED ANYMORE. INSTEAD % USE std_readerp, std_readspec, ... % load one or more requested measures % ['erp'|'spec'|'ersp'|'itc'|'dipole'|'map'] % for all components of a specified cluster. % Called by cluster plotting functions % std_envtopo(), std_erpplot(), std_erspplot(), ... % Usage: % >> [STUDY, clustinfo, finalinds] = std_readdata(STUDY, ALLEEG); % % return all measures % >> [STUDY, clustinfo, finalinds] = std_readdata(STUDY, ALLEEG, ... % cluster, infotype,varargin); % Inputs: % STUDY - studyset structure containing some or all files in ALLEEG % ALLEEG - vector of loaded EEG datasets % % Optional inputs: % 'infotype' - ['erp'|'spec'|'ersp'|'itc'|'dipole'|'map'|'data'|'event'] % type of stored data or cluster information to read. May % also be a cell array of these types, for example: { 'erp' % 'map' 'dipole' }. {default: 'erp'} % 'channels' - [cell] list of channels to import {default: all} % 'clusters' - [integer] list of clusters to import {[]|default: all but % the parent cluster (1) and any 'NotClust' clusters} % 'freqrange' - [min max] frequency range {default: whole measure range} % 'timerange' - [min max] time range {default: whole measure epoch} % 'statmode' - ['individual'|'trials'] statistical mode for ERSP (also % specify what type of data to import -- mean (of individual % subjects), or trials. This functionality is still unstable % for 'trials' { default: 'individual'} % 'rmsubjmean' - ['on'|'off'] remove mean subject spectrum from every component % or channel spectrum, making them easier to compare % { default: 'off' } % 'subbaseline' - ['on'|'off'] remove all condition and spectrum baselines % for ERSP data { default: 'on' } % % Optional inputs for events: % 'type','timewin','fieldname' - optional parameters for the function % eeg_geteventepoch may also be used to select specific % events. % % Optional inputs for raw data: % 'rmclust' - [integer] list of artifact cluster indices to subtract % when reading raw data. % % Output: % STUDY - (possibly) updated STUDY structure % clustinfo - structure of specified cluster information. % This is the same as STUDY.cluster(cluster_number) % Fields: % clustinfo.erpdata % (ncomps, ntimes) array of component ERPs % clustinfo.erptimes % vector of ERP epoch latencies (ms) % % clustinfo.specdata % (ncomps, nfreqs) array of component spectra % clustinfo.specfreqs % vector of spectral frequencies (Hz) % % clustinfo.erspdata % (ncomps,ntimes,nfreqs) array of component ERSPs % clustinfo.ersptimes % vector of ERSP latencies (ms) % clustinfo.erspfreqs % vector of ERSP frequencie (Hz) % % clustinfo.itcdata % (ncomps,ntimes,nfreqs) array of component ITCs % clustinfo.itctimes % vector of ITC latencies (ms) % clustinfo.itc_freqs % vector of ITC frequencies (Hz) % % clustinfo.topo % (ncomps,65,65) array of component scalp map grids % clustinfo.topox % abscissa values for columns of the scalp maps % clustinfo.topoy % ordinate values for rows of the scalp maps % % clustinfo.data % raw data arrays % clustinfo.datatimes % time point for raw data % clustinfo.datasortvals % sorting values (one per trial) % clustinfo.datacontinds % dataset indices (contacted for all trials) % % clustinfo.dipole % array of component dipole information structs % % with the same format as EEG.dipfit.model % % finalinds - either the cluster(s) or channel(s) indices selected. % % Example: % % To obtain the ERPs for all Cluster-3 components from a STUDY % % % [STUDY clustinfo] = std_readdata(STUDY, ALLEEG, 'clusters',3, 'infotype','erp'); % figure; plot(clustinfo.erptimes, mean(clustinfo.erpdata,2)); % % 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, clustinfo, finalinds] = std_readdata(STUDY, ALLEEG, varargin); if nargin < 2 help std_readdata; return; end if nargin < 3 channel = {}; end [opt moreopts] = finputcheck( varargin, { ... 'type' { 'string','cell' } { [] [] } ''; 'timewin' 'real' [] [-Inf Inf]; 'fieldname' 'string' [] 'latency'; 'condition' 'cell' [] {}; 'channels' 'cell' [] {}; 'clusters' 'integer' [] []; 'rmclust' 'integer' [] []; 'freqrange' 'real' [] []; 'timerange' 'real' [] []; 'statmode' 'string' { 'subjects','individual','common','trials' } 'individual'; 'rmicacomps' 'string' { 'on','off' } 'off'; 'subbaseline' 'string' { 'on','off' } 'off'; 'rmsubjmean' 'string' { 'on','off' } 'off'; 'singletrials' 'string' { 'on','off' } 'on'; 'infotype' 'string' { 'erp','spec','ersp','itc','map','topo','dipole','scalp','data','event','' } '' }, ... 'std_readdata', 'ignore'); if isstr(opt), error(opt); end; if isempty(opt.infotype), disp('No measure selected, returning ERPs'); opt.infotype = 'erp'; end; if strcmpi(opt.infotype, 'erp'), STUDY = pop_erpparams(STUDY, 'default'); if isempty(opt.timerange), opt.timerange = STUDY.etc.erpparams.timerange; end; elseif strcmpi(opt.infotype, 'spec'), STUDY = pop_specparams(STUDY, 'default'); if isempty(opt.freqrange), opt.freqrange = STUDY.etc.specparams.freqrange; end; elseif strcmpi(opt.infotype, 'ersp') | strcmpi(opt.infotype, 'itc') STUDY = pop_erspparams(STUDY, 'default'); if isempty(opt.freqrange), opt.freqrange = STUDY.etc.erspparams.freqrange; end; if isempty(opt.timerange), opt.timerange = STUDY.etc.erspparams.timerange; end; if strcmpi(opt.statmode, 'individual') | strcmpi(opt.statmode, 'subjects'), opt.statmode = STUDY.etc.erspparams.statmode;end; if strcmpi(opt.subbaseline, 'on'), opt.subbaseline = STUDY.etc.erspparams.subbaseline; end; end; nc = max(length(STUDY.condition),1); ng = max(length(STUDY.group),1); zero = single(0); tmpver = version; if tmpver(1) == '6' | tmpver(1) == '5' zero = double(zero); end; % find channel indices % -------------------- if ~isempty(opt.channels) finalinds = std_chaninds(STUDY, opt.channels); else finalinds = opt.clusters; end; % read topography with another function % ------------------------------------- if strcmpi(opt.infotype, 'map') | strcmpi(opt.infotype, 'scalp') | strcmpi(opt.infotype, 'topo') [STUDY tmpclust] = std_readtopoclust(STUDY, ALLEEG, opt.clusters); clustinfo = []; for index = 1:length(tmpclust) if index == 1, clustinfo = tmpclust{index}; else clustinfo(index) = tmpclust{index}; end; end; return; end; % read indices for removing component clusters from data % ------------------------------------------------------ % NOT USED ANY MORE if ~isempty(opt.rmclust) for ind = 1:length(opt.rmclust) [tmp setindsrm{ind} allindsrm{ind}] = std_setinds2cell(STUDY, opt.rmclust(ind)); end; end; for ind = 1:length(finalinds) % find indices % ------------ if ~isempty(opt.channels) tmpstruct = STUDY.changrp(finalinds(ind)); alldatasets = 1:length(STUDY.datasetinfo); %allchanorcomp = -tmpstruct.chaninds; allinds = tmpstruct.allinds; for i=1:length(allinds(:)), allinds{i} = -allinds{i}; end; % invert sign for reading setinds = tmpstruct.setinds; else % Use the 3 lines below and comment the last one when ready % to switch and remove all .comps and .inds %tmpstruct = STUDY.cluster(finalinds(ind)); %allinds = tmpstruct.allinds; %setinds = tmpstruct.setinds; [ tmpstruct setinds allinds ] = std_setcomps2cell(STUDY, finalinds(ind)); %[ STUDY.cluster(finalinds(ind)) ] = std_setcomps2cell(STUDY, finalinds(ind)); %STUDY.cluster(finalinds(ind)) = std_cell2setcomps( STUDY, ALLEEG, finalinds(ind)); %[ STUDY.cluster(finalinds(ind)) setinds allinds ] = std_setcomps2cell(STUDY, finalinds(ind)); end; dataread = 0; switch opt.infotype case 'event', % check if data is already here % ----------------------------- if isfield(tmpstruct, 'datasortvals') if ~isempty(tmpstruct.datasortvals) dataread = 1; end; end; if ~dataread % reserve arrays % -------------- datasortvals = cell( max(length(STUDY.condition),1), max(length(STUDY.group),1) ); datacontinds = cell( max(length(STUDY.condition),1), max(length(STUDY.group),1) ); for c = 1:nc for g = 1:ng datasortvals{c, g} = repmat(zero, [1, sum([ ALLEEG(setinds{c,g}).trials ] )]); datacontinds{c, g} = repmat(zero, [1, sum([ ALLEEG(setinds{c,g}).trials ] )]); end; end; % read the data and select channels % --------------------------------- if ~isempty(opt.type) fprintf('Reading events:'); for c = 1:nc for g = 1:ng counttrial = 1; for indtmp = 1:length(allinds{c,g}) tmpdata = eeg_getepochevent(ALLEEG(setinds{c,g}(indtmp)), ... 'type', opt.type, 'timewin', opt.timewin, 'fieldname', opt.fieldname); datasortvals{c, g}(:,counttrial:counttrial+ALLEEG(setinds{c,g}(indtmp)).trials-1) = squeeze(tmpdata); datacontinds{c, g}(:,counttrial:counttrial+ALLEEG(setinds{c,g}(indtmp)).trials-1) = setinds{c,g}(indtmp); counttrial = counttrial+ALLEEG(setinds{c,g}(indtmp)).trials; fprintf('.'); end; end; end; end; fprintf('\n'); tmpstruct.datasortvals = datasortvals; tmpstruct.datacontinds = datacontinds; end; case 'data', % check if data is already here % ----------------------------- if isfield(tmpstruct, 'data') if ~isempty(tmpstruct.data) dataread = 1; end; end; if ~dataread % reserve arrays % -------------- alldata = cell( max(length(STUDY.condition),1), max(length(STUDY.group),1) ); for c = 1:nc for g = 1:ng alldata{c, g} = repmat(zero, [ALLEEG(1).pnts, sum([ ALLEEG(setinds{c,g}).trials ] )]); end; end; % read the data and select channels % --------------------------------- fprintf('Reading data/activity:'); for c = 1:nc for g = 1:ng counttrial = 1; for indtmp = 1:length(allinds{c,g}) settmpind = STUDY.datasetinfo(setinds{c,g}(indtmp)).index; % current dataset if isempty(opt.channels) tmpdata = eeg_getdatact(ALLEEG(settmpind), 'component', allinds{c,g}(indtmp), 'verbose', 'off'); elseif isempty(opt.rmclust) & strcmpi(opt.rmicacomps, 'off') tmpdata = eeg_getdatact(ALLEEG(settmpind), 'channel', -allinds{c,g}(indtmp), 'verbose', 'off'); elseif strcmpi(opt.rmicacomps, 'on') rmcomps = find(ALLEEG(settmpind).reject.gcompreject); tmpdata = eeg_getdatact(ALLEEG(settmpind), 'channel', -allinds{c,g}(indtmp), 'rmcomps', rmcomps, 'verbose', 'off'); else rmcomps = getclustcomps(STUDY, opt.rmclust, settmpind); tmpdata = eeg_getdatact(ALLEEG(settmpind), 'channel', -allinds{c,g}(indtmp), 'rmcomps', rmcomps, 'verbose', 'off'); end; alldata{c, g}(:,counttrial:counttrial+ALLEEG(setinds{c,g}(indtmp)).trials-1) = squeeze(tmpdata); counttrial = counttrial+ALLEEG(setinds{c,g}(indtmp)).trials; fprintf('.'); end; end; end; fprintf('\n'); tmpstruct.datatimes = ALLEEG(1).times; tmpstruct.data = alldata; end; case 'erp', disp('std_readdata is a legacy function, it should not be used to read ERP data, use std_readerp instead'); % check if data is already here % ----------------------------- if isfield(tmpstruct, 'erpdata') if isequal( STUDY.etc.erpparams.timerange, opt.timerange) & ~isempty(tmpstruct.erpdata) dataread = 1; end; end; if ~dataread % reserve arrays % -------------- allerp = cell( max(length(STUDY.condition),1), max(length(STUDY.group),1) ); tmpind = 1; while(isempty(setinds{tmpind})), tmpind = tmpind+1; end; [ tmp alltimes ] = std_readerp( ALLEEG, setinds{tmpind}(1), allinds{tmpind}(1), opt.timerange); for c = 1:nc for g = 1:ng allerp{c, g} = repmat(zero, [length(alltimes), length(allinds{c,g})]); end; end; % read the data and select channels % --------------------------------- fprintf('Reading ERP data:'); for c = 1:nc for g = 1:ng for indtmp = 1:length(allinds{c,g}) [ tmperp alltimes ] = std_readerp( ALLEEG, setinds{c,g}(indtmp), allinds{c,g}(indtmp), opt.timerange); allerp{c, g}(:,indtmp) = tmperp(:); fprintf('.'); end; end; end; fprintf('\n'); tmpstruct.erptimes = alltimes; tmpstruct.erpdata = allerp; end; case 'spec', disp('std_readdata is a legacy function, it should not be used to read SPECTRUM data, use std_readspec instead'); % check if data is already here % ----------------------------- if isfield(tmpstruct, 'specdata') if isequal( STUDY.etc.specparams.freqrange, opt.freqrange) & ~isempty(tmpstruct.specdata) dataread = 1; end; end; if ~dataread % reserve arrays % -------------- allspec = cell( max(length(STUDY.condition),1), max(length(STUDY.group),1) ); filetype = 'spec'; tmpind = 1; while(isempty(setinds{tmpind})), tmpind = tmpind+1; end; try, [ tmp allfreqs ] = std_readspec( ALLEEG, setinds{tmpind}(1), allinds{tmpind}(1), opt.freqrange); catch filetype = 'ersp'; disp('Cannot find spectral file, trying ERSP baseline file instead'); [ tmpersp allfreqs alltimes tmpparams tmpspec] = std_readersp( ALLEEG, setinds{tmpind}(1), allinds{tmpind}(1), [], opt.freqrange); end; for c = 1:nc for g = 1:ng allspec{c, g} = repmat(zero, [length(allfreqs), length(allinds{c,g}) ]); end; end; % read the data and select channels % --------------------------------- if strcmpi(filetype, 'spec') fprintf('Reading Spectrum data...'); for c = 1:nc for g = 1:ng allspec{c, g} = std_readspec( ALLEEG, setinds{c,g}(:), allinds{c,g}(:), opt.freqrange)'; end; end; else % std_readersp cannot be converted to read multiple datasets since it subtracts data between conditions fprintf('Reading Spectrum data:'); for c = 1:nc for g = 1:ng for indtmp = 1:length(allinds{c,g}) [ tmpersp allfreqs alltimes tmpparams tmpspec] = std_readersp( ALLEEG, setinds{c,g}(indtmp), allinds{c,g}(indtmp), [], opt.freqrange); allspec{c, g}(:,indtmp) = 10*log(tmpspec(:)); fprintf('.'); end; end; end; end; fprintf('\n'); % remove mean of each subject across groups and conditions if strcmpi(opt.rmsubjmean, 'on') & ~isempty(opt.channels) disp('Removing mean spectrum accross subjects'); for indtmp = 1:length(allinds{c,g}) % scan subjects meanspec =zeros(size( allspec{1, 1}(:,indtmp) )); for c = 1:nc for g = 1:ng meanspec = meanspec + allspec{c, g}(:,indtmp)/(nc*ng); end; end; for c = 1:nc for g = 1:ng allspec{c, g}(:,indtmp) = allspec{c, g}(:,indtmp) - meanspec; % subtractive model % allspec{c, g}(:,indtmp) = allspec{c, g}(:,indtmp)./meanspec; % divisive model end; end; end; end; tmpstruct.specfreqs = allfreqs; tmpstruct.specdata = allspec; end; case { 'ersp' 'itc' 'pac' }, disp('std_readdata is a legacy function, it should not be used to read ERSP/ITC data, use std_readersp instead'); % check if data is already here % ----------------------------- if strcmpi(opt.infotype, 'ersp') if isfield(tmpstruct, 'erspdata') if isequal( STUDY.etc.erspparams.timerange, opt.timerange) & ... isequal( STUDY.etc.erspparams.freqrange, opt.freqrange) & ~isempty(tmpstruct.erspdata) dataread = 1; end; end; elseif strcmpi(opt.infotype, 'itc') if isfield(tmpstruct, 'itcdata') if isequal( STUDY.etc.erspparams.timerange, opt.timerange) & ... isequal( STUDY.etc.erspparams.freqrange, opt.freqrange) & ~isempty(tmpstruct.itcdata) dataread = 1; end; end; else if isfield(tmpstruct, 'pacdata') dataread = 1; end; end; if ~dataread % find total nb of trials % ----------------------- if strcmpi(opt.statmode, 'trials') tottrials = cell( length(STUDY.condition), length(STUDY.group) ); for index = 1:length( STUDY.datasetinfo ) condind = strmatch( STUDY.datasetinfo(index).condition, STUDY.condition ); grpind = strmatch( STUDY.datasetinfo(index).group , STUDY.group ); if isempty(tottrials{condind, grpind}), tottrials{condind, grpind} = ALLEEG(index).trials; else tottrials{condind, grpind} = tottrials{condind, grpind} + ALLEEG(index).trials; end; end; end; % reserve arrays % -------------- ersp = cell( max(length(STUDY.condition),1), max(length(STUDY.group),1) ); erspbase = cell( max(length(STUDY.condition),1), max(length(STUDY.group),1) ); erspinds = cell( max(length(STUDY.condition),1), max(length(STUDY.group),1) ); tmpind = 1; while(isempty(setinds{tmpind})), tmpind = tmpind+1; end; [ tmp allfreqs alltimes ] = std_readersp( ALLEEG, setinds{tmpind}(1), Inf*allinds{tmpind}(1), opt.timerange, opt.freqrange); for c = 1:nc for g = 1:ng ersp{c, g} = repmat(zero, [length(alltimes), length(allfreqs), length(allinds{c,g}) ]); erspbase{c, g} = repmat(zero, [ 1, length(allfreqs), length(allinds{c,g}) ]); if strcmpi(opt.statmode, 'trials') ersp{ c, g} = repmat(zero, [length(alltimes), length(allfreqs), tottrials{c, g} ]); count{c, g} = 1; end; end; end; % read the data and select channels % --------------------------------- fprintf('Reading all %s data:', upper(opt.infotype)); for c = 1:nc for g = 1:ng for indtmp = 1:length(allinds{c,g}) try % this 'try' is a poor solution the problem of attempting % to read specific channel/component data that doesn't exist % called below by: allinds{c,g}(indtmp) if strcmpi(opt.statmode, 'trials') [ tmpersp allfreqs alltimes tmpparams] = std_readtimef( ALLEEG, setinds{c,g}(indtmp), allinds{c,g}(indtmp), ... opt.timerange, opt.freqrange); indices = [count{c, g}:count{c, g}+size(tmpersp,3)-1]; ersp{ c, g}(:,:,indices) = permute(tmpersp, [2 1 3]); 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) ~= ALLEEG(STUDY.datasetinfo(index).index).trials error( sprintf('Wrong number of trials in datafile for dataset %d\n', STUDY.datasetinfo(index).index)); end; elseif strcmpi(opt.infotype, 'itc') [ tmpersp allfreqs alltimes tmpparams] = std_readitc( ALLEEG, setinds{c,g}(indtmp), allinds{c,g}(indtmp), ... opt.timerange, opt.freqrange); ersp{c, g}(:,:,indtmp) = abs(permute(tmpersp , [2 1])); elseif strcmpi(opt.infotype, 'pac') [ tmpersp allfreqs alltimes tmpparams] = std_readpac( ALLEEG, setinds{c,g}(indtmp), allinds{c,g}(indtmp), ... opt.timerange, opt.freqrange); ersp{c, g}(:,:,indtmp) = abs(permute(tmpersp , [2 1])); else [ tmpersp allfreqs alltimes tmpparams tmperspbase] = std_readersp( ALLEEG, setinds{c,g}(indtmp), allinds{c,g}(indtmp), ... opt.timerange, opt.freqrange); ersp{c, g}( :,:,indtmp) = permute(tmpersp , [2 1]); erspbase{c, g}(:,:,indtmp) = 10*log(permute(tmperspbase, [2 1])); end catch end fprintf('.'); end; end; end; fprintf('\n'); % compute ERSP or ITC if trial mode % (since only the timef have been loaded) % --------------------------------------- if strcmpi(opt.statmode, 'trials') for c = 1:nc for g = 1:ng if strcmpi(opt.infotype, 'itc') ersp{c,g} = ersp{c,g}./abs(ersp{c,g}); else ersp{c,g} = 20*log10(abs(ersp{c,g})); % remove baseline (each trial baseline is removed => could % also be the average across all data trials) [tmp indl] = min( abs(alltimes-0) ); erspbase{c,g} = mean(ersp{c,g}(1:indl,:,:,:)); ersp{c,g} = ersp{c,g} - repmat(erspbase{c,g}, [size(ersp{c,g},1) 1 1 1]); end; end; end; end; % compute average baseline across groups and conditions % ----------------------------------------------------- if strcmpi(opt.subbaseline, 'on') & strcmpi(opt.infotype, 'ersp') disp('Recomputing baseline...'); for g = 1:ng % ng = number of groups for c = 1:nc % nc = number of components if strcmpi(opt.statmode, 'trials') if c == 1, meanpowbase = abs(mean(erspbase{c,g}/nc,3)); else meanpowbase = meanpowbase + abs(mean(erspbase{c,g}/nc,3)); end; else if c == 1, meanpowbase = abs(erspbase{c,g}/nc); else meanpowbase = meanpowbase + abs(erspbase{c,g}/nc); end; end; end; % subtract average baseline % ------------------------- for c = 1:nc if strcmpi(opt.statmode, 'trials'), tmpmeanpowbase = repmat(meanpowbase, [length(alltimes) 1 tottrials{c,g}]); else tmpmeanpowbase = repmat(meanpowbase, [length(alltimes) 1 1]); end; ersp{c,g} = ersp{c,g} - repmat(abs(erspbase{c,g}), [length(alltimes) 1 1 1]) + tmpmeanpowbase; end; clear meanpowbase; 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 strcmpi(opt.infotype, 'ersp') tmpstruct.erspfreqs = allfreqs; tmpstruct.ersptimes = alltimes; tmpstruct.erspdata = ersp; tmpstruct.erspbase = erspbase; if strcmpi(opt.statmode, 'trials') tmpstruct.erspsubjinds = erspinds; end; elseif strcmpi(opt.infotype, 'itc') tmpstruct.itcfreqs = allfreqs; tmpstruct.itctimes = alltimes; tmpstruct.itcdata = ersp; if strcmpi(opt.statmode, 'trials') tmpstruct.itcsubjinds = erspinds; end; else tmpstruct.pacfreqs = allfreqs; tmpstruct.pactimes = alltimes; tmpstruct.pacdata = ersp; end; end; case 'dipole', fprintf('Reading dipole data...\n'); % old format EEGLAB 8.3 % alldips = {}; % for c = 1:nc % for g = 1:ng % for indtmp = 1:size(tmpstruct.sets,2) % alldips{c, g}(indtmp).posxyz = ALLEEG(tmpstruct.sets(1,indtmp)).dipfit.model(tmpstruct.comps(1,indtmp)).posxyz; % alldips{c, g}(indtmp).momxyz = ALLEEG(tmpstruct.sets(1,indtmp)).dipfit.model(tmpstruct.comps(1,indtmp)).momxyz; % alldips{c, g}(indtmp).rv = ALLEEG(tmpstruct.sets(1,indtmp)).dipfit.model(tmpstruct.comps(1,indtmp)).rv; % end; % end; % end; % tmpstruct.dipoles = alldips; alldips = []; for indtmp = 1:size(tmpstruct.sets,2) alldips(indtmp).posxyz = ALLEEG(tmpstruct.sets(1,indtmp)).dipfit.model(tmpstruct.comps(1,indtmp)).posxyz; alldips(indtmp).momxyz = ALLEEG(tmpstruct.sets(1,indtmp)).dipfit.model(tmpstruct.comps(1,indtmp)).momxyz; alldips(indtmp).rv = ALLEEG(tmpstruct.sets(1,indtmp)).dipfit.model(tmpstruct.comps(1,indtmp)).rv; end; tmpstruct.alldipoles = alldips; case { 'map' 'scalp' 'topo' } % this is currenlty being done by the function std_readtopoclust % at the beginning of this function otherwise, error('Unrecognized ''infotype'' entry'); end; % end switch % copy results to structure % ------------------------- fieldnames = { 'erpdata' 'erptimes' 'specdata' 'specfreqs' 'erspdata' 'erspbase' 'erspfreqs' 'ersptimes' ... 'itcfreqs' 'itctimes' 'itcdata' 'erspsubjinds' 'itcsubjinds' 'allinds' 'setinds' 'dipoles' 'alldipoles' ... 'data' 'datatimes' 'datasortvals' 'datacontinds' }; for f = 1:length(fieldnames) if isfield(tmpstruct, fieldnames{f}), tmpdata = getfield(tmpstruct, fieldnames{f}); if ~isempty(opt.channels) STUDY.changrp = setfield(STUDY.changrp, { finalinds(ind) }, fieldnames{f}, tmpdata); else STUDY.cluster = setfield(STUDY.cluster, { finalinds(ind) }, fieldnames{f}, tmpdata); end; end; end; end; % return structure % ---------------- if ~isempty(opt.channels) clustinfo = STUDY.changrp(finalinds); else clustinfo = STUDY.cluster(finalinds); end; % find components in cluster for specific dataset % ----------------------------------------------- function rmcomps = getclustcomps(STUDY, rmclust, settmpind); rmcomps = [ ]; for rmi = 1:length(rmclust) findind = find(settmpind == STUDY.cluster(rmclust(rmi)).setinds{c,g}); rmcomps = [ rmcomps STUDY.cluster(rmclust(rmi)).allinds{c,g}(findind) ]; end;
github
ZijingMao/baselineeegtest-master
std_readerp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readerp.m
17,686
utf_8
85e306c03b4a0894eb5e88a8db54b7a5
% std_readerp() - load ERP measures for data channels or % for all components of a specified cluster. % Called by plotting functions % std_envtopo(), std_erpplot(), std_erspplot(), ... % Usage: % >> [STUDY, datavals, times, setinds, cinds] = ... % std_readerp(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'. % 'subject' - [string] select a specific subject {default:all} % 'component' - [integer] select a specific component in a cluster % {default:all} % % ERP specific optional inputs: % 'timerange' - [min max] time range {default: whole measure range} % 'componentpol' - ['on'|'off'] invert ERP component sign based on % scalp map match with component scalp map centroid. % {default:'on'} % % Output: % STUDY - updated studyset structure % datavals - [cell array] erp data (the cell array size is % condition x groups) % times - [float array] array of time values % setinds - [cell array] datasets indices % cinds - [cell array] channel or component indices % % Example: % std_precomp(STUDY, ALLEEG, { ALLEEG(1).chanlocs.labels }, 'erp', 'on'); % [erp times] = std_readerp(STUDY, ALLEEG, 'channels', { ALLEEG(1).chanlocs(1).labels }); % % 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, datavals, xvals, setinds, allinds] = std_readerp(STUDY, ALLEEG, varargin) if nargin < 2 help std_readerp; return; end if ~isstruct(ALLEEG) % old calling format % ------------------ EEG = STUDY(ALLEEG); filename = fullfile(EEG.filepath, EEG.filename(1:end-4)); comporchan = varargin{1}; options = {'measure', 'erp'}; if length(varargin) > 1, options = { options{:} 'timelimits', varargin{2} }; end; if comporchan(1) > 0 [datavals tmp xvals] = std_readfile(filename, 'components',comporchan, options{:}); else [datavals tmp xvals] = std_readfile(filename, 'channels', comporchan, options{:}); end; STUDY = datavals'; datavals = xvals; return; end; STUDY = pop_erpparams(STUDY, 'default'); STUDY = pop_specparams(STUDY, 'default'); [opt moreopts] = finputcheck( varargin, { ... 'design' 'integer' [] STUDY.currentdesign; 'channels' 'cell' [] {}; 'clusters' 'integer' [] []; 'timerange' 'real' [] STUDY.etc.erpparams.timerange; 'freqrange' 'real' [] STUDY.etc.specparams.freqrange; 'datatype' 'string' { 'erp','spec' } 'erp'; 'rmsubjmean' 'string' { 'on','off' } 'off'; 'singletrials' 'string' { 'on','off' } 'off'; 'componentpol' 'string' { 'on','off' } 'on'; 'component' 'integer' [] []; 'subject' 'string' [] '' }, ... 'std_readerp', 'ignore'); if isstr(opt), error(opt); 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) % scan channels or components % 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 % ----------------------------- dataread = 0; if strcmpi(dtype, 'erp'), eqtf = isequal( STUDY.etc.erpparams.timerange, opt.timerange); else eqtf = isequal(STUDY.etc.specparams.freqrange, opt.freqrange) && ... isequal( STUDY.etc.specparams.subtractsubjectmean, opt.rmsubjmean); end; if strcmpi(opt.singletrials,'off') if isfield(tmpstruct, [ dtype 'data' ]) && ~isempty(getfield(tmpstruct, [ dtype 'data' ])) && eqtf dataread = 1; end; else if isfield(tmpstruct, [ dtype 'datatrials' ]) && eqtf tmpdat = getfield(tmpstruct, [ dtype 'datatrials' ]); range = fastif( strcmpi(dtype, 'erp'), 'erptimes', 'specfreqs'); if ~isempty(opt.channels) && ~isempty(tmpdat) && strcmpi(getfield(tmpstruct, [ dtype 'trialinfo' ]), opt.subject) if size(tmpdat{1},2) == length(getfield(tmpstruct, range)) dataread = 1; end; elseif isempty(opt.channels) && isequal(getfield(tmpstruct, [ dtype 'trialinfo' ]), opt.component) if size(tmpdat{1},2) == length(getfield(tmpstruct, range)) dataread = 1; end; end; end; end; if ~dataread % reserve arrays % -------------- alldata = cell( nc, ng ); setinfoIndices = cell( nc, ng ); tmpind = 1; while(isempty(setinds{tmpind})), tmpind = tmpind+1; end; setinfo = STUDY.design(opt.design).cell; tmpchanlocs = ALLEEG(setinfo(1).dataset(1)).chanlocs; chanlab = { tmpchanlocs.labels }; nonemptyindex = ~cellfun(@isempty, allinds); nonemptyindex = find(nonemptyindex(:)); optGetparams = { 'measure', dtype, 'getparamonly', 'on', 'singletrials', opt.singletrials, 'timelimits', opt.timerange, 'freqlimits', opt.freqrange, 'setinfoinds', 1}; if ~isempty(opt.channels), [ tmp params xvals] = std_readfile(setinfo(setinds{nonemptyindex(1)}(1)), optGetparams{:}, 'channels' , allChangrp(allinds{nonemptyindex(1)}(1))); else [ tmp params xvals] = std_readfile(setinfo(setinds{nonemptyindex(1)}(1)), optGetparams{:}, 'components', allinds{nonemptyindex(1)}(1)); end; % read the data and select channels % --------------------------------- fprintf([ 'Reading ' dtype ' data...' ]); if strcmpi(dtype, 'erp'), opts = { 'timelimits', opt.timerange }; else opts = { 'freqlimits', opt.freqrange }; end; if strcmpi(opt.singletrials, 'on') if strcmpi(params.singletrials, 'off') fprintf('\n'); errordlg2('No single trial data - recompute data files'); datavals = []; return; end; opts = { opts{:} 'singletrials' 'on' }; for c = 1:nc for g = 1:ng if ~isempty(setinds{c,g}) if ~isempty(opt.channels), [alldata{c, g} z z z z setinfoIndices{c, g}] = std_readfile( setinfo(setinds{c,g}(:)), 'measure', dtype, opts{:}, 'channels' , opt.channels(ind), 'setinfoinds', setinds{c,g}(:)); else [alldata{c, g} z z z z setinfoIndices{c, g}] = std_readfile( setinfo(setinds{c,g}(:)), 'measure', dtype, opts{:}, 'components', allinds{c,g}, 'setinfoinds', setinds{c,g}(:)); end; end; end; end; else for c = 1:nc for g = 1:ng if ~isempty(setinds{c,g}) if ~isempty(opt.channels), [alldata{c, g}] = std_readfile( setinfo(setinds{c,g}(:)), 'measure', dtype, opts{:}, 'channels' , opt.channels(ind)); else [alldata{c, g}] = std_readfile( setinfo(setinds{c,g}(:)), 'measure', dtype, opts{:}, 'components', allinds{c,g}); end; end; end; end; end; fprintf('\n'); % inverting component polaritites % ------------------------------- if isempty(opt.channels) && strcmpi(dtype, 'erp') if strcmpi(opt.singletrials, 'on') disp('Warning: component ERP polarity cannot (yet) be inverted for single trials'); else STUDY = std_readtopoclust(STUDY, ALLEEG, finalinds(ind)); if isfield(STUDY.cluster, 'topopol') && ~isempty(STUDY.cluster(finalinds(ind)).topopol) [ tmpstruct tmp1 tmp2 topopolcell] = std_setcomps2cell(STUDY, STUDY.cluster(finalinds(ind)).sets, STUDY.cluster(finalinds(ind)).comps, STUDY.cluster(finalinds(ind)).topopol); disp('Inverting ERP component polarities based on scalp map polarities'); for index = 1:length(alldata(:)) for comps = 1:size(alldata{index},2) alldata{index}(:,comps) = alldata{index}(:,comps)*topopolcell{index}(comps); end; end; else disp('Cluster topographies absent - cannot adjust single component ERP polarities'); end; end; end; % remove mean of each subject across groups and conditions if strcmpi(dtype, 'spec') && strcmpi(opt.rmsubjmean, 'on') && ~isempty(opt.channels) disp('Removing subject''s average spectrum based on pairing settings'); if strcmpi(paired1, 'on') && strcmpi(paired2, 'on') && (nc > 1 || ng > 1) disp('Removing average spectrum for both indep. variables'); meanpowbase = computemeanspectrum(alldata(:), opt.singletrials); alldata = removemeanspectrum(alldata, meanpowbase); elseif strcmpi(paired1, 'on') && ng > 1 disp('Removing average spectrum for first indep. variables (second indep. var. is unpaired)'); for g = 1:ng % ng = number of groups meanpowbase = computemeanspectrum(alldata(:,g), opt.singletrials); alldata(:,g) = removemeanspectrum(alldata(:,g), meanpowbase); end; elseif strcmpi(paired2, 'on') && nc > 1 disp('Removing average spectrum for second indep. variables (first indep. var. is unpaired)'); for c = 1:nc % ng = number of groups meanpowbase = computemeanspectrum(alldata(c,:), opt.singletrials); alldata(c,:) = removemeanspectrum(alldata(c,:), meanpowbase); end; else disp('Not removing average spectrum baseline (both indep. variables are unpaired'); end; end; if strcmpi(opt.singletrials, 'on') tmpstruct = setfield( tmpstruct, [ dtype 'datatrials' ], alldata); tmpstruct = setfield( tmpstruct, [ 'setindstrials' ], setinfoIndices); 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' ], alldata); end; if strcmpi(dtype, 'spec'), tmpstruct.specfreqs = xvals; else tmpstruct.erptimes = xvals; end; % copy results to structure % ------------------------- fieldnames = { [ dtype 'data' ] [ dtype 'freqs' ] [ dtype 'datatrials' ] ... [ dtype 'times' ] [ dtype 'trialinfo' ] 'allinds' 'setinds' 'setindstrials' }; for f = 1:length(fieldnames) if isfield(tmpstruct, fieldnames{f}), tmpdata = getfield(tmpstruct, fieldnames{f}); if ~isempty(opt.channels) STUDY.changrp = setfield(STUDY.changrp, { finalinds(ind) }, fieldnames{f}, tmpdata); else STUDY.cluster = setfield(STUDY.cluster, { finalinds(ind) }, fieldnames{f}, tmpdata); end; end; end; end; end; % if several channels, agregate them % ---------------------------------- allinds = finalinds; if ~isempty(opt.channels) structdat = STUDY.changrp; datavals = cell(nc, ng); if strcmpi( dtype, 'spec'), xvals = getfield(structdat(allinds(1)), [ dtype 'freqs' ]); else xvals = getfield(structdat(allinds(1)), [ dtype 'times' ]); end; for ind = 1:length(datavals(:)) if strcmpi(opt.singletrials, 'on') tmpdat = getfield(structdat(allinds(1)), [ dtype 'datatrials' ]); else tmpdat = getfield(structdat(allinds(1)), [ dtype 'data' ]); end; if ~isempty(tmpdat{ind}) datavals{ind} = zeros([ size(tmpdat{ind}) length(allinds)]); for chan = 1:length(allinds) if strcmpi(opt.singletrials, 'on') tmpdat = getfield(structdat(allinds(chan)), [ dtype 'datatrials' ]); else tmpdat = getfield(structdat(allinds(chan)), [ dtype 'data' ]); end; datavals{ind}(:,:,chan) = tmpdat{ind}; % only works for interpolated data end; datavals{ind} = squeeze(permute(datavals{ind}, [1 3 2])); % time elec subjects end; end; setinds = structdat(allinds(1)).setinds; if ~isempty(opt.subject) if strcmpi(opt.singletrials, 'on') datavals = std_selsubject(datavals, opt.subject, structdat(allinds(1)).setindstrials, { STUDY.design(opt.design).cell.case }, 2); else datavals = std_selsubject(datavals, opt.subject, setinds, { STUDY.design(opt.design).cell.case }, 2); end; end; else if strcmpi(opt.singletrials, 'on') datavals = getfield(STUDY.cluster(allinds(1)), [ dtype 'datatrials' ]); else datavals = getfield(STUDY.cluster(allinds(1)), [ dtype 'data' ]); end; if strcmpi( dtype, 'spec'), xvals = getfield(STUDY.cluster(allinds(1)), [ dtype 'freqs' ]); else xvals = getfield(STUDY.cluster(allinds(1)), [ dtype 'times' ]); end; compinds = STUDY.cluster(allinds(1)).allinds; setinds = STUDY.cluster(allinds(1)).setinds; if ~isempty(opt.component) && length(allinds) == 1 && strcmpi(opt.singletrials,'off') datavals = std_selcomp(STUDY, datavals, allinds, setinds, compinds, opt.component); end; end; % compute mean spectrum % --------------------- function meanpowbase = computemeanspectrum(spectrum, singletrials) try len = length(spectrum(:)); count = 0; for index = 1:len if ~isempty(spectrum{index}) if strcmpi(singletrials, 'on') if count == 0, meanpowbase = mean(spectrum{index},2); else meanpowbase = meanpowbase + mean(spectrum{index},2); end; else if count == 0, meanpowbase = spectrum{index}; else meanpowbase = meanpowbase + spectrum{index}; end; end; count = count+1; end; end; meanpowbase = meanpowbase/count; catch, error([ 'Problem while subtracting mean spectrum.' 10 ... 'Common spectrum 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 mean spectrum % -------------------- function spectrum = removemeanspectrum(spectrum, meanpowbase) for g = 1:size(spectrum,2) % ng = number of groups for c = 1:size(spectrum,1) if ~isempty(spectrum{c,g}) && ~isempty(spectrum{c,g}) if size(spectrum{c,g},2) ~= size(meanpowbase, 2) tmpmeanpowbase = repmat(meanpowbase, [1 size(spectrum{c,g},2)]); else tmpmeanpowbase = meanpowbase; end; spectrum{c,g} = spectrum{c,g} - tmpmeanpowbase; end; end; end;
github
ZijingMao/baselineeegtest-master
std_rmalldatafields.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_rmalldatafields.m
2,441
utf_8
b3f42cacc34383569006753be9c6d82b
% std_rmalldatafields - remove all data fields from STUDY (before saving % it for instance. % % Usage: % STUDY = std_rmalldatafields(STUDY, type); % % Input: % STUDY - EEGLAB study structure % % Optional input: % type - ['chan'|'clust'|'both'] remove from changrp channel location % structure, cluster structure or both. Default is 'both'. % % Ouput: % STUDY - updated EEGLAB study structure % % Author: Arnaud Delorme, CERCO/CNRS, 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_rmalldatafields(STUDY, chanorcomp); if nargin < 1 help std_rmalldatafields; return; end; if nargin < 2 chanorcomp = 'both'; end; fields = { 'erpdata' 'erptimes' 'erpdatatrials' 'erptrialinfo' ... 'specdata' 'specfreqs' 'specdatatrials' 'spectrialinfo' ... 'erspdata' 'erspbase' 'erspfreqs' 'ersptimes' 'erspdatatrials' 'ersptrialinfo' ... 'topo' 'topox' 'topoy' 'topoall' 'topopol' ... 'itcdata' 'itcfreqs' 'itctimes' 'itcdatatrials' 'itctrialinfo' ... 'erpimdata' 'erpimtrials' 'erpimevents' 'erpimtimes' 'erspsubjinds' 'itcsubjinds' 'dipoles' ... 'data' 'datatimes' 'datasortvals' 'datacontinds' 'centroid' }; for ff = 1:length(fields) if strcmpi(chanorcomp, 'data') || strcmpi(chanorcomp, 'both') if isfield(STUDY.changrp, fields{ff}) STUDY.changrp = rmfield(STUDY.changrp, fields{ff} ); end; end; if strcmpi(chanorcomp, 'clust') || strcmpi(chanorcomp, 'both') if isfield(STUDY.cluster, fields{ff}) STUDY.cluster = rmfield(STUDY.cluster, fields{ff} ); end; end; end;
github
ZijingMao/baselineeegtest-master
std_rejectoutliers.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_rejectoutliers.m
5,458
utf_8
5295d178e50afb94a6b71303a3d9aaa9
% std_rejectoutliers() - Commandline function, to reject outlier component(s) from clusters. % Reassign the outlier component(s) to an outlier cluster specific to each cluster. % Usage: % >> [STUDY] = std_rejectoutliers(STUDY, ALLEEG, clusters, th); % 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 (or 'all' clusters), which outliers % will be rejected from. {default:'all'}. % th - [number] a threshold factor to select outliers. How far a component can be from the % cluster centroid (in the cluster std multiples) befor it will be considered as an outlier. % Components that their distance from the cluster centroid are more than this factor % times the cluster std (th *std) will be rejected. {default: 3}. % % Outputs: % STUDY - the input STUDY set structure modified with the components reassignment, % from the cluster to its outlier cluster. % % Example: % >> clusters = [10 15]; th = 2; % >> [STUDY] = std_rejectoutliers(STUDY, ALLEEG, clusters, th); % Reject outlier components (that are more than 2 std from the cluster centroid) from cluster 10 and 15. % % See also pop_clustedit % % Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, July, 2005 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, July 11, 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_rejectoutliers(STUDY, ALLEEG, varargin) cls = 2:length(STUDY.cluster); % all clusters in STUDY th = 3; % The threshold factor - default: 3 if length(varargin) > 1 if isnumeric(varargin{1}) cls = varargin{1}; if isempty(cls) cls = 2:length(STUDY.cluster); end else if isstr(varargin{1}) & strcmpi(varargin{1}, 'all') cls = 2:length(STUDY.cluster); else error('std_prejectoutliers: clusters input takes either specific clusters (numeric vector) or keyword ''all''.'); end end end tmp =[]; 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; clear tmp if length(varargin) == 2 if isnumeric(varargin{2}) th = varargin{2}; else error('std_prejectoutliers: std input must be a numeric value.'); end end % Perform validity checks for k = 1:length(cls) % Cannot reject outlier components if cluster is a 'Notclust' or 'Outlier' cluster 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) warndlg2('Cannot reject outlier components from a Notclust or Outliers cluster'); return; end % Cannot reject outlier components if cluster has children clusters if ~isempty(STUDY.cluster(cls(k)).child) warndlg2('Cannot reject outlier components if cluster has children clusters.'); return; end % If the PCA data matrix of the cluster components is empty (case of merged cluster) if isempty(STUDY.cluster(cls(k)).preclust.preclustdata) % No preclustering information warndlg2('Cannot reject outlier components if cluster was not a part of pre-clustering.'); return; end end % For each of the clusters reject outlier components for k = 1:length(cls) % The PCA data matrix of the cluster components clsPCA = STUDY.cluster(cls(k)).preclust.preclustdata; % The cluster centroid clsCentr = mean(clsPCA,1); % The std of the cluster (based on the distances between all cluster components to the cluster centroid). std_std = std(sum((clsPCA-ones(size(clsPCA,1),1)*clsCentr).^2,2),1); outliers = []; for l = 1:length(STUDY.cluster(cls(k)).comps) compdist = sum((clsPCA(l,:) - clsCentr).^2); % Component distance from cluster centroid if compdist > std_std * th % check if an outlier outliers = [ outliers l]; end end % Move outlier to the outlier cluster if ~isempty(outliers) % reject outliers if exist STUDY = std_moveoutlier(STUDY, ALLEEG,cls(k) , outliers); end end
github
ZijingMao/baselineeegtest-master
std_makedesign.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_makedesign.m
21,528
utf_8
105961a70608d75435cf094b1ca8c1a3
% std_makedesign() - create a new or edit an existing STUDY.design by % selecting specific factors to include in subsequent % 1x2 or 2x2 STUDY measures and statistical computations % for this design. A STUDY may have many factors % (task or stimulus conditions, subject groups, session % numbers, trial types, etc.), but current EEGLAB % STUDY statistics functions apply only to at most two % (paired or unpaired) factors. A STUDY.design may % also be (further) restricted to include only specific % subjects, datasets, or trial types. % Usage: % >> [STUDY] = std_makedesign(STUDY, ALLEEG); % create a default design % >> [STUDY] = std_makedesign(STUDY, ALLEEG, designind, 'key', 'val' ...); % % Inputs: % STUDY - EEGLAB STUDY set % ALLEEG - vector of the EEG datasets included in the STUDY structure % designind - [integer > 0] index (number) of the new STUDY design {default: 1} % % Optional inputs: % 'name' - ['string'] mnemonic design name (ex: 'Targets only') % {default: 'Design d', where d = designind} % 'variable1' - ['string'] - first independent variable or contrast. Must % be a field name in STUDY.datasetinfo or in % STUDY.datasetinfo.trialinfo. Typical choices include (task % or other) 'condition', (subject) 'group', (subject) 'session', % or other condition/group/session factors in STUDY.datasetinfo % -- for example (subject factor) 'gender' or (condition factor) % 'timeofday', etc. If trial type variables are defined in % STUDY.datasetinfo.trialinfo, they may also be used here % -- for example, 'stimcolor'. However, in this case datasets % consist of heterogeneous sets of trials of different types, % so many dataset Plot and Tools menu items may not give % interpretable results and will thus be made unavailable for % selection {default: 'condition'} % 'pairing1' - ['on'|'off'] the nature of the 'variable1' contrast. % For example, to compare two conditions recorded from the % same group of 10 subjects, the 'variable1','condition' design % elements are paired ('on') since each dataset for one % condition has a corresponding dataset from the same subject % in the second condition. If the two conditions were recorded % from different groups of subjects, the variable1 'condition' % would be unpaired ('off') {default: 'on'} % 'values1' - {cell array of 'strings'} - 'variable1' instances to include % in the design. For example, if 'variable1' is 'condition'and % three values for 'condition' (e.g., 'a' , 'b', and 'c') % are listed in STUDY.datasetinfo, then 'indval1', { 'a' 'b' } % will contrast conditions 'a' and 'b', and datasets for % condition 'c' will be ignored. To combine conditions, use % nested '{}'s. For example, to combine conditions 'a' and % 'b' into one condition and contrast it to condition 'c', % specify 'indval1', { { 'a' 'b' } 'c' } {default: all values % of 'variable1' in STUDY.datasetinfo} % 'variable2' - ['string'] - second independent variable name, if any. Typically, % this might refer to ('unpaired') subject group or (typically % 'paired') session number, etc. % 'pairing2' - ['on'|'off'] type of statistics for variable2 % (default: 'on'} % 'values2' - {cell array of 'strings'} - variable2 values to include in the % design {default: all}. Here, 'var[12]' must be field names % in STUDY.datasetinfo or STUDY.datasetinfo.trialinfo. % 'datselect' - {cell array} select specific datasets and/or trials: 'datselect', % {'var1' {'vals'} 'var2' {'vas'}}. Selected datasets must % meet all the specified conditions. For example, 'datselect', % { 'condition' { 'a' 'b' } 'group' { 'g1' 'g2' } } will % select only datasets from conditions 'a' OR 'b' AND only % subjects in groups 'g1' OR 'g2'. If 'subjselect' is also % specified, only datasets meeting both criteria are included. % 'variable1' and 'variable2' will only consider % the values after they have passed through 'datselect' and % 'subjselect'. For instance, if conditions { 'a' 'b' 'c' } % exist and conditions 'a' is removed by 'datselect', the only % two conditions that will be considered are 'b' and 'c' % (which is then equivalent to using 'variable1vals' to specify % values for the 'condition' factor. Calls function % std_selectdataset() {default: select all datasets} % 'subjselect' - {cell array} subject codes of specific subjects to include % in the STUDY design {default: all subjects in the specified % conditions, groups, etc.} If 'datselect' is also specified, % only datasets meeting both criteria are included. % 'rmfiles' - ['on'|'off'] remove from the STUDY all data measure files % NOT included in this design. Selecting this option will % remove all the old measure files associated with the previous % definition of this design. {default: 'off'} % 'filepath' - [string] file path for saving precomputed files. Default is % empty meaning it is in the same folder as the data. % 'delfiles' - ['on'|'off'|'limited'] delete data files % associated with the design specified as parameter. 'on' % delete all data files related to the design. 'limited' % deletes all data files contained in the design. 'limited' % will not delete data files from other STUDY using the same % files. Default is 'off'. % % Output: % STUDY - The input STUDY with a new design added and designated % as the current design. % % Examples: % STUDY = std_makedesign(STUDY, ALLEEG); % make default design % % % create design with 1 independent variable equal to 'condition' % STUDY = std_makedesign(STUDY, ALLEEG, 2, 'variable1', 'condition'); % % % create design with 1 independent variable equal to 'condition' % % but only consider the sub-condition 'stim1' and 'stim2' - of course % % such conditions must be present in the STUDY % STUDY = std_makedesign(STUDY, ALLEEG, 2, 'variable1', 'condition', ... % 'values1', { 'stim1' 'stim2' }); % % % create design and only include subject 's1' and 's2' % STUDY = std_makedesign(STUDY, ALLEEG, 2, 'variable1', 'condition', ... % 'subjselect', { 's1' 's2' }); % % 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 com] = std_makedesign(STUDY, ALLEEG, designind, varargin) if nargin < 2 help std_makedesign; return; end; if nargin < 3 designind = 1; end; defdes.name = sprintf('STUDY.design %d', designind); defdes.cases.label = 'subject'; defdes.cases.value = {}; defdes.variable(1).label = 'condition'; defdes.variable(2).label = 'group'; defdes.variable(1).value = {}; defdes.variable(2).value = {}; defdes.variable(1).pairing = 'on'; defdes.variable(2).pairing = 'on'; defdes.filepath = ''; defdes.include = {}; orivarargin = varargin; if ~isempty(varargin) && isstruct(varargin{1}) defdes = varargin{1}; varargin(1) = []; end; if isempty(defdes.filepath), defdes.filepath = ''; end; opt = finputcheck(varargin, {'variable1' 'string' [] defdes.variable(1).label; 'variable2' 'string' [] defdes.variable(2).label; 'values1' {'real','cell' } [] defdes.variable(1).value; 'values2' {'real','cell' } [] defdes.variable(2).value; 'pairing1' 'string' [] defdes.variable(1).pairing; 'pairing2' 'string' [] defdes.variable(2).pairing; 'name' 'string' {} defdes.name; 'filepath' 'string' {} defdes.filepath; 'datselect' 'cell' {} defdes.include; 'dataselect' 'cell' {} {}; 'subjselect' 'cell' {} defdes.cases.value; 'delfiles' 'string' { 'on','off', 'limited' } 'off'; 'verbose' 'string' { 'on','off' } 'on'; 'defaultdesign' 'string' { 'on','off','forceoff'} fastif(nargin < 3, 'on', 'off') }, ... 'std_makedesign'); if isstr(opt), error(opt); end; if ~isempty(opt.dataselect), opt.datselect = opt.dataselect; end; if strcmpi(opt.variable1, 'none'), opt.variable1 = ''; end; if strcmpi(opt.variable2, 'none'), opt.variable2 = ''; end; %if iscell(opt.values1), for i = 1:length(opt.values1), if iscell(opt.values1{i}), opt.values1{i} = cell2str(opt.values1{i}); end; end; end; %if iscell(opt.values2), for i = 1:length(opt.values2), if iscell(opt.values2{i}), opt.values2{i} = cell2str(opt.values2{i}); end; end; end; % build command list for history % ------------------------------ listcom = { 'variable1' opt.variable1 'variable2' opt.variable2 'name' opt.name 'pairing1' opt.pairing1 'pairing2' opt.pairing2 'delfiles' opt.delfiles 'defaultdesign' opt.defaultdesign }; if ~isempty(opt.values1), listcom = { listcom{:} 'values1' opt.values1 }; end; if ~isempty(opt.values2), listcom = { listcom{:} 'values2' opt.values2 }; end; if ~isempty(opt.subjselect), listcom = { listcom{:} 'subjselect' opt.subjselect }; end; if ~isempty(opt.datselect), listcom = { listcom{:} 'datselect' opt.datselect }; end; if ~isempty(opt.filepath), listcom = { listcom{:} 'filepath' opt.filepath }; end; if ~isempty(opt.datselect), listcom = { listcom{:} 'datselect' opt.datselect }; end; % select specific subjects % ------------------------ datsubjects = { STUDY.datasetinfo.subject }; if ~isempty(opt.subjselect) allsubjects = opt.subjselect; else allsubjects = unique_bc( datsubjects ); end; % delete design files % --------------------- if strcmpi(opt.delfiles, 'on') myfprintf(opt.verbose, 'Deleting all files pertaining to design %d\n', designind); for index = 1:length(ALLEEG) files = fullfile(ALLEEG(index).filepath, sprintf(opt.verbose, 'design%d*.*', designind)); files = dir(files); for indf = 1:length(files) delete(fullfile(ALLEEG(index).filepath, files(indf).name)); end; end; elseif strcmpi(opt.delfiles, 'limited') myfprintf(opt.verbose, 'Deleting all files for STUDY design %d\n', designind); for index = 1:length(STUDY.design(designind).cell) filedir = [ STUDY.design(designind).cell(index).filebase '.dat*' ]; filepath = fileparts(filedir); files = dir(filedir); for indf = 1:length(files) %disp(fullfile(filepath, files(indf).name)); delete(fullfile(filepath, files(indf).name)); end; end; for index = 1:length(STUDY.design(designind).cell) filedir = [ STUDY.design(designind).cell(index).filebase '.ica*' ]; filepath = fileparts(filedir); files = dir(filedir); for indf = 1:length(files) %disp(fullfile(filepath, files(indf).name)); delete(fullfile(filepath, files(indf).name)); end; end; end; % check inputs % ------------ [indvars indvarvals ] = std_getindvar(STUDY); if isfield(STUDY.datasetinfo, 'trialinfo') alltrialinfo = { STUDY.datasetinfo.trialinfo }; dattrialselect = cellfun(@(x)([1:length(x)]), alltrialinfo, 'uniformoutput', false); else alltrialinfo = cell(length(STUDY.datasetinfo)); for i=1:length(ALLEEG), dattrialselect{i} = [1:ALLEEG(i).trials]; end; end; % get values for each independent variable % ---------------------------------------- m1 = strmatch(opt.variable1, indvars, 'exact'); if isempty(m1), opt.variable1 = ''; end; m2 = strmatch(opt.variable2, indvars, 'exact'); if isempty(m2), opt.variable2 = ''; end; if isempty(opt.values1) && ~isempty(opt.variable1), opt.values1 = indvarvals{m1}; end; if isempty(opt.values2) && ~isempty(opt.variable2), opt.values2 = indvarvals{m2}; end; if isempty(opt.variable1), opt.values1 = { '' }; end; if isempty(opt.variable2), opt.values2 = { '' }; end; % preselect data % -------------- datselect = [1:length(STUDY.datasetinfo)]; if ~isempty(opt.datselect) myfprintf(opt.verbose, 'Data preselection for STUDY design\n'); for ind = 1:2:length(opt.datselect) [ dattmp dattrialstmp ] = std_selectdataset( STUDY, ALLEEG, opt.datselect{ind}, opt.datselect{ind+1}); datselect = intersect_bc(datselect, dattmp); dattrialselect = intersectcell(dattrialselect, dattrialstmp); end; end; datselect = intersect_bc(datselect, strmatchmult(allsubjects, datsubjects)); % get the dataset and trials for each of the ind. variable % -------------------------------------------------------- ns = length(allsubjects); nf1 = max(1,length(opt.values1)); nf2 = max(1,length(opt.values2)); myfprintf(opt.verbose, 'Building STUDY design\n'); for n1 = 1:nf1, [ dats1{n1} dattrials1{n1} ] = std_selectdataset( STUDY, ALLEEG, opt.variable1, opt.values1{n1}, fastif(strcmpi(opt.verbose, 'on'), 'verbose', 'silent')); end; for n2 = 1:nf2, [ dats2{n2} dattrials2{n2} ] = std_selectdataset( STUDY, ALLEEG, opt.variable2, opt.values2{n2}, fastif(strcmpi(opt.verbose, 'on'), 'verbose', 'silent')); end; % detect files from old format % ---------------------------- if ~strcmpi(opt.defaultdesign, 'forceoff') && isempty(opt.filepath) if designind == 1 if strcmpi(opt.defaultdesign, 'off') if isfield(STUDY, 'design') && ( ~isfield(STUDY.design, 'cell') || ~isfield(STUDY.design(1).cell, 'filebase') ) opt.defaultdesign = 'on'; end; end; if isempty(dir(fullfile(ALLEEG(1).filepath, [ ALLEEG(1).filename(1:end-4) '.dat*' ]))) && ... isempty(dir(fullfile(ALLEEG(1).filepath, [ ALLEEG(1).filename(1:end-4) '.ica*' ]))) opt.defaultdesign = 'off'; end; else opt.defaultdesign = 'off'; end; else opt.defaultdesign = 'off'; end; % scan subjects and conditions % ---------------------------- count = 1; for n1 = 1:nf1 for n2 = 1:nf2 % create design for this set of conditions and subject % ---------------------------------------------------- datasets = intersect_bc(intersect(dats1{n1}, dats2{n2}), datselect); if ~isempty(datasets) subjects = unique_bc(datsubjects(datasets)); for s = 1:length(subjects) datsubj = datasets(strmatch(subjects{s}, datsubjects(datasets), 'exact')); des.cell(count).dataset = datsubj; des.cell(count).trials = intersectcell(dattrialselect(datsubj), dattrials1{n1}(datsubj), dattrials2{n2}(datsubj)); des.cell(count).value = { opt.values1{n1} opt.values2{n2} }; des.cell(count).case = subjects{s}; defaultFile = fullfile(ALLEEG(datsubj(1)).filepath, ALLEEG(datsubj(1)).filename(1:end-4)); dirres1 = dir( [ defaultFile '.dat*' ] ); dirres2 = dir( [ defaultFile '.ica*' ] ); if strcmpi(opt.defaultdesign, 'on') && (~isempty(dirres1) || ~isempty(dirres2)) && isempty(opt.filepath) des.cell(count).filebase = defaultFile; else if isempty(rmblk(opt.values1{n1})), txtval = rmblk(opt.values2{n2}); elseif isempty(rmblk(opt.values2{n2})) txtval = rmblk(opt.values1{n1}); else txtval = [ rmblk(opt.values1{n1}) '_' rmblk(opt.values2{n2}) ]; end; if ~isempty(txtval), txtval = [ '_' txtval ]; end; if ~isempty(subjects{s}), txtval = [ '_' rmblk(subjects{s}) txtval ]; end; if isempty(opt.filepath), tmpfilepath = ALLEEG(datsubj(1)).filepath; else tmpfilepath = opt.filepath; end; des.cell(count).filebase = fullfile(tmpfilepath, [ 'design' int2str(designind) txtval ] ); des.cell(count).filebase = checkfilelength(des.cell(count).filebase); end; count = count+1; end; end; end; end; % create other fields for the design % ---------------------------------- if exist('des') ~= 1 error( [ 'One of your design is empty. This could be because the datasets/subjects/trials' 10 ... 'you have selected do not contain any of the selected independent variables values.' 10 ... 'Check your data and datasets carefully for any missing information.' ]); else % check for duplicate entries in filebase % --------------------------------------- if length( { des.cell.filebase } ) > length(unique({ des.cell.filebase })) if ~isempty(findstr('design_', des.cell(1).filebase)) error('There is a problem with your STUDY, contact EEGLAB support'); else disp('Duplicate entry detected in new design, reinitializing design with new file names'); if length(dbstack) > 10 error('There is probably an issue with the folder names - move the files and try again'); end; [STUDY com] = std_makedesign(STUDY, ALLEEG, designind, orivarargin{:}, 'defaultdesign', 'forceoff'); return; end end; %allval1 = unique_bc(cellfun(@(x)x{1}, { des.cell.value }, 'uniformoutput', false)); %allval2 = unique_bc(cellfun(@(x)x{2}, { des.cell.value }, 'uniformoutput', false)); des.name = opt.name; des.filepath = opt.filepath; des.variable(1).label = opt.variable1; des.variable(2).label = opt.variable2; des.variable(1).pairing = opt.pairing1; des.variable(2).pairing = opt.pairing2; des.variable(1).value = opt.values1; des.variable(2).value = opt.values2; des.include = opt.datselect; des.cases.label = 'subject'; des.cases.value = unique_bc( { des.cell.case }); end; fieldorder = { 'name' 'filepath' 'variable' 'cases' 'include' 'cell' }; des = orderfields(des, fieldorder); try, STUDY.design = orderfields(STUDY.design, fieldorder); catch, STUDY.design = []; end; if ~isfield(STUDY, 'design') || isempty(STUDY.design) STUDY.design = des; else STUDY.design(designind) = des; % fill STUDY.design end; % select the new design in the STUDY output % ----------------------------------------- STUDY.currentdesign = designind; STUDY = std_selectdesign(STUDY, ALLEEG, designind); % build output command % -------------------- com = sprintf('STUDY = std_makedesign(STUDY, ALLEEG, %d, %s);', designind, vararg2str( listcom ) ); % --------------------------------------------------- % return intersection of cell arrays % ---------------------------------- function res = intersectcell(a, b, c); if nargin > 2 res = intersectcell(a, intersectcell(b, c)); else for index = 1:length(a) res{index} = intersect_bc(a{index}, b{index}); end; end; % perform multi strmatch % ---------------------- function res = strmatchmult(a, b); res = []; for index = 1:length(a) res = [ res strmatch(a{index}, b, 'exact')' ]; end; % remove blanks % ------------- function res = rmblk(a); if iscell(a), a = cell2str(a); end; if ~isstr(a), a = num2str(a); end; res = a; res(find(res == ' ')) = '_'; res(find(res == '\')) = '_'; res(find(res == '/')) = '_'; res(find(res == ':')) = '_'; res(find(res == ';')) = '_'; res(find(res == '"')) = '_'; function strval = cell2str(vals); strval = vals{1}; for ind = 2:length(vals) strval = [ strval ' - ' vals{ind} ]; end; function tmpfile = checkfilelength(tmpfile); if length(tmpfile) > 120, tmpfile = tmpfile(1:120); end; function myfprintf(verbose, varargin); if strcmpi(verbose, 'on'), fprintf(varargin{:}); end;
github
ZijingMao/baselineeegtest-master
std_readspec.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readspec.m
3,551
utf_8
0315bf04416f115f6af90007ab60704e
% std_readspec() - load spectrum measures for data channels or % for all components of a specified cluster. % Called by plotting functions % std_envtopo(), std_erpplot(), std_erspplot(), ... % Usage: % >> [STUDY, specdata, allfreqs, setinds, cinds] = ... % std_readspec(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'. % 'subject' - [string] select a specific subject {default:all} % 'component' - [integer] select a specific component in a cluster % {default:all} % % Spectrum specific inputs: % 'freqrange' - [min max] frequency range {default: whole measure range} % 'rmsubjmean' - ['on'|'off'] remove mean subject spectrum from every % channel spectrum, making them easier to compare % { default: 'off' } % Output: % STUDY - updated studyset structure % specdata - [cell array] spectral data (the cell array size is % condition x groups) % freqs - [float array] array of frequencies % setinds - [cell array] datasets indices % cinds - [cell array] channel or component indices % % Example: % std_precomp(STUDY, ALLEEG, { ALLEEG(1).chanlocs.labels }, 'spec', 'on'); % [spec freqs] = std_readspec(STUDY, ALLEEG, 'channels', { ALLEEG(1).chanlocs(1).labels }); % % 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, specdata, allfreqs] = std_readspec(STUDY, ALLEEG, varargin) if nargin < 2 help std_readspec; return; end if ~isstruct(ALLEEG) % old calling format % old calling format % ------------------ EEG = STUDY(ALLEEG); filename = fullfile(EEG.filepath, EEG.filename(1:end-4)); comporchan = varargin{1}; options = {'measure', 'spec'}; if length(varargin) > 1, options = { options{:} 'freqlimits', varargin{2} }; end; if comporchan(1) > 0 [datavals tmp xvals] = std_readfile(filename, 'components',comporchan, options{:}); else [datavals tmp xvals] = std_readfile(filename, 'channels', comporchan, options{:}); end; STUDY = datavals'; specdata = xvals; end; [STUDY, specdata, allfreqs] = std_readerp(STUDY, ALLEEG, 'datatype', 'spec', varargin{:});
github
ZijingMao/baselineeegtest-master
pop_erpparams.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_erpparams.m
9,909
utf_8
e31b70a349e7ce0295ce8ead41d98d8e
% pop_erpparams() - Set plotting and statistics parameters for cluster ERP % plotting % Usage: % >> STUDY = pop_erpparams(STUDY, 'key', 'val'); % % Inputs: % STUDY - EEGLAB STUDY set % % Input: % 'topotime' - [real] Plot ERP scalp maps at one specific latency (ms). % A latency range [min max] may also be defined (the % ERP is then averaged over the interval) {default: []} % 'filter' - [real] low pass filter the ERP curves at a given % frequency threshold. Default is no filtering. % 'timerange' - [min max] ERP plotting latency range in ms. % {default: the whole epoch} % 'ylim' - [min max] ERP limits in microvolts {default: from data} % 'plotgroups' - ['together'|'apart'] 'together' -> plot subject groups % on the same axis in different colors, else ('apart') % on different axes. {default: 'apart'} % 'plotconditions' - ['together'|'apart'] 'together' -> plot conditions % on the same axis in different colors, else ('apart') % on different axes. Note: Keywords 'plotgroups' and % 'plotconditions' may not both be set to 'together'. % {default: 'together'} % 'averagechan' - ['on'|'off'] average data channels when several are % selected. % % See also: std_erpplot() % % Authors: Arnaud Delorme, CERCO, CNRS, 2006- % Copyright (C) Arnaud Delorme, 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 [ STUDY, com ] = pop_erpparams(STUDY, varargin); STUDY = default_params(STUDY); TMPSTUDY = STUDY; com = ''; if isempty(varargin) enablecond = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off'); enablegroup = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off'); plotconditions = fastif(strcmpi(STUDY.etc.erpparams.plotconditions, 'together'), 1, 0); plotgroups = fastif(strcmpi(STUDY.etc.erpparams.plotgroups,'together'), 1, 0); radio_averagechan = fastif(strcmpi(STUDY.etc.erpparams.averagechan,'on'), 1, 0); radio_scalptopo = fastif(isempty(STUDY.etc.erpparams.topotime), 0, 1); if radio_scalptopo, radio_averagechan = 0; end; if radio_scalptopo+radio_averagechan == 0, radio_scalparray = 1; else radio_scalparray = 0; end; cb_radio = [ 'set(findobj(gcbf, ''userdata'', ''radio''), ''value'', 0);' ... 'set(gcbo, ''value'', 1);' ... 'set(findobj(gcbf, ''tag'', ''topotime''), ''string'', '''');' ]; cb_edit = [ 'set(findobj(gcbf, ''userdata'', ''radio''), ''value'', 0);' ... 'set(findobj(gcbf, ''tag'', ''scalptopotext''), ''value'', 1);' ]; uilist = { ... {'style' 'text' 'string' 'ERP plotting options' 'fontweight' 'bold' 'fontsize', 12} ... {} {'style' 'text' 'string' 'Time limits (ms) [low high]' } ... {'style' 'edit' 'string' num2str(STUDY.etc.erpparams.timerange) 'tag' 'timerange' } ... {} {'style' 'text' 'string' 'Plot limits [low high]'} ... {'style' 'edit' 'string' num2str(STUDY.etc.erpparams.ylim) 'tag' 'ylim' } ... {} {'style' 'text' 'string' 'Lowpass plotted data [Hz]' } ... {'style' 'edit' 'string' num2str(STUDY.etc.erpparams.filter) 'tag' 'filter' } ... {} ... {'style' 'text' 'string' 'ERP plotting format' 'fontweight' 'bold' 'fontsize', 12} ... {} {'style' 'checkbox' 'string' 'Plot first variable on the same panel' 'value' plotconditions 'enable' enablecond 'tag' 'plotconditions' } ... {} {'style' 'checkbox' 'string' 'Plot second variable on the same panel' 'value' plotgroups 'enable' enablegroup 'tag' 'plotgroups' } ... {} ... {'style' 'text' 'string' 'Multiple channels selection' 'fontweight' 'bold' 'tag', 'spec' 'fontsize', 12} ... {} {'style' 'radio' 'string' 'Plot channels in scalp array' 'value' radio_scalparray 'tag' 'scalparray' 'userdata' 'radio' 'callback' cb_radio} { } ... {} {'style' 'radio' 'string' 'Plot topography at time (ms)' 'value' radio_scalptopo 'tag' 'scalptopotext' 'userdata' 'radio' 'callback' cb_radio} ... {'style' 'edit' 'string' num2str(STUDY.etc.erpparams.topotime) 'tag' 'topotime' 'callback' cb_edit } ... {} {'style' 'radio' 'string' 'Average selected channels' 'value' radio_averagechan 'tag' 'averagechan' 'userdata' 'radio' 'callback' cb_radio} { } }; cbline = [0.07 1.1]; otherline = [ 0.07 0.6 .3]; chanline = [ 0.07 0.8 0.3]; geometry = { 1 otherline otherline otherline 1 1 cbline cbline 1 1 chanline chanline chanline }; geomvert = [1.2 1 1 1 0.5 1.2 1 1 0.5 1.2 1 1 1 ]; % component plotting % ------------------ if isnan(STUDY.etc.erpparams.topotime) geometry(end-4:end) = []; geomvert(end-4:end) = []; uilist(end-10:end) = []; end; [out_param userdat tmp res] = inputgui( 'geometry' , geometry, 'uilist', uilist, 'geomvert', geomvert, ... 'title', 'ERP plotting options -- pop_erpparams()'); if isempty(res), return; end; % decode inputs % ------------- %if res.plotgroups & res.plotconditions, warndlg2('Both conditions and group cannot be plotted on the same panel'); return; end; if res.plotgroups, res.plotgroups = 'together'; else res.plotgroups = 'apart'; end; if res.plotconditions , res.plotconditions = 'together'; else res.plotconditions = 'apart'; end; if ~isfield(res, 'topotime'), res.topotime = STUDY.etc.erpparams.topotime; else res.topotime = str2num( res.topotime ); end; res.timerange = str2num( res.timerange ); res.ylim = str2num( res.ylim ); res.filter = str2num( res.filter ); if ~isfield(res, 'averagechan'), res.averagechan = STUDY.etc.erpparams.averagechan; elseif res.averagechan, res.averagechan = 'on'; else res.averagechan = 'off'; end; % build command call % ------------------ options = {}; if ~strcmpi( char(res.filter), char(STUDY.etc.erpparams.filter)), options = { options{:} 'filter' res.filter }; end; if ~strcmpi( res.plotgroups, STUDY.etc.erpparams.plotgroups), options = { options{:} 'plotgroups' res.plotgroups }; end; if ~strcmpi( res.plotconditions , STUDY.etc.erpparams.plotconditions ), options = { options{:} 'plotconditions' res.plotconditions }; end; if ~isequal(res.ylim , STUDY.etc.erpparams.ylim), options = { options{:} 'ylim' res.ylim }; end; if ~isequal(res.timerange , STUDY.etc.erpparams.timerange) , options = { options{:} 'timerange' res.timerange }; end; if ~isequal(res.averagechan, STUDY.etc.erpparams.averagechan), options = { options{:} 'averagechan' res.averagechan }; end; if (all(isnan(res.topotime)) & all(~isnan(STUDY.etc.erpparams.topotime))) | ... (all(~isnan(res.topotime)) & all(isnan(STUDY.etc.erpparams.topotime))) | ... (all(~isnan(res.topotime)) & ~isequal(res.topotime, STUDY.etc.erpparams.topotime)) options = { options{:} 'topotime' res.topotime }; end; if ~isempty(options) STUDY = pop_erpparams(STUDY, options{:}); com = sprintf('STUDY = pop_erpparams(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.erpparams), 'exact')) STUDY.etc.erpparams = setfield(STUDY.etc.erpparams, varargin{index}, varargin{index+1}); end; end; end; end; % scan clusters and channels to remove erpdata info if timerange has changed % ---------------------------------------------------------- if ~isequal(STUDY.etc.erpparams.timerange, TMPSTUDY.etc.erpparams.timerange) rmfields = { 'erpdata' 'erptimes' }; for iField = 1:length(rmfields) if isfield(STUDY.cluster, rmfields{iField}) STUDY.cluster = rmfield(STUDY.cluster, rmfields{iField}); end; if isfield(STUDY.changrp, rmfields{iField}) STUDY.changrp = rmfield(STUDY.changrp, rmfields{iField}); end; end; end; function STUDY = default_params(STUDY) if ~isfield(STUDY.etc, 'erpparams'), STUDY.etc.erpparams = []; end; if ~isfield(STUDY.etc.erpparams, 'topotime'), STUDY.etc.erpparams.topotime = []; end; if ~isfield(STUDY.etc.erpparams, 'filter'), STUDY.etc.erpparams.filter = []; end; if ~isfield(STUDY.etc.erpparams, 'timerange'), STUDY.etc.erpparams.timerange = []; end; if ~isfield(STUDY.etc.erpparams, 'ylim' ), STUDY.etc.erpparams.ylim = []; end; if ~isfield(STUDY.etc.erpparams, 'plotgroups') , STUDY.etc.erpparams.plotgroups = 'apart'; end; if ~isfield(STUDY.etc.erpparams, 'plotconditions') , STUDY.etc.erpparams.plotconditions = 'apart'; end; if ~isfield(STUDY.etc.erpparams, 'averagechan') , STUDY.etc.erpparams.averagechan = 'off'; end;
github
ZijingMao/baselineeegtest-master
std_selectdesign.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_selectdesign.m
1,989
utf_8
b3048a1a88ea00503584ee7c9c6d418b
% std_selectdesign() - select an existing STUDY design. % Use std_makedesign() to add a new STUDY.design. % % Usage: % >> [STUDY] = std_selectdesign(STUDY, ALLEEG, designind); % % Inputs: % STUDY - EEGLAB STUDY structure % STUDY - EEGLAB ALLEEG structure % designind - desired (existing) design index % % Outputs: % STUDY - EEGLAB STUDY structure with currentdesign set to the input design index. % % 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_selectdesign(STUDY, ALLEEG, designind); if nargin < 3 help std_selectdesign; return; end; if designind < 1 || designind > length(STUDY.design) || isempty(STUDY.design(designind).name) disp('Cannot select an empty STUDY.design'); return; end; STUDY.currentdesign = designind; STUDY = std_rmalldatafields( STUDY ); % remake setinds and allinds % -------------------------- STUDY = std_changroup(STUDY, ALLEEG, [], 'on'); % with interpolation HAVE TO FIX THAT % update the component indices % ---------------------------- STUDY.cluster(1).setinds = {}; STUDY.cluster(1).allinds = {}; for index = 1:length(STUDY.cluster) STUDY.cluster(index) = std_setcomps2cell(STUDY, index); end;
github
ZijingMao/baselineeegtest-master
std_getdataset.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_getdataset.m
7,391
utf_8
30fe56beb0eae5a9d470402fc8ae35a2
% std_getdataset() - Constructs and returns EEG dataset from STUDY design. % % Usage: % >> EEG = std_getdataset(STUDY, ALLEEG, 'key', 'val', ...); % % Inputs: % STUDY - EEGLAB STUDY set % ALLEEG - vector of the EEG datasets included in the STUDY structure % % Optional inputs: % 'design' - [numeric vector] STUDY design index. Default is to use % the current design. % '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. % 'rmclust' - [integer array] which cluster(s) to remove from the data % Default is none. % 'interp' - [struct] channel location structure containing electrode % to interpolate ((this entry is ignored when plotting % components). Default is no interpolation. % 'cell' - [integer] index of the STUDY design cell to convert to % an EEG dataset. Default is the first cell. % 'onecomppercluster' - ['on'|'off'] when 'on' enforces one component per % cluster. Default is 'off'. % 'interpcomponent' - ['on'|'off'] when 'on' interpolating component % scalp maps. Default is 'off'. % 'cluster' - [integer] which cluster(s). When this option is being % used, only the component contained in the selected % clusters are being loaded in the dataset. % 'checkonly' - ['on'|'off'] use in conjunction with the option above. % When 'on', no dataset is returned. Default is 'off'. % % Outputs: % EEG - EEG dataset structure corresponding to the selected % STUDY design cell (element) % complist - list of components selected % % Example to build the dataset corresponding to the first cell of the first % design: % EEG = std_getdataset(STUDY, ALLEEG, 'design', 1, 'cell', 1); % % Example to check that all datasets in the design have exactly one % component per cluster for cluster 2, 3, 4 and 5. % std_getdataset(STUDY, ALLEEG, 'design', 1, 'cell', % [1:length(STUDY.design(1).cell)], 'cluster', [2 3 4 5], 'checkonly', 'on'); % % Authors: Arnaud Delorme, SCCN, INC, UCSD, January, 2012 % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, October 12, 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 [EEGOUT listcomp rmlistcomp] = std_getdataset(STUDY, ALLEEG, varargin); if nargin < 2 help std_getdataset; return; end; opt = finputcheck( varargin, { 'design' 'integer' [] STUDY.currentdesign; 'interp' 'struct' { } struct([]); 'rmcomps' 'integer' [] []; 'cluster' 'integer' [] []; 'rmclust' 'integer' [] []; 'onecomppercluster' 'string' {'on' 'off'} 'off'; 'interpcomponent' 'string' {'on' 'off'} 'off'; 'checkonly' 'string' {'on' 'off'} 'off'; 'cell' 'integer' [] 1 }, 'std_getdataset'); % 'mode' 'string' { 'channels' 'components' } 'channels'; if isstr(opt), error(opt); end; if length(opt.cell) > 1 % recursive call if more than one dataset % --------------------------------------- indcell = strmatch('cell', varargin(1:2:end)); for index = 1:length(opt.cell) varargin{2*indcell} = index; EEGOUT(index) = std_getdataset(STUDY, ALLEEG, varargin{:}); end; else mycell = STUDY.design(opt.design).cell(opt.cell); % find components in non-artifactual cluster if ~isempty(opt.cluster) listcomp = []; for index = 1:length(opt.cluster) clsset = STUDY.cluster(opt.cluster(index)).sets; clscomp = STUDY.cluster(opt.cluster(index)).comps; [indrow indcomp] = find(clsset == mycell.dataset(1)); if length(indcomp) ~= 1 && strcmpi(opt.onecomppercluster, 'on') error(sprintf('Dataset %d must have exactly 1 components in cluster %d', mycell.dataset(1), opt.cluster(index))); end; listcomp = [listcomp clscomp(indcomp')]; end; end; % find components in artifactual clusters if ~isempty(opt.rmclust) rmlistcomp = []; for index = 1:length(opt.rmclust) clsset = STUDY.cluster(opt.rmclust(index)).sets; clscomp = STUDY.cluster(opt.rmclust(index)).comps; [indrow indcomp] = find(clsset == mycell.dataset(1)); rmlistcomp = [rmlistcomp clscomp(indcomp')]; end; if ~isempty(opt.rmcomps) disp('Both ''rmclust'' and ''rmcomps'' are being set. Artifact components will be merged'); end; opt.rmcomps = [ opt.rmcomps rmlistcomp ]; end; rmlistcomp = opt.rmcomps; if strcmpi(opt.checkonly, 'on'), EEGOUT = 0; return; end; % get data EEG = ALLEEG(mycell.dataset); EEGOUT = EEG(1); EEGOUT.data = eeg_getdatact(EEG, 'channel', [], 'trialindices', mycell.trials, 'rmcomps', opt.rmcomps, 'interp', opt.interp); EEGOUT.trials = size(EEGOUT.data,3); EEGOUT.nbchan = size(EEGOUT.data,1); if ~isempty(opt.interp) EEGOUT.chanlocs = opt.interp; end; EEGOUT.event = []; EEGOUT.epoch = []; EEGOUT.filename = mycell.filebase; EEGOUT.condition = mycell.value{1}; EEGOUT.group = mycell.value{2}; EEGOUT.subject = mycell.case; if ~isempty(opt.cluster) if ~isempty(opt.interp) && strcmpi(opt.interpcomponent, 'on') TMPEEG = EEGOUT; TMPEEG.chanlocs = EEG(1).chanlocs; TMPEEG.data = EEG(1).icawinv; TMPEEG.nbchan = size(TMPEEG.data,1); TMPEEG.pnts = size(TMPEEG.data,2); TMPEEG.trials = 1; TMPEEG = eeg_interp(TMPEEG, opt.interp, 'spherical'); EEGOUT.icawinv = TMPEEG.data(:, listcomp); else EEGOUT.icawinv = EEGOUT.icawinv(:, listcomp); end; EEGOUT.icaact = eeg_getdatact(EEG, 'component', listcomp, 'trialindices', mycell.trials ); EEGOUT.icaweights = EEGOUT.icaweights(listcomp,:); EEGOUT.etc.clustid = { STUDY.cluster(opt.cluster).name }; % name of each cluster EEGOUT.etc.clustcmpid = listcomp; % index of each component in original ICA matrix else EEGOUT = eeg_checkset(EEGOUT); end; end;
github
ZijingMao/baselineeegtest-master
std_readpac.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readpac.m
9,664
utf_8
969615c6dc80b8442761d8a892ebdef1
% std_readpac() - read phase-amplitude correlation % % Usage: % >> [STUDY, clustinfo] = std_readpac(STUDY, ALLEEG); % >> [STUDY, clustinfo] = std_readpac(STUDY, ALLEEG, ... % 'key', 'val'); % Inputs: % STUDY - studyset structure containing some or all files in ALLEEG % ALLEEG - vector of loaded EEG datasets % % Optional inputs: % 'channels' - [cell] list of channels to import {default: all} % 'clusters' - [integer] list of clusters to import {[]|default: all but % the parent cluster (1) and any 'NotClust' clusters} % 'freqrange' - [min max] frequency range {default: whole measure range} % 'timerange' - [min max] time range {default: whole measure epoch} % % Output: % STUDY - (possibly) updated STUDY structure % clustinfo - structure of specified cluster information. % % Author: Arnaud Delorme, CERCO, 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, clustinfo] = std_readpac(STUDY, ALLEEG, varargin); if nargin < 2 help std_readpac; return; end [opt moreopts] = finputcheck( varargin, { ... 'condition' 'cell' [] {}; 'channels1' 'cell' [] {}; 'clusters1' 'integer' [] []; 'channels2' 'cell' [] {}; 'clusters2' 'integer' [] []; 'onepersubj' 'string' { 'on','off' } 'off'; 'forceread' 'string' { 'on','off' } 'off'; 'recompute' 'string' { 'on','off' } 'off'; 'freqrange' 'real' [] []; 'timerange' 'real' [] [] }, ... 'std_readpac', 'ignore'); if isstr(opt), error(opt); end; %STUDY = pop_pacparams(STUDY, 'default'); %if isempty(opt.timerange), opt.timerange = STUDY.etc.pacparams.timerange; end; %if isempty(opt.freqrange), opt.freqrange = STUDY.etc.pacparams.freqrange; end; nc = max(length(STUDY.condition),1); ng = max(length(STUDY.group),1); % find channel indices % -------------------- if ~isempty(opt.channels1) len1 = length(opt.channels1); len2 = length(opt.channels2); opt.indices1 = std_chaninds(STUDY, opt.channels1); opt.indices2 = std_chaninds(STUDY, opt.channels2); else len1 = length(opt.clusters1); len2 = length(opt.clusters2); opt.indices1 = opt.clusters1; opt.indices2 = opt.clusters2; end; STUDY = std_convertoldsetformat(STUDY); %XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX REMOVE WHEN READY TO GET RID OF OLD FORMAT for ind1 = 1:len1 % usually only one channel/component for ind2 = 1:len2 % usually one channel/component % find indices % ------------ if ~isempty(opt.channels1) tmpstruct1 = STUDY.changrp(opt.indices1(ind1)); tmpstruct2 = STUDY.changrp(opt.indices2(ind2)); else tmpstruct1 = STUDY.cluster(opt.indices1(ind1)); tmpstruct2 = STUDY.cluster(opt.indices2(ind2)); end; allinds1 = tmpstruct1.allinds; setinds1 = tmpstruct1.setinds; allinds2 = tmpstruct2.allinds; setinds2 = tmpstruct2.setinds; % check if data is already here % ----------------------------- dataread = 0; if isfield(tmpstruct1, 'pacdata') & strcmpi(opt.forceread, 'off') & strcmpi(opt.recompute, 'off') if ~isempty(tmpstruct1.pacdata) & iscell(tmpstruct1.pacdata) & length(tmpstruct1.pacdata) >= opt.indices2(ind2) if ~isempty(tmpstruct1.pacdata{opt.indices2(ind2)}) %if isequal( STUDY.etc.pacparams.timerange, opt.timerange) & ... % isequal( STUDY.etc.pacparams.freqrange, opt.freqrange) & ~isempty(tmpstruct.pacdata) dataread = 1; end; end; end; if ~dataread % reserve arrays % -------------- % pacarray = cell( max(length(STUDY.condition),1), max(length(STUDY.group),1) ); % tmpind1 = 1; while(isempty(setinds{tmpind1})), tmpind1 = tmpind1+1; end; % tmpind2 = 1; while(isempty(setinds{tmpind2})), tmpind2 = tmpind2+1; end; % if ~isempty(opt.channels1) % [ tmp allfreqs alltimes ] = std_readpac( ALLEEG, 'channels1' , setinds1{tmpind}(1), 'channels2' , setinds2{tmpind}(1), 'timerange', opt.timerange, 'freqrange', opt.freqrange); % else [ tmp allfreqs alltimes ] = std_readpac( ALLEEG, 'components1', setinds1{tmpind}(1), 'components2', setinds2{tmpind}(1), 'timerange', opt.timerange, 'freqrange', opt.freqrange); % end; % for c = 1:nc % for g = 1:ng % pacarray{c, g} = repmat(zero, [length(alltimes), length(allfreqs), length(allinds1{c,g}) ]); % end; % end; % read the data and select channels % --------------------------------- fprintf('Reading all PAC data...\n'); for c = 1:nc for g = 1:ng % scan all subjects count = 1; for subj = 1:length(STUDY.subject) % get dataset indices for this subject [inds1 inds2] = getsubjcomps(STUDY, subj, setinds1{c,g}, setinds2{c,g}); if setinds1{c,g}(inds1) ~= setinds2{c,g}(inds2), error('Wrong subject index'); end; if ~strcmpi(ALLEEG(setinds1{c,g}(inds1)).subject, STUDY.subject(subj)), error('Wrong subject index'); end; if ~isempty(inds1) & ~isempty(inds2) if ~isempty(opt.channels1) [pacarraytmp allfreqs alltimes] = std_pac( ALLEEG(setinds1{c,g}(subj)), 'channels1' , allinds1{c,g}(inds1), 'channels2', allinds2{c,g}(inds2), 'timerange', opt.timerange, 'freqrange', opt.freqrange, 'recompute', opt.recompute, moreopts{:}); else [pacarraytmp allfreqs alltimes] = std_pac( ALLEEG(setinds1{c,g}(subj)), 'components1', allinds1{c,g}(inds1), 'components2', allinds2{c,g}(inds2), 'timerange', opt.timerange, 'freqrange', opt.freqrange, 'recompute', opt.recompute, moreopts{:}); end; % collapse first 2 dimentions (comps x comps) if ndims(pacarraytmp) == 4 pacarraytmp = reshape(pacarraytmp, size(pacarraytmp,1)*size(pacarraytmp,2), size(pacarraytmp,3), size(pacarraytmp,4)); else pacarraytmp = reshape(pacarraytmp, 1, size(pacarraytmp,1),size(pacarraytmp,2)); end; if strcmpi(opt.onepersubj, 'on') pacarray{c, g}(:,:,count) = squeeze(mean(pacarraytmp,1)); count = count+1; else for tmpi = 1:size(pacarraytmp,1) pacarray{c, g}(:,:,count) = pacarraytmp(tmpi,:,:); count = count+1; end; end; end; end; end; end; % copy data to structure % ---------------------- if ~isempty(opt.channels1) STUDY.changrp(opt.indices1(ind1)).pacfreqs = allfreqs; STUDY.changrp(opt.indices1(ind1)).pactimes = alltimes; STUDY.changrp(opt.indices1(ind1)).pacdata{opt.indices2(ind2)} = pacarray; else STUDY.cluster(opt.indices1(ind1)).pacfreqs = allfreqs; STUDY.cluster(opt.indices1(ind1)).pactimes = alltimes; STUDY.cluster(opt.indices1(ind1)).pacdata{opt.indices2(ind2)} = pacarray; end; end; end; end; % return structure % ---------------- if ~isempty(opt.channels1) clustinfo = STUDY.changrp(opt.indices1); else clustinfo = STUDY.cluster(opt.indices1); end; % get components common to a given subject % ---------------------------------------- function [inds1 inds2] = getsubjcomps(STUDY, subj, setlist1, setlist2, complist1, complist2) inds1 = []; inds2 = []; datasets = strmatch(STUDY.subject{subj}, { STUDY.datasetinfo.subject } ); % all datasets of subject [tmp1] = intersect_bc(setlist1, datasets); [tmp2] = intersect_bc(setlist2, datasets); if length(tmp1) > 1, error('This function does not support sessions for subjects'); end; if length(tmp2) > 1, error('This function does not support sessions for subjects'); end; if tmp1 ~= tmp2, error('Different datasets while it should be the same'); end; if ~isempty(tmp1), inds1 = find(setlist1 == tmp1); end; if ~isempty(tmp2), inds2 = find(setlist2 == tmp2); end;
github
ZijingMao/baselineeegtest-master
std_pvaf.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_pvaf.m
3,535
utf_8
3244c50b0ea6577e8f51f7107250c283
% std_pvaf() - Compute 'percent variance accounted for' (pvaf) by specified % ICA component clusters. This function computes eeg_pvaf on each % of the component of the cluster and then average them. See % eeg_pvaf for more information. This function uses the % Usage: % >> [pvaf pvafs] = std_pvaf(STUDY, ALLEEG, cluster, 'key', 'val'); % Inputs: % EEG - EEGLAB dataset. Must have icaweights, icasphere, icawinv, icaact. % comps - vector of component indices to sum {default|[] -> progressive mode} % In progressive mode, comps is first [1], then [1 2], etc. up to % [1:size(EEG.icaweights,2)] (all components); here, the plot shows pvaf. % % Optional inputs: % 'design' - [integer] selected design. Default is the current design. % '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. % Other optional inputs are the same as eeg_pvaf() % % Outputs: % pvaf - (real) percent total variance accounted for by the summed % back-projection of the requested clusters. % pvafs - [vector] pvaf for each of the cell of the selected design. % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2012- % Copyright (C) 2012 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 % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [pvafAve pvafs] = std_pvaf(STUDY, ALLEEG, cluster, varargin); if nargin < 3 help std_pvaf; return; end; [opt addOptions] = finputcheck(varargin, { 'design' 'integer' [] STUDY.currentdesign; 'rmclust' 'integer' [] []; 'interp' 'struct' { } struct([]); 'rmcomps' 'cell' [] cell(1,length(ALLEEG)) }, 'std_pvaf', 'ignore'); if isstr(opt), error(opt); end; DES = STUDY.design(opt.design); for iCell = 1:length(DES.cell) [EEG complist rmlistcomp] = std_getdataset(STUDY, ALLEEG, 'cell', iCell, 'cluster', cluster, 'interp', opt.interp, ... 'rmcomps', opt.rmcomps{iCell}, 'rmclust', opt.rmclust, 'interpcomponent', 'on' ); %EEG = std_getdataset(STUDY, ALLEEG, 'cell', iCell); if ~isempty(EEG.icaweights) pvafs(iCell) = eeg_pvaf(EEG, [1:size(EEG.icaweights,1)], addOptions{:}); %pvafs(iCell) = eeg_pvaf(EEG, complist, 'artcomps', rmlistcomp, addOptions{:}); else pvafs(iCell) = NaN; end; end; pvafAve = nan_mean(pvafs);
github
ZijingMao/baselineeegtest-master
std_mergeclust.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_mergeclust.m
3,678
utf_8
8a328c6df1c40cfc3d89f72eb8af8a11
% std_mergeclust() - Commandline function, to merge several clusters. % Usage: % >> [STUDY] = std_mergeclust(STUDY, ALLEEG, mrg_cls, name); % 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(). % mrg_cls - clusters indexes to merge. % Optional inputs: % name - [string] a mnemonic cluster name for the merged cluster. % {default: 'Cls #', where '#' is the next available cluster number}. % % Outputs: % STUDY - the input STUDY set structure modified with the merged cluster. % % Example: % >> mrg_cls = [3 7 9]; name = 'eyes'; % >> [STUDY] = std_mergecluster(STUDY,ALLEEG, mrg_cls, name); % Merge clusters 3, 7 and 9 to a new cluster named 'eyes'. % % See also pop_clustedit % % Authors: Hilit Serby, Arnaud Delorme, Scott Makeig, SCCN, INC, UCSD, July, 2005 % Copyright (C) Hilit Serby, SCCN, INC, UCSD, July 11, 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_mergeclust(STUDY, ALLEEG, mrg_cls, varargin) if isempty(varargin) | strcmpi(varargin,'') name = 'Cls'; else name = varargin{1}; end % Cannot merge clusters if any of the clusters is a 'Notclust' or 'Outlier' % cluster, or if has children comps = []; sets = []; for k = 1:length(mrg_cls) if strncmpi('Notclust',STUDY.cluster(mrg_cls(k)).name,8) | strncmpi('Outliers',STUDY.cluster(mrg_cls(k)).name,8) | ... ~isempty(STUDY.cluster(mrg_cls(k)).child) warndlg2([ 'std_mergeclust: cannot merge clusters if one of the clusters '... 'is a ''Notclust'' or ''Outliers'' cluster, or if it has children clusters.']); end parent{k} = STUDY.cluster(mrg_cls(k)).name; comps = [comps STUDY.cluster(mrg_cls(k)).comps]; sets = [sets STUDY.cluster(mrg_cls(k)).sets]; end %sort by sets [tmp,sind] = sort(sets(1,:)); sets = sets(:,sind); comps = comps(sind); % sort component indexes within a set diffsets = unique_bc(sets(1,:)); for k = 1:length(diffsets) ci = find(sets(1,:) == diffsets(k)); % find the compnents belonging to each set [tmp,cind] = sort(comps(ci)); comps(ci) = comps(ci(cind)); end % Create a new empty cluster [STUDY] = std_createclust(STUDY, ALLEEG, name); % Update merge cluster with parent clusters STUDY.cluster(end).parent = parent; STUDY.cluster(end).sets = sets; % Update merge cluster with merged component sets STUDY.cluster(end).comps = comps; % Update merge cluster with the merged components for k = 1:length(mrg_cls) % update the merge cluster as a child for the parent clusters STUDY.cluster(mrg_cls(k)).child{end + 1} = STUDY.cluster(end).name; end STUDY = std_selectdesign(STUDY, ALLEEG, STUDY.currentdesign);
github
ZijingMao/baselineeegtest-master
std_findoutlierclust.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_findoutlierclust.m
599
utf_8
5cf670b56c3d2178f15c05b6c8482328
% std_findoutlierclust() - determine whether an outlier cluster already exists % for a specified cluster. If so, return the outlier cluster index. % If not, return zero. This helper function is called by % pop_clustedit(), std_moveoutlier(), std_renameclust(). function outlier_clust = std_findoutlierclust(STUDY,clust) outlier_clust = 0; outlier_name = [ 'Outliers ' STUDY.cluster(clust).name ' ' ]; for k = 1:length(STUDY.cluster) if strncmpi(outlier_name,STUDY.cluster(k).name,length(outlier_name)) outlier_clust = k; end end
github
ZijingMao/baselineeegtest-master
std_indvarmatch.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_indvarmatch.m
2,411
utf_8
5902a4b72dc6351b4f1b4c26c2975ab8
% std_indvarmatch - match independent variable value in a list of values % % Usage: % indices = std_indvarmatch(value, valuelist); % % Input: % value - [string|real|cell] value to be matched % valuelist - [cell array] cell array of string, numerical values or % cell array % % Output: % indices - [integer] numerical indices % % Example: % std_indvarmatch( 3, { 3 4 [2 3] }); % std_indvarmatch( [2 3], { 3 4 [2 3] }); % std_indvarmatch( [2 3], { 3 4 2 4 3 }); % std_indvarmatch( 'test1', { 'test1' 'test2' { 'test1' 'test2' } }); % std_indvarmatch( { 'test1' 'test2' }, { 'test1' 'test2' { 'test1' 'test2' } }); % std_indvarmatch( { 'test1' 'test2' }, { 'test1' 'test2' 'test3' 'test1' }); % % 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 indices = std_indvarmatch(val, allvals); indices = []; if nargin < 1 help std_indvarmatch; return; end; % match values % ------------ if all(cellfun(@isstr, allvals)) % string if ~iscell(val) indices = strmatch( val, allvals, 'exact')'; else for indcell = 1:length(val) indices = [ indices std_indvarmatch(val{indcell}, allvals) ]; end; end; elseif all(cellfun(@length, allvals) == 1) % numerical if length(val) == 1 indices = find( val == [allvals{:}]); else for ind = 1:length(val) indices = [ indices std_indvarmatch(val(ind), allvals) ]; end; end; else % mixed with cell array indices = []; for index = 1:length(allvals) if isequal(val, allvals{index}) indices = [indices index]; end; end; end; return;
github
ZijingMao/baselineeegtest-master
std_renamestudyfiles.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_renamestudyfiles.m
3,659
utf_8
4f9bcafcb1c0e952fab0e36174fc66b2
% std_renamestudyfiles() - rename files for design 1 if necessary. In design % 1, for backward compatibility, files could have % legacy names. For consistency these files now % need to be renamed. Note that the STUDY is % automatically resave on disk to avoid any potential % inconsistency. % % Usage: % >> STUDY = std_renamestudyfiles(STUDY, ALLEEG) % % Inputs: % STUDY - EEGLAB STUDY set % ALLEEG - vector of the EEG datasets included in the STUDY structure % % Output: % STUDY - The input STUDY with new design files. % % Author: Arnaud Delorme, Institute for Neural Computation UCSD, 2013- % 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_renamestudyfiles(STUDY, ALLEEG) if nargin < 2 help std_renamestudyfiles; return; end; STUDY2 = std_makedesign(STUDY, ALLEEG, 1, STUDY.design(1), 'defaultdesign', 'forceoff', 'verbose', 'off'); allCell1 = { STUDY.design(1).cell.filebase }; allCell2 = { STUDY2.design(1).cell.filebase }; fileExtensions = { 'daterp' 'datspec' 'datersp' 'daterpim' 'dattimef' 'datitc' 'daterpim' ... 'icaerp' 'icaspec' 'icaersp' 'icaerpim' 'icatimef' 'icaitc' 'icaerpim' }; if ~isequal(allCell1, allCell2) thereIsAFileNotDesign = false; for index = 1:length(allCell1), if length(allCell1{index}) < 6 || all(allCell1{index}(1:6) == 'design'), thereIsAFileNotDesign = true; end; end; for index = 1:length(allCell1), if length(allCell1{index}) < 6 || all(allCell1{index}(1:6) == 'design'), thereIsAFileNotDesign = true; end; end; if thereIsAFileNotDesign res = questdlg2(['Old STUDY design data files have been detected.' 10 ... 'EEGLAB wants to rename these files to improve consistency' 10 ... 'and stability. No dataset will be renamed, only preprocessed' 10 ... 'STUDY data files.' ], 'Rename STUDY data files', 'Cancel', ... 'Rename', 'Rename'); if strcmpi(res, 'rename') STUDY = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave'); for iCell = 1:length(allCell1) % scan file extensions for iExt = 1:length(fileExtensions) files = dir( [ allCell1{iCell} '.' fileExtensions{iExt} ]); if ~isempty(files) && ~strcmpi(allCell1{iCell}, allCell2{iCell}) movefile( [ allCell1{iCell} '.' fileExtensions{iExt} ], ... [ allCell2{iCell} '.' fileExtensions{iExt} ]); disp([ 'Moving ' [ allCell1{iCell} '.' fileExtensions{iExt} ] ' to ' [ allCell2{iCell} '.' fileExtensions{iExt} ] ]); end; end; end; STUDY = STUDY2; STUDY = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave'); end; end; end;
github
ZijingMao/baselineeegtest-master
pop_specparams.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_specparams.m
10,087
utf_8
f64596380d4c81cfb3653b30b7accfe4
% pop_specparams() - Set plotting and statistics parameters for computing % STUDY component spectra. % Usage: % >> STUDY = pop_specparams(STUDY, 'key', 'val'); % % Inputs: % STUDY - EEGLAB STUDY set % % Plot options: % 'topofreq' - [real] Plot Spectrum scalp maps at one specific freq. (Hz). % A frequency range [min max] may also be defined (the % spectrum is then averaged over the interval) {default: []} % 'freqrange' - [min max] spectral frequency range (in Hz) to plot. % {default: whole frequency range} . % 'ylim' - [mindB maxdB] spectral plotting limits in dB % {default: from data} % 'plotgroups' - ['together'|'apart'] 'together' -> plot subject groups % on the same figure in different colors, else ('apart') on % different figures {default: 'apart'} % 'plotconditions' - ['together'|'apart'] 'together' -> plot conditions % on the same figure in different colors, else ('apart') % on different figures. Note: keywords 'plotgroups' and % 'plotconditions' cannot both be set to 'together'. % {default: 'apart'} % 'subtractsubjectmean' - ['on'|'off'] subtract individual subject mean % from each spectrum before plotting and computing % statistics. Default is 'off'. % 'averagechan' - ['on'|'off'] average data channels when several are % selected. % % See also: std_specplot() % % Authors: Arnaud Delorme, CERCO, CNRS, 2006- % 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 [ STUDY, com ] = pop_specparams(STUDY, varargin); STUDY = default_params(STUDY); TMPSTUDY = STUDY; com = ''; if isempty(varargin) enablecond = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off'); enablegroup = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off'); plotconditions = fastif(strcmpi(STUDY.etc.specparams.plotconditions, 'together'), 1, 0); plotgroups = fastif(strcmpi(STUDY.etc.specparams.plotgroups,'together'), 1, 0); submean = fastif(strcmpi(STUDY.etc.specparams.subtractsubjectmean,'on'), 1, 0); radio_averagechan = fastif(strcmpi(STUDY.etc.specparams.averagechan,'on'), 1, 0); radio_scalptopo = fastif(isempty(STUDY.etc.specparams.topofreq), 0, 1); if radio_scalptopo, radio_averagechan = 0; end; if radio_scalptopo+radio_averagechan == 0, radio_scalparray = 1; else radio_scalparray = 0; end; cb_radio = [ 'set(findobj(gcbf, ''userdata'', ''radio''), ''value'', 0);' ... 'set(gcbo, ''value'', 1);' ... 'set(findobj(gcbf, ''tag'', ''topofreq''), ''string'', '''');' ]; cb_edit = [ 'set(findobj(gcbf, ''userdata'', ''radio''), ''value'', 0);' ... 'set(findobj(gcbf, ''tag'', ''scalptopotext''), ''value'', 1);' ]; uilist = { ... {'style' 'text' 'string' 'Spectrum plotting options' 'fontweight' 'bold' 'fontsize', 12} ... {} {'style' 'text' 'string' 'Frequency [low_Hz high_Hz]' } ... {'style' 'edit' 'string' num2str(STUDY.etc.specparams.freqrange) 'tag' 'freqrange' } ... {} {'style' 'text' 'string' 'Plot limits [low high]'} ... {'style' 'edit' 'string' num2str(STUDY.etc.specparams.ylim) 'tag' 'ylim' } ... {} {'style' 'checkbox' 'string' 'Subtract individual subject mean spectrum' 'value' submean 'tag' 'submean' } ... {} ... {'style' 'text' 'string' 'Spectrum plotting format' 'fontweight' 'bold' 'fontsize', 12} ... {} {'style' 'checkbox' 'string' 'Plot first variable on the same panel' 'value' plotconditions 'enable' enablecond 'tag' 'plotconditions' } ... {} {'style' 'checkbox' 'string' 'Plot second variable on the same panel' 'value' plotgroups 'enable' enablegroup 'tag' 'plotgroups' } ... {} ... {'style' 'text' 'string' 'Multiple channels selection' 'fontweight' 'bold' 'fontsize', 12} ... {} {'style' 'radio' 'string' 'Plot channels in scalp array' 'value' radio_scalparray 'tag' 'scalparray' 'userdata' 'radio' 'callback' cb_radio} { } ... {} {'style' 'radio' 'string' 'Plot topography at freq. (Hz)' 'value' radio_scalptopo 'tag' 'scalptopotext' 'userdata' 'radio' 'callback' cb_radio} ... {'style' 'edit' 'string' num2str(STUDY.etc.specparams.topofreq) 'tag' 'topofreq' 'callback' cb_edit } ... {} {'style' 'radio' 'string' 'Average selected channels' 'value' radio_averagechan 'tag' 'averagechan' 'userdata' 'radio' 'callback' cb_radio} { } }; cbline = [0.07 1.1]; otherline = [ 0.07 0.6 .3]; chanline = [ 0.07 0.8 0.3]; geometry = { 1 otherline otherline cbline 1 1 cbline cbline 1 1 chanline chanline chanline }; geomvert = [1.2 1 1 1 0.5 1.2 1 1 0.5 1.2 1 1 1 ]; % component plotting % ------------------ if isnan(STUDY.etc.specparams.topofreq) geometry(end-4:end) = []; geomvert(end-4:end) = []; uilist(end-10:end) = []; end; [out_param userdat tmp res] = inputgui( 'geometry' , geometry, 'uilist', uilist, 'geomvert', geomvert, ... 'title', 'Spectrum plotting options -- pop_specparams()'); if isempty(res), return; end; % decode inputs % ------------- %if res.plotgroups & res.plotconditions, warndlg2('Both conditions and group cannot be plotted on the same panel'); return; end; if res.submean , res.submean = 'on'; else res.submean = 'off'; end; if res.plotgroups, res.plotgroups = 'together'; else res.plotgroups = 'apart'; end; if res.plotconditions , res.plotconditions = 'together'; else res.plotconditions = 'apart'; end; if ~isfield(res, 'topofreq'), res.topofreq = STUDY.etc.specparams.topofreq; else res.topofreq = str2num( res.topofreq ); end; if ~isfield(res, 'averagechan'), res.averagechan = STUDY.etc.specparams.averagechan; elseif res.averagechan, res.averagechan = 'on'; else res.averagechan = 'off'; end; res.freqrange = str2num( res.freqrange ); res.ylim = str2num( res.ylim ); % build command call % ------------------ options = {}; if ~strcmpi( res.plotgroups, STUDY.etc.specparams.plotgroups), options = { options{:} 'plotgroups' res.plotgroups }; end; if ~strcmpi( res.plotconditions , STUDY.etc.specparams.plotconditions ), options = { options{:} 'plotconditions' res.plotconditions }; end; if ~strcmpi( res.submean , STUDY.etc.specparams.subtractsubjectmean ), options = { options{:} 'subtractsubjectmean' res.submean }; end; if ~isequal(res.topofreq, STUDY.etc.specparams.topofreq), options = { options{:} 'topofreq' res.topofreq }; end; if ~isequal(res.ylim, STUDY.etc.specparams.ylim), options = { options{:} 'ylim' res.ylim }; end; if ~isequal(res.freqrange, STUDY.etc.specparams.freqrange), options = { options{:} 'freqrange' res.freqrange }; end; if ~isequal(res.averagechan, STUDY.etc.specparams.averagechan), options = { options{:} 'averagechan' res.averagechan }; end; if ~isempty(options) STUDY = pop_specparams(STUDY, options{:}); com = sprintf('STUDY = pop_specparams(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.specparams), 'exact')) STUDY.etc.specparams = setfield(STUDY.etc.specparams, varargin{index}, varargin{index+1}); end; end; end; end; % scan clusters and channels to remove specdata info if freqrange has changed % ---------------------------------------------------------- if ~isequal(STUDY.etc.specparams.freqrange, TMPSTUDY.etc.specparams.freqrange) | ... ~isequal(STUDY.etc.specparams.subtractsubjectmean, TMPSTUDY.etc.specparams.subtractsubjectmean) rmfields = { 'specdata' 'specfreqs' }; for iField = 1:length(rmfields) if isfield(STUDY.cluster, rmfields{iField}) STUDY.cluster = rmfield(STUDY.cluster, rmfields{iField}); end; if isfield(STUDY.changrp, rmfields{iField}) STUDY.changrp = rmfield(STUDY.changrp, rmfields{iField}); end; end; end; function STUDY = default_params(STUDY) if ~isfield(STUDY.etc, 'specparams'), STUDY.etc.specparams = []; end; if ~isfield(STUDY.etc.specparams, 'topofreq'), STUDY.etc.specparams.topofreq = []; end; if ~isfield(STUDY.etc.specparams, 'freqrange'), STUDY.etc.specparams.freqrange = []; end; if ~isfield(STUDY.etc.specparams, 'ylim' ), STUDY.etc.specparams.ylim = []; end; if ~isfield(STUDY.etc.specparams, 'subtractsubjectmean' ), STUDY.etc.specparams.subtractsubjectmean = 'off'; end; if ~isfield(STUDY.etc.specparams, 'plotgroups'), STUDY.etc.specparams.plotgroups = 'apart'; end; if ~isfield(STUDY.etc.specparams, 'plotconditions'), STUDY.etc.specparams.plotconditions = 'apart'; end; if ~isfield(STUDY.etc.specparams, 'averagechan') , STUDY.etc.specparams.averagechan = 'off'; end;
github
ZijingMao/baselineeegtest-master
std_erp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_erp.m
10,502
utf_8
521c5aedf3d9acd898c441a4f4942fa2
% std_erp() - Constructs and returns channel or ICA activation ERPs for a dataset. % Saves the ERPs into a Matlab file, [dataset_name].icaerp, for % data channels or [dataset_name].icaerp for ICA components, % in the same directory as the dataset file. If such a file % already exists, loads its information. % Usage: % >> [erp, times] = std_erp(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 % activation ERPs will be computed. Note that because % computation of ERP is so fast, all components ERP 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 ERPs will be computed. Note that because % computation of ERP is so fast, all channels ERP 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. % % ERP specific options: % 'rmbase' - [min max] remove baseline. This option does not affect % the original datasets. % % Outputs: % erp - ERP for the requested ICA components in the selected % latency window. ERPs are scaled by the RMS over of the % component scalp map projection over all data channels. % times - vector of times (epoch latencies in ms) for the ERP % % File output: % [dataset_file].icaerp % component erp file % OR % [dataset_file].daterp % channel erp file % % See also: std_spec(), std_ersp(), std_topo(), std_preclust() % % Authors: Arnaud Delorme, SCCN, INC, UCSD, January, 2005 % 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, t] = std_erp(EEG, varargin); %comps, timerange) if nargin < 1 help std_erp; return; end; % decode inputs % ------------- if ~isempty(varargin) if ~isstr(varargin{1}) varargin = { varargin{:} [] [] }; if all(varargin{1} > 0) options = { 'components' varargin{1} 'timerange' varargin{2} }; else options = { 'channels' -varargin{1} 'timerange' varargin{2} }; end; else options = varargin; end; else options = varargin; end; g = finputcheck(options, { 'components' 'integer' [] []; 'channels' 'cell' {} {}; 'rmbase' 'real' [] []; 'trialindices' { 'integer','cell' } [] []; 'rmcomps' 'cell' [] cell(1,length(EEG)); 'fileout' 'string' [] ''; 'savetrials' 'string' { 'on','off' } 'off'; 'interp' 'struct' { } struct([]); 'timerange' 'real' [] []; % the timerange option is deprecated and has no effect 'recompute' 'string' { 'on','off' } 'off' }, 'std_erp'); if isstr(g), error(g); end; if isempty(g.trialindices), g.trialindices = cell(length(EEG)); end; if ~iscell(g.trialindices), g.trialindices = { g.trialindices }; 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 % % THIS SECTION WOULD NEED TO TEST THAT THE PARAMETERS ON DISK ARE CONSISTENT % % % filename % % -------- if isempty(g.fileout), g.fileout = fullfile(EEG(1).filepath, EEG(1).filename(1:end-4)); end; if ~isempty(g.channels) filenameshort = [ g.fileout '.daterp']; prefix = 'chan'; else filenameshort = [ g.fileout '.icaerp']; prefix = 'comp'; end; %filename = fullfile( EEG(1).filepath, filenameshort); filename = filenameshort; % ERP information found in datasets % --------------------------------- if exist(filename) & strcmpi(g.recompute, 'off') fprintf('File "%s" found on disk, no need to recompute\n', filenameshort); setinfo.filebase = g.fileout; if strcmpi(prefix, 'comp') [X tmp t] = std_readfile(setinfo, 'components', g.components, 'timelimits', g.timerange, 'measure', 'erp'); else [X tmp t] = std_readfile(setinfo, 'channels', g.channels, 'timelimits', g.timerange, 'measure', 'erp'); end; if ~isempty(X), return; end; end % No ERP information found % ------------------------ % if isstr(EEG.data) % TMP = eeg_checkset( EEG, 'loaddata' ); % load EEG.data and EEG.icaact % else % TMP = EEG; % end % & isempty(TMP.icaact) % TMP.icaact = (TMP.icaweights*TMP.icasphere)* ... % reshape(TMP.data(TMP.icachansind,:,:), [ length(TMP.icachansind) size(TMP.data,2)*size(TMP.data,3) ]); % TMP.icaact = reshape(TMP.icaact, [ size(TMP.icaact,1) size(TMP.data,2) size(TMP.data,3) ]); %end; %if strcmpi(prefix, 'comp'), X = TMP.icaact; %else X = TMP.data; %end; 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 = eeg_getdatact(EEG, 'component', [1:size(EEG(1).icaweights,1)], 'trialindices', g.trialindices ); else X = eeg_getdatact(EEG, 'channel' , [1:EEG(1).nbchan], 'trialindices', g.trialindices, 'rmcomps', g.rmcomps, 'interp', g.interp); end; % Remove baseline mean % -------------------- pnts = EEG(1).pnts; trials = size(X,3); timevals = EEG(1).times; if ~isempty(g.timerange) disp('Warning: the ''timerange'' option is deprecated and has no effect'); end; if ~isempty(X) if ~isempty(g.rmbase) disp('Removing baseline...'); options = { options{:} 'rmbase' g.rmbase }; [tmp timebeg] = min(abs(timevals - g.rmbase(1))); [tmp timeend] = min(abs(timevals - g.rmbase(2))); if ~isempty(timebeg) X = rmbase(X,pnts, [timebeg:timeend]); else X = rmbase(X,pnts); end end X = reshape(X, [ size(X,1) pnts trials ]); if strcmpi(prefix, 'comp') if strcmpi(g.savetrials, 'on') X = repmat(sqrt(mean(EEG(1).icawinv.^2))', [1 EEG(1).pnts size(X,3)]) .* X; else X = repmat(sqrt(mean(EEG(1).icawinv.^2))', [1 EEG(1).pnts]) .* mean(X,3); % calculate ERP end; elseif strcmpi(g.savetrials, 'off') X = mean(X, 3); end; end; % Save ERPs in file (all components or channels) % ---------------------------------------------- if isempty(timevals), timevals = linspace(EEG(1).xmin, EEG(1).xmax, EEG(1).pnts)*1000; end; % continuous data fileNames = computeFullFileName( { EEG.filepath }, { EEG.filename }); if strcmpi(prefix, 'comp') savetofile( filename, timevals, X, 'comp', 1:size(X,1), options, {}, fileNames, g.trialindices); %[X,t] = std_readerp( EEG, 1, g.components, g.timerange); else if ~isempty(g.interp) savetofile( filename, timevals, X, 'chan', 1:size(X,1), options, { g.interp.labels }, fileNames, g.trialindices); else tmpchanlocs = EEG(1).chanlocs; savetofile( filename, timevals, X, 'chan', 1:size(X,1), options, { tmpchanlocs.labels }, fileNames, g.trialindices); end; %[X,t] = std_readerp( EEG, 1, g.channels, g.timerange); end; % compute full file names % ----------------------- function res = computeFullFileName(filePaths, fileNames); for index = 1:length(fileNames) res{index} = fullfile(filePaths{index}, fileNames{index}); end; % ------------------------------------- % saving ERP information to Matlab file % ------------------------------------- function savetofile(filename, t, X, prefix, comps, params, labels, dataFiles, dataTrials); disp([ 'Saving ERP file ''' filename '''' ]); allerp = []; for k = 1:length(comps) allerp = setfield( allerp, [ prefix int2str(comps(k)) ], squeeze(X(k,:,:))); end; if nargin > 6 && ~isempty(labels) allerp.labels = labels; end; allerp.times = t; allerp.datatype = 'ERP'; allerp.parameters = params; allerp.datafiles = dataFiles; allerp.datatrials = dataTrials; std_savedat(filename, allerp);
github
ZijingMao/baselineeegtest-master
pop_erpimparams.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_erpimparams.m
8,436
utf_8
239b2e9f4a563e64fe4a3d7d631a5b62
% pop_erpimparams() - Set plotting and statistics parameters for % computing and plotting STUDY mean ERPimages and measure % statistics. Settings are stored within the STUDY % structure (STUDY.etc.erpimparams) which is used % whenever plotting is performed by the function % std_erpimage(). % Usage: % >> STUDY = pop_erpimparams(STUDY, 'key', 'val', ...); % % Inputs: % STUDY - EEGLAB STUDY set % % Erpimage plotting options: % 'timerange' - [min max] erpim/ITC plotting latency range in ms. % {default: the whole output latency range}. % 'trialrange' - [min max] erpim/ITC plotting frequency range in ms. % {default: the whole output frequency range} % 'topotime' - [float] plot scalp map at specific time. A time range may % also be provide and the erpim will be averaged over the % given time range. Requires 'topofreq' below to be set. % 'topotrial' - [float] plot scalp map at specific trial in ERPimage. As % above a trial range may also be provided. % % Authors: Arnaud Delorme, CERCO, CNRS, 2006- % Copyright (C) Arnaud Delorme, 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 [ STUDY, com ] = pop_erpimparams(STUDY, varargin); STUDY = default_params(STUDY); TMPSTUDY = STUDY; com = ''; if isempty(varargin) vis = fastif(isnan(STUDY.etc.erpimparams.topotime), 'off', 'on'); uilist = { ... {'style' 'text' 'string' 'ERPimage plotting options' 'fontweight' 'bold' 'tag', 'erpim' } ... {'style' 'text' 'string' 'Time range in ms [Low High]'} ... {'style' 'edit' 'string' num2str(STUDY.etc.erpimparams.timerange) 'tag' 'timerange' } ... {'style' 'text' 'string' 'Plot scalp map at time [ms]' 'visible' vis} ... {'style' 'edit' 'string' num2str(STUDY.etc.erpimparams.topotime) 'tag' 'topotime' 'visible' vis } ... {'style' 'text' 'string' 'Trial range [Low High]'} ... {'style' 'edit' 'string' num2str(STUDY.etc.erpimparams.trialrange) 'tag' 'trialrange' } ... {'style' 'text' 'string' 'Plot scalp map at trial(s)' 'visible' vis} ... {'style' 'edit' 'string' num2str(STUDY.etc.erpimparams.topotrial) 'tag' 'topotrial' 'visible' vis } ... {'style' 'text' 'string' 'Color limits [Low High]'} ... {'style' 'edit' 'string' num2str(STUDY.etc.erpimparams.colorlimits) 'tag' 'colorlimits' } ... {'style' 'text' 'string' '' } ... {'style' 'text' 'string' '' } }; evalstr = 'set(findobj(gcf, ''tag'', ''erpim''), ''fontsize'', 12);'; cbline = [0.07 1.1]; otherline = [ 0.6 .4 0.6 .4]; geometry = { 1 otherline otherline otherline }; enablecond = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off'); enablegroup = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off'); [out_param userdat tmp res] = inputgui( 'geometry' , geometry, 'uilist', uilist, ... 'title', 'Set Erpimage plotting parameters -- pop_erpimparams()', 'eval', evalstr); if isempty(res), return; end; % decode input % ------------ res.topotime = str2num( res.topotime ); res.topotrial = str2num( res.topotrial ); res.timerange = str2num( res.timerange ); res.trialrange = str2num( res.trialrange ); res.colorlimits = str2num( res.colorlimits ); % build command call % ------------------ options = {}; if ~isequal(res.topotime , STUDY.etc.erpimparams.topotime), options = { options{:} 'topotime' res.topotime }; end; if ~isequal(res.topotrial, STUDY.etc.erpimparams.topotrial), options = { options{:} 'topotrial' res.topotrial }; end; if ~isequal(res.timerange , STUDY.etc.erpimparams.timerange), options = { options{:} 'timerange' res.timerange }; end; if ~isequal(res.trialrange, STUDY.etc.erpimparams.trialrange), options = { options{:} 'trialrange' res.trialrange }; end; if ~isequal(res.colorlimits, STUDY.etc.erpimparams.colorlimits), options = { options{:} 'colorlimits' res.colorlimits }; end; if ~isempty(options) STUDY = pop_erpimparams(STUDY, options{:}); com = sprintf('STUDY = pop_erpimparams(STUDY, %s);', vararg2str( options )); end; else if strcmpi(varargin{1}, 'default') STUDY = default_params(STUDY); else allfields = fieldnames(STUDY.etc.erpimparams); for index = 1:2:length(varargin) if ~isempty(strmatch(varargin{index}, allfields, 'exact')) STUDY.etc.erpimparams = setfield(STUDY.etc.erpimparams, varargin{index}, varargin{index+1}); else if ~isequal(varargin{index}, 'datatype') && ~isequal(varargin{index}, 'channels') inderpimopt = strmatch(varargin{index}, STUDY.etc.erpimparams.erpimageopt(1:2:end), 'exact'); if ~isempty(inderpimopt) STUDY.etc.erpimparams.erpimageopt{2*inderpimopt} = varargin{index+1}; else STUDY.etc.erpimparams.erpimageopt = { STUDY.etc.erpimparams.erpimageopt{:} varargin{index}, varargin{index+1} }; end; end; end; end; end; end; % scan clusters and channels to remove erpimdata info if timerange etc. have changed % --------------------------------------------------------------------------------- if ~isequal(STUDY.etc.erpimparams.timerange, TMPSTUDY.etc.erpimparams.timerange) | ... ~isequal(STUDY.etc.erpimparams.trialrange, TMPSTUDY.etc.erpimparams.trialrange) rmfields = { 'erpimdata' 'erpimtimes' 'erpimtrials' 'erpimevents' }; for iField = 1:length(rmfields) if isfield(STUDY.cluster, rmfields{iField}) STUDY.cluster = rmfield(STUDY.cluster, rmfields{iField}); end; if isfield(STUDY.changrp, rmfields{iField}) STUDY.changrp = rmfield(STUDY.changrp, rmfields{iField}); end; end; end; function STUDY = default_params(STUDY) if ~isfield(STUDY.etc, 'erpimparams'), STUDY.etc.erpimparams = []; end; if ~isfield(STUDY.etc.erpimparams, 'erpimageopt'), STUDY.etc.erpimparams.erpimageopt = {}; end; if ~isfield(STUDY.etc.erpimparams, 'sorttype' ), STUDY.etc.erpimparams.sorttype = ''; end; if ~isfield(STUDY.etc.erpimparams, 'sortwin' ), STUDY.etc.erpimparams.sortwin = []; end; if ~isfield(STUDY.etc.erpimparams, 'sortfield' ), STUDY.etc.erpimparams.sortfield = 'latency'; end; if ~isfield(STUDY.etc.erpimparams, 'rmcomps' ), STUDY.etc.erpimparams.rmcomps = []; end; if ~isfield(STUDY.etc.erpimparams, 'interp' ), STUDY.etc.erpimparams.interp = []; end; if ~isfield(STUDY.etc.erpimparams, 'timerange' ), STUDY.etc.erpimparams.timerange = []; end; if ~isfield(STUDY.etc.erpimparams, 'trialrange' ), STUDY.etc.erpimparams.trialrange = []; end; if ~isfield(STUDY.etc.erpimparams, 'topotime' ), STUDY.etc.erpimparams.topotime = []; end; if ~isfield(STUDY.etc.erpimparams, 'topotrial' ), STUDY.etc.erpimparams.topotrial = []; end; if ~isfield(STUDY.etc.erpimparams, 'colorlimits'), STUDY.etc.erpimparams.colorlimits = []; end; if ~isfield(STUDY.etc.erpimparams, 'concatenate'), STUDY.etc.erpimparams.concatenate = 'off'; end; if ~isfield(STUDY.etc.erpimparams, 'nlines'), STUDY.etc.erpimparams.nlines = 20; end; if ~isfield(STUDY.etc.erpimparams, 'smoothing'), STUDY.etc.erpimparams.smoothing = 10; end;
github
ZijingMao/baselineeegtest-master
std_dipoleclusters.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_dipoleclusters.m
13,236
utf_8
6bbd84189c57ef6ab08de937ebf62583
% std_dipoleclusters - Plots clusters of ICs as colored dipoles in MRI % images (side, rear, top and oblique angles possible) % % std_dipoleclusters(STUDY,ALLEEG,'key1',value1, 'key2',value2, ... ); % % Inputs: % STUDY - EEGLAB STUDY set % ALLEEG - vector of the EEG datasets included in the STUDY structure % % Optional inputs: % 'clusters' - [vector of numbers] list of clusters to plot in same head space % 'title' - [string] figure title % 'viewnum' - [vector] list of views to plot: 1=top, 2=side, 3=rear, 4 is an oblique view; % length(viewnum) gives the number of subplots that will be produced and the % values within the vector tell the orientation and order of views % 'rowcolplace' - [rows cols subplot] If plotting into an existing figure, specify the number of rows, % columns and the subplot number to start plotting dipole panels. % 'colors' - [vector or matrix] if 1 x 3 vector of RGB values, this will plot all dipoles as the % same color. ex. [1 0 0] is red, [0 0 1] is blue, [0 1 0] is green. % If a matrix, should be n x 3, with the number of rows equal to the number % of clusters to be plotted and the columns should be RGB values for each. % If [], will plot clusters as 'jet' colorscale from the first to the last cluster % requested (therefore an alternate way to control dipole color is to input a specific % order of clusters). % [] will assign colors from hsv color scale. % 'centroid' - ['only', 'add', 'off'] 'only' will plot only cluster centroids, 'add' will superimpose % centroids over cluster dipoles, 'off' will skip centroid plotting and only plot % cluster-member dipoles. % % Authors: Julie Onton, SCCN/INC UCSD, June 2009 % Copyright (C) Julie Onton, SCCN/INC/UCSD, October 11, 2009 % % 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_dipoleclusters(STUDY,ALLEEG, varargin); if nargin < 2 help std_dipoleclusters; return; end; % Set default values------------------------------------------------------------------------ if strcmp(STUDY.cluster(2),'outlier 2') % don't plot outlier cluster #2 clustvec = [3:length(STUDY.cluster)]; % plot all clusters in STUDY else clustvec = [2:length(STUDY.cluster)]; % plot all clusters in STUDY end; onecolor = []; colvec = []; centroid = 'off'; viewnum = [1:4]; % plot all views and oblique rowcolplace = [2 2 1]; % 2 X 2 figure starting in subplot 1 figureon = 1; % plot on a new figure ttl = ''; % no title %--------------------------------------------------------------------------------- for k = 3:2:nargin switch varargin{k-2} case 'clusters' clusters = varargin{k-1}; % redefine from all to specified clusters case 'title' ttl = varargin{k-1}; case 'viewnum', viewnum = varargin{k-1}; case 'rowcolplace' %, mode = varargin{k-1}; % what is mode? JO rowcolplace = varargin{k-1}; if length(rowcolplace) < 3 fprintf('\nThe variable ''rowcolplace'' must contain 3 values.\n'); return; end; row = rowcolplace(1); col = rowcolplace(2); place = rowcolplace(3); figureon = 0; % don't pop a new figure if plotting into existing fig case 'colors' colvec = varargin{k-1}; case 'centroid' centroid = varargin{k-1}; end end % adjust color matrix for dipoles:--------------- if isempty(colvec) cols = jet(length(clusters));% default colors else cols = colvec; % input RGB colors end; % extract IC cluster and data path info from STUDY structure clear clustcps fullpaths gdcomps x = cell(1,length(unique({STUDY.datasetinfo.subject}))); subjs = unique_bc({STUDY.datasetinfo.subject}); origlist = cell(1,length(unique({STUDY.datasetinfo.subject}))); sets = cell(1,length(unique({STUDY.datasetinfo.subject}))); for clust = 1:length(STUDY.cluster) clustcps{clust} = x; for st = 1:size(STUDY.cluster(clust).sets,2) currset = STUDY.cluster(clust).sets(1,st); currcomp = STUDY.cluster(clust).comps(1,st); subjidx = strmatch(STUDY.datasetinfo(currset).subject,subjs); clustcps{clust}{subjidx}(end+1) = currcomp; origlist{subjidx} = [origlist{subjidx} currcomp]; [origlist{subjidx} idx] = unique_bc(origlist{subjidx}); sets{subjidx} = currset; end; end; %----------------------------------------------------------- % extract dipole info for ALL ICs to be plotted subj by subj for nx = 1:length(origlist) dipsources = []; if ~isempty(origlist{nx}) EEG = ALLEEG(sets{nx}); % call in a dataset from subj if isfield(EEG.dipfit.model,'diffmap') EEG.dipfit.model = rmfield(EEG.dipfit.model,'diffmap'); end; if isfield(EEG.dipfit.model,'active') EEG.dipfit.model = rmfield(EEG.dipfit.model,'active'); end; if isfield(EEG.dipfit.model,'select') EEG.dipfit.model = rmfield(EEG.dipfit.model,'select'); end; dipsources.posxyz = EEG.dipfit.model(origlist{nx}(1)).posxyz; dipsources.momxyz = EEG.dipfit.model(origlist{nx}(1)).momxyz; dipsources.rv = EEG.dipfit.model(origlist{nx}(1)).rv;p=1; for w = 1:length(origlist{nx}) dipsources(1,p).posxyz = EEG.dipfit.model(origlist{nx}(w)).posxyz; dipsources(1,p).momxyz = EEG.dipfit.model(origlist{nx}(w)).momxyz; dipsources(1,p).rv = EEG.dipfit.model(origlist{nx}(w)).rv; p=p+1; end; allbesa1{nx} = dipsources; new = 0; end; end; %----------------------------------------------------------- % collect cluster dipole info from extracted dipole infos (above) %%%%%%%%%%%%%%%%%%%%%%%%% new = 1; pp=1; bic = 1; centrstr = struct('posxyz',[0 0 0],'momxyz',[0 0 0],'rv',0); for clst =1:length(clusters) clust = clusters(clst); centr = []; centr2 = []; for nx = 1:length(clustcps{clust}) if ~isempty(clustcps{clust}{nx}) for k = 1:length(clustcps{clust}{nx}) if new == 1 allbesa = allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))); centr = [centr; allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(1,:)]; if size(allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz,1) > 1& allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,1) ~= 0 % actual values, not zero if allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,2) > 0 % on the wrong side, switch with centr1 centr2 = [centr2;allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,:)]; centr2(end,2) = centr2(end,2)*-1; centr1(end,2) = centr1(end,2)*-1; else centr2 = [centr2;allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,:)]; end; end; new = 0; else allbesa(1,end+1) = allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))); centr = [centr; allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(1,:)]; if size(allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz,1) > 1 & allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,1) ~= 0 % actual values, not zero if allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,2) > 0 % on the wrong side, switch with centr1 centr2 = [centr2; allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,:)]; centr2(end,2) = centr2(end,2)*-1; centr1(end,2) = centr1(end,2)*-1; else centr2 = [centr2;allbesa1{nx}(find(origlist{nx} == clustcps{clust}{nx}(k))).posxyz(2,:)]; end; end; end; colset{pp} = cols(clst,:); pp = pp+1; end; end; end; if length(allbesa) > 1 centr = mean(centr,1); centr2 = mean(centr2,1); centrstr(clst).posxyz = centr; centrstr(clst).momxyz = allbesa(end).momxyz(1,:); centrstr(clst).rv = 2; centcols{clst} = cols(clst,:); centcols2{clst} = cols(clst,:)/5; if ~isempty(find(centr2)) centrstr2(bic).posxyz = centr2; centrstr2(bic).momxyz = allbesa(end).momxyz(1,:); centrstr2(bic).rv = 2; bic = bic + 1; % separate count for bilaterals end; end; end; if figureon == 1 figure; row = 2; col = 2; place= 1; end; %------------------------------------------- % PLOT the clusster dipoles: if length(allbesa) > 1 for sbpt = 1:length(viewnum) if sbpt < 4 prjimg = 'off'; else prjimg = 'on'; end; sbplot(row,col,place) if strcmp(centroid,'only') dipplot(centrstr,'image','mri','gui','off','dipolelength',0,'dipolesize',40,'normlen','on','spheres','on','color',centcols,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0); if ~isempty(find(centrstr2(1).posxyz)) % only if there were bilaterals dipplot(centrstr2,'image','mri','gui','off','dipolelength',0,'dipolesize',40,'normlen','on','spheres','on','color',centcols,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0); camzoom(.8) else camzoom(1) end; elseif strcmp(centroid,'add') dipplot(allbesa,'image','mri','gui','off','dipolelength',0,'dipolesize',25,'normlen','on','spheres','on','color',colset,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0); dipplot(centrstr,'image','mri','gui','off','dipolelength',0,'dipolesize',40,'normlen','on','spheres','on','color',centcols2,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0); camzoom(.8) if ~isempty(find(centrstr2(1).posxyz)) % only if there were bilaterals dipplot(centrstr2,'image','mri','gui','off','dipolelength',0,'dipolesize',40,'normlen','on','spheres','on','color',centcols2,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0);camzoom(.8) else camzoom(1) end; else dipplot(allbesa,'image','mri','gui','off','dipolelength',0,'dipolesize',25,'normlen','on','spheres','on','color',colset,'projlines','off','projimg',prjimg,'coordformat',EEG.dipfit.coordformat);hold on; view(90,0); camzoom(1.1) end; if viewnum(sbpt) == 3 view(0,0) elseif viewnum(sbpt) == 1 view(0,90) elseif viewnum(sbpt) == 4 view(63,22); end; place = place+1; end; if ~isempty(ttl) if sbpt == 4 % if oblique ph = text(-75,-75,125,ttl); set(ph,'color','r'); elseif sbpt == 1 % 2d image: ph = text(-50,110,125,ttl); set(ph,'color','r'); elseif sbpt == 2 % 2d image: ph = text(-75,-75,125,ttl); set(ph,'color','r'); elseif sbpt == 3 % 2d image: ph = text(-100,-50,130,ttl); set(ph,'color','r'); end; end; end;
github
ZijingMao/baselineeegtest-master
std_readtopo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readtopo.m
5,758
utf_8
7a63ec0ca54deebed149d2d525446942
% std_readtopo() - returns the scalp map of a specified ICA component, assumed % to have been saved in a Matlab file, [dataset_name].icatopo, % in the same directory as the dataset file. If this file does % not exist, use std_topo() to create it, else a pre-clustering % function that calls it: pop_preclust() or eeg_preclust(). % Usage: % >> [grid, y, x ] = std_readtopo(ALLEEG, setindx, component); % >> [grid, y, x ] = std_readtopo(ALLEEG, setindx, component, transform, mode); % % Inputs: % ALLEEG - vector of EEG datasets (can also be one EEG set). % must contain the dataset of interest (see 'setindx' below). % setindx - [integer] an index of an EEG dataset in the ALLEEG % structure, for which to get the component ERP. % component - [integer] index of the component for which the scalp map % grid should be returned. % transform - ['none'!'laplacian'|'gradient'] transform scalp map to % laplacian or gradient map. Default is 'none'. % mode - ['2dmap'|'preclust'] return either a 2-D array for direct % plotting ('2dmap') or an array formated for preclustering % with all the NaN values removed (ncomps x points). Default % is '2dmap' for 1 component and 'preclust' for several. % % Outputs: % grid - square scalp-map color-value grid for the requested ICA component % in the specified dataset, an interpolated Cartesian grid as output % by topoplot(). % y - y-axis values for the interpolated grid % x - x-axis values of the interpolated grid % % See also std_topo(), std_preclust() % % Authors: Arnaud Delorme, Hilit Serby, SCCN, INC, UCSD, February, 2005 % 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, yi, xi ] = std_readtopo(ALLEEG, abset, comps, option, mode) X = []; yi = []; xi = []; if nargin < 4 option = 'none'; end; if nargin < 5 mode = '2Dmap'; end; filename = correctfile(fullfile( ALLEEG(abset).filepath,[ ALLEEG(abset).filename(1:end-3) 'icatopo'])); tmpfile = which(filename); if ~isempty(tmpfile), filename = tmpfile; end; % 061411, 2:51pm % Modified by Joaquin % while getfield(dir(filename), 'bytes') < 1000 i = 1; while getfield(dir(filename), 'bytes') < 1500 topo = load( '-mat', filename); filename = correctfile(topo.file, ALLEEG(abset).filepath); tmpfile = which(filename); if ~isempty(tmpfile), filename = tmpfile; end; if(i>100) error('too many attempts to find valid icatopo'); end i = i+1; end; for k = 1:length(comps) if length(comps) < 3 try topo = load( '-mat', filename, ... [ 'comp' int2str(comps(k)) '_grid'], ... [ 'comp' int2str(comps(k)) '_x'], ... [ 'comp' int2str(comps(k)) '_y'] ); catch error( [ 'Cannot read file ''' filename '''' ]); end; elseif k == 1 try topo = load( '-mat', filename); catch error([ 'Missing scalp topography file - also necessary for ERP polarity' 10 'Try recomputing scalp topographies for components' ]); end; end; try, tmp = getfield(topo, [ 'comp' int2str(comps(k)) '_grid' ]); catch, error([ 'Empty scalp topography file - also necessary for ERP polarity' 10 'Try recomputing scalp topographies for components' ]); end; if strcmpi(option, 'gradient') [tmpx, tmpy] = gradient(tmp); % Gradient tmp = tmpx; tmp(:,:,2) = tmpy; elseif strcmpi(option, 'laplacian') tmp = del2(tmp); % Laplacian end; if length(comps) > 1 | strcmpi(mode, 'preclust') tmp = tmp(find(~isnan(tmp))); % remove NaN for more than 1 component end; if k == 1 X = zeros([ length(comps) size(tmp) ]) ; end X(k,:,:,:) = tmp; if k == 1 yi = getfield(topo, [ 'comp' int2str(comps(k)) '_y']); xi = getfield(topo, [ 'comp' int2str(comps(k)) '_x']); end; end X = squeeze(X); return; function filename = correctfile(filename, datasetpath) comp = computer; if filename(2) == ':' & ~strcmpi(comp(1:2), 'PC') filename = [filesep filename(4:end) ]; filename(find(filename == '\')) = filesep; end; if ~exist(filename) [tmpp tmpf ext] = fileparts(filename); if exist([tmpf ext]) filename = [tmpf ext]; else [tmpp2 tmpp1] = fileparts(tmpp); if exist(fullfile(tmpp1, [ tmpf ext ])) filename = fullfile(tmpp1, [ tmpf ext ]); else filename = fullfile(datasetpath, [ tmpf ext ]); if ~exist(filename) error([ 'Cannot load file ''' [ tmpf ext ] '''' ]); end; end; end; end;
github
ZijingMao/baselineeegtest-master
std_erspplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_erspplot.m
19,648
utf_8
cb3030aac38bf825bfc6510c39e5d9cc
% std_erspplot() - plot STUDY cluster ERSPs. Displays either mean cluster ERSPs, % or else all cluster component ERSPs plus the mean cluster % ERSP in one figure per condition. The ERSPs can be plotted % only if component ERSPs were computed and saved in the % EEG datasets in the STUDY. These may either 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_erspplot(STUDY, ALLEEG, key1, val1, key2, val2); % >> [STUDY erspdata ersptimes erspfreqs pgroup pcond pinter] = ... % std_erspplot(STUDY, ALLEEG ...); % % Inputs: % STUDY - STUDY set comprising some or all of the EEG datasets in ALLEEG. % ALLEEG - global vector of EEG structures for the datasets included % in the STUDY. ALLEEG for a STUDY set is typically created % using load_ALLEEG(). % either 'channels' or 'cluster' inputs are also mandatory. % % Optional inputs for channel plotting: % 'channels' - [numeric vector] specific channel group to plot. By % default, the grand mean channel ERSP is plotted (using the % same format as for the cluster component means described above) % '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 ERSP of all subjects. % 'noplot' - ['on'|'off'] When 'on', only return output values. Default % is 'off'. % % Optional inputs: % 'clusters' - [numeric vector|'all'] indices of clusters to plot. % If no component indices ('comps' below) are given, the average % ERSPs of the requested clusters are plotted in the same figure, % with ERSPs for different conditions (and groups if any) plotted % in different colors. In 'comps' (below) mode, ERSP for each % specified cluster are plotted in separate figures (one per % condition), each overplotting cluster component ERSP plus the % average cluster ERSP 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: % 'plotmode' - ['normal'|'condensed'|'none'] 'normal' -> plot in a new figure; % 'condensed' -> plot all curves in the current figure in a % condensed fashion. 'none' toggles off plotting {default: 'normal'} % 'key','val' - All optional inputs to pop_specparams() are also accepted here % to plot subset of time, statistics etc. The values used by default % are the ones set using pop_specparams() and stored in the % STUDY structure. % Output: % STUDY - the input STUDY set structure with the plotted cluster % mean ERSPs added to allow quick replotting % erspdata - [cell] ERSP data for each condition, group and subjects. % size of cell array is [nconds x ngroups]. Size of each element % is [freqs x times x subjects] for data channels or % [freqs x times x components] for component clusters. This % array may be gicen as input directly to the statcond() f % unction or std_stats() function to compute statistics. % ersptimes - [array] ERSP time point latencies. % erspfreqs - [array] ERSP point frequency values. % 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_erspplot(STUDY,ALLEEG, 'clusters', 'all', ... % 'mode', 'together'); % % Plot the mean ERSPs of all clusters in STUDY together % % on the same figure. % % Known limitations: when plotting multiple clusters, the output % contains the last plotted cluster. % % See also: pop_clustedit(), pop_preclust(), eeg_createdata(), eeg_preclust(), pop_clustedit() % % 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, allersp, alltimes, allfreqs, pgroup, pcond, pinter events] = std_erspplot(STUDY, ALLEEG, varargin) if nargin < 2 help std_erspstatplot; return; end; % find datatype and default options % --------------------------------- dtype = 'ersp'; for ind = 1:2:length(varargin) if strcmpi(varargin{ind}, 'datatype') dtype = varargin{ind+1}; end; end; if strcmpi(dtype, 'erpim') STUDY = pop_erpimparams(STUDY, varargin{:}); params = STUDY.etc.erpimparams; else STUDY = pop_erspparams( STUDY, varargin{:}); params = STUDY.etc.erspparams; end; % get parameters % -------------- 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 = { 'freqrange' []; 'topofreq' []; 'topotrial' []; 'singletrials' 'off' 'trialrange' [] 'concatenate' 'off'; 'colorlimits' []; 'ersplim' []; 'itclim' []; 'maskdata' 'off'; 'subbaseline' 'off' }; for ind=1:size(fields,1) if ~isfield(params, fields{ind,1}), params = setfield(params, fields{ind,1}, fields{ind,2}); end; end; % decode input parameters % ----------------------- options = mystruct(varargin); options = myrmfield( options, myfieldnames(params)); options = myrmfield( options, myfieldnames(stats)); options = myrmfield( options, { 'threshold' 'statistics' } ); % for backward compatibility [ opt moreparams ] = finputcheck( options, { ... 'design' 'integer' [] STUDY.currentdesign; 'caxis' 'real' [] []; 'statmode' 'string' [] ''; % deprecated 'channels' 'cell' [] {}; 'clusters' 'integer' [] []; 'datatype' 'string' { 'itc','ersp','pac' 'erpim' } 'ersp'; 'plottf' 'real' [] []; 'mode' 'string' [] ''; % for backward compatibility (now used for statistics) 'comps' {'integer','string'} [] []; % for backward compatibility 'plotsubjects' 'string' { 'on','off' } 'off'; 'noplot' 'string' { 'on','off' } 'off'; 'plotmode' 'string' { 'normal','condensed','none' } 'normal'; 'subject' 'string' [] '' }, ... 'std_erspstatplot', 'ignore'); if isstr(opt), error(opt); end; if strcmpi(opt.noplot, 'on'), opt.plotmode = 'none'; end; if isempty(opt.caxis), if strcmpi(opt.datatype, 'ersp') opt.caxis = params.ersplim; elseif strcmpi(opt.datatype, 'itc') && ~isempty(params.itclim) opt.caxis = [-params.itclim(end) params.itclim(end)]; end; end; 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.datatype, 'erpim'), params.topofreq = params.topotrial; opt.caxis = params.colorlimits; valunit = 'trials'; else valunit = 'Hz'; end; if isempty(opt.plottf) && ~isempty(params.topofreq) && ~isempty(params.topotime) && ~isnan(params.topofreq(1)) && ~isnan(params.topotime(1)) params.plottf = [ params.topofreq(1) params.topofreq(end) params.topotime(1) params.topotime(end) ]; else params.plottf = opt.plottf; end; %if strcmpi(opt.mode, 'comps'), opt.plotsubjects = 'on'; end; %deprecated 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'); end; end; if length(opt.comps) == 1 stats.condstats = 'off'; stats.groupstats = 'off'; disp('Statistics cannot be computed for single component'); 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 ]); plottfopt = { ... 'ersplim', opt.caxis, ... 'threshold', alpha, ... 'maskdata', params.maskdata }; if ~isempty(params.plottf) && length(opt.channels) < 5 warndlg2(strvcat('ERSP/ITC parameters indicate that you wish to plot scalp maps', 'Select at least 5 channels to plot topography')); return; end; % plot single scalp map % --------------------- if ~isempty(opt.channels) [STUDY allersp alltimes allfreqs tmp events unitPower] = std_readersp(STUDY, ALLEEG, 'channels', opt.channels, 'infotype', opt.datatype, 'subject', opt.subject, ... 'singletrials', stats.singletrials, 'subbaseline', params.subbaseline, 'timerange', params.timerange, 'freqrange', params.freqrange, 'design', opt.design, 'concatenate', params.concatenate); % select specific time and freq % ----------------------------- if ~isempty(params.plottf) if length(params.plottf) < 3, params.plottf(3:4) = params.plottf(2); params.plottf(2) = params.plottf(1); end; [tmp fi1] = min(abs(allfreqs-params.plottf(1))); [tmp fi2] = min(abs(allfreqs-params.plottf(2))); [tmp ti1] = min(abs(alltimes-params.plottf(3))); [tmp ti2] = min(abs(alltimes-params.plottf(4))); for index = 1:length(allersp(:)) allersp{index} = mean(mean(allersp{index}(fi1:fi2,ti1:ti2,:,:),1),2); allersp{index} = reshape(allersp{index}, [1 size(allersp{index},3) size(allersp{index},4) ]); end; % prepare channel neighbor matrix for Fieldtrip statstruct = std_prepare_neighbors(statstruct, ALLEEG, 'channels', opt.channels); stats.fieldtrip.channelneighbor = statstruct.etc.statistics.fieldtrip.channelneighbor; params.plottf = { params.plottf(1:2) params.plottf(3:4) }; [pcond pgroup pinter] = std_stat(allersp, stats); if (~isempty(pcond) && length(pcond{1}) == 1) || (~isempty(pgroup) && length(pgroup{1}) == 1), pcond = {}; pgroup = {}; pinter = {}; end; % single subject STUDY else [pcond pgroup pinter] = std_stat(allersp, stats); if (~isempty(pcond ) && (size( pcond{1},1) == 1 || size( pcond{1},2) == 1)) || ... (~isempty(pgroup) && (size(pgroup{1},1) == 1 || size(pgroup{1},2) == 1)), pcond = {}; pgroup = {}; pinter = {}; disp('No statistics possible for single subject STUDY'); end; % single subject STUDY end % plot specific channel(s) % ------------------------ if ~strcmpi(opt.plotmode, 'none') locs = eeg_mergelocs(ALLEEG.chanlocs); locs = locs(std_chaninds(STUDY, opt.channels)); if ~isempty(params.plottf) alltitles = std_figtitle('threshold', alpha, 'mcorrect', mcorrect, 'condstat', stats.condstats, 'cond2stat', stats.groupstats, ... 'statistics', method, 'condnames', allconditions, 'cond2names', allgroups, 'chanlabels', { locs.labels }, ... 'subject', opt.subject, 'valsunit', { valunit 'ms' }, 'vals', params.plottf, 'datatype', upper(opt.datatype)); std_chantopo(allersp, 'groupstats', pgroup, 'condstats', pcond, 'interstats', pinter, 'caxis', opt.caxis, ... 'chanlocs', locs, 'threshold', alpha, 'titles', alltitles); else if length(opt.channels) > 1 & ~strcmpi(opt.plotmode, 'none'), figure; opt.plotmode = 'condensed'; end; nc = ceil(sqrt(length(opt.channels))); nr = ceil(length(opt.channels)/nc); for index = 1:max(cellfun(@(x)(size(x,3)), allersp(:))) if length(opt.channels) > 1, try, subplot(nr,nc,index, 'align'); catch, subplot(nr,nc,index); end; end; tmpersp = cell(size(allersp)); for ind = 1:length(allersp(:)) if ~isempty(allersp{ind}) tmpersp{ind} = squeeze(allersp{ind}(:,:,index,:)); end; end; alltitles = std_figtitle('threshold', alpha, 'mcorrect', mcorrect, 'condstat', stats.condstats, 'cond2stat', stats.groupstats, ... 'statistics', method, 'condnames', allconditions, 'cond2names', allgroups, 'chanlabels', { locs(index).labels }, ... 'subject', opt.subject, 'datatype', upper(opt.datatype), 'plotmode', opt.plotmode); std_plottf(alltimes, allfreqs, tmpersp, 'datatype', opt.datatype, 'titles', alltitles, ... 'groupstats', pgroup, 'condstats', pcond, 'interstats', pinter, 'plotmode', ... opt.plotmode, 'unitcolor', unitPower, 'chanlocs', ALLEEG(1).chanlocs, 'events', events, plottfopt{:}); end; end; end; else if length(opt.clusters) > 1 & ~strcmpi(opt.plotmode, 'none'), figure; opt.plotmode = 'condensed'; end; nc = ceil(sqrt(length(opt.clusters))); nr = ceil(length(opt.clusters)/nc); comp_names = {}; if length(opt.clusters) > 1 && ( strcmpi(stats.condstats, 'on') || strcmpi(stats.groupstats, 'on')) stats.condstats = 'off'; stats.groupstats = 'off'; end; for index = 1:length(opt.clusters) [STUDY allersp alltimes allfreqs tmp events unitPower] = std_readersp(STUDY, ALLEEG, 'clusters', opt.clusters(index), 'infotype', opt.datatype, ... 'component', opt.comps, 'singletrials', stats.singletrials, 'subbaseline', params.subbaseline, 'timerange', params.timerange, 'freqrange', params.freqrange, 'design', opt.design, 'concatenate', params.concatenate); if length(opt.clusters) > 1, try, subplot(nr,nc,index, 'align'); catch, subplot(nr,nc,index); end; 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; % select specific time and freq % ----------------------------- if ~isempty(params.plottf) if length(params.plottf) < 3, params.plottf(3:4) = params.plottf(2); params.plottf(2) = params.plottf(1); end; [tmp fi1] = min(abs(allfreqs-params.plottf(1))); [tmp fi2] = min(abs(allfreqs-params.plottf(2))); [tmp ti1] = min(abs(alltimes-params.plottf(3))); [tmp ti2] = min(abs(alltimes-params.plottf(4))); for index = 1:length(allersp(:)) allersp{index} = mean(mean(allersp{index}(fi1:fi2,ti1:ti2,:,:),1),2); allersp{index} = reshape(allersp{index}, [1 size(allersp{index},3) size(allersp{index},4) ]); end; end [pcond pgroup pinter] = std_stat(allersp, stats); % plot specific component % ----------------------- if index == length(opt.clusters), opt.legend = 'on'; end; if ~strcmpi(opt.plotmode, 'none') alltitles = std_figtitle('threshold', alpha, '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, 'datatype', upper(opt.datatype), 'plotmode', opt.plotmode); std_plottf(alltimes, allfreqs, allersp, 'datatype', opt.datatype, ... 'groupstats', pgroup, 'condstats', pcond, 'interstats', pinter, 'plotmode', ... opt.plotmode, 'titles', alltitles, ... 'events', events, 'unitcolor', unitPower, 'chanlocs', ALLEEG(1).chanlocs, plottfopt{:}); end; end; 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_readtopoclust.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readtopoclust.m
4,978
utf_8
d3ea827af1511d8ae06298bd66565857
% std_readtopoclust() - Compute and return cluster component scalp maps. % Automatically inverts the polarity of component scalp maps % to best match the polarity of the cluster mean scalp map. % Usage: % >> [STUDY clsstruct] = std_readtopoclust(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. % clusters - cluster numbers to read. % % Outputs: % STUDY - the input STUDY set structure with the computed mean cluster scalp % map added (unless cluster scalp map means already exist in the STUDY) % to allow quick replotting. % clsstruct - STUDY.cluster structure array for the modified clusters. % % See also std_topoplot(), pop_clustedit() % % Authors: Arnaud Delorme, SCCN, INC, UCSD, 2007 % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, June 07, 2007, [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, centroid] = std_readtopoclust(STUDY,ALLEEG, clsind); if nargin < 3 help readtopoclust; return; end; if isempty(clsind) for k = 2: length(STUDY.cluster) % don't include the ParentCluster if ~strncmpi('Notclust',STUDY.cluster(k).name,8) % don't include 'Notclust' clusters clsind = [clsind k]; end end end Ncond = length(STUDY.condition); if Ncond == 0 Ncond = 1; end centroid = cell(length(clsind),1); fprintf('Computing the requested mean cluster scalp maps (only done once)\n'); if ~isfield( STUDY.cluster, 'topo' ), STUDY.cluster(1).topo = []; end; cond = 1; for clust = 1:length(clsind) %go over all requested clusters if isempty( STUDY.cluster(clsind(clust)).topo ) numitems = length(STUDY.cluster(clsind(clust)).comps); for k = 1:numitems % go through all components comp = STUDY.cluster(clsind(clust)).comps(k); abset = STUDY.cluster(clsind(clust)).sets(cond,k); if ~isnan(comp) & ~isnan(abset) [grid yi xi] = std_readtopo(ALLEEG, abset, comp); if ~isfield(centroid{clust}, 'topotmp') || isempty(centroid{clust}.topotmp) centroid{clust}.topotmp = zeros([ size(grid(1:4:end),2) numitems ]); end; centroid{clust}.topotmp(:,k) = grid(1:4:end); % for inversion centroid{clust}.topo{k} = grid; centroid{clust}.topox = xi; centroid{clust}.topoy = yi; end end fprintf('\n'); %update STUDY tmpinds = find(isnan(centroid{clust}.topotmp(:,1))); %centroid{clust}.topotmp(tmpinds,:) = []; %for clust = 1:length(clsind) %go over all requested clusters for cond = 1 if clsind(1) > 0 ncomp = length(STUDY.cluster(clsind(clust)).comps); end; [ tmp pol ] = std_comppol(centroid{clust}.topotmp); fprintf('%d/%d polarities inverted while reading component scalp maps\n', ... length(find(pol == -1)), length(pol)); nitems = length(centroid{clust}.topo); for k = 1:nitems centroid{clust}.topo{k} = pol(k)*centroid{clust}.topo{k}; if k == 1, allscalp = centroid{clust}.topo{k}/nitems; else allscalp = centroid{clust}.topo{k}/nitems + allscalp; end; end; STUDY.cluster(clsind(clust)).topox = centroid{clust}.topox; STUDY.cluster(clsind(clust)).topoy = centroid{clust}.topoy; STUDY.cluster(clsind(clust)).topoall = centroid{clust}.topo; STUDY.cluster(clsind(clust)).topo = allscalp; STUDY.cluster(clsind(clust)).topopol = pol; end %end else centroid{clust}.topox = STUDY.cluster(clsind(clust)).topox; centroid{clust}.topoy = STUDY.cluster(clsind(clust)).topoy; centroid{clust}.topo = STUDY.cluster(clsind(clust)).topoall; end; end fprintf('\n');
github
ZijingMao/baselineeegtest-master
std_readcustom.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_readcustom.m
5,376
utf_8
ab9dee0bfcae0ccce1ff1c97d5d14089
% std_readcustom() - Read custom data structure for file save on disk. % % Usage: % >> data = std_readcustom(STUDY, ALLEEG, fileext, 'key', 'val', ...); % % Required inputs: % STUDY - an EEGLAB STUDY set of loaded EEG structures % ALLEEG - ALLEEG vector of one or more loaded EEG dataset structures % fileext - [string] file extension (without '.') % % Optional inputs: % 'design' - [integer] use specific study index design to compute measure. % Default is to use the default design. % 'datafield' - [string or cell] extract only specific variables from the data % files. By default, all fields are loaded. Use '*' to match % patterns. If more than 1 variable is selected, data is % placed in a structure named data. % 'eegfield' - [string] copy data to a field of an EEG structure and return % EEG structure. Default is to return the data itself. % 'eegrmdata' - ['on'|'off'] when option above is used, remove data from % EEG structures before returning them. Default is 'on'. % % Outputs: % data - cell array containing data organized according to the selected % design. % % Example: % % assuming ERP have been computed for the currently selected design % data = std_readcustom(STUDY, ALLEEG, 'daterp', 'datafield', 'chan1'); % data = cellfun(@(x)x', siftdata, 'uniformoutput', false); % transpose data % std_plotcurve([1:size(data{1})], data); % plot data % % Authors: Arnaud Delorme, SCCN, INC, UCSD, 2013- % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, 2013, [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 [ returndata ] = std_readcustom(STUDY, ALLEEG, fileext, varargin) if nargin < 2 help std_sift; return; end; [g arguments] = finputcheck(varargin, { 'design' 'integer' [] STUDY.currentdesign; 'datafield' { 'string' 'cell' } [] {}; 'eegfield' 'string' [] ''; 'eegrmdata' 'string' { 'on' 'off' } 'on' }, 'std_sift', 'mode', 'ignore'); if isstr(g), error(g); end; if ~iscell(g.datafield), g.datafield = { g.datafield }; end; % Scan design and save data % ------------------------- nc = max(length(STUDY.design(g.design).variable(1).value),1); ng = max(length(STUDY.design(g.design).variable(2).value),1); for cInd = 1:nc for gInd = 1:ng % find the right cell in the design cellInds = []; for index = 1:length(STUDY.design(g.design).cell) condind = std_indvarmatch( STUDY.design(g.design).cell(index).value{1}, STUDY.design(g.design).variable(1).value); grpind = std_indvarmatch( STUDY.design(g.design).cell(index).value{2}, STUDY.design(g.design).variable(2).value); if isempty(STUDY.design(g.design).variable(1).value), condind = 1; end; if isempty(STUDY.design(g.design).variable(2).value), grpind = 1; end; if cInd == condind && gInd == grpind cellInds = [ cellInds index ]; end; end; desset = STUDY.design(g.design).cell(cellInds); clear EEGTMP data; for iDes = 1:length(desset) % load data on disk tmpData = load('-mat', [ STUDY.design(g.design).cell(cellInds(iDes)).filebase '.' fileext ], g.datafield{:}); % put data in EEG structure if necessary if ~isempty(g.eegfield) EEGTMPTMP = std_getdataset(STUDY, ALLEEG, 'design', g.design, 'cell', cellInds(iDes)); if strcmpi(g.eegrmdata, 'on'), EEGTMPTMP.data = []; EEGTMPTMP.icaact = []; end; EEGTMPTMP.(g.eegfield) = tmpData; EEGTMP(iDes) = EEGTMPTMP; elseif length(g.datafield) == 1 if ~isstr(tmpData.(g.datafield{1})), error('Field content cannot be a string'); end; data(iDes,:,:,:) = tmpData.(g.datafield{1}); elseif isfield(tmpData, 'data') && isempty(g.datafield) data(iDes,:,:,:) = tmpData.data; else data(iDes) = tmpData; end; end; data = shiftdim(data,1); if ~isempty(g.eegfield) returndata{cInd,gInd} = EEGTMP; else returndata{cInd,gInd} = data; end; end; end;
github
ZijingMao/baselineeegtest-master
std_ersp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_ersp.m
20,553
utf_8
41dd4eed5c09acca4f4c7b9a30289ea8
% std_ersp() - Compute ERSP and/or ITC transforms for ICA components % or data channels of a dataset. Save results into Matlab % float files. % % Function description: % The function computes the mean ERSP or ITC for the selected % dataset ICA components or data channels in the requested % frequency range and time window (the two are dependent). % Frequencies are equally log spaced. Options specify component % numbers, desired frequency range, time window length, % frequency resolution, significance level, and wavelet % cycles. See >> help newtimef and >> timef details % % Two Matlab files are saved (for ERSP and ITC). These contain % the ERSP|ITC image, plus the transform parameters % used to compute them. Saves the computed dataset mean images % in dataset-name files with extensions '.icaersp' and '.icaitc' % for ICA components or '.datersp', '.datitc' for data channels. % Usage: % >> [X times logfreqs ] = std_ersp(EEG, 'key', 'val', ...); % Inputs: % EEG - a loaded epoched EEG dataset structure. May be an array % of such structure containing several datasets. % % Other inputs: % 'trialindices' - [cell array] indices of trials for each dataset. % Default is EMPTY (no trials). NEEDS TO BE SET. % '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. % '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. % 'savefile' - ['on'|'off'] save file or simply return measures. % Default is to save files ('on'). % 'getparams' - ['on'|'off'] return optional parameters for the newtimef % function (and do not compute anything). This argument is % obsolete (default is 'off'). % % ERSP optional inputs: % 'type' - ['ersp'|'itc'|'ersp&itc'] save ERSP, ITC, or both data % types to disk {default: 'ersp'} % 'freqs' - [minHz maxHz] the ERSP/ITC frequency range to compute % and return. {default: 3 to EEG sampling rate divided by 3} % 'timelimits' - [minms maxms] time window (in ms) to compute. % {default: whole input epoch}. % '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]} % '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). % 'alpha' - If in (0, 1), compute two-tailed permutation-based % probability thresholds and use these to mask the output % ERSP/ITC images {default: NaN} % 'powbase' - [ncomps,nfreqs] optional input matrix giving baseline power % spectra (not dB power, see >> help timef). % For use in repeated calls to timef() using the same baseine % {default|[] -> none; data windows centered before 0 latency} % % Other optional inputs: % This function will take any of the newtimef() optional inputs (for instance % to compute log-space frequencies)... % % Outputs: % X - the masked log ERSP/ITC of the requested ICA components/channels % in the selected frequency and time range. Note that for % optimization reasons, this parameter is now empty or 0. X % thus must be read from the datafile saved on disk. % times - vector of time points for which the ERSPs/ITCs were computed. % logfreqs - vector of (equally log spaced) frequencies (in Hz) at which the % log ERSP/ITC was evaluated. % parameters - parameters given as input to the newtimef function. % % Files written or modified: % [dataset_filename].icaersp <-- saved component ERSPs % [dataset_filename].icaitc <-- saved component ITCs % [dataset_filename].icatimef <-- saved component single % trial decompositions. % OR for channels % [dataset_filename].datersp <-- saved channel ERSPs % [dataset_filename].datitc <-- saved channel ITCs % [dataset_filename].dattimef <-- saved channel single % trial decompositions. % Example: % % Create mean ERSP and ITC images on disk for all comps from % % dataset EEG use three-cycle wavelets (at 3 Hz) to more than % % three-cycle wavelets at 50 Hz. See >> help newtimef % % Return the (equally log-freq spaced, probability-masked) ERSP. % >> [Xersp, times, logfreqs] = std_ersp(EEG, ... % 'type', 'ersp', 'freqs', [3 50], 'cycles', [3 0.5]); % % See also: timef(), std_itc(), std_erp(), std_spec(), std_topo(), std_preclust() % % Authors: Arnaud Delorme, Hilit Serby, SCCN, INC, UCSD, January, 2005- % 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, times, logfreqs, parameters] = std_ersp(EEG, varargin) if nargin < 1 help std_ersp; return; end; X = []; options = {}; if length(varargin) > 1 if ~isstr(varargin{1}) if length(varargin) > 0, options = { options{:} 'components' varargin{1} }; end; if length(varargin) > 1, options = { options{:} 'freqs' varargin{2} }; end; if length(varargin) > 2, options = { options{:} 'timewindow' varargin{3} }; end; if length(varargin) > 3, options = { options{:} 'cycles' varargin{4} }; end; if length(varargin) > 4, options = { options{:} 'padratio' varargin{5} }; end; if length(varargin) > 5, options = { options{:} 'alpha' varargin{6} }; end; if length(varargin) > 6, options = { options{:} 'type' varargin{7} }; end; if length(varargin) > 7, options = { options{:} 'powbase' varargin{8} }; end; else options = varargin; end; end; [g timefargs] = finputcheck(options, { ... 'components' 'integer' [] []; 'channels' { 'cell','integer' } { [] [] } {}; 'powbase' 'real' [] []; 'trialindices' { 'integer','cell' } [] []; 'savetrials' 'string' { 'on','off' } 'off'; 'plot' 'string' { 'on','off' } 'off'; % not documented for debugging purpose 'recompute' 'string' { 'on','off' } 'off'; 'getparams' 'string' { 'on','off' } 'off'; 'savefile' 'string' { 'on','off' } 'on'; 'timewindow' 'real' [] []; % ignored, deprecated 'fileout' 'string' [] ''; 'timelimits' 'real' [] [EEG(1).xmin EEG(1).xmax]*1000; 'cycles' 'real' [] [3 .5]; 'padratio' 'real' [] 1; 'freqs' 'real' [] [0 EEG(1).srate/2]; 'rmcomps' 'cell' [] cell(1,length(EEG)); 'interp' 'struct' { } struct([]); 'freqscale' 'string' [] 'log'; 'alpha' 'real' [] NaN; 'type' 'string' { 'ersp','itc','both','ersp&itc' } 'both'}, 'std_ersp', 'ignore'); if isstr(g), error(g); end; if isempty(g.trialindices), g.trialindices = cell(length(EEG)); end; if ~iscell(g.trialindices), g.trialindices = { g.trialindices }; end; % checking input parameters % ------------------------- if isempty(g.components) & isempty(g.channels) if isempty(EEG(1).icaweights) error('EEG.icaweights not found'); end g.components = 1:size(EEG(1).icaweights,1); disp('Computing ERSP with default values for all components of the dataset'); end % select ICA components or data channels % -------------------------------------- if isempty(g.fileout), g.fileout = fullfile(EEG(1).filepath, EEG(1).filename(1:end-4)); end; if ~isempty(g.components) g.indices = g.components; prefix = 'comp'; filenameersp = [ g.fileout '.icaersp' ]; filenameitc = [ g.fileout '.icaitc' ]; filenametrials = [ g.fileout '.icatimef' ]; if ~isempty(g.channels) error('Cannot compute ERSP/ITC for components and channels at the same time'); end; elseif ~isempty(g.channels) if iscell(g.channels) if ~isempty(g.interp) g.indices = eeg_chaninds(g.interp, g.channels, 0); else g.indices = eeg_chaninds(EEG(1), g.channels, 0); for ind = 2:length(EEG) if ~isequal(eeg_chaninds(EEG(ind), g.channels, 0), g.indices) error([ 'Channel information must be consistant when ' 10 'several datasets are merged for a specific design' ]); end; end; end; else g.indices = g.channels; end; prefix = 'chan'; filenameersp = [ g.fileout '.datersp' ]; filenameitc = [ g.fileout '.datitc' ]; filenametrials = [ g.fileout '.dattimef' ]; end; powbaseexist = 1; % used also later if isempty(g.powbase) | isnan(g.powbase) powbaseexist = 0; g.powbase = NaN*ones(length(g.indices),1); % default for timef() end; if size(g.powbase,1) ~= length(g.indices) error('powbase should be of size (ncomps,nfreqs)'); end % Check if ERSP/ITC information found in datasets and if fits requested parameters % ---------------------------------------------------------------------------- if exist( filenameersp ) & strcmpi(g.recompute, 'off') fprintf('Use existing file for ERSP: %s\n', filenameersp); return; end; % tmpersp = load( '-mat', filenameersp, 'parameters'); % AND IT SHOULD BE USED HERE TOO - ARNO % params = struct(tmpersp.parameters{:}); % if ~isequal(params.cycles, g.cycles) ... % | (g.padratio ~= params.padratio) ... % | ( (g.alpha~= params.alpha) & ~( isnan(g.alpha) & isnan(params.alpha)) ) % % if not computed with the requested parameters, recompute ERSP/ITC % % i.e., continue % else % disp('File ERSP/ITC data already present, computed with the same parameters: no need to recompute...'); % return; % no need to compute ERSP/ITC % end %end; % Compute ERSP parameters % ----------------------- parameters = { 'cycles', g.cycles, 'padratio', g.padratio, ... 'alpha', g.alpha, 'freqscale', g.freqscale, timefargs{:} }; defaultlowfreq = 3; [time_range] = compute_ersp_times(g.cycles, EEG(1).srate, ... [EEG(1).xmin EEG(1).xmax]*1000 , defaultlowfreq, g.padratio); if time_range(1) < time_range(2) && g.freqs(1) == 0 g.freqs(1) = defaultlowfreq; % for backward compatibility end parameters = { parameters{:} 'freqs' g.freqs }; if strcmpi(g.plot, 'off') parameters = { parameters{:} 'plotersp', 'off', 'plotitc', 'off', 'plotphase', 'off' }; end; if powbaseexist & time_range(1) >= 0 parameters{end+1} = 'baseboot'; parameters{end+1} = 0; fprintf('No pre-0 baseline spectral estimates: Using whole epoch for timef() "baseboot"\n'); end % return parameters % ----------------- if strcmpi(g.getparams, 'on') X = []; times = []; logfreqs = []; if strcmpi(g.savetrials, 'on') parameters = { parameters{:} 'savetrials', g.savetrials }; end; return; end; % No usable ERSP/ITC information available % --------------------------------- % tmpdata = []; % for index = 1:length(EEG) % if isstr(EEG(index).data) % TMP = eeg_checkset( EEG(index), 'loaddata' ); % load EEG.data and EEG.icaact % else % TMP = EEG; % end % if ~isempty(g.components) % if isempty(TMP.icaact) % make icaact if necessary % TMP.icaact = (TMP.icaweights*TMP.icasphere)* ... % reshape(TMP.data(TMP.icachansind,:,:), [ length(TMP.icachansind) size(TMP.data,2)*size(TMP.data,3) ]); % end; % tmpdata = reshape(TMP.icaact, [ size(TMP.icaact,1) size(TMP.data,2) size(TMP.data,3) ]); % tmpdata = tmpdata(g.indices, :,:); % else % if isempty(tmpdata) % tmpdata = TMP.data(g.indices,:,:); % else % tmpdata(:,:,end+1:end+size(TMP.data,3)) = TMP.data(g.indices,:,:); % end; % end; % end; 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 = eeg_getdatact(EEG, 'component', g.indices, 'trialindices', g.trialindices ); else X = eeg_getdatact(EEG, 'channel' , g.indices, 'trialindices', g.trialindices, 'rmcomps', g.rmcomps, 'interp', g.interp); end; % frame range % ----------- pointrange1 = round(max((g.timelimits(1)/1000-EEG(1).xmin)*EEG(1).srate, 1)); pointrange2 = round(min(((g.timelimits(2)+1000/EEG(1).srate)/1000-EEG(1).xmin)*EEG(1).srate, EEG(1).pnts)); pointrange = [pointrange1:pointrange2]; % Compute ERSP & ITC % ------------------ all_ersp = []; all_trials = []; all_itc = []; for k = 1:length(g.indices) % for each (specified) component if k>size(X,1), break; end; % happens for components if powbaseexist tmpparams = parameters; tmpparams{end+1} = 'powbase'; tmpparams{end+1} = g.powbase(k,:); else tmpparams = parameters; end; % Run timef() to get ERSP % ------------------------ timefdata = reshape(X(k,pointrange,:), 1, length(pointrange)*size(X,3)); if strcmpi(g.plot, 'on'), figure; end; flagEmpty = 0; if isempty(timefdata) flagEmpty = 1; timefdata = rand(1,length(pointrange)); end; [logersp,logitc,logbase,times,logfreqs,logeboot,logiboot,alltfX] ... = newtimef( timefdata, length(pointrange), g.timelimits, EEG(1).srate, tmpparams{2:end}); %figure; newtimef( TMP.data(32,:), EEG.pnts, [EEG.xmin EEG.xmax]*1000, EEG.srate, cycles, 'freqs', freqs); %figure; newtimef( timefdata, length(pointrange), g.timelimits, EEG.srate, cycles, 'freqs', freqs); if flagEmpty logersp = []; logitc = []; logbase = []; logeboot = []; logiboot = []; alltfX = []; end; if strcmpi(g.plot, 'on'), return; end; all_ersp = setfield( all_ersp, [ prefix int2str(g.indices(k)) '_ersp' ], single(logersp )); all_ersp = setfield( all_ersp, [ prefix int2str(g.indices(k)) '_erspbase' ], single(logbase )); all_ersp = setfield( all_ersp, [ prefix int2str(g.indices(k)) '_erspboot' ], single(logeboot)); all_itc = setfield( all_itc , [ prefix int2str(g.indices(k)) '_itc' ], single(logitc )); all_itc = setfield( all_itc , [ prefix int2str(g.indices(k)) '_itcboot' ], single(logiboot)); if strcmpi(g.savetrials, 'on') all_trials = setfield( all_trials, [ prefix int2str(g.indices(k)) '_timef' ], single( alltfX )); end; end X = logersp; % Save ERSP into file % ------------------- all_ersp.freqs = logfreqs; all_ersp.times = times; all_ersp.datatype = 'ERSP'; all_ersp.datafiles = computeFullFileName( { EEG.filepath }, { EEG.filename }); all_ersp.datatrials = g.trialindices; all_itc.freqs = logfreqs; all_itc.times = times; all_itc.parameters = parameters; all_itc.datatype = 'ITC'; all_itc.datafiles = computeFullFileName( { EEG.filepath }, { EEG.filename }); all_itc.datatrials = g.trialindices; all_trials.freqs = logfreqs; all_trials.times = times; all_trials.parameters = { options{:} parameters{:} }; all_trials.datatype = 'TIMEF'; all_trials.datafiles = computeFullFileName( { EEG.filepath }, { EEG.filename }); all_trials.datatrials = g.trialindices; if powbaseexist all_ersp.parameters = { parameters{:}, 'baseline', g.powbase }; else all_ersp.parameters = parameters; end; if ~isempty(g.channels) if ~isempty(g.interp) all_ersp.chanlabels = { g.interp(g.indices).labels }; all_itc.chanlabels = { g.interp(g.indices).labels }; all_trials.chanlabels = { g.interp(g.indices).labels }; elseif ~isempty(EEG(1).chanlocs) tmpchanlocs = EEG(1).chanlocs; all_ersp.chanlabels = { tmpchanlocs(g.indices).labels }; all_itc.chanlabels = { tmpchanlocs(g.indices).labels }; all_trials.chanlabels = { tmpchanlocs(g.indices).labels }; end; end; if strcmpi(g.savefile, 'on') if strcmpi(g.type, 'both') | strcmpi(g.type, 'ersp') | strcmpi(g.type, 'ersp&itc') std_savedat( filenameersp, all_ersp); end; if strcmpi(g.type, 'both') | strcmpi(g.type, 'itc') | strcmpi(g.type, 'ersp&itc') std_savedat( filenameitc , all_itc ); end; if strcmpi(g.savetrials, 'on') std_savedat( filenametrials , all_trials ); 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_setcomps2cell.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_setcomps2cell.m
3,998
utf_8
6f637e1842fe051b8c6772049b76f035
% std_setcomps2cell - 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 setinds allinds ] = std_setcomps2cell(STUDY, clustind); % [ struct setinds allinds ] = std_setcomps2cell(STUDY, sets, comps); % [ struct setinds allinds measurecell] = std_setcomps2cell(STUDY, sets, comps, measure); % % 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 setinds allinds measurecell] = std_setcomps2cell(STUDY, sets, comps, measure, generateerror) if nargin < 5 generateerror = 0; end; if nargin == 4 && length(measure) == 1 generateerror = measure; measure = []; end; if nargin < 3 tmpstruct = STUDY.cluster(sets); sets = tmpstruct.sets; comps = tmpstruct.comps; % old format else tmpstruct = []; end; if nargin < 4 || isempty(measure) measure = comps; end; measure = repmat(measure, [size(sets,1) 1]); comps = repmat(comps , [size(sets,1) 1]); oldsets = sets; sets = reshape(sets , 1, size(sets ,1)*size(sets ,2)); measure = reshape(measure, 1, size(measure,1)*size(measure,2)); comps = reshape(comps , 1, size(comps ,1)*size(comps ,2)); % get indices for all groups and conditions % ----------------------------------------- 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); allinds = cell( nc, ng ); setinds = cell( nc, ng ); measurecell = 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; % get the position in sets where the dataset is % if several datasets check that they all have the same % ICA and component index % ----------------------- datind = setinfo(index).dataset; ind = find(datind(1) == sets); if ~isempty(ind) && length(datind) > 1 [ind1 ind2] = find(datind(1) == oldsets); columnica = oldsets(:,ind2(1)); if ~all(ismember(datind, columnica)); disp('Warning: STUDY design combines datasets with different ICA - use ICA only for artifact rejection'); end; end; measurecell{ condind, grpind } = [ measurecell{ condind, grpind } measure(ind) ]; allinds{ condind, grpind } = [ allinds{ condind, grpind } comps( ind) ]; setinds{ condind, grpind } = [ setinds{ condind, grpind } repmat(index, [1 length(ind)]) ]; end; tmpstruct.allinds = allinds; tmpstruct.setinds = setinds; if generateerror && isempty(setinds{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;
github
ZijingMao/baselineeegtest-master
pop_study.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_study.m
32,127
utf_8
5cba10c4d5dd87706b4d34e32c1c98c0
% pop_study() - create a new STUDY set structure defining a group of related EEG datasets. % The STUDY set also contains information about each of the datasets: the % subject code, subject group, experimental condition, and session. This can % be provided interactively in a pop-up window or be automatically filled % in by the function. Defaults: Assume a different subject for each % dataset and only one condition; leave subject group and session fields % empty. Additional STUDY information about the STUDY name, task and % miscellaneous notes can also be saved in the STUDY structure. % Usage: % >> [ STUDY ALLEEG ] = pop_study([],[], 'gui', 'on'); % create new study interactively % >> [ STUDY ALLEEG ] = pop_study(STUDY, ALLEEG, 'gui', 'on'); % edit study interactively % >> [ STUDY ALLEEG ] = pop_study(STUDY, ALLEEG, 'key', 'val', ...); % edit study % % Optional Inputs: % STUDY - existing study structure. % ALLEEG - vector of EEG dataset structures to be included in the STUDY. % % Optional Inputs: % All "'key', 'val'" inputs of std_editset() may be used. % % Outputs: % STUDY - new STUDY set comprising some or all of the datasets in % ALLEEG, plus other information about the experiments. % ALLEEG - an updated ALLEEG structure including the STUDY datasets. % % Graphic interface buttons: % "STUDY set name" - [edit box] name for the STUDY structure {default: ''} % "STUDY set task name" - [edit box] name for the task performed by the subject {default: ''} % "STUDY set notes" - [edit box] notes about the experiment, the datasets, the STUDY, % or anything else to store with the rest of the STUDY information % {default: ''} % "subject" - [edit box] subject code associated with the dataset. If no % subject code is provided, each dataset will assumed to be from % a different subject {default: 'S1', 'S2', ..., 'Sn'} % "session" - [edit box] dataset session. If no session information is % provided, all datasets that belong to one subject are assumed to % have been recorded within one session {default: []} % "condition" - [edit box] dataset condition. If no condition code is provided, % all datasets are assumed to be from the same condition {default:[]} % "group" - [edit box] the subject group the dataset belongs to. If no group % is provided, all subjects and datasets are assumed to belong to % the same group. {default: []} % "Save this STUDY set to disk file" - [check box] If checked, save the new STUDY set % structure to disk. If no filename is provided, a window will % pop up to ask for it. % % See also: std_editset, pop_loadstudy(), pop_preclust(), pop_clust() % % Authors: Arnaud Delorme, Hilit Serby, Scott Makeig, SCCN, INC, UCSD, July 22, 2005 % Copyright (C) Arnaud Delorme, SCCN, INC, UCSD, July 22, 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_study(STUDY, ALLEEG, varargin) com = ''; if nargin < 1 help pop_study; return; end % type of call (gui, script or internal) % -------------------------------------- mode = 'internal_command'; if ~isstr(STUDY) %intial settings mode = 'script'; if nargin > 2 for index = 1:length(varargin) if isstr(varargin{index}) if strcmpi(varargin{index}, 'gui') mode = 'gui'; end; end; end; end; end; if isempty(STUDY) newstudy = 1; STUDY.name = ''; STUDY.task = ''; STUDY.notes = ''; STUDY.filename = ''; STUDY.cluster = []; STUDY.history = 'STUDY = [];'; else newstudy = 0; end; if strcmpi(mode, 'script') % script mode [STUDY ALLEEG] = std_editset(STUDY, ALLEEG, varargin{:}); return; elseif strcmpi(mode, 'gui') % GUI mode % show warning if necessary % ------------------------- if isreal(ALLEEG) if ALLEEG == 0 res = questdlg2( strvcat('Datasets currently loaded will be removed from EEGLAB memory.', ... 'Are you sure you want to continue?'), ... 'Discard loaded EEGLAB datasets?', 'Cancel', 'Yes', 'Yes'); if strcmpi(res, 'cancel'), return; end; end; ALLEEG = []; end; % set initial datasetinfo % ----------------------- if isfield(STUDY, 'datasetinfo') datasetinfo = STUDY.datasetinfo; different = 0; for k = 1:length(ALLEEG) if ~strcmpi(datasetinfo(k).filename, ALLEEG(k).filename), different = 1; break; end; if ~strcmpi(datasetinfo(k).subject, ALLEEG(k).subject), different = 1; break; end; if ~strcmpi(datasetinfo(k).condition, ALLEEG(k).condition), different = 1; break; end; if ~strcmpi(char(datasetinfo(k).group), char(ALLEEG(k).group)), different = 1; break; end; if datasetinfo(k).session ~= ALLEEG(k).session, different = 1; break; end; end if different info = 'from_STUDY_different_from_ALLEEG'; else info = 'from_STUDY'; end; if ~isfield(datasetinfo, 'comps'); datasetinfo(1).comps = []; end; else info = 'from_ALLEEG'; if length(ALLEEG) > 0 datasetinfo(length(ALLEEG)).filename = []; datasetinfo(length(ALLEEG)).filepath = []; datasetinfo(length(ALLEEG)).subject = []; datasetinfo(length(ALLEEG)).session = []; datasetinfo(length(ALLEEG)).condition = []; datasetinfo(length(ALLEEG)).group = []; for k = 1:length(ALLEEG) datasetinfo(k).filename = ALLEEG(k).filename; datasetinfo(k).filepath = ALLEEG(k).filepath; datasetinfo(k).subject = ALLEEG(k).subject; datasetinfo(k).session = ALLEEG(k).session; datasetinfo(k).condition = ALLEEG(k).condition; datasetinfo(k).group = ALLEEG(k).group; end if ~isfield(datasetinfo, 'comps'); datasetinfo(1).comps = []; end; else datasetinfo = []; end; end; nextpage = 'pop_study(''nextpage'', gcbf);'; prevpage = 'pop_study(''prevpage'', gcbf);'; delset = 'pop_study(''clear'', gcbf, get(gcbo, ''userdata''));'; loadset = 'pop_study(''load'', gcbf, get(guiind, ''userdata''), get(guiind, ''string'')); clear guiind;'; loadsetedit = [ 'guiind = gcbo;' loadset ]; subcom = 'pop_study(''subject'' , gcbf, get(gcbo, ''userdata''), get(gcbo, ''string''));'; sescom = 'pop_study(''session'' , gcbf, get(gcbo, ''userdata''), get(gcbo, ''string''));'; condcom = 'pop_study(''condition'', gcbf, get(gcbo, ''userdata''), get(gcbo, ''string''));'; grpcom = 'pop_study(''group'' , gcbf, get(gcbo, ''userdata''), get(gcbo, ''string''));'; compcom = 'pop_study(''component'', gcbf, get(gcbo, ''userdata''), get(gcbo, ''string''));'; cb_del = 'pop_study(''delclust'' , gcbf, ''showwarning'');'; cb_dipole = 'pop_study(''dipselect'', gcbf, ''showwarning'');'; browsestudy = [ '[filename, filepath] = uiputfile2(''*.study'', ''Use exsiting STUDY set to import dataset information -- pop_study()''); ' ... 'set(findobj(''parent'', gcbf, ''tag'', ''usestudy_file''), ''string'', [filepath filename]);' ]; 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()''); ' ... 'if filename ~= 0,' ... ' set(findobj(''parent'', gcbf, ''tag'', ''studyfile''), ''string'', [filepath filename]);' ... 'end;' ... 'clear filename filepath;' ]; texthead = fastif(newstudy, 'Create a new STUDY set', 'Edit STUDY set information - remember to save changes'); guispec = { ... {'style' 'text' 'string' texthead 'FontWeight' 'Bold' 'HorizontalAlignment' 'center'} ... {} {'style' 'text' 'string' 'STUDY set name:' } { 'style' 'edit' 'string' STUDY.name 'tag' 'study_name' } ... {} {'style' 'text' 'string' 'STUDY set task name:' } { 'style' 'edit' 'string' STUDY.task 'tag' 'study_task' } ... {} {'style' 'text' 'string' 'STUDY set notes:' } { 'style' 'edit' 'string' STUDY.notes 'tag' 'study_notes' } {}... {} ... {'style' 'text' 'string' 'dataset filename' 'userdata' 'addt'} {'style' 'text' 'string' 'browse' 'userdata' 'addt'} ... {'style' 'text' 'string' 'subject' 'userdata' 'addt'} ... {'style' 'text' 'string' 'session' 'userdata' 'addt'} ... {'style' 'text' 'string' 'condition' 'userdata' 'addt'} ... {'style' 'text' 'string' 'group' 'userdata' 'addt'} ... {'style' 'pushbutton' 'string' 'Select by r.v.' 'userdata' 'addt' 'callback' cb_dipole } ... {} }; guigeom = { [1] [0.2 1 3.5] [0.2 1 3.5] [0.2 1 3.5] [1] [0.2 1.05 0.35 0.4 0.35 0.6 0.4 0.6 0.3]}; % create edit boxes % ----------------- for index = 1:10 guigeom = { guigeom{:} [0.2 1 0.2 0.5 0.2 0.5 0.5 0.5 0.3] }; 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(index) ''');' ... ' set( guiind,''string'', [inputpath inputname]);' ... loadset ... 'end; clear inputname inputpath;']; numstr = int2str(index); guispec = { guispec{:}, ... {'style' 'text' 'string' numstr 'tag' [ 'num' int2str(index) ] 'userdata' index }, ... {'style' 'edit' 'string' '' 'tag' [ 'set' int2str(index) ] 'userdata' index 'callback' loadsetedit}, ... {'style' 'pushbutton' 'string' '...' 'tag' [ 'brw' int2str(index) ] 'userdata' index 'Callback' select_com}, ... {'style' 'edit' 'string' '' 'tag' [ 'sub' int2str(index) ] 'userdata' index 'Callback' subcom}, ... {'style' 'edit' 'string' '' 'tag' [ 'sess' int2str(index) ] 'userdata' index 'Callback' sescom}, ... {'style' 'edit' 'string' '' 'tag' [ 'cond' int2str(index) ] 'userdata' index 'Callback' condcom}, ... {'style' 'edit' 'string' '' 'tag' [ 'group' int2str(index) ] 'userdata' index 'Callback' grpcom}, ... {'style' 'pushbutton' 'string' 'All comp.' 'tag' [ 'comps' int2str(index) ] 'userdata' index 'Callback' compcom}, ... {'style' 'pushbutton' 'string' 'CLear' 'tag' [ 'clear' int2str(index) ] 'userdata' index 'callback' delset} }; end; if strcmpi(info, 'from_STUDY_different_from_ALLEEG') text1 = 'Dataset info (condition, group, ...) differs from study info. [set] = Overwrite dataset info for each dataset on disk.'; value_cb = 0; else text1 = 'Update dataset info - datasets stored on disk will be overwritten (unset = Keep study info separate).'; value_cb = 1; end; guispec = { guispec{:}, ... {'style' 'text' 'string' 'Important note: Removed datasets will not be saved before being deleted from EEGLAB memory' }, ... {}, ... {'style' 'pushbutton' 'string' '<' 'Callback' prevpage 'userdata' 'addt'}, ... {'style' 'text' 'string' 'Page 1' 'tag' 'page' 'horizontalalignment' 'center' }, ... {'style' 'pushbutton' 'string' '>' 'Callback' nextpage 'userdata' 'addt'}, {}, ... {}, ... {'style' 'checkbox' 'value' value_cb 'tag' 'copy_to_dataset' }, ... {'style' 'text' 'string' text1 }, ... {'style' 'checkbox' 'value' 0 'tag' 'delclust' 'callback' cb_del }, ... {'style' 'text' 'string' 'Delete cluster information (to allow loading new datasets, set new components for clustering, etc.)' } }; guigeom = { guigeom{:} [1] [1 0.2 0.3 0.2 1] [1] [0.14 3] [0.14 3] }; % if ~isempty(STUDY.filename) % guispec{end-3} = {'style' 'checkbox' 'string' '' 'value' 0 'tag' 'studyfile' }; % guispec{end-2} = {'style' 'text' 'string' 'Re-save STUDY. Uncheck and use menu File > Save study as to save under a new filename'}; % guispec(end-1) = []; % guigeom{end-1} = [0.14 3]; % end; fig_arg{1} = ALLEEG; % datasets fig_arg{2} = datasetinfo; % datasetinfo fig_arg{3} = 1; % page fig_arg{4} = {}; % all commands fig_arg{5} = (length(STUDY.cluster) > 1); % are cluster present fig_arg{6} = STUDY; % are cluster present % generate GUI % ------------ optiongui = { 'geometry', guigeom, ... 'uilist' , guispec, ... 'helpcom' , 'pophelp(''pop_study'')', ... 'title' , 'Create a new STUDY set -- pop_study()', ... 'userdata', fig_arg, ... 'eval' , 'pop_study(''delclust'', gcf); pop_study(''redraw'', gcf);' }; [result, userdat2, strhalt, outstruct] = inputgui( 'mode', 'noclose', optiongui{:}); if isempty(result), return; end; if ~isempty(get(0, 'currentfigure')) currentfig = gcf; end; while test_wrong_parameters(currentfig) [result, userdat2, strhalt, outstruct] = inputgui( 'mode', currentfig, optiongui{:}); if isempty(result), return; end; end; close(currentfig); % convert GUI selection to options % -------------------------------- allcom = simplifycom(userdat2{4}); options = {}; if ~strcmpi(result{1}, STUDY.name ), options = { options{:} 'name' result{1} }; end; if ~strcmpi(result{2}, STUDY.task ), options = { options{:} 'task' result{2} }; end; if ~strcmpi(result{3}, STUDY.notes), options = { options{:} 'notes' result{3} }; end; if ~isempty(allcom), options = { options{:} 'commands' allcom }; end; % if isnumeric(outstruct(1).studyfile) % if outstruct(1).studyfile == 1, options = { options{:} 'resave' 'on' }; end; % else % if ~isempty(outstruct(1).studyfile), options = { options{:} 'filename' outstruct(1).studyfile }; end; % end; if outstruct(1).copy_to_dataset == 1 options = { options{:} 'updatedat' 'on' }; eeglab_options; if option_storedisk options = { options{:} 'savedat' 'on' }; end; else options = { options{:} 'updatedat' 'off' }; end; if outstruct(1).delclust == 1 options = { options{:} 'rmclust' 'on' }; end; % check channel labels % -------------------- ALLEEG = userdat2{1}; if isfield(ALLEEG, 'chanlocs') allchans = { ALLEEG.chanlocs }; if any(cellfun('isempty', allchans)) txt = strvcat('Some datasets do not have channel labels. Do you wish to generate', ... 'channel labels automatically for all datasets ("1" for channel 1,', ... '"2" for channel 2, ...). Datasets will be overwritten on disk.', ... 'If you abort, the STUDY will not be created.'); res = questdlg2(txt, 'Dataset format problem', 'Yes', 'No, abort', 'Yes'); if strcmpi(res, 'yes'), options = { options{:} 'addchannellabels' 'on' 'savedat' 'on'}; else return; end; end; end; % run command and create history % ------------------------------ com = sprintf( '[STUDY ALLEEG] = std_editset( STUDY, ALLEEG, %s );\n[STUDY ALLEEG] = std_checkset(STUDY, ALLEEG);', vararg2str(options) ); [STUDY ALLEEG] = std_editset(STUDY, ALLEEG, options{:}); else % internal command com = STUDY; hdl = ALLEEG; %figure handle % userdata info % ------------- userdat = get(hdl, 'userdata'); ALLEEG = userdat{1}; datasetinfo = userdat{2}; page = userdat{3}; allcom = userdat{4}; clusterpresent = userdat{5}; STUDY = userdat{6}; switch com case 'subject' guiindex = varargin{1}; realindex = guiindex+(page-1)*10; datasetinfo(realindex).subject = varargin{2}; if get(findobj(hdl, 'tag', 'copy_to_dataset'), 'value') ALLEEG(realindex).subject = varargin{2}; end; allcom = { allcom{:}, { 'index' realindex 'subject' varargin{2} } }; userdat{1} = ALLEEG; userdat{2} = datasetinfo; userdat{4} = allcom; set(hdl, 'userdata', userdat); case 'session' guiindex = varargin{1}; realindex = guiindex+(page-1)*10; datasetinfo(realindex).session = str2num(varargin{2}); if get(findobj(hdl, 'tag', 'copy_to_dataset'), 'value') ALLEEG(realindex).session = str2num(varargin{2}); end; allcom = { allcom{:}, { 'index' realindex 'session' str2num(varargin{2}) } }; userdat{1} = ALLEEG; userdat{2} = datasetinfo; userdat{4} = allcom; set(hdl, 'userdata', userdat); case 'group' guiindex = varargin{1}; realindex = guiindex+(page-1)*10; datasetinfo(realindex).group = varargin{2}; if get(findobj(hdl, 'tag', 'copy_to_dataset'), 'value') ALLEEG(realindex).group = varargin{2}; end; allcom = { allcom{:}, { 'index' realindex 'group' varargin{2} } }; userdat{1} = ALLEEG; userdat{2} = datasetinfo; userdat{4} = allcom; set(hdl, 'userdata', userdat); case 'condition' guiindex = varargin{1}; realindex = guiindex+(page-1)*10; datasetinfo(realindex).condition = varargin{2}; if get(findobj(hdl, 'tag', 'copy_to_dataset'), 'value') ALLEEG(realindex).conditon = varargin{2}; end; allcom = { allcom{:}, { 'index' realindex 'condition' varargin{2} } }; userdat{1} = ALLEEG; userdat{2} = datasetinfo; userdat{4} = allcom; set(hdl, 'userdata', userdat); case 'dipselect' STUDY.datasetinfo = datasetinfo; res = inputdlg2_with_checkbox( { strvcat('Enter maximum residual (topo map - dipole proj.) var. (in %)', ... 'NOTE: This will delete any existing component clusters!') }, ... 'pop_study(): Pre-select components', 1, { '15' },'pop_study' ); if isempty(res), return; end; if res{2} == 1 STUDY = std_editset(STUDY, ALLEEG, 'commands', { 'inbrain', 'on', 'dipselect' str2num(res{1})/100 'return' }); allcom = { allcom{:}, { 'inbrain', 'on', 'dipselect' str2num(res{1})/100 } }; else STUDY = std_editset(STUDY, ALLEEG, 'commands', { 'inbrain', 'off','dipselect' str2num(res{1})/100 'return' }); allcom = { allcom{:}, { 'inbrain', 'off', 'dipselect' str2num(res{1})/100 } }; end; datasetinfo = STUDY.datasetinfo; userdat{2} = datasetinfo; userdat{4} = allcom; set(hdl, 'userdata', userdat); set(findobj(hdl, 'tag', 'delclust'), 'value', 1); pop_study('delclust', hdl); pop_study('redraw', hdl); case 'component' guiindex = varargin{1}; realindex = guiindex+(page-1)*10; for index = 1:size(ALLEEG(realindex).icaweights,1) complist{index} = [ 'IC ' int2str(index) ]; end; [tmps,tmpv] = listdlg2('PromptString', 'Select components', 'SelectionMode', ... 'multiple', 'ListString', strvcat(complist), 'initialvalue', datasetinfo(realindex).comps); if tmpv ~= 0 % no cancel % find other subjects with the same session % ----------------------------------------- for index = 1:length(datasetinfo) if realindex == index | (strcmpi(datasetinfo(index).subject, datasetinfo(realindex).subject) & ... ~isempty(datasetinfo(index).subject) & ... isequal( datasetinfo(index).session, datasetinfo(realindex).session ) ) datasetinfo(index).comps = tmps; allcom = { allcom{:}, { 'index' index 'comps' tmps } }; set(findobj('tag', [ 'comps' int2str(index) ]), ... 'string', formatbut(tmps), 'horizontalalignment', 'left'); end; end; end; userdat{2} = datasetinfo; userdat{4} = allcom; set(hdl, 'userdata', userdat); pop_study('redraw', hdl); case 'clear' guiindex = varargin{1}; realindex = guiindex+(page-1)*10; datasetinfo(realindex).filename = ''; datasetinfo(realindex).filepath = ''; datasetinfo(realindex).subject = ''; datasetinfo(realindex).session = []; datasetinfo(realindex).condition = ''; datasetinfo(realindex).group = ''; datasetinfo(realindex).comps = []; allcom = { allcom{:}, { 'remove' realindex } }; userdat{1} = ALLEEG; userdat{2} = datasetinfo; userdat{4} = allcom; set(hdl, 'userdata', userdat); pop_study('redraw', hdl); case 'nextpage' userdat{3} = page+1; set(hdl, 'userdata', userdat); pop_study('redraw', hdl); case 'prevpage' userdat{3} = max(1,page-1); set(hdl, 'userdata', userdat); pop_study('redraw', hdl); case 'load' guiindex = varargin{1}; filename = varargin{2}; realindex = guiindex+(page-1)*10; % load dataset % ------------ TMPEEG = pop_loadset('filename', filename, 'loadmode', 'info'); ALLEEG = eeg_store(ALLEEG, eeg_checkset(TMPEEG), realindex); % update datasetinfo structure % ---------------------------- datasetinfo(realindex).filename = ALLEEG(realindex).filename; datasetinfo(realindex).filepath = ALLEEG(realindex).filepath; datasetinfo(realindex).subject = ALLEEG(realindex).subject; datasetinfo(realindex).session = ALLEEG(realindex).session; datasetinfo(realindex).condition = ALLEEG(realindex).condition; datasetinfo(realindex).group = ALLEEG(realindex).group; datasetinfo(realindex).comps = []; allcom = { allcom{:}, { 'index' realindex 'load' filename } }; userdat{1} = ALLEEG; userdat{2} = datasetinfo; userdat{4} = allcom; set(hdl, 'userdata', userdat); pop_study('redraw', hdl); case 'delclust' if clusterpresent if ~get(findobj(hdl, 'tag', 'delclust'), 'value') for k = 1:10 set(findobj('parent', hdl, 'tag',['set' num2str(k)]), 'style', 'text'); set(findobj('parent', hdl, 'tag',['comps' num2str(k)]), 'enable', 'off'); set(findobj('parent', hdl, 'tag',['sess' num2str(k)]), 'enable', 'off'); set(findobj('parent', hdl, 'tag',['brw' num2str(k)]), 'enable', 'off'); end; else for k = 1:10 set(findobj('parent', hdl, 'tag',['set' num2str(k)]), 'style', 'edit'); set(findobj('parent', hdl, 'tag',['comps' num2str(k)]), 'enable', 'on'); set(findobj('parent', hdl, 'tag',['sess' num2str(k)]), 'enable', 'on'); set(findobj('parent', hdl, 'tag',['brw' num2str(k)]), 'enable', 'on'); end; end; else set(findobj(hdl, 'tag', 'delclust'), 'value', 0) if nargin > 2 warndlg2('No cluster present'); end; end; case 'redraw' for k = 1:10 kk = k+(page-1)*10; % real index if kk > length(datasetinfo) set(findobj('parent', hdl, 'tag',['num' num2str(k)]), 'string', int2str(kk)); set(findobj('parent', hdl, 'tag',['set' num2str(k)]), 'string', ''); set(findobj('parent', hdl, 'tag',['sub' num2str(k)]), 'string',''); set(findobj('parent', hdl, 'tag',['sess' num2str(k)]), 'string',''); set(findobj('parent', hdl, 'tag',['cond' num2str(k)]), 'string',''); set(findobj('parent', hdl, 'tag',['comps' num2str(k)]), 'string',''); set(findobj('parent', hdl, 'tag',['group' num2str(k)]), 'string',''); else set(findobj('parent', hdl, 'tag',['num' num2str(k)]), 'string', int2str(kk)); set(findobj('parent', hdl, 'tag',['set' num2str(k)]), 'string', fullfile(char(datasetinfo(kk).filepath), char(datasetinfo(kk).filename))); set(findobj('parent', hdl, 'tag',['sub' num2str(k)]), 'string', datasetinfo(kk).subject); set(findobj('parent', hdl, 'tag',['sess' num2str(k)]), 'string', int2str(datasetinfo(kk).session)); set(findobj('parent', hdl, 'tag',['cond' num2str(k)]), 'string', datasetinfo(kk).condition); set(findobj('parent', hdl, 'tag',['comps' num2str(k)]), 'string', formatbut(datasetinfo(kk).comps)); set(findobj('parent', hdl, 'tag',['group' num2str(k)]), 'string', datasetinfo(kk).group); end; end if page<10 pagestr = [ ' Page ' int2str(page) ]; else pagestr = [ 'Page ' int2str(page) ]; end; set(findobj('parent', hdl, 'tag','page'), 'string', pagestr ); end end; % remove empty elements in allcom % ------------------------------- function allcom = simplifycom(allcom); for index = length(allcom)-1:-1:1 if strcmpi(allcom{index}{1}, 'index') & strcmpi(allcom{index+1}{1}, 'index') if allcom{index}{2} == allcom{index+1}{2} % same dataset index allcom{index}(end+1:end+length(allcom{index+1})-2) = allcom{index+1}(3:end); allcom(index+1) = []; end; end; end; % test for wrong parameters % ------------------------- function bool = test_wrong_parameters(hdl) userdat = get(hdl, 'userdata'); datasetinfo = userdat{2}; datastrinfo = userdat{1}; bool = 0; for index = 1:length(datasetinfo) if ~isempty(datasetinfo(index).filename) if isempty(datasetinfo(index).subject) & bool == 0 bool = 1; warndlg2('All datasets must have a subject name or code', 'Error'); end; end; end; nonempty = cellfun('isempty', { datasetinfo.filename }); anysession = any(~cellfun('isempty', { datasetinfo(nonempty).session })); allsession = all(~cellfun('isempty', { datasetinfo(nonempty).session })); anycondition = any(~cellfun('isempty', { datasetinfo(nonempty).condition })); allcondition = all(~cellfun('isempty', { datasetinfo(nonempty).condition })); anygroup = any(~cellfun('isempty', { datasetinfo(nonempty).group })); allgroup = all(~cellfun('isempty', { datasetinfo(nonempty).group })); anydipfit = any(~cellfun('isempty', { datastrinfo(nonempty).dipfit})); alldipfit = all(~cellfun('isempty', { datastrinfo(nonempty).dipfit})); if anygroup & ~allgroup bool = 1; warndlg2('If one dataset has a group label, they must all have one', 'Error'); end; if anycondition & ~allcondition bool = 1; warndlg2('If one dataset has a condition label, they must all have one', 'Error'); end; if anysession & ~allsession bool = 1; warndlg2('If one dataset has a session index, they must all have one', 'Error'); end; if anydipfit & ~alldipfit bool = 1; warndlg2('Dipole''s data across datasets is not uniform'); end; function strbut = formatbut(complist) if isempty(complist) strbut = 'All comp.'; else if length(complist) > 3, strbut = [ 'Comp.: ' int2str(complist(1:2)) ' ...' ]; else strbut = [ 'Comp.: ' int2str(complist) ]; end; end; %---------------------- helper functions ------------------------------------- function [result] = inputdlg2_with_checkbox(Prompt,Title,LineNo,DefAns,funcname); if nargin < 4 help inputdlg2; return; end; if nargin < 5 funcname = ''; end; if length(Prompt) ~= length(DefAns) error('inputdlg2: prompt and default answer cell array must have the smae size'); end; geometry = {}; listgui = {}; % determine if vertical or horizontal % ----------------------------------- geomvert = []; for index = 1:length(Prompt) geomvert = [geomvert size(Prompt{index},1) 1]; % default is vertical geometry end; if all(geomvert == 1) & length(Prompt) > 1 geomvert = []; % horizontal end; for index = 1:length(Prompt) if ~isempty(geomvert) % vertical geometry = { geometry{:} [ 1] [1 ]}; else geometry = { geometry{:} [ 1 0.6 ]}; end; listgui = { listgui{:} { 'Style', 'text', 'string', Prompt{index}} ... { 'Style', 'edit', 'string', DefAns{index} } { 'Style', 'checkbox', 'string','Keep only in-brain dipoles (requires Fieldtrip extension).','value',1 } }; end; geometry = [1 1 1];geomvert = [2 1 1]; result = inputgui(geometry, listgui, ['pophelp(''' funcname ''');'], Title, [], 'normal', geomvert);
github
ZijingMao/baselineeegtest-master
std_convertdesign.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_convertdesign.m
1,356
utf_8
186f56b44af9306eb22e85b0ccd8896b
% std_convertdesign - temporary function converting STUDY design legacy % format to new format. function STUDY = std_convertdesign(STUDY,ALLEEG); for index = 1:length(STUDY.design) design(index).name = STUDY.design(index).name; design(index).variable(1).label = STUDY.design(index).indvar1; design(index).variable(2).label = STUDY.design(index).indvar2; design(index).variable(1).value = STUDY.design(index).condition; design(index).variable(2).value = STUDY.design(index).group; design(index).variable(1).pairing = STUDY.design(index).statvar1; design(index).variable(2).pairing = STUDY.design(index).statvar2; design(index).cases.label = 'subject'; design(index).cases.value = STUDY.design(index).subject; design(index).include = STUDY.design(index).includevarlist; setinfo = STUDY.design(index).setinfo; for c = 1:length(setinfo) design(index).cell(c).dataset = setinfo(c).setindex; design(index).cell(c).trials = setinfo(c).trialindices; design(index).cell(c).value = { setinfo(c).condition setinfo(c).group }; design(index).cell(c).case = setinfo(c).subject; design(index).cell(c).filebase = setinfo(c).filebase; end; end; STUDY.design = design; STUDY = std_selectdesign(STUDY, ALLEEG, STUDY.currentdesign);
github
ZijingMao/baselineeegtest-master
std_renameclust.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_renameclust.m
3,890
utf_8
c2149e8286112cc50bb730ff01424cdf
% std_renameclust() - Commandline function, to rename clusters using specified (mnemonic) names. % Usage: % >> [STUDY] = std_renameclust(STUDY, ALLEEG, cluster, new_name); % 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. % new_name - [string] mnemonic cluster name. % % Outputs: % STUDY - the input STUDY set structure modified according to specified new cluster name. % % Example: % >> cluster = 7; new_name = 'artifacts'; % >> [STUDY] = std_renameclust(STUDY,ALLEEG, cluster, new_name); % Cluster 7 name (i.e.: STUDY.cluster(7).name) will change to 'artifacts 7'. % % 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_renameclust(STUDY, ALLEEG, cls, new_name) if ~exist('cls') error('std_renameclust: you must provide a cluster number to rename.'); end if isempty(cls) error('std_renameclust: you must provide a cluster number to rename.'); end if ~exist('new_name') error('std_renameclust: you must provide a new cluster name.'); end if strncmpi('Notclust',STUDY.cluster(cls).name,8) % Don't rename Notclust 'clusters' warndlg2('std_renameclust: Notclust cannot be renamed'); return; end ti = strfind(STUDY.cluster(cls).name, ' '); clus_id = STUDY.cluster(cls).name(ti(end) + 1:end); new_name = sprintf('%s %s', new_name, clus_id); % If the cluster have children cluster update their parent cluster name to the % new cluster. if ~isempty(STUDY.cluster(cls).child) for k = 1:length(STUDY.cluster(cls).child) child_cls = STUDY.cluster(cls).child{k}; child_id = find(strcmp({STUDY.cluster.name},child_cls)); parent_id = find(strcmp(STUDY.cluster(child_id).parent,STUDY.cluster(cls).name)); STUDY.cluster(child_id).parent{parent_id} = new_name; end end % If the cluster has parent clusters, update the parent clusters with the % new cluster name of child cluster. if ~isempty(STUDY.cluster(cls).parent) for k = 1:length(STUDY.cluster(cls).parent) parent_cls = STUDY.cluster(cls).parent{k}; parent_id = find(strcmp({STUDY.cluster.name},parent_cls)); STUDY.cluster(parent_id).child{find(strcmp(STUDY.cluster(parent_id).child,STUDY.cluster(cls).name))} = new_name; end end % If the cluster have an Outlier cluster, update the Outlier cluster name. outlier_clust = std_findoutlierclust(STUDY,cls); %find the outlier cluster for this cluster if outlier_clust ~= 0 ti = strfind(STUDY.cluster(outlier_clust).name, ' '); clus_id = STUDY.cluster(outlier_clust).name(ti(end) + 1:end); STUDY.cluster(outlier_clust).name = sprintf('Outliers %s %s', new_name, clus_id); end % Rename cluster STUDY.cluster(cls).name = new_name;
github
ZijingMao/baselineeegtest-master
toporeplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/toporeplot.m
32,771
utf_8
a2d2fb39ae360df3cbefbd0d42f15e4a
% toporeplot() - re-plot a saved topoplot() output image (a square matrix) % in a 2-D circular scalp map view (as looking down at the top % of the head). May also be used to re-plot a mean topoplot() % map for a number of subjects and/or components without all % the constitutent maps having the same channel montage. % Nose is at top of plot. Left = left. See topoplot(). % Usage: % >> toporeplot(topoimage,'plotrad',val1, 'intrad',val2); % % Use an existing (or mean) topoplot output image. Give the % % original 'intrad' and 'plotrad' values used to in topoimage. % >> toporeplot(topoimage,'plotrad',val1,'xsurface', Xi, 'ysurface',Yi ); % % Use an existing (or mean) topoplot output image. Give the same % % 'plotrad' value used to create it. Since 'intrad' was not input % % to topoplot(), give the grid axes Xi and Yi as inputs. % >> [hfig val ]= toporeplot(topoimage,'plotrad',val1, 'Param1','Value1', ...); % % Give one of the two options above plus other optional parameters. % Required inputs: % topoimage - output image matrix (as) from topoplot(). For maximum flexibility, % create topoimage using topoplot() options: 'plotrad',1, 'intrad',1 % 'plotrad' - [0.15<=float<=1.0] plotting radius = max channel arc_length to plot. % 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. % The topoimage depends on 'plotrad', so 'plotrad' is required to % reproduce the 'topoplot' image. % Optional inputs: % 'chanlocs' - name of an EEG electrode position file (see >> topoplot example). % Else, an EEG.chanlocs structure (see >> help pop_editset). % '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 {default: 'both'} % 'fill' -> plot constant color between contour lines % 'blank' -> plot electrode locations only, requires electrode info. % 'electrodes' - 'on','off','labels','numbers','ptslabels','ptsnumbers' See Plot detail % options below. {default: 'on' -> mark electrode locations with points % unless more than 64 channels, then 'off'}. Requires electrode info. % 'intrad' - [0.15<=float<=1.0] radius of the interpolation area used in topoplot() % to get the grid. % 'headrad' - [0.15<=float<=1.0] drawing radius (arc_length) for the cartoon head. % NB: 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}. % Requires electrode information. % 'noplot' - [rad theta] are coordinates of a (possibly missing) channel. % Do not plot but return interpolated value for channel location. % Do not plot but return interpolated value for this location. % 'xsurface' - [Xi- matrix] the Xi grid points for the surface of the plotting % an output of topoplot(). % 'ysurface' - [Yi- matrix] the Yi grid points for the surface of the plotting, % an output of topoplot(). % Dipole plotting: % '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}. % Plot detail options: % 'electcolor' {'k'}|'emarker' {'.'}|'emarkersize' {14} ... % |'emarkersize1chan' {40}|'efontsize' {var} - electrode marking details and {defaults}. % 'shading' - 'flat','interp' {default: 'flat'} % 'colormap' - (n,3) any size colormap {default: existing colormap} % 'numcontour' - number of contour lines {default: 6} % 'ccolor' - color of the contours {default: dark grey} % 'hcolor'|'ecolor' - colors of the cartoon head and electrodes {default: black} % 'circgrid' - [int > 100] number of elements (angles) in head and border circles {201} % 'verbose' - ['on'|'off'] comment on operations on command line {default: 'on'}. % % Outputs: % hfig - plot axes handle % val - single interpolated value at the specified 'noplot' arg channel % location ([rad theta]). % % 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: Hilit Serby, Andy Spydell, Colin Humphries, Arnaud Delorme & Scott Makeig % CNL / Salk Institute, 8/1996-/10/2001; SCCN/INC/UCSD, Nov. 2001- Nov. 2004 % % See also: topoplot(), timtopo(), envtopo() % Deprecated but still usable; % 'interplimits' - ['electrodes'|'head'] 'electrodes'-> interpolate the electrode grid; % 'head'-> interpolate the whole disk {default: 'head'}. % toporeplot() - From topoplot.m, Revision 1.216 2004/12/05 12:00:00 hilit %[hfig grid] = topoplot( EEG.icawinv(:, 5), EEG.chanlocs, 'verbose', 'off','electrodes', 'off' ,'style','both'); %figure; toporeplot(grid, 'style', 'both', 'plotrad',0.5,'intrad',0.5, 'verbose', 'off'); function [handle,chanval] = toporeplot(grid,p1,v1,p2,v2,p3,v3,p4,v4,p5,v5,p6,v6,p7,v7,p8,v8,p9,v9,p10,v10) % %%%%%%%%%%%%%%%%%%%%%%%% 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 GRID_SCALE = length(grid); noplot = 'off'; handle = []; chanval = NaN; rmax = 0.5; % head radius - don't change this! INTERPLIMITS = 'head'; % head, electrodes MAPLIMITS = 'absmax'; % absmax, maxmin, [values] 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 ECOLOR = [0 0 0]; % default electrode 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 EMARKERSIZE = []; % default depends on number of electrodes, set in code EMARKERSIZE1CHAN = 40; % default selected channel location marker size EMARKERCOLOR1CHAN = 'red'; % selected channel location marker color EFSIZE = get(0,'DefaultAxesFontSize'); % use current default fontsize for electrode labels HLINEWIDTH = 3; % 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 plotrad = []; % plotting radius ([] = auto, based on outermost channel location) intrad = []; % default interpolation square is to outermost electrode (<=1.0) headrad = []; % default plotting radius for cartoon head is 0.5 MINPLOTRAD = 0.15; % can't make a topoplot with smaller plotrad (contours fail) VERBOSE = 'off'; MASKSURF = 'off'; %%%%%% Dipole defaults %%%%%%%%%%%% DIPOLE = []; DIPNORM = 'on'; DIPSPHERE = 85; DIPLEN = 1; DIPSCALE = 1; DIPORIENT = 1; DIPCOLOR = [0 0 0]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%% Handle arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if nargin< 1 help topoplot; return end nargs = nargin; if ~mod(nargs,2) error('Optional inputs must come in Key - Val pairs') end if ~isnumeric(grid) | size(grid,1) ~= size(grid,2) error('topoimage must be a square matrix'); end for i = 2:2:nargs Param = eval(['p',int2str((i-2)/2 +1)]); Value = eval(['v',int2str((i-2)/2 +1)]); if ~isstr(Param) error('Flag arguments must be strings') end Param = lower(Param); switch lower(Param) case 'chanlocs' loc_file = Value; case 'colormap' if size(Value,2)~=3 error('Colormap must be a n x 3 matrix') end colormap(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 '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 end if 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 end if strcmpi(ELECTRODES,'nums') ELECTRODES = 'numbers'; % backwards compatability end if strcmpi(ELECTRODES,'pts') ELECTRODES = 'on'; % backwards compatability end if ~strcmpi(ELECTRODES,'labelpoint') ... & ~strcmpi(ELECTRODES,'numpoint') ... & ~strcmp(ELECTRODES,'on') ... & ~strcmp(ELECTRODES,'off') ... & ~strcmp(ELECTRODES,'labels') ... & ~strcmpi(ELECTRODES,'numbers') 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 'diporient' DIPORIENT = Value; case 'dipcolor' DIPCOLOR = Value; case 'emarker' EMARKER = Value; 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 '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 '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 'xsurface' Xi = Value; if ~isnumeric(Xi) | size(Xi,1) ~= size(Xi,2) | size(Xi,1) ~= size(grid,1) error('xsurface must be a square matrix the size of grid'); end case 'ysurface' Yi = Value; if ~isnumeric(Yi) | size(Yi,1) ~= size(Yi,2) | size(Yi,1) ~= size(grid,1) error('ysurface must be a square matrix the size of grid'); end case {'headcolor','hcolor'} HEADCOLOR = Value; case {'contourcolor','ccolor'} CCOLOR = Value; case {'electcolor','ecolor'} ECOLOR = Value; case {'emarkersize','emsize'} EMARKERSIZE = Value; case 'emarkersize1chan' EMARKERSIZE1CHAN= Value; case {'efontsize','efsize'} EFSIZE = Value; case 'shading' SHADING = lower(Value); if ~any(strcmp(SHADING,{'flat','interp'})) error('Invalid shading parameter') 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 otherwise error(['Unknown input parameter ''' Param ''' ???']) end end if isempty(plotrad) error(' ''plotrad'' must be given') end if isempty(intrad) if ~exist('Yi') | ~exist('Xi') error('either ''intrad'' or the grid axes (Xi and Yi) must be given'); end end % %%%%%%%%%%%%%%%%%%%% Read the channel location information %%%%%%%%%%%%%%%%%%%%%%%% % if exist('loc_file') if isstr(loc_file) [tmpeloc labels Th Rd indices] = readlocs(loc_file,'filetype','loc'); else % a locs struct [tmpeloc labels Th Rd indices] = readlocs(loc_file); % Note: Th and Rd correspond to indices channels-with-coordinates only end labels = strvcat(labels); Th = pi/180*Th; % convert degrees to radians % %%%%%%%%%%%%%%%%%% 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 isstr(plotrad) | plotrad < MINPLOTRAD | plotrad > 1.0 error('plotrad must be between 0.15 and 1.0'); end end if isempty(plotrad) & ~ exist('loc_file') plotrad = 1; % default: plot out to the 0.5 head bounda end % plotrad now set % %%%%%%%%%%%%%%%%%%%%%%% 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 % headrad now set % %%%%%%%%%%%%%%%%% 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 squeezefac = rmax/plotrad; % %%%%%%%%%%%%%%%%%%%%% Find plotting channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if exist('tmpeloc') pltchans = find(Rd <= plotrad); % plot channels inside plotting circle [x,y] = pol2cart(Th,Rd); % transform electrode locations from polar to cartesian coordinates % %%%%%%%%%%%%%%%%%%%%% Eliminate channels not plotted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % allx = x; ally = y; 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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Rd = Rd*squeezefac; % squeeze electrode arc_lengths towards the vertex % to plot all inside the head cartoon x = x*squeezefac; y = y*squeezefac; allx = allx*squeezefac; ally = ally*squeezefac; end % Note: Now outermost channel will be plotted just inside rmax % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Make the plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if ~strcmpi(STYLE,'blank') % if draw interpolated scalp map % %%%%%%%%%%%%%%%%%%%%%%% Interpolate scalp map data %%%%%%%%%%%%%%%%%%%%%%%% % if ~isempty(intrad) % intrad specified xi = linspace(-intrad*squeezefac,intrad*squeezefac,GRID_SCALE); % use the specified intrad value yi = linspace(-intrad*squeezefac,intrad*squeezefac,GRID_SCALE); [Xi,Yi] = meshgrid(yi',xi); elseif ~exist('Xi') | ~exist('Yi') error('toporeplot require either intrad input or both xsurface and ysurface') end Zi = grid; mask = (sqrt(Xi.^2 + Yi.^2) <= rmax); % mask outside the plotting circle ii = find(mask == 0); Zi(ii) = NaN; % %%%%%%%%%% 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)); 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 %%%%%%%%%%%%%%%%%%%%%%%%%% % m = size(colormap,1); if isstr(MAPLIMITS) if strcmp(MAPLIMITS,'absmax') amin = -max(max(abs(Zi))); amax = max(max(abs(Zi))); elseif strcmp(MAPLIMITS,'maxmin') | strcmp(MAPLIMITS,'minmax') amin = min(min(Zi)); amax = max(max(Zi)); else error('unknown ''maplimits'' value.'); end else amin = MAPLIMITS(1); amax = MAPLIMITS(2); end delta = Xi(1,2)-Xi(1,1); % length of grid entry % %%%%%%%%%%%%%%%%%%%%%%%%%% 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 switch STYLE % %%%%%%%%%%%%%%%%%%%%%%%% Plot map contours only %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % case 'contour' % plot surface contours only [cls chs] = contour(Xi,Yi,Zi,CONTOURNUM,'k'); % %%%%%%%%%%%%%%%%%%%%%%%% Else plot map and contours %%%%%%%%%%%%%%%%%%%%%%%%% % case 'both' % plot interpolated surface and surface contours if strcmp(SHADING,'interp') tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi)),Zi,... 'EdgeColor','none','FaceColor',SHADING); else % SHADING == 'flat' 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; [cls chs] = contour(Xi,Yi,Zi,CONTOURNUM,'k'); for h=chs, set(h,'color',CCOLOR); end % %%%%%%%%%%%%%%%%%%%%%%%% Else plot map only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % case {'straight', '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; % %%%%%%%%%%%%%%%%%% Else fill contours with uniform colors %%%%%%%%%%%%%%%%%% % case 'fill' [cls chs] = contourf(Xi,Yi,Zi,CONTOURNUM,'k'); otherwise error('Invalid style') end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Set color axis %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % caxis([amin amax]) % set coloraxis % %%%%%%%%%%%%%%%%%%%%%%% Draw blank head %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % else % if STYLE 'blank' 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) if ~exist('tmpeloc') error('No electrode location information found'); end 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 if exist('handle') ~= 1 handle = gca; end; % %%%%%%%%%%%%%%%%%%% 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 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 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]; ringh= patch(headx,heady,ones(size(headx)),HEADCOLOR,'edgecolor',HEADCOLOR); hold on % %%%%%%%%%%%%%%%%%%% 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 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 % % %%%%%%%%%%%%%%%%%%% Show electrode information %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plotax = gca; axis square % make plotax square axis off pos = get(gca,'position'); xlm = get(gca,'xlim'); ylm = get(gca,'ylim'); 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 %%%%%%%%%%%%%%%%%%%%%%%%%only if electrode info is available %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if exist('tmpeloc') if isempty(EMARKERSIZE) EMARKERSIZE = 10; if length(y)>=32 EMARKERSIZE = 8; elseif length(y)>=48 EMARKERSIZE = 6; elseif length(y)>=64 EMARKERSIZE = 5; elseif length(y)>=80 EMARKERSIZE = 4; elseif length(y)>=100 EMARKERSIZE = 3; elseif length(y)>=128 EMARKERSIZE = 2; elseif length(y)>=160 EMARKERSIZE = 1; 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 hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,... EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE); % %%%%%%%%%%%%%%%%%%%%%%%% 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') hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,... EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE); 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(pltchans(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') hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE); for i = 1:size(labels,1) hh(i) = text(double(y(i)+0.01),double(x(i)),... ELECTRODE_HEIGHT,num2str(pltchans(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(pltchans(i)),'HorizontalAlignment','center',... 'VerticalAlignment','middle','Color',ECOLOR,... 'FontSize',EFSIZE) end end 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)]'); set(hh, 'color', DIPCOLOR, 'linewidth', DIPSCALE*30/7); end; end; end; % %%%%%%%%%%%%% Set EEGLAB background color to match head border %%%%%%%%%%%%%%%%%%%%%%%% % try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; hold off axis off return
github
ZijingMao/baselineeegtest-master
std_selectdataset.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_selectdataset.m
3,936
utf_8
2a1032fd19689b4c864e36ea390e7aff
% std_selectdataset() - select datasets and trials for a given independent % variable with a given set of values. % % Usage: % >> [STUDY] = std_selectdataset(STUDY, ALLEEG, indvar, indvarvals); % % Inputs: % STUDY - EELAB STUDY structure % ALLEEG - EELAB dataset structure % indvar - [string] independent variable name % indvarvals - [cell] cell array of string for selected values for the % verboseflag - ['verbose'|'silent'] print info flag % % choosen independent variable % Output: % datind - [integer array] indices of selected dataset % dattrialsind - [cell] trial indices for each dataset (not only the % datasets selected above). % % Author: Arnaud Delorme, CERCO, 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 [datind, dattrialselect] = std_selectdataset(STUDY, ALLEEG, indvar, indvarvals, verboseFlag); if nargin < 3 help std_selectdataset; return; end; if nargin < 5 verboseFlag = 'verbose'; end; % check for multiple condition selection if ~iscell(indvarvals), pos = findstr(' - ', indvarvals); if ~isempty(pos) tmpindvar = indvarvals; indvarvals = { indvarvals(1:pos(1)-1) }; pos(end+1) = length(tmpindvar)+1; for ind = 1:length(pos)-1 indvarvals{end+1} = tmpindvar(pos(ind)+3:pos(ind+1)-1); end; else indvarvals = { indvarvals }; end; end; % default dattrialselect = all trials % ----------------------------------- if isfield(STUDY.datasetinfo, 'trialinfo') dattrialselect = cellfun(@(x)([1:length(x)]), { STUDY.datasetinfo.trialinfo }, 'uniformoutput', false); else for i=1:length(ALLEEG), dattrialselect{i} = [1:ALLEEG(i).trials]; end; end; if isempty(indvar) datind = [1:length(STUDY.datasetinfo)]; elseif isfield(STUDY.datasetinfo, indvar) && ~isempty(getfield(STUDY.datasetinfo(1), indvar)) % regular selection of dataset in datasetinfo % ------------------------------------------- if strcmpi(verboseFlag, 'verbose'), fprintf(' Selecting datasets with field ''%s'' equal to %s\n', indvar, vararg2str(indvarvals)); end; eval( [ 'myfieldvals = { STUDY.datasetinfo.' indvar '};' ] ); datind = []; for dat = 1:length(indvarvals) datind = union_bc(datind, std_indvarmatch(indvarvals{dat}, myfieldvals)); end; else % selection of trials within datasets % ----------------------------------- if strcmpi(verboseFlag, 'verbose'), fprintf(' Selecting trials with field ''%s'' equal to %s\n', indvar, vararg2str(indvarvals)); end; dattrials = cellfun(@(x)(eval(['{ x.' indvar '}'])), { STUDY.datasetinfo.trialinfo }, 'uniformoutput', false); dattrials = cellfun(@(x)(eval(['{ x.' indvar '}'])), { STUDY.datasetinfo.trialinfo }, 'uniformoutput', false); % do not remove duplicate line (or Matlab crashes) dattrialselect = cell(1,length(STUDY.datasetinfo)); for dat = 1:length(indvarvals) for tmpi = 1:length(dattrials) dattrialselect{tmpi} = union_bc(dattrialselect{tmpi}, std_indvarmatch(indvarvals{dat}, dattrials{tmpi})); end; end; datind = find(~cellfun(@isempty, dattrialselect)); end;
github
ZijingMao/baselineeegtest-master
pop_clust.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_clust.m
17,363
utf_8
b5e06dc979fd397f7493bb99bc676b93
% pop_clust() - select and run a clustering algorithm on components from an EEGLAB STUDY % structure of EEG datasets. Clustering data should be prepared beforehand using % pop_preclust() and/or std_preclust(). The number of clusters must be % specified in advance. If called in gui mode, the pop_clustedit() window % appears when the clustering is complete to display clustering results % and allow the user to review and edit them. % Usage: % >> STUDY = pop_clust( STUDY, ALLEEG); % pop up a graphic interface % >> STUDY = pop_clust( STUDY, ALLEEG, 'key1', 'val1', ...); % no pop-up % Inputs: % STUDY - an EEGLAB STUDY set containing some or all of the EEG sets in ALLEEG. % ALLEEG - a vector of loaded EEG dataset structures of all sets in the STUDY set. % % Optional Inputs: % 'algorithm' - ['kmeans'|'kmeanscluster'|'Neural Network'] algorithm to be used for % clustering. The 'kmeans' options requires the statistical toolbox. The % 'kmeanscluster' option is included in EEGLAB. The 'Neural Network' % option requires the Matlab Neural Net toolbox {default: 'kmeans'} % 'clus_num' - [integer] the number of desired clusters (must be > 1) {default: 20} % 'outliers' - [integer] identify outliers further than the given number of standard % deviations from any cluster centroid. Inf --> identify no such outliers. % {default: Inf from the command line; 3 for 'kmeans' from the pop window} % 'save' - ['on' | 'off'] save the updated STUDY to disk {default: 'off'} % 'filename' - [string] if save option is 'on', save the STUDY under this file name % {default: current STUDY filename} % 'filepath' - [string] if save option is 'on', will save the STUDY in this directory % {default: current STUDY filepath} % Outputs: % STUDY - as input, but modified adding the clustering results. % % Graphic interface buttons: % "Clustering algorithm" - [list box] display/choose among the available clustering % algorithms. % "Number of clusters to compute" - [edit box] the number of desired clusters (>2) % "Identify outliers" - [check box] check to detect outliers. % "Save STUDY" - [check box] check to save the updated STUDY after clustering % is performed. If no file entered, overwrites the current STUDY. % % See also pop_clustedit(), pop_preclust(), std_preclust(), pop_clust() % % Authors: Hilit Serby & Arnaud Delorme, 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, ALLEEG, command] = pop_clust(STUDY, ALLEEG, varargin) command = ''; if nargin < 2 help pop_clust; return; end; if isempty(STUDY.etc) error('No pre-clustering information, pre-cluster first!'); end; if ~isfield(STUDY.etc, 'preclust') error('No pre-clustering information, pre-cluster first!'); end; if isempty(STUDY.etc.preclust) error('No pre-clustering information, pre-cluster first!'); end; % check that the path to the stat toolbox comes first (conflict % with Fieldtrip) kmeansPath = fileparts(which('kmeans')); if ~isempty(kmeansPath) rmpath(kmeansPath); addpath(kmeansPath); end; if isempty(varargin) %GUI call % remove clusters below clustering level (done also after GUI) % -------------------------------------- rmindex = []; clustlevel = STUDY.etc.preclust.clustlevel; nameclustbase = STUDY.cluster(clustlevel).name; if clustlevel == 1 rmindex = [2:length(STUDY.cluster)]; else for index = 2:length(STUDY.cluster) if strcmpi(STUDY.cluster(index).parent{1}, nameclustbase) & ~strncmpi('Notclust',STUDY.cluster(index).name,8) rmindex = [ rmindex index ]; end; end; end; if length(STUDY.cluster) > 2 & ~isempty(rmindex) resp = questdlg2('Clustering again will delete the last clustering results', 'Warning', 'Cancel', 'Ok', 'Ok'); if strcmpi(resp, 'cancel'), return; end; end; alg_options = {'Kmeans (stat. toolbox)' 'Neural Network (stat. toolbox)' 'Kmeanscluster (no toolbox)' }; %'Hierarchical tree' set_outliers = ['set(findobj(''parent'', gcbf, ''tag'', ''outliers_std''), ''enable'', fastif(get(gcbo, ''value''), ''on'', ''off''));'... 'set(findobj(''parent'', gcbf, ''tag'', ''std_txt''), ''enable'', fastif(get(gcbo, ''value''), ''on'', ''off''));']; algoptions = [ 'set(findobj(''parent'', gcbf, ''userdata'', ''kmeans''), ''enable'', fastif(get(gcbo, ''value'')==1, ''on'', ''off''));' ]; 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]);' ]; if ~exist('kmeans'), valalg = 3; else valalg = 1; end; strclust = ''; if STUDY.etc.preclust.clustlevel > length(STUDY.cluster) STUDY.etc.preclust.clustlevel = 1; end; if STUDY.etc.preclust.clustlevel == 1 strclust = [ 'Performing clustering on cluster ''' STUDY.cluster(STUDY.etc.preclust.clustlevel).name '''' ]; else strclust = [ 'Performing sub-clustering on cluster ''' STUDY.cluster(STUDY.etc.preclust.clustlevel).name '''' ]; end; numClust = ceil(mean(cellfun(@length, { STUDY.datasetinfo.comps }))); if numClust > 2, numClustStr = num2str(numClust); else numClustStr = '10'; end; clust_param = inputgui( { [1] [1] [1 1] [1 0.5 0.5 ] [ 1 0.5 0.5 ] }, ... { {'style' 'text' 'string' strclust 'fontweight' 'bold' } {} ... {'style' 'text' 'string' 'Clustering algorithm:' } ... {'style' 'popupmenu' 'string' alg_options 'value' valalg 'tag' 'clust_algorithm' 'Callback' algoptions } ... {'style' 'text' 'string' 'Number of clusters to compute:' } ... {'style' 'edit' 'string' numClustStr 'tag' 'clust_num' } {} ... {'style' 'checkbox' 'string' 'Separate outliers (enter std.)' 'tag' 'outliers_on' 'value' 0 'Callback' set_outliers 'userdata' 'kmeans' 'enable' 'on' } ... {'style' 'edit' 'string' '3' 'tag' 'outliers_std' 'enable' 'off' } {} },... 'pophelp(''pop_clust'')', 'Set clustering algorithm -- pop_clust()' , [] , 'normal', [ 1 .5 1 1 1]); if ~isempty(clust_param) % removing previous cluster information % ------------------------------------- if ~isempty(rmindex) fprintf('Removing child clusters of ''%s''...\n', nameclustbase); STUDY.cluster(rmindex) = []; STUDY.cluster(clustlevel).child = []; if clustlevel == 1 & length(STUDY.cluster) > 1 STUDY.cluster(1).child = { STUDY.cluster(2).name }; % "Notclust" cluster end; end; clus_alg = alg_options{clust_param{1}}; clus_num = str2num(clust_param{2}); outliers_on = clust_param{3}; stdval = clust_param{4}; outliers = []; try clustdata = STUDY.etc.preclust.preclustdata; catch error('Error accesing preclustering data. Perform pre-clustering.'); end; command = '[STUDY] = pop_clust(STUDY, ALLEEG,'; if ~isempty(findstr(clus_alg, 'Kmeanscluster')), clus_alg = 'kmeanscluster'; end; if ~isempty(findstr(clus_alg, 'Kmeans ')), clus_alg = 'kmeans'; end; if ~isempty(findstr(clus_alg, 'Neural ')), clus_alg = 'neural network'; end; disp('Clustering ...'); switch clus_alg case { 'kmeans' 'kmeanscluster' } command = sprintf('%s %s%s%s %d %s', command, '''algorithm'',''', clus_alg, ''',''clus_num'', ', clus_num, ','); if outliers_on command = sprintf('%s %s %s %s', command, '''outliers'', ', stdval, ','); [IDX,C,sumd,D,outliers] = robust_kmeans(clustdata,clus_num,str2num(stdval),5,lower(clus_alg)); [STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'robust_kmeans', clus_num}); else if strcmpi(clus_alg, 'kmeans') [IDX,C,sumd,D] = kmeans(clustdata,clus_num,'replicates',10,'emptyaction','drop'); else %[IDX,C,sumd,D] = kmeanscluster(clustdata,clus_num); [C,IDX,sumd] =kmeans_st(real(clustdata),clus_num,150); end; [STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'Kmeans', clus_num}); end case 'Hierarchical tree' %[IDX,C] = hierarchical_tree(clustdata,clus_num); %[STUDY] = std_createclust(STUDY,IDX,C, {'Neural Network', clus_num}); case 'neural network' [IDX,C] = neural_net(clustdata,clus_num); [STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'Neural Network', clus_num}); command = sprintf('%s %s %d %s', command, '''algorithm'', ''Neural Network'',''clus_num'', ', clus_num, ','); end disp('Done.'); % If save updated STUDY to disk save_on = 0; % old option to save STUDY if save_on command = sprintf('%s %s', command, '''save'', ''on'','); if ~isempty(clust_param{6}) [filepath filename ext] = fileparts(clust_param{6}); command = sprintf('%s%s%s%s%s%s', command, '''filename'', ''', [filename ext], ', ''filepath'', ''', filepath, ''');' ); STUDY = pop_savestudy(STUDY, ALLEEG, 'filename', [filename ext], 'filepath', filepath); else command(end:end+1) = ');'; if (~isempty(STUDY.filename)) & (~isempty(STUDY.filepath)) STUDY = pop_savestudy(STUDY, ALLEEG, 'filename', STUDY.filename, 'filepath', STUDY.filepath); else STUDY = pop_savestudy(STUDY, ALLEEG); end end else command(end:end+1) = ');'; end % Call menu to plot clusters (use EEGLAB menu which include std_envtopo) eval( [ get(findobj(findobj('tag', 'EEGLAB'), 'Label', 'Edit/plot clusters'), 'callback') ] ); %[STUDY com] = pop_clustedit(STUDY, ALLEEG); command = [ command LASTCOM ]; end else %command line call % remove clusters below clustering level (done also after GUI) % -------------------------------------- rmindex = []; clustlevel = STUDY.etc.preclust.clustlevel; nameclustbase = STUDY.cluster(clustlevel).name; if clustlevel == 1 rmindex = [2:length(STUDY.cluster)]; else for index = 2:length(STUDY.cluster) if strcmpi(STUDY.cluster(index).parent{1}, nameclustbase) & ~strncmpi('Notclust',STUDY.cluster(index).name,8) rmindex = [ rmindex index ]; end; end; end; if ~isempty(rmindex) fprintf('Removing child clusters of ''%s''...\n', nameclustbase); STUDY.cluster(rmindex) = []; STUDY.cluster(clustlevel).child = []; if clustlevel == 1 & length(STUDY.cluster) > 1 STUDY.cluster(1).child = { STUDY.cluster(2).name }; % "Notclust" cluster end; end; %default values algorithm = 'kmeans'; clus_num = 20; save = 'off'; filename = STUDY.filename; filepath = STUDY.filepath; outliers = Inf; % default std is Inf - no outliers if mod(length(varargin),2) ~= 0 error('pop_clust(): input variables must be specified in pairs: keywords, values'); end for k = 1:2:length(varargin) switch(varargin{k}) case 'algorithm' algorithm = varargin{k+1}; case 'clus_num' clus_num = varargin{k+1}; case 'outliers' outliers = varargin{k+1}; case 'save' save = varargin{k+1}; case 'filename' filename = varargin{k+1}; case 'filepath' filepath = varargin{k+1}; end end if clus_num < 2 clus_num = 2; end clustdata = STUDY.etc.preclust.preclustdata; switch lower(algorithm) case { 'kmeans' 'kmeanscluster' } if outliers == Inf if strcmpi(algorithm, 'kmeans') [IDX,C,sumd,D] = kmeans(clustdata,clus_num,'replicates',10,'emptyaction','drop'); else [IDX,C,sumd,D] = kmeanscluster(clustdata,clus_num); end; [STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'Kmeans', clus_num}); else [IDX,C,sumd,D,outliers] = robust_kmeans(clustdata,clus_num,outliers,5, algorithm); [STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'robust_kmeans', clus_num}); end case 'neural network' [IDX,C] = neural_net(clustdata,clus_num); [STUDY] = std_createclust(STUDY, ALLEEG, 'clusterind', IDX, 'algorithm', {'Neural Network', clus_num}); otherwise disp('pop_clust: unknown algorithm return'); return end % If save updated STUDY to disk if strcmpi(save,'on') if (~isempty(STUDY.filename)) & (~isempty(STUDY.filepath)) STUDY = pop_savestudy(STUDY, 'filename', STUDY.filename, 'filepath', STUDY.filepath); else STUDY = pop_savestudy(STUDY); end end end STUDY.saved = 'no'; % IDX - index of cluster for each component. Ex: 63 components and 2 % clusters: IDX 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 function [STUDY] = std_createclust2_old(STUDY,IDX,C, algorithm) % Find the next available cluster index % ------------------------------------- clusters = []; cls = size(C,1); % number of cluster = number of row of centroid matrix 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 strcmp(STUDY.cluster(k).parent,STUDY.cluster(STUDY.etc.preclust.clustlevel).name) STUDY.cluster(k).preclust.preclustparams = STUDY.etc.preclust.preclustparams; clusters = [clusters k]; end end len = length(STUDY.cluster); if ~isempty(find(IDX==0)) %outliers exist firstind = 0; nc = nc + 1; len = len + 1; else firstind = 1; 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 = [ 'Cls ' num2str(k+nc)]; end % find indices % ------------ tmp = find(IDX==k); % IDX 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 = algorithm; STUDY.cluster(k+len).parent{end+1} = STUDY.cluster(STUDY.etc.preclust.clustlevel).name; STUDY.cluster(k+len).child = []; STUDY.cluster(k+len).preclust.preclustdata = STUDY.etc.preclust.preclustdata(tmp,:); STUDY.cluster(k+len).preclust.preclustparams = STUDY.etc.preclust.preclustparams; STUDY.cluster(k+len).preclust.preclustcomps = STUDY.etc.preclust.preclustcomps; %update parents clusters with cluster child indices % ------------------------------------------------- STUDY.cluster(STUDY.etc.preclust.clustlevel).child{end+1} = STUDY.cluster(k+nc).name; end clusters = [ clusters firstind+len:cls+len];%the new created clusters indices.
github
ZijingMao/baselineeegtest-master
pop_erspparams.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_erspparams.m
8,995
utf_8
670aed78afeb3667c344e153cf8879fc
% pop_erspparams() - Set plotting and statistics parameters for % computing and plotting STUDY mean (and optionally % single-trial) ERSP and ITC measures and measure % statistics. Settings are stored within the STUDY % structure (STUDY.etc.erspparams) which is used % whenever plotting is performed by the function % std_erspplot(). % Usage: % >> STUDY = pop_erspparams(STUDY, 'key', 'val', ...); % % Inputs: % STUDY - EEGLAB STUDY set % % ERSP/ITC image plotting options: % 'timerange' - [min max] ERSP/ITC plotting latency range in ms. % {default: the whole output latency range}. % 'freqrange' - [min max] ERSP/ITC plotting frequency range in ms. % {default: the whole output frequency range} % 'ersplim' - [mindB maxdB] ERSP plotting limits in dB % {default: from [ERSPmin,ERSPmax]} % 'itclim' - [minitc maxitc] ITC plotting limits (range: [0,1]) % {default: from [0,ITC data max]} % 'topotime' - [float] plot scalp map at specific time. A time range may % also be provide and the ERSP will be averaged over the % given time range. Requires 'topofreq' below to be set. % 'topofreq' - [float] plot scalp map at specific frequencies. As above % a frequency range may also be provided. % 'subbaseline' - ['on'|'off'] subtract the same baseline across conditions % for ERSP (not ITC). When datasets with different conditions % are recorded simultaneously, a common baseline spectrum % should be used. Note that this also affects the % results of statistics {default: 'on'} % 'maskdata' - ['on'|'off'] when threshold is not NaN, and 'groupstats' % or 'condstats' (above) are 'off', masks the data % for significance. % % See also: std_erspplot(), std_itcplot() % % Authors: Arnaud Delorme, CERCO, CNRS, 2006- % Copyright (C) Arnaud Delorme, 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 [ STUDY, com ] = pop_erspparams(STUDY, varargin); STUDY = default_params(STUDY); TMPSTUDY = STUDY; com = ''; if isempty(varargin) subbaseline = fastif(strcmpi(STUDY.etc.erspparams.subbaseline,'on'), 1, 0); vis = fastif(isnan(STUDY.etc.erspparams.topotime), 'off', 'on'); uilist = { ... {'style' 'text' 'string' 'ERSP/ITC plotting options' 'fontweight' 'bold' 'tag', 'ersp' } ... {'style' 'text' 'string' 'Time range in ms [Low High]'} ... {'style' 'edit' 'string' num2str(STUDY.etc.erspparams.timerange) 'tag' 'timerange' } ... {'style' 'text' 'string' 'Plot scalp map at time [ms]' 'visible' vis} ... {'style' 'edit' 'string' num2str(STUDY.etc.erspparams.topotime) 'tag' 'topotime' 'visible' vis } ... {'style' 'text' 'string' 'Freq. range in Hz [Low High]'} ... {'style' 'edit' 'string' num2str(STUDY.etc.erspparams.freqrange) 'tag' 'freqrange' } ... {'style' 'text' 'string' 'Plot scalp map at freq. [Hz]' 'visible' vis} ... {'style' 'edit' 'string' num2str(STUDY.etc.erspparams.topofreq) 'tag' 'topofreq' 'visible' vis } ... {'style' 'text' 'string' 'Power limits in dB [Low High]'} ... {'style' 'edit' 'string' num2str(STUDY.etc.erspparams.ersplim) 'tag' 'ersplim' } ... {'style' 'text' 'string' 'ITC limit (0-1) [High]'} ... {'style' 'edit' 'string' num2str(STUDY.etc.erspparams.itclim) 'tag' 'itclim' } ... {} {'style' 'checkbox' 'string' 'Compute common ERSP baseline (assumes additive baseline)' 'value' subbaseline 'tag' 'subbaseline' } }; evalstr = 'set(findobj(gcf, ''tag'', ''ersp''), ''fontsize'', 12);'; cbline = [0.07 1.1]; otherline = [ 0.6 .4 0.6 .4]; geometry = { 1 otherline otherline otherline cbline }; enablecond = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off'); enablegroup = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off'); [out_param userdat tmp res] = inputgui( 'geometry' , geometry, 'uilist', uilist, 'skipline', 'off', ... 'title', 'Set ERSP/ITC plotting parameters -- pop_erspparams()', 'eval', evalstr); if isempty(res), return; end; % decode input % ------------ if res.subbaseline, res.subbaseline = 'on'; else res.subbaseline = 'off'; end; res.topotime = str2num( res.topotime ); res.topofreq = str2num( res.topofreq ); res.timerange = str2num( res.timerange ); res.freqrange = str2num( res.freqrange ); res.ersplim = str2num( res.ersplim ); res.itclim = str2num( res.itclim ); % build command call % ------------------ options = {}; if ~strcmpi( res.subbaseline , STUDY.etc.erspparams.subbaseline ), options = { options{:} 'subbaseline' res.subbaseline }; end; if ~isequal(res.topotime , STUDY.etc.erspparams.topotime), options = { options{:} 'topotime' res.topotime }; end; if ~isequal(res.topofreq , STUDY.etc.erspparams.topofreq), options = { options{:} 'topofreq' res.topofreq }; end; if ~isequal(res.ersplim , STUDY.etc.erspparams.ersplim), options = { options{:} 'ersplim' res.ersplim }; end; if ~isequal(res.itclim , STUDY.etc.erspparams.itclim), options = { options{:} 'itclim' res.itclim }; end; if ~isequal(res.timerange, STUDY.etc.erspparams.timerange), options = { options{:} 'timerange' res.timerange }; end; if ~isequal(res.freqrange, STUDY.etc.erspparams.freqrange), options = { options{:} 'freqrange' res.freqrange }; end; if ~isempty(options) STUDY = pop_erspparams(STUDY, options{:}); com = sprintf('STUDY = pop_erspparams(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.erspparams), 'exact')) STUDY.etc.erspparams = setfield(STUDY.etc.erspparams, varargin{index}, varargin{index+1}); end; end; end; end; % scan clusters and channels to remove erspdata info if timerange etc. have changed % --------------------------------------------------------------------------------- if ~isequal(STUDY.etc.erspparams.timerange, TMPSTUDY.etc.erspparams.timerange) | ... ~isequal(STUDY.etc.erspparams.freqrange, TMPSTUDY.etc.erspparams.freqrange) | ... ~isequal(STUDY.etc.erspparams.subbaseline, TMPSTUDY.etc.erspparams.subbaseline) rmfields = { 'erspdata' 'ersptimes' 'erspfreqs' 'erspbase' 'erspdatatrials' 'ersptimes' 'erspfreqs' 'erspsubjinds' 'ersptrialinfo' ... 'itcdata' 'itctimes' 'itcfreqs' 'itcdatatrials' 'itctimes' 'itcfreqs' 'itcsubjinds' 'itctrialinfo' }; for iField = 1:length(rmfields) if isfield(STUDY.cluster, rmfields{iField}) STUDY.cluster = rmfield(STUDY.cluster, rmfields{iField}); end; if isfield(STUDY.changrp, rmfields{iField}) STUDY.changrp = rmfield(STUDY.changrp, rmfields{iField}); end; end; end; function STUDY = default_params(STUDY) if ~isfield(STUDY.etc, 'erspparams'), STUDY.etc.erspparams = []; end; if ~isfield(STUDY.etc.erspparams, 'topotime'), STUDY.etc.erspparams.topotime = []; end; if ~isfield(STUDY.etc.erspparams, 'topofreq'), STUDY.etc.erspparams.topofreq = []; end; if ~isfield(STUDY.etc.erspparams, 'timerange'), STUDY.etc.erspparams.timerange = []; end; if ~isfield(STUDY.etc.erspparams, 'freqrange'), STUDY.etc.erspparams.freqrange = []; end; if ~isfield(STUDY.etc.erspparams, 'ersplim' ), STUDY.etc.erspparams.ersplim = []; end; if ~isfield(STUDY.etc.erspparams, 'itclim' ), STUDY.etc.erspparams.itclim = []; end; if ~isfield(STUDY.etc.erspparams, 'maskdata' ), STUDY.etc.erspparams.maskdata = 'off'; end; %deprecated if ~isfield(STUDY.etc.erspparams, 'subbaseline' ), STUDY.etc.erspparams.subbaseline = 'off'; end;
github
ZijingMao/baselineeegtest-master
std_specplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_specplot.m
5,582
utf_8
a9230bd77bad7d1ec5ac55b5c61beed8
% std_specplot() - plot STUDY component cluster spectra, either mean spectra % for all requested clusters in the same figure, with spectra % for different conditions (if any) plotted in different colors, % or spectra for each specified cluster in a separate figure % for each condition, showing the cluster component spectra plus % the mean cluster spectrum (in bold). The spectra can be % plotted only if component spectra have been computed and % saved with the EEG datasets in Matlab files "[datasetname].icaspec" % using pop_preclust() or std_preclust(). Called by pop_clustedit(). % Calls std_readspec() and internal function std_plotcompspec() % Usage: % >> [STUDY] = std_specplot(STUDY, ALLEEG, key1, val1, key2, val2, ...); % >> [STUDY specdata specfreqs pgroup pcond pinter] = std_specplot(STUDY, ALLEEG, ...); % % 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(). % Optional inputs for component plotting: % 'clusters' - [numeric vector|'all'] indices of clusters to plot. % If no component indices ('comps' below) are given, the average % spectrums of the requested clusters are plotted in the same figure, % with spectrums for different conditions (and groups if any) plotted % in different colors. In 'comps' (below) mode, spectrum for each % specified cluster are plotted in separate figures (one per % condition), each overplotting cluster component spectrum plus the % average cluster spectrum 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'. % % Optional inputs for channel plotting: % '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) % '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 spectrum of all subjects. % % Other optional inputs: % 'plotmode' - ['normal'|'condensed'] 'normal' -> plot in a new figure; % 'condensed' -> plot all curves in the current figure in a % condensed fashion {default: 'normal'} % 'key','val' - All optional inputs to pop_specparams() are also accepted here % to plot subset of time, statistics etc. The values used by default % are the ones set using pop_specparams() and stored in the % STUDY structure. % Outputs: % STUDY - the input STUDY set structure with the plotted cluster mean spectra % added?? to allow quick replotting. % specdata - [cell] spectral data for each condition, group and subjects. % size of cell array is [nconds x ngroups]. Size of each element % is [freqs x subjects] for data channels or [freqs x components] % for component clusters. This array may be gicen as input % directly to the statcond() function or std_stats() function % to compute statistics. % specfreqs - [array] Sprectum point frequency values. % 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_specplot(STUDY,ALLEEG, 'clusters', 2, 'mode', 'apart'); % % Plot component spectra for STUDY cluster 2, plus the mean cluster % % spectrum (in bold). % % See also pop_clustedit(), pop_preclust() std_preclust(), pop_clustedit(), std_readspec() % % 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, specdata, allfreqs, pgroup, pcond, pinter] = std_specplot(STUDY, ALLEEG, varargin) if nargin < 2 help std_specplot; return; end; [STUDY, specdata, allfreqs, pgroup, pcond, pinter] = std_erpplot(STUDY, ALLEEG, 'datatype', 'spec', 'unitx', 'Hz', varargin{:});
github
ZijingMao/baselineeegtest-master
std_movecomp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_movecomp.m
6,804
utf_8
a592dff7e0ffc5b384d4dcc8b41d55b6
% std_movecomp() - Move ICA component(s) from one cluster to another. % % Usage: % >> [STUDY] = std_movecomp(STUDY, ALLEEG, from_cluster, to_cluster, comps); % Inputs: % STUDY - STUDY structure comprising all or some of the EEG datasets in ALLEEG. % ALLEEG - vector of EEG structures in the STUDY, typically created using % load_ALLEEG(). % from_cluster - index of the cluster components are to be moved from. % to_cluster - index of the cluster components are to be moved to. % comps - [int vector] indices of from_cluster components to move. % % Outputs: % STUDY - input STUDY structure with modified component reassignments. % % Example: % >> [STUDY] = std_movecomp(STUDY, ALLEEG, 10, 7, [2 7]); % % Move components 2 and 7 of Cluster 10 to Cluster 7. % % 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_movecomp(STUDY, ALLEEG, old_clus, new_clus, comps) icadefs; % Cannot move components if clusters have children clusters if ~isempty(STUDY.cluster(old_clus).child) | ~isempty(STUDY.cluster(new_clus).child) warndlg2('Cannot move components if clusters have children clusters!' , 'Aborting move components'); return; end if isempty(STUDY.cluster(old_clus).parent) | isempty(STUDY.cluster(new_clus).parent) % The Parent cluster warndlg2('Cannot move components to or from the Parent cluster - off all components in STUDY!' , 'Aborting move components'); return; end % Cannot move components if clusters have different parent % clusters (didn'y come from the same level of clustering), % unless the cluster, components are moved to, is an empty new cluster. if (length(STUDY.cluster(old_clus).parent) ~= length(STUDY.cluster(new_clus).parent)) & ~strcmp(STUDY.cluster(new_clus).parent, 'manual') warndlg2(strvcat('Cannot move components if clusters have different parent clusters!', ... 'This limitation will be fixed in the future'), 'Aborting move components'); return; end % Check if all parents are the same if (~strcmp(STUDY.cluster(new_clus).parent, 'manual')) if ~(sum(strcmp(STUDY.cluster(old_clus).parent, STUDY.cluster(new_clus).parent)) == length(STUDY.cluster(new_clus).parent))% different parent warndlg2(strvcat('Cannot move components if clusters have different parent clusters!', ... 'This limitation will be fixed in the future') , 'Aborting move components'); return; end end for ci = 1:length(comps) comp = STUDY.cluster(old_clus).comps(comps(ci)); sets = STUDY.cluster(old_clus).sets(:,comps(ci)); fprintf('Moving component %d from cluster %d to cluster %d, centroids will be recomputed\n',comp, old_clus, new_clus); %update new cluster indcomp = length(STUDY.cluster(new_clus).comps)+1; STUDY.cluster(new_clus).comps(indcomp) = comp;%with comp index STUDY.cluster(new_clus).sets(:,indcomp) = sets; %with set indices if strcmpi(STUDY.cluster(new_clus).parent, 'manual') STUDY.cluster(new_clus).preclust.preclustparams = STUDY.cluster(old_clus).preclust.preclustparams; STUDY.cluster(new_clus).parent = STUDY.cluster(old_clus).parent; STUDY.cluster(find(strcmp({STUDY.cluster.name},STUDY.cluster(new_clus).parent))).child{end+1} = STUDY.cluster(new_clus).name; end % update preclustering array % -------------------------- if strncmpi('Notclust',STUDY.cluster(old_clus).name,8) STUDY.cluster(new_clus).preclust.preclustparams = []; STUDY.cluster(new_clus).preclust.preclustdata = []; STUDY.cluster(new_clus).preclust.preclustcomp = []; disp('Important warning: pre-clustering information removed for target cluster'); disp('(this is because the component moved had no pre-clustering data associated to it)'); elseif ~strncmpi('Notclust',STUDY.cluster(new_clus).name,8) STUDY.cluster(new_clus).preclust.preclustdata(indcomp,:) = STUDY.cluster(old_clus).preclust.preclustdata(comps(ci),:); %with preclustdata end; % sort by sets % ------------ [tmp,sind] = sort(STUDY.cluster(new_clus).sets(1,:)); STUDY.cluster(new_clus).sets = STUDY.cluster(new_clus).sets(:,sind); STUDY.cluster(new_clus).comps = STUDY.cluster(new_clus).comps(sind); if ~isempty(STUDY.cluster(new_clus).preclust.preclustdata) STUDY.cluster(new_clus).preclust.preclustdata(sind,:) = STUDY.cluster(new_clus).preclust.preclustdata(:,:); end end %STUDY.cluster(new_clus).centroid = []; % remove centroid STUDY = rm_centroid(STUDY, new_clus); STUDY = rm_centroid(STUDY, old_clus); % Remove data from old cluster % left_comps - are all the components of the cluster after the % components that were moved to the new cluster were removed. left_comps = find(~ismember([1:length(STUDY.cluster(old_clus).comps)],comps)); STUDY.cluster(old_clus).comps = STUDY.cluster(old_clus).comps(left_comps); STUDY.cluster(old_clus).sets = STUDY.cluster(old_clus).sets(:,left_comps); if ~isempty(STUDY.cluster(old_clus).preclust.preclustdata) try, STUDY.cluster(old_clus).preclust.preclustdata = STUDY.cluster(old_clus).preclust.preclustdata(left_comps,:); catch, % this generates an unknown error but I was not able to reproduce it - AD Sept. 26, 2009 end; end; % update the component indices % ---------------------------- STUDY = std_selectdesign(STUDY, ALLEEG, STUDY.currentdesign); disp('Done.'); % remove cluster information % -------------------------- function STUDY = rm_centroid(STUDY, clsindex) keepfields = { 'name' 'parent' 'child' 'comps' 'sets' 'algorithm' 'preclust' }; allfields = fieldnames(STUDY.cluster); for index = 1:length(allfields) if isempty(strmatch(allfields{index}, keepfields)) STUDY.cluster = setfield( STUDY.cluster, { clsindex }, allfields{index}, []); end; end;
github
ZijingMao/baselineeegtest-master
std_plottf.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_plottf.m
14,843
utf_8
9c47a23b3c566b505a98c33727621f9f
% std_plottf() - plot ERSP/ITC images a component % or channel cluster in a STUDY. Also allows plotting scalp % maps. % Usage: % >> std_plottf( times, freqs, data, 'key', 'val', ...) % Inputs: % times - [vector] latencies in ms of the data points. % freqs - [vector] frequencies in Hz of the data points. % 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_plottf(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. % % Optional display parameters: % 'datatype' - ['ersp'|'itc'] data type {default: 'ersp'} % 'titles' - [cell array of string] titles for each of the subplots. % { default: none} % % Statistics options: % 'groupstats' - ['on'|'off'] Compute (or not) statistics across groups. % {default: 'off'} % 'condstats' - ['on'|'off'] Compute (or not) statistics across groups. % {default: 'off'} % '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} % 'maskdata' - ['on'|'off'] when threshold is non-NaN and not both % condition and group statistics are computed, the user % has the option to mask the data for significance. % {defualt: 'off'} % % Other plotting options: % 'plotmode' - ['normal'|'condensed'] statistics plotting mode: % 'condensed' -> plot statistics under the curves % (when possible); 'normal' -> plot them in separate % axes {default: 'normal'} % 'freqscale' - ['log'|'linear'|'auto'] frequency plotting scale. This % will only change the ordinate not interpolate the data. % If you change this option blindly, your frequency scale % might be innacurate {default: 'auto'} % 'ylim' - [min max] ordinate limits for ERP and spectrum plots % {default: all available data} % % ITC/ERSP image plotting options: % 'tftopoopt' - [cell array] tftopo() plotting options (ERSP and ITC) % 'caxis' - [min max] color axis (ERSP, ITC, scalp maps) % % Scalp map plotting options: % 'chanlocs' - [struct] channel location structure % % Author: Arnaud Delorme, CERCO, CNRS, 2006- % % See also: pop_erspparams(), pop_erpparams(), pop_specparams(), statcond() % 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_plottf(timevals, freqs, data, varargin) pgroup = []; pcond = []; pinter = []; if nargin < 2 help std_plottf; return; end; opt = finputcheck( varargin, { 'titles' 'cell' [] cellfun(@num2str, cell(20,20), 'uniformoutput', false); 'caxis' 'real' [] []; 'ersplim' 'real' [] []; % same as above 'itclim' 'real' [] []; % same as above 'ylim' 'real' [] []; 'tftopoopt' 'cell' [] {}; 'threshold' 'real' [] NaN; 'unitx' 'string' [] 'ms'; % just for titles 'unitcolor' 'string' {} 'dB'; 'chanlocs' 'struct' [] struct('labels', {}); 'freqscale' 'string' { 'log','linear','auto' } 'auto'; 'events' 'cell' [] {}; 'groupstats' 'cell' [] {}; 'condstats' 'cell' [] {}; 'interstats' 'cell' [] {}; 'maskdata' 'string' { 'on','off' } 'off'; 'datatype' 'string' { 'ersp','itc' 'erpim' } 'ersp'; 'plotmode' 'string' { 'normal','condensed' } 'normal' }, 'std_plottf'); if isstr(opt), error(opt); end; if all(all(cellfun('size', data, 3)==1)) opt.singlesubject = 'on'; 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; if ~isempty(opt.groupstats) & ~isempty(opt.condstats) & strcmpi(opt.maskdata, 'on') disp('Cannot use ''maskdata'' option with both condition stat. and group stat. on'); disp('Disabling statistics'); opt.groupstats = {}; opt.condstats = {}; opt.maskdata = 'off'; end; if ~isempty(opt.ersplim), opt.caxis = opt.ersplim; end; if ~isempty(opt.itclim), opt.caxis = opt.itclim; end; onecol = { 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b' }; manycol = { 'b' 'r' 'g' 'k' 'c' 'y' }; nc = size(data,1); ng = size(data,2); if nc >= ng, opt.transpose = 'on'; else opt.transpose = 'off'; end; % test log frequencies % -------------------- if length(freqs) > 2 & strcmpi(opt.freqscale, 'auto') midfreq = (freqs(3)+freqs(1))/2; if midfreq*.9999 < freqs(2) & midfreq*1.0001 > freqs(2), opt.freqscale = 'linear'; else opt.freqscale = 'log'; end; end; % condensed plot % -------------- if strcmpi(opt.plotmode, 'condensed') meanplot = zeros(size(data{1},1), size(data{1},2)); count = 0; for c = 1:nc for g = 1:ng if ~isempty(data{c,g}) meanplot = meanplot + mean(data{c,g},3); count = count+1; end; end; end; meanplot = meanplot/count; options = { 'chanlocs', opt.chanlocs, 'electrodes', 'off', 'cbar', 'on', ... 'cmode', 'separate', opt.tftopoopt{:} }; if strcmpi(opt.datatype, 'erpim'), options = { options{:} 'ylabel' 'Trials' }; end; if strcmpi(opt.freqscale, 'log'), options = { options{:} 'logfreq', 'native' }; end; tftopo( meanplot', timevals, freqs, 'title', opt.titles{1}, options{:}); currentHangle = gca; if ~isempty( opt.caxis ) caxis( currentHangle, opt.caxis ) end colorbarHandle = cbar; title(colorbarHandle,opt.unitcolor); axes(currentHangle); return; 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; % 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; % ------------------------------- % masking for significance of not % ------------------------------- statmask = 0; if strcmpi(opt.maskdata, 'on') && ~isnan(opt.threshold) && ... (~isempty(opt.condstats) || ~isempty(opt.condstats)) addc = 0; addr = 0; statmask = 1; end; % ------------------------- % plot time/frequency image % ------------------------- options = { 'chanlocs', opt.chanlocs, 'electrodes', 'off', 'cbar', 'off', ... 'cmode', 'separate', opt.tftopoopt{:} }; if strcmpi(opt.freqscale, 'log'), options = { options{:} 'logfreq', 'native' }; end; if strcmpi(opt.datatype, 'erpim'), options = { options{:} 'ylabel' 'Trials' }; end; % adjust figure size % ------------------ 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; tmpc = [inf -inf]; for c = 1:nc for g = 1:ng hdl(c,g) = mysubplot(nc+addr, ng+addc, g + (c-1)*(ng+addc), opt.transpose); if ~isempty(data{c,g}) tmpplot = mean(data{c,g},3); if ~isreal(tmpplot(1)), tmpplot = abs(tmpplot); end; if statmask, if ~isempty(opt.condstats), tmpplot(find(pcondplot{g}(:) == 0)) = 0; else tmpplot(find(pgroupplot{c}(:) == 0)) = 0; end; end; if ~isempty(opt.events) tmpevents = mean(opt.events{c,g},2); else tmpevents = []; end; tftopo( tmpplot, timevals, freqs, 'events', tmpevents, 'title', opt.titles{c,g}, options{:}); if isempty(opt.caxis) && ~isempty(tmpc) warning off; tmpc = [ min(min(tmpplot(:)), tmpc(1)) max(max(tmpplot(:)), tmpc(2)) ]; warning on; else if ~isempty(opt.caxis) caxis(opt.caxis); end; end; if c > 1 ylabel(''); end; end; % statistics accross groups % ------------------------- if g == ng && ng > 1 && ~isempty(opt.groupstats) && ~isinf(pgroupplot{c}(1)) && ~statmask hdl(c,g+1) = mysubplot(nc+addr, ng+addc, g + 1 + (c-1)*(ng+addc), opt.transpose); tftopo( pgroupplot{c}, timevals, freqs, 'title', opt.titles{c,g+1}, options{:}); caxis([-maxplot maxplot]); end; end; end; for g = 1:ng % statistics accross conditions % ----------------------------- if ~isempty(opt.condstats) && ~isinf(pcondplot{g}(1)) && ~statmask && nc > 1 hdl(nc+1,g) = mysubplot(nc+addr, ng+addc, g + c*(ng+addc), opt.transpose); tftopo( pcondplot{g}, timevals, freqs, 'title', opt.titles{nc+1,g}, options{:}); caxis([-maxplot maxplot]); end; end; % color scale % ----------- if isempty(opt.caxis) tmpc = [-max(abs(tmpc)) max(abs(tmpc))]; for c = 1:nc for g = 1:ng axes(hdl(c,g)); if ~isempty(tmpc) caxis(tmpc); end; end; end; end; % statistics accross group and conditions % --------------------------------------- if ~isempty(opt.groupstats) && ~isempty(opt.condstats) && ng > 1 && nc > 1 hdl(nc+1,ng+1) = mysubplot(nc+addr, ng+addc, g + 1 + c*(ng+addr), opt.transpose); tftopo( pinterplot, timevals, freqs, 'title', opt.titles{nc+1,ng+1}, options{:}); caxis([-maxplot maxplot]); ylabel(''); end; % color bars % ---------- axes(hdl(nc,ng)); cbar_standard(opt.datatype, ng, opt.unitcolor); if isnan(opt.threshold) && (nc ~= size(hdl,1) || ng ~= size(hdl,2)) ind = find(hdl(end:-1:1)); axes(hdl(end-ind(1)+1)); cbar_signif(ng, maxplot); end; % 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; % colorbar for ERSP and scalp plot % -------------------------------- function cbar_standard(datatype, ng, unitcolor); pos = get(gca, 'position'); tmpc = caxis; fact = fastif(ng == 1, 40, 20); tmp = axes('position', [ pos(1)+pos(3)+max(pos(3)/fact,0.006) pos(2) max(pos(3)/fact,0.01) pos(4) ]); set(gca, 'unit', 'normalized'); if strcmpi(datatype, 'itc') cbar(tmp, 0, tmpc, 10); ylim([0.5 1]); title('ITC','fontsize',10,'fontweight','normal'); elseif strcmpi(datatype, 'erpim') cbar(tmp, 0, tmpc, 5); else cbar(tmp, 0, tmpc, 5); title(unitcolor); 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)+max(pos(3)/fact,0.006) pos(2) max(pos(3)/fact,0.01) 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); % rapid filtering for ERP % ----------------------- function tmpdata2 = myfilt(tmpdata, lowpass, highpass, factor, filtertype) tmpdata2 = reshape(tmpdata, size(tmpdata,1), size(tmpdata,2)*size(tmpdata,3)*size(tmpdata,4)); tmpdata2 = eegfiltfft(tmpdata2',lowpass, highpass, factor, filtertype)'; tmpdata2 = reshape(tmpdata2, size(tmpdata,1), size(tmpdata,2), size(tmpdata,3), size(tmpdata,4));
github
ZijingMao/baselineeegtest-master
std_getindvar.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_getindvar.m
7,332
utf_8
6ae9d669af217a88f9cf15ea2478d5c6
% std_getindvar - get independent variables of a STUDY % % Usage: % [indvar indvarvals] = std_getindvar(STUDY); % [indvar indvarvals] = std_getindvar(STUDY, mode, scandesign); % % Input: % STUDY - EEGLAB STUDY structure % mode - ['datinfo'|'trialinfo'|'both'] get independent variables % linked to STUDY.datasetinfo, STUDY.datasetinfo.trialinfo or % both. Default is 'both'. % scandesign - [0|1] scan STUDY design for additional combinations of % independent variable values. Default is 0. % % Output: % indvar - [cell array] cell array of independent variable names % indvarvals - [cell array] cell array of independent variable values % % Authors: A. Delorme, CERCO/CNRS and SCCN/UCSD, 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 function [ factor factorvals subjects ] = std_getindvar(STUDY, mode, scandesign) if nargin < 1 help std_getindvar; return; end; factor = {}; factorvals = {}; subjects = {}; if nargin < 2, mode = 'both'; end; if nargin < 3, scandesign = 0; end; countfact = 1; setinfo = STUDY.datasetinfo; if strcmpi(mode, 'datinfo') || strcmpi(mode, 'both') % get trial info ff = fieldnames(setinfo); ff = setdiff_bc(ff, { 'filepath' 'filename' 'subject' 'index' 'ncomps' 'comps' 'trialinfo' }); for index = 1:length(ff) if isstr(getfield(setinfo(1), ff{index})) eval( [ 'tmpvals = unique_bc({ setinfo.' ff{index} '});' ] ); if length(tmpvals) > 1 factor{ countfact} = ff{index}; factorvals{countfact} = tmpvals; % get subject for each factor value for c = 1:length(tmpvals) eval( [ 'datind = strmatch(tmpvals{c}, { setinfo.' ff{index} '}, ''exact'');' ] ); subjects{ countfact}{c} = unique_bc( { setinfo(datind).subject } ); end; countfact = countfact + 1; end; else eval( [ 'tmpvals = unique_bc([ setinfo.' ff{index} ']);' ] ); if length(tmpvals) > 1 factor{ countfact} = ff{index}; factorvals{countfact} = mattocell(tmpvals); % get subject for each factor value for c = 1:length(tmpvals) eval( [ 'datind = find(tmpvals(c) == [ setinfo.' ff{index} ']);' ] ); subjects{ countfact}{c} = unique_bc( { setinfo(datind).subject } ); end; countfact = countfact + 1; end; end; end; end; % add ind. variables for trials % ----------------------------- if strcmpi(mode, 'trialinfo') || strcmpi(mode, 'both') % add trial info if isfield(setinfo, 'trialinfo') ff = fieldnames(setinfo(1).trialinfo); for index = 1:length(ff) % check if any of the datasets are using string for event type allFieldsPresent = cellfun(@(x)(isfield(x, ff{index})), { setinfo.trialinfo }); allFirstVal = cellfun(@(x)(getfield(x, ff{index})), { setinfo(allFieldsPresent).trialinfo }, 'uniformoutput', false); if any(cellfun(@isstr, allFirstVal)) alltmpvals = {}; for ind = 1:length(setinfo) if isfield(setinfo(ind).trialinfo, ff{index}) eval( [ 'tmpTrialVals = { setinfo(ind).trialinfo.' ff{index} ' };' ] ); if isnumeric(tmpTrialVals{1}) % convert to string if necessary tmpTrialVals = cellfun(@num2str, tmpTrialVals, 'uniformoutput', false); end; tmpvals = unique_bc(tmpTrialVals); else tmpvals = {}; end; if isempty(alltmpvals) alltmpvals = tmpvals; else alltmpvals = { alltmpvals{:} tmpvals{:} }; end; end; alltmpvals = unique_bc(alltmpvals); if length(alltmpvals) > 1 factor{ countfact} = ff{index}; factorvals{countfact} = alltmpvals; subjects{ countfact} = {}; countfact = countfact + 1; end; else alltmpvals = []; for ind = 1:length(setinfo) if isfield(setinfo(ind).trialinfo, ff{index}) eval( [ 'tmpvals = unique_bc([ setinfo(ind).trialinfo.' ff{index} ' ]);' ] ); else tmpvals = []; end; alltmpvals = [ alltmpvals tmpvals ]; end; alltmpvals = unique_bc(alltmpvals); if length(alltmpvals) > 1 factor{ countfact} = ff{index}; factorvals{countfact} = mattocell(alltmpvals); subjects{ countfact} = {}; countfact = countfact + 1; end; end; end; end; end; % scan existing design for additional combinations % ------------------------------------------------ if scandesign for desind = 1:length(STUDY.design) pos1 = strmatch(STUDY.design(desind).variable(1).label, factor, 'exact'); pos2 = strmatch(STUDY.design(desind).variable(2).label, factor, 'exact'); if ~isempty(pos1), add1 = mysetdiff(STUDY.design(desind).variable(1).value, factorvals{pos1}); else add1 = []; end; if ~isempty(pos2), add2 = mysetdiff(STUDY.design(desind).variable(2).value, factorvals{pos2}); else add2 = []; end; if ~isempty(add1), factorvals{pos1} = { factorvals{pos1}{:} add1{:} }; end; if ~isempty(add2), factorvals{pos2} = { factorvals{pos2}{:} add2{:} }; end; end; end; function cellout = mysetdiff(cell1, cell2); if isstr(cell2{1}) indcell = cellfun(@iscell, cell1); else indcell = cellfun(@(x)(length(x)>1), cell1); end; cellout = cell1(indcell); % if isstr(cell1{1}) && isstr(cell2{1}) % cellout = setdiff_bc(cell1, cell2); % elseif ~isstr(cell1{1}) && ~isstr(cell2{1}) % cellout = mattocell(setdiff( [ cell1{:} ], [ cell2{:} ])); % elseif isstr(cell1{1}) && ~isstr(cell2{1}) % cellout = setdiff_bc(cell1, cellfun(@(x)(num2str(x)),cell2, 'uniformoutput', false)); % elseif ~isstr(cell1{1}) && isstr(cell2{1}) % cellout = setdiff_bc(cellfun(@(x)(num2str(x)),cell1, 'uniformoutput', false), cell2); % end;
github
ZijingMao/baselineeegtest-master
std_uniformsetinds.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_uniformsetinds.m
1,311
utf_8
8c693e38166509a1a4f3be6994c4eb1e
% std_uniformsetinds() - Check uniform channel distribution accross datasets % % Usage: % >> boolval = std_uniformsetinds(STUDY); % Inputs: % STUDY - EEGLAB STUDY % % Outputs: % boolval - [0|1] 1 if uniform % % 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 uniformchannels = std_uniformsetinds( STUDY ); uniformchannels = 1; for c = 1:length(STUDY.changrp(1).setinds(:)) tmpind = cellfun(@(x)(length(x{c})), { STUDY.changrp(:).setinds }); if length(unique(tmpind)) ~= 1 uniformchannels = 0; end; end;
github
ZijingMao/baselineeegtest-master
std_topoplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_topoplot.m
14,216
utf_8
7cfb2105e7776f7634a43d7c02707060
% std_topoplot() - Command line function to plot cluster component and mean scalp maps. % Displays either mean cluster/s scalp map/s, or all cluster/s components % scalp maps with the mean cluster/s scsalp map in one figure. % The scalp maps can be visualized only if component scalp maps % were calculated and saved in the EEG datasets in the STUDY. % These can be computed during pre-clustering using the GUI-based function % pop_preclust() or the equivalent commandline functions eeg_createdata() % and eeg_preclust(). A pop-function that calls this function is % pop_clustedit(). % Usage: % >> [STUDY] = std_topoplot(STUDY, ALLEEG, key1, val1, key2, val2); % 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 | 'all'] -> indices of the cluster components to plot. % 'all' -> plot all the components in the cluster % {default: 'all'}. % 'mode' - ['together'|'apart'] a plotting mode. In 'together' mode, the average % scalp maps of the requested clusters are plotted in the same figure, % one per condition. In 'apart' mode, component scalp maps for each % cluster are plotted in a separate figure for each condition, plus the % cluster mean map. Note that this option is irrelevant if component % indices ('comps' above) are provided.{default: 'apart'}. % 'figure' - ['on'|'off'] for the 'together' mode option, plots on % a new figure ('on'), or on the current figure ('off'). % {default: 'on'}. % Outputs: % STUDY - the input STUDY set structure modified with plotted cluster scalp % map means, to allow quick replotting (unless clusters meands % already exists in th STUDY). % % Example: % % Plot the mean scalp maps for clusters 1 through 20 on the same figure. % >> [STUDY] = std_topoplot(STUDY,ALLEEG, 'clusters', [1:20], 'mode', 'together'); % % See also pop_clustedit(), pop_preclust() % % 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_topoplot(STUDY, ALLEEG, varargin) icadefs; % Set default values cls = []; mode = 'together'; % plot all cluster mean scalp maps on one figure figureon = 1; % plot on a new figure 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_topoplot: ''clusters'' input takes either specific clusters (numeric vector) or keyword ''all''.'); end end case 'plotsubjects' % legacy mode = 'apart'; case 'comps' if isstr( varargin{k-1} ), mode = 'apart'; else STUDY = std_plotcompmap(STUDY, ALLEEG, cls, varargin{k-1}); return; end; case 'mode' % Plotting mode 'together' / 'apart' mode = varargin{k-1}; case 'figure' if strcmpi(varargin{k-1},'off') figureon = 0; end case 'plotrad' inputPlotrad = varargin{k-1}; 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; % Plot all the components in the cluster disp('Drawing components of cluster (all at once)...'); if ~isfield(STUDY.cluster,'topo'), STUDY.cluster(1).topo = []; end; for clus = 1: length(cls) % For each cluster requested if isempty(STUDY.cluster(cls(clus)).topo) STUDY = std_readtopoclust(STUDY,ALLEEG, cls(clus)); end; end if strcmpi(mode, 'apart') for clus = 1: length(cls) % For each cluster requested len = length(STUDY.cluster(cls(clus)).comps); if len > 0 % A non-empty cluster h_topo = figure; rowcols(2) = ceil(sqrt(len + 4)); rowcols(1) = ceil((len+4)/rowcols(2)); clusscalp = STUDY.cluster(cls(clus)); ave_grid = clusscalp.topo; tmp_ave = ave_grid; tmp_ave(find(isnan(tmp_ave))) = 0; % remove NaN values from grid for later correlation calculation. 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; comp = STUDY.cluster(cls(clus)).comps(k); [Xi,Yi] = meshgrid(clusscalp.topoy,clusscalp.topox); scalpmap = squeeze(clusscalp.topoall{k}); % already correct polarity if k <= rowcols(2) - 2 %first sbplot row figure(h_topo); sbplot(rowcols(1),rowcols(2),k+2) , toporeplot(scalpmap, 'style', 'both', 'plotrad',0.5,'intrad',0.5, 'verbose', 'off','xsurface', Xi, 'ysurface', Yi ); title([subject '/' 'ic' num2str(comp) ], 'interpreter', 'none'); %waitbar(k/(len+1),h_wait) else %other sbplot rows figure(h_topo) sbplot(rowcols(1),rowcols(2),k+4) , toporeplot(scalpmap, 'style', 'both', 'plotrad',0.5,'intrad',0.5, 'verbose', 'off','xsurface', Xi, 'ysurface', Yi ); title([subject '/' 'ic' num2str(comp)], 'interpreter', 'none'); %waitbar(k/(len+1),h_wait) end end figure(h_topo) sbplot(rowcols(1),rowcols(2),[1 rowcols(2)+2 ]) , toporeplot(ave_grid, 'style', 'both', 'plotrad',0.5,'intrad',0.5, 'verbose', 'off'); title([ STUDY.cluster(cls(clus)).name ' (' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(clus)).comps)),' ICs)']); %title([ STUDY.cluster(cls(clus)).name ' average scalp map, ' num2str(length(unique(STUDY.cluster(cls(clus)).sets(1,:)))) 'Ss']); set(gcf,'Color', BACKCOLOR); %waitbar(1,h_wait) %delete(h_wait) orient tall % fill the figure page for printing axcopy end % Finished one cluster plot end % Finished plotting all clusters end % Finished 'apart' plotting mode % Plot clusters centroid maps if strcmpi(mode, 'together') len = length(cls); rowcols(2) = ceil(sqrt(len)); rowcols(1) = ceil((len)/rowcols(2)); if figureon try % optional 'CreateCancelBtn', 'delete(gcbf); error(''USER ABORT'');', h_wait = waitbar(0,'Computing topoplot ...', 'Color', BACKEEGLABCOLOR,'position', [300, 200, 300, 48]); catch % for Matlab 5.3 h_wait = waitbar(0,'Computing topoplot ...','position', [300, 200, 300, 48]); end figure end for k = 1:len if len ~= 1 sbplot(rowcols(1),rowcols(2),k) end tmpcmap = colormap(DEFAULT_COLORMAP); toporeplot(STUDY.cluster(cls(k)).topo, 'style', 'both', 'plotrad',0.5,'intrad',0.5, 'verbose', 'off','colormap', tmpcmap); title([ STUDY.cluster(cls(k)).name ' (' num2str(length(unique(STUDY.cluster(cls(k)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(k)).comps)),' ICs)']); %title([ STUDY.cluster(cls(k)).name ', ' num2str(length(unique(STUDY.cluster(cls(k)).sets(1,:)))) 'Ss' ]); if figureon waitbar(k/len,h_wait) end end if figureon delete(h_wait) end if len ~= 1 maintitle = 'Average scalp map for all clusters'; a = textsc(maintitle, 'title'); set(a, 'fontweight', 'bold'); set(gcf,'name', maintitle); else title([ STUDY.cluster(cls(k)).name ' (' num2str(length(unique(STUDY.cluster(cls(k)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(k)).comps)),' ICs)']); set(gcf,'name',['Scalp map of ' STUDY.cluster(cls(k)).name ' (' num2str(length(unique(STUDY.cluster(cls(k)).sets(1,:)))) ' Ss, ' num2str(length(STUDY.cluster(cls(k)).comps)),' ICs)']); %title([ STUDY.cluster(cls(k)).name ' scalp map, ' num2str(length(unique(STUDY.cluster(cls(k)).sets(1,:)))) 'Ss' ]); end set(gcf,'Color', BACKCOLOR); orient tall axcopy end % std_plotcompmap() - Commandline function, to visualizing cluster components scalp maps. % Displays the scalp maps of specified cluster components on separate figures. % The scalp maps can be visualized only if component scalp maps % were calculated and saved in the EEG datasets in the STUDY. % These can be computed during pre-clustering using the GUI-based function % pop_preclust() or the equivalent commandline functions eeg_createdata() % and eeg_preclust(). A pop-function that calls this function is pop_clustedit(). % Usage: % >> [STUDY] = std_plotcompmap(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 % (as in std_topoplot). {default: 'all'}. % % Outputs: % STUDY - the input STUDY set structure modified with plotted cluster scalp % map mean, to allow quick replotting (unless cluster mean % already existed in the STUDY). % % Example: % >> cluster = 4; comps= [1 7 10]; % >> [STUDY] = std_plotcompmap(STUDY,ALLEEG, cluster, comps); % Plots components 1, 7 & 10 scalp maps of cluster 4 on separate figures. % % See also pop_clustedit, pop_preclust, eeg_createdata, std_topoplot % % 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_plotcompmap(STUDY, ALLEEG, cls, varargin) icadefs; if ~exist('cls') error('std_plotcompmap: you must provide a cluster numberas an input.'); end if isempty(cls) error('std_plotcompmap: you must provide a cluster numberas an input.'); end if nargin == 3 % no component indices were given % Default: plot all components of the cluster [STUDY] = std_topoplot(STUDY, ALLEEG, 'clusters', cls, 'mode', 'apart'); return else comp_ind = varargin{1}; end STUDY = std_readtopoclust(STUDY,ALLEEG, cls); for ci = 1:length(comp_ind) abset = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).index; subject = STUDY.datasetinfo(STUDY.cluster(cls).sets(1,comp_ind(ci))).subject; comp = STUDY.cluster(cls).comps(comp_ind(ci)); grid = STUDY.cluster(cls).topoall{comp_ind(ci)}; xi = STUDY.cluster(cls).topox; yi = STUDY.cluster(cls).topoy; [Xi,Yi] = meshgrid(yi,xi); figure; toporeplot(grid, 'style', 'both', 'plotrad',0.5,'intrad',0.5,'xsurface', Xi, 'ysurface', Yi, 'verbose', 'off'); title([subject ' / ' 'IC' num2str(comp) ', ' STUDY.cluster(cls).name ]); set(gcf,'Color', BACKCOLOR); axcopy; end
github
ZijingMao/baselineeegtest-master
std_centroid.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_centroid.m
14,174
utf_8
f1be77fa82ecbcda91a416c38ccf6fb1
% std_centroid() - compute cluster centroid in EEGLAB dataset STUDY. % Compute and store the centroid(s) (i.e., mean(s)) % for some combination of six measures on specified % clusters in a STUDY. Possible measures include: scalp % maps, ERPs, spectra, ERSPs, ITCs, dipole_locations % Usage: % >> [STUDY, centroid] = std_centroid(STUDY, ALLEEG, ... % clusters, measure1, measure2, ...); % % Inputs: % STUDY - STUDY set % ALLEEG - ALLEEG dataset vector (else an EEG dataset) containing the STUDY % datasets, typically created using load_ALLEEG(). % clusters - [vector] of cluster indices. Computes measure means for the % specified clusters. {deffault|[]: compute means for all % STUDY clusters} % measure(s) - ['erp'|'spec'|'scalp'|'dipole'|'itc'|'ersp']. % The measures(s) for which to calculate the cluster centroid(s): % 'erp' -> mean ERP of each cluster. % 'dipole' -> mean dipole of each cluster. % 'spec' -> mean spectrum of each cluster (baseline removed). % 'scalp' -> mean topoplot scalp map of each cluster. % 'ersp' -> mean ERSP of each cluster. % 'itc' -> mean ITC of each cluster. % If [], re-compute the centroid for whichever centroids % have previously been computed. % Outputs: % STUDY - input STUDY structure with computed centroids added. % If the requested centroids already exist, overwites them. % centroid - cell array of centroid structures, each cell corrasponding % to a different cluster requested in 'clusters' (above). % fields of 'centroid' may include centroid.erp, centroid.dipole, % etc. (as above). The structure is similar as the output % of the std_readdata() function (with some fields % about the cluster name and index missing). % Examples: % % >> [STUDY, centroid] = std_centroid(STUDY, ALLEEG,[], 'scalp'); % % For each of the clusters in STUDY, compute a mean scalp map. % % The centroids are saved in the STUDY structure as entries in array % % STUDY.cluster(k).centroid.scalp. The centroids are also returned in % % a cell array the size of the clusters (i.e., in: centroid(k).scalp). % % >> [STUDY, centroid] = std_centroid(STUDY, ALLEEG,5,'spec','scalp'); % % Same as above, but now compute only two centroids for Cluster 5. % % The returned 'centroid' has two fields: centroid.scalp and centroid.spec % % 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 % Coding notes: Useful information on functions and global variables used. function [STUDY, centroid] = std_centroid(STUDY,ALLEEG, clsind, varargin); if nargin < 3 help std_centroid; return end if isempty(clsind) for k = 2: length(STUDY.cluster) %don't include the ParentCluster if ~strncmpi('Notclust',STUDY.cluster(k).name,8) % don't include 'Notclust' clusters clsind = [clsind k]; end end end %defult values erpC =0; specC =0 ; scalpC = 0; dipoleC = 0; itcC = 0; erspC = 0; commands = {}; if isempty(varargin) if isfield(STUDY.cluster(clsind(1)).centroid,'scalp') commands{end+1} = 'scalp'; end if isfield(STUDY.cluster(clsind(1)).centroid,'spec') commands{end+1} = 'spec'; end if isfield(STUDY.cluster(clsind(1)).centroid,'erp') commands{end+1} = 'erp'; end if isfield(STUDY.cluster(clsind(1)).centroid,'ersp') commands{end+1} = 'ersp'; end if isfield(STUDY.cluster(clsind(1)).centroid,'itc') commands{end+1} = 'itc'; end if isfield(STUDY.cluster(clsind(1)).centroid,'dipole') commands{end+1} = 'dipole'; end else commands = varargin; end Ncond = length(STUDY.condition); if Ncond == 0 Ncond = 1; end centroid = cell(length(clsind),1); fprintf('Computing '); for k = 1:length(clsind) for l = 1:Ncond for ind = 1:length(commands) ctr = commands{ind}; switch ctr case 'scalp' centroid{k}.scalp = 0; scalpC = 1; if (l ==1) & (k ==1) fprintf('scalp '); end case 'erp' centroid{k}.erp{l} = 0; erpC = 1; if (l ==1) & (k ==1) fprintf('erp '); end case 'spec' centroid{k}.spec{l} = 0; specC = 1; if (l ==1) & (k ==1) fprintf('spectrum '); end case 'ersp' centroid{k}.ersp{l} = 0; centroid{k}.ersp_limits{l} = 0; erspC =1; if (l ==1) & (k ==1) fprintf('ersp '); end case 'itc' centroid{k}.itc{l} = 0; centroid{k}.itc_limits{l} = 0; itcC = 1; if (l ==1) & (k ==1) fprintf('itc '); end case 'dipole' dipoleC =1; if (l ==1) & (k ==1) fprintf('dipole '); end end end end end fprintf('centroid (only done once)\n'); if itcC | erspC | specC | erpC | scalpC for clust = 1:length(clsind) %go over all requested clusters for cond = 1:Ncond %compute for all conditions for k = 1:length(STUDY.cluster(clsind(clust)).comps) % go through all components comp = STUDY.cluster(clsind(clust)).comps(k); abset = STUDY.cluster(clsind(clust)).sets(cond,k); if scalpC & cond == 1 %scalp centroid, does not depend on condition grid = std_readtopo(ALLEEG, abset, comp); if isempty(grid) return; end centroid{clust}.scalp = centroid{clust}.scalp + grid; end if erpC %erp centroid [erp, t] = std_readerp(ALLEEG, abset, comp, STUDY.preclust.erpclusttimes); fprintf('.'); if isempty(erp) return; end if (cond==1) & (k==1) all_erp = zeros(length(erp),length(STUDY.cluster(clsind(clust)).comps)); end all_erp(:,k) = erp'; if k == length(STUDY.cluster(clsind(clust)).comps) [all_erp pol] = std_comppol(all_erp); centroid{clust}.erp{cond} = mean(all_erp,2); centroid{clust}.erp_times = t; end end if specC %spec centroid [spec, f] = std_readspec(ALLEEG, abset, comp, STUDY.preclust.specclustfreqs); fprintf('.'); if isempty(spec) return; end centroid{clust}.spec{cond} = centroid{clust}.spec{cond} + spec; centroid{clust}.spec_freqs = f; end if erspC %ersp centroid fprintf('.'); if cond == 1 tmpabset = STUDY.cluster(clsind(clust)).sets(:,k); [ersp, logfreqs, timevals] = std_readersp(ALLEEG, tmpabset, comp, STUDY.preclust.erspclusttimes, ... STUDY.preclust.erspclustfreqs ); if isempty(ersp) return; end for m = 1:Ncond centroid{clust}.ersp{m} = centroid{clust}.ersp{m} + ersp(:,:,m); centroid{clust}.ersp_limits{m} = max(floor(max(max(abs(ersp(:,:,m))))), centroid{clust}.ersp_limits{m}); end centroid{clust}.ersp_freqs = logfreqs; centroid{clust}.ersp_times = timevals; end end if itcC %itc centroid fprintf('.'); [itc, logfreqs, timevals] = std_readitc(ALLEEG, abset, comp, STUDY.preclust.erspclusttimes, ... STUDY.preclust.erspclustfreqs ); if isempty(itc) return; end centroid{clust}.itc{cond} = centroid{clust}.itc{cond} + itc; centroid{clust}.itc_limits{cond} = max(floor(max(max(abs(itc)))), centroid{clust}.itc_limits{cond}); %ersp image limits centroid{clust}.itc_freqs = logfreqs; centroid{clust}.itc_times = timevals; end end end if ~scalpC fprintf('\n'); end; end end if dipoleC %dipole centroid for clust = 1:length(clsind) max_r = 0; len = length(STUDY.cluster(clsind(clust)).comps); tmppos = 0; tmpmom = 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; tmppos = tmppos + ALLEEG(abset).dipfit.model(comp).posxyz; tmpmom = tmpmom + ALLEEG(abset).dipfit.model(comp).momxyz; 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)).centroid.dipole = centroid{clust}.dipole; end end %updat STUDY for clust = 1:length(clsind) %go over all requested clusters for cond = 1:Ncond ncomp = length(STUDY.cluster(clsind(clust)).comps); if scalpC & cond == 1%scalp centroid centroid{clust}.scalp = centroid{clust}.scalp/ncomp; STUDY.cluster(clsind(clust)).centroid.scalp = centroid{clust}.scalp ; end if erpC STUDY.cluster(clsind(clust)).centroid.erp{cond} = centroid{clust}.erp{cond}; STUDY.cluster(clsind(clust)).centroid.erp_times = centroid{clust}.erp_times; end if specC centroid{clust}.spec{cond} = centroid{clust}.spec{cond}/ncomp; STUDY.cluster(clsind(clust)).centroid.spec{cond} = centroid{clust}.spec{cond}; STUDY.cluster(clsind(clust)).centroid.spec_freqs = centroid{clust}.spec_freqs; end if erspC %ersp centroid centroid{clust}.ersp{cond} = centroid{clust}.ersp{cond}/ncomp; STUDY.cluster(clsind(clust)).centroid.ersp{cond} = centroid{clust}.ersp{cond}; STUDY.cluster(clsind(clust)).centroid.ersp_limits{cond} = floor(0.75*centroid{clust}.ersp_limits{cond}); %[round(0.9*min(cell2mat({centroid{clust}.ersp_limits{cond,:}}))) round(0.9*max(cell2mat({centroid{clust}.ersp_limits{cond,:}})))]; STUDY.cluster(clsind(clust)).centroid.ersp_freqs = centroid{clust}.ersp_freqs; STUDY.cluster(clsind(clust)).centroid.ersp_times = centroid{clust}.ersp_times; end if itcC centroid{clust}.itc{cond} = centroid{clust}.itc{cond}/ncomp; STUDY.cluster(clsind(clust)).centroid.itc{cond} = centroid{clust}.itc{cond} ; STUDY.cluster(clsind(clust)).centroid.itc_limits{cond} = floor(0.75*centroid{clust}.itc_limits{cond});%round(0.9*max(cell2mat({centroid{clust}.itc_limits{cond,:}}))); STUDY.cluster(clsind(clust)).centroid.itc_freqs = centroid{clust}.itc_freqs; STUDY.cluster(clsind(clust)).centroid.itc_times = centroid{clust}.itc_times; end end end fprintf('\n');
github
ZijingMao/baselineeegtest-master
std_loadalleeg.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_loadalleeg.m
7,104
utf_8
377b0d5ee639622ea35859ef5af323cf
% std_loadalleeg() - constructs an ALLEEG structure, given the paths and file names % of all the EEG datasets that will be loaded into the ALLEEG % structure. The EEG datasets may be loaded without their EEG.data % (see the pop_editoptions() function), so many datasets can be % loaded simultaneously. The loaded EEG datasets have dataset % information and a (filename) pointer to the data. % Usage: % % Load sseveral EEG datasets into an ALLEEG structure. % >> ALLEEG = std_loadalleeg(paths,datasets) ; % >> ALLEEG = std_loadalleeg(STUDY) ; % Inputs: % paths - [cell array of strings] cell array with all the datasets paths. % datasets - [cell array of strings] cell array with all the datasets file names. % % Output: % ALLEEG - an EEGLAB data structure, which holds the loaded EEG sets % (can also be one EEG set). % Example: % >> paths = {'/home/eeglab/data/sub1/','/home/eeglab/data/sub2/', ... % >> '/home/eeglab/data/sub3/', '/home/eeglab/data/sub6/'}; % >> datasets = { 'visattS1', 'visattS2', 'visattS3', 'visattS4'}; % >> ALLEEG = std_loadalleeg(paths,datasets) ; % % See also: pop_loadstudy(), pop_study() % % Authors: Hilit Serby, Arnaud Delorme, SCCN, INC, UCSD, October , 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 function ALLEEG = std_loadalleeg(varargin) if nargin < 1 help std_loadalleeg; return; end; genpath = ''; oldgenpath = ''; if isstruct(varargin{1}) datasets = {varargin{1}.datasetinfo.filename}; try, paths = {varargin{1}.datasetinfo.filepath}; catch, paths = cell(1,length(datasets)); paths(:) = { '' }; end; genpath = varargin{1}.filepath; if isfield(varargin{1}.etc, 'oldfilepath') oldgenpath = varargin{1}.etc.oldfilepath; end; else paths = varargin{1}; if nargin > 1 datasets = varargin{2}; else datasets = paths; paths = cell(size(datasets)); end; end set = 1; ALLEEG = []; eeglab_options; % read datasets % ------------- warnfold = 'off'; for dset = 1:length(paths) if ~isempty(paths{dset}) comp = computer; if paths{dset}(2) == ':' & ~strcmpi(comp(1:2), 'PC') paths{dset} = [ filesep paths{dset}(4:end) ]; paths{dset}(find(paths{dset} == '\')) = filesep; end; end; [sub2 sub1] = fileparts(char(paths{dset})); [sub3 sub2] = fileparts(sub2); % priority is given to relative path of the STUDY if STUDY has moved if ~isequal(genpath, oldgenpath) && ~isempty(oldgenpath) disp('Warning: STUDY moved since last saved, trying to load data files using relative path'); if ~isempty(strfind(char(paths{dset}), oldgenpath)) relativePath = char(paths{dset}(length(oldgenpath)+1:end)); relativePath = fullfile(genpath, relativePath); else disp('Important warning: relative path cannot calculated, make sure the correct data files are loaded'); relativePath = char(paths{dset}); end; else relativePath = char(paths{dset}); end; % load data files if exist(fullfile(relativePath, datasets{dset})) == 2 EEG = pop_loadset('filename', datasets{dset}, 'filepath', relativePath, 'loadmode', 'info', 'check', 'off'); elseif exist(fullfile(char(paths{dset}), datasets{dset})) == 2 EEG = pop_loadset('filename', datasets{dset}, 'filepath', char(paths{dset}), 'loadmode', 'info', 'check', 'off'); elseif exist( fullfile(genpath, datasets{dset})) == 2 [tmpp tmpf ext] = fileparts(fullfile(genpath, datasets{dset})); EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off'); warnfold = 'on'; elseif exist( fullfile(genpath, sub1, datasets{dset})) == 2 [tmpp tmpf ext] = fileparts(fullfile(genpath, sub1, datasets{dset})); EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off'); warnfold = 'on'; elseif exist( fullfile(genpath, sub2, datasets{dset})) == 2 [tmpp tmpf ext] = fileparts(fullfile(genpath, sub2, datasets{dset})); EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off'); warnfold = 'on'; elseif exist( fullfile(genpath, sub2, sub1, datasets{dset})) == 2 [tmpp tmpf ext] = fileparts(fullfile(genpath, sub2, sub1, datasets{dset})); EEG = pop_loadset('filename', [tmpf ext], 'filepath',tmpp, 'loadmode', 'info', 'check', 'off'); warnfold = 'on'; elseif exist(lower(fullfile(char(paths{dset}), datasets{dset}))) == 2 EEG = pop_loadset('filename', lower(datasets{dset}), 'filepath',lower(char(paths{dset})), 'loadmode', 'info', 'check', 'off'); else txt = [ sprintf('The dataset %s is missing\n', datasets{dset}) 10 ... 'Is it possible that it might have been deleted?' 10 ... 'If this is the case, re-create the STUDY using the remaining datasets' ]; error(txt); end; EEG = eeg_checkset(EEG); if ~option_storedisk EEG = eeg_checkset(EEG, 'loaddata'); elseif ~isstr(EEG.data) EEG.data = 'in set file'; EEG.icaact = []; end; [ALLEEG EEG] = eeg_store(ALLEEG, EEG, 0, 'notext'); end ALLEEG = eeg_checkset(ALLEEG); if strcmpi(warnfold, 'on') & ~strcmpi(pwd, genpath) disp('Changing current path to STUDY path...'); cd(genpath); end; if strcmpi(warnfold, 'on') disp('This STUDY has a relative path set for the datasets'); disp('so the current path MUST remain the STUDY path'); end;
github
ZijingMao/baselineeegtest-master
std_propplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_propplot.m
8,354
utf_8
e7b216945a5dab56aa4be65b1672f850
% std_propplot() - Command line function to plot component cluster % properties for a STUDY set. % Displays mean cluster scalp map, ERP, ERSP; % dipole model, spectrum, and ITC in one figure % per cluster. Only meaasures computed during % pre-clustering (by pop_preclust() or std_preclust()) % are plotted. Called by pop_clustedit(). % Leaves the plotted grand mean cluster measures % in STUDY.cluster for quick replotting. % Usage: % >> [STUDY] = std_propplot(STUDY, ALLEEG, clusters); % Inputs: % STUDY - STUDY set including some or all EEG datasets in ALLEEG. % ALLEEG - vector of EEG dataset structures including the datasets % in the STUDY. Yypically created using load_ALLEEG(). % % Optional inputs: % clusters - [numeric vector | 'all'] -> cluster numbers to plot. % Else 'all' -> make plots for all clusters in the STUDY % {default: 'all'}. % Outputs: % STUDY - the input STUDY set structure modified with the plotted % cluster mean properties to allow quick replotting (unless % cluster means already existed in the STUDY). % Example: % % Plot mean properties of Cluster 5 in one figure. % >> [STUDY] = std_propplot(STUDY,ALLEEG, 5); % % See also: pop_clustedit() % % Authors: Arnaud Delorme, Hilit Serby, Scott Makeig, SCCN/INC/UCSD, 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 = std_propplot(STUDY, ALLEEG, varargin) icadefs; % read EEGLAB defaults warningon = 0; if iscell(varargin{1}) % channel plotting chans = varargin{1}; for k = 1: length(chans); figure orient tall set(gcf,'Color', BACKCOLOR); subplot(2,2,1), try, STUDY = std_erpplot(STUDY,ALLEEG, 'channels', chans(k), 'mode', 'together', 'plotmode', 'condensed' ); erpAxisHangle = gca; catch axis off; text(0.5, 0.5, 'No ERP information', 'horizontalalignment', 'center'); warningon = 1; end subplot(2,2,2), try, [STUDY] = std_erspplot(STUDY,ALLEEG, 'channels', chans(k), 'mode', 'together', 'plotmode', 'condensed' ); catch, axis off; text(0.5, 0.5, 'No ERSP information', 'horizontalalignment', 'center'); warningon = 1; end subplot(2,2,3), try, STUDY = std_specplot(STUDY,ALLEEG, 'channels', chans(k), 'mode', 'together', 'plotmode', 'condensed'); catch axis off; text(0.5, 0.5, 'No spectral information', 'horizontalalignment', 'center'); warningon = 1; end subplot(2,2,4), try, [STUDY] = std_itcplot(STUDY,ALLEEG, 'channels', chans(k), 'mode', 'together', 'plotmode', 'condensed' ); catch, axis off; text(0.5, 0.5, 'No ITC information', 'horizontalalignment', 'center'); warningon = 1; end %subplot('position', [0.77 0.16 0.15 0.28]), maintitle = ['Channel ''' chans{k} ''' average properties' ]; a = textsc(maintitle, 'title'); set(a, 'fontweight', 'bold'); if warningon disp('Some properties could not be plotted. To plot these properties, first'); disp('include them in pre-clustering. There, specify 0 dimensions if you do'); disp('now want a property (scalp map, ERSP, etc...) to be included'); disp('in the clustering procedure. See the clustering tutorial.'); end; end % Finished all conditions return; end; % Set default values cls = 1:length(STUDY.cluster); % plot all clusters in STUDY if length(varargin) > 0 if length(varargin) == 1, varargin{2} = varargin{1}; end; % backward compatibility if isnumeric(varargin{2}) cls = varargin{2}; elseif isstr(varargin{2}) & strcmpi(varargin{2}, 'all') cls = 1:length(STUDY.cluster); else error('cluster input should be either a vector of cluster indices or the keyword ''all''.'); end end len = length(cls); % Plot clusters mean properties for k = 1: len if k == 1 try % optional 'CreateCancelBtn', 'delete(gcbf); error(''USER ABORT'');', h_wait = waitbar(0,['Computing cluster properties ...'], 'Color', BACKEEGLABCOLOR,'position', [300, 200, 300, 48]); catch % for Matlab 5.3 h_wait = waitbar(0,['Computing cluster properties ...'],'position', [300, 200, 300, 48]); end end warningon = 0; figure orient tall set(gcf,'Color', BACKCOLOR); subplot(2,3,1), try, STUDY = std_topoplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'together', 'figure', 'off'); catch axis off; text(0.5, 0.5, 'No scalp map information', 'horizontalalignment', 'center'); warningon = 1; end waitbar(k/(len*6),h_wait) subplot(2,3,2), try, STUDY = std_erpplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'together', 'plotmode', 'condensed' ); erpAxisHangle = gca; catch axis off; text(0.5, 0.5, 'No ERP information', 'horizontalalignment', 'center'); warningon = 1; end waitbar((k*2)/(len*6),h_wait) subplot(2,3,3), try, [STUDY] = std_erspplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'together', 'plotmode', 'condensed' ); catch, axis off; text(0.5, 0.5, 'No ERSP information', 'horizontalalignment', 'center'); warningon = 1; end waitbar((k*3)/(len*6),h_wait) axes('unit', 'normalized', 'position', [0.1 0.16 0.2 0.28]); %subplot(2,3,4), try, STUDY = std_dipplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'apart', 'figure', 'off'); set(gcf,'Color', BACKCOLOR); catch axis off; text(0.5, 0.5, 'No dipole information', 'horizontalalignment', 'center'); warningon = 1; end waitbar((k*4)/(len*6),h_wait) subplot(2,3,5), try, STUDY = std_specplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'together', 'plotmode', 'condensed'); catch axis off; text(0.5, 0.5, 'No spectral information', 'horizontalalignment', 'center'); warningon = 1; end waitbar((k*5)/(len*6),h_wait) subplot(2,3,6), try, [STUDY] = std_itcplot(STUDY,ALLEEG, 'clusters', cls(k), 'mode', 'together', 'plotmode', 'condensed' ); catch, axis off; text(0.5, 0.5, 'No ITC information', 'horizontalalignment', 'center'); warningon = 1; end waitbar((k*6)/(len*6),h_wait); %subplot('position', [0.77 0.16 0.15 0.28]), maintitle = ['Cluster ''' STUDY.cluster(cls(k)).name ''' mean properties (' num2str(length(STUDY.cluster(cls(k)).comps)) ' comps).' ]; a = textsc(maintitle, 'title'); set(a, 'fontweight', 'bold'); set(gcf,'name',maintitle); if warningon disp('Some properties could not be plotted. To plot these properties, first'); disp('include them in pre-clustering. There, specify 0 dimensions if you do'); disp('not want a property (scalp map, ERSP, etc...) to be included'); disp('in the clustering procedure. See the clustering tutorial.'); end; end % Finished all conditions if ishandle(erpAxisHangle) % make sure it is a valid graphics handle legend(erpAxisHangle,'off'); set(erpAxisHangle,'YTickLabelMode','auto'); set(erpAxisHangle,'YTickMode','auto'); end; delete(h_wait)
github
ZijingMao/baselineeegtest-master
robust_kmeans.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/robust_kmeans.m
2,982
utf_8
b864201b216bd48106be885d09d04273
% robust_kmeans() - an extension of Matlab kmeans() that removes outlier % components from all clusters. % This is a helper function called from pop_clust(). function [IDX,C,sumd,D,outliers] = robust_kmeans(data,N,STD,MAXiter,method) % data - pre-clustering data matrix. % N - number of wanted clusters. if nargin < 5 method = 'kmeans'; end; flag = 1; not_outliers = 1:size(data,1); old_outliers = []; if strcmpi(method, 'kmeans') [IDX,C,sumd,D] = kmeans(data,N,'replicates',30,'emptyaction','drop'); % Cluster using K-means algorithm else [IDX,C,sumd,D] = kmeanscluster(data,N); % Cluster using K-means algorithm end; if STD >= 2 % STD for returned outlier rSTD = STD -1; else rSTD = STD; end loop = 0; while flag loop = loop + 1; std_all = []; ref_D = 0; for k = 1:N tmp = ['cls' num2str(k) ' = find(IDX==' num2str(k) ')''; ' ]; %find the component indices belonging to each cluster (cls1 = ...). eval(tmp); tmp = ['std' num2str(k) ' = std(D(cls' num2str(k) ' ,' num2str(k) ')); ' ]; %compute the std of each cluster eval(tmp); std_all = [std_all ['std' num2str(k) ' ']]; tmp = [ 'ref_D = ' num2str(ref_D) ' + mean(D(cls' num2str(k) ' ,' num2str(k) '));' ]; eval(tmp); end std_all = [ '[ ' std_all ' ]' ]; std_all = eval(std_all); % Find the outliers % Outlier definition - its distance from its cluster center is bigger % than STD times the std of the cluster, as long as the distance is bigger % than the mean distance times STD (avoid problems where all points turn to be outliers). outliers = []; ref_D = ref_D/N; for k = 1:N tmp = ['cls' num2str(k) '(find(D(find(IDX==' num2str(k) ')'' , ' num2str(k) ') > ' num2str(STD) '*std' num2str(k) ')); ' ]; optionalO = eval(tmp); Oind = find(D(optionalO,k) > ref_D*STD); outliers = [outliers optionalO(Oind)]; end if isempty(outliers) | (loop == MAXiter) flag = 0; end l = length(old_outliers); returned_outliers = []; for k = 1:l tmp = sum((C-ones(N,1)*data(old_outliers(k),:)).^2,2)'; % Find the distance of each former outlier to the current cluster if isempty(find(tmp <= std_all*rSTD)) %Check if the outlier is still an outlier (far from each cluster center more than STD-1 times its std). returned_outliers = [returned_outliers old_outliers(k)]; end; end outliers = not_outliers(outliers); outliers = [outliers returned_outliers ]; tmp = ones(1,size(data,1)); tmp(outliers) = 0; not_outliers = (find(tmp==1)); if strcmpi(method, 'kmeans') [IDX,C,sumd,D] = kmeans(data(not_outliers,:),N,'replicates',30,'emptyaction','drop'); else [IDX,C,sumd,D] = kmeanscluster(data(not_outliers,:),N); end; old_outliers = outliers; old_IDX = zeros(size(data,1),1); old_IDX(sort(not_outliers)) = IDX; end IDX = old_IDX;
github
ZijingMao/baselineeegtest-master
std_interp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_interp.m
6,657
utf_8
7117e3e4255231bb8538847cbb3531b2
% std_interp() - interpolate, if needed, a list of named data channels % for all datasets included in a STUDY. Currently assumes % that all channels have uniform locations across datasets. % % Usage: >> [STUDY ALLEEG] = std_interp(STUDY, ALLEEG, chans, method); % % Inputs: % STUDY - EEGLAB STUDY structure % ALLEEG - EEGLAB vector containing all EEG dataset structures in the STUDY. % chans - [Cell array] cell array of channel names (labels) to interpolate % into the data if they are missing from one of the datasets. % method - [string] griddata() method to use for interpolation. % See >> help eeg_interp() {default:'spherical'} % % Important limitation: % This function currently presuposes that all datasets have the same channel % locations (with various channels from a standard set possibly missing). % If this is not the case, the interpolation will not be performed. % % Output: % STUDY - study structure. % ALLEEG - updated datasets. % % Author: Arnaud Delorme, CERCO, CNRS, August 2006- % % See also: eeg_interp() % Copyright (C) Arnaud Delorme, CERCO, 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 % Deprecated: % - [chanlocs structure] channel location structure containing % a full channel structure (missing channels in the current % dataset are interpolated). function [STUDY, ALLEEG] = std_interp(STUDY, ALLEEG, chans, method); if nargin < 2 help std_interp; return; end; if nargin < 3 chans = []; end; if nargin < 4 method = 'spherical'; end; % union of all channel structures % ------------------------------- alllocs = eeg_mergelocs(ALLEEG.chanlocs); % check electrode names to interpolate % ------------------------------------ if iscell(chans) alllabs = lower({ alllocs.labels }); for index = 1:length(chans) tmpind = strmatch(lower(chans{index}), alllabs, 'exact'); if isempty(tmpind) error( sprintf('Channel named ''%s'' not found in any dataset', chans{index})); end; end; end; % read all STUDY datasets and interpolate electrodes % --------------------------------------------------- for index = 1:length(STUDY.datasetinfo) tmpind = STUDY.datasetinfo(index).index; tmplocs = ALLEEG(tmpind).chanlocs; % build electrode location structure for interpolation % ---------------------------------------------------- [tmp tmp2 id1] = intersect_bc({tmplocs.labels}, {alllocs.labels}); if isempty(chans) interplocs = alllocs; elseif iscell(chans) [tmp tmp2 id2] = intersect_bc( chans, {alllocs.labels}); interplocs = alllocs(union(id1, id2)); else interplocs = chans; end; if length(interplocs) ~= length(tmplocs) % search for position of electrode in backup structure % ---------------------------------------------- extrachans = []; if isfield(ALLEEG(tmpind).chaninfo, 'nodatchans') if isfield(ALLEEG(tmpind).chaninfo.nodatchans, 'labels') extrachans = ALLEEG(tmpind).chaninfo.nodatchans; end; end; tmplabels = { tmplocs.labels }; for i=1:length(interplocs) ind = strmatch( interplocs(i).labels, tmplabels, 'exact'); if ~isempty(ind) interplocs(i) = tmplocs(ind); % this is necessary for polhemus elseif ~isempty(extrachans) ind = strmatch( interplocs(i).labels, { extrachans.labels }, 'exact'); if ~isempty(ind) fprintf('Found position of %s in chaninfo structure\n', interplocs(i).labels); interplocs(i) = extrachans(ind); end; end; end; % perform interpolation % --------------------- EEG = eeg_retrieve(ALLEEG, index); EEG = eeg_checkset(EEG); EEG = eeg_interp(EEG, interplocs, method); EEG.saved = 'no'; EEG = pop_saveset(EEG, 'savemode', 'resave'); % update dataset in EEGLAB % ------------------------ if isstr(ALLEEG(tmpind).data) tmpdata = ALLEEG(tmpind).data; [ ALLEEG EEG ] = eeg_store(ALLEEG, EEG, tmpind); ALLEEG(tmpind).data = tmpdata; ALLEEG(tmpind).saved = 'yes'; clear EEG; else [ ALLEEG EEG ] = eeg_store(ALLEEG, EEG, tmpind); ALLEEG(tmpind).saved = 'yes'; end; else fprintf('No need for interpolation for dataset %d\n', tmpind); end; end; function checkchans(STUDY, ALLEEG) % Check to see if all the channels have the same coordinates % (check only the theta field) % ---------------------------------------------------------- for index = 1:length(STUDY.datasetinfo) tmpind = STUDY.datasetinfo(index).index; tmplocs = ALLEEG(tmpind).chanlocs; [tmp id1 id2] = intersect_bc({tmplocs.labels}, {alllocs.labels}); for ind = 1:length(id1) if tmplocs(id1(ind)).theta ~= alllocs(id2(ind)).theta % find datasets with different coordinates % ---------------------------------------- for ind2 = 1:length(STUDY.datasetinfo) tmplocs2 = ALLEEG(ind2).chanlocs; tmpmatch = strmatch(alllocs(id2(ind)).labels, { tmplocs2.labels }, 'exact'); if ~isempty(tmpmatch) if alllocs(id2(ind)).theta == tmplocs2(tmpmatch).theta datind = ind2; break; end; end; end; error(sprintf( [ 'Dataset %d and %d do not have the same channel location\n' ... 'for electrode ''%s''' ], datind, tmpind, tmplocs(id1(ind)).labels)); end; end; end;
github
ZijingMao/baselineeegtest-master
std_chaninds.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_chaninds.m
2,244
utf_8
f67a5b8ff7e1719881c3267bb7140eba
% std_chaninds() - look up channel indices in a STUDY % % Usage: % >> inds = std_chaninds(STUDY, channames); % >> inds = std_chaninds(EEG, channames); % >> inds = std_chaninds(chanlocs, channames); % Inputs: % STUDY - studyset structure containing a changrp substructure. % EEG - EEG structure containing channel location structure % chanlocs - channel location structure % channames - [cell] channel names % % Outputs: % inds - [integer array] channel indices % % 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 finalinds = std_chaninds(instruct, channames); finalinds = []; if isfield(instruct, 'chanlocs') EEG = instruct; tmpchanlocs = EEG.chanlocs; tmpallchans = lower({ tmpchanlocs.labels }); elseif isfield(instruct, 'filename') tmpallchans = lower({ instruct.changrp.name }); else tmpallchans = instruct; end; if ~iscell(channames), channames = { channames }; end; if isempty(channames), finalinds = [1:length(tmpallchans)]; return; end; for c = 1:length(channames) if isnumeric(channames) chanind = channames(c); else chanind = strmatch( lower(channames{c}), tmpallchans, 'exact'); if isempty(chanind), warning(sprintf([ 'Channel "%s" and maybe others was not' 10 'found in pre-computed data file' ], channames{c})); end; end; finalinds = [ finalinds chanind ]; end;
github
ZijingMao/baselineeegtest-master
pop_statparams.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/pop_statparams.m
23,702
utf_8
93899b57bb471babe075eb43b1944db6
% pop_statparams() - helper function for pop_erspparams, pop_erpparams, and % pop_specparams. % % Usage: % >> struct = pop_statparams(struct, 'default'); % >> struct = pop_statparams(struct, 'key', 'val', ...); % % Inputs: % struct - parameter structure. When called with the 'default' % option only, the function creates all the fields in % the structure and populate these fields with default % values. % % Statistics options: % 'groupstats' - ['on'|'off'] Compute statistics across subject % groups {default: 'off'} % 'condstats' - ['on'|'off'] Compute statistics across data % conditions {default: 'off'} % 'statistics' - ['param'|'perm'|'bootstrap'] Type of statistics to compute % 'param' for parametric (t-test/anova); 'perm' for % permutation-based and 'bootstrap' for bootstrap % {default: 'param'} % 'singletrials' - ['on'|'off'] use single trials to compute statistics. % This requires the measure to be computed with the % 'savetrials', 'on' option. % % EEGLAB statistics: % 'method' - ['parametric'|'permutation'|'bootstrap'] statistical % method. See help statcond for more information. % 'naccu' - [integer] Number of surrogate data averages to use in % surrogate statistics. For instance, if p<0.01, % use naccu>200. For p<0.001, naccu>2000. If a 'threshold' % (not NaN) is set below and 'naccu' is too low, it will % be automatically increased. (This keyword is currently % only modifiable from the command line, not from the gui). % 'alpha' - [NaN|alpha] Significance threshold (0<alpha<<1). Value % NaN will plot p-values for each time and/or frequency % on a different axis. If alpha is used, significant time % and/or frequency regions will be indicated either on % a separate axis or (whenever possible) along with the % data {default: NaN} % 'mcorrect' - ['fdr'|'holms'|'bonferoni'|'none'] correction for multiple % comparisons. 'fdr' uses false discovery rate. See the fdr % function for more information. Defaut is % none'. % % Fieldtrip statistics: % 'fieldtripnaccu' - [integer] Number of surrogate data averages to use in % surrogate statistics. % 'fieldtripalpha' - [alpha] Significance threshold (0<alpha<<1). This % parameter is mandatory. Default is 0.05. % 'fieldtripmcorrect' - ['cluster'|'max'|'fdr'|'holms'|'bonferoni'|'none'] % correction for multiple comparisons. See help % ft_statistics_montecarlo for more information. % 'fieldtripclusterparam - [string] parameters for clustering. See help % ft_statistics_montecarlo for more information. % 'fieldtripchannelneighbor - [struct] channel neighbor structure. % 'fieldtripchannelneighborparam' - [string] parameters for channel % neighbor. See help ft_statistics_montecarlo for more % information. % % Legacy parameters: % 'threshold' - now 'alpha' % 'statistics' - now 'method' % % Authors: Arnaud Delorme, CERCO, CNRS, 2010- % Copyright (C) Arnaud Delorme, 2010 % % 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_statparams(STUDY, varargin); com = ''; if isfield(STUDY, 'etc') if ~isfield(STUDY.etc, 'statistics') STUDY.etc.statistics = default_stats([]); else STUDY.etc.statistics = default_stats(STUDY.etc.statistics); end; if length(varargin) == 1 && strcmpi(varargin{1}, 'default') return; end; end; if isempty(varargin) && ~isempty(STUDY) if ~exist('ft_freqstatistics'), fieldtripInstalled = false; else fieldtripInstalled = true; end; opt.enablecond = fastif(length(STUDY.design(STUDY.currentdesign).variable(1).value)>1, 'on', 'off'); opt.enablegroup = fastif(length(STUDY.design(STUDY.currentdesign).variable(2).value)>1, 'on', 'off'); opt.enablesingletrials = 'on'; % encode parameters % ----------------- paramstruct = STUDY.etc.statistics; eeglabStatvalues = { 'param' 'perm' 'bootstrap' }; fieldtripStatvalues = { 'analytic' 'montecarlo' }; mCorrectList = { 'none' 'bonferoni' 'holms' 'fdr' 'max' 'cluster' }; condstats = fastif(strcmpi(paramstruct.condstats, 'on'), 1, 0); groupstats = fastif(strcmpi(paramstruct.groupstats,'on'), 1, 0); statmode = fastif(strcmpi(paramstruct.singletrials,'on'), 1, 0); eeglabThresh = fastif(isnan(paramstruct.eeglab.alpha),'exact', num2str(paramstruct.eeglab.alpha)); fieldtripThresh = fastif(isnan(paramstruct.fieldtrip.alpha),'exact', num2str(paramstruct.fieldtrip.alpha)); eeglabStat = strmatch(paramstruct.eeglab.method, eeglabStatvalues); fieldtripStat = strmatch(paramstruct.fieldtrip.method, fieldtripStatvalues); eeglabRand = fastif(isempty(paramstruct.eeglab.naccu), 'auto', num2str(paramstruct.eeglab.naccu)); fieldtripRand = fastif(isempty(paramstruct.fieldtrip.naccu), 'auto', num2str(paramstruct.fieldtrip.naccu)); eeglabMcorrect = strmatch(paramstruct.eeglab.mcorrect, mCorrectList); fieldtripMcorrect = strmatch(paramstruct.fieldtrip.mcorrect, mCorrectList); fieldtripClust = paramstruct.fieldtrip.clusterparam; fieldtripChan = paramstruct.fieldtrip.channelneighborparam; combootstrap = [ 'warndlg2( strvcat(''Warning: bootstrap is selected. Bootstrap currently'',' ... '''overestimates significance by a factor of 2 for paired data '',' ... '''(unpaired data is working properly). You should use'',' ... '''permutation instead of bootstrap if you have paired data.'') );' ]; cb_bootstrap = [ 'if get(gcbo, ''value'') == 3,' combootstrap ' end;' ]; cb_help_neighbor = 'pophelp(''ft_prepare_neighbours'');'; cb_help_cluster = 'pophelp(''ft_statistics_montecarlo'');'; cb_textSyntax = 'try, eval( [ ''{'' get(gcbo, ''string'') ''};'' ]); catch, warndlg2(''Syntax error''); end;'; if strcmpi(opt.enablecond , 'off') && condstats == 1, condstats = 0; end; if strcmpi(opt.enablegroup, 'off') && groupstats == 1, groupstats = 0; end; % callback for randomization selection % ------------------------------------ cbSelectRandEeglab = [ 'set(findobj(gcbf, ''tag'', ''eeglabnaccu''), ''enable'', ''on'');' ... 'set(findobj(gcbf, ''tag'', ''eeglabnaccutext''),''enable'', ''on'');' ]; cbUnselectRandEeglab = [ 'set(findobj(gcbf, ''tag'', ''eeglabnaccu''), ''enable'', ''off'');' ... 'set(findobj(gcbf, ''tag'', ''eeglabnaccutext''),''enable'', ''off'');' ]; cbSelectRandFieldtrip = [ 'set(findobj(gcbf, ''tag'', ''fieldtripnaccu''), ''enable'', ''on'');' ... 'set(findobj(gcbf, ''tag'', ''fieldtripnaccutext''),''enable'', ''on'');' ]; cbUnselectRandFieldtrip = [ 'set(findobj(gcbf, ''tag'', ''fieldtripnaccu''), ''enable'', ''off'');' ... 'set(findobj(gcbf, ''tag'', ''fieldtripnaccutext''),''enable'', ''off'');' ]; cbSetFullMcorrectFieldtrip = 'set(findobj(gcbf, ''tag'', ''fieldtripmcorrect''), ''string'', ''Do not correct for multiple comparisons|Use Bonferoni correction|Use Holms correction|Use FDR correction|Use max correction|Use cluster correction (CC)'');'; cbUnsetFullMcorrectFieldtrip = 'set(findobj(gcbf, ''tag'', ''fieldtripmcorrect''), ''value'', min(4, get(findobj(gcbf, ''tag'', ''fieldtripmcorrect''), ''value'')), ''string'', ''Do not correct for multiple comparisons|Use Bonferoni correction|Use Holms correction|Use FDR correction'');'; cb_eeglab_statlist = [ 'if get(findobj(gcbf, ''tag'', ''stateeglab'' ),''value'') > 1,' cbSelectRandEeglab ',else,' cbUnselectRandEeglab ',end;' ]; cb_fieldtrip_statlist = [ 'if get(findobj(gcbf, ''tag'', ''statfieldtrip'' ),''value'') > 1,' cbSelectRandFieldtrip cbSetFullMcorrectFieldtrip ',else,' cbUnselectRandFieldtrip cbUnsetFullMcorrectFieldtrip ',end;' ]; % callback for activating clusters inputs % --------------------------------------- cb_select_cluster = [ 'set(findobj(gcbf, ''tag'', ''clustertext1''),''enable'', ''on'');' ... 'set(findobj(gcbf, ''tag'', ''clustertext2''),''enable'', ''on'');' ... 'set(findobj(gcbf, ''tag'', ''clusterhelp1''),''enable'', ''on'');' ... 'set(findobj(gcbf, ''tag'', ''clusterhelp2''),''enable'', ''on'');' ... 'set(findobj(gcbf, ''tag'', ''clusterchan'' ),''enable'', ''on'');' ... 'set(findobj(gcbf, ''tag'', ''clusterstat'' ),''enable'', ''on'');' ]; cb_unselect_cluster = [ 'set(findobj(gcbf, ''tag'', ''clustertext1''),''enable'', ''off'');' ... 'set(findobj(gcbf, ''tag'', ''clustertext2''),''enable'', ''off'');' ... 'set(findobj(gcbf, ''tag'', ''clusterhelp1''),''enable'', ''off'');' ... 'set(findobj(gcbf, ''tag'', ''clusterhelp2''),''enable'', ''off'');' ... 'set(findobj(gcbf, ''tag'', ''clusterchan'' ),''enable'', ''off'');' ... 'set(findobj(gcbf, ''tag'', ''clusterstat'' ),''enable'', ''off'');' ]; cb_fieldtrip_mcorrect = [ cb_fieldtrip_statlist 'if get(findobj(gcbf, ''tag'', ''fieldtripmcorrect'' ),''value'') == 6,' cb_select_cluster ',else,' cb_unselect_cluster ',end;' cb_fieldtrip_statlist]; % cb_fieldtrip_statlist repeated on purpose % callback for activating eeglab/fieldtrip % ---------------------------------------- enable_eeglab = [ 'set(findobj(gcbf, ''userdata'', ''eeglab'') ,''enable'', ''on'');' ... 'set(findobj(gcbf, ''userdata'', ''fieldtrip''),''enable'', ''off'');' ... 'set(findobj(gcbf, ''tag'', ''but_eeglab'') ,''value'', 1);' ... 'set(findobj(gcbf, ''tag'', ''but_fieldtrip''),''value'', 0);' cb_eeglab_statlist ]; enable_fieldtrip=[ 'if get(findobj(gcbf, ''tag'', ''condstats''), ''value'') && get(findobj(gcbf, ''tag'', ''groupstats''), ''value''),' ... enable_eeglab ... 'warndlg2(strvcat(''Switching to EEGLAB statistics since'',''Fieldtrip cannot perform 2-way statistics''));' ... 'else,' ... ' set(findobj(gcbf, ''userdata'', ''eeglab'') ,''enable'', ''off'');' ... ' set(findobj(gcbf, ''userdata'', ''fieldtrip''),''enable'', ''on'');' ... ' set(findobj(gcbf, ''tag'', ''but_fieldtrip''),''value'', 1);' ... ' set(findobj(gcbf, ''tag'', ''but_eeglab'') ,''value'', 0);' cb_fieldtrip_mcorrect ... 'end;']; cb_select_fieldtrip = [ 'if get(findobj(gcbf, ''tag'', ''but_fieldtrip''),''value''),' enable_fieldtrip ',else,' enable_eeglab ',end;' ]; cb_select_eeglab = [ 'if get(findobj(gcbf, ''tag'', ''but_eeglab''),''value''),,' enable_eeglab ',else,' enable_fieldtrip ',end;' ]; if strcmpi(paramstruct.mode, 'eeglab'), evalstr = enable_eeglab; else evalstr = enable_fieldtrip; end; inds = findstr('gcbf', evalstr); evalstr(inds+2) = []; % special case if Fieldtrip is not installed if ~fieldtripInstalled strFieldtrip = 'Use Fieldtrip statistics (to use install "Fieldtrip-lite" using File > Manage EEGLAB extensions)'; fieldtripEnable = 'off'; cb_select_eeglab = 'set(findobj(gcbf, ''tag'', ''but_eeglab''),''value'', 1)'; else strFieldtrip = 'Use Fieldtrip statistics'; fieldtripEnable = 'on'; end; opt.uilist = { ... {'style' 'text' 'string' 'General statistical parameters' 'fontweight' 'bold' } ... {} {'style' 'checkbox' 'string' 'Compute 1st independent variable statistics' 'value' condstats 'enable' opt.enablecond 'callback' cb_select_fieldtrip 'tag' 'condstats' } ... {} {'style' 'checkbox' 'string' 'Compute 2nd independent variable statistics' 'value' groupstats 'enable' opt.enablegroup 'callback' cb_select_fieldtrip 'tag' 'groupstats' } ... {} {'style' 'checkbox' 'string' 'Use single trials (when available)' 'value' statmode 'tag' 'singletrials' 'enable' opt.enablesingletrials } ... {} ... {'style' 'checkbox' 'string' 'Use EEGLAB statistics' 'fontweight' 'bold' 'tag' 'but_eeglab' 'callback' cb_select_eeglab } ... {} {'style' 'popupmenu' 'string' 'Use parametric statistics|Use permutation statistics|Use bootstrap statistics' 'tag' 'stateeglab' 'value' eeglabStat 'listboxtop' eeglabStat 'callback' [ cb_eeglab_statlist cb_bootstrap ] 'userdata' 'eeglab' } ... {'style' 'text' 'string' 'Statistical threshold (p-value)' 'userdata' 'eeglab'} ... {'style' 'edit' 'string' eeglabThresh 'tag' 'eeglabalpha' 'userdata' 'eeglab' } ... {} {'style' 'popupmenu' 'string' 'Do not correct for multiple comparisons|Use Bonferoni correction|Use Holms correction|Use FDR correction' 'value' eeglabMcorrect 'listboxtop' eeglabMcorrect 'tag' 'eeglabmcorrect' 'userdata' 'eeglab' } ... {'style' 'text' 'string' ' Randomization (n)' 'userdata' 'eeglab' 'tag' 'eeglabnaccutext' } ... {'style' 'edit' 'string' eeglabRand 'userdata' 'eeglab' 'tag' 'eeglabnaccu' } ... {} ... {'style' 'checkbox' 'string' strFieldtrip 'enable' fieldtripEnable 'fontweight' 'bold' 'tag' 'but_fieldtrip' 'callback' cb_select_fieldtrip } ... {} {'style' 'popupmenu' 'string' 'Use analytic/parametric statistics|Use montecarlo/permutation statistics' 'tag' 'statfieldtrip' 'value' fieldtripStat 'listboxtop' fieldtripStat 'callback' cb_fieldtrip_mcorrect 'userdata' 'fieldtrip' } ... {'style' 'text' 'string' 'Statistical threshold (p-value)' 'userdata' 'fieldtrip' } ... {'style' 'edit' 'string' fieldtripThresh 'tag' 'fieldtripalpha' 'userdata' 'fieldtrip' } ... {} {'style' 'popupmenu' 'string' 'Do not correct for multiple comparisons|Use Bonferoni correction|Use Holms correction|Use FDR correction|Use max correction|Use cluster correction (CC)' 'tag' 'fieldtripmcorrect' 'value' fieldtripMcorrect 'listboxtop' fieldtripMcorrect 'callback' cb_fieldtrip_mcorrect 'userdata' 'fieldtrip' } ... {'style' 'text' 'string' ' Randomization (n)' 'userdata' 'fieldtrip' 'tag' 'fieldtripnaccutext' } ... {'style' 'edit' 'string' fieldtripRand 'userdata' 'fieldtrip' 'tag' 'fieldtripnaccu' } ... {} {'style' 'text' 'string' 'CC channel neighbor parameters' 'userdata' 'fieldtrip' 'tag' 'clustertext1' } ... { 'style' 'edit' 'string' fieldtripChan 'userdata' 'fieldtrip' 'tag' 'clusterchan' 'callback' cb_textSyntax } ... { 'style' 'pushbutton' 'string' 'help' 'callback' cb_help_neighbor 'userdata' 'fieldtrip' 'tag' 'clusterhelp1' } ... {} {'style' 'text' 'string' 'CC clustering parameters' 'userdata' 'fieldtrip' 'tag' 'clustertext2' } ... { 'style' 'edit' 'string' fieldtripClust 'userdata' 'fieldtrip' 'tag' 'clusterstat' 'callback' cb_textSyntax } ... { 'style' 'pushbutton' 'string' 'help' 'callback' cb_help_cluster 'userdata' 'fieldtrip' 'tag' 'clusterhelp2' } ... }; if eeglabStat == 3, eval(combootstrap); end; cbline = [0.07 1.1]; otherline = [ 0.7 0.6 .5]; eeglabline = [ 0.7 0.6 .5]; opt.geometry = { [1] cbline cbline cbline [1] [1] [0.07 0.51 0.34 0.13] [0.07 0.6 0.25 0.13] ... [1] [1] [0.07 0.51 0.34 0.13] [0.07 0.6 0.25 0.13] [0.13 0.4 0.4 0.1] [0.13 0.4 0.4 0.1] }; [out_param userdat tmp res] = inputgui( 'geometry' , opt.geometry, 'uilist', opt.uilist, ... 'title', 'Set statistical parameters -- pop_statparams()','eval', evalstr); if isempty(res), return; end; % decode paramters % ---------------- if res.groupstats, res.groupstats = 'on'; else res.groupstats = 'off'; end; if res.condstats , res.condstats = 'on'; else res.condstats = 'off'; end; if res.singletrials, res.singletrials = 'on'; else res.singletrials = 'off'; end; res.eeglabalpha = str2num(res.eeglabalpha); res.fieldtripalpha = str2num(res.fieldtripalpha); if isempty(res.eeglabalpha) ,res.eeglabalpha = NaN; end; if isempty(res.fieldtripalpha),res.fieldtripalpha = NaN; end; res.stateeglab = eeglabStatvalues{res.stateeglab}; res.statfieldtrip = fieldtripStatvalues{res.statfieldtrip}; res.eeglabmcorrect = mCorrectList{res.eeglabmcorrect}; res.fieldtripmcorrect = mCorrectList{res.fieldtripmcorrect}; res.mode = fastif(res.but_eeglab, 'eeglab', 'fieldtrip'); res.eeglabnaccu = str2num(res.eeglabnaccu); if ~isstr(res.fieldtripnaccu) || ~strcmpi(res.fieldtripnaccu, 'all') res.fieldtripnaccu = str2num(res.fieldtripnaccu); end; % build command call % ------------------ options = {}; if ~strcmpi( res.groupstats, paramstruct.groupstats), options = { options{:} 'groupstats' res.groupstats }; end; if ~strcmpi( res.condstats , paramstruct.condstats ), options = { options{:} 'condstats' res.condstats }; end; if ~strcmpi( res.singletrials, paramstruct.singletrials ), options = { options{:} 'singletrials' res.singletrials }; end; if ~strcmpi( res.mode , paramstruct.mode), options = { options{:} 'mode' res.mode }; end; % statistics if ~isequal( res.eeglabnaccu , paramstruct.eeglab.naccu), options = { options{:} 'naccu' res.eeglabnaccu }; end; if ~strcmpi( res.stateeglab , paramstruct.eeglab.method), options = { options{:} 'method' res.stateeglab }; end; % statistics if ~strcmpi( res.eeglabmcorrect , paramstruct.eeglab.mcorrect), options = { options{:} 'mcorrect' res.eeglabmcorrect }; end; if ~isequal( res.fieldtripnaccu , paramstruct.fieldtrip.naccu), options = { options{:} 'fieldtripnaccu' res.fieldtripnaccu }; end; if ~strcmpi( res.statfieldtrip , paramstruct.fieldtrip.method), options = { options{:} 'fieldtripmethod' res.statfieldtrip }; end; if ~strcmpi( res.fieldtripmcorrect , paramstruct.fieldtrip.mcorrect), options = { options{:} 'fieldtripmcorrect' res.fieldtripmcorrect }; end; if ~strcmpi( res.clusterstat , paramstruct.fieldtrip.clusterparam), options = { options{:} 'fieldtripclusterparam' res.clusterstat }; end; if ~strcmpi( res.clusterchan , paramstruct.fieldtrip.channelneighborparam), options = { options{:} 'fieldtripchannelneighborparam' res.clusterchan }; end; if ~(isnan(res.eeglabalpha(1)) && isnan(paramstruct.eeglab.alpha(1))) && ~isequal(res.eeglabalpha, paramstruct.eeglab.alpha) % threshold options = { options{:} 'alpha' res.eeglabalpha }; end; if ~(isnan(res.fieldtripalpha(1)) && isnan(paramstruct.fieldtrip.alpha(1))) && ~isequal(res.fieldtripalpha, paramstruct.fieldtrip.alpha) % threshold options = { options{:} 'fieldtripalpha' res.fieldtripalpha }; end; if ~isempty(options) STUDY = pop_statparams(STUDY, options{:}); com = sprintf('STUDY = pop_statparams(STUDY, %s);', vararg2str( options )); end; else % interpret parameters % -------------------- if isfield(STUDY, 'etc') paramstruct = STUDY.etc.statistics; isstudy = true; else paramstruct = STUDY; if isempty(paramstruct), paramstruct = default_stats([]); end; isstudy = false; end; if isempty(varargin) || strcmpi(varargin{1}, 'default') paramstruct = default_stats(paramstruct); else for index = 1:2:length(varargin) v = varargin{index}; if strcmpi(v, 'statistics'), v = 'method'; end; % backward compatibility if strcmpi(v, 'threshold' ), v = 'alpha'; end; % backward compatibility if strcmpi(v, 'alpha') || strcmpi(v, 'method') || strcmpi(v, 'naccu') || strcmpi(v, 'mcorrect') paramstruct = setfield(paramstruct, 'eeglab', v, varargin{index+1}); elseif ~isempty(findstr('fieldtrip', v)) v2 = v(10:end); paramstruct = setfield(paramstruct, 'fieldtrip', v2, varargin{index+1}); if strcmpi(v2, 'channelneighborparam') paramstruct.fieldtrip.channelneighbor = []; % reset neighbor matrix if parameter change end; else if (~isempty(paramstruct) && ~isempty(strmatch(v, fieldnames(paramstruct), 'exact'))) || ~isstudy paramstruct = setfield(paramstruct, v, varargin{index+1}); end; end; end; end; if isfield(STUDY, 'etc') STUDY.etc.statistics = paramstruct; else STUDY = paramstruct; end; end; % default parameters % ------------------ function paramstruct = default_stats(paramstruct) if ~isfield(paramstruct, 'groupstats'), paramstruct.groupstats = 'off'; end; if ~isfield(paramstruct, 'condstats' ), paramstruct.condstats = 'off'; end; if ~isfield(paramstruct, 'singletrials' ), paramstruct.singletrials = 'off'; end; if ~isfield(paramstruct, 'mode' ), paramstruct.mode = 'eeglab'; end; if ~isfield(paramstruct, 'eeglab'), paramstruct.eeglab = []; end; if ~isfield(paramstruct, 'fieldtrip'), paramstruct.fieldtrip = []; end; if ~isfield(paramstruct.eeglab, 'naccu'), paramstruct.eeglab.naccu = []; end; if ~isfield(paramstruct.eeglab, 'alpha' ), paramstruct.eeglab.alpha = NaN; end; if ~isfield(paramstruct.eeglab, 'method'), paramstruct.eeglab.method = 'param'; end; if ~isfield(paramstruct.eeglab, 'mcorrect'), paramstruct.eeglab.mcorrect = 'none'; end; if ~isfield(paramstruct.fieldtrip, 'naccu'), paramstruct.fieldtrip.naccu = []; end; if ~isfield(paramstruct.fieldtrip, 'method'), paramstruct.fieldtrip.method = 'analytic'; end; if ~isfield(paramstruct.fieldtrip, 'alpha'), paramstruct.fieldtrip.alpha = NaN; end; if ~isfield(paramstruct.fieldtrip, 'mcorrect'), paramstruct.fieldtrip.mcorrect = 'none'; end; if ~isfield(paramstruct.fieldtrip, 'clusterparam'), paramstruct.fieldtrip.clusterparam = '''clusterstatistic'',''maxsum'''; end; if ~isfield(paramstruct.fieldtrip, 'channelneighbor'), paramstruct.fieldtrip.channelneighbor = []; end; if ~isfield(paramstruct.fieldtrip, 'channelneighborparam'), paramstruct.fieldtrip.channelneighborparam = '''method'',''triangulation'''; end; if strcmpi(paramstruct.eeglab.mcorrect, 'benferoni'), paramstruct.eeglab.mcorrect = 'bonferoni'; end; if strcmpi(paramstruct.eeglab.mcorrect, 'no'), paramstruct.eeglab.mcorrect = 'none'; end; if strcmpi(paramstruct.fieldtrip.mcorrect, 'no'), paramstruct.fieldtrip.mcorrect = 'none'; end;
github
ZijingMao/baselineeegtest-master
std_maketrialinfo.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/studyfunc/std_maketrialinfo.m
4,932
utf_8
74e88ea317e31cc0a4a5072dca23568b
% std_maketrialinfo() - create trial information structure using the % .epoch structure of EEGLAB datasets % % Usage: % >> STUDY = std_maketrialinfo(STUDY, ALLEEG); % % Inputs: % STUDY - EEGLAB STUDY set % ALLEEG - vector of the EEG datasets included in the STUDY structure % % Inputs: % STUDY - EEGLAB STUDY set updated. The fields which is created or % updated is STUDY.datasetinfo.trialinfo % % Authors: Arnaud Delorme, SCCN/INC/UCSD, April 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_maketrialinfo(STUDY, ALLEEG); %% test if .epoch field exist in ALLEEG structure epochfield = cellfun(@isempty, { ALLEEG.epoch }); if any(epochfield) fprintf('Warning: some datasets are continuous and trial information cannot be created\n'); return; end; %% check if conversion of event is necessary ff = {}; flagConvert = true; for index = 1:length(ALLEEG), ff = union(ff, fieldnames(ALLEEG(index).event)); end; for iField = 1:length(ff) fieldChar = zeros(1,length(ALLEEG))*NaN; for index = 1:length(ALLEEG) if isfield(ALLEEG(index).event, ff{iField}) if ischar(ALLEEG(index).event(1).(ff{iField})) fieldChar(index) = 1; else fieldChar(index) = 0; end; end; end; if ~all(fieldChar(~isnan(fieldChar)) == 1) && ~all(fieldChar(~isnan(fieldChar)) == 0) % need conversion to char for index = 1:length(ALLEEG) if fieldChar(index) == 0 if flagConvert, disp('Warning: converting some event fields to strings - this may be slow'); flagConvert = false; end; for iEvent = 1:length(ALLEEG(index).event) ALLEEG(index).event(iEvent).(ff{iField}) = num2str(ALLEEG(index).event(iEvent).(ff{iField})); end; end; end; end end; %% Make trial info for index = 1:length(ALLEEG) tmpevent = ALLEEG(index).event; eventlat = abs(eeg_point2lat( [ tmpevent.latency ], [ tmpevent.epoch ], ALLEEG(index).srate, [ALLEEG(index).xmin ALLEEG(index).xmax])); events = ALLEEG(index).event; ff = fieldnames(events); ff = setdiff_bc(ff, { 'latency' 'urevent' 'epoch' }); trialinfo = []; % process time locking event fields % --------------------------------- indtle = find(eventlat < 0.02); epochs = [ events(indtle).epoch ]; extractepoch = true; if length(epochs) ~= ALLEEG(index).trials % special case where there are not the same number of time-locking % event as there are data epochs if length(unique(epochs)) ~= ALLEEG(index).trials extractepoch = false; disp('std_maketrialinfo: not the same number of time-locking events as trials, trial info ignored'); else % pick one event per epoch [tmp tmpind] = unique_bc(epochs(end:-1:1)); % reversing the array ensures the first event gets picked tmpind = length(epochs)+1-tmpind; indtle = indtle(tmpind); if length(indtle) ~= ALLEEG(index).trials extractepoch = false; disp('std_maketrialinfo: not the same number of time-locking events as trials, trial info ignored'); end; end; end; if extractepoch commands = {}; for f = 1:length(ff) eval( [ 'eventvals = {events(indtle).' ff{f} '};' ]); %if isnumeric(eventvals{1}) % eventvals = cellfun(@num2str, eventvals, 'uniformoutput', false); %end; commands = { commands{:} ff{f} eventvals }; end; trialinfo = struct(commands{:}); STUDY.datasetinfo(index).trialinfo = trialinfo; end; % % same as above but 10 times slower % for e = 1:length(ALLEEG(index).event) % if eventlat(e) < 0.0005 % time locking event only % epoch = events(e).epoch; % for f = 1:length(ff) % fieldval = getfield(events, {e}, ff{f}); % trialinfo = setfield(trialinfo, {epoch}, ff{f}, fieldval); % end; % end; % end; end;