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
lcnbeapp/beapp-master
rsadjust.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/rsadjust.m
2,955
utf_8
45d8f416e2d360293ee83cb15f5e3976
% rsadjust() - adjust l-values (Ramberg-Schmeiser distribution) % with respect to signal mean and variance % % Usage: p = rsadjust(l3, l4, m, var, skew) % % Input: % l3 - value lambda3 for Ramberg-Schmeiser distribution % l4 - value lambda4 for Ramberg-Schmeiser distribution % m - mean of the signal distribution % var - variance of the signal distribution % skew - skewness of the signal distribution (only the sign of % this parameter is used). % % Output: % l1 - value lambda3 for Ramberg-Schmeiser distribution % l2 - value lambda4 for Ramberg-Schmeiser distribution % l3 - value lambda3 for Ramberg-Schmeiser distribution (copy % from input) % l4 - value lambda4 for Ramberg-Schmeiser distribution (copy % from input) % % Author: Arnaud Delorme, SCCN, 2003 % % See also: rsfit(), rsget() % % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % A probability distribution and its uses in fitting data. % Technimetrics, 1979, 21: 201-214. % Copyright (C) 2003 Arnaud Delorme, SCCN, [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 [l1,l2,l3,l4] = rsadjust( l3, l4, mu, sigma2, m3); % swap l3 and l4 for negative skewness % ------------------------------------ if m3 < 0 ltmp = l4; l4 = l3; l3 = ltmp; end; A = 1/(1 + l3) - 1/(1 + l4); B = 1/(1 + 2*l3) + 1/(1 + 2*l4) - 2*beta(1+l3, 1+l4); C = 1/(1 + 3*l3) - 1/(1 + 3*l4) ... - 3*beta(1+2*l3, 1+l4) + 3*beta(1+l3, 1+2*l4); % compute l2 (and its sign) % ------------------------ l2 = sqrt( (B-A^2)/sigma2 ); if m3 == 0, m3 = -0.000000000000001; end; if (m3*(C - 2*A*B + 2*A^3)) < 0, l2 = -l2; end; %l22 = ((C - 2*A*B + 2*A^3)/m3)^(1/3) % also equal to l2 % compute l1 % ---------- l1 = mu - A/l2; return; % fitting table 1 of % --------------- [l1 l2] = pdffitsolv2(-.0187,-.0388, 0, 1, 1) [l1 l2] = pdffitsolv2(-.1359,-.1359, 0, 1, 0) % sign problem [l1 l2] = pdffitsolv2(1.4501,1.4501, 0, 1) % numerical problem for l1 [l1 l2] = pdffitsolv2(-.00000407,-.001076, 0, 1, 2) [l1 l2] = pdffitsolv2(0,-.000580, 0, 1, 2)
github
lcnbeapp/beapp-master
newcrossf.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/newcrossf.m
63,870
utf_8
cb2a530dbabd60d30681d5c293194574
% newcrossf() - Returns estimates and plots event-related coherence (ERCOH) % between two input data time series. A lower panel (optionally) shows % the coherence phase difference between the processes. In this panel: % In the plot output by > newcrossf(x,y,...); % 90 degrees (orange) means x leads y by a quarter cycle. % -90 degrees (blue) means y leads x by a quarter cycle. % Click on any subplot to view separately and zoom in/out. % % Function description: % Uses EITHER fixed-window, zero-padded FFTs (fastest) OR constant-Q % 0-padded wavelet DFTs (more even sensitivity across frequencies), % both Hanning-tapered. Output frequency spacing is the lowest % frequency ('srate'/'winsize') divided by the 'padratio'. % % If an 'alpha' value is given, then bootstrap statistics are % computed (from a distribution of 'naccu' (200) surrogate baseline % data epochs) for the baseline epoch, and non-significant features % of the output plots are zeroed (and shown in green). The baseline % epoch is all windows with center latencies < the given 'baseline' value % or, if 'baseboot' is 1, the whole epoch. % % Usage with single dataset: % >> [coh,mcoh,timesout,freqsout,cohboot,cohangles,... % allcoher,alltfX,alltfY] = newcrossf(x,y,frames,tlimits,srate, ... % cycles, 'key1', 'val1', 'key2', val2' ...); % % Example to compare two condition (coh. comp 1-2 EEG versus ALLEEG(2)): % >> [coh,mcoh,timesout,freqsout,cohboot,cohangles,... % allcoher,alltfX,alltfY] = newcrossf({EEG.icaact(1,:,:) ... % ALLEEG(2).icaact(1,:,:)},{{EEG.icaact(2,:,:) ... % ALLEEG(2).icaact(2,:,:)}},frames,tlimits,srate, ... % cycles, 'key1', 'val1', 'key2', val2' ...); % % Required inputs: % x = First single-channel data set (1,frames*nepochs) % Else, cell array {x1,x2} of two such data vectors to also % estimate (significant) coherence differences between two % conditions. % y = Second single-channel data set (1,frames*nepochs) % Else, cell array {y1,y2} of two such data vectors. % frames = Frames per epoch {750} % tlimits = [mintime maxtime] (ms) Epoch latency limits {[-1000 2000]} % srate = Data sampling rate (Hz) {250} % cycles = 0 -> Use FFTs (with constant window length) % = >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 cycles: 0} % % Optional Coherence Type: % 'type' = ['coher'|'phasecoher'|'amp'] Compute either linear coherence % ('coher'), phase coherence ('phasecoher') also known % as phase coupling factor', or amplitude correlations ('amp') % {default: 'phasecoher'}. Note that for amplitude correlation, % the significance threshold is computed using the corrcoef % function, so can be set arbitrary low without increase in % computation load. An additional type is 'crossspec' to compute % cross-spectrum between 2 processes (single-trial). This type % is automatically selected if user enter continuous data. % 'amplag' = [integer vector] allow to compute non 0 amplitude correlation % (using option 'amp' above). The vector given as parameter % indicates the point lags ([-4 -2 0 2 4] would compute the % correlation at time t-4, t-2, t, t+2, t+4, and return the % maximum correlation at these points). % 'subitc' = ['on'|'off'] Subtract stimulus locked Inter-Trial Coherence % from x and y. This computes the 'intrinsic' coherence % x and y not arising from common synchronization to % experimental events. For cell array input, one may provide % a cell array ({'on','off'} for example). {default: 'off'} % 'shuffle' = Integer indicating the number of estimates to compute % bootstrap coherence based on shuffled trials. This estimates % the coherence arising only from time locking of x and y % to experimental events (opposite of 'subitc'). For cell array % input, one may provide a cell array, for example { 1 0 }. % { default 0: no shuffling }. % % Optional Detrend: % 'detrend' = ['on'|'off'], Linearly detrend each data epoch {'off'} % 'rmerp' = ['on'|'off'], Remove epoch mean from data epochs {'off'} % % Optional FFT/DFT: % '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 {~frames/8} % 'timesout' = Number of output latencies (int<frames-winframes). {200) % A negative value (-S) subsamples the original latencies % by S. An array of latencies computes spectral % decompositions at specific latency values (Note: the % algorithm finds the closest latencies in the data, % possibly resulting in slightly unevenly spaced % output latencies. % '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. % 'maxfreq' = Maximum frequency (Hz) to plot (& output if cycles>0) % If cycles==0, all FFT frequencies are output.{def: 50} % Note: NOW DEPRECATED, use 'freqs' instead, % 'freqs' = [min max] Frequency limits. {Default: [minfreq 50], % minfreq being determined by the number of data points, % cycles and sampling frequency}. % '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 scaling. {Default: 'linear'}. % Note that for obtaining 'log' spaced freqs using FFT, % closest correspondant frequencies in the 'linear' space % are returned. % 'baseline' = Spectral baseline end-time (in ms). NaN imply that no % baseline is used. A range [min max] may also be entered % You may also enter one row per region for baseline % e.g. [0 100; 300 400] considers the window 0 to 100 ms and % 300 to 400 ms. This is only valid for the coherence amplitude % not for the coherence phase. { default NaN } % 'lowmem' = ['on'|'off'] {'off'} Compute frequency by frequency to % save memory. % % Optional Bootstrap: % 'alpha' = If non-0, compute two-tailed bootstrap significance prob. % level. Show non-signif output values in neutral green. {0} % 'naccu' = Number of bootstrap replications to compute {200} % 'boottype' = ['shuffle'|'shufftrials'|'rand'|'randall'] Bootstrap type: Either % shuffle time and trial windows ('shuffle' default) or trials only % using a separate bootstrap for each time window ('shufftrials'). % Option 'rand' randomize the phase. Option 'randall' randomize the % phase for each individual time/frequency point. % 'baseboot' = Bootstrap baseline subtract (1 -> use 'baseline'; Default % 0 -> use whole trial % [min max] -> use time range) % Default is to use the baseline unless no baseline is % specified (then the function uses all sample up to time 0) % You may also enter one row per region for baseline % e.g. [0 100; 300 400] considers the window 0 to 100 ms and % 300 to 400 ms. % 'condboot' = ['abs'|'angle'|'complex'] In comparing two conditions, % either subtract complex spectral values' absolute vales % ('abs'), angles ('angles') or the complex values themselves % ('complex'). {default: 'abs'} % 'rboot' = Input bootstrap coherence limits (e.g., from newcrossf()) % The bootstrap type should be identical to that used % to obtain the input limits. {default: compute from data} % Optional scalp map plot: % 'topovec' = (2,nchans) matrix. Scalp maps to plot {[]} % ELSE [c1,c2], plot two cartoons showing channel locations. % 'elocs' = Electrode location file for scalp map {none} % File should be ascii in format of >> topoplot example % 'chaninfo' = Electrode location additional information (nose position...) % {default: none} % % Optional plot and compute features: % 'plottype' = ['image'|'curve'] plot time frequency images or % curves (one curve per frequency). Default is 'image'. % 'plotmean' = ['on'|'off'] For 'curve' plots only. Average all % frequencies given as input. Default: 'on'. % 'highlightmode' = ['background'|'bottom'] For 'curve' plots only, % display significant time regions either in the plot background % or underneatht the curve. % 'plotamp' = ['on'|'off']. Plot coherence magnitude {'on'} % 'maxamp' = [real] Set the maximum for the amplitude scale {auto} % 'plotphase' = ['on'|'off']. Plot coherence phase angle {'on'} % 'angleunit' = Phase units: 'ms' for msec or 'deg' for degrees or 'rad' % for radians {'deg'} % 'title' = Optional figure title. If two conditions are given % as input, title can be a cell array with two text % string elements {none} % 'vert' = Latencies to mark with a dotted vertical line {none} % 'linewidth' = Line width for marktimes traces (thick=2, thin=1) {2} % 'newfig' = ['on'|'off'] Create new figure for difference plots {'on'} % 'axesfont' = Axes font size {10} % 'titlefont' = Title font size {8} % % Outputs: % coh = Matrix (nfreqs,timesout) of coherence magnitudes. Not % that for continuous data, the function is returning the % cross-spectrum. % mcoh = Vector of mean baseline coherence at each frequency % see 'baseline' parameter. % timesout = Vector of output latencies (window centers) (ms). % freqsout = Vector of frequency bin centers (Hz). % cohboot = Matrix (nfreqs) of upper coher signif. limits % if 'boottype' is 'trials', (nfreqs,timesout) % cohangle = (nfreqs,timesout) matrix of coherence angles in radian % allcoher = single trial coherence % alltfX = single trial spectral decomposition of X % alltfY = single trial spectral decomposition of Y % % Plot description: % Assuming both 'plotamp' and 'plotphase' options are 'on' (=default), the upper panel % presents the magnitude of either phase coherence or linear coherence, depending on % the 'type' parameter (above). The lower panel presents the coherence phase difference % (in degrees). Click on any plot to pop up a new window (using 'axcopy()'). % -- The upper left marginal panel shows mean coherence during the baseline period % (blue), and when significance is set, the significance threshold (dotted black-green). % -- The horizontal panel under the coherence magnitude image indicates the maximum % (green) and minimum (blue) coherence values across all frequencies. When significance % is set (using option 'trials' for 'boottype'), an additional curve indicates the % significance threshold (dotted black-green). % % Notes: 1) When cycles==0, nfreqs is total number of FFT frequencies. % 2) 'blue' coherence lag -> x leads y; 'red' -> y leads x % 3) The 'boottype' should be ideally 'timestrials', but this creates % large memory demands, so 'times' must be used in many cases. % 4) If 'boottype' is 'trials', the average of the complex bootstrap % is subtracted from the coherence to compensate for phase differences % (the average is also subtracted from the bootstrap distribution). % For other bootstraps, this is not necessary since there the phase % distribution should be random. % 5) If baseline is non-NaN, the baseline is subtracted from % the complex coherence. On the left hand side of the coherence % amplitude image, the baseline is displayed as a magenta line. % (If no baseline is selected, this curve represents the average % coherence at every given frequency). % % Authors: Arnaud Delorme, Sigurd Enghoff & Scott Makeig % CNL/Salk Institute 1998-2001; SCCN/INC/UCSD, La Jolla, 2002- % % See also: timef() % NOTE: one hidden parameter 'savecoher', 0 or 1 % Copyright (C) 8/1/98 Arnaud Delorme, 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 g.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 % 03-09-02 function restructuration -ad % add 'key', val arguments (+ external baseboot, baseline, color axis, angleunit...) % add detrending (across time and trials) + 'coher' option for amplitude coherence % significance only if alpha is given, ploting options in 'plotamp' and 'plotphase' % 03-16-02 timeout automatically adjusted if too high -ad % 04-03-02 added new options for bootstrap -ad % There are 3 "objects" Tf, Coher and Boot which are handled % - by specific functions under Matlab % (Tf) function Tf = tfinit(...) - create object Time Frequency (Tf) associated with some data % (Tf) function [Tf, itcvals] = tfitc(...) - compute itc for the selected data % (Tf) function [Tf, itcvals] = tfitcpost(Tf, trials) - itc normlisation % (Tf) function [Tf, tmpX] = tfcomp(Tf, trials, times) - compute time freq. decomposition % (Coher) function Coher = coherinit(...) - initialize coherence object % (Coher) function Coher = cohercomp(Coher, tmpX, tmpY, trial, time) - compute coherence % (Coher) function Coher = cohercomppost(Coher, trials) - coherence normalization % (Boot) function Boot = bootinit(...) - intialize bootstrap object % (Boot) function Boot = bootcomp(...) - compute bootstrap % (Boot) function [Boot, Rbootout] = bootcomppost(...) - bootstrap normalization % - by real objects under C++ (see C++ code) function [R,mbase,timesout,freqs,Rbootout,Rangle, coherresout, alltfX, alltfY] = newcrossf(X, Y, frame, tlimits, Fs, varwin, varargin) %varwin,winsize,nwin,oversmp,maxfreq,alpha,verts,caxmax) % Commandline arg defaults: DEFAULT_ANGLEUNITS = 'deg'; % angle plotting units - 'ms' or 'deg' DEFAULT_EPOCH = 750; % Frames per epoch DEFAULT_TIMELIM = [-1000 2000]; % Time range of epochs (ms) DEFAULT_FS = 250; % 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 = 'Event-Related Coherence'; % Figure title DEFAULT_ALPHA = NaN; % Default two-sided significance probability threshold %disp('WARNING: this function is not part of the EEGLAB toolbox and should not be distributed'); %disp(' you must contact Arnaud Delorme ([email protected]) for terms of use'); if (nargin < 2) help newcrossf return end coherresout = []; if ~iscell(X) if (min(size(X))~=1 | length(X)<2) fprintf('crossf(): x must be a row or column vector.\n'); return elseif (min(size(Y))~=1 | length(Y)<2) fprintf('crossf(): y must be a row or column vector.\n'); return elseif (length(X) ~= length(Y)) fprintf('crossf(): x and y must have same length.\n'); return end end; if (nargin < 3) frame = DEFAULT_EPOCH; elseif (~isnumeric(frame) | length(frame)~=1 | frame~=round(frame)) fprintf('crossf(): Value of frames must be an integer.\n'); return elseif (frame <= 0) fprintf('crossf(): Value of frames must be positive.\n'); return elseif ~iscell(X) & (rem(size(X,2),frame) ~= 0) & (rem(size(X,1),frame) ~= 0) fprintf('crossf(): Length of data vectors must be divisible by frames.\n'); return end if (nargin < 4) tlimits = DEFAULT_TIMELIM; elseif (~isnumeric(tlimits) | sum(size(tlimits))~=3) error('crossf(): Value of tlimits must be a vector containing two numbers.'); elseif (tlimits(1) >= tlimits(2)) error('crossf(): tlimits interval must be [min,max].'); end if (nargin < 5) 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 < 6) varwin = DEFAULT_VARWIN; elseif (~isnumeric(varwin) | length(varwin)>2) error('crossf(): Value of cycles must be a number or a (1,2) vector.'); elseif (varwin < 0) error('crossf(): Value of cycles must be either zero or positive.'); end % consider structure for these arguments % -------------------------------------- vararginori = varargin; for index=1:length(varargin) if iscell(varargin{index}), varargin{index} = { varargin{index} }; end; end; if ~isempty(varargin) [tmp indices] = unique_bc(varargin(1:2:end)); % keep the first one varargin = varargin(sort(union(indices*2-1, indices*2))); % these 2 line remove duplicate arguments try, g = struct(varargin{:}); catch, error('Argument error in the {''param'', value} sequence'); end; else g = []; end; try, g.condboot; catch, g.condboot = 'abs'; end; try, g.shuffle; catch, g.shuffle = 0; end; try, g.title; catch, g.title = DEFAULT_TITLE; end; try, g.winsize; catch, g.winsize = max(pow2(nextpow2(frame)-3),4); end; try, g.pad; catch, g.pad = max(pow2(nextpow2(g.winsize)),4); end; try, g.timesout; catch, g.timesout = DEFAULT_NWIN; end; try, g.padratio; catch, g.padratio = DEFAULT_OVERSMP; end; try, g.topovec; catch, g.topovec = []; end; try, g.elocs; catch, g.elocs = ''; end; try, g.alpha; catch, g.alpha = DEFAULT_ALPHA; end; try, g.marktimes; catch, g.marktimes = []; end; % default no vertical lines try, g.marktimes = g.vert; catch, g.vert = []; end; % default no vertical lines try, g.rboot; catch, g.rboot = []; end; try, g.plotamp; catch, g.plotamp = 'on'; end; try, g.plotphase; catch, g.plotphase = 'on'; end; try, g.plotbootsub; catch, g.plotbootsub = 'on'; end; try, g.detrend; catch, g.detrend = 'off'; end; try, g.rmerp; catch, g.rmerp = 'off'; end; try, g.baseline; catch, g.baseline = NaN; end; try, g.baseboot; catch, g.baseboot = 1; end; try, g.linewidth; catch, g.linewidth = 2; end; try, g.maxfreq; catch, g.maxfreq = DEFAULT_MAXFREQ; end; try, g.freqs; catch, g.freqs = [0 g.maxfreq]; end; try, g.nfreqs; catch, g.nfreqs = []; end; try, g.freqscale; catch, g.freqscale = 'linear'; end; try, g.naccu; catch, g.naccu = 200; end; try, g.angleunit; catch, g.angleunit = DEFAULT_ANGLEUNITS; end; try, g.type; catch, g.type = 'phasecoher'; end; try, g.newfig; catch, g.newfig = 'on'; end; try, g.boottype; catch, g.boottype = 'shuffle'; end; try, g.subitc; catch, g.subitc = 'off'; end; try, g.compute; catch, g.compute = 'matlab'; end; try, g.maxamp; catch, g.maxamp = []; end; try, g.savecoher; catch, g.savecoher = 0; end; try, g.amplag; catch, g.amplag = 0; end; try, g.noinput; catch, g.noinput = 'no'; end; try, g.lowmem; catch, g.lowmem = 'off'; end; try, g.plottype; catch, g.plottype = 'image'; end; try, g.plotmean; catch, g.plotmean = 'on'; end; try, g.highlightmode; catch, g.highlightmode = 'background'; end; try, g.chaninfo; catch, g.chaninfo = []; end; if isfield(g, 'detret'), g.detrend = g.detret; end; if isfield(g, 'detrep'), g.rmerp = g.detrep; end; if ~isnan(g.alpha) && ndims(X) == 2 && (size(X,1) == 1 || size(X,2) == 1) error('Cannot compute significance for continuous data'); end; allfields = fieldnames(g); for index = 1:length(allfields) switch allfields{index} case { 'shuffle' 'title' 'winsize' 'pad' 'timesout' 'padratio' 'maxfreq' 'topovec' 'elocs' 'alpha' ... 'marktimes' 'vert' 'rboot' 'plotamp' 'plotphase' 'plotbootsub' 'detrep' 'rmerp' 'detret' 'detrend' ... 'baseline' 'baseboot' 'linewidth' 'naccu' 'angleunit' 'type' 'boottype' 'subitc' 'lowmem' 'plottype' ... 'compute' 'maxamp' 'savecoher' 'noinput' 'condboot' 'newfig' 'freqs' 'nfreqs' 'freqscale' 'amplag' ... 'highlightmode' 'plotmean' 'chaninfo' }; case {'plotersp' 'plotitc' }, disp(['crossf warning: timef option ''' allfields{index} ''' ignored']); otherwise disp(['crossf error: unrecognized option ''' allfields{index} '''']); beep; return; end; end; g.tlimits = tlimits; g.frame = frame; if ~iscell(X) g.trials = prod(size(X))/g.frame; else g.trials = prod(size(X{1}))/g.frame; end; g.srate = Fs; g.cycles = varwin; g.type = lower(g.type); g.boottype = lower(g.boottype); g.rmerp = lower(g.rmerp); g.detrend = lower(g.detrend); g.plotphase = lower(g.plotphase); g.plotbootsub = lower(g.plotbootsub); g.subitc = lower(g.subitc); g.plotamp = lower(g.plotamp); g.compute = lower(g.compute); g.AXES_FONT = 10; g.TITLE_FONT = 14; % change type if necessary if g.trials == 1 & ~strcmpi(g.type, 'crossspec') disp('Continuous data: switching to crossspectrum'); g.type = 'crossspec'; end; if strcmpi(g.freqscale, 'log') & g.freqs(1) == 0, g.freqs(1) = 3; end; % reshape 3D inputs % ----------------- if ndims(X) == 3 X = reshape(X, size(X,1), size(X,2)*size(X,3)); Y = reshape(Y, size(Y,1), size(Y,2)*size(Y,3)); end; % testing arguments consistency % ----------------------------- if strcmpi(g.title, DEFAULT_TITLE) switch g.type case 'coher', g.title = 'Event-Related Coherence'; % Figure title case 'phasecoher', g.title = 'Event-Related Phase Coherence'; case 'phasecoher2', g.title = 'Event-Related Phase Coherence 2'; case 'amp' , g.title = 'Event-Related Amplitude Correlation'; case 'crossspec', g.title = 'Event-Related Amplitude Correlation'; end; end; if ~ischar(g.title) & ~iscell(g.title) error('Title must be a string or a cell array.'); end if isempty(g.topovec) g.topovec = []; elseif min(size(g.topovec))==1 g.topovec = g.topovec(:); if size(g.topovec,1)~=2 error('topovec must be a row or column vector.'); end end; if isempty(g.elocs) g.elocs = ''; elseif (~ischar(g.elocs)) & ~isstruct(g.elocs) error('Channel location file must be a valid text file.'); end if (~isnumeric(g.alpha) | length(g.alpha)~=1) error('timef(): Value of g.alpha must be a number.\n'); elseif (round(g.naccu*g.alpha) < 2) fprintf('Value of g.alpha is out of the normal range [%g,0.5]\n',2/g.naccu); g.naccu = round(2/g.alpha); fprintf(' Increasing the number of bootstrap iterations to %d\n',g.naccu); end if g.alpha>0.5 | g.alpha<=0 error('Value of g.alpha is out of the allowed range (0.00,0.5).'); end switch lower(g.newfig) case { 'on', 'off' }, ; otherwise error('newfig must be either on or off'); end; switch g.angleunit case { 'ms', 'deg', 'rad' },; otherwise error('Angleunit must be either ''deg'', ''rad'', or ''ms'''); end; switch g.type case { 'coher', 'phasecoher' 'phasecoher2' 'amp' 'crossspec' },; otherwise error('Type must be either ''coher'', ''phasecoher'', ''crossspec'', or ''amp'''); end; switch g.boottype case { 'shuffle' 'shufftrials' 'rand' 'randall'},; otherwise error('Invalid boot type'); end; if ~isnumeric(g.shuffle) & ~iscell(g.shuffle) error('Shuffle argument type must be numeric'); end; switch g.compute case { 'matlab', 'c' },; otherwise error('compute must be either ''matlab'' or ''c'''); end; if ~strcmpi(g.condboot, 'abs') & ~strcmpi(g.condboot, 'angle') ... & ~strcmpi(g.condboot, 'complex') error('Condboot must be either ''abs'', ''angle'' or ''complex''.'); end; if g.tlimits(2)-g.tlimits(1) < 30 disp('Crossf WARNING: time range is very small (<30 ms). Times limits are in millisenconds not seconds.'); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute frequency by frequency if low memory %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(g.lowmem, 'on') & ~iscell(X) & length(X) ~= g.frame & (isempty(g.nfreqs) | g.nfreqs ~= 1) % compute for first 2 trials to get freqsout XX = reshape(X, 1, frame, length(X)/g.frame); YY = reshape(Y, 1, frame, length(Y)/g.frame); [coh,mcoh,timesout,freqs] = newcrossf(XX(1,:,1), YY(1,:,1), frame, tlimits, Fs, varwin, 'plotamp', 'off', 'plotphase', 'off',varargin{:}); % scan all frequencies for index = 1:length(freqs) if nargout < 6 [R(index,:),mbase(index),timesout,tmpfreqs(index),Rbootout(index,:),Rangle(index,:)] = ... newcrossf(X, Y, frame, tlimits, Fs, varwin, 'freqs', [freqs(index) freqs(index)], 'nfreqs', 1, ... 'plotamp', 'off', 'plotphase', 'off',varargin{:}, 'lowmem', 'off', 'timesout', timesout); elseif nargout == 7 % requires RAM [R(index,:),mbase(index),timesout,tmpfreqs(index),Rbootout(index,:),Rangle(index,:), ... coherresout(index,:,:)] = ... newcrossf(X, Y, frame, tlimits, Fs, varwin, 'freqs', [freqs(index) freqs(index)], 'nfreqs', 1, ... 'plotamp', 'off', 'plotphase', 'off',varargin{:}, 'lowmem', 'off', 'timesout', timesout); else [R(index,:),mbase(index),timesout,tmpfreqs(index),Rbootout(index,:),Rangle(index,:), ... coherresout(index,:,:),alltfX(index,:,:),alltfY(index,:,:)] = ... newcrossf(X, Y, frame, tlimits, Fs, varwin, 'freqs', [freqs(index) freqs(index)], 'nfreqs', 1, ... 'plotamp', 'off', 'plotphase', 'off',varargin{:}, 'lowmem', 'off', 'timesout', timesout); end; end; % plot and return plotall(R.*exp(j*Rangle), Rbootout, timesout, freqs, mbase, g); return; end; %%%%%%%%%%%%%%%%%%%%%%%%%%% % compare 2 conditions part %%%%%%%%%%%%%%%%%%%%%%%%%%% if iscell(X) if length(X) ~= 2 | length(Y) ~= 2 error('crossf: to compare conditions, X and Y input must be 2-elements cell arrays'); end; % deal with titles % ---------------- for index = length(vararginori)-1:-2:1 if index<=length(vararginori) % needed: if elemenets are deleted if strcmp(vararginori{index}, 'title') , vararginori(index:index+1) = []; end; if strcmp(vararginori{index}, 'subitc'), vararginori(index:index+1) = []; end; if strcmp(vararginori{index}, 'shuffle'), vararginori(index:index+1) = []; end; end; end; if ~iscell(g.subitc) g.subitc = { g.subitc g.subitc }; end; if ~iscell(g.shuffle) g.shuffle = { g.shuffle g.shuffle }; end; if iscell(g.title) if length(g.title) <= 2, g.title{3} = 'Condition 1 - condition 2'; end; else g.title = { 'Condition 1', 'Condition 2', 'Condition 1 - condition 2' }; end; fprintf('Running newcrossf on condition 1 *********************\n'); fprintf('Note: if an out-of-memory error occurs, try reducing the\n'); fprintf(' number of time points or number of frequencies\n'); fprintf(' (the ''coher'' options takes 3 times more memory than other options)\n'); if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') if strcmpi(g.newfig, 'on'), figure; end; subplot(1,3,1); end; if ~strcmp(g.type, 'coher') & nargout < 9 [R1,mbase,timesout,freqs,Rbootout1,Rangle1, savecoher1] = newcrossf(X{1}, Y{1}, ... frame, tlimits, Fs, varwin, 'savecoher', 1, 'title', g.title{1}, ... 'shuffle', g.shuffle{1}, 'subitc', g.subitc{1}, vararginori{:}); else [R1,mbase,timesout,freqs,Rbootout1,Rangle1, savecoher1, Tfx1, Tfy1] = newcrossf(X{1}, Y{1}, ... frame, tlimits, Fs, varwin, 'savecoher', 1, 'title', g.title{1}, ... 'shuffle', g.shuffle{1}, 'subitc', g.subitc{1}, vararginori{:}); end; R1 = R1.*exp(j*Rangle1/180*pi); fprintf('\nRunning newcrossf on condition 2 *********************\n'); if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') subplot(1,3,2); end; if ~strcmp(g.type, 'coher') & nargout < 9 [R2,mbase,timesout,freqs,Rbootout2,Rangle2, savecoher2] = newcrossf(X{2}, Y{2}, ... frame, tlimits, Fs, varwin,'savecoher', 1, 'title', g.title{2}, ... 'shuffle', g.shuffle{2}, 'subitc', g.subitc{2}, vararginori{:}); else [R2,mbase,timesout,freqs,Rbootout2,Rangle2, savecoher2, Tfx2, Tfy2] = newcrossf(X{2}, Y{2}, ... frame, tlimits, Fs, varwin,'savecoher', 1, 'title', g.title{2}, ... 'shuffle', g.shuffle{2}, 'subitc', g.subitc{2}, vararginori{:} ); end; %figure; imagesc(abs( sum( savecoher1 ./ abs(savecoher1), 3)) - abs( sum( savecoher2 ./ abs(savecoher2), 3) )); cbar; return; %figure; imagesc(abs( R2 ) - abs( R1) ); cbar; return; R2 = R2.*exp(j*Rangle2/180*pi); if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') subplot(1,3,3); end; if isnan(g.alpha) switch(g.condboot) case 'abs', Rdiff = abs(R1)-abs(R2); case 'angle', Rdiff = angle(R1)-angle(R2); case 'complex', Rdiff = R1-R2; end; g.title = g.title{3}; if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') plotall(Rdiff, [], timesout, freqs, mbase, g); end; Rbootout = []; else % preprocess data and run condstat % -------------------------------- switch g.type case 'coher', % take the square of alltfx and alltfy first to speed up Tfx1 = Tfx1.*conj(Tfx1); Tfx2 = Tfx2.*conj(Tfx2); Tfy1 = Tfy1.*conj(Tfy1); Tfy2 = Tfy2.*conj(Tfy2); formula = 'sum(arg1(:,:,X),3) ./ sqrt(sum(arg2(:,:,X),3)) ./ sqrt(sum(arg3(:,:,X),3))'; if strcmpi(g.lowmem, 'on') for ind = 1:2:size(savecoher1,1) if ind == size(savecoher1,1), indarr = ind; else indarr = [ind:ind+1]; end; [Rdiff(indarr,:,:) coherimages(indarr,:,:) coher1(indarr,:,:) coher2(indarr,:,:)] = condstat(formula, g.naccu, g.alpha, ... 'both', g.condboot, { savecoher1(indarr,:,:) savecoher2(indarr,:,:) }, ... { Tfx1(indarr,:,:) Tfx2(indarr,:,:) }, { Tfy1(indarr,:,:) Tfy2(indarr,:,:) }); end; else [Rdiff coherimages coher1 coher2] = condstat(formula, g.naccu, g.alpha, ... 'both', g.condboot, { savecoher1 savecoher2 }, { Tfx1 Tfx2 }, { Tfy1 Tfy2 }); end; case 'amp' % amplitude correlation error('Cannot compute difference of amplitude correlation images yet'); case 'crossspec' % amplitude correlation error('Cannot compute difference of cross-spectral decomposition'); case 'phasecoher', % normalize first to speed up savecoher1 = savecoher1 ./ sqrt(savecoher1.*conj(savecoher1)); savecoher2 = savecoher2 ./ sqrt(savecoher2.*conj(savecoher2)); % twice faster than abs() formula = 'sum(arg1(:,:,X),3) ./ length(X)'; if strcmpi(g.lowmem, 'on') for ind = 1:2:size(savecoher1,1) if ind == size(savecoher1,1), indarr = ind; else indarr = [ind:ind+1]; end; [Rdiff(indarr,:,:) coherimages(indarr,:,:) coher1(indarr,:,:) coher2(indarr,:,:)] = condstat(formula, g.naccu, g.alpha, ... 'both', g.condboot, { savecoher1(indarr,:,:) savecoher2(indarr,:,:) } ); end; else [Rdiff coherimages coher1 coher2] = condstat(formula, g.naccu, g.alpha, 'both', g.condboot, ... { savecoher1 savecoher2 }); end; case 'phasecoher2', savecoher1 = savecoher1 ./ sqrt(savecoher1.*conj(savecoher1)); savecoher2 = savecoher2 ./ sqrt(savecoher2.*conj(savecoher2)); % twice faster than abs() formula = 'sum(arg1(:,:,X),3) ./ sum(sqrt(arg1(:,:,X).*conj(arg1(:,:,X)))),3)'; % sqrt(a.*conj(a)) is about twice faster than abs() if strcmpi(g.lowmem, 'on') for ind = 1:2:size(savecoher1,1) if ind == size(savecoher1,1), indarr = ind; else indarr = [ind:ind+1]; end; [Rdiff(indarr,:,:) coherimages(indarr,:,:) coher1(indarr,:,:) coher2(indarr,:,:)] = condstat(formula, g.naccu, g.alpha, ... 'both', g.condboot, { savecoher1(indarr,:,:) savecoher2(indarr,:,:) } ); end; else [Rdiff coherimages coher1 coher2] = condstat(formula, g.naccu, g.alpha, 'both', g.condboot, ... { savecoher1 savecoher2 }); end; end; %Boot = bootinit( [], size(savecoher1,1), g.timesout, g.naccu, 0, g.baseboot, 'noboottype', g.alpha, g.rboot); %Boot.Coherboot.R = coherimages; %Boot = bootcomppost(Boot, [], [], []); g.title = g.title{3}; g.boottype = 'shufftrials'; if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') plotall(Rdiff, coherimages, timesout, freqs, mbase, g); end; % outputs Rbootout = {Rbootout1 Rbootout2 coherimages}; end; if size(Rdiff,3) > 1, Rdiff = reshape(Rdiff, 1, size(Rdiff,3)); end; R = { abs(R1) abs(R2) fastif(isreal(Rdiff), Rdiff, abs(Rdiff)) }; Rangle = { angle(R1) angle(R2) angle(Rdiff) }; coherresout = []; if nargout >=9 alltfX = { Tfx1 Tfx2 }; alltfY = { Tfy1 Tfy2 }; end; return; % ********************************** END FOR SEVERAL CONDITIONS end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % shuffle trials if necessary %%%%%%%%%%%%%%%%%%%%%%%%%%%%% if g.shuffle ~= 0 fprintf('x and y data trials being shuffled %d times\n',g.shuffle); XX = reshape(X, 1, frame, length(X)/g.frame); YY = Y; X = []; Y = []; for index = 1:g.shuffle XX = shuffle(XX,3); X = [X XX(:,:)]; Y = [Y YY]; end; end; % detrend over epochs (trials) if requested % ----------------------------------------- switch g.rmerp case 'on' X = reshape(X, g.frame, length(X)/g.frame); X = X - mean(X,2)*ones(1, length(X(:))/g.frame); Y = reshape(Y, g.frame, length(Y)/g.frame); Y = Y - mean(Y,2)*ones(1, length(Y(:))/g.frame); end; %%%%%%%%%%%%%%%%%%%%%% % display text to user %%%%%%%%%%%%%%%%%%%%%% fprintf('\nComputing the Event-Related \n'); switch g.type case 'phasecoher', fprintf('Phase Coherence (ITC) images based on %d trials\n',g.trials); case 'phasecoher2', fprintf('Phase Coherence 2 (ITC) images based on %d trials\n',g.trials); case 'coher', fprintf('Linear Coherence (ITC) images based on %d trials\n',g.trials); case 'amp', fprintf('Amplitude correlation images based on %d trials\n',g.trials); case 'crossspec', fprintf('Cross-spectral images based on %d trials\n',g.trials); end; if ~isnan(g.alpha) fprintf('Bootstrap confidence limits will be computed based on alpha = %g\n', g.alpha); else fprintf('Bootstrap confidence limits will NOT be computed.\n'); end switch g.plotphase case 'on', fprintf(['Coherence angles will be imaged in ',g.angleunit,'\n']); end; %%%%%%%%%%%%%%%%%%%%%%% % main computation loop %%%%%%%%%%%%%%%%%%%%%%% % ------------------------------------- % compute time frequency decompositions % ------------------------------------- if length(g.timesout) > 1, tmioutopt = { 'timesout' , g.timesout }; else tmioutopt = { 'ntimesout', g.timesout }; end; spectraloptions = { tmioutopt{:}, 'winsize', g.winsize, 'tlimits', g.tlimits, 'detrend', ... g.detrend, 'subitc', g.subitc, 'wavelet', g.cycles, 'padratio', g.padratio, ... 'freqs' g.freqs 'freqscale' g.freqscale 'nfreqs' g.nfreqs }; if ~strcmpi(g.type, 'amp') & ~strcmpi(g.type, 'crossspec') spectraloptions = { spectraloptions{:} 'itctype' g.type }; end; fprintf('\nProcessing first input\n'); X = reshape(X, g.frame, g.trials); [alltfX freqs timesout] = timefreq(X, g.srate, spectraloptions{:}); fprintf('\nProcessing second input\n'); Y = reshape(Y, g.frame, g.trials); [alltfY] = timefreq(Y, g.srate, spectraloptions{:}); % ------------------ % compute coherences % ------------------ tmpprod = alltfX .* conj(alltfY); if nargout > 6 | strcmpi(g.type, 'phasecoher2') | strcmpi(g.type, 'phasecoher') coherresout = alltfX .* conj(alltfY); end; switch g.type case 'crossspec', coherres = alltfX .* conj(alltfY); % no normalization case 'coher', coherres = sum(alltfX .* conj(alltfY), 3) ./ sqrt( sum(abs(alltfX).^2,3) .* sum(abs(alltfY).^2,3) ); case 'amp' alltfX = abs(alltfX); alltfY = abs(alltfY); coherres = ampcorr(alltfX, alltfY, freqs, timesout, g); g.alpha = NaN; coherresout = []; case 'phasecoher2', coherres = sum(coherresout, 3) ./ sum(abs(coherresout),3); case 'phasecoher', coherres = sum( coherresout ./ abs(coherresout), 3) / g.trials; end; %%%%%%%%%% % baseline %%%%%%%%%% if size(g.baseline,2) == 2 baseln = []; for index = 1:size(g.baseline,1) tmptime = find(timesout >= g.baseline(index,1) & timesout <= g.baseline(index,2)); baseln = union_bc(baseln, tmptime); end; if length(baseln)==0 error('No point found in baseline'); end; else if ~isempty(find(timesout < g.baseline)) baseln = find(timesout < g.baseline); % subtract means of pre-0 (centered) windows else baseln = 1:length(timesout); % use all times as baseline end end; if ~isnan(g.alpha) & length(baseln)==0 fprintf('timef(): no window centers in baseline (times<%g) - shorten (max) window length.\n', g.baseline) return end mbase = mean(abs(coherres(:,baseln)')); % mean baseline coherence magnitude % ----------------- % compute bootstrap % ----------------- if ~isempty(g.rboot) Rbootout = g.rboot; else if ~isnan(g.alpha) % getting formula for coherence % ----------------------------- switch g.type case 'coher', inputdata = { alltfX alltfY }; % default formula = 'sum(arg1 .* conj(arg2), 3) ./ sqrt( sum(abs(arg1).^2,3) .* sum(abs(arg2).^2,3) );'; case 'amp', % not implemented inputdata = { abs(alltfX) abs(alltfY) }; % default case 'phasecoher2', inputdata = { alltfX alltfY }; % default formula = [ 'tmp = arg1 .* conj(arg2);' ... 'res = sum(tmp, 3) ./ sum(abs(tmp),3);' ]; case 'phasecoher', inputdata = { alltfX./abs(alltfX) alltfY./abs(alltfY) }; formula = [ 'mean(arg1 .* conj(arg2),3);' ]; case 'crossspec', inputdata = { alltfX./abs(alltfX) alltfY./abs(alltfY) }; formulainit = [ 'arg1 .* conj(arg2);' ]; end; % finding baseline for bootstrap % ------------------------------ if size(g.baseboot,2) == 1 if g.baseboot == 0, baselntmp = []; elseif ~isnan(g.baseline(1)) baselntmp = baseln; else baselntmp = find(timesout <= 0); % if it is empty use whole epoch end; else baselntmp = []; for index = 1:size(g.baseboot,1) tmptime = find(timesout >= g.baseboot(index,1) & timesout <= g.baseboot(index,2)); baselntmp = union_bc(baselntmp, tmptime); end; end; if prod(size(g.baseboot)) > 2 fprintf('Bootstrap analysis will use data in multiple selected windows.\n'); elseif size(g.baseboot,2) == 2 fprintf('Bootstrap analysis will use data in range %3.2g-%3.2g ms.\n', g.baseboot(1), g.baseboot(2)); elseif g.baseboot fprintf(' %d bootstrap windows in baseline (times<%g).\n', length(baselntmp), g.baseboot) end; if strcmpi(g.boottype, 'shuffle') | strcmpi(g.boottype, 'rand') Rbootout = bootstat(inputdata, formula, 'boottype', g.boottype, 'label', 'coherence', ... 'bootside', 'upper', 'shuffledim', [2 3], 'dimaccu', 2, ... 'naccu', g.naccu, 'alpha', g.alpha, 'basevect', baselntmp); elseif strcmpi(g.boottype, 'randall') % randomize phase but do not accumulate over time % dimension (NOT TESTED) % note the absence of dimaccu and the shuffledim 3 Rbootout = bootstat(inputdata, formula, 'boottype', 'rand', ... 'bootside', 'upper', 'shuffledim', 3, ... 'naccu', g.naccu, 'alpha', g.alpha, 'basevect', baselntmp); else % shuffle only trials (NOT TESTED) % note the absence of dimaccu and the shuffledim 3 Rbootout = bootstat(inputdata, formula, 'boottype', 'shuffle', ... 'bootside', 'upper', 'shuffledim', 3, ... 'naccu', g.naccu, 'alpha', g.alpha, 'basevect', baselntmp); end; else Rbootout = []; end; % note that the bootstrap thresholding is actually performed in the display subfunction plotall() end; % plot everything % --------------- if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') if strcmpi(g.plottype, 'image') plotall ( coherres, Rbootout, timesout, freqs, mbase, g); else plotallcurves( coherres, Rbootout, timesout, freqs, mbase, g); end; end; % proces outputs % -------------- Rangle = angle(coherres); R = abs(coherres); return; % *********************************************************************** % ------------------------------ % amplitude correlation function % ------------------------------ function [coherres, lagmap] = ampcorr(alltfX, alltfY, freqs, timesout, g) % initialize variables % -------------------- coherres = zeros(length(freqs), length(timesout), length(g.amplag)); alpha = zeros(length(freqs), length(timesout), length(g.amplag)); countlag = 1; for lag = g.amplag fprintf('Computing %d point lag amplitude correlation, please wait...\n', lag); for i1 = 1:length(freqs) for i2 = max(1, 1-lag):min(length(timesout)-lag, length(timesout)) if ~isnan(g.alpha) [tmp1 tmp2] = corrcoef( squeeze(alltfX(i1,i2,:)), squeeze(alltfY(i1,i2+lag,:)) ); coherres(i1,i2,countlag) = tmp1(1,2); alpha(i1,i2,countlag) = tmp2(1,2); else tmp1 = corrcoef( squeeze(alltfX(i1,i2,:)), squeeze(alltfY(i1,i2+lag,:)) ); coherres(i1,i2,countlag) = tmp1(1,2); end; end; end; countlag = countlag + 1; end; % find max corr if different lags % ------------------------------- if length(g.amplag) > 1 [coherres lagmap] = max(coherres, [], 3); dimsize = length(freqs)*length(timesout); alpha = reshape(alpha((lagmap(:)-1)*dimsize+[1:dimsize]'),length(freqs), length(timesout)); % above is same as (but faster) % for i1 = 1:length(freqs) % for i2 = 1:length(timesout) % alphanew(i1, i2) = alpha(i1, i2, lagmap(i1, i2)); % end; % end; lagmap = g.amplag(lagmap); % real lag coherres = coherres.*exp(j*lagmap/max(abs(g.amplag))); % encode lag in the phase else lagmap = []; end; % apply significance mask % ----------------------- if ~isnan(g.alpha) tmpind = find(alpha(:) > g.alpha); coherres(tmpind) = 0; end; % ------------------ % plotting functions % ------------------ function plotall(R, Rboot, times, freqs, mbase, g) switch lower(g.plotphase) case 'on', switch lower(g.plotamp), case 'on', ordinate1 = 0.67; ordinate2 = 0.1; height = 0.33; g.plot = 1; case 'off', ordinate2 = 0.1; height = 0.9; g.plot = 1; end; case 'off', ordinate1 = 0.1; height = 0.9; switch lower(g.plotamp), case 'on', ordinate1 = 0.1; height = 0.9; g.plot = 1; case 'off', g.plot = 0; end; end; % compute angles % -------------- Rangle = angle(R); if ~isreal(R) R = abs(R); Rraw =R; % raw coherence values setylim = 1; if ~isnan(g.baseline) R = R - repmat(mbase',[1 g.timesout]); % remove baseline mean end; else Rraw = R; setylim = 0; end; if g.plot fprintf('\nNow plotting...\n'); set(gcf,'DefaultAxesFontSize',g.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') end; switch lower(g.plotamp) case 'on' % % Image the coherence [% perturbations] % RR = R; if ~isnan(g.alpha) % zero out (and 'green out') nonsignif. R values switch dims(Rboot) case 3, RR (find(RR > Rboot(:,:,1) & (RR < Rboot(:,:,2)))) = 0; Rraw(find(RR > Rboot(:,:,1) & (RR < Rboot(:,:,2)))) = 0; case 2, RR (find(RR < Rboot)) = 0; Rraw(find(RR < Rboot)) = 0; case 1, RR (find(RR < repmat(Rboot(:),[1 size(RR,2)]))) = 0; Rraw(find(RR < repmat(Rboot(:),[1 size(Rraw,2)]))) = 0; end; end h(6) = axes('Units','Normalized', 'Position',[.1 ordinate1 .8 height].*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); if ~strcmpi(g.freqscale, 'log') try, imagesc(times,freqs,RR,max(max(RR))*[-1 1]); % plot the coherence image catch, imagesc(times,freqs,RR,[-1 1]); end; else try, imagesclogy(times,freqs,RR,max(max(RR))*[-1 1]); % plot the coherence image catch, imagesclogy(times,freqs,RR,[-1 1]); end; end; set(gca,'ydir','norm'); if ~isempty(g.maxamp) caxis([-g.maxamp g.maxamp]); end; tmpscale = caxis; hold on plot([0 0],[0 freqs(end)],'--m','LineWidth',g.linewidth) for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[0 freqs(end)],'--m','LineWidth',g.linewidth); end; hold off set(h(6),'YTickLabel',[],'YTick',[]) set(h(6),'XTickLabel',[],'XTick',[]) h(8) = axes('Position',[.95 ordinate1 .05 height].*s+q); if setylim cbar(h(8),151:300, [0 tmpscale(2)]); % use only positive colors (gyorv) else cbar(h(8),1:300 , [-tmpscale(2) tmpscale(2)]); % use only positive colors (gyorv) end; % % Plot delta-mean min and max coherence at each time point on bottom of image % h(10) = axes('Units','Normalized','Position',[.1 ordinate1-0.1 .8 .1].*s+q); % plot marginal means below Emax = max(R); % mean coherence at each time point Emin = min(R); % mean coherence at each time point plot(times,Emin, times, Emax, 'LineWidth',g.linewidth); hold on; plot([times(1) times(length(times))],[0 0],'LineWidth',0.7); plot([0 0],[-500 500],'--m','LineWidth',g.linewidth); for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[-500 500],'--m','LineWidth',g.linewidth); end; if ~isnan(g.alpha) & dims(Rboot) > 1 % plot bootstrap significance limits (base mean +/-) switch dims(Rboot) case 2, plot(times,mean(Rboot(:,:),1),'g' ,'LineWidth',g.linewidth); plot(times,mean(Rboot(:,:),1),'k:','LineWidth',g.linewidth); case 3, plot(times,mean(Rboot(:,:,1),1),'g' ,'LineWidth',g.linewidth); plot(times,mean(Rboot(:,:,1),1),'k:','LineWidth',g.linewidth); plot(times,mean(Rboot(:,:,2),1),'g' ,'LineWidth',g.linewidth); plot(times,mean(Rboot(:,:,2),1),'k:','LineWidth',g.linewidth); end; axis([min(times) max(times) 0 max([Emax(:)' Rboot(:)'])*1.2]) else axis([min(times) max(times) 0 max(Emax)*1.2]) end; tick = get(h(10),'YTick'); set(h(10),'YTick',[tick(1) ; tick(length(tick))]) set(h(10),'YAxisLocation','right') xlabel('Time (ms)') ylabel('coh.') % % Plot mean baseline coherence at each freq on left side of image % h(11) = axes('Units','Normalized','Position',[0 ordinate1 .1 height].*s+q); % plot mean spectrum E = abs(mbase); % baseline mean coherence at each frequency if ~strcmpi(g.freqscale, 'log') plot(freqs,E,'b','LineWidth',g.linewidth); % plot mbase else semilogx(freqs,E,'b','LineWidth',g.linewidth); % plot mbase set(h(11),'View',[90 90]) divs = linspace(log(freqs(1)), log(freqs(end)), 10); set(gca, 'xtickmode', 'manual'); divs = ceil(exp(divs)); divs = unique_bc(divs); % ceil is critical here, round might misalign % out-of border label with within border ticks set(gca, 'xtick', divs); end; if ~isnan(g.alpha) % plot bootstrap significance limits (base mean +/-) hold on if ~strcmpi(g.freqscale, 'log') switch dims(Rboot) case 1, plot(freqs,Rboot(:),'g' ,'LineWidth',g.linewidth); plot(freqs,Rboot(:),'k:','LineWidth',g.linewidth); case 2, plot(freqs,mean(Rboot(:,:),2),'g' ,'LineWidth',g.linewidth); plot(freqs,mean(Rboot(:,:),2),'k:','LineWidth',g.linewidth); case 3, plot(freqs,mean(Rboot(:,:,1),2),'g' ,'LineWidth',g.linewidth); plot(freqs,mean(Rboot(:,:,1),2),'k:','LineWidth',g.linewidth); plot(freqs,mean(Rboot(:,:,2),2),'g' ,'LineWidth',g.linewidth); plot(freqs,mean(Rboot(:,:,2),2),'k:','LineWidth',g.linewidth); end; else switch dims(Rboot) case 1, semilogy(freqs,Rboot(:),'g' ,'LineWidth',g.linewidth); semilogy(freqs,Rboot(:),'k:','LineWidth',g.linewidth); case 2, semilogy(freqs,mean(Rboot(:,:),2),'g' ,'LineWidth',g.linewidth); semilogy(freqs,mean(Rboot(:,:),2),'k:','LineWidth',g.linewidth); case 3, semilogy(freqs,mean(Rboot(:,:,1),2),'g' ,'LineWidth',g.linewidth); semilogy(freqs,mean(Rboot(:,:,1),2),'k:','LineWidth',g.linewidth); semilogy(freqs,mean(Rboot(:,:,2),2),'g' ,'LineWidth',g.linewidth); semilogy(freqs,mean(Rboot(:,:,2),2),'k:','LineWidth',g.linewidth); end; end; if ~isnan(max(E)) axis([freqs(1) freqs(end) 0 max([E Rboot(:)'])*1.2]); end; else % plot marginal mean coherence only if ~isnan(max(E)) axis([freqs(1) freqs(end) 0 max(E)*1.2]); end; end set(gca,'xdir','rev'); % nima tick = get(h(11),'YTick'); set(h(11),'YTick',[tick(1) ; tick(length(tick))]); % crashes for log set(h(11),'View',[90 90]) xlabel('Freq. (Hz)') ylabel('coh.') end; switch lower(g.plotphase) case 'on' % % Plot coherence phase lags in bottom panel % h(13) = axes('Units','Normalized','Position',[.1 ordinate2 .8 height].*s+q); if setylim if strcmpi(g.type, 'amp') % currrently -1 to 1 maxangle = max(abs(g.amplag)) * mean(times(2:end) - times(1:end-1)); Rangle = Rangle * maxangle; maxangle = maxangle+5; % so that the min and the max does not mix else if strcmp(g.angleunit,'ms') % convert to ms Rangle = (Rangle/(2*pi)).*repmat(1000./freqs(:)',1,length(times)); maxangle = max(max(abs(Rangle))); elseif strcmpi(g.angleunit,'deg') % convert to degrees Rangle = Rangle*180/pi; % convert to degrees maxangle = 180; % use full-cycle plotting else maxangle = pi; end end; Rangle(find(Rraw==0)) = 0; % set angle at non-signif coher points to 0 if ~strcmpi(g.freqscale, 'log') imagesc(times,freqs,Rangle,[-maxangle maxangle]); % plot the coherence phase angles else imagesclogy(times,freqs,Rangle,[-maxangle maxangle]); % plot the coherence phase angles end; hold on plot([0 0],[0 freqs(end)],'--m','LineWidth',g.linewidth); % zero-time line for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[0 freqs(end)],'--m','LineWidth',g.linewidth); end; set(gca,'ydir','norm'); % nima ylabel('Freq. (Hz)') xlabel('Time (ms)') h(14)=axes('Position',[.95 ordinate2 .05 height].*s+q); cbar(h(14),0,[-maxangle maxangle]); % two-sided colorbar else axis off; text(0, 0.5, 'Real values, no angles'); end; end if g.plot try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) % plot title axes('Position',pos,'Visible','Off'); h(13) = text(-.05,1.01,g.title); set(h(13),'VerticalAlignment','bottom') set(h(13),'HorizontalAlignment','left') set(h(13),'FontSize',g.TITLE_FONT) end % %%%%%%%%%%%%%%% plot topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) & strcmpi(g.plotamp, 'on') & strcmpi(g.plotphase, 'on') h(15) = subplot('Position',[-.1 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(1),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec(1,:),g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') h(16) = subplot('Position',[.9 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(2),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec(2,:),g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') end try, axcopy(gcf); catch, end; end; % --------------- % Plotting curves % --------------- function plotallcurves(R, Rboot, times, freqs, mbase, g) % compute angles % -------------- Rangle = angle(R); 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)]; if ~isreal(R) R = abs(R); Rraw =R; % raw coherence values if ~isnan(g.baseline) R = R - repmat(mbase',[1 g.timesout]); % remove baseline mean end; else Rraw = R; setylim = 0; end; % time unit % --------- if times(end) > 10000 times = times/1000; timeunit = 's'; else timeunit = 'ms'; end; % legend % ------ alllegend = {}; if strcmpi(g.plotmean, 'on') & freqs(1) ~= freqs(end) alllegend = { [ num2str(freqs(1)) '-' num2str(freqs(end)) 'Hz' ] }; else for index = 1:length(freqs) alllegend{index} = [ num2str(freqs(index)) 'Hz' ]; end; end; fprintf('\nNow plotting...\n'); if strcmpi(g.plotamp, 'on') % % Plot coherence amplitude in top panel % if strcmpi(g.plotphase, 'on'), subplot(2,1,1); end; if isempty(g.maxamp), g.maxamp = 0; end; plotcurve(times, R, 'maskarray', Rboot, 'title', 'Coherence amplitude', ... 'xlabel', [ 'Time (' timeunit ')' ], 'ylabel', '0-1', 'ylim', g.maxamp, ... 'vert', g.vert, 'marktimes', g.marktimes, 'legend', alllegend, ... 'linewidth', g.linewidth, 'highlightmode', g.highlightmode, 'plotmean', g.plotmean); end; if strcmpi(g.plotphase, 'on') % % Plot coherence phase lags in bottom panel % if strcmpi(g.plotamp, 'on'), subplot(2,1,2); end; plotcurve(times, Rangle/pi*180, 'maskarray', Rboot, 'val2mask', R, 'title', 'Coherence phase', ... 'xlabel', [ 'Time (' timeunit ')' ], 'ylabel', 'Angle (deg.)', 'ylim', [-180 180], ... 'vert', g.vert, 'marktimes', g.marktimes, 'legend', alllegend, ... 'linewidth', g.linewidth, 'highlightmode', g.highlightmode, 'plotmean', g.plotmean); end if strcmpi(g.plotamp, 'on') | strcmpi(g.plotphase, 'on') try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) % plot title h(13) = textsc(g.title, 'title'); end % %%%%%%%%%%%%%%% plot topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) h(15) = subplot('Position',[-.1 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(1),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10); else topoplot(g.topovec(1,:),g.elocs,'electrodes','off'); end; axis('square') h(16) = subplot('Position',[.9 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(2),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10); else topoplot(g.topovec(2,:),g.elocs,'electrodes','off'); end; axis('square') end try, axcopy(gcf); catch, end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COHERENCE OBSOLETE %%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function for coherence initialisation % ------------------------------------- function Coher = coherinit(nb_points, trials, timesout, type); Coher.R = zeros(nb_points,timesout); % mean coherence %Coher.RR = repmat(nan,nb_points,timesout); % initialize with nans Coher.type = type; Coher.Rn=zeros(trials,timesout); switch type case 'coher', Coher.cumulX = zeros(nb_points,timesout); Coher.cumulY = zeros(nb_points,timesout); case 'phasecoher2', Coher.cumul = zeros(nb_points,timesout); end; % function for coherence calculation % ------------------------------------- %function Coher = cohercomparray(Coher, tmpX, tmpY, trial); %switch Coher.type % case 'coher', % Coher.R = Coher.R + tmpX.*conj(tmpY); % complex coher. % Coher.cumulXY = Coher.cumulXY + abs(tmpX).*abs(tmpY); % case 'phasecoher', % Coher.R = Coher.R + tmpX.*conj(tmpY) ./ (abs(tmpX).*abs(tmpY)); % complex coher. % Coher.Rn(trial,:) = 1; %end % ~any(isnan()) function [Coher,tmptrialcoh] = cohercomp(Coher, tmpX, tmpY, trial, time); tmptrialcoh = tmpX.*conj(tmpY); switch Coher.type case 'coher', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh; % complex coher. Coher.cumulX(:,time) = Coher.cumulX(:,time) + abs(tmpX).^2; Coher.cumulY(:,time) = Coher.cumulY(:,time) + abs(tmpY).^2; case 'phasecoher2', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh; % complex coher. Coher.cumul(:,time) = Coher.cumul(:,time) + abs(tmptrialcoh); case 'phasecoher', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh ./ abs(tmptrialcoh); % complex coher. %figure; imagesc(abs(tmpX.*conj(tmpY) ./ (abs(tmpX).*abs(tmpY)))); Coher.Rn(trial,time) = Coher.Rn(trial,time)+1; end % ~any(isnan()) % function for post coherence calculation % --------------------------------------- function Coher = cohercomppost(Coher, trials); switch Coher.type case 'coher', Coher.R = Coher.R ./ sqrt(Coher.cumulX) ./ sqrt(Coher.cumulY); case 'phasecoher2', Coher.R = Coher.R ./ Coher.cumul; case 'phasecoher', Coher.Rn = sum(Coher.Rn, 1); Coher.R = Coher.R ./ (ones(size(Coher.R,1),1)*Coher.Rn); % coherence magnitude end; % function for 2 conditions coherence calculation % ----------------------------------------------- function [coherimage, coherimage1, coherimage2] = coher2conddiff( allsavedcoher, alltrials, cond1trials, type, tfx, tfy); t1s = alltrials(1:cond1trials); t2s = alltrials(cond1trials+1:end); switch type case 'coher', coherimage1 = sum(allsavedcoher(:,:,t1s),3) ./ sqrt(sum(tfx(:,:,t1s))) ./ sqrt(sum(tfy(:,:,t1s))); coherimage2 = sum(allsavedcoher(:,:,t2s),3) ./ sqrt(sum(tfx(:,:,t2s))) ./ sqrt(sum(tfy(:,:,t1s))); case 'phasecoher2', coherimage1 = sum(allsavedcoher(:,:,t1s),3) ./ sum(abs(allsavedcoher(:,:,t1s)),3); coherimage2 = sum(allsavedcoher(:,:,t2s),3) ./ sum(abs(allsavedcoher(:,:,t2s)),3); case 'phasecoher', coherimage1 = sum(allsavedcoher(:,:,t1s),3) / cond1trials; coherimage2 = sum(allsavedcoher(:,:,t2s),3) / (size(allsavedcoher,3)-cond1trials); end; coherimage = coherimage2 - coherimage1; function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end function res = dims(array) res = min(ndims(array), max(size(array,2),size(array,3)));
github
lcnbeapp/beapp-master
crossf.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/crossf.m
59,295
utf_8
395468032fe3d1abba14d59dfe6d1317
% crossf() - Returns estimates and plots event-related coherence (ERCOH) % between two input data time series (X,Y). A lower panel (optionally) % shows the coherence phase difference between the processes. % In this panel, output by > crossf(X,Y,...); % 90 degrees (orange) means X leads Y by a quarter cycle. % -90 degrees (blue) means Y leads X by a quarter cycle. % Coherence phase units may be radians, degrees, or msec. % Click on any subplot to view separately and zoom in/out. % % Function description: % Uses EITHER fixed-window, zero-padded FFTs (fastest) OR constant-Q % 0-padded wavelet DFTs (more even sensitivity across frequencies), % both Hanning-tapered. Output frequency spacing is the lowest % frequency ('srate'/'winsize') divided by the 'padratio'. % % If an 'alpha' value is given, then bootstrap statistics are % computed (from a distribution of 'naccu' {200} surrogate baseline % data epochs) for the baseline epoch, and non-significant features % of the output plots are zeroed (and shown in green). The baseline % epoch is all windows with center latencies < the given 'baseline' % value, or if 'baseboot' is 1, the whole epoch. % Usage: % >> [coh,mcoh,timesout,freqsout,cohboot,cohangles] ... % = crossf(X,Y,frames,tlimits,srate,cycles, ... % 'key1', 'val1', 'key2', val2' ...); % Required inputs: % X = first single-channel data set (1,frames*nepochs) % Y = second single-channel data set (1,frames*nepochs) % frames = frames per epoch {default: 750} % tlimits = [mintime maxtime] (ms) epoch latency limits {def: [-1000 2000]} % srate = data sampling rate (Hz) {default: 250} % cycles = 0 -> Use FFTs (with constant window length) % = >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: 0} % Optional Coherence Type: % 'type' = ['coher'|'phasecoher'] Compute either linear coherence % ('coher') or phase coherence ('phasecoher') also known % as phase coupling factor' {default: 'phasecoher'}. % 'subitc' = ['on'|'off'] subtract stimulus locked Inter-Trial Coherence % from X and Y. This computes the 'intrinsic' coherence % X and Y not arising from common synchronization to % experimental events. See notes. {default: 'off'} % 'shuffle' = integer indicating the number of estimates to compute % bootstrap coherence based on shuffled trials. This estimates % the coherence arising only from time locking of X and Y % to experimental events (opposite of 'subitc') {default: 0} % Optional Detrend: % 'detret' = ['on'|'off'], Linearly detrend data within epochs {def: 'off'} % 'detrep' = ['on'|'off'], Linearly detrend data across trials {def: 'off'} % % Optional FFT/DFT: % '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 {default: ~frames/8} % 'timesout' = Number of output latencies (int<frames-winsize) {def: 200} % 'padratio' = FFTlength/winsize (2^k) {default: 2} % Multiplies the number of output frequencies by % dividing their spacing. When cycles==0, frequency % spacing is (low_frequency/padratio). % 'maxfreq' = Maximum frequency (Hz) to plot (& output if cycles>0) % If cycles==0, all FFT frequencies are output {default: 50} % 'baseline' = Coherence baseline end latency (ms). NaN -> No baseline % {default:NaN} % 'powbase' = Baseline spectrum to log-subtract {default: from data} % % Optional Bootstrap: % 'alpha' = If non-0, compute two-tailed bootstrap significance prob. % level. Show non-signif output values as green. {def: 0} % 'naccu' = Number of bootstrap replications to compute {def: 200} % 'boottype' = ['times'|'timestrials'] Bootstrap type: Either shuffle % windows ('times') or windows and trials ('timestrials') % Option 'timestrials' requires more memory {default: 'times'} % 'memory' = ['low'|'high'] 'low' -> decrease memory use {default: 'high'} % 'baseboot' = Extent of bootstrap shuffling (0=to 'baseline'; 1=whole epoch) % If no baseline is given (NaN), extent of bootstrap shuffling % is the whole epoch {default: 0} % 'rboot' = Input bootstrap coherence limits (e.g., from crossf()) % The bootstrap type should be identical to that used % to obtain the input limits. {default: compute from data} % Optional Scalp Map: % 'topovec' = (2,nchans) matrix, plot scalp maps to plot {default: []} % ELSE (c1,c2), plot two cartoons showing channel locations. % 'elocs' = Electrode location structure or file for scalp map % {default: none} % 'chaninfo' = Electrode location additional information (nose position...) % {default: none} % % Optional Plot and Compute Features: % 'compute' = ['matlab'|'c'] Use C subroutines to speed up the % computation (currently unimplemented) {def: 'matlab'} % 'savecoher' - [0|1] 1 --> Accumulate the individual trial coherence % vectors; output them as cohangles {default: 0 = off} % 'plotamp' = ['on'|'off'], Plot coherence magnitude {def: 'on'} % 'maxamp' = [real] Set the maximum for the amp. scale {def: auto} % 'plotphase' = ['on'|'off'], Plot coherence phase angle {def: 'on'} % 'angleunit' = Phase units: 'ms' -> msec, 'deg' -> degrees, % or 'rad' -> radians {default: 'deg'} % 'title' = Optional figure title {default: none} % 'vert' = Latencies to mark with a dotted vertical line % {default: none} % 'linewidth' = Line width for marktimes traces (thick=2, thin=1) % {default: 2} % 'cmax' = Maximum amplitude for color scale {def: data limits} % 'axesfont' = Axes font size {default: 10} % 'titlefont' = Title font size {default: 8} % % Outputs: % coh = Matrix (nfreqs,timesout) of coherence magnitudes % mcoh = Vector of mean baseline coherence at each frequency % timesout = Vector of output latencies (window centers) (ms). % freqsout = Vector of frequency bin centers (Hz). % cohboot = Matrix (nfreqs,2) of [lower;upper] coher signif. limits % if 'boottype' is 'trials', (nfreqs,timesout, 2) % cohangle = (nfreqs,timesout) matrix of coherence angles (in radians) % cohangles = (nfreqs,timesout,trials) matrix of single-trial coherence % angles (in radians), saved and output only if 'savecoher',1 % % Plot description: % Assuming both 'plotamp' and 'plotphase' options are 'on' (=default), the upper panel % presents the magnitude of either phase coherence or linear coherence, depending on % the 'type' parameter (above). The lower panel presents the coherence phase difference % (in degrees). Click on any plot to pop up a new window (using 'axcopy()'). % -- The upper left marginal panel shows mean coherence during the baseline period % (blue), and when significance is set, the significance threshold (dotted black-green). % -- The horizontal panel under the coherence magnitude image indicates the maximum % (green) and minimum (blue) coherence values across all frequencies. When significance % is set (using option 'trials' for 'boottype'), an additional curve indicates the % significance threshold (dotted black-green). % % Notes: 1) When cycles==0, nfreqs is total number of FFT frequencies. % 2) As noted above: 'blue' coherence angle -> X leads Y; 'red' -> Y leads X % 3) The 'boottype' should be ideally 'timesframes', but this creates high % memory demands, so the 'times' method must be used in many cases. % 4) If 'boottype' is 'trials', the average of the complex bootstrap % is subtracted from the coherence to compensate for phase differences % (the average is also subtracted from the bootstrap distribution). % For other bootstraps, this is not necessary since the phase is random. % 5) If baseline is non-NaN, the baseline is subtracted from % the complex coherence. On the left hand side of the coherence % amplitude image, the baseline is displayed as a magenta line % (if no baseline is selected, this curve represents the average % coherence at every given frequency). % 6) If a out-of-memory error occurs, set the 'memory' option to 'low' % (Makes computation time slower; Only the 'times' bootstrap method % can be used in this mode). % % Authors: Arnaud Delorme, Sigurd Enghoff & Scott Makeig % CNL/Salk Institute 1998-2001; SCCN/INC/UCSD, La Jolla, 2002- % % See also: timef() % Copyright (C) 8/1/98 Arnaud Delorme, 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 g.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-05-2007 eventlock.m deprecated to eegalign.m. -tf % 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 % 03-09-02 function restructuration -ad % add 'key', val arguments (+ external baseboot, baseline, color axis, angleunit...) % add detrending (across time and trials) + 'coher' option for amplitude coherence % significance only if alpha is given, ploting options in 'plotamp' and 'plotphase' % 03-16-02 timeout automatically adjusted if too high -ad % 04-03-02 added new options for bootstrap -ad % Note: 3 "objects" (Tf, Coher and Boot) are handled by specific functions under Matlab % (Tf) function Tf = tfinit(...) - create object Time Frequency (Tf) associated with some data % (Tf) function [Tf, itcvals] = tfitc(...) - compute itc for the selected data % (Tf) function [Tf, itcvals] = tfitcpost(Tf, trials) - itc normlisation % (Tf) function [Tf, tmpX] = tfcomp(Tf, trials, times) - compute time freq. decomposition % (Coher) function Coher = coherinit(...) - initialize coherence object % (Coher) function Coher = cohercomp(Coher, tmpX, tmpY, trial, time) - compute coherence % (Coher) function Coher = cohercomppost(Coher, trials) - coherence normalization % (Boot) function Boot = bootinit(...) - intialize bootstrap object % (Boot) function Boot = bootcomp(...) - compute bootstrap % (Boot) function [Boot, Rbootout] = bootcomppost(...) - bootstrap normalization % and by real objects under C++ (C++ code, incomplete) function [R,mbase,times,freqs,Rbootout,Rangle, trialcoher, Tfx, Tfy] = crossf(X, Y, frame, tlimits, Fs, varwin, varargin) %varwin,winsize,nwin,oversmp,maxfreq,alpha,verts,caxmax) % ------------------------ % Commandline arg defaults: % ------------------------ DEFAULT_ANGLEUNIT = 'deg'; % angle plotting units - 'rad', 'ms', or 'deg' DEFAULT_EPOCH = 750; % Frames per epoch DEFAULT_TIMELIM = [-1000 2000]; % Time range of epochs (ms) DEFAULT_FS = 250; % 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 = 'Event-Related Coherence'; % Figure title DEFAULT_ALPHA = NaN; % Default two-sided significance probability threshold if (nargin < 2) help crossf return end if ~iscell(X) if (min(size(X))~=1 | length(X)<2) fprintf('crossf(): X must be a row or column vector.\n'); return elseif (min(size(Y))~=1 | length(Y)<2) fprintf('crossf(): Y must be a row or column vector.\n'); return elseif (length(X) ~= length(Y)) fprintf('crossf(): X and Y must have same length.\n'); return end end; if (nargin < 3) frame = DEFAULT_EPOCH; elseif (~isnumeric(frame) | length(frame)~=1 | frame~=round(frame)) fprintf('crossf(): Value of frames must be an integer.\n'); return elseif (frame <= 0) fprintf('crossf(): Value of frames must be positive.\n'); return elseif ~iscell(X) & (rem(length(X),frame) ~= 0) fprintf('crossf(): Length of data vectors must be divisible by frames.\n'); return end if (nargin < 4) tlimits = DEFAULT_TIMELIM; elseif (~isnumeric(tlimits) | sum(size(tlimits))~=3) error('crossf(): Value of tlimits must be a vector containing two numbers.'); elseif (tlimits(1) >= tlimits(2)) error('crossf(): tlimits interval must be [min,max].'); end if (nargin < 5) 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 < 6) varwin = DEFAULT_VARWIN; elseif (~isnumeric(varwin) | length(varwin)>2) error('crossf(): Value of cycles must be a number or a (1,2) vector.'); elseif (varwin < 0) error('crossf(): Value of cycles must be either zero or positive.'); end % consider structure for these arguments % -------------------------------------- vararginori = varargin; for index=1:length(varargin) if iscell(varargin{index}), varargin{index} = { varargin{index} }; end; end; if ~isempty(varargin) try, g = struct(varargin{:}); catch, error('Argument error in the {''param'', value} sequence'); end; else g = []; end; try, g.shuffle; catch, g.shuffle = 0; end; try, g.title; catch, g.title = DEFAULT_TITLE; end; try, g.winsize; catch, g.winsize = max(pow2(nextpow2(frame)-3),4); end; try, g.pad; catch, g.pad = max(pow2(nextpow2(g.winsize)),4); end; try, g.timesout; catch, g.timesout = DEFAULT_NWIN; end; try, g.padratio; catch, g.padratio = DEFAULT_OVERSMP; end; try, g.maxfreq; catch, g.maxfreq = DEFAULT_MAXFREQ; end; try, g.topovec; catch, g.topovec = []; end; try, g.elocs; catch, g.elocs = ''; end; try, g.alpha; catch, g.alpha = DEFAULT_ALPHA; end; try, g.marktimes; catch, g.marktimes = []; end; % default no vertical lines try, g.marktimes = g.vert; catch, g.vert = []; end; % default no vertical lines try, g.powbase; catch, g.powbase = nan; end; try, g.rboot; catch, g.rboot = nan; end; try, g.plotamp; catch, g.plotamp = 'on'; end; try, g.plotphase; catch, g.plotphase = 'on'; end; try, g.plotbootsub; catch, g.plotbootsub = 'on'; end; try, g.detrep; catch, g.detrep = 'off'; end; try, g.detret; catch, g.detret = 'off'; end; try, g.baseline; catch, g.baseline = NaN; end; try, g.baseboot; catch, g.baseboot = 0; end; try, g.linewidth; catch, g.linewidth = 2; end; try, g.naccu; catch, g.naccu = 200; end; try, g.angleunit; catch, g.angleunit = DEFAULT_ANGLEUNIT; end; try, g.cmax; catch, g.cmax = 0; end; % 0=use data limits try, g.type; catch, g.type = 'phasecoher'; end; try, g.boottype; catch, g.boottype = 'times'; end; try, g.subitc; catch, g.subitc = 'off'; end; try, g.memory; catch, g.memory = 'high'; end; try, g.compute; catch, g.compute = 'matlab'; end; try, g.maxamp; catch, g.maxamp = []; end; try, g.savecoher; catch, g.savecoher = 0; end; try, g.noinput; catch, g.noinput = 'no'; end; try, g.chaninfo; catch, g.chaninfo = []; end; allfields = fieldnames(g); for index = 1:length(allfields) switch allfields{index} case { 'shuffle' 'title' 'winsize' 'pad' 'timesout' 'padratio' 'maxfreq' 'topovec' 'elocs' 'alpha' ... 'marktimes' 'vert' 'powbase' 'rboot' 'plotamp' 'plotphase' 'plotbootsub' 'detrep' 'detret' ... 'baseline' 'baseboot' 'linewidth' 'naccu' 'angleunit' 'cmax' 'type' 'boottype' 'subitc' ... 'memory' 'compute' 'maxamp' 'savecoher' 'noinput' 'chaninfo' }; case {'plotersp' 'plotitc' }, disp(['crossf warning: timef option ''' allfields{index} ''' ignored']); otherwise disp(['crossf error: unrecognized option ''' allfields{index} '''']); beep; return; end; end; g.tlimits = tlimits; g.frame = frame; g.srate = Fs; g.cycles = varwin(1); if length(varwin)>1 g.cyclesfact = varwin(2); else g.cyclesfact = 1; end; g.type = lower(g.type); g.boottype = lower(g.boottype); g.detrep = lower(g.detrep); g.detret = lower(g.detret); g.plotphase = lower(g.plotphase); g.plotbootsub = lower(g.plotbootsub); g.subitc = lower(g.subitc); g.plotamp = lower(g.plotamp); g.shuffle = lower(g.shuffle); g.compute = lower(g.compute); g.AXES_FONT = 10; g.TITLE_FONT = 14; % testing arguments consistency % ----------------------------- if (~ischar(g.title)) error('Title must be a string.'); end if (~isnumeric(g.winsize) | length(g.winsize)~=1 | g.winsize~=round(g.winsize)) error('Value of winsize must be an integer number.'); elseif (g.winsize <= 0) error('Value of winsize must be positive.'); elseif (g.cycles == 0 & pow2(nextpow2(g.winsize)) ~= g.winsize) error('Value of winsize must be an integer power of two [1,2,4,8,16,...]'); elseif (g.winsize > g.frame) error('Value of winsize must be less than frame length.'); end if (~isnumeric(g.timesout) | length(g.timesout)~=1 | g.timesout~=round(g.timesout)) error('Value of timesout must be an integer number.'); elseif (g.timesout <= 0) error('Value of timesout must be positive.'); end if (g.timesout > g.frame-g.winsize) g.timesout = g.frame-g.winsize; disp(['Value of timesout must be <= frame-winsize, timeout adjusted to ' int2str(g.timesout) ]); end if (~isnumeric(g.padratio) | length(g.padratio)~=1 | g.padratio~=round(g.padratio)) error('Value of padratio must be an integer.'); elseif (g.padratio <= 0) error('Value of padratio must be positive.'); elseif (pow2(nextpow2(g.padratio)) ~= g.padratio) error('Value of padratio must be an integer power of two [1,2,4,8,16,...]'); end if (~isnumeric(g.maxfreq) | length(g.maxfreq)~=1) error('Value of g.maxfreq must be a number.'); elseif (g.maxfreq <= 0) error('Value of g.maxfreq must be positive.'); elseif (g.maxfreq > Fs/2) fprintf('Warning: input value of g.maxfreq larger that Nyquist frequency %3.4 Hz\n\n',Fs/2); end if isempty(g.topovec) g.topovec = []; elseif min(size(g.topovec))==1 g.topovec = g.topovec(:); if size(g.topovec,1)~=2 error('topovec must be a row or column vector.'); end end; if isempty(g.elocs) g.elocs = ''; elseif (~ischar(g.elocs)) & ~isstruct(g.elocs) error('Channel location file must be a valid text file.'); end if (~isnumeric(g.alpha) | length(g.alpha)~=1) error('timef(): Value of g.alpha must be a number.\n'); elseif (round(g.naccu*g.alpha) < 2) fprintf('Value of g.alpha is out of the normal range [%g,0.5]\n',2/g.naccu); g.naccu = round(2/g.alpha); fprintf(' Increasing the number of bootstrap iterations to %d\n',g.naccu); end if g.alpha>0.5 | g.alpha<=0 error('Value of g.alpha is out of the allowed range (0.00,0.5).'); end if ~isnan(g.alpha) if g.baseboot > 0 fprintf('Bootstrap analysis will use data in baseline (pre-0) subwindows only.\n') else fprintf('Bootstrap analysis will use data in all subwindows.\n') end end switch g.angleunit case { 'rad', 'ms', 'deg' },; otherwise error('Angleunit must be either ''rad'', ''deg'', or ''ms'''); end; switch g.type case { 'coher', 'phasecoher' 'phasecoher2' },; otherwise error('Type must be either ''coher'' or ''phasecoher'''); end; switch g.boottype case { 'times' 'timestrials' 'trials'},; otherwise error('Boot type must be either ''times'', ''trials'' or ''timestrials'''); end; if (~isnumeric(g.shuffle)) error('Shuffle argument type must be numeric'); end; switch g.memory case { 'low', 'high' },; otherwise error('memory must be either ''low'' or ''high'''); end; if strcmp(g.memory, 'low') & ~strcmp(g.boottype, 'times') error(['Bootstrap type ''' g.boottype ''' cannot be used in low memory mode']); end; switch g.compute case { 'matlab', 'c' },; otherwise error('compute must be either ''matlab'' or ''c'''); end; %%%%%%%%%%%%%%%%%%%%%%%%%%% % Compare 2 conditions %%%%%%%%%%%%%%%%%%%%%%%%%%% if iscell(X) if length(X) ~= 2 | length(Y) ~= 2 error('crossf: to compare conditions, X and Y input must be 2-elements cell arrays'); end; if ~strcmp(g.boottype, 'times') disp('crossf warning: The significance bootstrap type is irrelevant when comparing conditions'); end; for index = 1:2:length(vararginori) if index<=length(vararginori) % needed: if elemenets are deleted %if strcmp(vararginori{index}, 'alpha'), vararginori(index:index+1) = []; if strcmp(vararginori{index}, 'title'), vararginori(index:index+1) = []; end; end; end; if iscell(g.title) if length(g.title) <= 2, g.title{3} = 'Condition 2 - condition 1'; end; else g.title = { 'Condition 1', 'Condition 2', 'Condition 2 - condition 1' }; end; fprintf('Running crossf on condition 1 *********************\n'); fprintf('Note: If an out-of-memory error occurs, try reducing the\n'); fprintf(' number of time points or number of frequencies\n'); if ~strcmp(g.type, 'coher') fprintf('Note: Type ''coher'' takes 3 times as much memory as other options!)\n'); end figure; subplot(1,3,1); title(g.title{1}); if ~strcmp(g.type, 'coher') [R1,mbase,times,freqs,Rbootout1,Rangle1, savecoher1] = crossf(X{1}, Y{1}, ... frame, tlimits, Fs, varwin, 'savecoher', 1, 'title', ' ',vararginori{:}); else [R1,mbase,times,freqs,Rbootout1,Rangle1, savecoher1, Tfx1, Tfy1] = crossf(X{1}, Y{1}, ... frame, tlimits, Fs, varwin, 'savecoher', 1,'title', ' ',vararginori{:}); end; R1 = R1.*exp(j*Rangle1); % output Rangle is in radians % Asking user for memory limitations % if ~strcmp(g.noinput, 'yes') % tmp = whos('Tfx1'); % fprintf('This function will require an additional %d bytes, do you wish\n', ... % tmp.bytes*6+size(savecoher1,1)*size(savecoher1,2)*g.naccu*8); % res = input('to continue (y/n) (use the ''noinput'' option to disable this message):', 's'); % if res == 'n', return; end; % end; fprintf('\nRunning crossf on condition 2 *********************\n'); subplot(1,3,2); title(g.title{2}); if ~strcmp(g.type, 'coher') [R2,mbase,times,freqs,Rbootout2,Rangle2, savecoher2] = crossf(X{2}, Y{2}, ... frame, tlimits, Fs, varwin,'savecoher', 1, 'title', ' ',vararginori{:}); else [R2,mbase,times,freqs,Rbootout2,Rangle2, savecoher2, Tfx2, Tfy2] = crossf(X{2}, Y{2}, ... frame, tlimits, Fs, varwin,'savecoher', 1, 'title', ' ',vararginori{:}); end; R2 = R2.*exp(j*Rangle2); % output Rangle is in radians subplot(1,3,3); title(g.title{3}); if isnan(g.alpha) plotall(R2-R1, [], [], times, freqs, mbase, find(freqs <= g.maxfreq), g); else % accumulate coherence images (all arrays [nb_points * timesout * trials]) % --------------------------- allsavedcoher = zeros(size(savecoher1,1), ... size(savecoher1,2), ... size(savecoher1,3)+size(savecoher2,3)); allsavedcoher(:,:,1:size(savecoher1,3)) = savecoher1; allsavedcoher(:,:,size(savecoher1,3)+1:end) = savecoher2; clear savecoher1 savecoher2; if strcmp(g.type, 'coher') alltfx = zeros(size(Tfx1,1), size(Tfx2,2), size(Tfx1,3)+size(Tfx2,3)); alltfx(:,:,1:size(Tfx1,3)) = Tfx1; alltfx(:,:,size(Tfx1,3)+1:end) = Tfx2; clear Tfx1 Tfx2; alltfy = zeros(size(Tfy1,1), size(Tfy2,2), size(Tfy1,3)+size(Tfy2,3)); alltfy(:,:,1:size(Tfy1,3)) = Tfy1; alltfy(:,:,size(Tfy1,3)+1:end) = Tfy2; clear Tfy1 Tfy2; end; coherimages = zeros(size(allsavedcoher,1), size(allsavedcoher,2), g.naccu); cond1trials = length(X{1})/g.frame; cond2trials = length(X{2})/g.frame; alltrials = [1:cond1trials+cond2trials]; fprintf('Accumulating bootstrap:'); % preprocess data % --------------- switch g.type case 'coher', % take the square of alltfx and alltfy alltfx = alltfx.^2; alltfy = alltfy.^2; case 'phasecoher', % normalize allsavedcoher = allsavedcoher ./ abs(allsavedcoher); case 'phasecoher2', % don't do anything end; if strcmp(g.type, 'coher') [coherdiff coher1 coher2] = coher2conddiff( allsavedcoher, alltrials, ... cond1trials, g.type, alltfx, alltfy); else [coherdiff coher1 coher2] = coher2conddiff( allsavedcoher, alltrials, ... cond1trials, g.type); end; %figure; g.alpha = NaN; & to check that the new images are the same as the original %subplot(1,3,1); plotall(coher1, [], [], times, freqs, mbase, find(freqs <= g.maxfreq), g); %subplot(1,3,2); plotall(coher2, [], [], times, freqs, mbase, find(freqs <= g.maxfreq), g); %return; for index=1:g.naccu if rem(index,10) == 0, fprintf(' %d',index); end if rem(index,120) == 0, fprintf('\n'); end if strcmp(g.type, 'coher') coherimages(:,:,index) = coher2conddiff( allsavedcoher, shuffle(alltrials), ... cond1trials, g.type, alltfx, alltfy); else coherimages(:,:,index) = coher2conddiff( allsavedcoher, shuffle(alltrials), ... cond1trials, g.type); end; end; fprintf('\n'); % create articially a Bootstrap object to compute significance Boot = bootinit( [], size(allsavedcoher,1), g.timesout, g.naccu, 0, g.baseboot, ... 'noboottype', g.alpha, g.rboot); Boot.Coherboot.R = coherimages; Boot = bootcomppost(Boot, [], [], []); g.title = ''; plotall(coherdiff, Boot.Coherboot.R, Boot.Rsignif, times, freqs, mbase, ... find(freqs <= g.maxfreq), g); end; return; % ********************************** END PROCESSING TWO CONDITIONS end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % shuffle trials if necessary %%%%%%%%%%%%%%%%%%%%%%%%%%%%% if g.shuffle ~= 0 fprintf('x and y data trials being shuffled %d times\n',g.shuffle); XX = reshape(X, 1, frame, length(X)/g.frame); YY = Y; X = []; Y = []; for index = 1:g.shuffle XX = shuffle(XX,3); X = [X XX(:,:)]; Y = [Y YY]; end; end; % detrend over epochs (trials) if requested % ----------------------------------------- switch g.detrep case 'on' X = reshape(X, g.frame, length(X)/g.frame); X = X - mean(X,2)*ones(1, length(X(:))/g.frame); Y = reshape(Y, g.frame, length(Y)/g.frame); Y = Y - mean(Y,2)*ones(1, length(Y(:))/g.frame); end; % time limits wintime = 500*g.winsize/g.srate; times = [g.tlimits(1)+wintime:(g.tlimits(2)-g.tlimits(1)-2*wintime)/(g.timesout-1):g.tlimits(2)-wintime]; %%%%%%%%%% % baseline %%%%%%%%%% if ~isnan(g.baseline) baseln = find(times < g.baseline); % subtract means of pre-0 (centered) windows if isempty(baseln) baseln = 1:length(times); % use all times as baseline disp('Bootstrap baseline empty, using the whole epoch.'); end; baselength = length(baseln); else baseln = 1:length(times); % use all times as baseline baselength = length(times); % used for bootstrap end; %%%%%%%%%%%%%%%%%%%% % Initialize objects %%%%%%%%%%%%%%%%%%%% tmpsaveall = (~isnan(g.alpha) & isnan(g.rboot) & strcmp(g.memory, 'high')) ... | (strcmp(g.subitc, 'on') & strcmp(g.memory, 'high')); trials = length(X)/g.frame; if ~strcmp(g.compute, 'c') Tfx = tfinit(X, g.timesout, g.winsize, g.cycles, g.frame, g.padratio, g.detret, ... g.srate, g.maxfreq, g.subitc, g.type, g.cyclesfact, tmpsaveall); Tfy = tfinit(Y, g.timesout, g.winsize, g.cycles, g.frame, g.padratio, g.detret, ... g.srate, g.maxfreq, g.subitc, g.type, g.cyclesfact, tmpsaveall); Coher = coherinit(Tfx.nb_points, trials, g.timesout, g.type); Coherboot = coherinit(Tfx.nb_points, trials, g.naccu , g.type); Boot = bootinit( Coherboot, Tfx.nb_points, g.timesout, g.naccu, baselength, ... g.baseboot, g.boottype, g.alpha, g.rboot); freqs = Tfx.freqs; dispf = find(freqs <= g.maxfreq); freqs = freqs(dispf); else freqs = g.srate*g.cycles/g.winsize*[2:2/g.padratio:g.winsize]/2; end; dispf = find(Tfx.freqs <= g.maxfreq); %------------- % Reserve space %------------- % R = zeros(tfx.nb_points,g.timesout); % mean coherence % RR = repmat(nan,tfx.nb_points,g.timesout); % initialize with nans % Rboot = zeros(tfx.nb_points,g.naccu); % summed bootstrap coher % switch g.type % case 'coher', % cumulXY = zeros(tfx.nb_points,g.timesout); % cumulXYboot = zeros(tfx.nb_points,g.naccu); % end; % if g.bootsub > 0 % Rboottrial = zeros(tfx.nb_points, g.timesout, g.bootsub); % summed bootstrap coher % cumulXYboottrial = zeros(tfx.nb_points, g.timesout, g.bootsub); % end; % if ~isnan(g.alpha) & isnan(g.rboot) % tf.tmpalltimes = repmat(nan,tfx.nb_points,g.timesout); % end % -------------------- % Display text to user % -------------------- fprintf('\nComputing Event-Related '); switch g.type case 'phasecoher', fprintf('Phase Coherence (ITC) images for %d trials.\n',length(X)/g.frame); case 'phasecoher2', fprintf('Phase Coherence 2 (ITC) images for %d trials.\n',length(X)/g.frame); case 'coher', fprintf('Linear Coherence (ITC) images for %d trials.\n',length(X)/g.frame); end; fprintf('The trial latency range is from %4.5g ms before to %4.5g ms after\n the time-locking event.\n', g.tlimits(1),g.tlimits(2)); fprintf('The frequency range displayed will be %g-%g Hz.\n',min(freqs),g.maxfreq); if ~isnan(g.baseline) if length(baseln) == length(times) fprintf('Using the full trial latency range as baseline.\n'); else fprintf('Using trial latencies from %4.5g ms to %4.5g ms as baseline.\n', g.tlimits,g.baseline); end; else fprintf('No baseline time range was specified.\n'); end; if g.cycles==0 fprintf('The data window size will be %d samples (%g ms).\n',g.winsize,2*wintime); fprintf('The FFT length will be %d samples\n',g.winsize*g.padratio); else fprintf('The window size will be %2.3g cycles.\n',g.cycles); fprintf('The maximum window size will be %d samples (%g ms).\n',g.winsize,2*wintime); end fprintf('The window will be applied %d times\n',g.timesout); fprintf(' with an average step size of %2.2g samples (%2.4g ms).\n', Tfx.stp,1000*Tfx.stp/g.srate); fprintf('Results will be oversampled %d times.\n',g.padratio); if ~isnan(g.alpha) fprintf('Bootstrap confidence limits will be computed based on alpha = %g\n', g.alpha); else fprintf('Bootstrap confidence limits will NOT be computed.\n'); end switch g.plotphase case 'on', if strcmp(g.angleunit,'deg') fprintf(['Coherence angles will be imaged in degrees.\n']); elseif strcmp(g.angleunit,'rad') fprintf(['Coherence angles will be imaged in radians.\n']); elseif strcmp(g.angleunit,'ms') fprintf(['Coherence angles will be imaged in ms.\n']); end end; fprintf('\nProcessing trial (of %d): ',trials); % firstboot = 1; % Rn=zeros(trials,g.timesout); % X = X(:)'; % make X and Y column vectors % Y = Y(:)'; % tfy = tfx; if strcmp(g.compute, 'c') % C PART filename = [ 'tmpcrossf' num2str(round(rand(1)*1000)) ]; f = fopen([ filename '.in'], 'w'); fwrite(f, tmpsaveall, 'int32'); fwrite(f, g.detret, 'int32'); fwrite(f, g.srate, 'int32'); fwrite(f, g.maxfreq, 'int32'); fwrite(f, g.padratio, 'int32'); fwrite(f, g.cycles, 'int32'); fwrite(f, g.winsize, 'int32'); fwrite(f, g.timesout, 'int32'); fwrite(f, g.subitc, 'int32'); fwrite(f, g.type, 'int32'); fwrite(f, trials, 'int32'); fwrite(f, g.naccu, 'int32'); fwrite(f, length(X), 'int32'); fwrite(f, X, 'double'); fwrite(f, Y, 'double'); fclose(f); command = [ '!cppcrosff ' filename '.in ' filename '.out' ]; eval(command); f = fopen([ filename '.out'], 'r'); size1 = fread(f, 'int32', 1); size2 = fread(f, 'int32', 1); Rreal = fread(f, 'double', [size1 size2]); Rimg = fread(f, 'double', [size1 size2]); Coher.R = Rreal + j*Rimg; Boot.Coherboot.R = []; Boot.Rsignif = []; else % ------------------------ % MATLAB PART % compute ITC if necessary % ------------------------ if strcmp(g.subitc, 'on') for t=1:trials if rem(t,10) == 0, fprintf(' %d',t); end if rem(t,120) == 0, fprintf('\n'); end Tfx = tfitc( Tfx, t, 1:g.timesout); Tfy = tfitc( Tfy, t, 1:g.timesout); end; fprintf('\n'); Tfx = tfitcpost( Tfx, trials); Tfy = tfitcpost( Tfy, trials); end; % --------- % Main loop % --------- if g.savecoher, trialcoher = zeros(Tfx.nb_points, g.timesout, trials); else trialcoher = []; end; for t=1:trials if rem(t,10) == 0, fprintf(' %d',t); end if rem(t,120) == 0, fprintf('\n'); end Tfx = tfcomp( Tfx, t, 1:g.timesout); Tfy = tfcomp( Tfy, t, 1:g.timesout); if g.savecoher [Coher trialcoher(:,:,t)] = cohercomp( Coher, Tfx.tmpalltimes, ... Tfy.tmpalltimes, t, 1:g.timesout); else Coher = cohercomp( Coher, Tfx.tmpalltimes, Tfy.tmpalltimes, t, 1:g.timesout); end; Boot = bootcomp( Boot, Coher.Rn(t,:), Tfx.tmpalltimes, Tfy.tmpalltimes); end % t = trial [Boot Rbootout] = bootcomppost(Boot, Coher.Rn, Tfx.tmpall, Tfy.tmpall); % Note that the bootstrap thresholding is actually performed % in the display subfunction plotall() Coher = cohercomppost(Coher, trials); end; % ---------------------------------- % If coherence, perform the division % ---------------------------------- % switch g.type % case 'coher', % R = R ./ cumulXY; % if ~isnan(g.alpha) & isnan(g.rboot) % Rboot = Rboot ./ cumulXYboot; % end; % if g.bootsub > 0 % Rboottrial = Rboottrial ./ cumulXYboottrial; % end; % case 'phasecoher', % Rn = sum(Rn, 1); % R = R ./ (ones(size(R,1),1)*Rn); % coherence magnitude % if ~isnan(g.alpha) & isnan(g.rboot) % Rboot = Rboot / trials; % end; % if g.bootsub > 0 % Rboottrial = Rboottrial / trials; % end; % end; % ---------------- % Compute baseline % ---------------- mbase = mean(abs(Coher.R(:,baseln)')); % mean baseline coherence magnitude % --------------- % Plot everything % --------------- plotall(Coher.R, Boot.Coherboot.R, Boot.Rsignif, times, freqs, mbase, dispf, g); % -------------------------------------- % Convert output Rangle to degrees or ms - Disabled to keep original default: radians output % -------------------------------------- % Rangle = angle(Coher.R); % returns radians % if strcmp(g.angleunit,'ms') % convert to ms % Rangle = (Rangle/(2*pi)).*repmat(1000./freqs(dispf)',1,length(times)); % elseif strcmp(g.angleunit,'deg') % convert to deg % Rangle = Rangle*180/pi; % convert to degrees % else % angleunit is 'rad' % % Rangle = Rangle; % end % Rangle(find(Rraw==0)) = 0; % mask for significance - set angle at non-signif coher points to 0 R = abs(Coher.R); Rsignif = Boot.Rsignif; Tfx = permute(Tfx.tmpall, [3 2 1]); % from [trials timesout nb_points] % to [nb_points timesout trials] Tfy = permute(Tfy.tmpall, [3 2 1]); return; % end crossf() ************************************************* % % crossf() plotting functions % ---------------------------------------------------------------------- function plotall(R, Rboot, Rsignif, times, freqs, mbase, dispf, g) switch lower(g.plotphase) case 'on', switch lower(g.plotamp), case 'on', ordinate1 = 0.67; ordinate2 = 0.1; height = 0.33; g.plot = 1; case 'off', ordinate2 = 0.1; height = 0.9; g.plot = 1; end; case 'off', ordinate1 = 0.1; height = 0.9; switch lower(g.plotamp), case 'on', ordinate1 = 0.1; height = 0.9; g.plot = 1; case 'off', g.plot = 0; end; end; % % Compute cross-spectral angles % ----------------------------- Rangle = angle(R); % returns radians % % Optionally convert Rangle to degrees or ms % ------------------------------------------ if strcmp(g.angleunit,'ms') % convert to ms Rangle = (Rangle/(2*pi)).*repmat(1000./freqs(dispf)',1,length(times)); maxangle = max(max(abs(Rangle))); elseif strcmp(g.angleunit,'deg') % convert to degrees Rangle = Rangle*180/pi; % convert to degrees maxangle = 180; % use full-cycle plotting else maxangle = pi; % radians end R = abs(R); % if ~isnan(g.baseline) % R = R - repmat(mbase',[1 g.timesout]); % remove baseline mean % end; Rraw = R; % raw coherence (e.g., coherency) magnitude values output if g.plot fprintf('\nNow plotting...\n'); set(gcf,'DefaultAxesFontSize',g.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') end; switch lower(g.plotamp) case 'on' % % Image the coherence [% perturbations] % RR = R; if ~isnan(g.alpha) % zero out (and 'green out') nonsignif. R values RR(find(RR < repmat(Rboot(:),[1 g.timesout]))) = 0; Rraw(find(repmat(Rsignif(:),[1,size(Rraw,2)])>=Rraw))=0; end if g.cmax == 0 coh_caxis = max(max(R(dispf,:)))*[-1 1]; else coh_caxis = g.cmax*[-1 1]; end h(6) = axes('Units','Normalized', 'Position',[.1 ordinate1 .8 height].*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 if ~isempty(g.maxamp) caxis([-g.maxamp g.maxamp]); end; tmpscale = caxis; hold on plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth) for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); end; hold off set(h(6),'YTickLabel',[],'YTick',[]) set(h(6),'XTickLabel',[],'XTick',[]) %title('Event-Related Coherence') h(8) = axes('Position',[.95 ordinate1 .05 height].*s+q); cbar(h(8),151:300, [0 tmpscale(2)]); % use only positive colors (gyorv) % % Plot delta-mean min and max coherence at each time point on bottom of image % h(10) = axes('Units','Normalized','Position',[.1 ordinate1-0.1 .8 .1].*s+q); % plot marginal means below Emax = max(R(dispf,:)); % mean coherence at each time point Emin = min(R(dispf,:)); % mean coherence at each time point plot(times,Emin, times, Emax, 'LineWidth',g.linewidth); hold on; plot([times(1) times(length(times))],[0 0],'LineWidth',0.7); plot([0 0],[-500 500],'--m','LineWidth',g.linewidth); for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[-500 500],'--m','LineWidth',g.linewidth); end; if ~isnan(g.alpha) & strcmp(g.boottype, 'trials') % plot bootstrap significance limits (base mean +/-) plot(times,mean(Rboot(dispf,:)),'g','LineWidth',g.linewidth); hold on; plot(times,mean(Rsignif(dispf,:)),'k:','LineWidth',g.linewidth); axis([min(times) max(times) 0 max([Emax(:)' Rsignif(:)'])*1.2]) else axis([min(times) max(times) 0 max(Emax)*1.2]) end; tick = get(h(10),'YTick'); set(h(10),'YTick',[tick(1) ; tick(length(tick))]) set(h(10),'YAxisLocation','right') xlabel('Time (ms)') ylabel('coh.') % % Plot mean baseline coherence at each freq on left side of image % h(11) = axes('Units','Normalized','Position',[0 ordinate1 .1 height].*s+q); % plot mean spectrum E = abs(mbase(dispf)); % baseline mean coherence at each frequency plot(freqs(dispf),E,'LineWidth',g.linewidth); % plot mbase if ~isnan(g.alpha) % plot bootstrap significance limits (base mean +/-) hold on % plot(freqs(dispf),Rboot(:,dispf)+[E;E],'g','LineWidth',g.linewidth); plot(freqs(dispf),mean(Rboot (dispf,:),2),'g','LineWidth',g.linewidth); plot(freqs(dispf),mean(Rsignif(dispf,:),2),'k:','LineWidth',g.linewidth); axis([freqs(1) freqs(max(dispf)) 0 max([E Rsignif(:)'])*1.2]); else % plot marginal mean coherence only 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.') end; switch lower(g.plotphase) case 'on' % % Plot coherence phase lags in bottom panel % h(13) = axes('Units','Normalized','Position',[.1 ordinate2 .8 height].*s+q); Rangle(find(Rraw==0)) = 0; % when plotting, mask for significance % = 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',g.linewidth); % zero-time line for i=1:length(g.marktimes) plot([g.marktimes(i) g.marktimes(i)],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); end; ylabel('Freq. (Hz)') xlabel('Time (ms)') h(14)=axes('Position',[.95 ordinate2 .05 height].*s+q); cbar(h(14),0,[-maxangle maxangle]); % two-sided colorbar end if g.plot try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) % plot title if h(6) ~= 0, axes(h(6)); else axes(h(13)); end; %h = subplot('Position',[0 0 1 1].*s+q, 'Visible','Off'); %h(13) = text(-.05,1.01,g.title); h(13) = title(g.title); %set(h(13),'VerticalAlignment','bottom') %set(h(13),'HorizontalAlignment','left') set(h(13),'FontSize',g.TITLE_FONT); end % %%%%%%%%%%%%%%% plot topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) h(15) = subplot('Position',[-.1 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(1),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec(1,:),g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') h(16) = subplot('Position',[.9 .43 .2 .14].*s+q); if size(g.topovec,2) <= 2 topoplot(g.topovec(2),g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec(2,:),g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') end axcopy(gcf); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TIME FREQUENCY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function for time freq initialisation % ------------------------------------- function Tf = tfinit(X, timesout, winsize, ... cycles, frame, padratio, detret, srate, maxfreq, subitc, type, cyclesfact, saveall); Tf.X = X(:)'; % make X column vectors Tf.winsize = winsize; Tf.cycles = cycles; Tf.frame = frame; Tf.padratio = padratio; Tf.detret = detret; Tf.stp = (frame-winsize)/(timesout-1); Tf.subitc = subitc; % for ITC Tf.type = type; % for ITC Tf.saveall = saveall; if (Tf.cycles == 0) %%%%%%%%%%%%%% constant window-length FFTs %%%%%%%%%%%%%%%% % Tf.freqs = srate/winsize*[1:2/padratio:winsize]/2; % incorect for padratio > 2 Tf.freqs = linspace(0, srate/2, length([1:2/padratio:winsize])+1); Tf.freqs = Tf.freqs(2:end); Tf.win = hanning(winsize); Tf.nb_points = padratio*winsize/2; else % %%%%%%%%%%%%%%%%%% Constant-Q (wavelet) DFTs %%%%%%%%%%%%%%%%%%%%%%%%%%%% Tf.freqs = srate*cycles/winsize*[2:2/padratio:winsize]/2; Tf.win = dftfilt(winsize,maxfreq/srate,cycles,padratio,cyclesfact); Tf.nb_points = size(Tf.win,2); end; Tf.tmpalltimes = zeros(Tf.nb_points, timesout); trials = length(X)/frame; if saveall Tf.tmpall = repmat(nan,[trials timesout Tf.nb_points]); else Tf.tmpall = []; end Tf.tmpallbool = zeros(trials,timesout); Tf.ITCdone = 0; if Tf.subitc Tf.ITC = zeros(Tf.nb_points, timesout); switch Tf.type, case { 'coher' 'phasecoher2' } Tf.ITCcumul = zeros(Tf.nb_points, timesout); end; end; % function for itc % ---------------- function [Tf, itcvals] = tfitc(Tf, trials, times); Tf = tfcomp(Tf, trials, times); switch Tf.type case 'coher', Tf.ITC(:,times) = Tf.ITC(:,times) + Tf.tmpalltimes; % complex coher. Tf.ITCcumul(:,times) = Tf.ITCcumul(:,times)+abs(Tf.tmpalltimes).^2; case 'phasecoher2', Tf.ITC(:,times) = Tf.ITC(:,times) + Tf.tmpalltimes; % complex coher. Tf.ITCcumul(:,times) = Tf.ITCcumul(:,times)+abs(Tf.tmpalltimes); case 'phasecoher', Tf.ITC(:,times) = Tf.ITC(:,times) + Tf.tmpalltimes ./ abs(Tf.tmpalltimes); % complex coher. end % ~any(isnan()) return; function [Tf, itcvals] = tfitcpost(Tf, trials); switch Tf.type case 'coher', Tf.ITC = Tf.ITC ./ sqrt(trials * Tf.ITCcumul); case 'phasecoher2', Tf.ITC = Tf.ITC ./ Tf.ITCcumul; case 'phasecoher', Tf.ITC = Tf.ITC / trials; % complex coher. end % ~any(isnan()) if Tf.saveall Tf.ITC = transpose(Tf.ITC); % do not use ' otherwise conjugate %imagesc(abs(Tf.ITC)); colorbar; figure; %squeeze(Tf.tmpall(1,1,1:Tf.nb_points)) %squeeze(Tf.ITC (1,1,1:Tf.nb_points)) %Tf.ITC = shiftdim(Tf.ITC, -1); Tf.ITC = repmat(shiftdim(Tf.ITC, -1), [trials 1 1]); Tf.tmpall = (Tf.tmpall - abs(Tf.tmpall) .* Tf.ITC) ./ abs(Tf.tmpall); % for index = 1:trials % imagesc(squeeze(abs(Tf.tmpall(index,:,:)))); drawnow; figure; % Tf.tmpall(index,:,:) = (Tf.tmpall(index,:,:) - Tf.tmpall(index,:,:) .* Tf.ITC)./Tf.tmpall(index,:,:); % imagesc(squeeze(abs(Tf.tmpall(index,:,:)))); drawnow; % subplot(10,10, index); imagesc(squeeze(abs(Tf.tmpall(index,:,:)))); caxis([0 1]); drawnow; % end; % squeeze(Tf.tmpall(1,1,1:Tf.nb_points)) % figure; axcopy; end; Tf.ITCdone = 1; return; % function for time freq decomposition % ------------------------------------ function [Tf, tmpX] = tfcomp(Tf, trials, times); % tf is an structure containing all the information about the decomposition for trial = trials for index = times if ~Tf.tmpallbool(trial, index) % already computed tmpX = Tf.X([1:Tf.winsize]+floor((index-1)*Tf.stp)+(trial-1)*Tf.frame); if ~any(isnan(tmpX)) % perform the decomposition tmpX = tmpX - mean(tmpX); switch Tf.detret, case 'on', tmpX = detrend(tmpX); end; if Tf.cycles == 0 % use FFTs tmpX = Tf.win .* tmpX(:); tmpX = fft(tmpX,Tf.padratio*Tf.winsize); tmpX = tmpX(2:Tf.padratio*Tf.winsize/2+1); else tmpX = transpose(Tf.win) * tmpX(:); end else tmpX = NaN; end; if Tf.ITCdone tmpX = (tmpX - abs(tmpX) .* Tf.ITC(:,index)) ./ abs(tmpX); end; Tf.tmpalltimes(:,index) = tmpX; if Tf.saveall Tf.tmpall(trial, index,:) = tmpX; Tf.tmpallbool(trial, index) = 1; end else Tf.tmpalltimes(:,index) = Tf.tmpall(trial, index,:); end; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COHERENCE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function for coherence initialisation % ------------------------------------- function Coher = coherinit(nb_points, trials, timesout, type); Coher.R = zeros(nb_points,timesout); % mean coherence % Coher.RR = repmat(nan,nb_points,timesout); % initialize with nans Coher.type = type; Coher.Rn=zeros(trials,timesout); switch type case 'coher', Coher.cumulX = zeros(nb_points,timesout); Coher.cumulY = zeros(nb_points,timesout); case 'phasecoher2', Coher.cumul = zeros(nb_points,timesout); end; % function for coherence calculation % ------------------------------------- % function Coher = cohercomparray(Coher, tmpX, tmpY, trial); % switch Coher.type % case 'coher', % Coher.R = Coher.R + tmpX.*conj(tmpY); % complex coher. % Coher.cumulXY = Coher.cumulXY + abs(tmpX).*abs(tmpY); % case 'phasecoher', % Coher.R = Coher.R + tmpX.*conj(tmpY) ./ (abs(tmpX).*abs(tmpY)); % complex coher. % Coher.Rn(trial,:) = 1; % end % ~any(isnan()) function [Coher,tmptrialcoh] = cohercomp(Coher, tmpX, tmpY, trial, time); tmptrialcoh = tmpX.*conj(tmpY); switch Coher.type case 'coher', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh; % complex coher. Coher.cumulX(:,time) = Coher.cumulX(:,time) + abs(tmpX).^2; Coher.cumulY(:,time) = Coher.cumulY(:,time) + abs(tmpY).^2; case 'phasecoher2', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh; % complex coher. Coher.cumul(:,time) = Coher.cumul(:,time) + abs(tmptrialcoh); case 'phasecoher', Coher.R(:,time) = Coher.R(:,time) + tmptrialcoh ./ abs(tmptrialcoh); % complex coher. %figure; imagesc(abs(tmpX.*conj(tmpY) ./ (abs(tmpX).*abs(tmpY)))); Coher.Rn(trial,time) = Coher.Rn(trial,time)+1; end % ~any(isnan()) % function for post coherence calculation % --------------------------------------- function Coher = cohercomppost(Coher, trials); switch Coher.type case 'coher', Coher.R = Coher.R ./ sqrt(Coher.cumulX) ./ sqrt(Coher.cumulY); case 'phasecoher2', Coher.R = Coher.R ./ Coher.cumul; case 'phasecoher', Coher.Rn = sum(Coher.Rn, 1); Coher.R = Coher.R ./ (ones(size(Coher.R,1),1)*Coher.Rn); % coherence magnitude end; % function for 2 conditions coherence calculation % ----------------------------------------------- function [coherimage, coherimage1, coherimage2] = coher2conddiff( allsavedcoher, alltrials, cond1trials, type, tfx, tfy); t1s = alltrials(1:cond1trials); t2s = alltrials(cond1trials+1:end); switch type case 'coher', coherimage1 = sum(allsavedcoher(:,:,t1s),3) ./ sqrt(sum(tfx(:,:,t1s),3)) ./ sqrt(sum(tfy(:,:,t1s),3)); coherimage2 = sum(allsavedcoher(:,:,t2s),3) ./ sqrt(sum(tfx(:,:,t2s),3)) ./ sqrt(sum(tfy(:,:,t1s),3)); case 'phasecoher2', coherimage1 = sum(allsavedcoher(:,:,t1s),3) ./ sum(abs(allsavedcoher(:,:,t1s)),3); coherimage2 = sum(allsavedcoher(:,:,t2s),3) ./ sum(abs(allsavedcoher(:,:,t2s)),3); case 'phasecoher', coherimage1 = sum(allsavedcoher(:,:,t1s),3) / cond1trials; coherimage2 = sum(allsavedcoher(:,:,t2s),3) / (size(allsavedcoher,3)-cond1trials); end; coherimage = coherimage2 - coherimage1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BOOTSTRAP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function for bootstrap initialisation % ------------------------------------- function Boot = bootinit(Coherboot, nb_points, timesout, naccu, baselength, baseboot, boottype, alpha, rboot); Boot.Rboot = zeros(nb_points,naccu); % summed bootstrap coher Boot.boottype = boottype; Boot.baselength = baselength; Boot.baseboot = baseboot; Boot.Coherboot = Coherboot; Boot.naccu = naccu; Boot.alpha = alpha; Boot.rboot = rboot; % function for bootstrap computation % ---------------------------------- function Boot = bootcomp(Boot, Rn, tmpalltimesx, tmpalltimesy); if ~isnan(Boot.alpha) & isnan(Boot.rboot) if strcmp(Boot.boottype, 'times') % get g.naccu bootstrap estimates for each trial goodbasewins = find(Rn==1); if Boot.baseboot % use baseline windows only goodbasewins = find(goodbasewins<=Boot.baselength); end ngdbasewins = length(goodbasewins); j=1; tmpsX = zeros(size(tmpalltimesx,1), Boot.naccu); tmpsY = zeros(size(tmpalltimesx,1), Boot.naccu); if ngdbasewins > 1 while j<=Boot.naccu s = ceil(rand([1 2])*ngdbasewins); % random ints [1,g.timesout] s = goodbasewins(s); if ~any(isnan(tmpalltimesx(:,s(1)))) & ~any(isnan(tmpalltimesy(:,s(2)))) tmpsX(:,j) = tmpalltimesx(:,s(1)); tmpsY(:,j) = tmpalltimesy(:,s(2)); j = j+1; end end Boot.Coherboot = cohercomp(Boot.Coherboot, tmpsX, tmpsY, 1, 1:Boot.naccu); end; end end; % handle other trial bootstrap types % ---------------------------------- function [Boot, Rbootout] = bootcomppost(Boot, allRn, alltmpsX, alltmpsY); trials = size(alltmpsX, 1); times = size(alltmpsX, 2); nb_points = size(alltmpsX, 3); if ~isnan(Boot.alpha) & isnan(Boot.rboot) if strcmp(Boot.boottype, 'trials') % get g.naccu bootstrap estimates for each trial fprintf('\nProcessing trial bootstrap (of %d):',times(end)); tmpsX = zeros(size(alltmpsX,3), Boot.naccu); tmpsY = zeros(size(alltmpsY,3), Boot.naccu ); Boot.fullcoherboot = zeros(nb_points, Boot.naccu, times); for index=1:times if rem(index,10) == 0, fprintf(' %d',index); end if rem(index,120) == 0, fprintf('\n'); end for allt=1:trials j=1; while j<=Boot.naccu t = ceil(rand([1 2])*trials); % random ints [1,g.timesout] if (allRn(t(1),index) == 1) & (allRn(t(2),index) == 1) tmpsX(:,j) = squeeze(alltmpsX(t(1),index,:)); tmpsY(:,j) = squeeze(alltmpsY(t(2),index,:)); j = j+1; end end Boot.Coherboot = cohercomp(Boot.Coherboot, tmpsX, tmpsY, 1, 1:Boot.naccu); end; Boot.Coherboot = cohercomppost(Boot.Coherboot); % CHECK IF NECSSARY FOR ALL BOOT TYPE Boot.fullcoherboot(:,:,index) = Boot.Coherboot.R; Boot.Coherboot = coherinit(nb_points, trials, Boot.naccu, Boot.Coherboot.type); end; Boot.Coherboot.R = Boot.fullcoherboot; Boot = rmfield(Boot, 'fullcoherboot'); elseif strcmp(Boot.boottype, 'timestrials') % handle timestrials bootstrap fprintf('\nProcessing time and trial bootstrap (of %d):',trials); tmpsX = zeros(size(alltmpsX,3), Boot.naccu); tmpsY = zeros(size(alltmpsY,3), Boot.naccu ); for allt=1:trials if rem(allt,10) == 0, fprintf(' %d',allt); end if rem(allt,120) == 0, fprintf('\n'); end j=1; while j<=Boot.naccu t = ceil(rand([1 2])*trials); % random ints [1,g.timesout] goodbasewins = find((allRn(t(1),:) & allRn(t(2),:)) ==1); if Boot.baseboot % use baseline windows only goodbasewins = find(goodbasewins<=baselength); end ngdbasewins = length(goodbasewins); if ngdbasewins>1 s = ceil(rand([1 2])*ngdbasewins); % random ints [1,g.timesout] s=goodbasewins(s); if all(allRn(t(1),s(1)) == 1) & all(allRn(t(2),s(2)) == 1) tmpsX(:,j) = squeeze(alltmpsX(t(1),s(1),:)); tmpsY(:,j) = squeeze(alltmpsY(t(2),s(2),:)); j = j+1; end end end Boot.Coherboot = cohercomp(Boot.Coherboot, tmpsX, tmpsY, 1, 1:Boot.naccu); end Boot.Coherboot = cohercomppost(Boot.Coherboot); elseif strcmp(Boot.boottype, 'times') % boottype is 'times' Boot.Coherboot = cohercomppost(Boot.Coherboot); end; end; % test if precomputed if ~isnan(Boot.alpha) & isnan(Boot.rboot) % if bootstrap analysis included . . . % 'boottype'='times' or 'timestrials', size(R)=nb_points*naccu % 'boottype'='trials', size(R)=nb_points*naccu*times Boot.Coherboot.R = abs (Boot.Coherboot.R); Boot.Coherboot.R = sort(Boot.Coherboot.R,2); % compute bootstrap significance level i = round(Boot.naccu*Boot.alpha); Boot.Rsignif = mean(Boot.Coherboot.R(:,Boot.naccu-i+1:Boot.naccu),2); % significance levels for Rraw Boot.Coherboot.R = squeeze(mean(Boot.Coherboot.R(:,Boot.naccu-i+1:Boot.naccu),2)); if size(Boot.Coherboot.R, 2) == 1 Rbootout(:,2) = Boot.Coherboot.R; else Rbootout(:,:,2) = Boot.Coherboot.R; end; % BEFORE %Rboot = [mean(Rboot(1:i,:)) ; mean(Rboot(g.naccu-i+1:g.naccu,:))]; elseif ~isnan(Boot.rboot) Boot.Coherboot.R = Boot.rboot; Boot.Rsignif = Boot.rboot; Rbootout = Boot.rboot; else Boot.Coherboot.R = []; Boot.Rsignif = []; Rbootout = []; end % NOTE: above, mean ????? function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end
github
lcnbeapp/beapp-master
dftfilt2.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/dftfilt2.m
5,665
utf_8
fa2b4cd1d3a209b72ce506ee4e6fee46
% dftfilt2() - discrete complex wavelet filters % % Usage: % >> wavelet = dftfilt2( freqs, cycles, srate, cyclefact) % % Inputs: % freqs - frequency array % cycles - cycles array. If one value is given, all wavelets have % the same number of cycles. If two values are given, the % two values are used for the number of cycles at the lowest % frequency and at the highest frequency, with linear % interpolation between these values for intermediate % frequencies % srate - sampling rate (in Hz) % % cycleinc - ['linear'|'log'] increase mode if [min max] cycles is % provided in 'cycle' parameter. {default: 'linear'} % type - ['sinus'|'morlet'] wavelet type is a sinusoid with % cosine (real) and sine (imaginary) parts tapered by % a Hanning or Morlet function. 'morlet' is a typical Morlet % wavelet (with p=2*pi and sigma=0.7) best matching the % 'sinus' Hanning taper) {default: 'morlet'} % Output: % wavelet - cell array of wavelet filters % % Note: The length of the window is automatically computed from the % number of cycles and is always made odd. % % Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 3/28/2003 % Copyright (C) 3/28/2003 Arnaud Delorme 8, 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 wavelet = dftfilt2( freqs, cycles, srate, cycleinc, type); if nargin < 3 error('3 arguments required'); end; if nargin < 5 type = 'morlet'; end; % compute number of cycles at each frequency % ------------------------------------------ if length(cycles) == 1 cycles = cycles*ones(size(freqs)); elseif length(cycles) == 2 if nargin == 4 & strcmpi(cycleinc, 'log') % cycleinc cycles = linspace(log(cycles(1)), log(cycles(2)), length(freqs)); cycles = exp(cycles); else cycles = linspace(cycles(1), cycles(2), length(freqs)); end; end; % compute wavelet for index = 1:length(freqs) % number of cycles depend on window size % number of cycles automatically reduced if smaller window % note: as the number of cycle changes, the frequency shifts a little % this has to be fixed winlen = cycles(index)*srate/freqs(index); winlenint = floor(winlen); if mod(winlenint,2) == 1, winlenint = winlenint+1; end; winval = linspace(winlenint/2, -winlenint/2, winlenint+1); if strcmpi(type, 'sinus') % Hanning win = exp(2i*pi*freqs(index)*winval/srate); wavelet{index} = win .* hanning(length(winval))'; else % Morlet t = freqs(index)*winval/srate; p = 2*pi; s = cycles(index)/5; wavelet{index} = exp(j*t*p)/sqrt(2*pi) .* ... (exp(-t.^2/(2*s^2))-sqrt(2)*exp(-t.^2/(s^2)-p^2*s^2/4)); end; end; return; % testing % ------- wav1 = dftfilt2(5, 5, 256); wav1 = wav1{1}; abs1 = linspace(-floor(length(wav1)),floor(length(wav1)), length(wav1)); figure; plot(abs1, real(wav1), 'b'); wav2 = dftfilt2(5, 3, 256); wav2 = wav2{1}; abs2 = linspace(-floor(length(wav2)),floor(length(wav2)), length(wav2)); hold on; plot(abs2, real(wav2), 'r'); wav3 = dftfilt2(5, 1.4895990, 256); wav3 = wav3{1}; abs3 = linspace(-floor(length(wav3)),floor(length(wav3)), length(wav3)); hold on; plot(abs3, real(wav3), 'g'); wav4 = dftfilt2(5, 8.73, 256); wav4 = wav4{1}; abs4 = linspace(-floor(length(wav4)),floor(length(wav4)), length(wav4)); hold on; plot(abs4, real(wav4), 'm'); % more testing % ------------ freqs = exp(linspace(0,log(10),10)); win = dftfilt2(freqs, [3 3], 256, 'linear', 'sinus'); win = dftfilt2(freqs, [3 3], 256, 'linear', 'morlet'); freqs = [12.0008 13.2675 14.5341 15.8007 17.0674 18.3340 19.6007 20.8673 22.1339 23.4006 24.6672 25.9339 27.2005 28.4671 29.7338 31.0004 32.2670 33.5337 34.8003 36.0670 37.3336 38.6002 39.8669 41.1335 42.4002 43.6668 44.9334 46.2001 47.4667 ... 48.7334 50.0000]; win = dftfilt2(freqs, [3 12], 256, 'linear'); size(win) winsize = 0; for index = 1:length(win) winsize = max(winsize,length(win{index})); end; allwav = zeros(winsize, length(win)); for index = 1:length(win) wav1 = win{index}; abs1 = linspace(-(length(wav1)-1)/2,(length(wav1)-1)/2, length(wav1)); allwav(abs1+(winsize+1)/2,index) = wav1(:); end; figure; imagesc(imag(allwav)); % syemtric hanning function function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end
github
lcnbeapp/beapp-master
newtimef.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/newtimef.m
97,481
utf_8
9b205e33083e0973b5d9e671eac0abb5
% newtimef() - Return estimates and plots of mean event-related (log) spectral % perturbation (ERSP) and inter-trial coherence (ITC) events across % event-related trials (epochs) of a single input channel time series. % % * Also can compute and statistically compare transforms for two time % series. Use this to compare ERSP and ITC means in two conditions. % % * Uses either fixed-window, zero-padded FFTs (fastest), or wavelet % 0-padded DFTs. FFT uses Hanning tapers; wavelets use (similar) Morlet % tapers. % % * For the wavelet and FFT methods, output frequency spacing % is the lowest frequency ('srate'/'winsize') divided by 'padratio'. % NaN input values (such as returned by eventlock()) are ignored. % % * If 'alpha' is given (see below), permutation statistics are computed % (from a distribution of 'naccu' surrogate data trials) and % non-significant features of the output plots are zeroed out % and plotted in green. % % * Given a 'topovec' topo vector and 'elocs' electrode location file, % the figure also shows a topoplot() view of the specified scalp map. % % * Note: Left-click on subplots to view and zoom in separate windows. % % Usage with single dataset: % >> [ersp,itc,powbase,times,freqs,erspboot,itcboot] = ... % newtimef(data, frames, epochlim, srate, cycles,... % 'key1',value1, 'key2',value2, ... ); % % Example to compare two condition (channel 1 EEG versus ALLEEG(2)): % >> [ersp,itc,powbase,times,freqs,erspboot,itcboot] = ... % newtimef({EEG.data(1,:,:) ALLEEG(2).data(1,:,:)}, % EEG.pnts, [EEG.xmin EEG.xmax]*1000, EEG.srate, cycles); % NOTE: % >> timef details % presents more detailed argument information % % Note: version timef() also computes multitaper transforms % % Required inputs: Value {default} % data = Single-channel data vector (1,frames*ntrials), else % 2-D array (frames,trials) or 3-D array (1,frames,trials). % To compare two conditions (data1 versus data2), in place of % a single data matrix enter a cell array {data1 data2} % frames = Frames per trial. Ignored if data are 2-D or 3-D. {750} % tlimits = [mintime maxtime] (ms). Note that these are the time limits % of the data epochs themselves, NOT A SUB-WINDOW TO EXTRACT % FROM THE EPOCHS as is the case for pop_newtimef(). {[-1000 2000]} % Fs = data sampling rate (Hz) {default: read from icadefs.m or 250} % varwin = [real] indicates the number of cycles for the time-frequency % decomposition {default: 0} % If 0, use FFTs and Hanning window tapering. % If [real positive scalar], the number of cycles in each Morlet % wavelet, held constant across frequencies. % If [cycles cycles(2)] wavelet cycles increase with % frequency beginning at cycles(1) and, if cycles(2) > 1, % increasing to cycles(2) at the upper frequency, % If cycles(2) = 0, use same window size for all frequencies % (similar to FFT when cycles(1) = 1) % If cycles(2) = 1, cycles do not increase (same as giving % only one value for 'cycles'). This corresponds to a pure % wavelet decomposition, same number of cycles at each frequency. % If 0 < cycles(2) < 1, cycles increase linearly with frequency: % from 0 --> FFT (same window width at all frequencies) % to 1 --> wavelet (same number of cycles at all frequencies). % The exact number of cycles in the highest frequency window is % indicated in the command line output. Typical value: 'cycles', [3 0.5] % % Optional inter-trial coherence (ITC) Type: % 'itctype' = ['coher'|'phasecoher'|'phasecoher2'] Compute either linear % coherence ('coher') or phase coherence ('phasecoher'). % Originall called 'phase-locking factor' {default: 'phasecoher'} % % 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: The *longest* window length to use. This % determines the lowest output frequency. Note: this parameter % is overwritten when the minimum frequency requires % a longer time window {default: ~frames/8} % 'timesout' = Number of output times (int<frames-winframes). Enter a % negative value [-S] to subsample original times by S. % Enter an array to obtain spectral decomposition at % specific times (Note: The algorithm finds the closest time % point in data; this could give a slightly unevenly spaced % time array {default: 200} % 'padratio' = FFT-length/winframes (2^k) {default: 2} % Multiplies the number of output frequencies by dividing % their spacing (standard FFT padding). When cycles~=0, % frequency spacing is divided by padratio. % 'maxfreq' = Maximum frequency (Hz) to plot (& to output, if cycles>0) % If cycles==0, all FFT frequencies are output. {default: 50} % DEPRECATED, use 'freqs' instead,and never both. % 'freqs' = [min max] frequency limits. {default [minfreq 50], % minfreq being determined by the number of data points, % cycles and sampling frequency. % '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: 'linear'} % Note that for obtaining 'log' spaced freqs using FFT, % closest correspondant frequencies in the 'linear' space % are returned. % 'verbose' = ['on'|'off'] print text {'on'} % 'subitc' = ['on'|'off'] subtract stimulus locked Inter-Trial Coherence % (ITC) from x and y. This computes an 'intrinsic' coherence % of x and y not arising directly from common phase locking % to experimental events. See notes. {default: 'off'} % 'wletmethod' = ['dftfilt'|'dftfilt2'|'dftfilt3'] Wavelet type to use. % 'dftfilt2' -> Morlet-variant wavelets, or Hanning DFT. % 'dftfilt3' -> Morlet wavelets. See the timefreq() function % for more detials {default: 'dftfilt3'} % 'cycleinc' ['linear'|'log'] mode of cycles increase when [min max] cycles % are provided in 'cycle' parameter. Applies only to % 'wletmethod','dftfilt' {default: 'linear'} % % Optional baseline parameters: % 'baseline' = Spectral baseline end-time (in ms). NaN --> no baseline is used. % A [min max] range may also be entered % You may also enter one row per region for baseline % e.g. [0 100; 300 400] considers the window 0 to 100 ms and % 300 to 400 ms This parameter validly defines all baseline types % below. Again, [NaN] Prevent baseline subtraction. % {default: 0 -> all negative time values}. % 'powbase' = Baseline spectrum to log-subtract {default|NaN -> from data} % 'commonbase' = ['on'|'off'] use common baseline when comparing two % conditions {default: 'on'}. % 'basenorm' = ['on'|'off'] 'on' normalize baseline in the power spectral % average; else 'off', divide by the average power across % trials at each frequency (gain model). {default: 'off'} % 'trialbase' = ['on'|'off'|'full'] perform baseline (normalization or division % above in single trial instead of the trial average. Default % if 'off'. 'full' is an option that perform single % trial normalization (or simple division based on the % 'basenorm' input over the full trial length before % performing standard baseline removal. It has been % shown to be less sensitive to noisy trials in Grandchamp R, % Delorme A. (2011) Single-trial normalization for event-related % spectral decomposition reduces sensitivity to noisy trials. % Front Psychol. 2:236. % % Optional time warping parameter: % 'timewarp' = [eventms matrix] Time-warp amplitude and phase time- % courses(following time/freq transform but before % smoothing across trials). 'eventms' is a matrix % of size (all_trials,epoch_events) whose columns % specify the epoch times (latencies) (in ms) at which % the same series of successive events occur in each % trial. If two data conditions, eventms should be % [eventms1;eventms2] --> all trials stacked vertically. % 'timewarpms' = [warpms] optional vector of event times (latencies) (in ms) % to which the series of events should be warped. % (Note: Epoch start and end should not be declared % as eventms or warpms}. If 'warpms' is absent or [], % the median of each 'eventms' column will be used; % If two datasets, the grand medians of the two are used. % 'timewarpidx' = [plotidx] is an vector of indices telling which of % the time-warped 'eventms' columns (above) to show with % vertical lines. If undefined, all columns are plotted. % Overwrites the 'vert' argument (below) if any. % % Optional permutation parameters: % 'alpha' = If non-0, compute two-tailed permutation significance % probability level. Show non-signif. output values % as green. {default: 0} % 'mcorrect' = ['none'|'fdr'] correction for multiple comparison % 'fdr' uses false detection rate (see function fdr()). % Not available for condition comparisons. {default:'none'} % 'pcontour' = ['on'|'off'] draw contour around significant regions % instead of masking them. Not available for condition % comparisons. {default:'off'} % 'naccu' = Number of permutation replications to accumulate {200} % 'baseboot' = permutation baseline subtract (1 -> use 'baseline'; % 0 -> use whole trial % [min max] -> use time range) % You may also enter one row per region for baseline, % e.g. [0 100; 300 400] considers the window 0 to 100 ms % and 300 to 400 ms. {default: 1} % 'boottype' = ['shuffle'|'rand'|'randall'] 'shuffle' -> shuffle times % and trials; 'rand' -> invert polarity of spectral data % (for ERSP) or randomize phase (for ITC); 'randall' -> % compute significances by accumulating random-polarity % inversions for each time/frequency point (slow!). Note % that in the previous revision of this function, this % method was called 'bootstrap' though it is actually % permutation {default: 'shuffle'} % 'condboot' = ['abs'|'angle'|'complex'] to compare two conditions, % either subtract ITC absolute values ('abs'), angles % ('angles'), or complex values ('complex'). {default: 'abs'} % 'pboot' = permutation power limits (e.g., from newtimef()) {def: from data} % 'rboot' = permutation ITC limits (e.g., from newtimef()). % Note: Both 'pboot' and 'rboot' must be provided to avoid % recomputing the surrogate data! {default: from data} % % Optional Scalp Map: % 'topovec' = Scalp topography (map) to plot {none} % 'elocs' = Electrode location file for scalp map {none} % Value should be a string array containing the path % and name of the file. For file format, see % >> topoplot example % 'chaninfo' Passed to topoplot, if called. % [struct] optional structure containing fields % 'nosedir', 'plotrad', and/or 'chantype'. See these % field definitions above, below. % {default: nosedir +X, plotrad 0.5, all channels} % % Optional Plotting Parameters: % 'scale' = ['log'|'abs'] visualize power in log scale (dB) or absolute % scale. {default: 'log'} % 'plottype' = ['image'|'curve'] plot time/frequency images or traces % (curves, one curve per frequency). {default: 'image'} % 'plotmean' = ['on'|'off'] For 'curve' plots only. Average all % frequencies given as input. {default: 'on'} % 'highlightmode' = ['background'|'bottom'] For 'curve' plots only, % display significant time regions either in the plot background % or under the curve. % 'plotersp' = ['on'|'off'] Plot power spectral perturbations {'on'} % 'plotitc' = ['on'|'off'] Plot inter-trial coherence {'on'} % 'plotphasesign' = ['on'|'off'] Plot phase sign in the inter trial coherence {'on'} % 'plotphaseonly' = ['on'|'off'] Plot ITC phase instead of ITC amplitude {'off'} % 'erspmax' = [real] set the ERSP max. For the color scale (min= -max) {auto} % 'itcmax' = [real] set the ITC image maximum for the color scale {auto} % 'hzdir' = ['up' or 'normal'|'down' or 'reverse'] Direction of % the frequency axes {default: as in icadefs.m, or 'up'} % 'ydir' = ['up' or 'normal'|'down' or 'reverse'] Direction of % the ERP axis plotted below the ITC {as in icadefs.m, or 'up'} % 'erplim' = [min max] ERP limits for ITC (below ITC image) {auto} % 'itcavglim' = [min max] average ITC limits for all freq. (left of ITC) {auto} % 'speclim' = [min max] average spectrum limits (left of ERSP image) {auto} % 'erspmarglim' = [min max] average marginal ERSP limits (below ERSP image) {auto} % 'title' = Optional figure or (brief) title {none}. For multiple conditions % this must contain a cell array of 2 or 3 title strings. % 'marktimes' = Non-0 times to mark with a dotted vertical line (ms) {none} % 'linewidth' = Line width for 'marktimes' traces (thick=2, thin=1) {2} % 'axesfont' = Axes text font size {10} % 'titlefont' = Title text font size {8} % 'vert' = [times_vector] -> plot vertical dashed lines at specified times % in ms. {default: none} % 'newfig' = ['on'|'off'] Create new figure for difference plots {'on'} % 'caption' = Caption of the figure {none} % 'outputformat' = ['old'|'plot'] for compatibility with script that used the % old output format, set to 'old' (mbase in absolute amplitude (not % dB) and real itc instead of complex itc). 'plot' returns % the plotted result {default: 'plot'} % Outputs: % ersp = (nfreqs,timesout) matrix of log spectral diffs from baseline % (in dB log scale or absolute scale). Use the 'plot' output format % above to output the ERSP as shown on the plot. % itc = (nfreqs,timesout) matrix of complex inter-trial coherencies. % itc is complex -- ITC magnitude is abs(itc); ITC phase in radians % is angle(itc), or in deg phase(itc)*180/pi. % powbase = baseline power spectrum. Note that even, when selecting the % the 'trialbase' option, the average power spectrum is % returned (not trial based). To obtain the baseline of % each trial, recompute it manually using the tfdata % output described below. % times = vector of output times (spectral time window centers) (in ms). % freqs = vector of frequency bin centers (in Hz). % erspboot = (nfreqs,2) matrix of [lower upper] ERSP significance. % itcboot = (nfreqs) matrix of [upper] abs(itc) threshold. % tfdata = optional (nfreqs,timesout,trials) time/frequency decomposition % of the single data trials. Values are complex. % % Plot description: % Assuming both 'plotersp' and 'plotitc' options are 'on' (= default). % The upper panel presents the data ERSP (Event-Related Spectral Perturbation) % in dB, with mean baseline spectral activity (in dB) subtracted. Use % "'baseline', NaN" to prevent timef() from removing the baseline. % The lower panel presents the data ITC (Inter-Trial Coherence). % Click on any plot axes to pop up a new window (using 'axcopy()') % -- Upper left marginal panel presents the mean spectrum during the baseline % period (blue), and when significance is set, the significance threshold % at each frequency (dotted green-black trace). % -- The marginal panel under the ERSP image shows the maximum (green) and % minimum (blue) ERSP values relative to baseline power at each frequency. % -- The lower left marginal panel shows mean ITC across the imaged time range % (blue), and when significance is set, the significance threshold (dotted % green-black). % -- The marginal panel under the ITC image shows the ERP (which is produced by % ITC across the data spectral pass band). % % Authors: Arnaud Delorme, Jean Hausser from timef() by Sigurd Enghoff, Scott Makeig % CNL / Salk Institute 1998- | SCCN/INC, UCSD 2002- % % See also: timefreq(), condstat(), newcrossf(), tftopo() % Deprecated Multitaper Parameters: [not included here] % 'mtaper' = If [N W], performs multitaper decomposition. % (N is the time resolution and W the frequency resolution; % maximum taper number is 2NW-1). Overwrites 'winsize' and 'padratio'. % If [N W K], forces the use of K Slepian tapers (if possible). % Phase is calculated using standard methods. % The use of mutitaper with wavelets (cycles>0) is not % recommended (as multiwavelets are not implemented). % Uses Matlab functions DPSS, PMTM. {no multitaper} % Deprecated time warp keywords (working?) % 'timewarpfr' = {{[events], [warpfr], [plotidx]}} Time warp amplitude and phase % time-courses (after time/freq transform but before smoothingtimefreqfunc % across trials). 'events' is a matrix whose columns specify the % epoch frames [1 ... end] at which a series of successive events % occur in each trial. 'warpfr' is an optional vector of event % frames to which the series of events should be time locked. % (Note: Epoch start and end should not be declared as events or % warpfr}. If 'warpfr' is absent or [], the median of each 'events' % column will be used. [plotidx] is an optional vector of indices % telling which of the warpfr to plot with vertical lines. If % undefined, all marks are plotted. Overwrites 'vert' argument, % if any. [Note: In future releases, 'timewarpfr' will be deprecated % in favor of 'timewarp' using latencies in ms instead of frames]. % Deprecated original time warp keywords (working?) % 'timeStretchMarks' = [(marks,trials) matrix] Each trial data will be % linearly warped (after time/freq. transform) so that the % event marks are time locked to the reference frames % (see timeStretchRefs). Marks must be specified in frames % 'timeStretchRefs' = [1 x marks] Common reference frames to all trials. % If empty or undefined, median latency for each mark will be used.boottype % 'timeStretchPlot' = [vector] Indicates the indices of the reference frames % (in StretchRefs) should be overplotted on the ERSP and ITC. % % % Copyright (C) University of California San Diego, La Jolla, CA % % First built as timef.m at CNL / Salk Institute 8/1/98-8/28/01 by % Sigurd Enghoff and Scott Makeig, edited by Arnaud Delorme % SCCN/INC/UCSD/ reprogrammed as newtimef -Arnaud Delorme 2002- % SCCN/INC/UCSD/ added time warping capabilities -Jean Hausser 2005 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 10-19-98 avoided division by zero (using MIN_ABS) -sm % 10-19-98 improved usage message and commandline info printing -sm % 10-19-98 made valid [] values for tvec and g.elocs -sm % 04-01-99 added missing freq in freqs and plots, fixed log scaling bug -se && -tpj % 06-29-99 fixed frequency indexing for constant-Q -se % 08-24-99 reworked to handle NaN input values -sm % 12-07-99 adjusted ERPtimes to plot ERP under ITC -sm % 12-22-99 debugged ERPtimes, added BASE_BOOT -sm % 01-10-00 debugged BASE_BOOT=0 -sm % 02-28-00 added NOTE on formula derivation below -sm % 03-16-00 added axcopy() feature -sm && tpj % 04-16-00 added multiple marktimes loop -sm % 04-20-00 fixed ITC cbar limits when spcified in input -sm % 07-29-00 changed frequencies displayed msg -sm % 10-12-00 fixed bug in freqs when cycles>0 -sm % 02-07-01 fixed inconsistency in BASE_BOOT use -sm % 08-28-01 matlab 'key' value arguments -ad % 08-28-01 multitaper decomposition -ad % 01-25-02 reformated help && license -ad % 03-08-02 debug && compare to old timef function -ad % 03-16-02 timeout automatically adjusted if too high -ad % 04-02-02 added 'coher' option -ad function [P,R,mbase,timesout,freqs,Pboot,Rboot,alltfX,PA] = newtimef( data, frames, tlimits, Fs, varwin, varargin); % Note: Above, PA is output of 'phsamp','on' % For future 'timewarp' keyword help: 'timewarp' 3rd element {colors} contains a % list of Matlab linestyles to use for vertical lines marking the occurence % of the time warped events. If '', no line will be drawn for this event % column. If fewer colors than event columns, cycles through the given color % labels. Note: Not compatible with 'vert' (below). %varwin,winsize,g.timesout,g.padratio,g.maxfreq,g.topovec,g.elocs,g.alpha,g.marktimes,g.powbase,g.pboot,g.rboot) % ITC: Normally, R = |Sum(Pxy)| / (Sum(|Pxx|)*Sum(|Pyy|)) is coherence. % But here, we consider Phase(Pyy) = 0 and |Pyy| = 1 -> Pxy = Pxx % Giving, R = |Sum(Pxx)|/Sum(|Pxx|), the inter-trial coherence (ITC) % Also called 'phase-locking factor' by Tallon-Baudry et al. (1996) if nargin < 1 help newtimef; return; end; % Read system (or directory) constants and preferences: % ------------------------------------------------------ icadefs % read local EEGLAB constants: HZDIR, YDIR, DEFAULT_SRATE, DEFAULT_TIMLIM if ~exist('HZDIR'), HZDIR = 'up'; end; % ascending freqs if ~exist('YDIR'), YDIR = 'up'; end; % positive up if YDIR == 1, YDIR = 'up'; end; % convert from [-1|1] as set in icadefs.m if YDIR == -1, YDIR = 'down'; end; % and read by other plotting functions if ~exist('DEFAULT_SRATE'), DEFAULT_SRATE = 250; end; % 250 Hz if ~exist('DEFAULT_TIMLIM'), DEFAULT_TIMLIM = [-1000 2000]; end; % [-1 2] s epochs % Constants set here: % ------------------ ERSP_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value % giving symmetric +/- caxis limits. ITC_CAXIS_LIMIT = 0; % 0 -> use data limits; else positive value % giving symmetric +/- caxis limits. MIN_ABS = 1e-8; % avoid division by ~zero % Command line argument defaults: % ------------------------------ DEFAULT_NWIN = 200; % Number of windows = horizontal resolution DEFAULT_VARWIN = 0; % Fixed window length or fixed number of cycles. % =0: fix window length to that determined by nwin % >0: set window length equal to varwin cycles % Bounded above by winsize, which determines % the min. freq. to be computed. DEFAULT_OVERSMP = 2; % Number of times to oversample frequencies DEFAULT_MAXFREQ = 50; % Maximum frequency to display (Hz) DEFAULT_TITLE = ''; % Figure title (no default) DEFAULT_ELOC = 'chan.locs'; % Channel location file DEFAULT_ALPHA = NaN; % Percentile of bins to keep DEFAULT_MARKTIME= NaN; % Font sizes: AXES_FONT = 10; % axes text FontSize TITLE_FONT = 8; if (nargin < 2) frames = floor((DEFAULT_TIMLIN(2)-DEFAULT_TIMLIM(1))/DEFAULT_SRATE); elseif (~isnumeric(frames) | length(frames)~=1 | frames~=round(frames)) error('Value of frames must be an integer.'); elseif (frames <= 0) error('Value of frames must be positive.'); end; DEFAULT_WINSIZE = max(pow2(nextpow2(frames)-3),4); DEFAULT_PAD = max(pow2(nextpow2(DEFAULT_WINSIZE)),4); if (nargin < 1) help newtimef return end if isstr(data) && strcmp(data,'details') more on help timefdetails more off return end if ~iscell(data) data = reshape_data(data, frames); trials = size(data,ndims(data)); else if ndims(data) == 3 && size(data,1) == 1 error('Cannot process multiple channel component in compare mode'); end; [data{1}, frames] = reshape_data(data{1}, frames); [data{2}, frames] = reshape_data(data{2}, frames); trials = size(data{1},2); end; if (nargin < 3) tlimits = DEFAULT_TIMLIM; elseif (~isnumeric(tlimits) | sum(size(tlimits))~=3) error('Value of tlimits must be a vector containing two numbers.'); elseif (tlimits(1) >= tlimits(2)) error('tlimits interval must be ascending.'); end if (nargin < 4) Fs = DEFAULT_SRATE; elseif (~isnumeric(Fs) | length(Fs)~=1) error('Value of srate must be a number.'); elseif (Fs <= 0) error('Value of srate must be positive.'); end if (nargin < 5) varwin = DEFAULT_VARWIN; elseif ~isnumeric(varwin) && strcmpi(varwin, 'cycles') varwin = varargin{1}; varargin(1) = []; elseif (varwin < 0) error('Value of cycles must be zero or positive.'); end % build a structure for keyword arguments % -------------------------------------- if ~isempty(varargin) [tmp indices] = unique_bc(varargin(1:2:end)); varargin = varargin(sort(union(indices*2-1, indices*2))); % these 2 lines remove duplicate arguments try, g = struct(varargin{:}); catch, error('Argument error in the {''param'', value} sequence'); end; end %} [ g timefreqopts ] = finputcheck(varargin, ... {'boottype' 'string' {'shuffle','rand','randall'} 'shuffle'; ... 'condboot' 'string' {'abs','angle','complex'} 'abs'; ... 'title' { 'string','cell' } { [] [] } DEFAULT_TITLE; ... 'title2' 'string' [] DEFAULT_TITLE; ... 'winsize' 'integer' [0 Inf] DEFAULT_WINSIZE; ... 'pad' 'real' [] DEFAULT_PAD; ... 'timesout' 'integer' [] DEFAULT_NWIN; ... 'padratio' 'integer' [0 Inf] DEFAULT_OVERSMP; ... 'topovec' 'real' [] []; ... 'elocs' {'string','struct'} [] DEFAULT_ELOC; ... 'alpha' 'real' [0 0.5] DEFAULT_ALPHA; ... 'marktimes' 'real' [] DEFAULT_MARKTIME; ... 'powbase' 'real' [] NaN; ... 'pboot' 'real' [] NaN; ... 'rboot' 'real' [] NaN; ... 'plotersp' 'string' {'on','off'} 'on'; ... 'plotamp' 'string' {'on','off'} 'on'; ... 'plotitc' 'string' {'on','off'} 'on'; ... 'detrend' 'string' {'on','off'} 'off'; ... 'rmerp' 'string' {'on','off'} 'off'; ... 'basenorm' 'string' {'on','off'} 'off'; ... 'commonbase' 'string' {'on','off'} 'on'; ... 'baseline' 'real' [] 0; ... 'baseboot' 'real' [] 1; ... 'linewidth' 'integer' [1 2] 2; ... 'naccu' 'integer' [1 Inf] 200; ... 'mtaper' 'real' [] []; ... 'maxfreq' 'real' [0 Inf] DEFAULT_MAXFREQ; ... 'freqs' 'real' [0 Inf] [0 DEFAULT_MAXFREQ]; ... 'cycles' 'integer' [] []; ... 'nfreqs' 'integer' [] []; ... 'freqscale' 'string' [] 'linear'; ... 'vert' 'real' [] []; ... 'newfig' 'string' {'on','off'} 'on'; ... 'type' 'string' {'coher','phasecoher','phasecoher2'} 'phasecoher'; ... 'itctype' 'string' {'coher','phasecoher','phasecoher2'} 'phasecoher'; ... 'phsamp' 'string' {'on','off'} 'off'; ... % phsamp not completed - Toby 9.28.2006 'plotphaseonly' 'string' {'on','off'} 'off'; ... 'plotphasesign' 'string' {'on','off'} 'on'; ... 'plotphase' 'string' {'on','off'} 'on'; ... % same as above for backward compatibility 'pcontour' 'string' {'on','off'} 'off'; ... 'outputformat' 'string' {'old','new','plot' } 'plot'; ... 'itcmax' 'real' [] []; ... 'erspmax' 'real' [] []; ... 'lowmem' 'string' {'on','off'} 'off'; ... 'verbose' 'string' {'on','off'} 'on'; ... 'plottype' 'string' {'image','curve'} 'image'; ... 'mcorrect' 'string' {'fdr','none'} 'none'; ... 'plotmean' 'string' {'on','off'} 'on'; ... 'plotmode' 'string' {} ''; ... % for metaplottopo 'highlightmode' 'string' {'background','bottom'} 'background'; ... 'chaninfo' 'struct' [] struct([]); ... 'erspmarglim' 'real' [] []; ... 'itcavglim' 'real' [] []; ... 'erplim' 'real' [] []; ... 'speclim' 'real' [] []; ... 'ntimesout' 'real' [] []; ... 'scale' 'string' { 'log','abs'} 'log'; ... 'timewarp' 'real' [] []; ... 'precomputed' 'struct' [] struct([]); ... 'timewarpms' 'real' [] []; ... 'timewarpfr' 'real' [] []; ... 'timewarpidx' 'real' [] []; ... 'timewarpidx' 'real' [] []; ... 'timeStretchMarks' 'real' [] []; ... 'timeStretchRefs' 'real' [] []; ... 'timeStretchPlot' 'real' [] []; ... 'trialbase' 'string' {'on','off','full'} 'off'; 'caption' 'string' [] ''; ... 'hzdir' 'string' {'up','down','normal','reverse'} HZDIR; ... 'ydir' 'string' {'up','down','normal','reverse'} YDIR; ... 'cycleinc' 'string' {'linear','log'} 'linear' }, 'newtimef', 'ignore'); if isstr(g), error(g); end; if strcmpi(g.plotamp, 'off'), g.plotersp = 'off'; end; if strcmpi(g.basenorm, 'on'), g.scale = 'abs'; end; if ~strcmpi(g.itctype , 'phasecoher'), g.type = g.itctype; end; g.tlimits = tlimits; g.frames = frames; g.srate = Fs; if isempty(g.cycles) g.cycles = varwin; end; g.AXES_FONT = AXES_FONT; % axes text FontSize g.TITLE_FONT = TITLE_FONT; g.ERSP_CAXIS_LIMIT = ERSP_CAXIS_LIMIT; g.ITC_CAXIS_LIMIT = ITC_CAXIS_LIMIT; if ~strcmpi(g.plotphase, 'on'), g.plotphasesign = g.plotphase; end; % unpack 'timewarp' (and undocumented 'timewarpfr') arguments %------------------------------------------------------------ if isfield(g,'timewarpfr') if iscell(g.timewarpfr) && length(g.timewarpfr) > 3 error('undocumented ''timewarpfr'' cell array may have at most 3 elements'); end end if ~isempty(g.nfreqs) verboseprintf(g.verbose, 'Warning: ''nfreqs'' input overwrite ''padratio''\n'); end; if strcmpi(g.basenorm, 'on') verboseprintf(g.verbose, 'Baseline normalization is on (results will be shown as z-scores)\n'); end; if isfield(g,'timewarp') && ~isempty(g.timewarp) if ndims(data) == 3 error('Cannot perform time warping on 3-D data input'); end; if ~isempty(g.timewarp) % convert timewarp ms to timewarpfr frames -sm fprintf('\n') if iscell(g.timewarp) error('timewarp argument must be a (total_trials,epoch_events) matrix'); end evntms = g.timewarp; warpfr = round((evntms - g.tlimits(1))/1000*g.srate)+1; g.timewarpfr{1} = warpfr'; if isfield(g,'timewarpms') refms = g.timewarpms; reffr = round((refms - g.tlimits(1))/1000*g.srate)+1; g.timewarpfr{2} = reffr'; end if isfield(g,'timewarpidx') g.timewarpfr{3} = g.timewarpidx; end end % convert again to timeStretch parameters % --------------------------------------- if ~isempty(g.timewarpfr) g.timeStretchMarks = g.timewarpfr{1}; if length(g.timewarpfr) > 1 g.timeStretchRefs = g.timewarpfr{2}; end if length(g.timewarpfr) > 2 if isempty(g.timewarpfr{3}) stretchevents = size(g.timeStretchMarks,1); g.timeStretchPlot = [1:stretchevents]; % default to plotting all lines else g.timeStretchPlot = g.timewarpfr{3}; end end if max(max(g.timeStretchMarks)) > frames-2 | min(min(g.timeStretchMarks)) < 3 error('Time warping events must be inside the epochs.'); end if ~isempty(g.timeStretchRefs) if max(g.timeStretchRefs) > frames-2 | min(g.timeStretchRefs) < 3 error('Time warping reference latencies must be within the epochs.'); end end end end % Determining source of the call % --------------------------------------% 'guicall'= 1 if newtimef is called callerstr = dbstack(1); % from EEGLAB GUI, otherwise 'guicall'= 0 if isempty(callerstr) % 7/3/2014, Ramon guicall = 0; elseif strcmp(callerstr(end).name,'pop_newtimef') guicall = 1; else guicall = 0; end % test argument consistency % -------------------------- if g.tlimits(2)-g.tlimits(1) < 30 verboseprintf(g.verbose, 'newtimef(): WARNING: Specified time range is very small (< 30 ms)???\n'); verboseprintf(g.verbose, ' Epoch time limits should be in msec, not seconds!\n'); end if (g.winsize > g.frames) error('Value of winsize must be smaller than epoch frames.'); end if length(g.timesout) == 1 && g.timesout > 0 if g.timesout > g.frames-g.winsize g.timesout = g.frames-g.winsize; disp(['Value of timesout must be <= frames-winsize, timeout adjusted to ' int2str(g.timesout) ]); end end; if (pow2(nextpow2(g.padratio)) ~= g.padratio) error('Value of padratio must be an integer power of two [1,2,4,8,16,...]'); end if (g.maxfreq > Fs/2) verboseprintf(g.verbose, ['Warning: value of maxfreq reduced to Nyquist rate' ... ' (%3.2f)\n\n'], Fs/2); g.maxfreq = Fs/2; end if g.maxfreq ~= DEFAULT_MAXFREQ, g.freqs(2) = g.maxfreq; end; if isempty(g.topovec) g.topovec = []; if isempty(g.elocs) error('Channel location file must be specified.'); end; end if (round(g.naccu*g.alpha) < 2) verboseprintf(g.verbose, 'Value of alpha is outside its normal range [%g,0.5]\n',2/g.naccu); g.naccu = round(2/g.alpha); verboseprintf(g.verbose, ' Increasing the number of iterations to %d\n',g.naccu); end if ~isnan(g.alpha) if length(g.baseboot) == 2 verboseprintf(g.verbose, 'Permutation analysis will use data from %3.2g to %3.2g ms.\n', ... g.baseboot(1), g.baseboot(2)) elseif g.baseboot > 0 verboseprintf(g.verbose, 'Permutation analysis will use data in (pre-0) baseline subwindows only.\n') else verboseprintf(g.verbose, 'Permutation analysis will use data in all subwindows.\n') end end if ~isempty(g.timeStretchMarks) % timeStretch code by Jean Hauser if isempty(g.timeStretchRefs) verboseprintf(g.verbose, ['Using median event latencies as reference event times for time warping.\n']); g.timeStretchRefs = median(g.timeStretchMarks,2); % Note: Uses (grand) median latencies for two conditions else verboseprintf(g.verbose, ['Using supplied latencies as reference event times for time warping.\n']); end if isempty(g.timeStretchPlot) verboseprintf(g.verbose, 'Will not overplot the reference event times on the ERSP.\n'); elseif length(g.timeStretchPlot) > 0 g.vert = ((g.timeStretchRefs(g.timeStretchPlot)-1) ... /g.srate+g.tlimits(1)/1000)*1000; fprintf('Plotting timewarp markers at ') for li = 1:length(g.vert), fprintf('%d ',g.vert(li)); end fprintf(' ms.\n') end end if min(g.vert) < g.tlimits(1) | max(g.vert) > g.tlimits(2) error('vertical line (''vert'') latency outside of epoch boundaries'); end if strcmp(g.hzdir,'up')| strcmp(g.hzdir,'normal') g.hzdir = 'normal'; % convert to Matlab graphics constants elseif strcmp(g.hzdir,'down') | strcmp(g.hzdir,'reverse')| g.hzdir==-1 g.hzdir = 'reverse'; else error('unknown ''hzdir'' argument'); end if strcmp(g.ydir,'up')| strcmp(g.ydir,'normal') g.ydir = 'normal'; % convert to Matlab graphics constants elseif strcmp(g.ydir,'down') | strcmp(g.ydir,'reverse') g.ydir = 'reverse'; else error('unknown ''ydir'' argument'); end % ----------------- % ERSP scaling unit % ----------------- if strcmpi(g.scale, 'log') if strcmpi(g.basenorm, 'on') g.unitpower = '10*log(std.)'; % impossible elseif isnan(g.baseline) g.unitpower = '10*log10(\muV^{2}/Hz)'; else g.unitpower = 'dB'; end; else if strcmpi(g.basenorm, 'on') g.unitpower = 'std.'; elseif isnan(g.baseline) g.unitpower = '\muV^{2}/Hz'; else g.unitpower = '% of baseline'; end; end; % Multitaper - used in timef % -------------------------- if ~isempty(g.mtaper) % multitaper, inspired from a Bijan Pesaran matlab function if length(g.mtaper) < 3 %error('mtaper arguement must be [N W] or [N W K]'); if g.mtaper(1) * g.mtaper(2) < 1 error('mtaper 2 first arguments'' product must be larger than 1'); end; if length(g.mtaper) == 2 g.mtaper(3) = floor( 2*g.mtaper(2)*g.mtaper(1) - 1); end if length(g.mtaper) == 3 if g.mtaper(3) > 2 * g.mtaper(1) * g.mtaper(2) -1 error('mtaper number too high (maximum (2*N*W-1))'); end; end disp(['Using ' num2str(g.mtaper(3)) ' tapers.']); NW = g.mtaper(1)*g.mtaper(2); % product NW N = g.mtaper(1)*g.srate; [e,v] = dpss(N, NW, 'calc'); e=e(:,1:g.mtaper(3)); g.alltapers = e; else g.alltapers = g.mtaper; disp('mtaper argument not [N W] or [N W K]; considering raw taper matrix'); end; g.winsize = size(g.alltapers, 1); g.pad = max(pow2(nextpow2(g.winsize)),256); % pad*nextpow nfk = floor([0 g.maxfreq]./g.srate.*g.pad); g.padratio = 2*nfk(2)/g.winsize; %compute number of frequencies %nf = max(256, g.pad*2^nextpow2(g.winsize+1)); %nfk = floor([0 g.maxfreq]./g.srate.*nf); %freqs = linspace( 0, g.maxfreq, diff(nfk)); % this also works in the case of a FFT end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute frequency by frequency if low memory %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(g.lowmem, 'on') && numel(data) ~= g.frames && isempty(g.nfreqs) && ~iscell(data) disp('Lowmem is a deprecated option that is not functional any more'); return; % NOTE: the code below is functional but the graphical output is % different when the 'lowmem' option is used compared to when it is not % used - AD, 29 April 2011 % compute for first 2 trials to get freqsout XX = reshape(data, 1, frames, prod(size(data))/g.frames); [P,R,mbase,timesout,freqsout] = newtimef(XX(1,:,1), frames, tlimits, Fs, g.cycles, 'plotitc', 'off', 'plotamp', 'off',varargin{:}, 'lowmem', 'off'); % scan all frequencies for index = 1:length(freqsout) if nargout < 8 [P(index,:),R(index,:),mbase(index),timesout,tmpfreqs(index),Pboottmp,Rboottmp] = ... newtimef(data, frames, tlimits, Fs, g.cycles, ... 'freqs', [freqsout(index) freqsout(index)], 'nfreqs', 1, ... 'plotamp', 'off', 'plotitc', 'off', 'plotphasesign', 'off',varargin{:}, ... 'lowmem', 'off', 'timesout', timesout); if ~isempty(Pboottmp) Pboot(index,:) = Pboottmp; Rboot(index,:) = Rboottmp; else Pboot = []; Rboot = []; end; else [P(index,:),R(index,:),mbase(index),timesout,tmpfreqs(index),Pboot(index,:),Rboot(index,:), ... alltfX(index,:,:)] = ... newtimef(data, frames, tlimits, Fs, g.cycles, ... 'freqs', [freqsout(index) freqsout(index)], 'nfreqs', 1, ... 'plotamp', 'off', 'plotphasesign', 'off',varargin{:}, ... 'lowmem', 'off', 'timesout', timesout); end; end; % compute trial-average ERP % ------------------------- ERP = mean(data,2); % plot results %------------- plottimef(P, R, Pboot, Rboot, ERP, freqsout, timesout, mbase, [], [], g); return; % finished end; %%%%%%%%%%%%%%%%%%%%%%% % compare 2 conditions %%%%%%%%%%%%%%%%%%%%%%% if iscell(data) if ~guicall && (strcmp(g.basenorm, 'on') || strcmp(g.trialbase, 'on')) % ------------------------------------- Temporary fix for error when using error('EEGLAB error: basenorm and/or trialbase options cannot be used when processing 2 conditions'); % basenorm or trialbase with two conditions end; Pboot = []; Rboot = []; if ~strcmpi(g.mcorrect, 'none') error('Correction for multiple comparison not implemented for comparing conditions'); end; vararginori = varargin; if length(data) ~= 2 error('newtimef: to compare two conditions, data must be a length-2 cell array'); end; % deal with titles % ---------------- for index = 1:2:length(vararginori) if index<=length(vararginori) % needed if elements are deleted % if strcmp(vararginori{index}, 'title') | ... % Added by Jean Hauser % strcmp(vararginori{index}, 'title2') | ... if strcmp(vararginori{index}, 'timeStretchMarks') | ... strcmp(vararginori{index}, 'timeStretchRefs') | ... strcmp(vararginori{index}, 'timeStretchPlots') vararginori(index:index+1) = []; end; end; end; if iscell(g.title) && length(g.title) >= 2 % Changed that part because providing titles % as cells caused the function to crash (why?) % at line 704 (g.tlimits = tlimits) -Jean if length(g.title) == 2, g.title{3} = [ g.title{1} ' - ' g.title{2} ]; end; else disp('Warning: title must be a cell array'); g.title = { 'Condition 1' 'Condition 2' 'Condition 1 minus Condition 2' }; end; verboseprintf(g.verbose, '\nRunning newtimef() on Condition 1 **********************\n\n'); verboseprintf(g.verbose, 'Note: If an out-of-memory error occurs, try reducing the\n'); verboseprintf(g.verbose, ' the number of time points or number of frequencies\n'); verboseprintf(g.verbose, '(''coher'' options take 3 times the memory of other options)\n\n'); cond_1_epochs = size(data{1},2); if ~isempty(g.timeStretchMarks) [P1,R1,mbase1,timesout,freqs,Pboot1,Rboot1,alltfX1] = ... newtimef( data{1}, frames, tlimits, Fs, g.cycles, 'plotitc', 'off', ... 'plotersp', 'off', vararginori{:}, 'lowmem', 'off', ... 'timeStretchMarks', g.timeStretchMarks(:,1:cond_1_epochs), ... 'timeStretchRefs', g.timeStretchRefs); else [P1,R1,mbase1,timesout,freqs,Pboot1,Rboot1,alltfX1] = ... newtimef( data{1}, frames, tlimits, Fs, g.cycles, 'plotitc', 'off', ... 'plotersp', 'off', vararginori{:}, 'lowmem', 'off'); end verboseprintf(g.verbose,'\nRunning newtimef() on Condition 2 **********************\n\n'); [P2,R2,mbase2,timesout,freqs,Pboot2,Rboot2,alltfX2] = ... newtimef( data{2}, frames, tlimits, Fs, g.cycles, 'plotitc', 'off', ... 'plotersp', 'off', vararginori{:}, 'lowmem', 'off', ... 'timeStretchMarks', g.timeStretchMarks(:,cond_1_epochs+1:end), ... 'timeStretchRefs', g.timeStretchRefs); verboseprintf(g.verbose,'\nComputing difference **********************\n\n'); % recompute power baselines % ------------------------- if ~isnan( g.baseline(1) ) && ~isnan( mbase1(1) ) && isnan(g.powbase(1)) && strcmpi(g.commonbase, 'on') disp('Recomputing baseline power: using the grand mean of both conditions ...'); mbase = (mbase1 + mbase2)/2; P1 = P1 + repmat(mbase1(1:size(P1,1))',[1 size(P1,2)]); P2 = P2 + repmat(mbase2(1:size(P1,1))',[1 size(P1,2)]); P1 = P1 - repmat(mbase (1:size(P1,1))',[1 size(P1,2)]); P2 = P2 - repmat(mbase (1:size(P1,1))',[1 size(P1,2)]); if ~isnan(g.alpha) Pboot1 = Pboot1 + repmat(mbase1(1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]); Pboot2 = Pboot2 + repmat(mbase2(1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]); Pboot1 = Pboot1 - repmat(mbase (1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]); Pboot2 = Pboot2 - repmat(mbase (1:size(Pboot1,1))',[1 size(Pboot1,2) size(Pboot1,3)]); end; verboseprintf(g.verbose, '\nSubtracting the common power baseline ...\n'); meanmbase = mbase; mbase = { mbase mbase }; elseif strcmpi(g.commonbase, 'on') mbase = { NaN NaN }; meanmbase = mbase{1}; %Ramon :for bug 1657 else meanmbase = (mbase1 + mbase2)/2; mbase = { mbase1 mbase2 }; end; % plotting % -------- if strcmpi(g.plotersp, 'on') | strcmpi(g.plotitc, 'on') g.titleall = g.title; if strcmpi(g.newfig, 'on'), figure; end; % declare a new figure % using same color scale % ---------------------- if ~isfield(g, 'erspmax') g.erspmax = max( max(max(abs(Pboot1))), max(max(abs(Pboot2))) ); end; if ~isfield(g, 'itcmax') g.itcmax = max( max(max(abs(Rboot1))), max(max(abs(Rboot2))) ); end; subplot(1,3,1); % plot Condition 1 g.title = g.titleall{1}; g = plottimef(P1, R1, Pboot1, Rboot1, mean(data{1},2), freqs, timesout, mbase{1}, [], [], g); g.itcavglim = []; subplot(1,3,2); % plot Condition 2 g.title = g.titleall{2}; plottimef(P2, R2, Pboot2, Rboot2, mean(data{2},2), freqs, timesout, mbase{2}, [], [], g); subplot(1,3,3); % plot Condition 1 - Condition 2 g.title = g.titleall{3}; end; if isnan(g.alpha) switch(g.condboot) case 'abs', Rdiff = abs(R1)-abs(R2); case 'angle', Rdiff = angle(R1)-angle(R2); case 'complex', Rdiff = R1-R2; end; if strcmpi(g.plotersp, 'on') | strcmpi(g.plotitc, 'on') g.erspmax = []; g.itcmax = []; % auto scale inserted for diff plottimef(P1-P2, Rdiff, [], [], mean(data{1},2)-mean(data{2},2), freqs, timesout, meanmbase, [], [], g); end; else % preprocess data and run compstat() function % ------------------------------------------- alltfX1power = alltfX1.*conj(alltfX1); alltfX2power = alltfX2.*conj(alltfX2); if ~isnan(mbase{1}(1)) mbase1 = 10.^(mbase{1}(1:size(alltfX1,1))'/20); mbase2 = 10.^(mbase{2}(1:size(alltfX1,1))'/20); alltfX1 = alltfX1./repmat(mbase1/2,[1 size(alltfX1,2) size(alltfX1,3)]); alltfX2 = alltfX2./repmat(mbase2/2,[1 size(alltfX2,2) size(alltfX2,3)]); alltfX1power = alltfX1power./repmat(mbase1,[1 size(alltfX1power,2) size(alltfX1power,3)]); alltfX2power = alltfX2power./repmat(mbase2,[1 size(alltfX2power,2) size(alltfX2power,3)]); end; %formula = {'log10(mean(arg1,3))'}; % toby 10.02.2006 %formula = {'log10(mean(arg1(:,:,data),3))'}; formula = {'log10(mean(arg1(:,:,X),3))'}; switch g.type case 'coher', % take the square of alltfx and alltfy first to speed up formula = { formula{1} ['sum(arg2(:,:,data),3)./sqrt(sum(arg1(:,:,data),3)*length(data) )'] }; if strcmpi(g.lowmem, 'on') for ind = 1:2:size(alltfX1power,1) if ind == size(alltfX1,1), indarr = ind; else indarr = [ind:ind+1]; end; [resdifftmp resimagestmp res1tmp res2tmp] = ... condstat(formula, g.naccu, g.alpha, {'both' 'upper'}, { '' g.condboot}, ... { alltfX1power(indarr,:,:) alltfX2power(indarr,:,:) }, {alltfX1(indarr,:,:) alltfX2(indarr,:,:)}); resdiff{1}(indarr,:) = resdifftmp{1}; resdiff{2}(indarr,:) = resdifftmp{2}; resimages{1}(indarr,:,:) = resimagestmp{1}; resimages{2}(indarr,:,:) = resimagestmp{2}; res1{1}(indarr,:) = res1tmp{1}; res1{2}(indarr,:) = res1tmp{2}; res2{1}(indarr,:) = res2tmp{1}; res2{2}(indarr,:) = res2tmp{2}; end; else alltfXpower = { alltfX1power alltfX2power }; alltfX = { alltfX1 alltfX2 }; alltfXabs = { alltfX1abs alltfX2abs }; [resdiff resimages res1 res2] = condstat(formula, g.naccu, g.alpha, {'both' 'upper'}, { '' g.condboot}, alltfXpower, alltfX, alltfXabs); end; case 'phasecoher2', % normalize first to speed up %formula = { formula{1} ['sum(arg2(:,:,data),3)./sum(arg3(:,:,data),3)'] }; % toby 10/3/2006 formula = { formula{1} ['sum(arg2(:,:,X),3)./sum(arg3(:,:,X),3)'] }; alltfX1abs = sqrt(alltfX1power); % these 2 lines can be suppressed alltfX2abs = sqrt(alltfX2power); % by inserting sqrt(arg1(:,:,data)) instead of arg3(:,:,data)) if strcmpi(g.lowmem, 'on') for ind = 1:2:size(alltfX1abs,1) if ind == size(alltfX1,1), indarr = ind; else indarr = [ind:ind+1]; end; [resdifftmp resimagestmp res1tmp res2tmp] = ... condstat(formula, g.naccu, g.alpha, {'both' 'upper'}, { '' g.condboot}, ... { alltfX1power(indarr,:,:) alltfX2power(indarr,:,:) }, {alltfX1(indarr,:,:) ... alltfX2(indarr,:,:)}, { alltfX1abs(indarr,:,:) alltfX2abs(indarr,:,:) }); resdiff{1}(indarr,:) = resdifftmp{1}; resdiff{2}(indarr,:) = resdifftmp{2}; resimages{1}(indarr,:,:) = resimagestmp{1}; resimages{2}(indarr,:,:) = resimagestmp{2}; res1{1}(indarr,:) = res1tmp{1}; res1{2}(indarr,:) = res1tmp{2}; res2{1}(indarr,:) = res2tmp{1}; res2{2}(indarr,:) = res2tmp{2}; end; else alltfXpower = { alltfX1power alltfX2power }; alltfX = { alltfX1 alltfX2 }; alltfXabs = { alltfX1abs alltfX2abs }; [resdiff resimages res1 res2] = condstat(formula, g.naccu, g.alpha, {'both' 'upper'}, { '' g.condboot}, alltfXpower, alltfX, alltfXabs); end; case 'phasecoher', %formula = { formula{1} ['mean(arg2,3)'] }; % toby 10.02.2006 %formula = { formula{1} ['mean(arg2(:,:,data),3)'] }; formula = { formula{1} ['mean(arg2(:,:,X),3)'] }; if strcmpi(g.lowmem, 'on') for ind = 1:2:size(alltfX1,1) if ind == size(alltfX1,1), indarr = ind; else indarr = [ind:ind+1]; end; alltfX1norm = alltfX1(indarr,:,:)./sqrt(alltfX1(indarr,:,:).*conj(alltfX1(indarr,:,:))); alltfX2norm = alltfX2(indarr,:,:)./sqrt(alltfX2(indarr,:,:).*conj(alltfX2(indarr,:,:))); alltfXpower = { alltfX1power(indarr,:,:) alltfX2power(indarr,:,:) }; alltfXnorm = { alltfX1norm alltfX2norm }; [resdifftmp resimagestmp res1tmp res2tmp] = ... condstat(formula, g.naccu, g.alpha, {'both' 'both'}, { '' g.condboot}, ... alltfXpower, alltfXnorm); resdiff{1}(indarr,:) = resdifftmp{1}; resdiff{2}(indarr,:) = resdifftmp{2}; resimages{1}(indarr,:,:) = resimagestmp{1}; resimages{2}(indarr,:,:) = resimagestmp{2}; res1{1}(indarr,:) = res1tmp{1}; res1{2}(indarr,:) = res1tmp{2}; res2{1}(indarr,:) = res2tmp{1}; res2{2}(indarr,:) = res2tmp{2}; end; else alltfX1norm = alltfX1./sqrt(alltfX1.*conj(alltfX1)); alltfX2norm = alltfX2./sqrt(alltfX2.*conj(alltfX2)); % maybe have to suppress preprocessing -> lot of memory alltfXpower = { alltfX1power alltfX2power }; alltfXnorm = { alltfX1norm alltfX2norm }; [resdiff resimages res1 res2] = condstat(formula, g.naccu, g.alpha, {'both' 'both'}, { '' g.condboot}, ... alltfXpower, alltfXnorm); end; end; % same as below: plottimef(P1-P2, R2-R1, 10*resimages{1}, resimages{2}, mean(data{1},2)-mean(data{2},2), freqs, times, mbase, g); if strcmpi(g.plotersp, 'on') | strcmpi(g.plotitc, 'on') g.erspmax = []; % auto scale g.itcmax = []; % auto scale plottimef(10*resdiff{1}, resdiff{2}, 10*resimages{1}, resimages{2}, ... mean(data{1},2)-mean(data{2},2), freqs, timesout, meanmbase, [], [], g); end; R1 = res1{2}; R2 = res2{2}; Rdiff = resdiff{2}; Pboot = { Pboot1 Pboot2 10*resimages{1} }; Rboot = { Rboot1 Rboot2 resimages{2} }; end; P = { P1 P2 P1-P2 }; R = { R1 R2 Rdiff }; if nargout >= 8, alltfX = { alltfX1 alltfX2 }; end; return; % ********************************** END FOR MULTIPLE CONDITIONS end; %%%%%%%%%%%%%%%%%%%%%% % display text to user (computation perfomed only for display) %%%%%%%%%%%%%%%%%%%%%% verboseprintf(g.verbose, 'Computing Event-Related Spectral Perturbation (ERSP) and\n'); switch g.type case 'phasecoher', verboseprintf(g.verbose, ' Inter-Trial Phase Coherence (ITC) images based on %d trials\n',trials); case 'phasecoher2', verboseprintf(g.verbose, ' Inter-Trial Phase Coherence 2 (ITC) images based on %d trials\n',trials); case 'coher', verboseprintf(g.verbose, ' Linear Inter-Trial Coherence (ITC) images based on %d trials\n',trials); end; verboseprintf(g.verbose, ' of %d frames sampled at %g Hz.\n',g.frames,g.srate); verboseprintf(g.verbose, 'Each trial contains samples from %1.0f ms before to\n',g.tlimits(1)); verboseprintf(g.verbose, ' %1.0f ms after the timelocking event.\n',g.tlimits(2)); if ~isnan(g.alpha) verboseprintf(g.verbose, 'Only significant values (permutation statistics p<%g) will be colored;\n',g.alpha) verboseprintf(g.verbose, ' non-significant values will be plotted in green\n'); end verboseprintf(g.verbose,' Image frequency direction: %s\n',g.hzdir); if isempty(g.precomputed) % ----------------------------------------- % detrend over epochs (trials) if requested % ----------------------------------------- if strcmpi(g.rmerp, 'on') if ndims(data) == 2 data = data - mean(data,2)*ones(1, length(data(:))/g.frames); else data = data - repmat(mean(data,3), [1 1 trials]); end; end; % ---------------------------------------------------- % compute time frequency decompositions, power and ITC % ---------------------------------------------------- if length(g.timesout) > 1, tmioutopt = { 'timesout' , g.timesout }; elseif ~isempty(g.ntimesout) tmioutopt = { 'ntimesout', g.ntimesout }; else tmioutopt = { 'ntimesout', g.timesout }; end; [alltfX freqs timesout R] = timefreq(data, g.srate, tmioutopt{:}, ... 'winsize', g.winsize, 'tlimits', g.tlimits, 'detrend', g.detrend, ... 'itctype', g.type, 'wavelet', g.cycles, 'verbose', g.verbose, ... 'padratio', g.padratio, 'freqs', g.freqs, 'freqscale', g.freqscale, ... 'nfreqs', g.nfreqs, 'timestretch', {g.timeStretchMarks', g.timeStretchRefs}, timefreqopts{:}); else alltfX = g.precomputed.tfdata; timesout = g.precomputed.times; freqs = g.precomputed.freqs; if strcmpi(g.precomputed.recompute, 'ersp') R = []; else switch g.itctype case 'coher', R = alltfX ./ repmat(sqrt(sum(alltfX .* conj(alltfX),3) * size(alltfX,3)), [1 1 size(alltfX,3)]); case 'phasecoher2', R = alltfX ./ repmat(sum(sqrt(alltfX .* conj(alltfX)),3), [1 1 size(alltfX,3)]); case 'phasecoher', R = alltfX ./ sqrt(alltfX .* conj(alltfX)); end; P = []; mbase = []; return; end; end; if g.cycles(1) == 0 alltfX = 2/0.375*alltfX/g.winsize; % TF and MC (12/11/2006): normalization, divide by g.winsize P = alltfX.*conj(alltfX); % power % TF and MC (12/14/2006): multiply by 2 account for negative frequencies, % and ounteract the reduction by a factor 0.375 that occurs as a result of % cosine (Hann) tapering. Refer to Bug 446 % Modified again 04/29/2011 due to comment in bug 1032 else P = alltfX.*conj(alltfX); % power for wavelets end; % --------------- % baseline length % --------------- if size(g.baseline,2) == 2 baseln = []; for index = 1:size(g.baseline,1) tmptime = find(timesout >= g.baseline(index,1) & timesout <= g.baseline(index,2)); baseln = union_bc(baseln, tmptime); end; if length(baseln)==0 error( [ 'There are no sample points found in the default baseline.' 10 ... 'This may happen even though data time limits overlap with' 10 ... 'the baseline period (because of the time-freq. window width).' 10 ... 'Either disable the baseline, change the baseline limits.' ] ); end else if ~isempty(find(timesout < g.baseline)) baseln = find(timesout < g.baseline); % subtract means of pre-0 (centered) windows else baseln = 1:length(timesout); % use all times as baseline end end; if ~isnan(g.alpha) && length(baseln)==0 verboseprintf(g.verbose, 'timef(): no window centers in baseline (times<%g) - shorten (max) window length.\n', g.baseline) return end % ----------------------------------------- % remove baseline on a trial by trial basis % ----------------------------------------- if strcmpi(g.trialbase, 'on'), tmpbase = baseln; else tmpbase = 1:size(P,2); % full baseline end; if ndims(P) == 4 if ~strcmpi(g.trialbase, 'off') && isnan( g.powbase(1) ) mbase = mean(P(:,:,tmpbase,:),3); if strcmpi(g.basenorm, 'on') mstd = std(P(:,:,tmpbase,:),[],3); P = bsxfun(@rdivide, bsxfun(@minus, P, mbase), mstd); else P = bsxfun(@rdivide, P, mbase); end; end; else if ~strcmpi(g.trialbase, 'off') && isnan( g.powbase(1) ) mbase = mean(P(:,tmpbase,:),2); if strcmpi(g.basenorm, 'on') mstd = std(P(:,tmpbase,:),[],2); P = (P-repmat(mbase,[1 size(P,2) 1]))./repmat(mstd,[1 size(P,2) 1]); % convert to log then back to normal else P = P./repmat(mbase,[1 size(P,2) 1]); %P = 10 .^ (log10(P) - repmat(log10(mbase),[1 size(P,2) 1])); % same as above end; end; end; if ~isempty(g.precomputed) return; % return single trial power end; % ----------------------- % compute baseline values % ----------------------- if isnan(g.powbase(1)) verboseprintf(g.verbose, 'Computing the mean baseline spectrum\n'); if ndims(P) == 4 if ndims(P) > 3, Pori = mean(P, 4); else Pori = P; end; mbase = mean(Pori(:,:,baseln),3); else if ndims(P) > 2, Pori = mean(P, 3); else Pori = P; end; mbase = mean(Pori(:,baseln),2); end; else verboseprintf(g.verbose, 'Using the input baseline spectrum\n'); mbase = g.powbase; if strcmpi(g.scale, 'log'), mbase = 10.^(mbase/10); end; if size(mbase,1) == 1 % if input was a row vector, flip to be a column mbase = mbase'; end; end baselength = length(baseln); % ------------------------- % remove baseline (average) % ------------------------- % original ERSP baseline removal if ~strcmpi(g.trialbase, 'on') if ~isnan( g.baseline(1) ) && any(~isnan( mbase(1) )) && strcmpi(g.basenorm, 'off') P = bsxfun(@rdivide, P, mbase); % use single trials % ERSP baseline normalized elseif ~isnan( g.baseline(1) ) && ~isnan( mbase(1) ) && strcmpi(g.basenorm, 'on') if ndims(Pori) == 3, mstd = std(Pori(:,:,baseln),[],3); else mstd = std(Pori(:,baseln),[],2); end; P = bsxfun(@rdivide, bsxfun(@minus, P, mbase), mstd); end; end; % ---------------- % phase amp option % ---------------- if strcmpi(g.phsamp, 'on') disp( 'phsamp option is deprecated'); % switch g.phsamp % case 'on' %PA = zeros(size(P,1),size(P,1),g.timesout); % NB: (freqs,freqs,times) % $$$ end % phs amp %PA (freq x freq x time) %PA(:,:,j) = PA(:,:,j) + (tmpX ./ abs(tmpX)) * ((P(:,j)))'; % x-product: unit phase column % times amplitude row %tmpcx(1,:,:) = cumulX; % allow ./ below %for jj=1:g.timesout % PA(:,:,jj) = PA(:,:,jj) ./ repmat(P(:,jj)', [size(P,1) 1]); %end end % --------- % bootstrap % --------- % this ensures that if bootstrap limits provided that no % 'alpha' won't prevent application of the provided limits if ~isnan(g.alpha) | ~isempty(find(~isnan(g.pboot))) | ~isempty(find(~isnan(g.rboot)))% if bootstrap analysis requested . . . % ERSP bootstrap % -------------- if ~isempty(find(~isnan(g.pboot))) % if ERSP bootstrap limits provided already Pboot = g.pboot(:); else if size(g.baseboot,2) == 1 if g.baseboot == 0, baselntmp = []; elseif ~isnan(g.baseline(1)) baselntmp = baseln; else baselntmp = find(timesout <= 0); % if it is empty use whole epoch end; else baselntmp = []; for index = 1:size(g.baseboot,1) tmptime = find(timesout >= g.baseboot(index,1) & timesout <= g.baseboot(index,2)); if isempty(tmptime), fprintf('Warning: empty baseline interval [%3.2f %3.2f]\n', g.baseboot(index,1), g.baseboot(index,2)); end; baselntmp = union_bc(baselntmp, tmptime); end; end; if prod(size(g.baseboot)) > 2 fprintf('Permutation statistics will use data in multiple selected windows.\n'); elseif size(g.baseboot,2) == 2 fprintf('Permutation statistics will use data in range %3.2g-%3.2g ms.\n', g.baseboot(1), g.baseboot(2)); elseif g.baseboot fprintf(' %d permutation statistics windows in baseline (times<%g).\n', length(baselntmp), g.baseboot) end; % power significance % ------------------ if strcmpi(g.boottype, 'shuffle') formula = 'mean(arg1,3);'; [ Pboot Pboottrialstmp Pboottrials] = bootstat(P, formula, 'boottype', 'shuffle', ... 'label', 'ERSP', 'bootside', 'both', 'naccu', g.naccu, ... 'basevect', baselntmp, 'alpha', g.alpha, 'dimaccu', 2 ); clear Pboottrialstmp; else center = 0; if strcmpi(g.basenorm, 'off'), center = 1; end; % bootstrap signs Pboottmp = P; Pboottrials = zeros([ size(P,1) size(P,2) g.naccu ]); for index = 1:g.naccu Pboottmp = (Pboottmp-center).*(ceil(rand(size(Pboottmp))*2-1)*2-1)+center; Pboottrials(:,:,index) = mean(Pboottmp,3); end; Pboot = []; end; if size(Pboot,2) == 1, Pboot = Pboot'; end; end; % ITC bootstrap % ------------- if ~isempty(find(~isnan(g.rboot))) % if itc bootstrap provided Rboot = g.rboot; else if ~isempty(find(~isnan(g.pboot))) % if ERSP limits were provided (but ITC not) if size(g.baseboot,2) == 1 if g.baseboot == 0, baselntmp = []; elseif ~isnan(g.baseline(1)) baselntmp = baseln; else baselntmp = find(timesout <= 0); % if it is empty use whole epoch end; else baselntmp = []; for index = 1:size(g.baseboot,1) tmptime = find(timesout >= g.baseboot(index,1) && timesout <= g.baseboot(index,2)); if isempty(tmptime), fprintf('Warning: empty baseline interval [%3.2f %3.2f]\n', g.baseboot(index,1), g.baseboot(index,2)); end; baselntmp = union_bc(baselntmp, tmptime); end; end; if prod(size(g.baseboot)) > 2 fprintf('Permutation statistics will use data in multiple selected windows.\n'); elseif size(g.baseboot,2) == 2 fprintf('Permutation statistics will use data in range %3.2g-%3.2g ms.\n', g.baseboot(1), g.baseboot(2)); elseif g.baseboot fprintf(' %d permutation statistics windows in baseline (times<%g).\n', length(baselntmp), g.baseboot) end; end; % ITC significance % ---------------- inputdata = alltfX; switch g.type case 'coher', formula = [ 'sum(arg1,3)./sqrt(sum(arg1.*conj(arg1),3))/ sqrt(' int2str(size(alltfX,3)) ');' ]; case 'phasecoher', formula = [ 'mean(arg1,3);' ]; inputdata = alltfX./sqrt(alltfX.*conj(alltfX)); case 'phasecoher2', formula = [ 'sum(arg1,3)./sum(sqrt(arg1.*conj(arg1)),3);' ]; end; if strcmpi(g.boottype, 'randall'), dimaccu = []; g.boottype = 'rand'; else dimaccu = 2; end; [Rboot Rboottmp Rboottrials] = bootstat(inputdata, formula, 'boottype', g.boottype, ... 'label', 'ITC', 'bootside', 'upper', 'naccu', g.naccu, ... 'basevect', baselntmp, 'alpha', g.alpha, 'dimaccu', 2 ); fprintf('\n'); clear Rboottmp; end; else Pboot = []; Rboot = []; end % average the power % ----------------- PA = P; if ndims(P) == 4, P = mean(P, 4); elseif ndims(P) == 3, P = mean(P, 3); end; % correction for multiple comparisons % ----------------------------------- maskersp = []; maskitc = []; if ~isnan(g.alpha) if isempty(find(~isnan(g.pboot))) % if ERSP lims not provided if ndims(Pboottrials) < 3, Pboottrials = Pboottrials'; end; exactp_ersp = compute_pvals(P, Pboottrials); if strcmpi(g.mcorrect, 'fdr') alphafdr = fdr(exactp_ersp, g.alpha); if alphafdr ~= 0 fprintf('ERSP correction for multiple comparisons using FDR, alpha_fdr = %3.6f\n', alphafdr); else fprintf('ERSP correction for multiple comparisons using FDR, nothing significant\n', alphafdr); end; maskersp = exactp_ersp <= alphafdr; else maskersp = exactp_ersp <= g.alpha; end; end; if isempty(find(~isnan(g.rboot))) % if ITC lims not provided exactp_itc = compute_pvals(abs(R), abs(Rboottrials')); if strcmpi(g.mcorrect, 'fdr') alphafdr = fdr(exactp_itc, g.alpha); if alphafdr ~= 0 fprintf('ITC correction for multiple comparisons using FDR, alpha_fdr = %3.6f\n', alphafdr); else fprintf('ITC correction for multiple comparisons using FDR, nothing significant\n', alphafdr); end; maskitc = exactp_itc <= alphafdr; else maskitc = exactp_itc <= g.alpha; end end; end; % convert to log if necessary % --------------------------- if strcmpi(g.scale, 'log') if ~isnan( g.baseline(1) ) && ~isnan( mbase(1) ) && strcmpi(g.trialbase, 'off'), mbase = log10(mbase)*10; end; P = 10 * log10(P); if ~isempty(Pboot) Pboot = 10 * log10(Pboot); end; end; if isempty(Pboot) && exist('maskersp') Pboot = maskersp; end; % auto scalling % ------------- if isempty(g.erspmax) g.erspmax = [max(max(abs(P)))]/2; if strcmpi(g.scale, 'abs') && strcmpi(g.basenorm, 'off') % % of baseline g.erspmax = [max(max(abs(P)))]; if g.erspmax > 1 g.erspmax = [1-(g.erspmax-1) g.erspmax]; else g.erspmax = [g.erspmax 1+(1-g.erspmax)]; end; end; %g.erspmax = [-g.erspmax g.erspmax]+1; end; % -------- % plotting % -------- if strcmpi(g.plotersp, 'on') || strcmpi(g.plotitc, 'on') if ndims(P) == 3 P = squeeze(P(2,:,:,:)); R = squeeze(R(2,:,:,:)); mbase = squeeze(mbase(2,:)); ERP = mean(squeeze(data(1,:,:)),2); else ERP = mean(data,2); end; if strcmpi(g.plottype, 'image') plottimef(P, R, Pboot, Rboot, ERP, freqs, timesout, mbase, maskersp, maskitc, g); else plotallcurves(P, R, Pboot, Rboot, ERP, freqs, timesout, mbase, g); end; end; % -------------- % format outputs % -------------- if strcmpi(g.outputformat, 'old') R = abs(R); % convert coherence vector to magnitude if strcmpi(g.scale, 'log'), mbase = 10^(mbase/10); end; end; if strcmpi(g.verbose, 'on') disp('Note: Add output variables to command line call in history to'); disp(' retrieve results and use the tftopo function to replot them'); end; mbase = mbase'; if ~isempty(g.caption) h = textsc(g.caption, 'title'); set(h, 'FontWeight', 'bold'); end return; % ----------------- % plotting function % ----------------- function g = plottimef(P, R, Pboot, Rboot, ERP, freqs, times, mbase, maskersp, maskitc, g); persistent showwarning; if isempty(showwarning) warning( [ 'Some versions of Matlab crash on this function. If this is' 10 ... 'the case, simply comment the code line 1655-1673 in newtimef.m' 10 ... 'which aims at "ploting marginal ERSP mean below ERSP image"' ]); showwarning = 1; end; % % compute ERP % ERPtimes = [g.tlimits(1):(g.tlimits(2)-g.tlimits(1))/(g.frames-1):g.tlimits(2)+0.000001]; ERPindices = zeros(1, length(times)); for ti=1:length(times) [tmp ERPindices(ti)] = min(abs(ERPtimes-times(ti))); end ERPtimes = ERPtimes(ERPindices); % subset of ERP frames on t/f window centers ERP = ERP(ERPindices); if ~isreal(R) Rangle = angle(R); Rsign = sign(imag(R)); R = abs(R); % convert coherence vector to magnitude setylim = 1; else Rangle = zeros(size(R)); % Ramon: if isreal(R) then we get an error because Rangle does not exist Rsign = ones(size(R)); setylim = 0; end; switch lower(g.plotitc) case 'on', switch lower(g.plotersp), case 'on', ordinate1 = 0.67; ordinate2 = 0.1; height = 0.33; g.plot = 1; case 'off', ordinate2 = 0.1; height = 0.9; g.plot = 1; end; case 'off', ordinate1 = 0.1; height = 0.9; switch lower(g.plotersp), case 'on', ordinate1 = 0.1; height = 0.9; g.plot = 1; case 'off', g.plot = 0; end; end; if g.plot % verboseprintf(g.verbose, '\nNow plotting...\n'); set(gcf,'DefaultAxesFontSize',g.AXES_FONT) colormap(jet(256)); pos = get(gca,'position'); q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; axis off; end; switch lower(g.plotersp) case 'on' % %%%%%%% image the ERSP %%%%%%%%%%%%%%%%%%%%%%%%%% % h(1) = axes('Position',[.1 ordinate1 .9 height].*s+q); set(h(1), 'tag', 'ersp'); PP = P; if strcmpi(g.scale, 'abs') && strcmpi(g.basenorm, 'off') baseval = 1; else baseval = 0; end; if ~isnan(g.alpha) if strcmpi(g.pcontour, 'off') && ~isempty(maskersp) % zero out nonsignif. power differences PP(~maskersp) = baseval; %PP = PP .* maskersp; elseif isempty(maskersp) if size(PP,1) == size(Pboot,1) && size(PP,2) == size(Pboot,2) PP(find(PP > Pboot(:,:,1) & (PP < Pboot(:,:,2)))) = baseval; Pboot = squeeze(mean(Pboot,2)); if size(Pboot,2) == 1, Pboot = Pboot'; end; else PP(find((PP > repmat(Pboot(:,1),[1 length(times)])) ... & (PP < repmat(Pboot(:,2),[1 length(times)])))) = baseval; end end; end; % find color limits % ----------------- if isempty(g.erspmax) if g.ERSP_CAXIS_LIMIT == 0 g.erspmax = [-1 1]*1.1*max(max(abs(P(:,:)))); else g.erspmax = g.ERSP_CAXIS_LIMIT*[-1 1]; end elseif length(g.erspmax) == 1 g.erspmax = [ -g.erspmax g.erspmax]; end if isnan( g.baseline(1) ) && g.erspmax(1) < 0 g.erspmax = [ min(min(P(:,:))) max(max(P(:,:)))]; end; % plot image % ---------- if ~strcmpi(g.freqscale, 'log') imagesc(times,freqs,PP(:,:), g.erspmax); else imagesclogy(times,freqs,PP(:,:),g.erspmax); end; set(gca,'ydir',g.hzdir); % make frequency ascend or descend % put contour for multiple comparison masking if ~isempty(maskersp) && strcmpi(g.pcontour, 'on') hold on; [tmpc tmph] = contour(times, freqs, maskersp); set(tmph, 'linecolor', 'k', 'linewidth', 0.25) end; hold on plot([0 0],[0 freqs(end)],'--m','LineWidth',g.linewidth); % plot time 0 if ~isnan(g.marktimes) % plot marked time for mt = g.marktimes(:)' plot([mt mt],[0 freqs(end)],'--k','LineWidth',g.linewidth); end end hold off set(h(1),'YTickLabel',[],'YTick',[]) set(h(1),'XTickLabel',[],'XTick',[]) if ~isempty(g.vert) for index = 1:length(g.vert) line([g.vert(index), g.vert(index)], [min(freqs) max(freqs)], 'linewidth', 1, 'color', 'm'); end; end; h(2) = gca; h(3) = cbar('vert'); % ERSP colorbar axes set(h(2),'Position',[.1 ordinate1 .8 height].*s+q) set(h(3),'Position',[.95 ordinate1 .05 height].*s+q) title([ 'ERSP(' g.unitpower ')' ]) % %%%%% plot marginal ERSP mean below ERSP image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % h(4) = axes('Position',[.1 ordinate1-0.1 .8 .1].*s+q); E = [min(P(:,:),[],1);max(P(:,:),[],1)]; % plotting limits if isempty(g.erspmarglim) g.erspmarglim = [min(E(1,:))-max(max(abs(E)))/3 max(E(2,:))+max(max(abs(E)))/3]; end; plot(times,E,[0 0],g.erspmarglim, '--m','LineWidth',g.linewidth) xlim([min(times) max(times)]) ylim(g.erspmarglim) tick = get(h(4),'YTick'); set(h(4),'YTick',[tick(1) ; tick(end)]) set(h(4),'YAxisLocation','right') set(h(4),'TickLength',[0.020 0.025]); xlabel('Time (ms)') ylabel(g.unitpower) % %%%%% plot mean spectrum to left of ERSP image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % h(5) = axes('Position',[0 ordinate1 .1 height].*s+q); if isnan(g.baseline) % Ramon :for bug 1657 E = zeros(size(freqs)); else E = mbase; end if ~isnan(E(1)) % plotting limits if isempty(g.speclim) % g.speclim = [min(E)-max(abs(E))/3 max(E)+max(abs(E))/3]; if all(~isnan(mbase)) g.speclim = [min(mbase)-max(abs(mbase))/3 max(mbase)+max(abs(mbase))/3]; % RMC: Just for plotting else g.speclim = [min(E)-max(abs(E))/3 max(E)+max(abs(E))/3]; end end; % plot curves if ~strcmpi(g.freqscale, 'log') plot(freqs,E,'LineWidth',g.linewidth); hold on; if ~isnan(g.alpha) && size(Pboot,2) == 2 try plot(freqs,Pboot(:,:)'+[E;E], 'g', 'LineWidth',g.linewidth) plot(freqs,Pboot(:,:)'+[E;E], 'k:','LineWidth',g.linewidth) catch plot(freqs,Pboot(:,:)+[E E], 'g', 'LineWidth',g.linewidth) plot(freqs,Pboot(:,:)+[E E], 'k:','LineWidth',g.linewidth) end; end if freqs(1) ~= freqs(end), xlim([freqs(1) freqs(end)]); end; if g.speclim(1) ~= g.speclim(2), ylim(g.speclim); end; % Ramon :for bug 1657 else % 'log' semilogx(freqs,E,'LineWidth',g.linewidth); hold on; if ~isnan(g.alpha) try semilogx(freqs,Pboot(:,:)'+[E;E],'g', 'LineWidth',g.linewidth) semilogx(freqs,Pboot(:,:)'+[E;E],'k:','LineWidth',g.linewidth) catch semilogx(freqs,Pboot(:,:)+[E E],'g', 'LineWidth',g.linewidth) semilogx(freqs,Pboot(:,:)+[E E],'k:','LineWidth',g.linewidth) end; end if freqs(1) ~= freqs(end), xlim([freqs(1) freqs(end)]); end; if g.speclim(1) ~= g.speclim(2), ylim(g.speclim); end; %RMC set(h(5),'View',[90 90]) divs = linspace(log(freqs(1)), log(freqs(end)), 10); set(gca, 'xtickmode', 'manual'); divs = ceil(exp(divs)); divs = unique_bc(divs); % ceil is critical here, round might misalign set(gca, 'xtick', divs); end; set(h(5),'TickLength',[0.020 0.025]); set(h(5),'View',[90 90]) xlabel('Frequency (Hz)') if strcmp(g.hzdir,'normal') set(gca,'xdir','reverse'); else set(gca,'xdir','normal'); end ylabel(g.unitpower) tick = get(h(5),'YTick'); if (length(tick)>2) set(h(5),'YTick',[tick(1) ; tick(end-1)]) end end; end; switch lower(g.plotitc) case 'on' % %%%%%%%%%%%% Image the ITC %%%%%%%%%%%%%%%%%% % h(6) = axes('Position',[.1 ordinate2 .9 height].*s+q); % ITC image if ishandle(h(1));set(h(1), 'tag', 'itc');end; if abs(R(1,1)-1) < 0.0001, g.plotphaseonly = 'on'; end; if strcmpi(g.plotphaseonly, 'on') RR = Rangle/pi*180; else RR = R; end; if ~isnan(g.alpha) if ~isempty(maskitc) && strcmpi(g.pcontour, 'off') RR = RR .* maskitc; elseif isempty(maskitc) if size(RR,1) == size(Rboot,1) && size(RR,2) == size(Rboot,2) tmp = gcf; if size(Rboot,3) == 2 RR(find(RR > Rboot(:,:,1) & RR < Rboot(:,:,2))) = 0; else RR(find(RR < Rboot)) = 0; end; Rboot = mean(Rboot(:,:,end),2); else RR(find(RR < repmat(Rboot(:),[1 length(times)]))) = 0; end; end; end if g.ITC_CAXIS_LIMIT == 0 coh_caxis = min(max(max(R(:,:))),1)*[-1 1]; % 1 WAS 0.4 ! else coh_caxis = g.ITC_CAXIS_LIMIT*[-1 1]; end if strcmpi(g.plotphaseonly, 'on') if ~strcmpi(g.freqscale, 'log') imagesc(times,freqs,RR(:,:)); % <--- else imagesclogy(times,freqs,RR(:,:)); % <--- end; g.itcmax = [-180 180]; setylim = 0; else if max(coh_caxis) == 0, % toby 10.02.2006 coh_caxis = [-1 1]; end if ~strcmpi(g.freqscale, 'log') if exist('Rsign') && strcmp(g.plotphasesign, 'on') imagesc(times,freqs,Rsign(:,:).*RR(:,:),coh_caxis); % <--- else imagesc(times,freqs,RR(:,:),coh_caxis); % <--- end else if exist('Rsign') && strcmp(g.plotphasesign, 'on') imagesclogy(times,freqs,Rsign(:,:).*RR(:,:),coh_caxis); % <--- else imagesclogy(times,freqs,RR(:,:),coh_caxis); % <--- end end; end; set(gca,'ydir',g.hzdir); % make frequency ascend or descend % plot contour if necessary if ~isempty(maskitc) && strcmpi(g.pcontour, 'on') hold on; [tmpc tmph] = contour(times, freqs, maskitc); set(tmph, 'linecolor', 'k', 'linewidth', 0.25) end; if isempty(g.itcmax) g.itcmax = caxis; elseif length(g.itcmax) == 1 g.itcmax = [ -g.itcmax g.itcmax ]; end; caxis(g.itcmax); hold on plot([0 0],[0 freqs(end)],'--m','LineWidth',g.linewidth); if ~isnan(g.marktimes) for mt = g.marktimes(:)' plot([mt mt],[0 freqs(end)],'--k','LineWidth',g.linewidth); end end hold off set(h(6),'YTickLabel',[],'YTick',[]) set(h(6),'XTickLabel',[],'XTick',[]) if ~isempty(g.vert) for index = 1:length(g.vert) line([g.vert(index), g.vert(index)], [min(freqs) max(freqs)], 'linewidth', 1, 'color', 'm'); end; end; h(7) = gca; h(8) = cbar('vert'); %h(9) = get(h(8),'Children'); % make the function crash set(h(7),'Position',[.1 ordinate2 .8 height].*s+q) set(h(8),'Position',[.95 ordinate2 .05 height].*s+q) if setylim set(h(8),'YLim',[0 g.itcmax(2)]); end; if strcmpi(g.plotphaseonly, 'on') title('ITC phase') else title('ITC') end; % %%%%% plot the ERP below the ITC image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % h(10) = axes('Position',[.1 ordinate2-0.1 .8 .1].*s+q); % ERP if isempty(g.erplim) ERPmax = max(ERP); ERPmin = min(ERP); g.erplim = [ ERPmin - 0.1*(ERPmax-ERPmin) ERPmax + 0.1*(ERPmax-ERPmin) ]; end; plot(ERPtimes,ERP, [0 0],g.erplim,'--m','LineWidth',g.linewidth); hold on; plot([times(1) times(length(times))],[0 0], 'k'); xlim([min(ERPtimes) max(ERPtimes)]); ylim(g.erplim) set(gca,'ydir',g.ydir); tick = get(h(10),'YTick'); set(h(10),'YTick',[tick(1) ; tick(end)]) set(h(10),'TickLength',[0.02 0.025]); set(h(10),'YAxisLocation','right') xlabel('Time (ms)') ylabel('\muV') if (~isempty(g.topovec)) if length(g.topovec) ~= 1, ylabel(''); end; % ICA component end; E = nan_mean(R(:,:)'); % don't let a few NaN's crash this % %%%%% plot the marginal mean left of the ITC image %%%%%%%%%%%%%%%%%%%%% % h(11) = axes('Position',[0 ordinate2 .1 height].*s+q); % plot the marginal mean % ITC left of the ITC image % set plotting limits if isempty(g.itcavglim) if ~isnan(g.alpha) g.itcavglim = [ min(E)-max(E)/3 max(Rboot)+max(Rboot)/3]; else g.itcavglim = [ min(E)-max(E)/3 max(E)+max(E)/3]; end; end; if max(g.itcavglim) == 0 || any(isnan(g.itcavglim)) g.itcavglim = [-1 1]; end % plot marginal ITC if ~strcmpi(g.freqscale, 'log') plot(freqs,E,'LineWidth',g.linewidth); hold on; if ~isnan(g.alpha) plot(freqs,Rboot,'g', 'LineWidth',g.linewidth) plot(freqs,Rboot,'k:','LineWidth',g.linewidth) end if freqs(1) ~= freqs(end), xlim([freqs(1) freqs(end)]); end ylim(g.itcavglim) else semilogx(freqs,E,'LineWidth',g.linewidth); hold on; if ~isnan(g.alpha) semilogx(freqs,Rboot(:),'g', 'LineWidth',g.linewidth) semilogx(freqs,Rboot(:),'k:','LineWidth',g.linewidth) end if freqs(1) ~= freqs(end), xlim([freqs(1) freqs(end)]); end; ylim(g.itcavglim) divs = linspace(log(freqs(1)), log(freqs(end)), 10); set(gca, 'xtickmode', 'manual'); divs = ceil(exp(divs)); divs = unique_bc(divs); % ceil is critical here, round might misalign set(gca, 'xtick', divs); end; % ITC plot details tick = get(h(11),'YTick'); if length(tick) > 1 set(h(11),'YTick',[tick(1) ; tick(length(tick))]) end; set(h(11),'View',[90 90]) %set(h(11),'TickLength',[0.020 0.025]); xlabel('Frequency (Hz)') if strcmp(g.hzdir,'normal') set(gca,'xdir','reverse'); else set(gca,'xdir','normal'); end ylabel('ERP') end; %switch % %%%%%%%%%%%%%%% plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) && strcmpi(g.plotitc, 'on') && strcmpi(g.plotersp, 'on') if strcmp(g.plotersp,'off') h(12) = axes('Position',[-.207 .95 .2 .14].*s+q); % place the scalp map at top-left else h(12) = axes('Position',[-.1 .43 .2 .14].*s+q); % place the scalp map at middle-left end; if length(g.topovec) == 1 topoplot(g.topovec,g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10, 'chaninfo', g.chaninfo); else topoplot(g.topovec,g.elocs,'electrodes','off', 'chaninfo', g.chaninfo); end; axis('square') end if g.plot try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) && ~iscell(g.title) axes('Position',pos,'Visible','Off'); h(13) = text(-.05,1.01,g.title); set(h(13),'VerticalAlignment','bottom') set(h(13),'HorizontalAlignment','left') set(h(13),'FontSize',g.TITLE_FONT); end try, axcopy(gcf); catch, end; end; % --------------- % Plotting curves % --------------- function plotallcurves(P, R, Pboot, Rboot, ERP, freqs, times, mbase, g); if ~isreal(R) Rangle = angle(R); R = abs(R); % convert coherence vector to magnitude setylim = 1; else Rangle = zeros(size(R)); % Ramon: if isreal(R) then we get an error because Rangle does not exist Rsign = ones(size(R)); setylim = 0; end; if strcmpi(g.plotitc, 'on') | strcmpi(g.plotersp, 'on') verboseprintf(g.verbose, '\nNow plotting...\n'); pos = get(gca,'position'); q = [pos(1) pos(2) 0 0]; s = [pos(3) pos(4) pos(3) pos(4)]; end; % time unit % --------- if times(end) > 10000 times = times/1000; timeunit = 's'; else timeunit = 'ms'; end; if strcmpi(g.plotersp, 'on') % %%%%%%% image the ERSP %%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(g.plotitc, 'on'), subplot(2,1,1); end; set(gca, 'tag', 'ersp'); alllegend = {}; for index = 1:length(freqs) alllegend{index} = [ num2str(freqs(index)) 'Hz baseline ' num2str(mbase(index)) ' dB' ]; end; if strcmpi(g.plotmean, 'on') && freqs(1) ~= freqs(end) alllegend = { alllegend{:} [ num2str(freqs(1)) '-' num2str(freqs(end)) ... 'Hz mean baseline ' num2str(mean(mbase)) ' dB' ] }; end; plotcurve(times, P, 'maskarray', Pboot, 'title', 'ERSP', ... 'xlabel', [ 'Time (' timeunit ')' ], 'ylabel', 'dB', 'ylim', [-g.erspmax g.erspmax], ... 'vert', g.vert, 'marktimes', g.marktimes, 'legend', alllegend, ... 'linewidth', g.linewidth, 'highlightmode', g.highlightmode, 'plotmean', g.plotmean); end; if strcmpi(g.plotitc, 'on') % %%%%%%%%%%%% Image the ITC %%%%%%%%%%%%%%%%%% % if strcmpi(g.plotersp, 'on'), subplot(2,1,2); end; set(gca, 'tag', 'itc'); if abs(R(1,1)-1) < 0.0001, g.plotphaseonly = 'on'; end; if strcmpi(g.plotphaseonly, 'on') % plot ITC phase instead of amplitude (e.g. for continuous data) RR = Rangle/pi*180; else RR = R; end; % find regions of significance % ---------------------------- alllegend = {}; for index = 1:length(freqs) alllegend{index} = [ num2str(freqs(index)) 'Hz baseline ' num2str(mbase(index)) ' dB' ]; end; if strcmpi(g.plotmean, 'on') && freqs(1) ~= freqs(end) alllegend = { alllegend{:} [ num2str(freqs(1)) '-' num2str(freqs(end)) ... 'Hz mean baseline ' num2str(mean(mbase)) ' dB' ] }; end; plotcurve(times, RR, 'maskarray', Rboot, 'val2mask', R, 'title', 'ITC', ... 'xlabel', [ 'Time (' timeunit ')' ], 'ylabel', 'dB', 'ylim', g.itcmax, ... 'vert', g.vert, 'marktimes', g.marktimes, 'legend', alllegend, ... 'linewidth', g.linewidth, 'highlightmode', g.highlightmode, 'plotmean', g.plotmean); end; if strcmpi(g.plotitc, 'on') | strcmpi(g.plotersp, 'on') % %%%%%%%%%%%%%%% plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) h(12) = axes('Position',[-.1 .43 .2 .14].*s+q); if length(g.topovec) == 1 topoplot(g.topovec,g.elocs,'electrodes','off', ... 'style', 'blank', 'emarkersize1chan', 10); else topoplot(g.topovec,g.elocs,'electrodes','off'); end; axis('square') end try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) && ~iscell(g.title) axes('Position',pos,'Visible','Off'); h(13) = text(-.05,1.01,g.title); set(h(13),'VerticalAlignment','bottom') set(h(13),'HorizontalAlignment','left') set(h(13),'FontSize',g.TITLE_FONT); end try, axcopy(gcf); catch, end; end; % %%%%%%%%%%%%%%%%%%%%%%% Highlight regions %%%%%%%%%%%%%%%%%%%%%%%%%% % function highlight(ax, times, regions, highlightmode); color1 = [0.75 0.75 0.75]; color2 = [0 0 0]; yl = ylim; if ~strcmpi(highlightmode, 'background') yl2 = [ yl(1)-(yl(2)-yl(1))*0.15 yl(1)-(yl(2)-yl(1))*0.1 ]; tmph = patch([times(1) times(end) times(end) times(1)], ... [yl2(1) yl2(1) yl2(2) yl2(2)], [1 1 1]); hold on; ylim([ yl2(1) yl(2)]); set(tmph, 'edgecolor', [1 1 1]); end; if ~isempty(regions) axes(ax); in_a_region = 0; for index=1:length(regions) if regions(index) && ~in_a_region tmpreg(1) = times(index); in_a_region = 1; end; if ~regions(index) && in_a_region tmpreg(2) = times(index); in_a_region = 0; if strcmpi(highlightmode, 'background') tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ... [yl(1) yl(1) yl(2) yl(2)], color1); hold on; set(tmph, 'edgecolor', color1); else tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ... [yl2(1) yl2(1) yl2(2) yl2(2)], color2); hold on; set(tmph, 'edgecolor', color2); end; end; end; end; % reshaping data % ----------- function [data, frames] = reshape_data(data, frames) data = squeeze(data); if min(size(data)) == 1 if (rem(length(data),frames) ~= 0) error('Length of data vector must be divisible by frames.'); end data = reshape(data, frames, length(data)/frames); else frames = size(data,1); end function verboseprintf(verbose, varargin) if strcmpi(verbose, 'on') fprintf(varargin{:}); end; % reshaping data % ----------- function pvals = compute_pvals(oridat, surrog, tail) if nargin < 3 tail = 'both'; end; if myndims(oridat) > 1 if size(oridat,2) ~= size(surrog, 2) | myndims(surrog) == 2 if size(oridat,1) == size(surrog, 1) surrog = repmat( reshape(surrog, [size(surrog,1) 1 size(surrog,2)]), [1 size(oridat,2) 1]); elseif size(oridat,2) == size(surrog, 1) surrog = repmat( reshape(surrog, [1 size(surrog,1) size(surrog,2)]), [size(oridat,1) 1 1]); else error('Permutation statistics array size error'); end; end; end; surrog = sort(surrog, myndims(surrog)); % sort last dimension if myndims(surrog) == 1 surrog(end+1) = oridat; elseif myndims(surrog) == 2 surrog(:,end+1) = oridat; elseif myndims(surrog) == 3 surrog(:,:,end+1) = oridat; else surrog(:,:,:,end+1) = oridat; end; [tmp idx] = sort( surrog, myndims(surrog) ); [tmp mx] = max( idx,[], myndims(surrog)); len = size(surrog, myndims(surrog) ); pvals = 1-(mx-0.5)/len; if strcmpi(tail, 'both') pvals = min(pvals, 1-pvals); pvals = 2*pvals; end; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;
github
lcnbeapp/beapp-master
rspdfsolv.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/rspdfsolv.m
2,680
utf_8
f54da2906c104216b972ff3b6bbf6f3e
% rspdfsolv() - sub-function used by rsfit() to searc for optimal % parameter for Ramberg-Schmeiser distribution % % Usage: res = rspdfsolv(l, l3, l4) % % Input: % l - [lambda3 lamda4] parameters to optimize % skew - expected skewness % kurt - expected kurtosis % % Output: % res - residual % % Author: Arnaud Delorme, SCCN, 2003 % % See also: rsget() % % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % A probability distribution and its uses in fitting data. % Technimetrics, 1979, 21: 201-214. % Copyright (C) 2003 Arnaud Delorme, SCCN, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function res = rspdfsolv( l, a3, a4); A = 1/(1 + l(1)) - 1/(1 + l(2)); B = 1/(1 + 2*l(1)) + 1/(1 + 2*l(2)) - 2*beta(1+l(1), 1+l(2)); C = 1/(1 + 3*l(1)) - 1/(1 + 3*l(2)) ... - 3*beta(1+2*l(1), 1+l(2)) + 3*beta(1+l(1), 1+2*l(2)); D = 1/(1 + 4*l(1)) + 1/(1 + 4*l(2)) ... - 4*beta(1+3*l(1), 1+l(2)) - 4*beta(1+l(1), 1+3*l(2)) ... + 6*beta(1+2*l(1), 1+2*l(2)); estim_a3 = (C - 3*A*B + 2*A^3)/(B-A^2)^(3/2); estim_a4 = (D - 4*A*C + 6*A^2*B - 3*A^4)/(B-A^2)^2; res = (estim_a3 - a3)^2 + (estim_a4 - a4)^2; % the last term try to ensures that l(1) and l(2) are of the same sign if sign(l(1)*l(2)) == -1, res = 2*res; end; return; % original equations % $$$ A = 1(1 + l(3)) - 1/(1 + l(4)); % $$$ B = 1(1 + 2*l(3)) + 1/(1 + 2*l(4)) - 2*beta(1+l(3), 1+l(4)); % $$$ C = 1(1 + 3*l(3)) - 1/(1 + 3*l(4)) ... % $$$ - 3*beta(1+2*l(3), 1+l(4)) + 3*beta(1+l(3), 1+2*l(4)); % $$$ D = 1(1 + 4*l(3)) + 1/(1 + 4*l(4)) ... % $$$ - 4*beta(1+3*l(3), 1+l(4)) - 4*beta(1+l(3), 1+3*l(4)) ... % $$$ + 6*beta(1+2*l(3), 1+2*l(4)); % $$$ % $$$ R(1) = l(1) + A/l(2); % $$$ R(2) = (B-A^2)/l(2)^2; % $$$ R(3) = (C - 3*A*B + 2*A^3)/l(2)^3; % $$$ R(4) = (D - 4*A*C + 6*A^2*B - 3*A^4)/l(2)^4;
github
lcnbeapp/beapp-master
dftfilt.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/dftfilt.m
2,686
utf_8
b950c4302f749a1e9cffcd4c7f4ebe6a
% dftfilt() - discrete Fourier filter % % Usage: % >> b = dftfilt(n,W,c,k,q) % % Inputs: % n - number of input samples % W - maximum angular freq. relative to n, 0 < W <= .5 % c - cycles % k - oversampling % q - [0;1] 0->fft, 1->c cycles % % Authors: Sigurd Enghoff, Arnaud Delorme & Scott Makeig, % SCCN/INC/UCSD, La Jolla, 8/1/98 % Copyright (C) 8/1/98 Sigurd Enghoff & Scott Makei, 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 -ad % future developments % ------------------- % input into dftfilt: % - lowfreq and maxfreq (of interest) % - lowcycle and maxcyle (ex: 3 cycles at low freq and 10 cycles at maxfreq) % - the delta in frequency: ex 0.5 Hz % The function should: compute the number of points (len) automatically % Warning with FFT compatibility % Still, something has to be done about the masking so that it would be comaptible function b = dftfilt(len,maxfreq,cycle,oversmp,wavfact) count = 1; for index = 1:1/oversmp:maxfreq*len/cycle % scan frequencies w(:,count) = j * index * cycle * linspace(-pi+2*pi/len, pi-2*pi/len, len)'; % exp(-w) is a sinus curve count = count+1; % -2*pi/len ensures that we really scan from -pi to pi without redundance (-pi=+pi) end; b = exp(-w); %srate = 2*pi/len; % Angular increment. %w = j * cycle * [0:srate:2*pi-srate/2]'; % Column. %x = 1:1/oversmp:maxfreq*len/cycle; % Row. %b = exp(-w*x); % Exponentiation of outer product. for i = 1:size(b,2), m = round(wavfact*len*(i-1)/(i+oversmp-1)); % Number of elements to discard. mu = round(m/2); % Number of upper elemnts. ml = m-round(m/2); % Number of lower elemnts. b(:,i) = b(:,i) .* [zeros(mu,1) ; hanning(len-m) ; zeros(ml,1)]; end % syemtric hanning function function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end
github
lcnbeapp/beapp-master
rspfunc.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/rspfunc.m
1,468
utf_8
d6a6d26022ec2e38fa4adca9a28a5dde
% rspfunc() - sub-function used by rsget() % % Usage: res = rspfunc(pval, l, rval) % % Input: % pval - p-value to optimize % l - [l1 l2 l3 l4] l-values for Ramberg-Schmeiser distribution % rval - expected r-value % % Output: % res - residual % % Author: Arnaud Delorme, SCCN, 2003 % % See also: rsget() % % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % A probability distribution and its uses in fitting data. % Technimetrics, 1979, 21: 201-214. % Copyright (C) 2003 Arnaud Delorme, SCCN, [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 rp = rspfunc( pval, l, rval); % for fiting rp with fminsearch % ----------------------------- rp = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2); rp = abs(rval-rp);
github
lcnbeapp/beapp-master
correct_mc.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/correct_mc.m
5,698
utf_8
92f18a363d2fec001a50fafbcf9e06b5
% correct_mc() - compute an upper limit for the number of independant % time-frequency estimate in a given time-frequency image. % This number can be used to correct for multiple comparisons. % % Usage: % [ncorrect array] = correct_mc( EEG, cycles, maxfreq, timesout); % % Inputs: % EEG - EEGLAB structure % cycles - [float] same as the cycle input to timef(). Default is [3 0.5]. % freqrange - [float] minimum and maximum frequency. Default is [2 50] Hz. % timesout - [integer] array of number of time points to test. % % Output: % ncorrect - number of independant tf estimate in the time-freq image % array - array of size (freqs x timesout) containing pvalues. % % Method details: % % Dividing by the total number of time-frequency estimate in the 2-D % time-frequency image decomposition would be too conservative since % spectral estimates of neighboring time-frequency points are highly % correlated. One must thus estimate the number of independent % time-frequency points in the TF image. Here, I used geometrical wavelets % which are optimal in terms of image compression, so neighboring % frequencies can be assume to carry independent spectral estimates. % We thus had time-frequency decompositions at only X frequencies (e.g. 120, % 60, 30, 15, 7.5, 3.25, 1.625 Hz). For each frequency, I then found % the minimum number of time points for which there was a significant % correlation of the spectral estimates between neighboring time points % (for each frequency and number of time point, I computed the correlation % from 0 to 1 for all data channel to obtain an a probability distribution % of correlation; we then fitted this distribution using a 4th order curve % (Ramberg, J. S., E. J. Dudewicz, et al. (1979). "A probability % distribution and its uses in fitting data." Technometrics 21(2)) and % assessed the probability of significance for the value 0 (no correlation) % to be within the distribution of estimated correlation). For instance, % using 28 time points at 120 Hz, there was no significant (p>0.05 taking % into account Bonferoni correction for multiple comparisons) correlation % between neighboring time-frequency power estimate, but there was a % significant correlation using 32 time points instead of 28 (p<0.05). % Applying the same approach for the X geometrical frequencies and summing % the minimum number of time points for observing a significant correlation % at all frequencies, ones obtain in general a number below 200 (with the % defaults above and 3-second data epochs) independent estimates. In all % the time-frequency plots, one has to used a significance mask at p<0.00025 % (0.05/200). An alternative method for correcting for multiple comparisons % is presented in Nichols & Holmes, Human Brain Mapping, 2001. % % Author: Arnaud Delorme, SCCN, Jan 17, 2004 % Copyright (C) 2004 Arnaud Delorme, SCCN, [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 [ncorrect, pval] = correct_mc( EEG, cycles, freqrange, timesout); if nargin < 1 help correct_mc; return; end; if nargin < 2 cycles = [3 0.5]; end; if nargin < 3 freqrange = [2 50]; end; if nargin < 4 % possible number of time outputs % ------------------------------- timesout = [5 6 7 8 9 10 12 14 16 18 20 24 28 32 36 40]; end; nfreqs = ceil(log2(freqrange(2))); % scan times % ---------- for ti = 1:length(timesout) clear tmpf % scan data channels % ------------------ for index = 1:EEG.nbchan clf; [ersp,itc,powbase,times,freqs,erspboot,itcboot] = newtimef(EEG.data(index,:),EEG.pnts, ... [EEG.xmin EEG.xmax]*1000,EEG.srate, cycles, 'timesout', timesout(ti), ... 'freqscale', 'log', 'nfreqs', nfreqs, 'freqrange', freqrange, 'plotitc', 'off', 'plotersp', 'off'); % compute correlation % ------------------- for fi = 1:length(freqs) tmp = corrcoef(ersp(fi,1:end-1), ersp(fi,2:end)); tmpf(index,fi) = tmp(2,1); end; end; % fit curve and determine if the result is significant % ---------------------------------------------------- for fi = 1:length(freqs) pval(fi, ti) = rsfit(tmpf(:,fi)', 0); if pval(fi,ti) > 0.9999, pval(fi,ti) = NaN; end; end; end; % find minimum number of points for each frequency % ------------------------------------------------ ncorrect = 0; threshold = 0.05 / prod(size(pval)); for fi = 1:size(pval,1) ti = 1; while ti <= size(pval,2) if pval(fi,ti) < threshold ncorrect = ncorrect + timesout(ti); ti = size(pval,2)+1; end; ti = ti+1; end; end;
github
lcnbeapp/beapp-master
pac.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/pac.m
21,849
utf_8
a7d13b249d1c873e24a0f43a7cda2c5c
% pac() - compute phase-amplitude coupling (power of first input % correlation with phase of second). There is no graphical output % to this function. % % Usage: % >> pac(x,y,srate); % >> [coh,timesout,freqsout1,freqsout2,cohboot] ... % = pac(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 % 'method' = ['mod'|'corrsin'|'corrcos'|'latphase'] modulation % method or correlation of amplitude with sine or cosine of % angle (see ref). 'laphase' compute the phase % histogram at a specific time and requires the % 'powerlat' option to be set. % '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} % 'powerlat' = [float] latency in ms at which to compute phase % histogram % '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). % % Outputs: % pac = 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). % alltfX = single trial spectral decomposition of X % alltfY = single trial spectral decomposition of Y % % Author: Arnaud Delorme, SCCN/INC, UCSD 2005- % % 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, crossfcohall, alltfX, alltfY] = pac(X, Y, srate, varargin); if nargin < 1 help pac; 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'; 'method' 'string' { 'mod','corrsin','corrcos','latphase' } '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' [] []; ... 'gammapowerlim' 'real' [] []; ... 'powerlim' 'real' [] []; ... 'powerlat' 'real' [] []; ... 'gammabase' '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) }, 'pac'); 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'); [vals ind1 ind2 ] = intersect_bc(timesout1, timesout2); fprintf('Searching for common time points: %d found\n', length(vals)); 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 =[]; if ~strcmpi(g.method, 'latphase') 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; elseif 1 % this option computes power at a given latency % then computes the same as above (vectors) %if isempty(g.powerlat) % error('You need to specify a latency for the ''powerlat'' option'); %end; gammapower = mean(10*log10(alltfX(:,:,:).*conj(alltfX)),1); % average all frequencies for power if isempty(g.gammapowerlim) g.gammapowerlim = [ min(gammapower(:)) max(gammapower(:)) ]; end; fprintf('Gamma power limits: %3.2f to %3.2f\n', g.gammapowerlim(1), g.gammapowerlim(2)); power = 10*log10(alltfY(:,:,:).*conj(alltfY)); if isempty(g.powerlim) for freq = 1:size(power,1) g.powerlim(freq,:) = [ min(power(freq,:)) max(power(freq,:)) ]; end; end; for freq = 1:size(power,1) fprintf('Freq %d power limits: %3.2f to %3.2f\n', freqs2(freq), g.powerlim(freq,1), g.powerlim(freq,2)); end; % power plot %figure; plot(timesout2/1000, (mean(power(9,:,:),3)-mean(power(9,:)))/50); %hold on; plot(linspace(0, length(Y)/srate, length(Y)), mean(Y'), 'g'); % phase with power % figure; plot(timesout2/1000, (mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50); % hold on; plot(timesout1/1000, (mean(gammapower,3)-mean(gammapower(:)))/100, 'r'); %figure; plot((mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50+j*(mean(gammapower,3)-mean(gammapower(:)))/100, '.'); matsize = 32; matcenter = (matsize-1)/2+1; matrixfinalgammapower = zeros(size(alltfY,1),size(alltfX,3),matsize,matsize); matrixfinalcount = zeros(size(alltfY,1),size(alltfX,3),matsize,matsize); % get power indices if isempty(g.gammabase) g.gammabase = mean(gammapower(:)); end; fprintf('Gamma power average: %3.2f\n', g.gammabase); gammapoweradd = gammapower-g.gammabase; gammapower = floor((gammapower-g.gammapowerlim(1))/(g.gammapowerlim(2)-g.gammapowerlim(1))*(matsize-2))+1; phaseangle = angle(alltfY); posx = zeros(size(power)); posy = zeros(size(power)); for freq = 1:length(freqs2) fprintf('Processing frequency %3.2f\n', freqs2(freq)); power(freq,:,:) = (power(freq,:,:)-g.powerlim(freq,1))/(g.powerlim(freq,2)-g.powerlim(freq,1))*(matsize-3)/2+1; complexval = power(freq,:,:).*exp(j*phaseangle(freq,:,:)); posx(freq,:,:) = round(real(complexval)+matcenter); posy(freq,:,:) = round(imag(complexval)+matcenter); for trial = 1:size(alltfX,3) % scan trials for time = 1:size(alltfX,2) %matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial)) = ... % matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial))+1; matrixfinalgammapower(freq,trial,posx(freq,time,trial),posy(freq,time,trial)) = ... matrixfinalgammapower(freq,trial,posx(freq,time,trial),posy(freq,time,trial))+gammapoweradd(1,time,trial); matrixfinalcount(freq,trial,posx(freq,time,trial),posy(freq,time,trial)) = ... matrixfinalcount(freq,trial,posx(freq,time,trial),posy(freq,time,trial))+1; end; end; %matrixfinal(freq,:,:,:) = convn(squeeze(matrixfinal(freq,:,:,:)), gs, 'same'); %tmpmat = posx(index,:)+(posy(index,:)-1)*64+(gammapower(:)-1)*64*64; matrixfinalcount(freq, find(matrixfinalcount(freq,:) == 0)) = 1; matrixfinalgammapower(freq,:,:,:) = matrixfinalgammapower(freq,:,:,:)./matrixfinalcount(freq,:,:,:); end; % average and smooth matrixfinalgammapowermean = squeeze(mean(matrixfinalgammapower,2)); for freq = 1:length(freqs2) matrixfinalgammapowermean(freq,:,:) = conv2(squeeze(matrixfinalgammapowermean(freq,:,:)), gauss2d(5,5), 'same'); end; %matrixfinalgammapower = matrixfinalgammapower/size(alltfX,3)/size(alltfX,2); %vect = linspace(-pi,pi,50); %for f = 1:length(freqs2) % crossfcoh(f,:) = hist(tmpalltfy(f,:), vect); %end; % smoothing of output image % ------------------------- %gs = gauss2d(6, 6, 6); %crossfcoh = convn(crossfcoh, gs, 'same'); %freqs1 = freqs2; %timesout1 = linspace(-180, 180, size(crossfcoh,2)); crossfcoh = matrixfinalgammapowermean; crossfcohall = matrixfinalgammapower; else % this option computes power at a given latency % then computes the same as above (vectors) %if isempty(g.powerlat) % error('You need to specify a latency for the ''powerlat'' option'); %end; gammapower = mean(10*log10(alltfX(:,:,:).*conj(alltfX)),1); % average all frequencies for power if isempty(g.gammapowerlim) g.gammapowerlim = [ min(gammapower(:)) max(gammapower(:)) ]; end; power = 10*log10(alltfY(:,:,:).*conj(alltfY)); if isempty(g.powerlim) for freq = 1:size(power,1) g.powerlim(freq,:) = [ min(power(freq,:)) max(power(freq,:)) ]; end; end; % power plot %figure; plot(timesout2/1000, (mean(power(9,:,:),3)-mean(power(9,:)))/50); %hold on; plot(linspace(0, length(Y)/srate, length(Y)), mean(Y'), 'g'); % phase with power % figure; plot(timesout2/1000, (mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50); % hold on; plot(timesout1/1000, (mean(gammapower,3)-mean(gammapower(:)))/100, 'r'); %figure; plot((mean(phaseangle(9,:,:),3)-mean(phaseangle(9,:)))/50+j*(mean(gammapower,3)-mean(gammapower(:)))/100, '.'); matsize = 64; matcenter = (matsize-1)/2+1; matrixfinal = zeros(size(alltfY,1),64,64,64); matrixfinalgammapower = zeros(size(alltfY,1),matsize,matsize); matrixfinalcount = zeros(size(alltfY,1),matsize,matsize); % get power indices gammapoweradd = gammapower-mean(gammapower(:)); gammapower = floor((gammapower-g.gammapowerlim(1))/(g.gammapowerlim(2)-g.gammapowerlim(1))*(matsize-1))+1; phaseangle = angle(alltfY); posx = zeros(size(power)); posy = zeros(size(power)); gs = gauss3d(6, 6, 6); for freq = 1:size(alltfY) fprintf('Processing frequency %3.2f\n', freqs2(freq)); power(freq,:,:) = (power(freq,:,:)-g.powerlim(freq,1))/(g.powerlim(freq,2)-g.powerlim(freq,1))*(matsize-2)/2; complexval = power(freq,:,:).*exp(j*phaseangle(freq,:,:)); posx(freq,:,:) = round(real(complexval)+matcenter); posy(freq,:,:) = round(imag(complexval)+matcenter); for trial = 1:size(alltfX,3) % scan trials for time = 1:size(alltfX,2) %matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial)) = ... % matrixfinal(freq,posx(freq,time,trial),posy(freq,time,trial),gammapower(1,time,trial))+1; matrixfinalgammapower(freq,posx(freq,time,trial),posy(freq,time,trial)) = ... matrixfinalgammapower(freq,posx(freq,time,trial),posy(freq,time,trial))+gammapoweradd(1,time,trial); matrixfinalcount(freq,posx(freq,time,trial),posy(freq,time,trial)) = ... matrixfinalcount(freq,posx(freq,time,trial),posy(freq,time,trial))+1; end; end; %matrixfinal(freq,:,:,:) = convn(squeeze(matrixfinal(freq,:,:,:)), gs, 'same'); %tmpmat = posx(index,:)+(posy(index,:)-1)*64+(gammapower(:)-1)*64*64; matrixfinalcount(freq, find(matrixfinalcount(freq,:) == 0)) = 1; matrixfinalgammapower(freq,:,:) = matrixfinalgammapower(freq,:,:)./matrixfinalcount(freq, :,:); matrixfinalgammapower(freq,:,:) = conv2(squeeze(matrixfinalgammapower(freq,:,:)), gauss2d(5,5), 'same'); end; %matrixfinalgammapower = matrixfinalgammapower/size(alltfX,3)/size(alltfX,2); %vect = linspace(-pi,pi,50); %for f = 1:length(freqs2) % crossfcoh(f,:) = hist(tmpalltfy(f,:), vect); %end; % smoothing of output image % ------------------------- %gs = gauss2d(6, 6, 6); %crossfcoh = convn(crossfcoh, gs, 'same'); %freqs1 = freqs2; %timesout1 = linspace(-180, 180, size(crossfcoh,2)); crossfcoh = matrixfinalgammapower; end; % 7/31/2014 Ramon: crossfcohall sometimes does not exist depending on choice of input options if ~exist('crossfcohall', 'var') crossfcohall = []; end
github
lcnbeapp/beapp-master
bootstat.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/bootstat.m
20,825
utf_8
406a9744b6812cd9f9f1eed16ca63e82
% bootstat() - accumulate surrogate data to assess significance by permutation of some % measure of two input variables. % % If 'distfit','on', fits the psd with a 4th-order polynomial using the % data kurtosis, as in Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., % Mykkytka, E.F. "A probability distribution and its uses in fitting data." % Technometrics, 21:201-214, 1979. % Usage: % >> [rsignif,rboot] = bootstat( { arg1 arg2 ...}, formula, varargin ...); % Inputs: % arg1 - [array] 1-D, 2-D or 3-D array of values % arg2 - [array] 1-D, 2-D or 3-D array of values % formula - [string] formula to compute the given measure. Takes arguments % 'arg1', 'arg2' as inputs and 'res' (result, by default) as output. % For data arrays of more than 1 dimension, the formula must be iterative % so that shuffling can occur at each step while scanning the last % array dimension. Examples: % 'res = arg1 - arg2' % difference of two 1-D data arrays % 'res = mean( arg1 .* arg2)' % mean projection of two 1-D data arrays % 'res = res + arg1 .* conj(arg2)' % iterative, for use with 2|3-D arrays % Optional inputs: % 'boottype ' - ['rand'|'shuffle'] % 'rand' = do not shuffle data. Only flip polarity randomly (for real % number) or phase (for complex numbers). % 'shuffle' = shuffle values of first argument (see two options below). % Default. % 'shuffledim' - [integer] indices of dimensions to shuffle. For instance, [1 2] will % shuffle the first two dimensions. Default is to shuffle along % dimension 2. % 'shufflemode' - ['swap'|'regular'] shuffle mode. Either swap dimensions (for instance % swap rows then columns if dimension [1 2] are selected) or shuffle % in each dimension independently (slower). If only one dimension is % selected for shuffling, this option does not change the result. % 'randmode' - ['opposite'|'inverse'] randomize sign (or phase for complex number, % or randomly set half the value to reference. % 'alpha' - [real] significance level (between 0 and 1) {default 0.05}. % 'naccu' - [integer] number of exemplars to accumulate {default 200}. % 'bootside' - ['both'|'upper'] side of the surrogate distribution to % consider for significance. This parameter affects the size % of the last dimension of the accumulation array ('accres') % (size is 2 for 'both' and 1 for 'upper') {default: 'both'}. % 'basevect' - [integer vector] time vector indices for baseline in second dimension. % {default: all time points}. % 'rboot' - accumulation array (from a previous call). Allows faster % computation of the 'rsignif' output {default: none}. % 'formulaout' - [string] name of the computed variable {default: 'res'}. % 'dimaccu' - [integer] use dimension in result to accumulate data. % For instance if the result array is size [60x50] and this value is 2, % the function will consider than 50 times 60 value have been accumulated. % % Fitting distribution: % 'distfit' - ['on'|'off'] fit distribution with known function to compute more accurate % limits or exact p-value (see 'vals' option). The MATLAB statistical toolbox % is required. This option is currently implemented only for 1-D data. % 'vals' - [float array] significance values. 'alpha' is ignored and % rsignif returns the p-values. Requires 'distfit' (see above). % This option currently implemented only for 1-D data. % 'correctp' - [phat pci zerofreq] parameters for correcting for a biased probability % distribution (requires 'distfit' above). See help of correctfit(). % Outputs: % rsignif - significance arrays. 2 values (low high) for each point (use % 'alpha' to change these limits). % rboot - accumulated surrogate data values. % % Authors: Arnaud Delorme, Bhaktivedcanta Institute, Mumbai, India, Nov 2004 % % See also: timef() % NOTE: There is an undocumented parameter, 'savecoher', [0|1] % HELP TEXT REMOVED: (Ex: Using option 'both', coherence during baseline would be % ignored since times are shuffled during each accumulation. % Copyright (C) 9/2002 Arnaud Delorme & 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 % ************************************* % To fit the psd with as 4th order polynomial using the distribution kurtosis, % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % "A probability distribution and its uses in fitting data." % Technimetrics, 1979, 21: 201-214. % ************************************* function [accarrayout, Rbootout, Rbootout2] = bootstat(oriargs, formula, varargin) % nb_points, timesout, naccu, baselength, baseboot, boottype, alpha, rboot); if nargin < 2 help bootstat; return; end; if ~isstr(formula) error('The second argument must be a string formula'); end; g = finputcheck(varargin, ... { 'dims' 'integer' [] []; ... 'naccu' 'integer' [0 10000] 200; ... 'bootside' 'string' { 'both','upper' } 'both'; ... 'basevect' 'integer' [] []; ... 'boottype' 'string' { 'rand','shuffle' } 'shuffle'; ... 'shufflemode' 'string' { 'swap','regular' } 'swap'; ... 'randmode' 'string' { 'opposite','inverse' } 'opposite'; ... 'shuffledim' 'integer' [0 Inf] []; ... 'label' 'string' [] formula; ... 'alpha' 'real' [0 1] 0.05; ... 'vals' 'real' [] []; ... 'distfit' 'string' {'on','off' } 'off'; ... 'dimaccu' 'integer' [1 Inf] []; ... 'correctp' 'real' [] []; ... 'rboot' 'real' [] NaN }); if isstr(g) error(g); end; if isempty(g.shuffledim) & strcmpi(g.boottype, 'rand') g.shuffledim = []; elseif isempty(g.shuffledim) g.shuffledim = 2; end; unitname = ''; if 2/g.alpha > g.naccu if strcmpi(g.distfit, 'off') | ~((size(oriarg1,1) == 1 | size(oriarg1,2) == 1) & size(oriarg1,3) == 1) g.naccu = 2/g.alpha; fprintf('Adjusting naccu to compute alpha value'); end; end; if isempty(g.rboot) g.rboot = NaN; end; % function for bootstrap computation % ---------------------------------- if ~iscell(oriargs) | length(oriargs) == 1, oriarg1 = oriargs; oriarg2 = []; else oriarg1 = oriargs{1}; oriarg2 = oriargs{2}; end; [nb_points times trials] = size(oriarg1); if times == 1, disp('Warning 1 value only for shuffling dimension'); end; % only consider baseline % ---------------------- if ~isempty(g.basevect) fprintf('\nPermutation statistics baseline length is %d (out of %d) points\n', length(g.basevect), times); arg1 = oriarg1(:,g.basevect,:); if ~isempty(oriarg2) arg2 = oriarg2(:,g.basevect,:); end; else arg1 = oriarg1; arg2 = oriarg2; end; % formula for accumulation array % ------------------------------ % if g.dimaccu is not empty, accumulate over that dimension % of the resulting array to speed up computation formula = [ 'res=' formula ]; g.formulapost = [ 'if index == 1, ' ... ' if ~isempty(g.dimaccu), ' ... ' Rbootout= zeros([ ceil(g.naccu/size(res,g.dimaccu)) size( res ) ]);' ... ' else,' ... ' Rbootout= zeros([ g.naccu size( res ) ]);' ... ' end;' ... 'end,' ... 'Rbootout(count,:,:,:) = res;' ... 'count = count+1;' ... 'if ~isempty(g.dimaccu), ' ... ' index = index + size(res,g.dimaccu);' ... ' fprintf(''%d '', index-1);' ... 'else ' ... ' index=index+1;' ... ' if rem(index,10) == 0, fprintf(''%d '', index); end;' ... ' if rem(index,100) == 0, fprintf(''\n''); end;' ... 'end;' ]; % ************************** % case 1: precomputed values % ************************** if ~isnan(g.rboot) Rbootout = g.rboot; % *********************************** % case 2: randomize polarity or phase % *********************************** elseif strcmpi(g.boottype, 'rand') & strcmpi(g.randmode, 'inverse') fprintf('Bootstat function: randomize inverse values\n'); fprintf('Processing permutation statistics for %s (naccu=%d):', g.label, g.naccu); % compute random array % -------------------- multarray = ones(size(arg1)); totlen = prod(size(arg1)); if isreal(arg1), multarray(1:round(totlen/2)) = 0; end; for shuff = 1:ndims(multarray) multarray = supershuffle(multarray,shuff); % initial shuffling end; if isempty(g.shuffledim), g.shuffledim = 1:ndims(multarray); end; invarg1 = 1./arg1; % accumulate % ---------- index = 1; count = 1; while index <= g.naccu for shuff = g.shuffledim multarray = supershuffle(multarray,shuff); end; tmpinds = find(reshape(multarray, 1, prod(size(multarray)))); arg1 = oriarg1; arg1(tmpinds) = invarg1(tmpinds); eval([ formula ';' ]); eval( g.formulapost ); % also contains index = index+1 end elseif strcmpi(g.boottype, 'rand') % opposite fprintf('Bootstat function: randomize polarity or phase\n'); fprintf('Processing permutation statistics for %s (naccu=%d):', g.label, g.naccu); % compute random array % -------------------- multarray = ones(size(arg1)); totlen = prod(size(arg1)); if isreal(arg1), multarray(1:round(totlen/2)) = -1; else tmparray = exp(j*linspace(0,2*pi,totlen+1)); multarray(1:totlen) = tmparray(1:end-1); end; for shuff = 1:ndims(multarray) multarray = supershuffle(multarray,shuff); % initial shuffling end; if isempty(g.shuffledim), g.shuffledim = 1:ndims(multarray); end; % accumulate % ---------- index = 1; count = 1; while index <= g.naccu for shuff = g.shuffledim multarray = supershuffle(multarray,shuff); end; arg1 = arg1.*multarray; eval([ formula ';' ]); eval( g.formulapost ); % also contains index = index+1 end % ******************************************** % case 3: shuffle vector of only one dimension % ******************************************** elseif length(g.shuffledim) == 1 fprintf('Bootstat function: shuffling along dimension %d only\n', g.shuffledim); fprintf('Processing permutation statistics for %s (naccu=%d):', g.label, g.naccu); index = 1; count = 1; while index <= g.naccu arg1 = shuffleonedim(arg1,g.shuffledim); eval([ formula ';' ]); eval( g.formulapost ); end % *********************************************** % case 5: shuffle vector along several dimensions % *********************************************** else if strcmpi(g.shufflemode, 'swap') % swap mode fprintf('Bootstat function: shuffling along dimension %s (swap mode)\n', int2str(g.shuffledim)); fprintf('Processing permutation statistics for %s (naccu=%d):', g.label, g.naccu); index = 1; count = 1; while index <= g.naccu for shuff = g.shuffledim arg1 = supershuffle(arg1,shuff); end; eval([ formula ';' ]); eval( g.formulapost ); end else % regular shuffling fprintf('Bootstat function: shuffling along dimension %s (regular mode)\n', int2str(g.shuffledim)); fprintf('Processing permutation statistics for %s (naccu=%d):', g.label, g.naccu); index = 1; count = 1; while index <= g.naccu for shuff = g.shuffledim arg1 = shuffleonedim(arg1,shuff); end; eval([ formula ';' ]); eval( g.formulapost ); end end; end; Rbootout(count:end,:,:,:) = []; % ********************** % assessing significance % ********************** % get accumulation array % ---------------------- accarray = Rbootout; if ~isreal(accarray) accarray = sqrt(accarray .* conj(accarray)); % faster than abs() end; % reshape the output if necessary % ------------------------------- if ~isempty(g.dimaccu) if g.dimaccu+1 == 3 accarray = permute( accarray, [1 3 2]); end; accarray = reshape( accarray, size(accarray,1)*size(accarray,2), size(accarray,3) ); end; if size(accarray,1) == 1, accarray = accarray'; end; % first dim contains g.naccu % ****************************************************** % compute thresholds on array not fitting a distribution % ****************************************************** if strcmpi(g.distfit, 'off') % compute bootstrap significance level % ------------------------------------ accarray = sort(accarray,1); % always sort on naccu Rbootout2 = accarray; i = round(size(accarray,1)*g.alpha); accarray1 = squeeze(mean(accarray(size(accarray,1)-i+1:end,:,:),1)); accarray2 = squeeze(mean(accarray(1:i ,:,:),1)); if abs(accarray(1,1,1) - accarray(end,1,1)) < abs(accarray(1,1,1))*1e-15 accarray1(:) = NaN; accarray2(:) = NaN; end; else % ******************* % fit to distribution % ******************* sizerboot = size (accarray); accarray1 = zeros(sizerboot(2:end)); accarray2 = zeros(sizerboot(2:end)); if ~isempty(g.vals{index}) if ~all(size(g.vals{index}) == sizerboot(2:end) ) error('For fitting, vals must have the same dimension as the output array (try transposing)'); end; end; % fitting with Ramberg-Schmeiser distribution % ------------------------------------------- if ~isempty(g.vals{index}) % compute significance for value for index1 = 1:size(accarrayout,1) for index2 = 1:size(accarrayout,2) accarray1(index1,index2) = 1 - rsfit(squeeze(accarray(:,index1,index2)), g.vals{index}(index1, index2)); if length(g.correctp) == 2 accarray1(index1,index2) = correctfit(accarray1, 'gamparams', [g.correctp 0]); % no correction for p=0 else accarray1(index1,index2) = correctfit(accarray1, 'gamparams', g.correctp); end; end; end; else % compute value for significance for index1 = 1:size(accarrayout,1) for index2 = 1:size(accarrayout,2) [p c l chi2] = rsfit(Rbootout(:),0); pval = g.alpha; accarray1(index1,index2) = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2); pval = 1-g.alpha; accarray2(index1,index2) = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2); end; end; end; % plot results % ------------------------------------- % figure; % hist(abs(Rbootout)); tmpax = axis; % hold on; % valcomp = linspace(min(abs(Rbootout(:))), max(abs(Rbootout(:))), 100); % normy = normpdf(valcomp, mu, sigma); % plot(valcomp, normy/max(normy)*tmpax(4), 'r'); % return; end; % set output array: backward compatible % ------------------------------------- if strcmpi(g.bootside, 'upper'); % only upper significance accarrayout = accarray1; else if size(accarray1,1) ~= 1 & size(accarray1,2) ~= 1 accarrayout = accarray2; accarrayout(:,:,2) = accarray1; else accarrayout = [ accarray2(:) accarray1(:) ]; end; end; accarrayout = squeeze(accarrayout); if size(accarrayout,1) == 1 & size(accarrayout,3) == 1, accarrayout = accarrayout'; end; % better but not backward compatible % ---------------------------------- % accarrayout = { accarray1 accarray2 }; return; % fitting with normal distribution (deprecated) % -------------------------------- [mu sigma] = normfit(abs(Rbootout(:))); accarrayout = 1 - normcdf(g.vals, mu, sigma); % cumulative density distribution % formula of normal distribution % y = 1/sqrt(2) * exp( -(x-mu).^2/(sigma*sigma*2) ) / (sqrt(pi)*sigma); % % Gamma and Beta fits: % elseif strcmpi(g.distfit, 'gamma') % [phatgam pcigam] = gamfit(abs(Rbootout(:))); % gamy = gampdf(valcomp, phatgam(1), pcigam(2)) % p = 1 - gamcdf(g.vals, phatgam(1), pcigam(2)); % cumulative density distribution % elseif strcmpi(g.distfit, 'beta') % [phatbeta pcibeta] = betafit(abs(Rbootout(:))); % betay = betapdf(valcomp, phatbeta(1), pcibeta(1)); % p = 1 - betacdf(g.vals, phatbeta(1), pcibeta(1)); % cumulative density distribution % end if strcmpi(g.distfit, 'off') tmpsort = sort(Rbootout); i = round(g.alpha*g.naccu); sigval = [mean(tmpsort(1:i)) mean(tmpsort(g.naccu-i+1:g.naccu))]; if strcmpi(g.bootside, 'upper'), sigval = sigval(2); end; accarrayout = sigval; end; % this shuffling preserve the number of -1 and 1 % for cloumns and rows (assuming matrix size is multiple of 2 % ----------------------------------------------------------- function array = supershuffle(array, dim) if size(array, 1) == 1 | size(array,2) == 1 array = shuffle(array); return; end; if size(array, dim) == 1, return; end; if dim == 1 indrows = shuffle(1:size(array,1)); for index = 1:2:length(indrows)-rem(length(indrows),2) % shuffle rows tmparray = array(indrows(index),:,:); array(indrows(index),:,:) = array(indrows(index+1),:,:); array(indrows(index+1),:,:) = tmparray; end; elseif dim == 2 indcols = shuffle(1:size(array,2)); for index = 1:2:length(indcols)-rem(length(indcols),2) % shuffle colums tmparray = array(:,indcols(index),:); array(:,indcols(index),:) = array(:,indcols(index+1),:); array(:,indcols(index+1),:) = tmparray; end; else ind3d = shuffle(1:size(array,3)); for index = 1:2:length(ind3d)-rem(length(ind3d),2) % shuffle colums tmparray = array(:,:,ind3d(index)); array(:,:,ind3d(index)) = array(:,:,ind3d(index+1)); array(:,:,ind3d(index+1)) = tmparray; end; end; % shuffle one dimension, one row/colums at a time % ----------------------------------------------- function array = shuffleonedim(array, dim) if size(array, 1) == 1 | size(array,2) == 1 array = shuffle(array, dim); else if dim == 1 for index1 = 1:size(array,3) for index2 = 1:size(array,2) array(:,index2,index1) = shuffle(array(:,index2,index1)); end; end; elseif dim == 2 for index1 = 1:size(array,3) for index2 = 1:size(array,1) array(index2,:,index1) = shuffle(array(index2,:,index1)); end; end; else for index1 = 1:size(array,1) for index2 = 1:size(array,2) array(index1,index2,:) = shuffle(array(index1,index2,:)); end; end; end; end;
github
lcnbeapp/beapp-master
timefreq.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/timefreq.m
33,427
utf_8
dc70f7b5afd51d05bcf926a934072865
% timefreq() - compute time/frequency decomposition of data trials. This % function is a compute-only function called by % the more complete time/frequency functions newtimef() % and newcrossf() which also plot timefreq() results. % % Usage: % >> [tf, freqs, times] = timefreq(data, srate); % >> [tf, freqs, times, itcvals] = timefreq(data, srate, ... % 'key1', 'val1', 'key2', 'val2' ...) % Inputs: % data = [float array] 2-D data array of size (times,trials) % srate = sampling rate % % Optional inputs: % 'cycles' = [real] indicates the number of cycles for the % time-frequency decomposition {default: 0} % if 0, use FFTs and Hanning window tapering. % or [real positive scalar] Number of cycles in each Morlet % wavelet, constant across frequencies. % or [cycles cycles(2)] wavelet cycles increase with % frequency starting at cycles(1) and, % if cycles(2) > 1, increasing to cycles(2) at % the upper frequency, % or if cycles(2) = 0, same window size at all % frequencies (similar to FFT if cycles(1) = 1) % or if cycles(2) = 1, not increasing (same as giving % only one value for 'cycles'). This corresponds to pure % wavelet with the same number of cycles at each frequencies % if 0 < cycles(2) < 1, linear variation in between pure % wavelets (1) and FFT (0). The exact number of cycles % at the highest frequency is indicated on the command line. % 'wavelet' = DEPRECATED, please use 'cycles'. This function does not % support multitaper. For multitaper, use timef(). % 'wletmethod' = ['dftfilt2'|'dftfilt3'] Wavelet method/program to use. % {default: 'dftfilt3'} % 'dftfilt' DEPRECATED. Method used in regular timef() % program. Not available any more. % 'dftfilt2' Morlet-variant or Hanning DFT (calls dftfilt2() % to generate wavelets). % 'dftfilt3' Morlet wavelet or Hanning DFT (exact Tallon % Baudry). Calls dftfilt3(). % 'ffttaper' = ['none'|'hanning'|'hamming'|'blackmanharris'] FFT tapering % function. Default is 'hanning'. Note that 'hamming' and % 'blackmanharris' require the signal processing toolbox. % Optional ITC type: % 'type' = ['coher'|'phasecoher'] Compute either linear coherence % ('coher') or phase coherence ('phasecoher') also known % as phase coupling factor' {default: 'phasecoher'}. % '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'} % % Optional detrending: % 'detrend' = ['on'|'off'], Linearly detrend each data epoch {'off'} % % Optional FFT/DFT parameters: % 'tlimits' = [min max] time limits in ms. % 'winsize' = If cycles==0 (FFT, see 'wavelet' input): data subwindow % length (fastest, 2^n<frames); % if cycles >0: *longest* window length to use. This % determines the lowest output frequency {~frames/8} % 'ntimesout' = Number of output times (int<frames-winsize). 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} % 'freqs' = [min max] frequency limits. Default [minfreq srate/2], % minfreq being determined by the number of data points, % cycles and sampling frequency. Enter a single value % to compute spectral decompisition at a single frequency % (note: for FFT the closest frequency will be estimated). % For wavelet, reducing the max frequency reduce % the computation load. % 'padratio' = FFTlength/winsize (2^k) {def: 2} % Multiplies the number of output frequencies by % dividing their spacing. When cycles==0, frequency % spacing is (low_frequency/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. % 'wletmethod'= ['dftfilt2'|'dftfilt3'] Wavelet method/program to use. % Default is 'dftfilt3' % 'dftfilt3' Morlet wavelet or Hanning DFT % 'dftfilt2' Morlet-variant or Hanning DFT. % Note that there are differences betweeen the Hanning % DFTs in the two programs. % 'causal' = ['on'|'off'] apply FFT or time-frequency in a causal % way where only data before any given latency can % influence the spectral decomposition. (default: 'off'} % % Optional time warping: % 'timestretch' = {[Refmarks], [Refframes]} % Stretch amplitude and phase time-course before smoothing. % Refmarks is a (trials,eventframes) matrix in which rows are % event marks to time-lock to for a given trial. Each trial % will be stretched so that its marked events occur at frames % Refframes. If Refframes is [], the median frame, across trials, % of the Refmarks latencies will be used. Both Refmarks and % Refframes are given in frames in this version - will be % changed to ms in future. % Outputs: % tf = complex time frequency array for all trials (freqs, % times, trials) % freqs = vector of computed frequencies (Hz) % times = vector of computed time points (ms) % itcvals = time frequency "average" for all trials (freqs, times). % In the coherence case, it is the real mean of the time % frequency decomposition, but in the phase coherence case % (see 'type' input'), this is the mean of the normalized % spectral estimate. % % Authors: Arnaud Delorme, Jean Hausser & Scott Makeig % CNL/Salk Institute 1998-2001; SCCN/INC/UCSD, La Jolla, 2002- % Fix FFT frequency innacuracy, bug 874 by WuQiang % % See also: timef(), newtimef(), crossf(), newcrossf() % Note: it is not advised to use a FFT decomposition in a log scale. Output % value are accurate but plotting might not be because of the non-uniform % frequency output values in log-space. If you have to do it, use a % padratio as large as possible, or interpolate time-freq image at % exact log scale values before plotting. % Copyright (C) 8/1/98 Arnaud Delorme, 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 function [tmpall, freqs, timesout, itcvals] = timefreq(data, srate, varargin) if nargin < 2 help timefreq; return; end; [chan frame trials]= size(data); if trials == 1 && chan ~= 1 trials = frame; frame = chan; chan = 1; end; g = finputcheck(varargin, ... { 'ntimesout' 'integer' [] []; ... 'timesout' 'real' [] []; ... 'winsize' 'integer' [0 Inf] []; ... 'tlimits' 'real' [] []; ... 'detrend' 'string' {'on','off'} 'off'; ... 'causal' 'string' {'on','off'} 'off'; ... 'verbose' 'string' {'on','off'} 'on'; ... 'freqs' 'real' [0 Inf] []; ... 'nfreqs' 'integer' [0 Inf] []; ... 'freqscale' 'string' { 'linear','log','' } 'linear'; ... 'ffttaper' 'string' { 'hanning','hamming','blackmanharris','none' } 'hanning'; 'wavelet' 'real' [0 Inf] 0; ... 'cycles' {'real','integer'} [0 Inf] 0; ... 'padratio' 'integer' [1 Inf] 2; ... 'itctype' 'string' {'phasecoher','phasecoher2','coher'} 'phasecoher'; ... 'subitc' 'string' {'on','off'} 'off'; ... 'timestretch' 'cell' [] {}; ... 'wletmethod' 'string' {'dftfilt2','dftfilt3'} 'dftfilt3'; ... }); if isstr(g), error(g); end; if isempty(g.freqscale), g.freqscale = 'linear'; end; if isempty(g.winsize), g.winsize = max(pow2(nextpow2(frame)-3),4); end; if isempty(g.ntimesout), g.ntimesout = 200; end; if isempty(g.freqs), g.freqs = [0 srate/2]; end; if isempty(g.tlimits), g.tlimits = [0 frame/srate*1000]; end; % checkin parameters % ------------------ % Use 'wavelet' if 'cycles' undefined for backwards compatibility if g.cycles == 0 g.cycles = g.wavelet; end if (g.winsize > frame) error('Value of winsize must be less than frame length.'); end if (pow2(nextpow2(g.padratio)) ~= g.padratio) error('Value of padratio must be an integer power of two [1,2,4,8,16,...]'); end % finding frequency limits % ------------------------ if g.cycles(1) ~= 0 & g.freqs(1) == 0, g.freqs(1) = srate*g.cycles(1)/g.winsize; end; % finding frequencies % ------------------- if length(g.freqs) == 2 % min and max % ----------- if g.freqs(1) == 0 & g.cycles(1) ~= 0 g.freqs(1) = srate*g.cycles(1)/g.winsize; end; % default number of freqs using padratio % -------------------------------------- if isempty(g.nfreqs) g.nfreqs = g.winsize/2*g.padratio+1; % adjust nfreqs depending on frequency range tmpfreqs = linspace(0, srate/2, g.nfreqs); tmpfreqs = tmpfreqs(2:end); % remove DC (match the output of PSD) % adjust limits for FFT (only linear scale) if g.cycles(1) == 0 & ~strcmpi(g.freqscale, 'log') if ~any(tmpfreqs == g.freqs(1)) [tmp minind] = min(abs(tmpfreqs-g.freqs(1))); g.freqs(1) = tmpfreqs(minind); verboseprintf(g.verbose, 'Adjust min freq. to %3.2f Hz to match FFT output frequencies\n', g.freqs(1)); end; if ~any(tmpfreqs == g.freqs(2)) [tmp minind] = min(abs(tmpfreqs-g.freqs(2))); g.freqs(2) = tmpfreqs(minind); verboseprintf(g.verbose, 'Adjust max freq. to %3.2f Hz to match FFT output frequencies\n', g.freqs(2)); end; end; % find number of frequencies % -------------------------- g.nfreqs = length(tmpfreqs( intersect( find(tmpfreqs >= g.freqs(1)), find(tmpfreqs <= g.freqs(2))))); if g.freqs(1)==g.freqs(2), g.nfreqs = 1; end; end; % find closest freqs for FFT % -------------------------- if strcmpi(g.freqscale, 'log') g.freqs = linspace(log(g.freqs(1)), log(g.freqs(end)), g.nfreqs); g.freqs = exp(g.freqs); else g.freqs = linspace(g.freqs(1), g.freqs(2), g.nfreqs); % this should be OK for FFT % because of the limit adjustment end; end; g.nfreqs = length(g.freqs); % function for time freq initialisation % ------------------------------------- if (g.cycles(1) == 0) %%%%%%%%%%%%%% constant window-length FFTs %%%%%%%%%%%%%%%% freqs = linspace(0, srate/2, g.winsize*g.padratio/2+1); freqs = freqs(2:end); % remove DC (match the output of PSD) %srate/g.winsize*[1:2/g.padratio:g.winsize]/2 verboseprintf(g.verbose, 'Using %s FFT tapering\n', g.ffttaper); switch g.ffttaper case 'hanning', g.win = hanning(g.winsize); case 'hamming', g.win = hamming(g.winsize); case 'blackmanharris', g.win = blackmanharris(g.winsize); case 'none', g.win = ones(g.winsize,1); end; else % %%%%%%%%%%%%%%%%%% Constant-Q (wavelet) DFTs %%%%%%%%%%%%%%%%%%%%%%%%%%%% %freqs = srate*g.cycles/g.winsize*[2:2/g.padratio:g.winsize]/2; %g.win = dftfilt(g.winsize,g.freqs(2)/srate,g.cycles,g.padratio,g.cyclesfact); freqs = g.freqs; if length(g.cycles) == 2 if g.cycles(2) < 1 g.cycles = [ g.cycles(1) g.cycles(1)*g.freqs(end)/g.freqs(1)*(1-g.cycles(2))]; end verboseprintf(g.verbose, 'Using %g cycles at lowest frequency to %g at highest.\n', g.cycles(1), g.cycles(2)); elseif length(g.cycles) == 1 verboseprintf(g.verbose, 'Using %d cycles at all frequencies.\n',g.cycles); else verboseprintf(g.verbose, 'Using user-defined cycle for each frequency\n'); end if strcmp(g.wletmethod, 'dftfilt2') g.win = dftfilt2(g.freqs,g.cycles,srate, g.freqscale); % uses Morlet taper by default elseif strcmp(g.wletmethod, 'dftfilt3') % Default g.win = dftfilt3(g.freqs,g.cycles,srate, 'cycleinc', g.freqscale); % uses Morlet taper by default else return end g.winsize = 0; for index = 1:length(g.win) g.winsize = max(g.winsize,length(g.win{index})); end; end; % compute time vector % ------------------- [ g.timesout g.indexout ] = gettimes(frame, g.tlimits, g.timesout, g.winsize, g.ntimesout, g.causal, g.verbose); % ------------------------------- % compute time freq decomposition % ------------------------------- verboseprintf(g.verbose, 'The window size used is %d samples (%g ms) wide.\n',g.winsize, 1000/srate*g.winsize); if strcmpi(g.freqscale, 'log') % fastif was having strange "function not available" messages scaletoprint = 'log'; else scaletoprint = 'linear'; end verboseprintf(g.verbose, 'Estimating %d %s-spaced frequencies from %2.1f Hz to %3.1f Hz.\n', length(g.freqs), ... scaletoprint, g.freqs(1), g.freqs(end)); %verboseprintf(g.verbose, 'Estimating %d %s-spaced frequencies from %2.1f Hz to %3.1f Hz.\n', length(g.freqs), ... % fastif(strcmpi(g.freqscale, 'log'), 'log', 'linear'), g.freqs(1), g.freqs(end)); if g.cycles(1) == 0 if 1 % build large matrix to compute FFT % --------------------------------- indices = repmat([-g.winsize/2+1:g.winsize/2]', [1 length(g.indexout) trials]); indices = indices + repmat(g.indexout, [size(indices,1) 1 trials]); indices = indices + repmat(reshape(([1:trials]-1)*frame,1,1,trials), [size(indices,1) length(g.indexout) 1]); if chan > 1 tmpall = repmat(nan,[chan length(freqs) length(g.timesout) trials]); tmpX = reshape(data(:,indices), [ size(data,1) size(indices)]); tmpX = bsxfun(@minus, tmpX, mean( tmpX, 2)); % avoids repmat - faster than tmpX = tmpX - repmat(mean(tmpX), [size(tmpX,1) 1 1]); tmpX = bsxfun(@times, tmpX, g.win'); tmpX = fft(tmpX,g.padratio*g.winsize,2); tmpall = squeeze(tmpX(:,2:g.padratio*g.winsize/2+1,:,:)); else tmpall = repmat(nan,[length(freqs) length(g.timesout) trials]); tmpX = data(indices); tmpX = bsxfun(@minus, tmpX, mean( tmpX, 1)); % avoids repmat - faster than tmpX = tmpX - repmat(mean(tmpX), [size(tmpX,1) 1 1]); tmpX = bsxfun(@times, tmpX, g.win); %tmpX = fft(tmpX,2^ceil(log2(g.padratio*g.winsize))); %tmpall = tmpX(2:g.padratio*g.winsize/2+1,:,:); tmpX = fft(tmpX,g.padratio*g.winsize); tmpall = tmpX(2:g.padratio*g.winsize/2+1,:,:); end; else % old iterative computation tmpall = repmat(nan,[length(freqs) length(g.timesout) trials]); verboseprintf(g.verbose, 'Processing trial (of %d):',trials); for trial = 1:trials if rem(trial,10) == 0, verboseprintf(g.verbose, ' %d',trial); end if rem(trial,120) == 0, verboseprintf(g.verbose, '\n'); end for index = 1:length(g.indexout) if strcmpi(g.causal, 'off') tmpX = data([-g.winsize/2+1:g.winsize/2]+g.indexout(index)+(trial-1)*frame); % 1 point imprecision else tmpX = data([-g.winsize+1:0]+g.indexout(index)+(trial-1)*frame); % 1 point imprecision end; tmpX = tmpX - mean(tmpX); if strcmpi(g.detrend, 'on'), tmpX = detrend(tmpX); end; tmpX = g.win .* tmpX(:); tmpX = fft(tmpX,g.padratio*g.winsize); tmpX = tmpX(2:g.padratio*g.winsize/2+1); tmpall(:,index, trial) = tmpX(:); end; end; end; else % wavelet if chan > 1 % wavelets are processed in groups of the same size % to speed up computation. Wavelet of groups of different size % can be processed together but at a cost of a lot of RAM and % a lot of extra computation -> not efficient tmpall = repmat(nan,[chan length(freqs) length(g.timesout) trials]); wt = [ 1 find(diff(cellfun(@length,g.win)))+1 length(g.win)+1]; verboseprintf(g.verbose, 'Computing of %d:', length(wt)); for ind = 1:length(wt)-1 verboseprintf(g.verbose, '.'); wavarray = reshape([ g.win{wt(ind):wt(ind+1)-1} ], [ length(g.win{wt(ind)}) wt(ind+1)-wt(ind) ]); sizewav = size(wavarray,1)-1; indices = repmat([-sizewav/2:sizewav/2]', [1 size(wavarray,2) length(g.indexout) trials]); indices = indices + repmat(reshape(g.indexout, 1,1,length(g.indexout)), [size(indices,1) size(indices,2) 1 trials]); indices = indices + repmat(reshape(([1:trials]-1)*frame,1,1,1,trials), [size(indices,1) size(indices,2) size(indices,3) 1]); szfreqdata = [ size(data,1) size(indices) ]; tmpX = reshape(data(:,indices), szfreqdata); tmpX = bsxfun(@minus, tmpX, mean( tmpX, 2)); % avoids repmat - faster than tmpX = tmpX - repmat(mean(tmpX), [size(tmpX,1) 1 1]); wavarray = reshape(wavarray, [1 size(wavarray,1) size(wavarray,2)]); tmpall(:,wt(ind):wt(ind+1)-1,:,:,:) = reshape(sum(bsxfun(@times, tmpX, wavarray),2), [szfreqdata(1) szfreqdata(3:end)]); end; verboseprintf(g.verbose, '\n'); %tmpall = squeeze(tmpall(1,:,:,:)); elseif 0 tmpall = repmat(nan,[length(freqs) length(g.timesout) trials]); % wavelets are processed in groups of the same size % to speed up computation. Wavelet of groups of different size % can be processed together but at a cost of a lot of RAM and % a lot of extra computation -> not faster than the regular % iterative method wt = [ 1 find(diff(cellfun(@length,g.win)))+1 length(g.win)+1]; for ind = 1:length(wt)-1 wavarray = reshape([ g.win{wt(ind):wt(ind+1)-1} ], [ length(g.win{wt(ind)}) wt(ind+1)-wt(ind) ]); sizewav = size(wavarray,1)-1; indices = repmat([-sizewav/2:sizewav/2]', [1 size(wavarray,2) length(g.indexout) trials]); indices = indices + repmat(reshape(g.indexout, 1,1,length(g.indexout)), [size(indices,1) size(indices,2) 1 trials]); indices = indices + repmat(reshape(([1:trials]-1)*frame,1,1,1,trials), [size(indices,1) size(indices,2) size(indices,3) 1]); tmpX = data(indices); tmpX = bsxfun(@minus, tmpX, mean( tmpX, 1)); % avoids repmat - faster than tmpX = tmpX - repmat(mean(tmpX), [size(tmpX,1) 1 1]); tmpall(wt(ind):wt(ind+1)-1,:,:) = squeeze(sum(bsxfun(@times, tmpX, wavarray),1)); end; elseif 0 % wavelets are processed one by one but all windows simultaneously % -> not faster than the regular iterative method tmpall = repmat(nan,[length(freqs) length(g.timesout) trials]); sizewav = length(g.win{1})-1; % max window size mainc = sizewav/2; indices = repmat([-sizewav/2:sizewav/2]', [1 length(g.indexout) trials]); indices = indices + repmat(g.indexout, [size(indices,1) 1 trials]); indices = indices + repmat(reshape(([1:trials]-1)*frame,1,1,trials), [size(indices,1) length(g.indexout) 1]); for freqind = 1:length(g.win) winc = (length(g.win{freqind})-1)/2; wins = length(g.win{freqind})-1; wini = [-wins/2:wins/2]+winc+mainc-winc+1; tmpX = data(indices(wini,:,:)); tmpX = bsxfun(@minus, tmpX, mean( tmpX, 1)); % avoids repmat - faster than tmpX = tmpX - repmat(mean(tmpX), [size(tmpX,1) 1 1]); tmpX = sum(bsxfun(@times, tmpX, g.win{freqind}'),1); tmpall(freqind,:,:) = tmpX; end; else % prepare wavelet filters % ----------------------- for index = 1:length(g.win) g.win{index} = transpose(repmat(g.win{index}, [trials 1])); end; % apply filters % ------------- verboseprintf(g.verbose, 'Processing time point (of %d):',length(g.timesout)); tmpall = zeros(length(g.win), length(g.indexout), size(data,2)); for index = 1:length(g.indexout) if rem(index,10) == 0, verboseprintf(g.verbose, ' %d',index); end if rem(index,120) == 0, verboseprintf(g.verbose, '\n'); end for freqind = 1:length(g.win) wav = g.win{freqind}; sizewav = size(wav,1)-1; %g.indexout(index), size(wav,1), g.freqs(freqind) if strcmpi(g.causal, 'off') tmpX = data([-sizewav/2:sizewav/2]+g.indexout(index),:); else tmpX = data([-sizewav:0]+g.indexout(index),:); end; tmpX = tmpX - ones(size(tmpX,1),1)*mean(tmpX); if strcmpi(g.detrend, 'on'), for trial = 1:trials tmpX(:,trial) = detrend(tmpX(:,trial)); end; end; tmpX = sum(wav .* tmpX); tmpall( freqind, index, :) = tmpX; end; end; end; end; verboseprintf(g.verbose, '\n'); % time-warp code begins -Jean % --------------------------- if ~isempty(g.timestretch) && length(g.timestretch{1}) > 0 timemarks = g.timestretch{1}'; if isempty(g.timestretch{2}) | length(g.timestretch{2}) == 0 timerefs = median(g.timestretch{1}',2); else timerefs = g.timestretch{2}; end trials = size(tmpall,3); % convert timerefs to subsampled ERSP space % ----------------------------------------- [dummy refsPos] = min(transpose(abs( ... repmat(timerefs, [1 length(g.indexout)]) - repmat(g.indexout, [length(timerefs) 1])))); refsPos(end+1) = 1; refsPos(end+1) = length(g.indexout); refsPos = sort(refsPos); for t=1:trials % convert timemarks to subsampled ERSP space % ------------------------------------------ %[dummy pos]=min(abs(repmat(timemarks(2:7,1), [1 length(g.indexout)])-repmat(g.indexout,[6 1]))); outOfTimeRangeTimeWarpMarkers = find(timemarks(:,t) < min(g.indexout) | timemarks(:,t) > max(g.indexout)); % if ~isempty(outOfTimeRangeTimeWarpMarkers) % verboseprintf(g.verbose, 'Timefreq warning: time-warp latencies in epoch %d are out of time range defined for calculation of ERSP.\n', t); % end; [dummy marksPos] = min(transpose( ... abs( ... repmat(timemarks(:,t), [1 length(g.indexout)]) ... - repmat(g.indexout, [size(timemarks,1) 1]) ... ) ... )); marksPos(end+1) = 1; marksPos(end+1) = length(g.indexout); marksPos = sort(marksPos); %now warp tmpall mytmpall = tmpall(:,:,t); r = sqrt(mytmpall.*conj(mytmpall)); theta = angle(mytmpall); % So mytmpall is almost equal to r.*exp(i*theta) % whos marksPos refsPos M = timewarp(marksPos, refsPos); TSr = transpose(M*r'); TStheta = zeros(size(theta,1), size(theta,2)); for freqInd=1:size(TStheta,1) TStheta(freqInd, :) = angtimewarp(marksPos, refsPos, theta(freqInd, :)); end TStmpall = TSr.*exp(i*TStheta); % $$$ keyboard; tmpall(:,:,t) = TStmpall; end end %time-warp ends zerovals = tmpall == 0; if any(reshape(zerovals, 1, prod(size(zerovals)))) tmpall(zerovals) = Inf; minval = min(tmpall(:)); % remove bug tmpall(zerovals) = minval; end; % compute and subtract ITC % ------------------------ if nargout > 3 || strcmpi(g.subitc, 'on') itcvals = tfitc(tmpall, g.itctype); end; if strcmpi(g.subitc, 'on') %a = gcf; figure; imagesc(abs(itcvals)); cbar; figure(a); if ndims(tmpall) <= 3 tmpall = (tmpall - abs(tmpall) .* repmat(itcvals, [1 1 trials])) ./ abs(tmpall); else tmpall = (tmpall - abs(tmpall) .* repmat(itcvals, [1 1 1 trials])) ./ abs(tmpall); end; end; % find closest output frequencies % ------------------------------- if length(g.freqs) ~= length(freqs) || any(g.freqs ~= freqs) allindices = zeros(1,length(g.freqs)); for index = 1:length(g.freqs) [dum ind] = min(abs(freqs-g.freqs(index))); allindices(index) = ind; end; verboseprintf(g.verbose, 'finding closest frequencies: %d freqs removed\n', length(freqs)-length(allindices)); freqs = freqs(allindices); if ndims(tmpall) <= 3 tmpall = tmpall(allindices,:,:); else tmpall = tmpall(:,allindices,:,:); end; if nargout > 3 | strcmpi(g.subitc, 'on') if ndims(tmpall) <= 3 itcvals = itcvals(allindices,:,:); else itcvals = itcvals(:,allindices,:,:); end; end; end; timesout = g.timesout; %figure; imagesc(abs(sum(itcvals,3))); cbar; return; % function for itc % ---------------- function [itcvals] = tfitc(tfdecomp, itctype); % first dimension are trials nd = max(3,ndims(tfdecomp)); switch itctype case 'coher', try, itcvals = sum(tfdecomp,nd) ./ sqrt(sum(tfdecomp .* conj(tfdecomp),nd) * size(tfdecomp,nd)); catch, % scan rows if out of memory for index =1:size(tfdecomp,1) itcvals(index,:,:) = sum(tfdecomp(index,:,:,:),nd) ./ sqrt(sum(tfdecomp(index,:,:,:) .* conj(tfdecomp(index,:,:,:)),nd) * size(tfdecomp,nd)); end; end; case 'phasecoher2', try, itcvals = sum(tfdecomp,nd) ./ sum(sqrt(tfdecomp .* conj(tfdecomp)),nd); catch, % scan rows if out of memory for index =1:size(tfdecomp,1) itcvals(index,:,:) = sum(tfdecomp(index,:,:,:),nd) ./ sum(sqrt(tfdecomp(index,:,:,:) .* conj(tfdecomp(index,:,:,:))),nd); end; end; case 'phasecoher', try, itcvals = sum(tfdecomp ./ sqrt(tfdecomp .* conj(tfdecomp)) ,nd) / size(tfdecomp,nd); catch, % scan rows if out of memory for index =1:size(tfdecomp,1) itcvals(index,:,:) = sum(tfdecomp(index,:,:,:) ./ sqrt(tfdecomp(index,:,:,:) .* conj(tfdecomp(index,:,:,:))) ,nd) / size(tfdecomp,nd); end; end; end % ~any(isnan()) return; function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end % get time points % --------------- function [ timevals, timeindices ] = gettimes(frames, tlimits, timevar, winsize, ntimevar, causal, verbose); timevect = linspace(tlimits(1), tlimits(2), frames); srate = 1000*(frames-1)/(tlimits(2)-tlimits(1)); if isempty(timevar) % no pre-defined time points if ntimevar(1) > 0 % generate linearly space vector % ------------------------------ if (ntimevar > frames-winsize) ntimevar = frames-winsize; if ntimevar < 0 error('Not enough data points, reduce the window size or lowest frequency'); end; verboseprintf(verbose, ['Value of ''timesout'' must be <= frame-winsize, ''timesout'' adjusted to ' int2str(ntimevar) '\n']); end npoints = ntimevar(1); wintime = 500*winsize/srate; if strcmpi(causal, 'on') timevals = linspace(tlimits(1)+2*wintime, tlimits(2), npoints); else timevals = linspace(tlimits(1)+wintime, tlimits(2)-wintime, npoints); end; verboseprintf(verbose, 'Generating %d time points (%1.1f to %1.1f ms)\n', npoints, min(timevals), max(timevals)); else % subsample data % -------------- nsub = -ntimevar(1); if strcmpi(causal, 'on') timeindices = [ceil(winsize+nsub):nsub:length(timevect)]; else timeindices = [ceil(winsize/2+nsub/2):nsub:length(timevect)-ceil(winsize/2)-1]; end; timevals = timevect( timeindices ); % the conversion at line 741 leaves timeindices unchanged verboseprintf(verbose, 'Subsampling by %d (%1.1f to %1.1f ms)\n', nsub, min(timevals), max(timevals)); end; else timevals = timevar; % check boundaries % ---------------- wintime = 500*winsize/srate; if strcmpi(causal, 'on') tmpind = find( (timevals >= tlimits(1)+2*wintime-0.0001) & (timevals <= tlimits(2)) ); else tmpind = find( (timevals >= tlimits(1)+wintime-0.0001) & (timevals <= tlimits(2)-wintime+0.0001) ); end; % 0.0001 account for numerical innacuracies on opteron computers if isempty(tmpind) error('No time points. Reduce time window or minimum frequency.'); end; if length(timevals) ~= length(tmpind) verboseprintf(verbose, 'Warning: %d out of %d time values were removed (now %3.2f to %3.2f ms) so the lowest\n', ... length(timevals)-length(tmpind), length(timevals), timevals(tmpind(1)), timevals(tmpind(end))); verboseprintf(verbose, ' frequency could be computed with the requested accuracy\n'); end; timevals = timevals(tmpind); end; % find closet points in data % -------------------------- timeindices = round(eeg_lat2point(timevals, 1, srate, tlimits, 1E-3)); if length(timeindices) < length(unique(timeindices)) timeindices = unique_bc(timeindices) verboseprintf(verbose, 'Warning: duplicate times, reduce the number of output times\n'); end; if length(unique(timeindices(2:end)-timeindices(1:end-1))) > 1 verboseprintf(verbose, 'Finding closest points for time variable\n'); verboseprintf(verbose, 'Time values for time/freq decomposition is not perfectly uniformly distributed\n'); else verboseprintf(verbose, 'Distribution of data point for time/freq decomposition is perfectly uniform\n'); end; timevals = timevect(timeindices); % DEPRECATED, FOR C INTERFACE function nofunction() % C PART %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% filename = [ 'tmpcrossf' num2str(round(rand(1)*1000)) ]; f = fopen([ filename '.in'], 'w'); fwrite(f, tmpsaveall, 'int32'); fwrite(f, g.detret, 'int32'); fwrite(f, g.srate, 'int32'); fwrite(f, g.maxfreq, 'int32'); fwrite(f, g.padratio, 'int32'); fwrite(f, g.cycles, 'int32'); fwrite(f, g.winsize, 'int32'); fwrite(f, g.timesout, 'int32'); fwrite(f, g.subitc, 'int32'); fwrite(f, g.type, 'int32'); fwrite(f, trials, 'int32'); fwrite(f, g.naccu, 'int32'); fwrite(f, length(X), 'int32'); fwrite(f, X, 'double'); fwrite(f, Y, 'double'); fclose(f); command = [ '!cppcrosff ' filename '.in ' filename '.out' ]; eval(command); f = fopen([ filename '.out'], 'r'); size1 = fread(f, 'int32', 1); size2 = fread(f, 'int32', 1); Rreal = fread(f, 'double', [size1 size2]); Rimg = fread(f, 'double', [size1 size2]); Coher.R = Rreal + j*Rimg; Boot.Coherboot.R = []; Boot.Rsignif = []; function verboseprintf(verbose, varargin) if strcmpi(verbose, 'on') fprintf(varargin{:}); end;
github
lcnbeapp/beapp-master
pac_cont.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/pac_cont.m
17,447
utf_8
9b94d431be58419e3715e54645687469
% pac_cont() - compute phase-amplitude coupling (power of first input % correlation with phase of second). There is no graphical output % to this function. % % Usage: % >> pac_cont(x,y,srate); % >> [pac timesout pvals] = pac_cont(x,y,srate,'key1', 'val1', 'key2', val2' ...); % % Inputs: % x = [float array] 1-D data vector of size (1xtimes) % y = [float array] 1-D data vector of size (1xtimes) % srate = data sampling rate (Hz) % % Optional time information intputs: % '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} % '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 PAC inputs: % 'method' = ['modulation'|'plv'|'corr'|'glm'] (see reference). % 'freqphase' = [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). % 'freqamp' = [float array] array of frequencies for the second % argument. 'freqs' is used for the first argument. % By default it is the same as 'freqs'. % 'filterfunc' = ['eegfilt'|'iirfilt'|'eegfftfilt'] filtering function. % Default is iirfilt. Warning, filtering may dramatically % affect the result. With the 'corr' method, make sure you % have a large window size because each window is filtered % independently. % 'filterphase' = @f_handle. Function handle to filter the data for the % phase information. For example, @(x)iirfilt(x, 1000, 2, % 20). Note that 'freqphase' is ignore in this case. % 'filteramp' = @f_handle. Function handle to filter the data for the % amplitude information. Note that 'freqamp' is ignore in % this case. % % Inputs for statistics: % 'alpha' = [float] p-value threshold. Default is none (no statistics). % 'mcorrect' = ['none'|'fdr'] method to correct for multiple comparison. % Default is 'none'. % 'baseline' = [min max] baseline period for the Null distribution. Default % is the whole data range. Note that this option is ignored % for instanstaneous statistics. % 'instantstat' = ['on'|'off'] performs statistics for each time window % independently. Default is 'off'. % 'naccu' = [integer] number of accumulations for surrogate % statistics. % 'statlim' = ['parametric'|'surrogate'] use a parametric methods to % asseess the limit of the surrogate distribution or use % the tail of the distribution ('surrogate' method) % % Other inputs: % 'title' = [string] figure title. Default is none. % 'vert' = [float array] array of time value for which to plot % vertical lines. Default is none. % % Outputs: % pac = Phase-amplitude coupling values. % timesout = vector of time indices % pvals = Associated p-values % % Author: Arnaud Delorme and Makoto Miyakoshi, SCCN/INC, UCSD 2012- % % References: % Methods used here are introduced and compared in: % Penny, Duzel, Miller, Ojemann. (20089). Testing for Nested Oscilations. % J Neuro Methods. 174:50-61 % % Modulation Index is defined in: % Canolty, Edwards, Dalal, Soltani, Nagarajan, Kirsch, et al. (2006). Modulation index is defined in High Gamma Power Is Phase-Locked to Theta % Oscillations in Human Neocortex. Science. 313:1626-8. % % PLV (Phase locking value) is defined in: % Lachaux, Rodriguez, Martiniere, Varela. (1999). Measuring phase synchrony % in brain signal. Hum Brain Mapp. 8:194-208. % % corr (correlation) method is defined in: % Brunce, Eckhorn. (2004). Task-related coupling from high- to % low-frequency signals among visual cortical areas in human subdural % recordings. Int J Psychophysiol. 51:97-116. % % glm (general linear model) is defined in % Penny, Duzel, Miller, Ojemann. (20089). Testing for Nested Oscilations. % J Neuro Methods. 174:50-61 % Copyright (C) 2012 Arnaud Delorme, 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 [m_raw pvals indexout] = pac_cont(X, Y, srate, varargin); if nargin < 1 help pac_cont; return; end; % deal with 3-D inputs % -------------------- if ndims(X) == 3 || ndims(Y) == 3, error('Cannot process 3-D input'); end; if size(X,1) > 1, X = X'; end; if size(Y,1) > 1, Y = Y'; end; if size(X,1) ~= 1 || size(Y,1) ~= 1, error('Cannot only process vector input'); end; frame = size(X,2); pvals = []; g = finputcheck(varargin, ... { ... 'alpha' 'real' [0 0.2] []; 'baseline' 'float' [] []; 'freqphase' 'real' [0 Inf] [0 srate/2]; 'freqamp' 'real' [0 Inf] []; 'mcorrect' 'string' { 'none' 'fdr' } 'none'; 'method' 'string' { 'plv' 'modulation' 'glm' 'corr' } 'modulation'; 'naccu' 'integer' [1 Inf] 250; 'instantstat' 'string' {'on','off'} 'off'; 'newfig' 'string' {'on','off'} 'on'; 'nofig' 'string' {'on','off'} 'off'; 'statlim' 'string' {'surrogate','parametric'} 'parametric'; 'timesout' 'real' [] []; ... 'filterfunc' 'string' { 'eegfilt' 'iirfilt' 'eegfiltfft' } 'eegfiltfft'; ... 'filterphase' '' {} []; 'filteramp' '' {} []; 'ntimesout' 'integer' [] 200; ... 'tlimits' 'real' [] [0 frame/srate]; 'title' 'string' [] ''; 'vert' 'real' [] []; 'winsize' 'integer' [0 Inf] max(pow2(nextpow2(frame)-3),4) }, 'pac'); if isstr(g), error(g); end; if ~isempty(g.filterphase) x_freqphase = feval(g.filterphase, X(:)'); else x_freqphase = feval(g.filterfunc, X(:)', srate, g.freqphase(1), g.freqphase(end)); end; if ~isempty(g.filteramp) x_freqamp = feval(g.filteramp, Y(:)'); else x_freqamp = feval(g.filterfunc, Y(:)', srate, g.freqamp( 1), g.freqamp( end)); end; z_phasedata = hilbert(x_freqphase); z_ampdata = hilbert(x_freqamp); phase = angle(z_phasedata); amplitude = abs( z_ampdata); z = amplitude.*exp(i*phase); % this is the pac measure % get time windows % ---------------- g.verbose = 'on'; g.causal = 'off'; [ timesout1 indexout ] = gettimes(frame, g.tlimits, g.timesout, g.winsize, g.ntimesout, g.causal, g.verbose); % scan time windows % ----------------- if ~isempty(g.alpha) m_raw = zeros(1,length(indexout)); pvals = zeros(1,length(indexout)); end; fprintf('Computing PAC:\n'); for iWin = 1:length(indexout) x_phaseEpoch = x_freqphase(indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); x_ampEpoch = x_freqamp( indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); z_phaseEpoch = z_phasedata(indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); z_ampEpoch = z_ampdata( indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); z_epoch = z( indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); numpoints=length(x_phaseEpoch); if rem(iWin,10) == 0, verboseprintf(g.verbose, ' %d',iWin); end if rem(iWin,120) == 0, verboseprintf(g.verbose, '\n'); end % Choose method % ------------- if strcmpi(g.method, 'modulation') % Modulation index m_raw(iWin) = abs(sum(z_epoch))/numpoints; elseif strcmpi(g.method, 'plv') if iWin == 145 %dsfsd; end; %amplitude_filt = sgolayfilt(amplitude, 3, 101); if ~isempty(g.filterphase) amplitude_filt = feval(g.filterphase, z_ampEpoch); else amplitude_filt = feval(g.filterfunc , z_ampEpoch, srate, g.freqphase(1), g.freqphase(end)); end; z_amplitude_filt = hilbert(amplitude_filt); phase_amp_modulation = angle(z_amplitude_filt); m_raw(iWin) = abs(sum(exp(i*(x_phaseEpoch - phase_amp_modulation)))/numpoints); elseif strcmpi(g.method, 'corr') if iWin == inf %145 figure; plot(abs(z_ampdata)) hold on; plot(x_phasedata/10000000000, 'r') x = X(indexout(iWin)+[-g.winsize/2+1:g.winsize/2]); hold on; plot(x, 'g'); dsfsd; end; [r_ESC pval_corr] = corrcoef(x_phaseEpoch, abs(z_ampEpoch)); m_raw(iWin) = r_ESC(1,2); pvals(iWin) = pval_corr(1,2); elseif strcmpi(g.method, 'glm') [b dev stats] = glmfit(x_phaseEpoch', abs(z_ampEpoch)', 'normal'); GLM_beta = stats.beta(2,1); pvals(iWin) = stats.p(2,1); m_raw(iWin) = b(1); end; %% compute statistics (instantaneous) % ----------------------------------- if ~isempty(g.alpha) && strcmpi(g.instantstat, 'on') && ~strcmpi(g.method, 'corr') && ~strcmpi(g.method, 'glm') % compute surrogate values numsurrogate=g.naccu; minskip=srate; maxskip=numpoints-srate; % max variation half a second if maxskip < 1 error('Window size shorter than 1 second; too short for computing surrogate data'); end; skip=ceil(numpoints.*rand(numsurrogate*4,1)); skip(skip>maxskip)=[]; skip(skip<minskip)=[]; skip=skip(1:numsurrogate,1); surrogate_m=zeros(numsurrogate,1); for s=1:numsurrogate surrogate_amplitude=[amplitude(skip(s):end) amplitude(1:skip(s)-1)]; % consider circular shifts surrogate_m(s)=abs(mean(surrogate_amplitude.*exp(i*phase))); %disp(numsurrogate-s) end if strcmpi(g.statlim, 'surrogate') pvals(iWin) = stat_surrogate_pvals(surrogate_m, m_raw(iWin), 'upper'); %fprintf('Raw PAC is %3.2f (p-value=%1.3f)\n', m_raw(iWin), pvals(iWin)); else % Canolty method below %% fit gaussian to surrogate data, uses normfit.m from MATLAB Statistics toolbox [surrogate_mean,surrogate_std]=normfit(surrogate_m); %% normalize length using surrogate data (z-score) m_norm_length=(abs(m_raw(iWin))-surrogate_mean)/surrogate_std; pvals(iWin) = normcdf(0, m_norm_length, 1); m_norm_phase=angle(m_raw(iWin)); m_norm=m_norm_length*exp(i*m_norm_phase); % compare parametric and non-parametric methods (return similar % results) if iWin == length(indexout) figure; plot(-log10(pvals)); hold on; plot(-log10(pvals2), 'r'); end; end; end; end; fprintf('\n'); % Computes alpha % -------------- if ~isempty(g.alpha) && strcmpi(g.instantstat, 'off') if isempty(g.baseline) g.baseline = [ timesout1(1) timesout1(end) ]; end; baselineInd = find(timesout1 >= g.baseline(1) & timesout1 <= g.baseline(end)); m_raw_base = abs(m_raw(baselineInd)); if strcmpi(g.statlim, 'surrogate') for index = 1:length(m_raw) pvals(index) = stat_surrogate_pvals(m_raw_base, m_raw(index), 'upper'); end; else [surrogate_mean,surrogate_std]=normfit(m_raw_base); m_norm_length=(abs(m_raw)-surrogate_mean)/surrogate_std; pvals = normcdf(0, m_norm_length, 1); end; if strcmpi(g.mcorrect, 'fdr') pvals = fdr(pvals); end; end; %% plot results % ------------- if strcmpi(g.nofig, 'on') return end; if strcmpi(g.newfig, 'on') figure; end; if ~isempty(g.alpha) plotcurve(timesout1, m_raw, 'maskarray', pvals < g.alpha); else plotcurve(timesout1, m_raw); end; xlabel('Time (ms)'); ylabel('PAC (0 to 1)'); title(g.title); % plot vertical lines % ------------------- if ~isempty(g.vert) hold on; yl = ylim; for index = 1:length(g.vert) plot([g.vert(index) g.vert(index)], yl, 'g'); end; end; % ------------- % gettime function identical to timefreq function % DO NOT MODIFY % ------------- function [ timevals, timeindices ] = gettimes(frames, tlimits, timevar, winsize, ntimevar, causal, verbose); timevect = linspace(tlimits(1), tlimits(2), frames); srate = 1000*(frames-1)/(tlimits(2)-tlimits(1)); if isempty(timevar) % no pre-defined time points if ntimevar(1) > 0 % generate linearly space vector % ------------------------------ if (ntimevar > frames-winsize) ntimevar = frames-winsize; if ntimevar < 0 error('Not enough data points, reduce the window size or lowest frequency'); end; verboseprintf(verbose, ['Value of ''timesout'' must be <= frame-winsize, ''timesout'' adjusted to ' int2str(ntimevar) '\n']); end npoints = ntimevar(1); wintime = 500*winsize/srate; if strcmpi(causal, 'on') timevals = linspace(tlimits(1)+2*wintime, tlimits(2), npoints); else timevals = linspace(tlimits(1)+wintime, tlimits(2)-wintime, npoints); end; verboseprintf(verbose, 'Generating %d time points (%1.1f to %1.1f ms)\n', npoints, min(timevals), max(timevals)); else % subsample data % -------------- nsub = -ntimevar(1); if strcmpi(causal, 'on') timeindices = [ceil(winsize+nsub):nsub:length(timevect)]; else timeindices = [ceil(winsize/2+nsub/2):nsub:length(timevect)-ceil(winsize/2)-1]; end; timevals = timevect( timeindices ); % the conversion at line 741 leaves timeindices unchanged verboseprintf(verbose, 'Subsampling by %d (%1.1f to %1.1f ms)\n', nsub, min(timevals), max(timevals)); end; else timevals = timevar; % check boundaries % ---------------- wintime = 500*winsize/srate; if strcmpi(causal, 'on') tmpind = find( (timevals >= tlimits(1)+2*wintime-0.0001) & (timevals <= tlimits(2)) ); else tmpind = find( (timevals >= tlimits(1)+wintime-0.0001) & (timevals <= tlimits(2)-wintime+0.0001) ); end; % 0.0001 account for numerical innacuracies on opteron computers if isempty(tmpind) error('No time points. Reduce time window or minimum frequency.'); end; if length(timevals) ~= length(tmpind) verboseprintf(verbose, 'Warning: %d out of %d time values were removed (now %3.2f to %3.2f ms) so the lowest\n', ... length(timevals)-length(tmpind), length(timevals), timevals(tmpind(1)), timevals(tmpind(end))); verboseprintf(verbose, ' frequency could be computed with the requested accuracy\n'); end; timevals = timevals(tmpind); end; % find closet points in data % -------------------------- timeindices = round(eeg_lat2point(timevals, 1, srate, tlimits, 1E-3)); if length(timeindices) < length(unique(timeindices)) timeindices = unique_bc(timeindices) verboseprintf(verbose, 'Warning: duplicate times, reduce the number of output times\n'); end; if length(unique(timeindices(2:end)-timeindices(1:end-1))) > 1 verboseprintf(verbose, 'Finding closest points for time variable\n'); verboseprintf(verbose, 'Time values for time/freq decomposition is not perfectly uniformly distributed\n'); else verboseprintf(verbose, 'Distribution of data point for time/freq decomposition is perfectly uniform\n'); end; timevals = timevect(timeindices); function verboseprintf(verbose, varargin) if strcmpi(verbose, 'on') fprintf(varargin{:}); end;
github
lcnbeapp/beapp-master
dftfilt3.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/dftfilt3.m
7,390
utf_8
7ef2a5114ee38513d5a55a8f38553cb1
% dftfilt3() - discrete complex wavelet filters % % Usage: % >> [wavelet,cycles,freqresol,timeresol] = dftfilt3( freqs, cycles, srate, varargin) % % Inputs: % freqs - vector of frequencies of interest. % cycles - cycles array. If cycles=0, then the Hanning tapered Short-term FFT is used. % If one value is given and cycles>0, all wavelets have % the same number of cycles. If two values are given, the % two values are used for the number of cycles at the lowest % frequency and at the highest frequency, with linear or % log-linear interpolation between these values for intermediate % frequencies % srate - sampling rate (in Hz) % % Optional Inputs: Input these as 'key/value pairs. % 'cycleinc' - ['linear'|'log'] increase mode if [min max] cycles is % provided in 'cycle' parameter. {default: 'linear'} % 'winsize' Use this option for Hanning tapered FFT or if you prefer to set the length of the % wavelets to be equal for all of them (e.g., to set the % length to 256 samples input: 'winsize',256). {default: []) % Note: the output 'wavelet' will be a matrix and it may be % incompatible with current versions of timefreq and newtimef. % 'timesupport' The number of temporal standard deviation used for wavelet lengths {default: 7) % % Output: % wavelet - cell array or matrix of wavelet filters % timeresol - temporal resolution of Morlet wavelets. % freqresol - frequency resolution of Morlet wavelets. % % Note: The length of the window is always made odd. % % Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 3/28/2003 % Rey Ramirez, SCCN/INC/UCSD, La Jolla, 9/26/2006 % Copyright (C) 3/28/2003 Arnaud Delorme 8, 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 % % Revision 1.12 2006/09/25 rey r % Almost complete rewriting of dftfilt2.m, changing both Morlet and Hanning % DFT to be more in line with conventional implementations. % % Revision 1.11 2006/09/07 19:05:34 scott % further clarified the Morlet/Hanning distinction -sm % % Revision 1.10 2006/09/07 18:55:15 scott % clarified window types in help msg -sm % % Revision 1.9 2006/05/05 16:17:36 arno % implementing cycle array % % Revision 1.8 2004/03/04 19:31:03 arno % email % % Revision 1.7 2004/02/25 01:45:55 arno % sinus test % % Revision 1.6 2004/02/15 22:23:08 arno % implementing morlet wavelet % % Revision 1.5 2003/05/09 20:55:10 arno % adding hanning function % % Revision 1.4 2003/04/29 16:02:54 arno % header typos % % Revision 1.3 2003/04/29 01:09:16 arno % debug imaginary part % % Revision 1.2 2003/04/28 23:01:13 arno % *** empty log message *** % % Revision 1.1 2003/04/28 22:46:49 arno % Initial revision % function [wavelet,cycles,freqresol,timeresol] = dftfilt3( freqs, cycles, srate, varargin); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Rey fixed all input parameter sorting. if nargin < 3 error(' A minimum of 3 arguments is required'); end; numargin=length(varargin); if rem(numargin,2) error('There is an uneven number key/value inputs. You are probably missing a keyword or its value.') end varargin(1:2:end)=lower(varargin(1:2:end)); % Setting default parameter values. cycleinc='linear'; winsize=[]; timesupport=7; % Setting default of 7 temporal standard deviations for wavelet's length. for n=1:2:numargin keyword=varargin{n}; if strcmpi('cycleinc',keyword) cycleinc=varargin{n+1}; elseif strcmpi('winsize',keyword) winsize=varargin{n+1}; if ~mod(winsize,2) winsize=winsize+1; % Always set to odd length wavelets and hanning windows; end elseif strcmpi('timesupport',keyword) timesupport=varargin{n+1}; else error(['What is ' keyword '? The only legal keywords are: type, cycleinc, winsize, or timesupport.']) end end if isempty(winsize) & cycles==0 error('If you are using a Hanning tapered FFT, please supply the winsize input-pair.') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute number of cycles at each frequency % ------------------------------------------ type='morlet'; if length(cycles) == 1 & cycles(1)~=0 cycles = cycles*ones(size(freqs)); elseif length(cycles) == 2 if strcmpi(cycleinc, 'log') % cycleinc cycles = linspace(log(cycles(1)), log(cycles(2)), length(freqs)); cycles = exp(cycles); %cycles=logspace(log10(cycles(1)),log10(cycles(2)),length(freqs)); %rey else cycles = linspace(cycles(1), cycles(2), length(freqs)); end; end; if cycles==0 type='sinus'; end sp=1/srate; % Rey added this line (i.e., sampling period). % compute wavelet for index = 1:length(freqs) fk=freqs(index); if strcmpi(type, 'morlet') % Morlet. sigf=fk/cycles(index); % Computing time and frequency standard deviations, resolutions, and normalization constant. sigt=1./(2*pi*sigf); A=1./sqrt(sigt*sqrt(pi)); timeresol(index)=2*sigt; freqresol(index)=2*sigf; if isempty(winsize) % bases will be a cell array. tneg=[-sp:-sp:-sigt*timesupport/2]; tpos=[0:sp:sigt*timesupport/2]; t=[fliplr(tneg) tpos]; psi=A.*(exp(-(t.^2)./(2*(sigt^2))).*exp(2*i*pi*fk*t)); wavelet{index}=psi; % These are the wavelets with variable number of samples based on temporal standard deviations (sigt). else % bases will be a matrix. tneg=[-sp:-sp:-sp*winsize/2]; tpos=[0:sp:sp*winsize/2]; t=[fliplr(tneg) tpos]; psi=A.*(exp(-(t.^2)./(2*(sigt^2))).*exp(2*i*pi*fk*t)); wavelet(index,:)=psi; % These are the wavelets with the same length. % This is useful for doing time-frequency analysis as a matrix vector or matrix matrix multiplication. end elseif strcmpi(type, 'sinus') % Hanning tneg=[-sp:-sp:-sp*winsize/2]; tpos=[0:sp:sp*winsize/2]; t=[fliplr(tneg) tpos]; win = exp(2*i*pi*fk*t); wavelet(index,:) = win .* hanning(winsize)'; %wavelet{index} = win .* hanning(winsize)'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end; end; % symmetric hanning function function w = hanning(n) if ~rem(n,2) w = .5*(1 - cos(2*pi*(1:n/2)'/(n+1))); w = [w; w(end:-1:1)]; else w = .5*(1 - cos(2*pi*(1:(n+1)/2)'/(n+1))); w = [w; w(end-1:-1:1)]; end
github
lcnbeapp/beapp-master
rsget.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/rsget.m
1,800
utf_8
47daf6498859ced84787d07802f22789
% rsget() - get the p-value for a given collection of l-values % (Ramberg-Schmeiser distribution) % % Usage: p = getfit(l, val) % % Input: % l - [l1 l2 l3 l4] l-values for Ramberg-Schmeiser distribution % val - value in the distribution to get a p-value estimate at % % Output: % p - p-value % % Author: Arnaud Delorme, SCCN, 2003 % % see also: rspfunc() % % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % A probability distribution and its uses in fitting data. % Technimetrics, 1979, 21: 201-214. % Copyright (C) 2003 Arnaud Delorme, SCCN, [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 p = rsget( l, val); % plot the curve % -------------- %pval = linspace(0,1, 102); pval(1) = []; pval(end) = []; %rp = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2); %fp = l(2)*1./(l(3).*(pval.^(l(3)-1)) + l(4).*((1-pval).^(l(4)-1))); %figure; plot(pval, rp); %figure; plot(rp, fp); % find p value for a given val % ---------------------------- p = fminbnd('rspfunc', 0, 1, optimset('TolX',1e-300), l, val);
github
lcnbeapp/beapp-master
rsfit.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/rsfit.m
6,481
utf_8
ea9ce35750ccb745a5f9471fc6554a91
% rsfit() - find p value for a given value in a given distribution % using Ramberg-Schmeiser distribution % % Usage: >> p = rsfit(x, val) % >> [p c l chi2] = rsfit(x, val, plot) % % Input: % x - [float array] accumulation values % val - [float] value to test % plot - [0|1|2] plot fit. Using 2, the function avoids creating % a new figure. Default: 0. % % Output: % p - p value % c - [mean var skewness kurtosis] distribution cumulants % l - [4x float vector] Ramberg-Schmeiser distribution best fit % parameters. % chi2 - [float] chi2 for goodness of fit (based on 12 bins). % Fit is significantly different from data histogram if % chi2 > 19 (5%) % % Author: Arnaud Delorme, SCCN, 2003 % % See also: rsadjust(), rsget(), rspdfsolv(), rspfunc() % % Reference: Ramberg, J.S., Tadikamalla, P.R., Dudewicz E.J., Mykkytka, E.F. % A probability distribution and its uses in fitting data. % Technimetrics, 1979, 21: 201-214. % Copyright (C) 2003 Arnaud Delorme, SCCN, [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 [p, c, l, res] = rsfit(x, val, plotflag) if nargin < 2 help rsfit; return; end; if nargin < 3 plotflag = 0; end; % moments % ------- m1 = mean(x); m2 = sum((x-m1).^2)/length(x); m3 = sum((x-m1).^3)/length(x); m4 = sum((x-m1).^4)/length(x); xmean = m1; xvar = m2; xskew = m3/(m2^1.5); xkurt = m4/(m2^2); c = [ xmean xvar xskew xkurt ]; if xkurt < 0 disp('rsfit error: Can not fit negative kurtosis'); save('/home/arno/temp/dattmp.mat', '-mat', 'x'); disp('data saved to disk in /home/arno/temp/dattmp.mat'); end; % find fit % -------- try, [sol tmp exitcode] = fminsearch('rspdfsolv', [0.1 0.1], optimset('TolX',1e-12, 'MaxFunEvals', 100000000), abs(xskew), xkurt); catch, exitcode = 0; % did not converge end; if ~exitcode try, [sol tmp exitcode] = fminsearch('rspdfsolv', -[0.1 0.1], optimset('TolX',1e-12, 'MaxFunEvals', 100000000), abs(xskew), xkurt); catch, exitcode = 0; end; end; if ~exitcode, error('No convergence'); end; if sol(2)*sol(1) == -1, error('Wrong sign for convergence'); end; %fprintf(' l-val:%f\n', sol); res = rspdfsolv(sol, abs(xskew), xkurt); l3 = sol(1); l4 = sol(2); %load res; %[tmp indalpha3] = min( abs(rangealpha3 - xskew) ); %[tmp indalpha4] = min( abs(rangealpha4 - xkurt) ); %l3 = res(indalpha3,indalpha4,1); %l4 = res(indalpha3,indalpha4,2); %res = res(indalpha3,indalpha4,3); % adjust fit % ---------- [l1 l2 l3 l4] = rsadjust(l3, l4, xmean, xvar, xskew); l = [l1 l2 l3 l4]; p = rsget(l, val); % compute goodness of fit % ----------------------- if nargout > 3 | plotflag % histogram of value 12 bins % -------------------------- [N X] = hist(x, 25); interval = X(2)-X(1); X = [X-interval/2 X(end)+interval/2]; % borders % regroup bin with less than 5 values % ----------------------------------- indices2rm = []; for index = 1:length(N)-1 if N(index) < 5 N(index+1) = N(index+1) + N(index); indices2rm = [ indices2rm index]; end; end; N(indices2rm) = []; X(indices2rm+1) = []; indices2rm = []; for index = length(N):-1:2 if N(index) < 5 N(index-1) = N(index-1) + N(index); indices2rm = [ indices2rm index]; end; end; N(indices2rm) = []; X(indices2rm) = []; % compute expected values % ----------------------- for index = 1:length(X)-1 p1 = rsget( l, X(index+1)); p2 = rsget( l, X(index )); expect(index) = length(x)*(p1-p2); end; % value of X2 % ----------- res = sum(((expect - N).^2)./expect); % plot fit % -------- if plotflag if plotflag ~= 2, figure('paperpositionmode', 'auto'); end; hist(x, 10); % plot fit % -------- xdiff = X(end)-X(1); abscisia = linspace(X(1)-0.2*xdiff, X(end)+0.2*xdiff, 100); %abscisia = (X(1:end-1)+X(2:end))/2; expectplot = zeros(1,length(abscisia)-1); for index = 2:length(abscisia); p1 = rsget( l, abscisia(index-1)); p2 = rsget( l, abscisia(index )); expectplot(index-1) = length(x)*(p2-p1); % have to do this subtraction since this a cumulate density distribution end; abscisia = (abscisia(2:end)+abscisia(1:end-1))/2; hold on; plot(abscisia, expectplot, 'r'); % plot PDF % ---------- pval = linspace(0,1, 102); pval(1) = []; pval(end) = []; rp = l(1) + (pval.^l(3) - (1-pval).^l(4))/l(2); fp = l(2)*1./(l(3).*(pval.^(l(3)-1)) + l(4).*((1-pval).^(l(4)-1))); [maxval index] = max(expect); [tmp closestind] = min(abs(rp - abscisia(index))); fp = fp./fp(closestind)*maxval; plot(rp, fp, 'g'); legend('Chi2 fit (some bins have been grouped)', 'Pdf', 'Data histogram' ); xlabel('Bins'); ylabel('# of data point per bin'); title (sprintf('Fit of distribution using Ramberg-Schmeiser distribution (Chi2 = %2.4g)', res)); end; end; return
github
lcnbeapp/beapp-master
timewarp.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/timewarp.m
3,452
utf_8
910bc9b6a9fca6b6a50908d815239dc6
% timewarp() - Given two event marker vectors, computes a matrix % that can be used to warp a time series so that its % evlatencies match newlatencies. Values of the warped % timeserie that falls between two frames in the original % timeserie will be linear interpolated. % Usage: % >> warpmat = timewarp(evlatency, newlatency) % % Necessary inputs: % evlatency - [vector] event markers in the original time series, in frames % Markers must be ordered by increasing frame latency. % If you want to warp the entire time-series, make sure % the first (1) and last frames are in the vector. % newlatency - [vector] desired warped event time latencies. The original % time series will be warped so that the frame numbers of its % events (see evlatency above) match the frame numbers in % newlatency. newlatency frames must be sorted by ascending % latency. Both vectors must be the same length. % % Optional outputs: % warpmat - [matrix] Multiplying this matrix with the original % time series (column) vectors performs the warping. % % Example: % % In 10-frame vectors, warp frames 3 and 5 to frames 4 and 8, % % respectively. Generate a matrix to warp data epochs in % % variable 'data' of size (10,k) % >> warpmat = timewarp([1 3 5 10], [1 4 8 10]) % >> warped_data = warpmat*data; % % Authors: Jean Hausser, SCCN/INC/UCSD, 2006 % % See also: angtimewarp(), phasecoher(), erpimage() % function M=timewarp(evLatency, newLatency) M = [0]; if min(sort(evLatency) == evLatency) == 0 error('evLatency should be in ascending order'); return; end if min(sort(newLatency) == newLatency) == 0 error('newLatency should be in ascending order'); return; end if length(evLatency) ~= length(newLatency) error('evLatency and newLatency must have the same length.'); return; end if length(evLatency) < 2 | length(newLatency) < 2 error(['There should be at least two events in evlatency and ' ... 'newlatency (e.g., "begin" and "end")'] ); return; end if evLatency(1) ~= 1 disp(['Assuming old and new time series beginnings are synchronized.']); disp(['Make sure you have defined an ending event in both the old and new time series!']); evLatency(end+1)=1; newLatency(end+1)=1; evLatency = sort(evLatency); newLatency = sort(newLatency); end t = 1:max(evLatency); for k=1:length(evLatency)-1 for i=evLatency(k):evLatency(k+1)-1 tp(i) = (t(i)-evLatency(k)) * ... (newLatency(k+1) - newLatency(k))/... (evLatency(k+1) - evLatency(k)) + ... newLatency(k); end end % Check what's going on at tp(max(newLatency)), should equal t(max(evLatency)) tp(max(evLatency)) = max(newLatency); ts = tp-min(newLatency)+1; % $$$ M = sparse(max(newLatency)-min(newLatency)+1, max(evLatency)); M = zeros(max(newLatency)-min(newLatency)+1, max(evLatency)); k = 0; for i=1:size(M,1) while i > ts(k+1) k = k+1; end % $$$ k = k-1; if k == 0 % Check wether i == ts(1) and i == 1 % In that case, M(1,1) = 1 M(1,1) = 1; else M(i,k) = 1 - (i-ts(k))/(ts(k+1)-ts(k)); M(i,k+1) = 1 - (ts(k+1)-i)/(ts(k+1)-ts(k)); end end
github
lcnbeapp/beapp-master
angtimewarp.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/timefreqfunc/angtimewarp.m
4,683
utf_8
f46e870ae5d7873544a08ffa9a4ff38b
% angtimewarp() - Given two event marker vectors, computes a % warping of the input angular time series so that its % evlatencies match newlatencies. Values of the warped % timeserie that falls between two frames in the original % timeserie will be linearly interpolated under the % assumption that phase change is minimal between two % successive time points. % Usage: % >> warpAngs = angtimewarp(evlatency, newlatency, angData) % % Necessary inputs: % evlatency - [vector] time markers on the original time-series, in % frames. Markers must be ordered by increasing % latency. If you want to warp the entire time series, % make sure frame 1 and the last frame are in the vector. % newlatency - [vector] desired time marker latencies. The original % time series will be warped so that its time markers (see % evlatency) match the ones in newlatency. newlatency % frames must be sorted by ascending latencies in frames. % Both vectors have to be the same length. % angData - [vector] original angular time series (in radians). % Angles should be between -pi and pi. % % Optional outputs: % warpAngs - [vector] warped angular time-course, with values between % -pi and pi % % Example: % >> angs = 2*pi*rand(1,10)-pi; % >> warpangs = angtimewarp([1 5 10], [1 6 10], angs) % % Authors: Jean Hausser, SCCN/INC/UCSD, 2006 % % See also: timeWarp(), phasecoher(), erpimage(), newtimef() % function angdataw=angtimewarp(evLatency, newLatency, angdata) if min(sort(evLatency) == evLatency) == 0 error('evlatency should be sorted'); return; end if min(sort(newLatency) == newLatency) == 0 error('newlatency should be sorted'); return; end if length(evLatency) ~= length(newLatency) error('evlatency and newlatency must have the same length.'); return; end if length(evLatency) < 2 | length(newLatency) < 2 error(['There should be at least two events in evlatency and ' ... 'newlatency, that is "begin" and "end"' ]); return; end if evLatency(1) ~= 1 disp(['Assuming old and new time series beginnings are ' ... 'synchronized']); disp(['Make sure you defined an end event for both old and new time ' ... 'series !']); evLatency(end+1)=1; newLatency(end+1)=1; evLatency = sort(evLatency); newLatency = sort(newLatency); end t = 1:max(evLatency); for k=1:length(evLatency)-1 for i=evLatency(k):evLatency(k+1)-1 tp(i) = (t(i)-evLatency(k)) * ... (newLatency(k+1) - newLatency(k))/... (evLatency(k+1) - evLatency(k)) + ... newLatency(k); end end %Check what's going on at tp(max(newLatency)), should equal t(max(evLatency)) tp(max(evLatency)) = max(newLatency); ts = tp-min(newLatency)+1; angdataw = zeros(1, max(newLatency)-min(newLatency)+1); k = 0; for i=1:length(angdataw) while i > ts(k+1) k = k+1; end if k == 0 angdataw(1) = angdata(1); else %Linear interp angdataw(i) = angdata(k)*(1 - (i-ts(k))/(ts(k+1)-ts(k))) + ... angdata(k+1)*(1 - (ts(k+1)-i)/(ts(k+1)-ts(k))); % %Correction because angles have a ring structure % theta1 = [angdata(k) angdata(k+1) angdataw(i)]; % theta2 = theta1 - min(angdata(k), angdata(k+1)); % theta2max = max(theta2(1), theta2(2)); % if ~ ( (theta2max <= pi & theta2(3) <= theta2max) | ... % (theta2max >= pi & theta2(3) >= theta2max) | ... % theta2(3) == theta2(1) | theta2(3) == theta2(2) ) % angdataw(i) = angdataw(i) + pi; % end % if angdataw(i) > pi %Make sure we're still on [-pi, pi] % angdataw(i) = angdataw(i) - 2*pi; % end end end angdataw = wrap2pi(angdataw); function a = wrap2pi(a, a_center ) % function a = wrap(a,a_center) % % Wraps angles to a range of 2*pi. % Inverse of Matlab's "unwrap", and better than wrapToPi ( which has % redundant [-pi,pi]) % Optional input "a_center" defines the center angle. Default is 0, giving % angles from (-pi,pi], chosen to match angle(complex(-1,0)). Maximum % possible value is pi. % T.Hilmer, UH % 2010.10.18 version 2 % removed code from version 1. Have not bug-checked second input % "a_center" if nargin < 2, a_center = 0; end % new way a = mod(a,2*pi); % [0 2pi) % shift j = a > pi - a_center; a(j) = a(j) - 2*pi; j = a < a_center - pi; a(j) = a(j) + 2*pi;
github
lcnbeapp/beapp-master
shortread.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/shortread.m
2,642
utf_8
7efadd1fb9c9395f1cd3c917e6a93675
% shortread() - Read matrix from short file. % % Usage: % >> A = shortread(filename,size,'format',offset) % % Inputs: % filename - Read matrix a from specified file while assuming four byte % short integers. % size - The vector SIZE determine the number of short elements to be % read and the dimensions of the resulting matrix. If the last % element of SIZE is INF the size of the last dimension is determined % by the file length. % % Optional inputs: % 'format' - The option FORMAT argument specifies the storage format as % defined by fopen(). Default format ([]) is 'native'. % offset - The option OFFSET is offset in shorts from the beginning of file (=0) % to start reading (2-byte shorts assumed). % It uses fseek to read a portion of a large data file. % % Author: Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/1998 % % See also: floatread(), floatwrite(), fopen() % Copyright (C) Sigurd Enghoff, CNL / Salk Institute, La Jolla, 7/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 % xx-07-98 written by Sigurd Enghoff, Salk Institute % 04-26-99 modified by Sigurd Enghoff to handle variable-sized and % multi-dimensional data. % 07-08-99 modified by Sigurd Enghoff, FORMAT argument added. % 02-08-00 help updated for toolbox inclusion -sm % 02-14-00 added segment arg -sm function A = shortread(fname,Asize,fform,offset) if ~exist('fform') | isempty(fform)|fform==0 fform = 'native'; end fid = fopen(fname,'rb',fform); if fid>0 if exist('offset') stts = fseek(fid,2*offset,'bof'); if stts ~= 0 error('shortread(): fseek() error.'); return end end A = fread(fid,prod(Asize),'short'); else error('shortread(): fopen() error.'); return end fprintf(' %d shorts read\n',prod(size(A))); if Asize(end) == Inf Asize = Asize(1:end-1); A = reshape(A,[Asize length(A)/prod(Asize)]); else A = reshape(A,Asize); end fclose(fid);
github
lcnbeapp/beapp-master
scanfold.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/scanfold.m
2,396
utf_8
fc03538051488f1358961f46484d958d
% scanfold() - scan folder content % % Usage: % >> [cellres textres] = scanfold(foldname); % >> [cellres textres] = scanfold(foldname, ignorelist, maxdepth); % % Inputs: % foldname - [string] name of the folder % ignorelist - [cell] list of folders to ignore % maxdepth - [integer] maximum folder depth % % Outputs: % cellres - cell array containing all the files % textres - string array containing all the names preceeded by "-a" % % Authors: Arnaud Delorme, SCCN, INC, UCSD, 2009 % 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 [ cellres, textres ] = scanfold(foldname, ignorelist, maxdepth) if nargin < 2, ignorelist = {}; end; if nargin < 3, maxdepth = 100; end; foldcontent = dir(foldname); textres = ''; cellres = {}; if maxdepth == 0, return; end; for i = 1:length(foldcontent) if (exist(foldcontent(i).name) == 7 || strcmpi(foldcontent(i).name, 'functions')) && ~ismember(foldcontent(i).name, ignorelist) if ~strcmpi(foldcontent(i).name, '..') && ~strcmpi(foldcontent(i).name, '.') disp(fullfile(foldname, foldcontent(i).name)); [tmpcellres tmpres] = scanfold(fullfile(foldname, foldcontent(i).name), ignorelist, maxdepth-1); textres = [ textres tmpres ]; cellres = { cellres{:} tmpcellres{:} }; end; elseif length(foldcontent(i).name) > 2 if strcmpi(foldcontent(i).name(end-1:end), '.m') textres = [ textres ' -a ' foldcontent(i).name ]; cellres = { cellres{:} foldcontent(i).name }; end; else disp( [ 'Skipping ' fullfile(foldname, foldcontent(i).name) ]); end; end; return;
github
lcnbeapp/beapp-master
datlim.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/datlim.m
641
utf_8
f4c0160c492f5049e9dbcc932cafe0e7
% datlim() - return min and max of a matrix % % Usage: % >> limits_vector = datlim(data); % % Input: % data - numeric array % Outputs: % limits_vector = [minval maxval] % % Author: Scott Makeig, SCCN/INC/UCSD, May 28, 2005 function [limits_vector] = datlim(data) if ~isnumeric(data) error('data must be a numeric array') return end limits_vector = [ min(data(:)) max(data(:)) ]; % thanks to Arno Delorme % minval = squeeze(min(data)); maxval = squeeze(max(data)); % while numel(minval) > 1 % minval = squeeze(min(minval)); maxval = squeeze(max(maxval)); % end % limits_vector = [minval maxval];
github
lcnbeapp/beapp-master
lapplot.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/lapplot.m
4,148
utf_8
bbfb726aee519b4b7b446c516439e24f
% lapplot() - Compute the discrete laplacian of EEG scalp distribution(s) % % Usage: % >> laplace = lapplot(map,eloc_file,draw) % % Inputs: % map - Activity levels, size (nelectrodes,nmaps) % eloc_file - Electrode location filename (.loc file) % For format, see >> topoplot example % draw - If defined, draw the map(s) {default: no} % % Output: % laplace - Laplacian map, size (nelectrodes,nmaps) % % Note: uses del2() % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 1998 % % See also: topoplot(), gradplot() % Copyright (C) Scott Makeig, SCCN/INC/UCSD, La Jolla, 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 % 01-25-02 reformated help & license, added links -ad function [laplac] = lapplot(map,filename,draw) if nargin < 2 help lapplot; return; end; MAXCHANS = size(map,1); GRID_SCALE = 2*MAXCHANS+5; MAX_RADIUS = 0.5; % --------------------- % Read the channel file % --------------------- if isstr( filename ) fid = fopen(filename); locations = fscanf(fid,'%d %f %f %s',[7 MAXCHANS]); fclose(fid); locations = locations'; Th = pi/180*locations(:,2); % convert degrees to rads Rd = locations(:,3); ii = find(Rd <= MAX_RADIUS); % interpolate on-scalp channels only Th = Th(ii); Rd = Rd(ii); [x,y] = pol2cart(Th,Rd); else x = real(filename); y = imag(filename); end; % --------------------------------------------------- % Locate nearest position of an 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) 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; % ----------------- % Compute laplacian % ----------------- 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(:)); % ------------------ % Draw laplacian map % ------------------ if exist('draw'); mask = (sqrt(Xi.^2+Yi.^2) <= MAX_RADIUS); laplac2D(find(mask==0)) = NaN; subplot(ceil(sqrt(size(map,2))), ceil(sqrt(size(map,2))), i); contour(laplac2D); title( int2str(i) ); % %%% Draw Head %%%% ax = axis; width = ax(2)-ax(1); axis([ax(1)-width/3 ax(2)+width/3 ax(3)-width/3 ax(4)+width/3]) 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
lcnbeapp/beapp-master
compmap.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/compmap.m
9,132
utf_8
91717f8d02db6c0193adc7ece08828ca
% compmap() - Plot multiple topoplot() maps of ICA component topographies % Click on an individual map to view separately. % Usage: % >> compmap (winv,'eloc_file',compnos,'title',rowscols,labels,printflag) % % 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). % 'eloc_file' - Name of the eloctrode position file in the style defined % by >> topoplot example {default|0 ->'chan_file'} % compnos - Vector telling which (order of) component maps to show % Indices <0 tell compmap to invert a map; = 0 leave blank sbplot % 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, else ' ' -> no labels {default|0 -> 1:ncolumns_in_winv} % printflag - 0= screen-plot colors {default} % 1= printer-plot colors % % Note: Map scaling is to +/-max(abs(data); green = 0 % % Author: Colin Humphries, CNL / Salk Institute, Aug, 1996 % % See also: topoplot() % This function calls topoplot(). and cbar(). % Copyright (C) Colin Humphries & Scott Makeig, CNL / Salk Institute, Aug, 1996 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % Colin Humphries, CNL / Salk Institute, Aug, 1996 % 03-97 revised -CH % 11-05-97 revised for Matlab 5.0.0.4064; added negative compnnos option % improved help msg; added figure offsets -Scott Makeig & CH % 11-13-97 fixed compnos<0 bug -sm % 11-18-97 added test for labels=comps -sm % 12-08-97 added test for colorbar_tp() -sm % 12-15-97 added axis('square'), see SQUARE below -sm % 03-09-98 added test for eloc_file, fixed size checking for labels -sm % 02-09-00 added test for ' ' for srclabels(1,1) -sm % 02-23-00 added srclabels==' ' -> no labels -sm % 03-16-00 added axcopy() -sm & tpj % 02-25-01 added test for max(compnos) -sm % 05-24-01 added HEADPLOT logical flag below -sm % 01-25-02 reformated help & license -ad % NOTE: % There is a minor problem with the Matlab function colorbar(). % Use the toolbox cbar() instead. function compmap(Winv,eloc_file,compnos,titleval,pagesize,srclabels,printlabel,caxis) 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 ELECTRODES = 'on'; % default: 'on' or 'off' ELECTRODESIZE = []; % defaults 1-10 set in topoplot text. HEADPLOT = 0; % 1/0 plot 3-D headplots instead of 2-d topoplots. if nargin<1 help compmap return end curaxes = gca; curpos = get(curaxes,'Position'); mapaxes = axes('Position',[curpos(1) curpos(2)+0.09 curpos(3) curpos(4)-0.09],... 'Visible','off'); % leave room for cbar set(mapaxes,'visible','off'); pos = get(mapaxes,'Position'); % delete(gca); % ax = axes('Position',pos); [chans, frames] = size (Winv); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check inputs and set defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin==8 if strcmp(caxis(1,1:2), 'mi') % min/max of data MAPLIMITS = [min(min(Winv(:,compnos))) max(max(Winv(:,compnos)))]; elseif caxis(1,1:2) == 'ab' % +/-max abs data absmax = max([abs(min(min(Winv(:,compnos)))) abs(max(max(Winv(:,compnos))))]); MAPLIMITS = [-absmax absmax]; elseif size(caxis) == [1,2] % given color axis limits MAPLIMITS = caxis; end % else default end if nargin < 7 printlabel = 0; end if printlabel == 0 printlabel = OUTPUT; % default set above else printlabel = 'printer'; 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 max(compnos)>frames fprintf('compmap(): Cannot show comp %d. Only %d components in inverse weights\n',... max(compnos),frames); return 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 compmap 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)) | srclabels(1,1)==' ' % if numbers if size(srclabels,1) == 1 srclabels = srclabels'; end end if size(srclabels,1)==1 & size(srclabels,2)==1 & srclabels==' ' srclabels = repmat(srclabels,totalsources,1); end if size(srclabels,1) ~= totalsources, fprintf('compmap(): numbers of components and component labels do not agree.\n'); return end end pages = ceil(totalsources/(m*n)); if pages > 1 fprintf('compmap(): will create %d figures of %d by %d maps: ',... pages,m,n); end off = [ 25 -25 0 0]; % position offsets for multiple figures fid = fopen(eloc_file); if fid<1, fprintf('compmap()^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 set(gca,'Color','w') %CJH - set background color to white curaxes = gca; curpos = get(curaxes,'Position'); % new whole-figure axes end if (totalsources > i*m*n) sbreak = n*m; else sbreak = totalsources - (i-1)*m*n; % change page/figure after this many end for j = (1:sbreak) % maps on this page/figure 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 sbplot(m,n,j,'ax',mapaxes); if HEADPLOT headplot(source_var,eloc_file,'electrodes','off'); % 3-d image else topoplot(source_var,eloc_file,... 'style',STYLE,... 'electrodes',ELECTRODES,... 'emarkersize',ELECTRODESIZE,... 'numcontour',NUMCONTOUR,... 'interplimits',INTERPLIMITS,... 'maplimits',MAPLIMITS); % draw 2-d scalp map end if SQUARE, axis('square'); end if isempty(srclabels) title(int2str(compnos(comp))) ; else if ischar(srclabels) title(srclabels(comp,:)); else title(num2str(srclabels(comp))); end end drawnow % draw one map at a time end end % ax = axes('Units','Normal','Position',[.5 .06 .32 .05],'Visible','Off'); axes(curaxes); set(gca,'Visible','off','Units','normalized'); curpos = get(gca,'position'); ax = axes('Units','Normalized','Position',... [curpos(1)+0.5*curpos(3) curpos(2)+0.01*curpos(4) ... 0.32*curpos(3) 0.05*curpos(4)],'Visible','Off'); if exist('cbar') == 2 cbar(ax); % Slightly altered Matlab colorbar() % Write authors for further information. else colorbar(ax); % Note: there is a minor problem with this call. end axval = axis; Xlim = get(ax,'Xlim'); set(ax,'XTick',(Xlim(2)+Xlim(1))/2); set(ax,'XTickMode','manual'); set(ax,'XTickLabelMode','manual'); set(ax,'XTickLabel','0'); axes(curaxes); axis off; % axbig = axes('Units','Normalized','Position',[0 0 1 1],'Visible','off'); t1 = text(.25,.07,titleval,'HorizontalAlignment','center'); if pages > 1 fprintf('%d ',i); end axcopy(gcf); % allow popup window of single map with mouse click end if pages > 1 fprintf('\n'); end
github
lcnbeapp/beapp-master
topoimage.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/topoimage.m
21,312
utf_8
952b9066313797fa812f1352f2586565
% topoimage() - plot concatenated multichannel time/frequency images % in a topographic format % Uses a channel location file with the same format as topoplot() % or else plots data on a rectangular grid of axes. % Click on individual images to examine separately. % % Usage: % >> topoimage(data,'chan_locs',ntimes,limits); % >> topoimage(data,[rows cols],ntimes,limits); % >> topoimage(data,'chan_locs',ntimes,limits,title,... % channels,axsize,colors,ydir,rmbase) % % Inputs: % data = data consisting of nchans images, each size (rows,ntimes*chans) % 'chan_locs' = file of channel locations as in >> topoplot example % Else [rows cols] matrix of locations. Example: [6 4] % ntimes = columns per image % [limits] = [mintime maxtime minfreq maxfreq mincaxis maxcaxis] % Give times in msec {default|0 (|both caxis 0) -> use data limits) % 'title' = plot title {0 -> none} % channels = vector of channel numbers to plot & label {0 -> all} % axsize = [x y] axis size {default [.08 .07]} % 'colors' = file of color codes, 3 chars per line % ( '.' = space) {0 -> default color order} % ydir = y-axis polarity (pos-up = 1; neg-up = -1) {def -> pos-up} % rmbase = if ~=0, remove the mean value for times<=0 for each freq {def -> no} % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 12-10-1999 % % See also: topoplot(), timef() % Copyright (C) 12-10-99 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 % 1-16-00 debugged help msg and improved presentation -sm % 3-16-00 added axcopy() -sm % 8-07-00 added logimagesc() via 'LOGIT' -sm % 9-02-00 added RMBASE option below, plus colorbar to key image -sm ??? % 1-25-02 reformated help & license, added link -ad function topoimage(data,loc_file,times,limits,plottitle,channels,axsize,colors,ydr,rmbas) % Options: % LOGIT = 1; % comment out for non-log imaging % YVAL = 10; % plot horizontal lines at 10 Hz (comment to omit) % RMBASE = 0; % remove <0 mean for each image row MAXCHANS = 256; DEFAULT_AXWIDTH = 0.08; DEFAULT_AXHEIGHT = 0.07; DEFAULT_SIGN = 1; % Default - plot positive-up LINEWIDTH = 2.0; FONTSIZE = 14; % font size to use for labels CHANFONTSIZE = 10; % font size to use for channel names TICKFONTSIZE=10; % font size to use for axis labels TITLEFONTSIZE = 16; PLOT_WIDTH = 0.75; % width and height of plot array on figure! PLOT_HEIGHT = 0.81; ISRECT = 0; % default if nargin < 1, help topoimage return end if nargin < 4, help topoimage error('topoimage(): needs four arguments'); end if times <0, help topoimage return elseif times==1, fprintf('topoimage: cannot plot less than 2 times per image.\n'); return else freqs = 0; end; axcolor= get(0,'DefaultAxesXcolor'); % find what the default x-axis color is plotfile = 'topoimage.ps'; ls_plotfile = 'ls -l topoimage.ps'; % %%%%%%%%%%%%%%%%%%%%%%%%%% Substitute defaults for missing parameters %%%%% % SIGN = DEFAULT_SIGN; if nargin < 10 rmbas = 0; end if nargin < 9 ydr = 0; end if ydr == -1 SIGN = -1; end if nargin < 8 colors = 0; end if nargin < 7, axwidth = DEFAULT_AXWIDTH; axheight = DEFAULT_AXHEIGHT; elseif size(axsize) == [1 1] & axsize(1) == 0 axwidth = DEFAULT_AXWIDTH; axheight = DEFAULT_AXHEIGHT; elseif size(axsize) == [1 2] axwidth = axsize(1); axheight = axsize(2); if axwidth > 1 | axwidth < 0 | axheight > 1 | axwidth < 0 help topoimage return end else help topoimage return end [freqs,framestotal]=size(data); % data size chans = framestotal/times; fprintf('\nPlotting data using axis size [%g,%g]\n',axwidth,axheight); if nargin < 6 channels = 0; end if channels == 0 channels = 1:chans; end if nargin < 5 plottitle = 0; %CJH end limitset = 0; if nargin < 4, limits = 0; elseif length(limits)>1 limitset = 1; end %%%%%%%%%%%%%%%%%%%%%%%%%%% Test parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % icadefs; % read MAXPLOTDATACHANS constant from icadefs.m if max(channels) > chans fprintf('topoimage(): max channel index > %d channels in data.\n',... chans); return end if min(channels) < 1 fprintf('topoimage(): min channel index (%g) < 1.\n',... min(channels)); return end; if length(channels)>MAXPLOTDATACHANS, fprintf('topoimage(): not set up to plot more than %d channels.\n',... MAXPLOTDATACHANS); return end; % %%%%%%%%%%%%% Extend the size of the plotting area in the window %%%%%%%%%%%% % curfig = gcf; h=figure(curfig); set(h,'Color',BACKCOLOR); % set the background color set(h,'PaperUnits','normalized'); % use percentages to avoid US/A4 difference set(h,'PaperPosition',[0.0235308 0.0272775 0.894169 0.909249]); % equivalent % orient portrait axis('normal'); % %%%%%%%%%%%%%%%%%%%% Read the channel names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if isstr(channels) == 0, % channames = zeros(MAXPLOTDATACHANS,4); % for c=1:length(channels), % channames(c,:)= sprintf('%4d',channels(c)); % end; channames = num2str(channels(:)); %%CJH else, if ~isstr(channels) fprintf('topoimage(): channel file name must be a string.\n'); return end chid = fopen(channels,'r'); if chid <3, fprintf('topoimage(): cannot open file %s.\n',channels); return end; channames = fscanf(chid,'%s',[4 MAXPLOTDATACHANS]); channames = channames'; [r c] = size(channames); for i=1:r for j=1:c if channames(i,j)=='.', channames(i,j)=' '; end; end; end; end; % setting channames % %%%%%%%%%%%%%%%%%%%%%%%%% Plot and label specified channels %%%%%%%%%%%%%%%%%% % data = matsel(data,times,0,0,channels); chans = length(channels); % %%%%%%%%%%%%%%%%%%%%%%%%% Read the color names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if colors ~=0, if ~isstr(colors) fprintf('topoimage(): color file name must be a string.\n'); return end cid = fopen(colors,'r'); % fprintf('cid = %d\n',cid); if cid <3, fprintf('topoimage: cannot open file %s.\n',colors); return end; colors = fscanf(cid,'%s',[3 MAXPLOTDATAEPOCHS]); 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 % use default color order (no yellow!) colors =['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 ';'b ';'g ';'c ';'m ']; colors = [colors; colors]; % make > 64 available end; for c=1:length(colors) % make white traces black unless axis color is white if colors(c,1)=='w' & axcolor~=[1 1 1] colors(c,1)='k'; end end % %%%%%%%%%%%%%%%%%%%%%%% Read and adjust limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if limits==0, % == 0 or [0 0 0 0] xmin=min(times); xmax=max(times); ymin=min(freqs); ymax=max(freqs); else if length(limits)~=6, fprintf( ... 'topoimage: limits should be 0 or an array [xmin xmax ymin ymax zmin zmax].\n'); return end; xmin = limits(1); xmax = limits(2); ymin = limits(3); ymax = limits(4); zmin = limits(5); zmax = limits(6); end; if xmax == 0 & xmin == 0, x = [0:1:times-1]; xmin = min(x); xmax = max(x); else dx = (xmax-xmin)/(times-1); x=xmin*ones(1,times)+dx*(0:times-1); % compute x-values xmax = xmax*times/times; end; if xmax<=xmin, fprintf('topoimage() - xmax must be > xmin.\n') return end if ymax == 0 & ymin == 0, y=[1:1:freqs]; ymax=freqs; ymin=1; else dy = (ymax-ymin)/(freqs-1); y=ymin*ones(1,freqs)+dy*(0:freqs-1); % compute y-values ymax = max(y); end if ymax<=ymin, fprintf('topoimage() - ymax must be > ymin.\n') return end if zmax == 0 & zmin == 0, zmax=max(max(data)); zmin=min(min(data)); fprintf('Color axis limits [%g,%g]\n',zmin,zmax); end if zmax<=zmin, fprintf('topoimage() - zmax must be > zmin.\n') return end xlabel = 'Time (ms)'; ylabel = 'Hz'; % %%%%%%%%%%%%%%%%%%%%%%%% Set up plotting environment %%%%%%%%%%%%%%%%%%%%%%%%% % h = gcf; % set(h,'YLim',[ymin ymax]); % set default plotting parameters % set(h,'XLim',[xmin xmax]); % set(h,'FontSize',18); % set(h,'DefaultLineLineWidth',1); % for thinner postscript lines % %%%%%%%%%%%%%%%%%%%%%%%%%% Print plot info %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % clf; % clear the current figure % print plottitle over (left) subplot 1 if plottitle==0, plottitle = ''; end h=gca;title(plottitle,'FontSize',TITLEFONTSIZE); % title plot and hold on msg = ['\nPlotting %d traces of %d frames with colors: ']; msg = [msg ' -> \n']; % print starting info on screen . . . fprintf(... '\nlimits: [xmin,xmax,ymin,ymax] = [%4.1f %4.1f %4.2f %4.2f]\n',... xmin,xmax,ymin,ymax); set(h,'YLim',[ymin ymax]); % set default plotting parameters set(h,'XLim',[xmin xmax]); set(h,'FontSize',FONTSIZE); % choose font size set(h,'FontSize',FONTSIZE); % choose font size set(h,'YLim',[ymin ymax]); % set default plotting parameters set(h,'XLim',[xmin xmax]); axis('off') % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Read chan_locs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if size(loc_file,2) == 2 % plot in a rectangular grid ISRECT = 1; ht = loc_file(1); wd = loc_file(2); if chans > ht*wd fprintf(... '\ntopoimage(): (d%) channels to be plotted > grid size [%d %d]\n\n',... chans,ht,wd); return end hht = (ht-1)/2; hwd = (wd-1)/2; xvals = zeros(ht*wd,1); yvals = zeros(ht*wd,1); dist = zeros(ht*wd,1); for i=1:wd for j=1:ht xvals(i+(j-1)*wd) = -hwd+(i-1); yvals(i+(j-1)*wd) = hht-(j-1); dist(i+(j-1)*wd) = sqrt(xvals(j+(i-1)*ht).^2+yvals(j+(i-1)*ht).^2); end end maxdist = max(dist); for i=1:wd for j=1:ht xvals(i+(j-1)*wd) = 0.499*xvals(i+(j-1)*wd)/maxdist; yvals(i+(j-1)*wd) = 0.499*yvals(i+(j-1)*wd)/maxdist; end end channames = repmat(' ',ht*wd,4); for i=1:ht*wd channum = num2str(i); channames(i,1:length(channum)) = channum; end else % read chan_locs file fid = fopen(loc_file); if fid<1, fprintf('topoimage(): cannot open eloc_file "%s"\n',loc_file) return end A = fscanf(fid,'%d %f %f %s',[7 MAXCHANS]); fclose(fid); A = A'; if length(channels) > size(A,1), error('topoimage(): data channels must be <= chan_locs channels') end channames = setstr(A(channels,4:7)); idx = find(channames == '.'); % some labels have dots channames(idx) = setstr(abs(' ')*ones(size(idx))); % replace them with spaces Th = pi/180*A(channels,2); % convert degrees to rads Rd = A(channels,3); % ii = find(Rd <= 0.5); % interpolate on-head channels only % Th = Th(ii); % Rd = Rd(ii); [yvals,xvals] = pol2cart(Th,Rd); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% xvals = 0.5+PLOT_WIDTH*xvals; % controls width of plot array on page! yvals = 0.5+PLOT_HEIGHT*yvals; % controls height of plot array on page! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot traces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % xdiff=xmax-xmin; rightmost = max(xvals); basetimes = find(x<=0); P=0; Axes = []; fprintf('\ntrace %d: ',P+1); for I=1:chans,%%%%%%%%%% for each data channel %%%%%%%%%%%%%%%%%%%%%%%%%% if P>0 axes(Axes(I)) hold on; % plot down left side of page first axis('off') else % P <= 0 % %%%%%%%%%%%%%%%%%%%%%%% Plot data images %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % xcenter = xvals(I); ycenter = yvals(I); Axes = [Axes axes('Units','Normal','Position', ... [xcenter-axwidth/2 ycenter-axheight/2 axwidth axheight])]; axes(Axes(I)) imageaxes = gca; axislcolor = get(gca,'Xcolor'); %%CJH dataimage = matsel(data,times,0,0,I); if rmbas~=0 % rm baseline dataimage = dataimage ... - repmat(mean(matsel(data,times,basetimes,0,I)')',1,times); end if exist('LOGIT') logimagesc(x,y,dataimage); % <---- plot logfreq image if exist('YVAL') YVAL = log(YVAL); end else imagesc(x,y,dataimage); % <---- plot image end hold on curax = axis; xtk = get(gca,'xtick'); % use these for cal axes below xtkl = get(gca,'xticklabel'); ytk = get(gca,'ytick'); ytkl = get(gca,'yticklabel'); set(gca,'tickdir','out'); set(gca,'ticklength',[0.02 0.05]); set(gca,'xticklabel',[]); set(gca,'yticklabel',[]); set(gca,'ydir','normal'); caxis([zmin zmax]); if exist('YVAL') & YVAL>=curax(3) & YVAL<=curax(4) hold on hp=plot([xmin xmax],[YVAL YVAL],'r-');%,'color',axislcolor); % draw horizontal axis set(hp,'Linewidth',1.0) end if xmin<0 & xmax>0 hold on vl= plot([0 0],[curax(3) curax(4)],'color',axislcolor); % draw vert axis set(vl,'linewidth',2); end % if xcenter == rightmost % colorbar % rightmost = Inf; % end % secondx = 200; % draw second vert axis % axis('off');plot([secondx secondx],[ymin ymax],'color',axislcolor); % %%%%%%%%%%%%%%%%%%%%%%% Print channel names %%%%%%%%%%%%%%%%%%%%%%%%%% % NAME_OFFSET = 0.01; if channels~=0, % print channames if ~ISRECT % print before topographically arrayed image % axis('off'); hold on h=text(xmin-NAME_OFFSET*xdiff,(curax(4)+curax(3))*0.5,[channames(I,:)]); set(h,'HorizontalAlignment','right'); set(h,'FontSize',CHANFONTSIZE); % choose font size else % print before rectangularly arrayed image if xmin<0 xmn = 0; else xmn = xmin; end % axis('off'); h=text(xmin-NAME_OFFSET*xdiff,ymax,[channames(I,:)]); set(h,'HorizontalAlignment','right'); set(h,'FontSize',TICKFONTSIZE); % choose font size end end; % channels end; % P=0 % if xcenter == rightmost % colorbar % rightmost = Inf; % end % if xmin<0 & xmax>0 % axes(imageaxes); % hold on; plot([0 0],[curax(3) curax(4)],'k','linewidth',2); % end drawnow fprintf(' %d',I); end; % %%%%%%%%%%%%%%% chan I %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf('\n'); % %%%%%%%%%%%%%%%%%%%%% Make time and freq cal axis %%%%%%%%%%%%%%%%%%%%%%%%% % ax = axes('Units','Normal','Position', ... [0.80 0.1 axwidth axheight]); axes(ax) axis('off'); imagesc(x,y,zeros(size(dataimage))); hold on % <---- plot green caxis([zmin zmax]); set(gca,'ydir','normal'); if xmin <=0 py=plot([0 0],[curax(3) curax(4)],'color','k'); % draw vert axis at time zero else py=plot([xmin xmin],[curax(3) curax(4)],'color','k'); % vert axis at xmin end hold on if exist('YVAL') & YVAL>=curax(3) px=plot([xmin xmax],[YVAL YVAL],'color',axislcolor); % draw horiz axis at YVAL else px=plot([xmin xmax],[curax(3) curax(4)],'color',axislcolor); % draw horiz axis at ymin end axis(curax); set(gca,'xtick',xtk); % use these for cal axes set(gca,'xticklabel',xtkl); set(gca,'ytick',ytk); set(gca,'yticklabel',ytkl); set(gca,'ticklength',[0.02 0.05]); set(gca,'tickdir','out'); h = colorbar; cbp = get(h,'position'); set(h,'position',[cbp(1) cbp(2) 2*cbp(3) cbp(4)]); caxis([zmin zmax]); % secondx = 200; % draw second vert axis % axis('off');plot([secondx secondx],[curax(3) curax(4)],'color',axislcolor); % %%%%%%%%%%%%%%%%%%%%% Plot axis values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if 0 % DETOUR signx = xmin-0.15*xdiff; axis('off');h=text(signx,SIGN*curax(3),num2str(curax(3),3)); set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','right','Clipping','off'); textx = xmin-0.6*xdiff; axis('off');h=text(textx,(curax(3)+curax(4))/2,ylabel); % text Hz set(h,'Rotation',90); set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center','Clipping','off'); % axis('off');h=text(signx,SIGN*ymax,['+' num2str(ymax,3)]); % text +ymax axis('off');h=text(signx,SIGN*ymax,[ num2str(ymax,3)]); % text ymax set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','right','Clipping','off'); ytick = curax(3)-0.3*(curax(4)-curax(3)); tick = [int2str(xmin)]; h=text(xmin,ytick,tick); % text xmin set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text h=text(xmin+xdiff/2,ytick-0.5*(curax(4)-curax(3)),xlabel);% text Times set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text tick = [int2str(xmax)]; h=text(xmax,ytick,tick); % text xmax set(h,'FontSize',TICKFONTSIZE); % choose font size set(h,'HorizontalAlignment','center',... 'Clipping','off'); % center text axis on set(ax,'xticklabel',''); set(ax,'yticklabel',''); set(ax,'ticklength',[0.02 0.05]); set(ax,'tickdir','out'); caxis([zmin zmax]); hc=colorbar; cmapsize = size(colormap,1); set(hc,'ytick',[1 cmapsize]); % minlabel = num2str(zmin,3); while (length(minlabel)<4) if ~contains(minlabel,'.') minlabel = [minlabel '.']; else minlabel = [minlabel '0']; end end maxlabel = num2str(zmax,3); if zmin<0 & zmax>0 maxlabel = ['+' maxlabel]; end while (length(maxlabel)<length(minlabel)) if ~contains(maxlabel,'.') maxlabel = [maxlabel '.']; else maxlabel = [maxlabel '0']; end end while (length(maxlabel)>length(minlabel)) if ~contains(minlabel,'.') minlabel = [minlabel '.']; else minlabel = [minlabel '0']; end end set(hc,'yticklabel',[minlabel;maxlabel]); set(hc,'Color',BACKCOLOR); set(hc,'Zcolor',BACKCOLOR); end % DETOUR axcopy(gcf); % turn on pop-up axes % %%%%%%%%%%%%%%%%%% Make printed figure fill page %%%%%%%%%%%%%%%%%%%%%%%%%%% % % orient tall % curfig = gcf; % h=figure(curfig); % set(h,'PaperPosition',[0.2 0.3 7.6 10]); % stretch out the plot on the page function [returnval] = contains(strng,chr) returnval=0; for i=1:length(strng) if strng(i)==chr returnval=1; break end end
github
lcnbeapp/beapp-master
getallmenuseeglab.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/getallmenuseeglab.m
3,609
utf_8
3f20087025ca923857b9ce9ec4553255
% getallmenuseeglab() - get all submenus of a window or a menu and return % a tree. The function will also look for callback. % % Usage: % >> [tree nb] = getallmenuseeglab( 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] = getallmenuseeglab( handler, level ) NBBLANK = 6; % number of blank for each submenu input if nargin < 1 help getallmenuseeglab; 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=length(allmenu):-1:1 [txtmp nbtmp tmplab] = getallmenuseeglab(allmenu(i), level+1); txtmp = [ '% ' blanks(level*NBBLANK) txtmp ]; txt = [ txtmp txt ]; labels = { tmplab labels{:} }; nb = nb+nbtmp; end; end; try lab = get(handler, 'Label'); cb = get(handler, 'Callback'); cb = extract_callback(cb); if ~isempty(cb) newtxt = [ lab ' - <a href="matlab:helpwin ' cb '">' cb '</a>']; else newtxt = [ lab ]; end; txt = [ newtxt 10 txt ]; %txt = [ get(handler, 'Label') 10 txt ]; nb = nb+1; catch, end; if isempty(labels) labels = { nb }; end; if level == 0 fid = fopen('tmpfile.m', 'w'); fprintf(fid, '%s', txt); fclose(fid); disp(' '); disp('Results saved in tmpfile.m'); 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; % extract plugin name % ------------------- function cbout = extract_callback(cbin); funcList = { 'pop_' 'topoplot' 'eeg_' }; for iList = 1:3 indList = findstr(funcList{iList}, cbin); if ~isempty(indList), if strcmpi(cbin(indList(1):indList(1)+length('pop_stdwarn')-1), 'pop_stdwarn') indList = findstr(funcList{iList}, cbin(indList(1)+1:end))+indList(1); end; break; end; end; if ~isempty(indList) indEndList = find( cbin(indList(1):end) == '(' ); if isempty(indEndList) || indEndList(1) > 25 indEndList = find( cbin(indList(1):end) == ';' ); if cbin(indList(1)+indEndList(1)-2) == ')' indEndList = indEndList-2; end; end; cbout = cbin(indList(1):indList(1)+indEndList(1)-2); else cbout = ''; end;
github
lcnbeapp/beapp-master
loglike.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/loglike.m
1,238
utf_8
b9a8aa64d20e0fc72257880d837f9f19
% loglike() - log likehood function to estimate dependence between components % % Usage: f = loglike(W, S); % % Computation of the log-likelihood function under the model % that the ICs are 1/cosh(s) distributed (according to the tanh % nonlinearity in ICA). It does not exactly match for the logistic % nonlinearity, but should be a decent approximation % % negative log likelihood function % f = -( log(abs(det(W))) - sum(sum(log( cosh(S) )))/N - M*log(pi) ); % % With these meanings: % W: total unmixing matrix, ie, icaweights*icasphere % S: 2-dim Matrix of source estimates % N: number of time points % M: number of components % % Author: Arnaud Delorme and Jorn Anemuller function f=loglike(W, S); W = double(W); S = double(S); % normalize activities stds = std(S, [], 2); S = S./repmat(stds, [1 size(S,2)]); W = W./repmat(stds, [1 size(W,2)]); M = size(W,1); if ndims(S) == 3 S = reshape(S, size(S,1), size(S,3)*size(S,2)); end; N = size(S,2); % detect infinite and remove them tmpcoh = log( cosh(S) ); tmpinf = find(isinf(tmpcoh)); tmpcoh(tmpinf) = []; N = (N*M-length(tmpinf))/M; f=-( log(abs(det(W))) - sum(sum(tmpcoh))/N - M*log(pi) );
github
lcnbeapp/beapp-master
corrimage.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/corrimage.m
25,394
utf_8
aaddb89d7d26c507e8075ec38d644f0a
% corrimage() - compute correlation image between an event and amplitude % and phase in the time-frequency domain. % % Usage: % corrimage(data, sortvar, times); % [times, freqs, alpha, sigout, limits ] = corrimage(data, sortvar, ... % times, 'key1', val1, 'key2', val2, ...) % % Inputs: % data - [float array] data of size (times,trials) % sortvar - [float array] sorting variable of size (trials) % times - [float array] time indices for every data point. Size of % (times). Note: same input as the times vector for erpimage. % % Optional input: % 'mode' - ['phase'|'amp'] compute correlation of event values with % phase ('phase') or amplitude ('amp') of signal at the % given time-frequency points. Default is 'amp'. % 'freqs' - [min nfreqs max] build a frequency vector of size nfreqs % with frequency spaced in a log scale. Then compute % correlation at these frequency value. % Default is 50 points in a log scale between 2.5Hz to 50Hz. % 'times' - [float vector] compute correlation at these time value (ms). % (uses closest times points in 'times' input and return % them in the times output). % Default is 100 steps between min time+5% of time range and % max time-5%. Enter only 2 values [N X] to generate N % time points and trim by X %. If N is negative, uses it as % a subsampling factor [-3 5] trims times by 5% and subsample % by 3 (by subsampling one obtains a regularly spaced times). % 'trim' - [low high] low and high percentile of sorted sortvar values % to retain. i.e. [5 95] remove the 5 lowest and highest % percentile of sortvar values (and associated data) before % computing statistics. Default is [0 100]. % 'align' - [float] same as 'align' parameter of erpimage(). This % parameter is used to contrain the 'times' parameter so % correlation with data trials containing 0-values (as a % result of data alignment) are avoided: computing these % correlations would produce spurious significant results. % Default is no alignment. % 'method' - ['erpimage'|timefreq'] use either the erpimage() function % of the timefreq() function to compute spectral decomposition. % Default is 'timefreq' for speed reasons (note that both % methods should return the same results). % 'erpout' - [min max] regress out ERP using the selected time-window [min % max] in ms (the ERP is subtracted from the whole time period % but only regressed out in the selected time window). % 'triallimit' - [integer array] specify trial boundaries for subjects. For % instance [1 200 400] indicates 2 subjects, trials 1 to 199 % for subject 1 and trials 200 to 399 for subject 2. This is % currently only used for regressing erp out. % % Processing options: % 'erpimopt' - [cell array] erpimage additional options (number of cycle ...). % 'tfopt' - [cell array] timefreq additional options (number of cycle ...). % % Plotting options: % 'plotvals' - [cell array of output values] enter output values here % { times freqs alpha sigout} to replot them. % 'nofig' - ['on'|'off'] do not create figure. % 'cbar' - ['on'|'off'] plot color bar. Default: 'on'. % 'smooth' - ['on'|'off'] smooth significance array. Default: 'on'. % 'plot' - ['no'|'alpha'|'sigout'|'sigoutm'|'sigoutm2'] plot -10*log(alpha) % values ('alpha'); output signal (slope or ITC) ('sigout'), % output signal masked by significance ('sigoutm') or the last % 2 option combined ('sigoutm2'). 'no' prevent the function % from plotting. In addition, see pmask. Default is 'sigoutmasked'. % 'pmask' - [real] maximum p value to show in plot. Default is 0.00001 % (0.001 taking into account multiple comparisons (100)). Enter % 0.9XXX to get the higher tail or a negative value (e.e., -0.001 % to get both tails). % 'vert' - [real array] time vector for vertivcal lines. % 'limits' - [min max] plotting limits. % % Outputs: % times - [float vector] vector of times (ms) % freqs - [float vector] vector of frequencies (Hz) % alpha - [float array] array (freqs,times) of p-values. % sigout - [float array] array (freqs,times) of signal out (coherence % for phase and slope for amplitude). % % Important note: the 'timefreq' method may truncate the time window to % compute the spectral decomposition at the lowest freq. % % Author: Arnaud Delorme & Scott Makeig, SCCN UCSD, % and CNL Salk Institute, 18 April 2003 % % See also: erpimage() %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2002 Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [time, freq, alpha, sigout, limits, tf, sortvar] = corrimage(data, sortvar, timevect, varargin) if nargin < 3 help corrimage; return; end; if isempty(timevect), timevect = [1 2]; end; % check inputs % ------------ g = finputcheck(varargin, { 'freqs' 'real' [0 Inf] [2.5 50 50]; 'times' 'real' [] [100 5]; % see function at the end 'mode' 'string' { 'phase','amp' } 'amp'; 'vert' 'real' [] []; 'align' { 'real','cell' } [] []; 'plotvals' 'cell' [] {}; 'pmask' 'real' [] 0.00001; 'triallimit' 'integer' [] []; 'trim' 'real' [0 100] [0 100]; 'limits' 'real' [] []; 'method' 'string' { 'erpimage','timefreq' } 'timefreq'; 'plot' 'string' { 'no','alpha','sigout','sigoutm','sigoutp','sigoutm2' } 'sigoutm'; 'nofig' 'string' { 'on','off' } 'off'; 'cbar' 'string' { 'on','off' } 'on'; 'smooth' 'string' { 'on','off' } 'off'; 'erpout' 'real' [] []; 'tfopt' 'cell' [] {}; 'erpimopt' 'cell' [] {} }); if isstr(g), error(g); end; fprintf('Generating %d frequencies in log scale (ignore message on linear scale)\n', g.freqs(2)); g.freqs = logscale(g.freqs(1), g.freqs(3), g.freqs(2)); frames = length(timevect); if size(data,1) == 1 data = reshape(data, frames, size(data,2)*size(data,3)/frames); end; % trim sortvar values % ------------------- [sortvar sortorder] = sort(sortvar); data = data(:, sortorder); len = length(sortvar); lowindex = round(len*g.trim(1)/100)+1; highindex = round(len*g.trim(2)/100); sortvar = sortvar(lowindex:highindex); data = data(:, lowindex:highindex); if lowindex ~=1 | highindex ~= length(sortorder) fprintf('Actual percentiles %1.2f-%1.2f (indices 1-%d -> %d-%d): event vals min %3.2f; max %3.2f\n', ... 100*(lowindex-1)/len, 100*highindex/len, len, lowindex, highindex, min(sortvar), max(sortvar)); end; % assign subject number for each trial % ------------------------------------ if ~isempty(g.triallimit) alltrials = zeros(1,len); for index = 1:length(g.triallimit)-1 alltrials([g.triallimit(index):g.triallimit(index+1)-1]) = index; end; alltrials = alltrials(sortorder); alltrials = alltrials(lowindex:highindex); end; %figure; hist(sortvar) % constraining time values depending on data alignment % ---------------------------------------------------- srate = 1000*(length(timevect)-1)/(timevect(end)-timevect(1)); if ~isempty(g.align) if iscell(g.align) fprintf('Realigned sortvar plotted at %g ms.\n',g.align{1}); shifts = round((g.align{1}-g.align{2})*srate/1000); % shifts can be positive or negative g.align = g.align{1}; else if isinf(g.align) g.align = median(sortvar); end fprintf('Realigned sortvar plotted at %g ms.\n',g.align); % compute shifts % -------------- shifts = round((g.align-sortvar)*srate/1000); % shifts can be positive or negative end; %figure; hist(shifts) minshift = min(shifts); % negative maxshift = max(shifts); % positive if minshift > 0, error('minshift has to be negative'); end; if maxshift < 0, error('maxshift has to be positive'); end; % realign data for all trials % --------------------------- aligndata=zeros(size(data))+NaN; % begin with matrix of zeros() for t=1:size(data,2), %%%%%%%%% foreach trial %%%%%%%%% shft = shifts(t); if shft>0, % shift right aligndata(shft+1:frames,t)=data(1:frames-shft,t); elseif shft < 0 % shift left aligndata(1:frames+shft,t)=data(1-shft:frames,t); else % shft == 0 aligndata(:,t) = data(:,t); end end % end trial data = aligndata(maxshift+1:frames+minshift,:); if any(any(isnan(data))), error('NaNs remaining after data alignment'); end; timevect = timevect(maxshift+1:frames+minshift); % take the time vector subset % --------------------------- if isempty(timevect), error('Shift too big, empty time vector'); else fprintf('Time vector truncated for data alignment between %1.0f and %1.0f\n', ... min(timevect), max(timevect)); end; end; % regress out the ERP from the data (4 times to have residual ERP close to 0) % --------------------------------------------------------------------------- if ~isempty(g.erpout) %data = erpregout(data); %data = erpregout(data); %data = erpregout(data); disp('Regressing out ERP'); erpbeg = mean(data,2); if ~isempty(g.triallimit) for index = 1:length(g.triallimit)-1 trials = find(alltrials == index); %[data(:,trials) erp factors]= erpregout(data(:,trials), [timevect(1) timevect(end)], [300 400]); erpstart = mean(data(:,trials),2); data(:,trials) = erpregout(data(:,trials)); data(:,trials) = erpregout(data(:,trials)); data(:,trials) = erpregout(data(:,trials)); data(:,trials) = erpregout(data(:,trials)); erpend = mean(data(:,trials),2); fprintf([ '***********************************************\n' ... 'Ratio in ERP after regression (compare to before) is %3.2f\n' ... '***********************************************\n' ], mean(erpend./erpstart)); end; end; erpend = mean(data,2); fprintf([ '***********************************************\n' ... 'Ratio in grand ERP after regression (compare to before) is %3.2f\n' ... '***********************************************\n' ], mean(erpend./erpbeg)); if 0 %trials = find(alltrials == 1); data2 = data; dasf [data(:,trials) erp factors]= erpregout(data(:,trials), [timevect(1) timevect(end)], [300 400]); figure; subplot(1,2,1); erpimage(data, sortvar, timevect, '', 300, 500, 'erp'); figure; subplot(1,2,1); erpimage(data2, sortvar, timevect, '', 300, 500, 'erp'); subplot(1,2,2); erpimage(data , sortvar, timevect, '', 300, 500, 'erp'); figure; subplot(1,2,1); erpimage(data2(:,trials), sortvar(trials), timevect, '', 0, 0, 'erp'); subplot(1,2,2); erpimage(data (:,trials), sortvar(trials), timevect, '', 0, 0, 'erp'); figure; for index = 1:length(g.triallimit)-1 subplot(3,5,index); trials = find(alltrials == index); erpimage(data(:,trials), sortvar(trials), timevect, '', 50, 100, 'erp'); end; disp('Regressing out ERP'); if ~isempty(g.triallimit) for index = 1:length(g.triallimit)-1 trials = find(alltrials == index); [data(:,trials) erp factors]= erpregout(data(:,trials), [timevect(1) timevect(end)], [300 400]); data(:,trials) = erpregout(data(:,trials)); data(:,trials) = erpregout(data(:,trials)); data(:,trials) = erpregout(data(:,trials)); data(:,trials) = erpregout(data(:,trials)); data(:,trials) = erpregout(data(:,trials)); data(:,trials) = erpregout(data(:,trials)); data(:,trials) = erpregout(data(:,trials)); %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout); %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout); %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout); %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout); %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout); %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout); %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout); %data(:,trials) = erpregout(data(:,trials), [timevect(1) timevect(end)], g.erpout); end; else %data = erpregout(data, [timevect(1) timevect(end)], g.erpout); end; end; end; % generate time points % -------------------- g.times = gettimes(timevect, g.times); data = reshape(data, 1, size(data,2)*size(data,1)); % time frequency decomposition % ---------------------------- if strcmpi(g.method, 'timefreq') & isempty(g.plotvals) data = reshape(data, length(data)/length(sortvar), length(sortvar)); [tf, g.freqs, g.times] = timefreq(data, srate, 'freqs', g.freqs, 'timesout', g.times, ... 'tlimits', [min(timevect) max(timevect)], 'wavelet', 3); outvar = sortvar; end; % compute correlation % ------------------- if strcmpi(g.mode, 'phase') & isempty(g.plotvals) for freq = 1:length(g.freqs) fprintf('Computing correlation with phase %3.2f Hz ----------------------\n', g.freqs(freq)); for time = 1:length(g.times) if strcmpi(g.method, 'erpimage') [outdata,outvar,outtrials,limits,axhndls,erp, ... amps,cohers,cohsig,ampsig,outamps,phsangls,phsamp,sortidx] =erpimage(data,sortvar,timevect, ... '', 0,0,g.erpimopt{:}, 'phasesort', [g.times(time) 0 g.freqs(freq)], 'noshow', 'yes'); else phsangls = angle( squeeze(tf(freq, time, :))' ); end; % computing ITCs [ ITC(freq, time) alpha(freq, time) ] = ... bootcircle(outvar/mean(outvar), exp(j*phsangls), 'naccu', 250); % accumulate 200 values, fitted with a normal distribution % -------------------------------------------------------- %cmplx = outvar .* exp(j*phsangls)/mean(outvar); %ITC(freq, time) = mean(cmplx); %alpha(freq,time) = bootstat(outvar/mean(outvar), exp(j*phsangls), 'res = mean(arg1 .* arg2)', ... % 'naccu', 100, 'vals', abs(ITC(freq, time)), 'distfit', 'norm'); end; end; sigout = ITC; elseif isempty(g.plotvals) for freq = 1:length(g.freqs) fprintf('Computing correlation with amplitude %3.2f Hz ----------------------\n', g.freqs(freq)); for time = 1:length(g.times) if strcmpi(g.method, 'erpimage') [outdata,outvar,outtrials,limits,axhndls,erp, ... amps,cohers,cohsig,ampsig,outamps,phsangls,phsamp,sortidx] =erpimage(data,sortvar,timevect, ... '', 0,0,g.erpimopt{:}, 'ampsort', [g.times(time) 0 g.freqs(freq)], 'noshow', 'yes'); else phsamp = abs(squeeze(tf(freq, time, :)))'; end; % computing ITCs [ypred alpha(freq, time) Rsq slope(freq, time)] = myregress(outvar, 20*log10(phsamp)); end; end; sigout = slope; else g.times = g.plotvals{1}; g.freqs = g.plotvals{2}; alpha = g.plotvals{3}; sigout = g.plotvals{4}; end; % plot correlation % ---------------- if ~strcmp('plot', 'no') if ~isreal(sigout), if strcmpi(g.plot, 'sigoutp') sigoutplot = angle(sigout); else sigoutplot = abs(sigout); end; else sigoutplot = sigout; end; sigouttmp = sigoutplot; if strcmpi(g.smooth, 'on') tmpfilt = gauss2d(3,3,.3,.3); tmpfilt = tmpfilt/sum(sum(tmpfilt)); alpha = conv2(alpha, tmpfilt, 'same'); end; % mask signal out if g.pmask > 0.5 indices = find( alpha(:) < g.pmask); sigouttmp = sigoutplot; sigouttmp(indices) = 0; elseif g.pmask < 0 % both sides, i.e. 0.01 sigouttmp = sigoutplot; indices = intersect_bc(find( alpha(:) > -g.pmask), find( alpha(:) < 1+g.pmask)); sigouttmp(indices) = 0; else sigouttmp = sigoutplot; indices = find( alpha(:) > g.pmask); sigouttmp(indices) = 0; end; if strcmpi(g.nofig, 'off'), figure; end; switch g.plot case 'alpha', limits = plotfig(g.times, g.freqs, -log10(alpha), g); case 'sigout', limits = plotfigsim(g.times, g.freqs, sigoutplot, g); case { 'sigoutm' 'sigoutp' }, limits = plotfigsim(g.times, g.freqs, sigouttmp, g); case 'sigoutm2', limits = subplot(1,2,1); plotfigsim(g.times, g.freqs, sigoutplot, g); limits = subplot(1,2,2); plotfigsim(g.times, g.freqs, sigouttmp, g); end; end; time = g.times; freq = g.freqs; return; % formula for the normal distribution % ----------------------------------- function y = norm(mu, sigma, x); y = 1/sqrt(2) * exp( -(x-mu).^2/(sigma*sigma*2) ) / (sqrt(pi)*sigma); % get time points % --------------- function val = gettimes(timevect, timevar); if length(timevar) == 2 if timevar(1) > 0 % generate linearly space vector % ------------------------------ npoints = timevar(1); trim = timevar(2); if length(timevect)-2*round(trim/100*length(timevect)) < npoints npoints = length(timevect)-round(trim/100*length(timevect)); end; fprintf('Generating %d times points trimmed by %1.1f percent\n', npoints, trim); timer = max(timevect) - min(timevect); maxt = max(timevect)-timer*trim/100; mint = min(timevect)+timer*trim/100; val = linspace(mint,maxt, npoints); else % subsample data % -------------- nsub = -timevar(1); trim = timevar(2); len = length(timevect); trimtimevect = timevect(round(trim/100*len)+1:len-round(trim/100*len)); fprintf('Subsampling by %d and triming data by %1.1f percent (%d points)\n', nsub, trim, round(trim/100*len)); val = trimtimevect(1:nsub:end); end; else val = timevar; end; % find closet points in data oldval = val; for index = 1:length(val) [dum ind] = min(abs(timevect-val(index))); val(index) = timevect(ind); end; if length(val) < length(unique(val)) disp('Warning: duplicate times, reduce the number of output times'); end; if all(oldval == val) disp('Debug msg: Time value unchanged by finding closest in data'); end; % get log scale (for frequency) % ------------- function val = logscale(a,b,n); %val = [5 7 9]; return; val = linspace(log(a), log(b), n); val = exp(val); % plot figure % ----------- function limits = plotfig(times, freqs, vals, g) icadefs; imagesc(times, [1:size(vals,1)], vals); colormap(DEFAULT_COLORMAP); ticks = linspace(1, size(vals,1), length(freqs)); ticks = ticks(1:4:end); set(gca, 'ytick', ticks); set(gca, 'yticklabel', num2str(freqs(1:4:end)', 3)) xlabel('Time (ms)'); ylabel('Freq (Hz)'); if ~isempty(g.limits), caxis(g.limits); end; limits = caxis; if ~isempty(g.vert) for vert = g.vert(:)' hold on; plot([vert vert], [0.001 500], 'k', 'linewidth', 2); end; end; if strcmpi(g.cbar,'on') cbar; end; % plot figure with symetrical phase % --------------------------------- function limits = plotfigsim(times, freqs, vals, g) icadefs; imagesc(times, [1:size(vals,1)], vals); colormap(DEFAULT_COLORMAP); ticks = linspace(1, size(vals,1), length(freqs)); ticks = ticks(1:4:end); set(gca, 'ytick', ticks); set(gca, 'yticklabel', num2str(freqs(1:4:end)', 3)) if ~isempty(g.limits) caxis(g.limits); limits = g.limits; else clim = max(abs(caxis)); limits = [-clim clim]; caxis(limits); end; xlabel('Time (ms)'); ylabel('Freq (Hz)'); if ~isempty(g.vert) for vert = g.vert(:)' hold on; plot([vert vert], [0.01 500], 'k', 'linewidth', 2); end; end; if strcmpi(g.cbar,'on') cbar; end; return; % ----------------------------------------- % plot time-freq point (when clicking on it % ----------------------------------------- function plotpoint(data, sortvar, timevect, freq, timepnts); figure; subplot(2,2,1); erpimage(act_all(:,:),sortvar_all,timepnts, ... '', 300,10,'erp', 'erpstd', 'caxis',[-1.0 1.0], 'srate',256,'align',352, 'yerplabel', '', erpimopt{:}, ... 'phasesort', [500 0 5]); % aligned to median rt % plot in polar coordinates phase versus RT % ----------------------------------------- phaseang2 = [phsangls phsangls-2*pi]; phaseang2 = movav(phaseang2,[], 100); outvar2 = [outvar outvar]; outvar2 = movav(outvar2,[], 100); phaseang2 = phaseang2(length(phsangls)/2-50:length(phsangls)+length(phsangls)/2-50); outvar2 = outvar2 (length(phsangls)/2-50:length(phsangls)+length(phsangls)/2-50); subplot(2,2,3); polar(phsangls, outvar, '.'); hold on; polar(phaseang2, outvar2, 'r'); % computing ITC % ------------- cmplx = outvar .* exp(j*phsangls); ITCval = mean(cmplx); angle(ITCval)/pi*180; abs(ITCval)/mean(outvar); text(-1300,-1400,sprintf('ITC value: amplitude %3.4f, angle %3.1f\n', abs(ITCval)/mean(outvar), angle(ITCval)/pi*180)); % accumulate 200 values % --------------------- alpha = 0.05; if exist('accarray') ~= 1, accarray = NaN; end; [sigval accarray] = bootstat(outvar/mean(outvar), phsangls, 'res = mean(arg1 .* exp(arg2*complex(0,1)))', ... 'accarray', accarray, 'bootside', 'upper', 'alpha', alpha); text(-1300,-1600,sprintf('Threshold for significance at %d percent(naccu=200): %3.4f\n', alpha*100, sigval)); title(sprintf('Clust %d corr. theta phase at 500 ms and RT', clust)); % amplitude sorting % ----------------- figure; [outdata,outvar,outtrials,limits,axhndls,erp, ... amps,cohers,cohsig,ampsig,outamps,phsangls,phsamp,sortidx]=erpimage(act_all(:,:),sortvar_all,timepnts, ... '', 0,0,'erp', 'erpstd', 'caxis', 0.5, 'cbar', ... 'srate',256,'align',352, 'yerplabel', '', erpimopt{:}, 'ampsort', [500 0 5]); % aligned to median rt close; subplot(2,2,2); erpimage(act_all(:,:),sortvar_all,timevect, ... '', 300,10,'erp', 'erpstd', 'caxis', 0.5, 'cbar', ... 'srate',256,'align',352, 'yerplabel', '', erpimopt{:}, 'ampsort', [500 0 5]); % aligned to median rt % compute correlation % ------------------- [ypred alpha Rsq] = myregress(outvar, phsamp); subplot(2,2,4); plot(outvar, phsamp, '.'); hold on; plot(outvar, ypred, 'r'); xlabel('Reaction time'); ylabel('Amplitude'); title(sprintf('Theta amp. at 500 ms vs RT (p=%1.8f, R^2=%3.4f)', alpha, Rsq)); set(gcf, 'position', [336 485 730 540], 'paperpositionmode', 'auto'); setfont(gcf, 'fontsize', 10); eval(['print -djpeg clust' int2str(clust) 'corrthetart.jpg']); % set up for command line call % copy text from plotcorrthetaart %timevect = times; sortvar = sortvar_all; data = act_all; time = 1 freq = 1 g.times = 0; g.freqs = 5; g.erpimopt = {};
github
lcnbeapp/beapp-master
dendhier.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/dendhier.m
1,290
utf_8
4ad99782a7d86d471c4ce68b9a0dbf1e
% DENDHIER: Recursive algorithm to find links and distance coordinates on a % dendrogram, given the topology matrix. % % Usage: [links,topology,node] = dendhier(links,topology,node) % % links = 4-col matrix of descendants, ancestors, descendant % distances, and ancestor distances; pass to % function as null vector [] % topology = dendrogram topology matrix % node = current node; pass as N-1 % % RE Strauss, 7/13/95 function [links,topology,node] = dendhier(links,topology,node) n = size(topology,1)+1; % Number of OTUs c1 = topology(node,1); c2 = topology(node,2); clst = topology(node,3); dist = topology(node,4); if (c1 <= n) links = [links; c1 clst 0 dist]; else prevnode = find(topology(:,3)==c1); prevdist = topology(prevnode,4); links = [links; c1 clst prevdist dist]; [links,topology,node] = dendhier(links,topology,prevnode); end; if (c2 <= n) links = [links; c2 clst 0 dist]; else prevnode = find(topology(:,3)==c2); prevdist = topology(prevnode,4); links = [links; c2 clst prevdist dist]; [links,topology,node] = dendhier(links,topology,prevnode); end; return;
github
lcnbeapp/beapp-master
runicalowmem.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/runicalowmem.m
62,951
utf_8
ae726ddb4771edbac5539b0c00cf3fb9
% runica() - Perform Independent Component Analysis (ICA) decomposition % of input data using the logistic infomax ICA algorithm of % Bell & Sejnowski (1995) with the natural gradient feature % of Amari, Cichocki & Yang, or optionally the extended-ICA % algorithm of Lee, Girolami & Sejnowski, with optional PCA % dimension reduction. Annealing based on weight changes is % used to automate the separation process. % Usage: % >> [weights,sphere] = runica(data); % train using defaults % else % >> [weights,sphere,compvars,bias,signs,lrates,activations] ... % = runica(data,'Key1',Value1',...); % Input: % data = input data (chans,frames*epochs). % Note that if data consists of multiple discontinuous epochs, % each epoch should be separately baseline-zero'd using % >> data = rmbase(data,frames,basevector); % % Optional keywords [argument]: % 'extended' = [N] perform tanh() "extended-ICA" with sign estimation % N training blocks. If N > 0, automatically estimate the % number of sub-Gaussian sources. If N < 0, fix number of % sub-Gaussian comps to -N [faster than N>0] (default|0 -> off) % 'pca' = [N] decompose a principal component (default -> 0=off) % subspace of the data. Value is the number of PCs to retain. % 'sphering' = ['on'/'off'] flag sphering of data (default -> 'on') % 'weights' = [W] initial weight matrix (default -> eye()) % (Note: if 'sphering' 'off', default -> spher()) % 'lrate' = [rate] initial ICA learning rate (<< 1) (default -> heuristic) % 'block' = [N] ICA block size (<< datalength) (default -> heuristic) % 'anneal' = annealing constant (0,1] (defaults -> 0.90, or 0.98, extended) % controls speed of convergence % 'annealdeg' = [N] degrees weight change for annealing (default -> 70) % 'stop' = [f] stop training when weight-change < this (default -> 1e-6 % if less than 33 channel and 1E-7 otherwise) % 'maxsteps' = [N] max number of ICA training steps (default -> 512) % 'bias' = ['on'/'off'] perform bias adjustment (default -> 'on') % 'momentum' = [0<f<1] training momentum (default -> 0) % 'specgram' = [srate loHz hiHz frames winframes] decompose a complex time/frequency % transform of the data - though not optimally. (Note: winframes must % divide frames) (defaults [srate 0 srate/2 size(data,2) size(data,2)]) % 'posact' = make all component activations net-positive(default 'off'} % Requires time and memory; posact() may be applied separately. % 'ncomps' = [N] number of ICA components to compute (default -> chans or 'pca' arg) % using rectangular ICA decomposition. This parameter may return % strange results. This is because the weight matrix is rectangular % instead of being square. Do not use except to try to fix the problem. % 'verbose' = give ascii messages ('on'/'off') (default -> 'on') % 'submean' = ['on'|'off'] subtract mean from each channel (default -> 'on') % 'logfile' = [filename] save all message in a log file in addition to showing them % on screen (default -> none) % % Outputs: [Note: RO means output in reverse order of projected mean variance % unless starting weight matrix passed ('weights' above)] % weights = ICA weight matrix (comps,chans) [RO] % sphere = data sphering matrix (chans,chans) = spher(data) % Note that unmixing_matrix = weights*sphere {if sphering off -> eye(chans)} % compvars = back-projected component variances [RO] % bias = vector of final (ncomps) online bias [RO] (default = zeros()) % signs = extended-ICA signs for components [RO] (default = ones()) % [ -1 = sub-Gaussian; 1 = super-Gaussian] % lrates = vector of learning rates used at each training step [RO] % activations = activation time courses of the output components (ncomps,frames*epochs) % % Authors: Scott Makeig with contributions from Tony Bell, Te-Won Lee, % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky, Delorme Arnaud, % CNL/The Salk Institute, La Jolla, 1996- % Reference (please cite): % % Makeig, S., Bell, A.J., Jung, T-P and Sejnowski, T.J., % "Independent component analysis of electroencephalographic data," % In: D. Touretzky, M. Mozer and M. Hasselmo (Eds). Advances in Neural % Information Processing Systems 8:145-151, MIT Press, Cambridge, MA (1996). % % Toolbox Citation: % % Makeig, Scott et al. "EEGLAB: ICA Toolbox for Psychophysiological Research". % WWW Site, Swartz Center for Computational Neuroscience, Institute of Neural % Computation, University of San Diego California % <www.sccn.ucsd.edu/eeglab/>, 2000. [World Wide Web Publication]. % % For more information: % http://www.sccn.ucsd.edu/eeglab/icafaq.html - FAQ on ICA/EEG % http://www.sccn.ucsd.edu/eeglab/icabib.html - mss. on ICA & biosignals % http://www.cnl.salk.edu/~tony/ica.html - math. mss. on ICA % Copyright (C) 1996 Scott Makeig et al, 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 %%%%%%%%%%%%%%%%%%%%%%%%%%% Edit history %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % runica() - by Scott Makeig with contributions from Tony Bell, Te-Won Lee % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky et al. % CNL / Salk Institute 1996-00 % 04-30-96 built from icatest.m and ~jung/.../wtwpwica.m -sm % 07-28-97 new runica(), adds bias (default on), momentum (default off), % extended-ICA (Lee & Sejnowski, 1997), cumulative angledelta % (until lrate drops), keywords, signcount for speeding extended-ICA % 10-07-97 put acos() outside verbose loop; verbose 'off' wasn't stopping -sm % 11-11-97 adjusted help msg -sm % 11-30-97 return eye(chans) if sphering 'off' or 'none' (undocumented option) -sm % 02-27-98 use pinv() instead of inv() to rank order comps if ncomps < chans -sm % 04-28-98 added 'posact' and 'pca' flags -sm % 07-16-98 reduced length of randperm() for kurtosis subset calc. -se & sm % 07-19-98 fixed typo in weights def. above -tl & sm % 12-21-99 added 'specgram' option suggested by Michael Zibulevsky, UNM -sm % 12-22-99 fixed rand() sizing inefficiency on suggestion of Mike Spratling, UK -sm % 01-11-00 fixed rand() sizing bug on suggestion of Jack Foucher, Strasbourg -sm % 12-18-00 test for existence of Sig Proc Tlbx function 'specgram'; improve % 'specgram' option arguments -sm % 01-25-02 reformated help & license -ad % 01-25-02 lowered default lrate and block -ad % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [weights,sphere,meanvar,bias,signs,lrates,data,y] = runica(data,varargin) % NB: Now optionally returns activations as variable 'data' -sm 7/05 if nargin < 1 help runica return end [chans frames] = size(data); % determine the data size urchans = chans; % remember original data channels datalength = frames; if chans<2 fprintf('\nrunica() - data size (%d,%d) too small.\n\n', chans,frames); return end % %%%%%%%%%%%%%%%%%%%%%% Declare defaults used below %%%%%%%%%%%%%%%%%%%%%%%% % MAX_WEIGHT = 1e8; % guess that weights larger than this have blown up DEFAULT_STOP = 0.000001; % stop training if weight changes below this DEFAULT_ANNEALDEG = 60; % when angle change reaches this value, DEFAULT_ANNEALSTEP = 0.90; % anneal by multiplying lrate by this DEFAULT_EXTANNEAL = 0.98; % or this if extended-ICA DEFAULT_MAXSTEPS = 512; % ]top training after this many steps DEFAULT_MOMENTUM = 0.0; % default momentum weight DEFAULT_BLOWUP = 1000000000.0; % = learning rate has 'blown up' DEFAULT_BLOWUP_FAC = 0.8; % when lrate 'blows up,' anneal by this fac DEFAULT_RESTART_FAC = 0.9; % if weights blowup, restart with lrate % lower by this factor MIN_LRATE = 0.000001; % if weight blowups make lrate < this, quit MAX_LRATE = 0.1; % guard against uselessly high learning rate DEFAULT_LRATE = 0.00065/log(chans); % heuristic default - may need adjustment % for large or tiny data sets! % DEFAULT_BLOCK = floor(sqrt(frames/4)); % heuristic default DEFAULT_BLOCK = ceil(min(5*log(frames),0.3*frames)); % heuristic % - may need adjustment! % Extended-ICA option: DEFAULT_EXTENDED = 0; % default off DEFAULT_EXTBLOCKS = 1; % number of blocks per kurtosis calculation DEFAULT_NSUB = 1; % initial default number of assumed sub-Gaussians % for extended-ICA DEFAULT_EXTMOMENTUM = 0.5; % momentum term for computing extended-ICA kurtosis MAX_KURTSIZE = 6000; % max points to use in kurtosis calculation MIN_KURTSIZE = 2000; % minimum good kurtosis size (flag warning) SIGNCOUNT_THRESHOLD = 25; % raise extblocks when sign vector unchanged % after this many steps SIGNCOUNT_STEP = 2; % extblocks increment factor DEFAULT_SPHEREFLAG = 'on'; % use the sphere matrix as the default % starting weight matrix DEFAULT_PCAFLAG = 'off'; % don't use PCA reduction DEFAULT_POSACTFLAG = 'off'; % don't use posact(), to save space -sm 7/05 DEFAULT_SUBMEAN = 'on'; DEFAULT_VERBOSE = 1; % write ascii info to calling screen DEFAULT_BIASFLAG = 1; % default to using bias in the ICA update rule % %%%%%%%%%%%%%%%%%%%%%%% Set up keyword default values %%%%%%%%%%%%%%%%%%%%%%%%% % if nargout < 2, fprintf('runica() - needs at least two output arguments.\n'); return end epochs = 1; % do not care how many epochs in data pcaflag = DEFAULT_PCAFLAG; sphering = DEFAULT_SPHEREFLAG; % default flags posactflag = DEFAULT_POSACTFLAG; verbose = DEFAULT_VERBOSE; logfile = []; block = DEFAULT_BLOCK; % heuristic default - may need adjustment! lrate = DEFAULT_LRATE; annealdeg = DEFAULT_ANNEALDEG; annealstep = 0; % defaults declared below nochange = NaN; momentum = DEFAULT_MOMENTUM; maxsteps = DEFAULT_MAXSTEPS; weights = 0; % defaults defined below ncomps = chans; biasflag = DEFAULT_BIASFLAG; extended = DEFAULT_EXTENDED; extblocks = DEFAULT_EXTBLOCKS; kurtsize = MAX_KURTSIZE; signsbias = 0.02; % bias towards super-Gaussian components extmomentum= DEFAULT_EXTMOMENTUM; % exp. average the kurtosis estimates nsub = DEFAULT_NSUB; wts_blowup = 0; % flag =1 when weights too large wts_passed = 0; % flag weights passed as argument submean = DEFAULT_SUBMEAN; % %%%%%%%%%% Collect keywords and values from argument list %%%%%%%%%%%%%%% % if (nargin> 1 & rem(nargin,2) == 0) fprintf('runica(): Even number of input arguments???') return end for i = 1:2:length(varargin) % for each Keyword Keyword = varargin{i}; Value = varargin{i+1}; if ~isstr(Keyword) fprintf('runica(): keywords must be strings') return end Keyword = lower(Keyword); % convert upper or mixed case to lower if strcmp(Keyword,'weights') | strcmp(Keyword,'weight') if isstr(Value) fprintf(... 'runica(): weights value must be a weight matrix or sphere') return else weights = Value; wts_passed =1; end elseif strcmp(Keyword,'ncomps') if isstr(Value) fprintf('runica(): ncomps value must be an integer') return end if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end fprintf('*****************************************************************************************'); fprintf('************** WARNING: NCOMPS OPTION OFTEN DOES NOT RETURN ACCURATE RESULTS ************'); fprintf('************** WARNING: IF YOU FIND THE PROBLEM, PLEASE LET US KNOW ************'); fprintf('*****************************************************************************************'); ncomps = Value; if ~ncomps, ncomps = chans; end elseif strcmp(Keyword,'pca') if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end if isstr(Value) fprintf(... 'runica(): pca value should be the number of principal components to retain') return end pcaflag = 'on'; ncomps = Value; if ncomps > chans | ncomps < 1, fprintf('runica(): pca value must be in range [1,%d]\n',chans) return end chans = ncomps; elseif strcmp(Keyword,'posact') if ~isstr(Value) fprintf('runica(): posact value must be on or off') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off'), fprintf('runica(): posact value must be on or off') return end posactflag = Value; end elseif strcmp(Keyword,'submean') if ~isstr(Value) fprintf('runica(): submean value must be on or off') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off'), fprintf('runica(): submean value must be on or off') return end submean = Value; end elseif strcmp(Keyword,'lrate') if isstr(Value) fprintf('runica(): lrate value must be a number') return end lrate = Value; if lrate>MAX_LRATE | lrate <0, fprintf('runica(): lrate value is out of bounds'); return end if ~lrate, lrate = DEFAULT_LRATE; end elseif strcmp(Keyword,'block') | strcmp(Keyword,'blocksize') if isstr(Value) fprintf('runica(): block size value must be a number') return end block = floor(Value); if ~block, block = DEFAULT_BLOCK; end elseif strcmp(Keyword,'stop') | strcmp(Keyword,'nochange') ... | strcmp(Keyword,'stopping') if isstr(Value) fprintf('runica(): stop wchange value must be a number') return end nochange = Value; elseif strcmp(Keyword,'logfile') if ~isstr(Value) fprintf('runica(): logfile value must be a string') return end logfile = Value; elseif strcmp(Keyword,'maxsteps') | strcmp(Keyword,'steps') if isstr(Value) fprintf('runica(): maxsteps value must be an integer') return end maxsteps = Value; if ~maxsteps, maxsteps = DEFAULT_MAXSTEPS; end if maxsteps < 0 fprintf('runica(): maxsteps value (%d) must be a positive integer',maxsteps) return end elseif strcmp(Keyword,'anneal') | strcmp(Keyword,'annealstep') if isstr(Value) fprintf('runica(): anneal step value (%2.4f) must be a number (0,1)',Value) return end annealstep = Value; if annealstep <=0 | annealstep > 1, fprintf('runica(): anneal step value (%2.4f) must be (0,1]',annealstep) return end elseif strcmp(Keyword,'annealdeg') | strcmp(Keyword,'degrees') if isstr(Value) fprintf('runica(): annealdeg value must be a number') return end annealdeg = Value; if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG; elseif annealdeg > 180 | annealdeg < 0 fprintf('runica(): annealdeg (%3.1f) is out of bounds [0,180]',... annealdeg); return end elseif strcmp(Keyword,'momentum') if isstr(Value) fprintf('runica(): momentum value must be a number') return end momentum = Value; if momentum > 1.0 | momentum < 0 fprintf('runica(): momentum value is out of bounds [0,1]') return end elseif strcmp(Keyword,'sphering') | strcmp(Keyword,'sphereing') ... | strcmp(Keyword,'sphere') if ~isstr(Value) fprintf('runica(): sphering value must be on, off, or none') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off') & ~strcmp(Value,'none'), fprintf('runica(): sphering value must be on or off') return end sphering = Value; end elseif strcmp(Keyword,'bias') if ~isstr(Value) fprintf('runica(): bias value must be on or off') return else Value = lower(Value); if strcmp(Value,'on') biasflag = 1; elseif strcmp(Value,'off'), biasflag = 0; else fprintf('runica(): bias value must be on or off') return end end elseif strcmp(Keyword,'specgram') | strcmp(Keyword,'spec') if ~exist('specgram') < 2 % if ~exist or defined workspace variable fprintf(... 'runica(): MATLAB Sig. Proc. Toolbox function "specgram" not found.\n') return end if isstr(Value) fprintf('runica(): specgram argument must be a vector') return end srate = Value(1); if (srate < 0) fprintf('runica(): specgram srate (%4.1f) must be >=0',srate) return end if length(Value)>1 loHz = Value(2); if (loHz < 0 | loHz > srate/2) fprintf('runica(): specgram loHz must be >=0 and <= srate/2 (%4.1f)',srate/2) return end else loHz = 0; % default end if length(Value)>2 hiHz = Value(3); if (hiHz < loHz | hiHz > srate/2) fprintf('runica(): specgram hiHz must be >=loHz (%4.1f) and <= srate/2 (%4.1f)',loHz,srate/2) return end else hiHz = srate/2; % default end if length(Value)>3 Hzframes = Value(5); if (Hzframes<0 | Hzframes > size(data,2)) fprintf('runica(): specgram frames must be >=0 and <= data length (%d)',size(data,2)) return end else Hzframes = size(data,2); % default end if length(Value)>4 Hzwinlen = Value(4); if rem(Hzframes,Hzwinlen) % if winlen doesn't divide frames fprintf('runica(): specgram Hzinc must divide frames (%d)',Hzframes) return end else Hzwinlen = Hzframes; % default end Specgramflag = 1; % set flag to perform specgram() elseif strcmp(Keyword,'extended') | strcmp(Keyword,'extend') if isstr(Value) fprintf('runica(): extended value must be an integer (+/-)') return else extended = 1; % turn on extended-ICA extblocks = fix(Value); % number of blocks per kurt() compute if extblocks < 0 nsub = -1*fix(extblocks); % fix this many sub-Gauss comps elseif ~extblocks, extended = 0; % turn extended-ICA off elseif kurtsize>frames, % length of kurtosis calculation kurtsize = frames; if kurtsize < MIN_KURTSIZE fprintf(... 'runica() warning: kurtosis values inexact for << %d points.\n',... MIN_KURTSIZE); end end end elseif strcmp(Keyword,'verbose') if ~isstr(Value) fprintf('runica(): verbose flag value must be on or off') return elseif strcmp(Value,'on'), verbose = 1; elseif strcmp(Value,'off'), verbose = 0; else fprintf('runica(): verbose flag value must be on or off') return end else fprintf('runica(): unknown flag') return end end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize weights, etc. %%%%%%%%%%%%%%%%%%%%%%%% % if ~annealstep, if ~extended, annealstep = DEFAULT_ANNEALSTEP; % defaults defined above else annealstep = DEFAULT_EXTANNEAL; % defaults defined above end end % else use annealstep from commandline if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG - momentum*90; % heuristic if annealdeg < 0, annealdeg = 0; end end if ncomps > chans | ncomps < 1 fprintf('runica(): number of components must be 1 to %d.\n',chans); return end % %%%%%%%%%%%%%%%%%%%%% Check keyword values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if frames<chans, fprintf('runica(): data length (%d) < data channels (%d)!\n',frames,chans) return elseif block < 2, fprintf('runica(): block size %d too small!\n',block) return elseif block > frames, fprintf('runica(): block size exceeds data length!\n'); return elseif floor(epochs) ~= epochs, fprintf('runica(): data length is not a multiple of the epoch length!\n'); return elseif nsub > ncomps fprintf('runica(): there can be at most %d sub-Gaussian components!\n',ncomps); return end; if ~isempty(logfile) fid = fopen(logfile, 'w'); if fid == -1, error('Cannot open logfile for writing'); end; else fid = []; end; verb = verbose; if weights ~= 0, % initialize weights % starting weights are being passed to runica() from the commandline if chans>ncomps & weights ~=0, [r,c]=size(weights); if r~=ncomps | c~=chans, fprintf('runica(): weight matrix must have %d rows, %d columns.\n', ... chans,ncomps); return; end end icaprintf(verb,fid,'Using starting weight matrix named in argument list ...\n'); end; % % adjust nochange if necessary % if isnan(nochange) if ncomps > 32 nochange = 1E-7; nochangeupdated = 1; % for fprinting purposes else nochangeupdated = 1; % for fprinting purposes nochange = DEFAULT_STOP; end; else nochangeupdated = 0; end; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Process the data %%%%%%%%%%%%%%%%%%%%%%%%%% % icaprintf(verb,fid,'\nInput data size [%d,%d] = %d channels, %d frames\n', ... chans,frames,chans,frames); if strcmp(pcaflag,'on') icaprintf(verb,fid,'After PCA dimension reduction,\n finding '); else icaprintf(verb,fid,'Finding '); end if ~extended icaprintf(verb,fid,'%d ICA components using logistic ICA.\n',ncomps); else % if extended icaprintf(verb,fid,'%d ICA components using extended ICA.\n',ncomps); if extblocks > 0 icaprintf(verb,fid,'Kurtosis will be calculated initially every %d blocks using %d data points.\n',... extblocks, kurtsize); else icaprintf(verb,fid,'Kurtosis will not be calculated. Exactly %d sub-Gaussian components assumed.\n',nsub); end end icaprintf(verb,fid,'Decomposing %d frames per ICA weight ((%d)^2 = %d weights, %d frames)\n',... floor(frames/ncomps.^2),ncomps.^2,frames); icaprintf(verb,fid,'Initial learning rate will be %g, block size %d.\n',... lrate,block); if momentum>0, icaprintf(verb,fid,'Momentum will be %g.\n',momentum); end icaprintf(verb,fid,'Learning rate will be multiplied by %g whenever angledelta >= %g deg.\n', ... annealstep,annealdeg); if nochangeupdated icaprintf(verb,fid,'More than 32 channels: default stopping weight change 1E-7\n'); end; icaprintf(verb,fid,'Training will end when wchange < %g or after %d steps.\n', nochange,maxsteps); if biasflag, icaprintf(verb,fid,'Online bias adjustment will be used.\n'); else icaprintf(verb,fid,'Online bias adjustment will not be used.\n'); end % %%%%%%%%%%%%%%%%% Remove overall row means of data %%%%%%%%%%%%%%%%%%%%%%% % if strcmpi(submean, 'on') icaprintf(verb,fid,'Removing mean of each channel ...\n'); rowmeans = mean(data,2); for index = 1:size(data,1) data(index,:) = data(index,:) - rowmeans(index); % subtract row means end; end; icaprintf(verb,fid,'Final training data range: %g to %g\n', min(min(data,[],2)),max(max(data,[],2))); % %%%%%%%%%%%%%%%%%%% Perform PCA reduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') icaprintf(verb,fid,'Reducing the data to %d principal dimensions...\n',ncomps); [eigenvectors,eigenvalues,data] = pcsquash(data,ncomps); % make data its projection onto the ncomps-dim principal subspace end % %%%%%%%%%%%%%%%%%%% Perform specgram transformation %%%%%%%%%%%%%%%%%%%%%%% % if exist('Specgramflag') == 1 % [P F T] = SPECGRAM(A,NFFT,Fs,WINDOW,NOVERLAP) % MATLAB Sig Proc Toolbox % Hzwinlen = fix(srate/Hzinc); % CHANGED FROM THIS 12/18/00 -sm Hzfftlen = 2^(ceil(log(Hzwinlen)/log(2))); % make FFT length next higher 2^k Hzoverlap = 0; % use sequential windows % % Get freqs and times from 1st channel analysis % [tmp,freqs,tms] = specgram(data(1,:),Hzfftlen,srate,Hzwinlen,Hzoverlap); fs = find(freqs>=loHz & freqs <= hiHz); icaprintf(verb,fid,'runica(): specified frequency range too narrow, exiting!\n'); specdata = reshape(tmp(fs,:),1,length(fs)*size(tmp,2)); specdata = [real(specdata) imag(specdata)]; % fprintf(' size(fs) = %d,%d\n',size(fs,1),size(fs,2)); % fprintf(' size(tmp) = %d,%d\n',size(tmp,1),size(tmp,2)); % % Loop through remaining channels % for ch=2:chans [tmp] = specgram(data(ch,:),Hzwinlen,srate,Hzwinlen,Hzoverlap); tmp = reshape((tmp(fs,:)),1,length(fs)*size(tmp,2)); specdata = [specdata;[real(tmp) imag(tmp)]]; % channels are rows end % % Print specgram confirmation and details % icaprintf(verb,fid,'Converted data to %d channels by %d=2*%dx%d points spectrogram data.\n',... chans,2*length(fs)*length(tms),length(fs),length(tms)); if length(fs) > 1 icaprintf(verb,fid,' Low Hz %g, high Hz %g, Hz incr %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),freqs(fs(2))-freqs(fs(1)),Hzwinlen); else icaprintf(verb,fid,' Low Hz %g, high Hz %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),Hzwinlen); end % % Replace data with specdata % data = specdata; datalength=size(data,2); end % %%%%%%%%%%%%%%%%%%% Perform sphering %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(sphering,'on'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% icaprintf(verb,fid,'Computing the sphering matrix...\n'); sphere = 2.0*inv(sqrtm(double(mycov(data)))); % find the "sphering" matrix = spher() if ~weights, icaprintf(verb,fid,'Starting weights are the identity matrix ...\n'); weights = eye(ncomps,chans); % begin with the identity matrix else % weights given on commandline icaprintf(verb,fid,'Using starting weights named on commandline ...\n'); end icaprintf(verb,fid,'Sphering the data ...\n'); elseif strcmp(sphering,'off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~weights % is starting weights not given icaprintf(verb,fid,'Using the sphering matrix as the starting weight matrix ...\n'); icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n'); sphere = 2.0*inv(sqrtm(mycov(data))); % find the "sphering" matrix = spher() weights = eye(ncomps,chans)*sphere; % begin with the identity matrix sphere = eye(chans); % return the identity matrix else % weights ~= 0 icaprintf(verb,fid,'Using starting weights from commandline ...\n'); icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n'); sphere = eye(chans); % return the identity matrix end elseif strcmp(sphering,'none') sphere = eye(chans,chans);% return the identity matrix if ~weights icaprintf(verb,fid,'Starting weights are the identity matrix ...\n'); icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n'); weights = eye(ncomps,chans); % begin with the identity matrix else % weights ~= 0 icaprintf(verb,fid,'Using starting weights named on commandline ...\n'); icaprintf(verb,fid,'Returning the identity matrix in variable "sphere" ...\n'); end icaprintf(verb,fid,'Returned variable "sphere" will be the identity matrix.\n'); end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize ICA training %%%%%%%%%%%%%%%%%%%%%%%%% % lastt=fix((datalength/block-1)*block+1); BI=block*eye(ncomps,ncomps); delta=zeros(1,chans*ncomps); changes = []; degconst = 180./pi; startweights = weights; prevweights = startweights; oldweights = startweights; prevwtchange = zeros(chans,ncomps); oldwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); onesrow = ones(1,block); bias = zeros(ncomps,1); signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end if extended & extblocks < 0, icaprintf(verb,fid,'Fixed extended-ICA sign assignments: '); for k=1:ncomps icaprintf(verb,fid,'%d ',signs(k)); end; icaprintf(verb,fid,'\n'); end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; signcount = 0; % counter for same-signs signcounts = []; urextblocks = extblocks; % original value, for resets old_kk = zeros(1,ncomps); % for kurtosis momemtum % %%%%%%%% ICA training loop using the logistic sigmoid %%%%%%%%%%%%%%%%%%% % icaprintf(verb,fid,'Beginning ICA training ...'); if extended, icaprintf(verb,fid,' first training step may be slow ...\n'); else icaprintf(verb,fid,'\n'); end step=0; laststep=0; blockno = 1; % running block counter for kurtosis interrupts rand('state',sum(100*clock)); % set the random number generator state to % a position dependent on the system clock %% Compute ICA Weights if biasflag & extended while step < maxsteps, %%% ICA step = pass through all the data %%%%%%%%% timeperm=randperm(datalength); % shuffle data order at each step for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% pause(0); if ~isempty(get(0, 'currentfigure')) % look for user abort if strcmp(get(gcf, 'tag'), 'stop') if ~isempty(fid), fclose(fid); end; close; error('USER ABORT'); end; end %% promote data block (only) to double to keep u and weights double u=(weights*sphere)*double(data(:,timeperm(t:t+block-1))) + bias*onesrow; y=tanh(u); weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; bias = bias + lrate*sum((-2*y)')'; % for tanh() nonlin. if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end if ~wts_blowup % %%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%% %while step < maxsteps if extblocks > 0 & rem(blockno,extblocks) == 0, % recompute signs vector using kurtosis if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling rp = fix(rand(1,kurtsize)*datalength); % pick random subset % Accout for the possibility of a 0 generation by rand ou = find(rp == 0); while ~isempty(ou) % 1-11-00 suggestion by J. Foucher rp(ou) = fix(rand(1,length(ou))*datalength); ou = find(rp == 0); end partact=(weights*sphere)*double(data(:,rp(1:kurtsize))); else % for small data sets, partact=(weights*sphere)*double(data); % use whole data end m2=mean(partact'.^2).^2; m4= mean(partact'.^4); kk= (m4./m2)-3.0; % kurtosis estimates if extmomentum kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum old_kk = kk; end signs=diag(sign(kk+signsbias)); % pick component signs if signs == oldsigns, signcount = signcount+1; else signcount = 0; end oldsigns = signs; signcounts = [signcounts signcount]; if signcount >= SIGNCOUNT_THRESHOLD, extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation signcount = 0; % less frequent if sign end % is not changing end % extblocks > 0 & . . . end % if extended & ~wts_blowup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% blockno = blockno + 1; if wts_blowup break end end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, icaprintf(verb,fid,''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; if lrate> MIN_LRATE r = rank(double(data(:,1:min(10000,size(data,2))))); % determine if data rank is too low if r<ncomps icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',... r,ncomps); return else icaprintf(verb,fid,... 'Lowering learning rate to %g and starting again.\n',lrate); end else icaprintf(verb,fid, ... 'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end places = -floor(log10(nochange)); icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ... step, lrate, change, degconst*angledelta); % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %% Compute ICA Weights if biasflag & ~extended while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% timeperm=randperm(datalength); % shuffle data order at each step for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% pause(0); if ~isempty(get(0, 'currentfigure')) & strcmp(get(gcf, 'tag'), 'stop') close; error('USER ABORT'); end; u=(weights*sphere)*double(data(:,timeperm(t:t+block-1))) + bias*onesrow; y=1./(1+exp(-u)); weights = weights + lrate*(BI+(1-2*y)*u')*weights; bias = bias + lrate*sum((1-2*y)')'; % for logistic nonlin. % if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end blockno = blockno + 1; if wts_blowup break end end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, icaprintf(verb,fid,''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); if lrate> MIN_LRATE r = rank(double(data(:,1:min(10000,size(data,2))))); % determine if data rank is too low if r<ncomps icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',r,ncomps); return else icaprintf(verb,fid,'Lowering learning rate to %g and starting again.\n',lrate); end else icaprintf(verb,fid,'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end places = -floor(log10(nochange)); icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ... step, lrate, change, degconst*angledelta); % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %% Compute ICA Weights if ~biasflag & extended while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% timeperm=randperm(datalength); % shuffle data order at each step through data for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% pause(0); if ~isempty(get(0, 'currentfigure')) & strcmp(get(gcf, 'tag'), 'stop') close; error('USER ABORT'); % detect user abort end u=(weights*sphere)*double(data(:,timeperm(t:t+block-1))); % promote block to dbl y=tanh(u); % weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end if ~wts_blowup % %%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%% %while step < maxsteps if extblocks > 0 & rem(blockno,extblocks) == 0, % recompute signs vector using kurtosis if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling rp = fix(rand(1,kurtsize)*datalength); % pick random subset % Accout for the possibility of a 0 generation by rand ou = find(rp == 0); while ~isempty(ou) % 1-11-00 suggestion by J. Foucher rp(ou) = fix(rand(1,length(ou))*datalength); ou = find(rp == 0); end partact=(weights*sphere)*double(data(:,rp(1:kurtsize))); else % for small data sets, partact=(weights*sphere)*double(data); % use whole data end m2=mean(partact'.^2).^2; m4= mean(partact'.^4); kk= (m4./m2)-3.0; % kurtosis estimates if extmomentum kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum old_kk = kk; end signs=diag(sign(kk+signsbias)); % pick component signs if signs == oldsigns, signcount = signcount+1; else signcount = 0; end oldsigns = signs; signcounts = [signcounts signcount]; if signcount >= SIGNCOUNT_THRESHOLD, extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation signcount = 0; % less frequent if sign end % is not changing end % extblocks > 0 & . . . end % if ~wts_blowup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% blockno = blockno + 1; if wts_blowup break end end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, icaprintf(verb,fid,''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs)); if lrate> MIN_LRATE r = rank(data); % find whether data rank is too low if r<ncomps icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',... r,ncomps); return else icaprintf(verb,fid,... 'Lowering learning rate to %g and starting again.\n',lrate); end else icaprintf(verb,fid, ... 'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end places = -floor(log10(nochange)); icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ... step, lrate, change, degconst*angledelta); % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Compute ICA Weights if ~biasflag & ~extended while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% timeperm=randperm(datalength); % shuffle data order at each step for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% pause(0); if ~isempty(get(0, 'currentfigure')) & strcmp(get(gcf, 'tag'), 'stop') close; error('USER ABORT'); end; u=(weights*sphere)*double(data(:,timeperm(t:t+block-1))); y=1./(1+exp(-u)); % weights = weights + lrate*(BI+(1-2*y)*u')*weights; if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end blockno = blockno + 1; if wts_blowup break end end % for t=1:block:lastt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, icaprintf(verb,fid,''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); if lrate> MIN_LRATE r = rank(data); % find whether data rank is too low if r<ncomps icaprintf(verb,fid,'Data has rank %d. Cannot compute %d components.\n',... r,ncomps); return else icaprintf(verb,fid,... 'Lowering learning rate to %g and starting again.\n',lrate); end else icaprintf(verb,fid, ... 'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end places = -floor(log10(nochange)); icaprintf(verb,fid,'step %d - lrate %5f, wchange %8.8f, angledelta %4.1f deg\n', ... step, lrate, change, degconst*angledelta); % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end while step < maxsteps (ICA Training) %%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %% Finalize Computed Data for Output if ~laststep laststep = step; end; lrates = lrates(1,1:laststep); % truncate lrate history vector % %%%%%%%%%%%%%% Orient components towards max positive activation %%%%%% % if nargout > 6 | strcmp(posactflag,'on') % make activations from sphered and pca'd data; -sm 7/05 % add back the row means removed from data before sphering if strcmp(pcaflag,'off') sr = sphere * rowmeans'; for r = 1:ncomps data(r,:) = data(r,:)+sr(r); % add back row means end data = (weights*sphere)*data; % OK in single else ser = sphere*eigenvectors(:,1:ncomps)'*rowmeans'; for r = 1:ncomps data(r,:) = data(r,:)+ser(r); % add back row means end data = (weights*sphere)*data; % OK in single end; end % % NOTE: Now 'data' are the component activations = weights*sphere*raw_data % % %%%%%%%%%%%%%% If pcaflag, compose PCA and ICA matrices %%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') icaprintf(verb,fid,'Composing the eigenvector, weights, and sphere matrices\n'); icaprintf(verb,fid,' into a single rectangular weights matrix; sphere=eye(%d)\n'... ,chans); weights= weights*sphere*eigenvectors(:,1:ncomps)'; sphere = eye(urchans); end % %%%%%% Sort components in descending order of max projected variance %%%% % icaprintf(verb,fid,'Sorting components in descending order of mean projected variance ...\n'); % %%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % meanvar = zeros(ncomps,1); % size of the projections if ncomps == urchans % if weights are square . . . winv = inv(weights*sphere); else icaprintf(verb,fid,'Using pseudo-inverse of weight matrix to rank order component projections.\n'); winv = pinv(weights*sphere); end % % compute variances without backprojecting to save time and memory -sm 7/05 % for index = 1:size(data,1) meanvar(index) = sum(winv(:,index).^2).*sum(double(data(index,:)).^2)/((chans*frames)-1); % from Rey Ramirez 8/07 end; % %%%%%%%%%%%%%% Sort components by mean variance %%%%%%%%%%%%%%%%%%%%%%%% % [sortvar, windex] = sort(meanvar); windex = windex(ncomps:-1:1); % order large to small meanvar = meanvar(windex); % %%%%%%%%%%%% re-orient max(abs(activations)) to >=0 ('posact') %%%%%%%% % if strcmp(posactflag,'on') % default is now off to save processing and memory icaprintf(verb,fid,'Making the max(abs(activations)) positive ...\n'); for index = 1:ize(data,2) [tmp ix(index)] = max(abs(data(index,:))); % = max abs activations end; signsflipped = 0; for r=1:ncomps if sign(data(r,ix(r))) < 0 if nargout>6 % if activations are to be returned (only) data(r,:) = -1*data(r,:); % flip activations so max(abs()) is >= 0 end winv(:,r) = -1*winv(:,r); % flip component maps signsflipped = 1; end end if signsflipped == 1 weights = pinv(winv)*inv(sphere); % re-invert the component maps end % [data,winvout,weights] = posact(data,weights); % overwrite data with activations % changes signs of activations (now = data) and weights % to make activations (data) net rms-positive % can call this outside of runica() - though it is inefficient! end % %%%%%%%%%%%%%%%%%%%%% Filter data using final weights %%%%%%%%%%%%%%%%%% % if nargout>6, % if activations are to be returned icaprintf(verb,fid,'Permuting the activation wave forms ...\n'); data = data(windex,:); % data is now activations -sm 7/05 else clear data end weights = weights(windex,:);% reorder the weight matrix bias = bias(windex); % reorder them signs = diag(signs); % vectorize the signs matrix signs = signs(windex); % reorder them if ~isempty(fid), fclose(fid); end; % close logfile % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % return % printing functions % ------------------ function icaprintf(verb,fid, varargin); if verb if ~isempty(fid) fprintf(fid, varargin{:}); end; fprintf(varargin{:}); end; % this function compute covariance % without using much memory (no need to transpose a) % -------------------------------- function c = mycov(a) % same as cov(a') try c = cov(a'); catch, c = zeros(size(a,1), size(a,1)); for i1=1:size(a,1) for i2=1:size(a,1) %c(i1,i2) = sum(double((a(i1,:)-mean(a(i1,:)))).*(double(a(i2,:)-mean(a(i2,:)))))/(size(a,2)-1); c(i1,i2) = sum(double(a(i1,:).*a(i2,:)))/(size(a,2)-1); % mean has already been subtracted end; end; end;
github
lcnbeapp/beapp-master
eeg_time2prev.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/eeg_time2prev.m
6,514
utf_8
b09492c5bf451c4d42c06b87dc8921af
% eeg_time2prev() - returns a vector giving, for each event of specified ("target") type(s), % the delay (in ms) since the preceding event (if any) of specified % ("previous") type(s). Requires the EEG.urevent structure, plus % EEG.event().urevent pointers to it. % % NOW SUPERCEDED BY eeg_context() % Usage: % >> [delays,targets,urtargs,urprevs] = eeg_time2prev(EEG,{target},{previous}); % Inputs: % EEG - structure containing an EEGLAB dataset % {target} - cell array of strings naming event type(s) of the specified target events %{previous} - cell array of strings naming event type(s) of the specified previous events % % Outputs: % delays - vector giving, for each event of a type listed in "target", the delay (in ms) % since the last preceding event of a type listed in "previous" (0 if none such). % targets - vector of indices of the "target" events in the event structure % urtargs - vector of indices of the "target" events in the urevent structure % urprevs - vector of indices of the "previous" events in the urevent structure (0 if none). % % Example: % >> target = {'novel'}; % target event type 'novel' % >> previous = {'novel', 'rare'}; % either 'novel' or 'rare' % >> [delays,targets] = eeg_time2prev(EEG,target,previous); %% Vector 'delays' now contains delays (in ms) from each 'novel' event to the previous %% 'rare' OR 'novel' event, else 0 if none such. Vector 'targets' now contains the %% 'novel' event indices. %% % Scott Makeig & Arnaud Delorme, SCCN/INC/UCSD, August 28, 2003 function [delays,targets,urtargets,urprevs] = eeg_time2prev(EEG,target,previous); verbose = 1; % FLAG (1=on|0=off) nevents = length(EEG.event); % %%%%%%%%%%%%%%%%%%%% Test input arguments %%%%%%%%%%%%%%%%%%%%%%%%% % if ~iscell(target) error('2nd argument "target" must be a {cell array} of event type strings.'); return end for k=1:length(target) if ~ischar([ target{k}{:} ]) error('2nd argument "target" must be a {cell array} of event type strings.'); end end if ~iscell(previous) error('3rd argument "previous" must be a {cell array} of event types.'); return end for k=1:length(target) % make all target types strings if ~ischar(target{k}) target{k} = num2str(target{k}); end end for k=1:length(previous) % make all previous types strings if ~ischar(previous{k}) previous{k} = num2str(previous{k}); end end if ~isfield(EEG,'urevent') error('requires the urevent structure be present.'); return end if length(EEG.urevent) < nevents error('WARNING: In dataset, number of urevents < number of events!?'); return end % %%%%%%%%%%%%%%%%%%%% Initialize output arrays %%%%%%%%%%%%%%%%%%%%%% % delays = zeros(1,nevents); % holds output times in ms targets = zeros(1,nevents); % holds indxes of targets urtargets = zeros(1,nevents); % holds indxes of targets urprevs = zeros(1,nevents); % holds indxes of prevs targetcount = 0; % index of current target % Below: % idx = current event index % uridx = current urevent index % tidx = target type index % uidx = previous urevent index % pidx = previous type index % %%%%%%%%%%%for each event in the dataset %%%%%%%%%%%%%%%%%%%% % for idx = 1:nevents % for each event in the dataset % %%%%%%%%%%%%%%%%%%%%%%%% find target events %%%%%%%%%%%%%%%%% % uridx = EEG.event(idx).urevent; % find its urevent index istarget = 0; % initialize target flag tidx = 1; % initialize target type index while ~istarget & tidx<=length(target) % for each potential target type if strcmpi(num2str(EEG.urevent(uridx).type),target(tidx)) istarget=1; % flag event as target targetcount = targetcount+1; % increment target count targets(targetcount) = idx; % save event index urtargets(targetcount) = uridx; % save urevent index break % stop target type checking else tidx = tidx+1; % else try next target type end end if istarget % if current event is a target type % %%%%%%%%%%%%%%%%%%% Find a 'previous' event %%%%%%%%%%%%%%%%%% % isprevious = 0; % initialize previous flag uidx = uridx-1; % begin with the previous urevent while uridx > 0 pidx = 1; % initialize previous type index while ~isprevious & pidx<=length(previous) % for each previous event type if strcmpi(num2str(EEG.urevent(uidx).type),previous(pidx)) isprevious=1; % flag 'previous' event urprevs(targetcount) = uidx; % mark event as previous break % stop previous type checking else pidx = pidx+1; % try next 'previous' event type end end % pidx if isprevious break % stop previous event checking else uidx = uidx-1; % keep checking for a 'previous' type event end % isprevious end % uidx % %%% Compute delay from current target to previous event %%%%% % if isprevious % if type 'previous' event found delays(targetcount) = 1000/EEG.srate * ... (-1)*(EEG.urevent(uridx).latency - EEG.urevent(urprevs(targetcount)).latency); else delays(targetcount) = 0; % mark no previous event with 0 end if verbose fprintf('%4d. (targ %s) %4d - (prev %s) %4d = %4.1f ms\n',... targetcount, targets(tidx),idx, ... previous(pidx),urprevs(targetcount),... delays(targetcount)); end % verbose end % istarget end % event loop % %%%%%%%%%%%%%% Truncate the output arrays %%%%%%%%%%%%%%%%%%%%%% % if targetcount > 0 targets = targets(1:targetcount); urtargets = urtargets(1:targetcount); urprevs = urprevs(1:targetcount); delays = delays(1:targetcount); else if verbose fprintf('eeg_time2prev(): No target type events found.\n') end targets = []; urtargets = []; urprevs = []; delays = []; end
github
lcnbeapp/beapp-master
helpforexe.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/helpforexe.m
2,556
utf_8
dc086adf5a27490f1a3e39f6d218bbd1
% helpforexe() - Write help files for exe version % % Usage: % histtoexe( mfile, folder) % % Inputs: % mfile - [cell of string] Matlab files with help message % folder - [string] Output folder % % Output: % text files name help_"mfile".m % % Author: Arnaud Delorme, 2006 % % See also: eeglab() % 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 helpforexe( funct, fold ); if nargin <1 help histforexe; return; end; nonmatlab = 0; % write all files % --------------- for index = 1:length(funct) doc1 = readfunc(funct{index}, nonmatlab); fid = fopen( fullfile(fold, [ 'help_' funct{index} ]), 'w'); for ind2 = 1:length(doc1) if isempty(doc1{ind2}) fprintf(fid, [ 'disp('' '');\n' ]); else fprintf(fid, [ 'disp(' vararg2str({ doc1{ind2} }) ');\n' ]); end; end; fclose(fid); %fprintf(fid, 'for tmpind = 1:length(tmptxt), if isempty(tmptxt{tmpind}), disp('' ''); else disp(tmptxt{tmpind}); end; end; clear tmpind tmptxt;\n' ); end; % try all functions % ----------------- tmppath = pwd; cd(fold); for index = 1:length(funct) evalc([ 'help_' funct{index}(1:end-2) ]); end; cd(tmppath); return; %------------------------------------- function [doc] = readfunc(funct, nonmatlab) doc = {}; if nonmatlab fid = fopen( funct, 'r'); else if findstr( funct, '.m') fid = fopen( funct, 'r'); else fid = fopen( [funct '.m'], 'r'); end; end; if fid == -1 error('File not found'); end; sub = 1; try, if ~isunix, sub = 0; end; catch, end; if nonmatlab str = fgets( fid ); while ~feof(fid) str = deblank(str(1:end-sub)); doc = { doc{:} str(1:end) }; str = fgets( fid ); end; else str = fgets( fid ); while (str(1) == '%') str = deblank(str(1:end-sub)); doc = { doc{:} str(2:end) }; str = fgets( fid ); end; end; fclose(fid);
github
lcnbeapp/beapp-master
imagesclogy.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/imagesclogy.m
3,685
utf_8
73cfa531e2316e4148fec6793f6f8646
% imagesclogy() - make an imagesc(0) plot with log y-axis values (ala semilogy()) % % Usage: >> imagesclogy(times,freqs,data); % Usage: >> imagesclogy(times,freqs,data,clim,xticks,yticks,'key','val',...); % % Inputs: % times = vector of x-axis values % 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 imagesclogy(times,freqs,data,clim, xticks, yticks, varargin) if size(data,1) ~= length(freqs) fprintf('imagesclogy(): data matrix must have %d rows!\n',length(freqs)); return end if size(data,2) ~= length(times) fprintf('imagesclogy(): data matrix must have %d columns!\n',length(times)); return end if min(freqs)<= 0 fprintf('imagesclogy(): frequencies must be > 0!\n'); return end % 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(times,newfreqs,data,clim); else imagesc(times,newfreqs,data); end; set(gca, 'yscale', 'log'); % puting ticks % ------------ if nargin >= 5, set(gca, 'xtick', xticks); end; 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
lcnbeapp/beapp-master
gauss.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/gauss.m
431
utf_8
ac68a4b38603e75bbb97ab7770117c1c
% gauss() - return a smooth Gaussian window % % Usage: % >> outvector = gauss(frames,sds); % % Inputs: % frames = window length % sds = number of +/-std. deviations = steepness % (~0+ -> flat; >>10 -> spike) function outvec = gauss(frames,sds) outvec = []; if nargin < 2 help gauss return end if sds <=0 | frames < 1 help gauss return end incr = 2*sds/(frames-1); outvec = exp(-(-sds:incr:sds).^2);
github
lcnbeapp/beapp-master
runpca2.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/runpca2.m
2,347
utf_8
bec4863264e507c374a64d5ecbfe4132
% runpca() - perform principal component analysis (PCA) using singular value % decomposition (SVD) using Matlab svd() or svds() % >> inv(eigvec)*data = pc; % Usage: % >> [pc,eigvec,sv] = runpca(data); % >> [pc,eigvec,sv] = runpca(data,num,norm) % % Inputs: % data - input data matrix (rows are variables, columns observations) % num - number of principal comps to return {def|0|[] -> rows in data} % norm - 1/0 = do/don't normalize the eigvec's to be equivariant % {def|0 -> no normalization} % Outputs: % pc - the principal components, i.e. >> inv(eigvec)*data = pc; % eigvec - the inverse weight matrix (=eigenvectors). >> data = eigvec*pc; % sv - the singular values (=eigenvalues) % % Author: Colin Humphries, CNL / Salk Institute, 1997 % % See also: runica() % Copyright (C) Colin Humphries, CNL / Salk Institute, Aug, 1997 % % 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/31/00 renamed runpca() and improved usage message -sm % 01-25-02 reformated help & license, added links -ad function [pc,A,sv]= runpca2(data,K,dosym) [chans,frames] = size(data); if nargin < 3 || K < chans dosym = 1; end if nargin < 2 K = chans; end if nargin < 1 help runpca return end % remove the mean for i = 1:chans data(i,:) = data(i,:) - mean(data(i,:)); end % do svd [U,S,V] = svd(data*data'/frames); % U and V should be the same since data*data' is symmetric sv = sqrt(diag(S)); if dosym == 1 pc = pinv(diag(sv(1:K))) * V(:,1:K)' * data; A = U(:,1:K) * diag(sv(1:K)); else pc = U * pinv(diag(sv)) * V' * data; A = U * diag(sv) * V'; end
github
lcnbeapp/beapp-master
loc_subsets.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/loc_subsets.m
8,435
utf_8
0d9bef14db75412fc13a4088966c510a
% loc_subsets() - Separate channels into maximally evenly-spaced subsets. % This is achieved by exchanging channels between subsets so as to % increase the sum of average of distances within each channel subset. % Usage: % >> subset = loc_subsets(chanlocs, nchans); % select an evenly spaced nchans % >> [subsets subidx pos] = loc_subsets(chanlocs, nchans, plotobj, plotchans, keepchans); % % Inputs: % % chanlocs - EEGLAB dataset channel locations structure (e.g., EEG.chanlocs) % % nchans - (1,N) matrix containing number of channels that should be in each % of N channel subsets respectively. if total number of channels in % all subsets is less than the number of EEG channels in the chanlocs % structure, N+1 subsets are created. The last subset includes the % remaining channels. % % Optional inputs: % % plotobj - (true|false|1|0) plot the time course of the objective function % {default: false|0) % plotchans - (true|false|1|0) make 3-D plots showing the channel locations of % the subsets {default: false|0) % keepchans - (cell array) channels that has to be kept in each set and % not undergo optimization. You can use this option to make % sure certain channels will be assigned to each set. For % example, to keep channels 1:10 to the first subset and % channels 20:30 to the second, use keepchans = {[1:10], [20:30]}. % To only keeps channels 1:5 in the first set, use % keepchans = {1:5}. {default: {}} % % Outputs: % % subsets - {1,N} or {1,N+1} cell array containing channel indices for each % requested channel subset. % subidx - (1, EEG.nbchans) vector giving the index of the subset associated % with each channel. % pos - (3,N) matrix, columns containing the cartesian (x,y,z) channel % positions plotted. % Example: % % % Create three sub-montages of a 256-channel montage containing 32, 60, and 100 % % channels respectively.The 64 remaining channels will be put into a fourth subset. % % Also visualize time course of optimization and the channel subset head locations. % % >> subset = loc_subsets(EEG.chanlocs, [32 60 100], true, true); % % Author: Nima Bigdely Shamlo, SCCN/INC/UCSD, 2007 % Copyright (C) 2007 Nima Bigdely Shamlo, 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 % if plotOptimization|plotSubsets in line 130 removed by nima 3/6/2007 % line 133, removed num2str removed by nima 3/6/2007 function [subset idx pos] = loc_subsets(chanlocs, numberOfChannelsInSubset, plotOptimization, plotSubsets, mandatoryChannelsForSet); if sum(numberOfChannelsInSubset)> length(chanlocs) error('Total channels in requested subsets larger than number of EEG channels.'); end; if min(numberOfChannelsInSubset) < 2 error('Number of channels in the requested subsets must be >= 2.'); end; rand('state',0); if nargin < 5 mandatoryChannelsForSet = {}; end; if nargin < 4 plotSubsets = false; end; if nargin < 3 plotOptimization = false; end; pos=[cell2mat({chanlocs.X}); cell2mat({chanlocs.Y}); cell2mat({chanlocs.Z});]; dist = squareform(pdist(pos')); nChans = length(chanlocs); idx = ones(nChans,1); setId = cell(1, length(numberOfChannelsInSubset)); % cell array containing channels in each set remainingChannels = 1:nChans; % channles that are to be assigned to subsets % channels that have to stay in their original subset (as in % mandatoryChannelsForSet) and should not be re-assigned allMandatoryChannels = cell2mat(mandatoryChannelsForSet); % assign requested mandatory channels to subset for i=1:length(mandatoryChannelsForSet) setId{i} = mandatoryChannelsForSet{i}; remainingChannels(mandatoryChannelsForSet{i}) = NaN; % flag with Nan so they can be deleted later, this is to keep indexing simple end; remainingChannels(isnan(remainingChannels)) = []; r = remainingChannels(randperm(length(remainingChannels))); % randomly assign remaining channels to subsets for i=1:length(numberOfChannelsInSubset) numberOfChannelsTobeAddedToSubset = numberOfChannelsInSubset(i) - length(setId{i}) setId{i} = [setId{i} r(1:numberOfChannelsTobeAddedToSubset)]; r(1:numberOfChannelsTobeAddedToSubset) = []; end; if length(r) > 0 setId{length(numberOfChannelsInSubset) + 1} = r; % last set gets remaining channels end; if plotOptimization|plotSubsets fprintf(['Creating total of ' num2str(length(setId)) ' channel subsets:\n']); end if plotOptimization figure; xp = floor(sqrt(length(setId))); yp = ceil(length(setId)/xp); end; counter = 1; exchangeHappened = true; while exchangeHappened exchangeHappened = false; for set1 = 1:length(setId) for set2 = (set1 + 1):length(setId) for i = 1:length(setId{set1}) for j = 1:length(setId{set2}) chan(1) = setId{set1}(i); chan(2) = setId{set2}(j); if cost_of_exchanging_channels(chan,[set1 set2], setId, dist) < 0 & ~ismember(chan, allMandatoryChannels) setId{set1}(find(setId{set1} == chan(1))) = chan(2); setId{set2}(find(setId{set2} == chan(2))) = chan(1); sumDistances(counter) = 0; for s = 1:length(setId) sumDistances(counter) = sumDistances(counter) ... + (sum(sum(dist(setId{s},setId{s}))) / length(setId{s})); end; if plotOptimization plot(1:counter,sumDistances,'-b'); xlabel('number of exchanges'); ylabel('sum mean distances within each channel subset'); drawnow; else if mod(counter, 20) ==0 fprintf('number of exchanges = %d\nsum of mean distances = %g\n',... counter, sumDistances(counter)); end; end counter = counter + 1; exchangeHappened = true; end; end; end; end; end; end; for set = 1:length(setId) idx(setId{set}) = set; % legendTitle{set} = ['subset ' num2str(set)]; end; subset = setId; if plotSubsets FIG_OFFSET = 40; fpos = get(gcf,'position'); figure('position',[fpos(1)+FIG_OFFSET,fpos(2)-FIG_OFFSET,fpos(3),fpos(4)]); scatter3(pos(1,:), pos(2,:), pos(3,:),100,idx,'fill'); axis equal; %legend(legendTitle); it does not work propr th=title('Channel Subsets'); %set(th,'fontsize',14) end; if length(r)>0 & (plotOptimization|plotSubsets) fprintf('The last subset returned contains the %d unused channels.\n',... length(r)); end function cost = cost_of_exchanging_channels(chan, betweenSets, setId, dist); mirrorChan(1) = 2; mirrorChan(2) = 1; for i=1:2 newSetId{betweenSets(i)} = setId{betweenSets(i)}; newSetId{betweenSets(i)}(find(newSetId{betweenSets(i)} == chan(i))) = chan(mirrorChan(i)); end; cost = 0; for i=betweenSets distSumBefore{i} = sum(sum(dist(setId{i},setId{i}))); distSumAfter{i} = sum(sum(dist(newSetId{i},newSetId{i}))); cost = cost + (distSumBefore{i} - distSumAfter{i}) / length(setId{i}); end; %cost = (distSumAfter{1} > distSumBefore{1}) && (distSumAfter{2} > distSumBefore{2});
github
lcnbeapp/beapp-master
pcexpand.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/pcexpand.m
2,209
utf_8
2e520d826d0abe34ee1356fd8766e594
% pcexpand() - expand data using Principal Component Analysis (PCA) % returns data expanded from a principal component subspace % [compare pcsquash()] % Usage: % After >> [eigenvectors,eigenvalues,projections] = pcsquash(data,ncomps); % then >> [expanded_data] = pcexpand(projections,eigenvectors,mean(data')); % % Inputs: % projections = (comps,frames) each row is a component, each column a time point % eigenvectors = square matrix of (column) eigenvectors % datameans = vector of original data channel means % % Outputs: % projections = data projected back into the original data space % size (chans=eigenvector_rows,frames) % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000 % % See also: pcsquash(), svd() % Copyright (C) 6-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 % 4-15-98 debugged -sm & t-pj % 01-25-02 reformated help & license, added links -ad function [expanded_data]=pcexpand(PCAproj,EigenVectors,Datameans) if nargin < 2 help pcexpand return; end [ncomps,frames]=size(PCAproj); [j,k]=size(EigenVectors); if j ~= k error('Wrong array input size (eigenvectors matrix not square'); end if j < ncomps error('Wrong array input size (eigenvectors rows must be equal to projection matrix rows'); end if size(Datameans,1) == 1, Datameans = Datameans'; % make a column vector end expanded_data = EigenVectors(:,1:ncomps)*PCAproj + Datameans*ones(1,frames);
github
lcnbeapp/beapp-master
detectmalware.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/detectmalware.m
1,726
utf_8
805aa37c62f2d84ecb6d36df2499d684
% this function detects potential malware in the current folder and subfolders % % Author: A. Delorme, Cotober 2013 function detectmalware(currentFolder); if nargin < 1 currentFolder = pwd; end; folderContent = dir(currentFolder); folderContent = { folderContent.name }; malwareStrings = { 'eval(' 'evalin(' 'evalc(' 'delete(' 'movefile(' 'rmdir' 'mkdir' 'copyfile' 'system(' '!' }; for iFile = 1:length(folderContent) currentFile = folderContent{iFile}; if length(currentFile) > 2 && strcmpi(currentFile(end-1:end), '.m') fid = fopen(fullfile(currentFolder, currentFile), 'r'); countLine = 0; prevstr = ''; while ~feof(fid) str = fgetl(fid); countLine = countLine+1; if length(str) > 1 && str(1) ~= '%' res = cellfun(@(x)~isempty(findstr(x, str)), malwareStrings(1:end-1)); if str(1) == '!', res(end+1) = 1; end; if any(res) pos = find(res); pos = pos(1); disp('************************************') fprintf('Potential malware command detected containing "%s" in\n %s line %d\n', malwareStrings{pos}, fullfile(currentFolder, currentFile), countLine); fprintf('%d: %s\n%d: %s\n%d: %s\n', countLine-1, prevstr, countLine, str, countLine+1, fgetl(fid)); countLine = countLine+1; end; end; prevstr = str; end; fclose(fid); elseif exist(currentFile) == 7 && ~strcmpi(currentFile, '..') && ~strcmpi(currentFile, '.') detectmalware(fullfile(currentFolder, currentFile)); end; end;
github
lcnbeapp/beapp-master
loadelec.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/loadelec.m
2,360
utf_8
655d4fbe32be8c99d9d4a2f4deb754a6
% loadelec() - Load electrode names file for eegplot() % % Usage: >> labelmatrix = loadelec('elec_file'); % % 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 = loadelec(channamefile) MAXCHANS = 256; chans = MAXCHANS; errorcode = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Read the channel names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if channamefile ~= 0 & channamefile ~= '0' % read file of channel names chid = fopen(channamefile,'r'); if chid <3, fprintf('cannot open file %s.\n',channamefile); errorcode=2; channamefile = 0; else fprintf('Channamefile %s opened\n',channamefile); end; if errorcode==0, channames = fscanf(chid,'%s',[6 MAXCHANS]); channames = channames'; [r c] = size(channames); for i=1:r for j=1:c if channames(i,j)=='.', channames(i,j)=' '; 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 | 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
github
lcnbeapp/beapp-master
erpregout.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/erpregout.m
3,083
utf_8
a7430431f9ce614aaa04b826032bfcd5
% erpregout() - regress out the ERP from the data % % Usage: % newdata = erpregout(data); % [newdata erp factors] = erpregout(data, tlim, reglim); % % Inputs: % data - [float] 2-D data (times x trials) or 3-D data % (channels x times x trials). % % Optional inputs: % tlim - [min max] time limits in ms. % reglim - [min max] regression time window in ms (by default % the whole time period is used % Outputs: % newdata - data with ERP regressed out % erp - data ERP % factors - factors used for regressing out the ERP (size is the same % as the number of trials or (channels x trials) % % Note: it is better to regress out the ERP about 4 times (launch the % function 4 times in a row) to really be able to regress out the % ERP and have a residual ERP close to 0. % % 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 [data, erp, factors] = erpregout(data, tlim, reglim); if nargin < 1 help erpregout; return; end; if nargin < 2 tlim = [0 1]; end; if nargin < 3 reglim = tlim; end; if ndims(data) == 2 data = reshape(data, 1, size(data,1), size(data,2)); redim = 1; else redim = 0; end; % find closest points % ------------------- timevect = linspace(tlim(1), tlim(2), size(data,2)); [tmp begpoint] = min( abs(timevect-reglim(1)) ); [tmp endpoint] = min( abs(timevect-reglim(2)) ); erp = mean(data, 3); % regressing out erp in channels and trials % ----------------------------------------- for chan = 1:size(data,1) fprintf('Channel %d (trials out of %d):', chan, size(data,3)); for trial = 1:size(data,3) if ~mod(trial, 10) , fprintf('%d ', trial); end; if ~mod(trial, 200), fprintf('\n', trial); end; [factors(chan, trial) tmpf exitflag] = fminbnd('erpregoutfunc', 0, 10, [], ... data(chan, begpoint:endpoint, trial), erp(chan, begpoint:endpoint)); data(chan,:,trial) = data(chan,:,trial) - factors(chan, trial)*erp(chan, :); end; fprintf('\n'); end; if redim data = squeeze(data); end;
github
lcnbeapp/beapp-master
compdsp.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/compdsp.m
7,154
utf_8
d81cd429eda825751f36ef7706ea02bc
% compdsp() - Display standard info figures for a data decomposition % Creates four figure windows showing: Component amplitudes, % scalp maps, activations and activation spectra. % Usage: % >> compdsp(data,weights,locfile,[srate],[title],[compnums],[amps],[act]); % % Inputs: % data = data matrix used to train the decomposition % weights = the unmixing matrix (e.g., weights*sphere from runica()) % % Optional: % locfile = 2-d electrode locations file (as in >> topoplot example) % {default|[]: default locations file given in icadefs.m % srate = sampling rate in Hz {default|[]: as in icadefs.m} % title = optional figure title text % {default|'': none} % compnums = optional vector of component numbers to display % {default|[] -> all} % amps = all component amplitudes (from runica()) % {default|[]->recompute} % act = activations matrix (from runica()) % {default|[]->recompute} % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000 % Copyright (C) 12/16/00 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 % 02-01-01 replaced std() with rms() -sm % 02-10-01 made srate optional -sm % 01-25-02 reformated help & license -ad function compdsp(data,unmix,locfile,srate,titl,compnums,amps,act) minHz = 2; % frequency display limits maxHz = 40; ACTS_PER_EEGPLOT = 32; % %%%%%%%%%%%%%%%%%%%%%% Read and test arguments %%%%%%%%%%%%%%%%%%%%%%%% % icadefs % read BACKCOLOR, DEFAULT_SRATE if nargin<2 help compdsp return end chans = size(data,1); frames = size(data,2); ncomps = size(unmix,1); if ncomps < 1 error('Unmixing matrix must have at least one component'); end if chans < 2 error('Data must have at least two channels'); end if frames < 2 error('Data must have at least two frames'); end if size(unmix,2) ~= chans error('Sizes of unmix and data do not match'); end if nargin<3 locfile=[]; end if isempty(locfile) locfile = DEFAULT_ELOC; % from icsdefs.m end if ~exist(locfile) error('Cannot find electrode locations file'); end if nargin<4 srate = 0; % from icadefs end if isempty(srate) | srate==0 srate = DEFAULT_SRATE; % from icadefs end if nargin<5 titl = ''; % default - no title text end if isempty(titl) titl = ''; end if nargin<6 compnums = 0; % default - all components end if isempty(compnums) compnums = 0; end if nargin<7 amps = NaN; % default - recompute amps end if isempty(amps) amps = NaN; end if ~isnan(amps) & length(amps) ~= ncomps error('Supplied amps does not match the number of unmixed components'); end if compnums(1) == 0 compnums = 1:ncomps; end if min(compnums) < 1 error('Compnums must be positive'); end if min(compnums) > ncomps error('Some compnum > number of components in unmix'); end if nargin<8 act = NaN; % default - recompute act end % %%%%%%%%%%%%%%%%%%%%%%%%%%% Create plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if chans == ncomps winv = inv(unmix); elseif chans < ncomps error('More components than channels?'); else winv = pinv(unmix); end if isnan(act) fprintf('Computing activations ...') act = unmix(compnums,:)*data; fprintf('\n'); elseif size(act,2) ~= frames error('Supplied activations do not match data length'); elseif size(act,1) ~= ncomps & size(act,1) ~= length(compnums) error('Number of supplied activations matrix does not match data or weights'); elseif size(act,1) == ncomps act = act(compnums,:); % cut down matrix to desired components end % %%%%%%%%%%%%%%%%%%%%% I. Plot component amps %%%%%%%%%%%%%%%%%%%%%%%%%%% % pos = [40,520,550,400]; figure('Position',pos); if isnan(amps) fprintf('Computing component rms amplitudes '); amps = zeros(1,length(compnums)); for j=1:length(compnums) amps(j) = rms(winv(:,compnums(j)))*rms(act(j,:)'); fprintf('.') end fprintf('\n'); else amps = amps(compnums); % truncate passed amps to desired compnums end plot(compnums,amps,'k'); hold on plot(compnums,amps,'r^'); xl=xlabel('Component numbers'); yl=ylabel('RMS Amplitudes'); tl=title([titl ' Amplitudes']); ax = axis; axis([min(compnums)-1 max(compnums)+1 0 ax(4)]); % %%%%%%%%%%%%%%%%%%%%%%%%% II. Plot component maps %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pos = [40,40,550,400]; figure('Position',pos); fprintf('Plotting component scalp maps ...') % compmaps() may make multiple figures compmap(winv,locfile,compnums,[titl ' Scalp Maps'],0,compnums); fprintf('\n'); % %%%%%%%%%%%%%%%%%%%%%% III. eegplot() activations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if frames/srate < 10 dispsecs = ceil(frames/srate); else dispsecs = 10; % defaults - display 10s data per screen end range = 0.8*max(max(act')-min(act')); stact=1; lact=ACTS_PER_EEGPLOT; if lact>size(act,1) lact = size(act,1); end pos = [620,520,550,400]; figure('Position',pos); while stact <= size(act,1) % eegplot(data,srate,spacing,eloc_file,windowlength,title,posn) eegplot(act(stact:lact,:),srate,range,compnums(stact:lact),... dispsecs,[titl ' Activations'],pos); pos = pos + [.02 .02 0 0]; stact = stact+ACTS_PER_EEGPLOT; lact = lact +ACTS_PER_EEGPLOT; if lact>size(act,1) lact = size(act,1); end end % %%%%%%%%%%%%%%%%%%%%%%% IV. plotdata() spectra %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pos = [620,40,550,400]; figure('Position',pos); if frames > 2048 windw = 512; elseif frames > 1024 windw = 256; else windw = 128; end fprintf('Computing component spectra ') for j = 1:length(compnums) % [Pxx,F] = PSD(X,NFFT,Fs,WINDOW,NOVERLAP) [spec,freqs] = psd(act(j,:),1024,srate,windw,ceil(windw*0.5)); if ~exist('specs') specs = zeros(length(compnums),length(freqs)); end specs(j,:) = spec'; fprintf('.') end fprintf('\n'); specs = 10*log10(specs); tmp = ceil(sqrt(length(compnums))); tmp2 = ceil(length(compnums)/tmp); for j=1:length(compnums) sbplot(tmp2,tmp,j) plot(freqs,specs(j,:)) set(gca,'box','off') set(gca,'color',BACKCOLOR); ax=axis; axis([minHz,maxHz,ax(3),ax(4)]); tl = title(int2str(compnums(j))); end xl=xlabel('Frequency (Hz)'); yl=ylabel('Power (dB)'); set(gca,'YAxisLocation','right'); txl=textsc([titl ' Activation Spectra'],'title'); axcopy % pop-up axes on mouse click % plottopo(specs,[tmp2 tmp],0,[2,70 min(min(specs)) max(max(specs))],... % [titl ' Activation Power Spectra']); function rmsval = rms(column) rmsval = sqrt(mean(column.*column)); % don't remove mean
github
lcnbeapp/beapp-master
perminv.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/perminv.m
1,386
utf_8
d5fe91da3ab79a692c0adbd6b4a9498a
% perminv() - returns the inverse permutation vector % % Usage: >> [invvec] = perminverse(vector); % % Author: Scott Makeig, 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 % 4-4-97 shortened name to perminv() -sm % 4-7-97 allowed row vector, added tests -sm % 01-25-02 reformated help & license -ad function [invvec]=perminv(vector) [n,c] = size(vector); if n>1 & c>1, fprintf('perminv(): input must be a vector.\n'); return end transpose=0; if c>1 vector = vector'; transpose =1; end invvec = zeros(size(vector)); for i=1:length(vector) invvec(vector(i)) = i; end; if transpose==1, invvec = invvec'; end
github
lcnbeapp/beapp-master
runicatest.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/runicatest.m
40,794
utf_8
39e884850dab339c9c4e2a052d4cf934
% runicatest() - Perform Independent Component Analysis (ICA) decomposition % using natural-gradient infomax - the infomax ICA algorithm of % Bell & Sejnowski (1995) with the natural gradient method % of Amari, Cichocki & Yang, the extended-ICA algorithm % of Lee, Girolami & Sejnowski, PCA dimension reduction, % and/or specgram() preprocessing (suggested by M. Zibulevsky). % Usage: % >> [weights,sphere] = runica(data); % >> [weights,sphere,activations,bias,signs,lrates] ... % = runica(data,'Key1',Value1',...); % Input: % data = input data (chans,frames*epochs). % Note that if data consists of multiple discontinuous epochs, % each epoch should be separately baseline-zero'd using % >> data = rmbase(data,frames,basevector); % % Optional keywords: % 'ncomps' = [N] number of ICA components to compute (default -> chans) % using rectangular ICA decomposition % 'pca' = [N] decompose a principal component (default -> 0=off) % subspace of the data. Value is the number of PCs to retain. % 'sphering' = ['on'/'off'] flag sphering of data (default -> 'on') % 'weights' = [W] initial weight matrix (default -> eye()) % (Note: if 'sphering' 'off', default -> spher()) % 'lrate' = [rate] initial ICA learning rate (<< 1) (default -> heuristic) % 'block' = [N] ICA block size (<< datalength) (default -> heuristic) % 'anneal' = annealing constant (0,1] (defaults -> 0.90, or 0.98, extended) % controls speed of convergence % 'annealdeg' = [N] degrees weight change for annealing (default -> 70) % 'stop' = [f] stop training when weight-change < this (default -> 1e-6) % 'maxsteps' = [N] max number of ICA training steps (default -> 512) % 'bias' = ['on'/'off'] perform bias adjustment (default -> 'on') % 'momentum' = [0<f<1] training momentum (default -> 0) % 'extended' = [N] perform tanh() "extended-ICA" with sign estimation % every N training blocks. If N > 0, automatically estimate the % number of sub-Gaussian sources. If N < 0, fix number of sub-Gaussian % components to -N [faster than N>0] (default|0 -> off) % 'specgram' = [srate loHz hiHz frames winframes] decompose a complex time/frequency % transform of the data (Note: winframes must divide frames) % (defaults [srate 0 srate/2 size(data,2) size(data,2)]) % 'posact' = make all component activations net-positive(default 'on'} % 'verbose' = give ascii messages ('on'/'off') (default -> 'on') % % Outputs: [RO: output in reverse order of projected mean variance % unless starting weight matrix passed ('weights' above)] % weights = ICA weight matrix (comps,chans) [RO] % sphere = data sphering matrix (chans,chans) = spher(data) % Note that unmixing_matrix = weights*sphere {sphering off -> eye(chans)} % activations = activation time courses of the output components (ncomps,frames*epochs) % bias = vector of final (ncomps) online bias [RO] (default = zeros()) % signs = extended-ICA signs for components [RO] (default = ones()) % [ -1 = sub-Gaussian; 1 = super-Gaussian] % lrates = vector of learning rates used at each training step % % Authors: Scott Makeig with contributions from Tony Bell, Te-Won Lee, % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky, CNL/The Salk Institute, % La Jolla, 1996- % Uses: posact() % Reference (please cite): % % Makeig, S., Bell, A.J., Jung, T-P and Sejnowski, T.J., % "Independent component analysis of electroencephalographic data," % In: D. Touretzky, M. Mozer and M. Hasselmo (Eds). Advances in Neural % Information Processing Systems 8:145-151, MIT Press, Cambridge, MA (1996). % % Toolbox Citation: % % Makeig, Scott et al. "EEGLAB: Matlab ICA Toolbox for Psychophysiological Research". % WWW Site, Swartz Center for Computational Neuroscience, Institute of Neural % Computation, University of San Diego California % <www.sccn.ucsd.edu/eeglab/>, 2000. [World Wide Web Publication]. % % For more information: % http://www.sccn.ucsd.edu/eeglab/icafaq.html - FAQ on ICA/EEG % http://www.sccn.ucsd.edu/eeglab/icabib.html - mss. on ICA & biosignals % http://www.cnl.salk.edu/~tony/ica.html - math. mss. on ICA % Copyright (C) 1996 Scott Makeig et al, 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 %%%%%%%%%%%%%%%%%%%%%%%%%%% Edit history %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % runica() - by Scott Makeig with contributions from Tony Bell, Te-Won Lee % Tzyy-Ping Jung, Sigurd Enghoff, Michael Zibulevsky et al. % CNL / Salk Institute 1996-00 % 04-30-96 built from icatest.m and ~jung/.../wtwpwica.m -sm % 07-28-97 new runica(), adds bias (default on), momentum (default off), % extended-ICA (Lee & Sejnowski, 1997), cumulative angledelta % (until lrate drops), keywords, signcount for speeding extended-ICA % 10-07-97 put acos() outside verbose loop; verbose 'off' wasn't stopping -sm % 11-11-97 adjusted help msg -sm % 11-30-97 return eye(chans) if sphering 'off' or 'none' (undocumented option) -sm % 02-27-98 use pinv() instead of inv() to rank order comps if ncomps < chans -sm % 04-28-98 added 'posact' and 'pca' flags -sm % 07-16-98 reduced length of randperm() for kurtosis subset calc. -se & sm % 07-19-98 fixed typo in weights def. above -tl & sm % 12-21-99 added 'specgram' option suggested by Michael Zibulevsky, UNM -sm % 12-22-99 fixed rand() sizing inefficiency on suggestion of Mike Spratling, UK -sm % 01-11-00 fixed rand() sizing bug on suggestion of Jack Foucher, Strasbourg -sm % 12-18-00 test for existence of Sig Proc Tlbx function 'specgram'; improve % 'specgram' option arguments -sm % 01-25-02 reformated help & license -ad % 01-25-02 lowered default lrate and block -ad % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [weights,sphere,activations,bias,signs,lrates,y] = runica(data,p1,v1,p2,v2,p3,v3,p4,v4,p5,v5,p6,v6,p7,v7,p8,v8,p9,v9,p10,v10,p11,v11,p12,v12,p13,v13,p14,v14) if nargin < 1 help runica return end if ndims(data) > 2 data = data(:,:); % make data two-dimensional elseif ndims(data) < 2 help runica return end [chans frames] = size(data); % determine the data size urchans = chans; % remember original data channels datalength = frames; if chans<2 fprintf('\nrunica() - data size (%d,%d) too small.\n\n', chans,frames); return end % %%%%%%%%%%%%%%%%%%%%%% Declare defaults used below %%%%%%%%%%%%%%%%%%%%%%%% % MAX_WEIGHT = 1e8; % guess that weights larger than this have blown up DEFAULT_STOP = 0.000001; % stop training if weight changes below this DEFAULT_ANNEALDEG = 60; % when angle change reaches this value, DEFAULT_ANNEALSTEP = 0.90; % anneal by multiplying lrate by this DEFAULT_EXTANNEAL = 0.98; % or this if extended-ICA DEFAULT_MAXSTEPS = 512; % ]top training after this many steps DEFAULT_MOMENTUM = 0.0; % default momentum weight DEFAULT_BLOWUP = 1000000000.0; % = learning rate has 'blown up' DEFAULT_BLOWUP_FAC = 0.8; % when lrate 'blows up,' anneal by this fac DEFAULT_RESTART_FAC = 0.9; % if weights blowup, restart with lrate % lower by this factor MIN_LRATE = 0.000001; % if weight blowups make lrate < this, quit MAX_LRATE = 0.1; % guard against uselessly high learning rate DEFAULT_LRATE = 0.00065/log(chans); % heuristic default - may need adjustment % for large or tiny data sets! % DEFAULT_BLOCK = floor(sqrt(frames/4)); % heuristic default DEFAULT_BLOCK = min(floor(5*log(frames)),0.3*frames); % heuristic % - may need adjustment! % Extended-ICA option: DEFAULT_EXTENDED = 0; % default off DEFAULT_EXTBLOCKS = 1; % number of blocks per kurtosis calculation DEFAULT_NSUB = 1; % initial default number of assumed sub-Gaussians % for extended-ICA DEFAULT_EXTMOMENTUM = 0.5; % momentum term for computing extended-ICA kurtosis MAX_KURTSIZE = 6000; % max points to use in kurtosis calculation MIN_KURTSIZE = 2000; % minimum good kurtosis size (flag warning) SIGNCOUNT_THRESHOLD = 25; % raise extblocks when sign vector unchanged % after this many steps SIGNCOUNT_STEP = 2; % extblocks increment factor DEFAULT_SPHEREFLAG = 'on'; % use the sphere matrix as the default % starting weight matrix DEFAULT_PCAFLAG = 'off'; % don't use PCA reduction DEFAULT_POSACTFLAG = 'on'; % use posact() DEFAULT_VERBOSE = 1; % write ascii info to calling screen DEFAULT_BIASFLAG = 1; % default to using bias in the ICA update rule % %%%%%%%%%%%%%%%%%%%%%%% Set up keyword default values %%%%%%%%%%%%%%%%%%%%%%%%% % if nargout < 2, fprintf('runica() - needs at least two output arguments.\n'); return end epochs = 1; % do not care how many epochs in data pcaflag = DEFAULT_PCAFLAG; sphering = DEFAULT_SPHEREFLAG; % default flags posactflag = DEFAULT_POSACTFLAG; verbose = DEFAULT_VERBOSE; block = DEFAULT_BLOCK; % heuristic default - may need adjustment! lrate = DEFAULT_LRATE; annealdeg = DEFAULT_ANNEALDEG; annealstep = 0; % defaults declared below nochange = DEFAULT_STOP; momentum = DEFAULT_MOMENTUM; maxsteps = DEFAULT_MAXSTEPS; weights = 0; % defaults defined below ncomps = chans; biasflag = DEFAULT_BIASFLAG; extended = DEFAULT_EXTENDED; extblocks = DEFAULT_EXTBLOCKS; kurtsize = MAX_KURTSIZE; signsbias = 0.02; % bias towards super-Gaussian components extmomentum= DEFAULT_EXTMOMENTUM; % exp. average the kurtosis estimates nsub = DEFAULT_NSUB; wts_blowup = 0; % flag =1 when weights too large wts_passed = 0; % flag weights passed as argument % %%%%%%%%%% Collect keywords and values from argument list %%%%%%%%%%%%%%% % if (nargin> 1 & rem(nargin,2) == 0) fprintf('runica(): Even number of input arguments???') return end for i = 3:2:nargin % for each Keyword Keyword = eval(['p',int2str((i-3)/2 +1)]); Value = eval(['v',int2str((i-3)/2 +1)]); if ~isstr(Keyword) fprintf('runica(): keywords must be strings') return end Keyword = lower(Keyword); % convert upper or mixed case to lower if strcmp(Keyword,'weights') | strcmp(Keyword,'weight') if isstr(Value) fprintf(... 'runica(): weights value must be a weight matrix or sphere') return else weights = Value; wts_passed =1; end elseif strcmp(Keyword,'ncomps') if isstr(Value) fprintf('runica(): ncomps value must be an integer') return end if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end ncomps = Value; if ~ncomps, ncomps = chans; end elseif strcmp(Keyword,'pca') if ncomps < urchans & ncomps ~= Value fprintf('runica(): Use either PCA or ICA dimension reduction'); return end if isstr(Value) fprintf(... 'runica(): pca value should be the number of principal components to retain') return end pcaflag = 'on'; ncomps = Value; if ncomps >= chans | ncomps < 1, fprintf('runica(): pca value must be in range [1,%d]\n',chans-1) return end chans = ncomps; elseif strcmp(Keyword,'posact') if ~isstr(Value) fprintf('runica(): posact value must be on or off') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off'), fprintf('runica(): posact value must be on or off') return end posactflag = Value; end elseif strcmp(Keyword,'lrate') if isstr(Value) fprintf('runica(): lrate value must be a number') return end lrate = Value; if lrate>MAX_LRATE | lrate <0, fprintf('runica(): lrate value is out of bounds'); return end if ~lrate, lrate = DEFAULT_LRATE; end elseif strcmp(Keyword,'block') | strcmp(Keyword,'blocksize') if isstr(Value) fprintf('runica(): block size value must be a number') return end block = Value; if ~block, block = DEFAULT_BLOCK; end elseif strcmp(Keyword,'stop') | strcmp(Keyword,'nochange') ... | strcmp(Keyword,'stopping') if isstr(Value) fprintf('runica(): stop wchange value must be a number') return end nochange = Value; elseif strcmp(Keyword,'maxsteps') | strcmp(Keyword,'steps') if isstr(Value) fprintf('runica(): maxsteps value must be an integer') return end maxsteps = Value; if ~maxsteps, maxsteps = DEFAULT_MAXSTEPS; end if maxsteps < 0 fprintf('runica(): maxsteps value (%d) must be a positive integer',maxsteps) return end elseif strcmp(Keyword,'anneal') | strcmp(Keyword,'annealstep') if isstr(Value) fprintf('runica(): anneal step value (%2.4f) must be a number (0,1)',Value) return end annealstep = Value; if annealstep <=0 | annealstep > 1, fprintf('runica(): anneal step value (%2.4f) must be (0,1]',annealstep) return end elseif strcmp(Keyword,'annealdeg') | strcmp(Keyword,'degrees') if isstr(Value) fprintf('runica(): annealdeg value must be a number') return end annealdeg = Value; if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG; elseif annealdeg > 180 | annealdeg < 0 fprintf('runica(): annealdeg (%3.1f) is out of bounds [0,180]',... annealdeg); return end elseif strcmp(Keyword,'momentum') if isstr(Value) fprintf('runica(): momentum value must be a number') return end momentum = Value; if momentum > 1.0 | momentum < 0 fprintf('runica(): momentum value is out of bounds [0,1]') return end elseif strcmp(Keyword,'sphering') | strcmp(Keyword,'sphereing') ... | strcmp(Keyword,'sphere') if ~isstr(Value) fprintf('runica(): sphering value must be on, off, or none') return else Value = lower(Value); if ~strcmp(Value,'on') & ~strcmp(Value,'off') & ~strcmp(Value,'none'), fprintf('runica(): sphering value must be on or off') return end sphering = Value; end elseif strcmp(Keyword,'bias') if ~isstr(Value) fprintf('runica(): bias value must be on or off') return else Value = lower(Value); if strcmp(Value,'on') biasflag = 1; elseif strcmp(Value,'off'), biasflag = 0; else fprintf('runica(): bias value must be on or off') return end end elseif strcmp(Keyword,'specgram') | strcmp(Keyword,'spec') if ~exist('specgram') < 2 % if ~exist or defined workspace variable fprintf(... 'runica(): MATLAB Sig. Proc. Toolbox function "specgram" not found.\n') return end if isstr(Value) fprintf('runica(): specgram argument must be a vector') return end srate = Value(1); if (srate < 0) fprintf('runica(): specgram srate (%4.1f) must be >=0',srate) return end if length(Value)>1 loHz = Value(2); if (loHz < 0 | loHz > srate/2) fprintf('runica(): specgram loHz must be >=0 and <= srate/2 (%4.1f)',srate/2) return end else loHz = 0; % default end if length(Value)>2 hiHz = Value(3); if (hiHz < loHz | hiHz > srate/2) fprintf('runica(): specgram hiHz must be >=loHz (%4.1f) and <= srate/2 (%4.1f)',loHz,srate/2) return end else hiHz = srate/2; % default end if length(Value)>3 Hzframes = Value(5); if (Hzframes<0 | Hzframes > size(data,2)) fprintf('runica(): specgram frames must be >=0 and <= data length (%d)',size(data,2)) return end else Hzframes = size(data,2); % default end if length(Value)>4 Hzwinlen = Value(4); if rem(Hzframes,Hzwinlen) % if winlen doesn't divide frames fprintf('runica(): specgram Hzinc must divide frames (%d)',Hzframes) return end else Hzwinlen = Hzframes; % default end Specgramflag = 1; % set flag to perform specgram() elseif strcmp(Keyword,'extended') | strcmp(Keyword,'extend') if isstr(Value) fprintf('runica(): extended value must be an integer (+/-)') return else extended = 1; % turn on extended-ICA extblocks = fix(Value); % number of blocks per kurt() compute if extblocks < 0 nsub = -1*fix(extblocks); % fix this many sub-Gauss comps elseif ~extblocks, extended = 0; % turn extended-ICA off elseif kurtsize>frames, % length of kurtosis calculation kurtsize = frames; if kurtsize < MIN_KURTSIZE fprintf(... 'runica() warning: kurtosis values inexact for << %d points.\n',... MIN_KURTSIZE); end end end elseif strcmp(Keyword,'verbose') if ~isstr(Value) fprintf('runica(): verbose flag value must be on or off') return elseif strcmp(Value,'on'), verbose = 1; elseif strcmp(Value,'off'), verbose = 0; else fprintf('runica(): verbose flag value must be on or off') return end else fprintf('runica(): unknown flag') return end end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize weights, etc. %%%%%%%%%%%%%%%%%%%%%%%% % if ~annealstep, if ~extended, annealstep = DEFAULT_ANNEALSTEP; % defaults defined above else annealstep = DEFAULT_EXTANNEAL; % defaults defined above end end % else use annealstep from commandline if ~annealdeg, annealdeg = DEFAULT_ANNEALDEG - momentum*90; % heuristic if annealdeg < 0, annealdeg = 0; end end if ncomps > chans | ncomps < 1 fprintf('runica(): number of components must be 1 to %d.\n',chans); return end if weights ~= 0, % initialize weights % starting weights are being passed to runica() from the commandline if verbose, fprintf('Using starting weight matrix named in argument list ...\n') end if chans>ncomps & weights ~=0, [r,c]=size(weights); if r~=ncomps | c~=chans, fprintf(... 'runica(): weight matrix must have %d rows, %d columns.\n', ... chans,ncomps); return; end end end; % %%%%%%%%%%%%%%%%%%%%% Check keyword values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if frames<chans, fprintf('runica(): data length (%d) < data channels (%d)!\n',frames,chans) return elseif block < 2, fprintf('runica(): block size %d too small!\n',block) return elseif block > frames, fprintf('runica(): block size exceeds data length!\n'); return elseif floor(epochs) ~= epochs, fprintf('runica(): data length is not a multiple of the epoch length!\n'); return elseif nsub > ncomps fprintf('runica(): there can be at most %d sub-Gaussian components!\n',ncomps); return end; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Process the data %%%%%%%%%%%%%%%%%%%%%%%%%% % if verbose, fprintf( ... '\nInput data size [%d,%d] = %d channels, %d frames.\n', ... chans,frames,chans,frames); if strcmp(pcaflag,'on') fprintf('After PCA dimension reduction,\n finding '); else fprintf('Finding '); end if ~extended fprintf('%d ICA components using logistic ICA.\n',ncomps); else % if extended fprintf('%d ICA components using extended ICA.\n',ncomps); if extblocks > 0 fprintf(... 'Kurtosis will be calculated initially every %d blocks using %d data points.\n',... extblocks, kurtsize); else fprintf(... 'Kurtosis will not be calculated. Exactly %d sub-Gaussian components assumed.\n',... nsub); end end fprintf('Initial learning rate will be %g, block size %d.\n',lrate,block); if momentum>0, fprintf('Momentum will be %g.\n',momentum); end fprintf( ... 'Learning rate will be multiplied by %g whenever angledelta >= %g deg.\n', ... annealstep,annealdeg); fprintf('Training will end when wchange < %g or after %d steps.\n', ... nochange,maxsteps); if biasflag, fprintf('Online bias adjustment will be used.\n'); else fprintf('Online bias adjustment will not be used.\n'); end end % %%%%%%%%%%%%%%%%%%%%%%%%% Remove overall row means %%%%%%%%%%%%%%%%%%%%%%%% % if verbose, fprintf('Removing mean of each channel ...\n'); end data = data - mean(data')'*ones(1,frames); % subtract row means if verbose, fprintf('Final training data range: %g to %g\n', ... min(min(data)),max(max(data))); end % %%%%%%%%%%%%%%%%%%% Perform PCA reduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') fprintf('Reducing the data to %d principal dimensions...\n',ncomps); [eigenvectors,eigenvalues,data] = pcsquash(data,ncomps); % make data its projection onto the ncomps-dim principal subspace end % %%%%%%%%%%%%%%%%%%% Perform specgram transformation %%%%%%%%%%%%%%%%%%%%%%% % if exist('Specgramflag') == 1 % [P F T] = SPECGRAM(A,NFFT,Fs,WINDOW,NOVERLAP) % MATLAB Sig Proc Toolbox % Hzwinlen = fix(srate/Hzinc); % CHANGED FROM THIS 12/18/00 -sm Hzfftlen = 2^(ceil(log(Hzwinlen)/log(2))); % make FFT length next higher 2^k Hzoverlap = 0; % use sequential windows % % Get freqs and times from 1st channel analysis % [tmp,freqs,tms] = specgram(data(1,:),Hzfftlen,srate,Hzwinlen,Hzoverlap); fs = find(freqs>=loHz & freqs <= hiHz); if isempty(fs) fprintf('runica(): specified frequency range too narrow!\n'); return end; specdata = reshape(tmp(fs,:),1,length(fs)*size(tmp,2)); specdata = [real(specdata) imag(specdata)]; % fprintf(' size(fs) = %d,%d\n',size(fs,1),size(fs,2)); % fprintf(' size(tmp) = %d,%d\n',size(tmp,1),size(tmp,2)); % % Loop through remaining channels % for ch=2:chans [tmp] = specgram(data(ch,:),Hzwinlen,srate,Hzwinlen,Hzoverlap); tmp = reshape((tmp(fs,:)),1,length(fs)*size(tmp,2)); specdata = [specdata;[real(tmp) imag(tmp)]]; % channels are rows end % % Print specgram confirmation and details % fprintf(... 'Converted data to %d channels by %d=2*%dx%d points spectrogram data.\n',... chans,2*length(fs)*length(tms),length(fs),length(tms)); if length(fs) > 1 fprintf(... ' Low Hz %g, high Hz %g, Hz incr %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),freqs(fs(2))-freqs(fs(1)),Hzwinlen); else fprintf(... ' Low Hz %g, high Hz %g, window length %d\n',freqs(fs(1)),freqs(fs(end)),Hzwinlen); end % % Replace data with specdata % data = specdata; datalength=size(data,2); end % %%%%%%%%%%%%%%%%%%% Perform sphering %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if strcmp(sphering,'on'), %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if verbose, fprintf('Computing the sphering matrix...\n'); end sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher() if ~weights, if verbose, fprintf('Starting weights are the identity matrix ...\n'); end weights = eye(ncomps,chans); % begin with the identity matrix else % weights given on commandline if verbose, fprintf('Using starting weights named on commandline ...\n'); end end if verbose, fprintf('Sphering the data ...\n'); end data = sphere*data; % actually decorrelate the electrode signals elseif strcmp(sphering,'off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~weights if verbose, fprintf('Using the sphering matrix as the starting weight matrix ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end sphere = 2.0*inv(sqrtm(cov(data'))); % find the "sphering" matrix = spher() weights = eye(ncomps,chans)*sphere; % begin with the identity matrix sphere = eye(chans); % return the identity matrix else % weights ~= 0 if verbose, fprintf('Using starting weights named on commandline ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end sphere = eye(chans); % return the identity matrix end elseif strcmp(sphering,'none') sphere = eye(chans); % return the identity matrix if ~weights if verbose, fprintf('Starting weights are the identity matrix ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end weights = eye(ncomps,chans); % begin with the identity matrix else % weights ~= 0 if verbose, fprintf('Using starting weights named on commandline ...\n'); fprintf('Returning the identity matrix in variable "sphere" ...\n'); end end sphere = eye(chans,chans); if verbose, fprintf('Returned variable "sphere" will be the identity matrix.\n'); end end % %%%%%%%%%%%%%%%%%%%%%%%% Initialize ICA training %%%%%%%%%%%%%%%%%%%%%%%%% % lastt=fix((datalength/block-1)*block+1); BI=block*eye(ncomps,ncomps); delta=zeros(1,chans*ncomps); changes = []; degconst = 180./pi; startweights = weights; prevweights = startweights; oldweights = startweights; prevwtchange = zeros(chans,ncomps); oldwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); onesrow = ones(1,block); bias = zeros(ncomps,1); signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end if extended & extblocks < 0 & verbose, fprintf('Fixed extended-ICA sign assignments: '); for k=1:ncomps fprintf('%d ',signs(k)); end; fprintf('\n'); end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; signcount = 0; % counter for same-signs signcounts = []; urextblocks = extblocks; % original value, for resets old_kk = zeros(1,ncomps); % for kurtosis momemtum % %%%%%%%% ICA training loop using the logistic sigmoid %%%%%%%%%%%%%%%%%%% % if verbose, fprintf('Beginning ICA training ...'); if extended, fprintf(' first training step may be slow ...\n'); else fprintf('\n'); end end step=0; laststep=0; blockno = 1; % running block counter for kurtosis interrupts while step < maxsteps, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % permute=randperm(datalength); % shuffle data order at each step bootstrap = round(datalength*rand(1,datalength)+0.5); % draw a new bootstrap dataset at each step for t=1:block:lastt, %%%%%%%%% ICA Training Block %%%%%%%%%%%%%%%%%%% pause(0); if ~isempty(get(0, 'currentfigure')) & strcmp(get(gcf, 'tag'), 'stop') close; error('USER ABORT'); end; if biasflag u=weights*data(:,bootstrap(t:t+block-1)) + bias*onesrow; else u=weights*data(:,bootstrap(t:t+block-1)); end if ~extended %%%%%%%%%%%%%%%%%%% Logistic ICA weight update %%%%%%%%%%%%%%%%%%% y=1./(1+exp(-u)); % weights=weights+lrate*(BI+(1-2*y)*u')*weights; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else % extended-ICA %%%%%%%%%%%%%%%%%%% Extended-ICA weight update %%%%%%%%%%%%%%%%%%% y=tanh(u); % weights = weights + lrate*(BI-signs*y*u'-u*u')*weights; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end if biasflag if ~extended %%%%%%%%%%%%%%%%%%%%%%%% Logistic ICA bias %%%%%%%%%%%%%%%%%%%%%%% bias = bias + lrate*sum((1-2*y)')'; % for logistic nonlin. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else % extended %%%%%%%%%%%%%%%%%%% Extended-ICA bias %%%%%%%%%%%%%%%%%%%%%%%%%%%% bias = bias + lrate*sum((-2*y)')'; % for tanh() nonlin. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end end if momentum > 0 %%%%%%%%% Add momentum %%%%%%%%%%%%%%%%%%%%%%%%%%%% weights = weights + momentum*prevwtchange; prevwtchange = weights-prevweights; prevweights = weights; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if max(max(abs(weights))) > MAX_WEIGHT wts_blowup = 1; change = nochange; end if extended & ~wts_blowup % %%%%%%%%%%% Extended-ICA kurtosis estimation %%%%%%%%%%%%%%%%%%%%% % if extblocks > 0 & rem(blockno,extblocks) == 0, % recompute signs vector using kurtosis if kurtsize < frames % 12-22-99 rand() size suggestion by M. Spratling rp = fix(rand(1,kurtsize)*datalength); % pick random subset % Accout for the possibility of a 0 generation by rand ou = find(rp == 0); while ~isempty(ou) % 1-11-00 suggestion by J. Foucher rp(ou) = fix(rand(1,length(ou))*datalength); ou = find(rp == 0); end partact=weights*data(:,rp(1:kurtsize)); else % for small data sets, partact=weights*data; % use whole data end m2=mean(partact'.^2).^2; m4= mean(partact'.^4); kk= (m4./m2)-3.0; % kurtosis estimates if extmomentum kk = extmomentum*old_kk + (1.0-extmomentum)*kk; % use momentum old_kk = kk; end signs=diag(sign(kk+signsbias)); % pick component signs if signs == oldsigns, signcount = signcount+1; else signcount = 0; end oldsigns = signs; signcounts = [signcounts signcount]; if signcount >= SIGNCOUNT_THRESHOLD, extblocks = fix(extblocks * SIGNCOUNT_STEP);% make kurt() estimation signcount = 0; % less frequent if sign end % is not changing end % extblocks > 0 & . . . end % if extended %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% blockno = blockno + 1; if wts_blowup break end end % training block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~wts_blowup oldwtchange = weights-oldweights; step=step+1; % %%%%%%% Compute and print weight and update angle changes %%%%%%%%% % lrates(1,step) = lrate; angledelta=0.; delta=reshape(oldwtchange,1,chans*ncomps); change=delta*delta'; end % %%%%%%%%%%%%%%%%%%%%%% Restart if weights blow up %%%%%%%%%%%%%%%%%%%% % if wts_blowup | isnan(change)|isinf(change), % if weights blow up, fprintf(''); step = 0; % start again change = nochange; wts_blowup = 0; % re-initialize variables blockno = 1; lrate = lrate*DEFAULT_RESTART_FAC; % with lower learning rate weights = startweights; % and original weight matrix oldweights = startweights; change = nochange; oldwtchange = zeros(chans,ncomps); delta=zeros(1,chans*ncomps); olddelta = delta; extblocks = urextblocks; prevweights = startweights; prevwtchange = zeros(chans,ncomps); lrates = zeros(1,maxsteps); bias = zeros(ncomps,1); if extended signs = ones(1,ncomps); % initialize signs to nsub -1, rest +1 for k=1:nsub signs(k) = -1; end signs = diag(signs); % make a diagonal matrix oldsigns = zeros(size(signs));; end if lrate> MIN_LRATE r = rank(data); if r<ncomps fprintf('Data has rank %d. Cannot compute %d components.\n',... r,ncomps); return else fprintf(... 'Lowering learning rate to %g and starting again.\n',lrate); end else fprintf( ... 'runica(): QUITTING - weight matrix may not be invertible!\n'); return; end else % if weights in bounds % %%%%%%%%%%%%% Print weight update information %%%%%%%%%%%%%%%%%%%%%% % if step> 2 angledelta=acos((delta*olddelta')/sqrt(change*oldchange)); end if verbose, if step > 2, if ~extended, fprintf(... 'step %d - lrate %5f, wchange %7.6f, angledelta %4.1f deg\n', ... step,lrate,change,degconst*angledelta); else fprintf(... 'step %d - lrate %5f, wchange %7.6f, angledelta %4.1f deg, %d subgauss\n',... step,lrate,change,degconst*angledelta,(ncomps-sum(diag(signs)))/2); end elseif ~extended fprintf(... 'step %d - lrate %5f, wchange %7.6f\n',step,lrate,change); else fprintf(... 'step %d - lrate %5f, wchange %7.6f, %d subgauss\n',... step,lrate,change,(ncomps-sum(diag(signs)))/2); end % step > 2 end; % if verbose % %%%%%%%%%%%%%%%%%%%% Save current values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % changes = [changes change]; oldweights = weights; % %%%%%%%%%%%%%%%%%%%% Anneal learning rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if degconst*angledelta > annealdeg, lrate = lrate*annealstep; % anneal learning rate olddelta = delta; % accumulate angledelta until oldchange = change; % annealdeg is reached elseif step == 1 % on first step only olddelta = delta; % initialize oldchange = change; end % %%%%%%%%%%%%%%%%%%%% Apply stopping rule %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if step >2 & change < nochange, % apply stopping rule laststep=step; step=maxsteps; % stop when weights stabilize elseif change > DEFAULT_BLOWUP, % if weights blow up, lrate=lrate*DEFAULT_BLOWUP_FAC; % keep trying end; % with a smaller learning rate end; % end if weights in bounds end; % end training %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~laststep laststep = step; end; lrates = lrates(1,1:laststep); % truncate lrate history vector % %%%%%%%%%%%%%% Orient components towards max positive activation %%%%%% % if strcmp(posactflag,'on') [activations,winvout,weights] = posact(data,weights); % changes signs of activations and weights to make activations % net rms-positive else activations = weights*data; end % %%%%%%%%%%%%%% If pcaflag, compose PCA and ICA matrices %%%%%%%%%%%%%%% % if strcmp(pcaflag,'on') fprintf('Composing the eigenvector, weights, and sphere matrices\n'); fprintf(' into a single rectangular weights matrix; sphere=eye(%d)\n'... ,chans); weights= weights*sphere*eigenvectors(:,1:ncomps)'; sphere = eye(urchans); end % %%%%%% Sort components in descending order of max projected variance %%%% % if verbose, fprintf(... 'Sorting components in descending order of mean projected variance ...\n'); end if wts_passed == 0 % %%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % meanvar = zeros(ncomps,1); % size of the projections if ncomps == urchans % if weights are square . . . winv = inv(weights*sphere); else fprintf('Using pseudo-inverse of weight matrix to rank order component projections.\n'); winv = pinv(weights*sphere); end for s=1:ncomps if verbose, fprintf('%d ',s); % construct single-component data matrix end % project to scalp, then add row means compproj = winv(:,s)*activations(s,:); meanvar(s) = mean(sum(compproj.*compproj)/(size(compproj,1)-1)); % compute mean variance end % at all scalp channels if verbose, fprintf('\n'); end % %%%%%%%%%%%%%% Sort components by mean variance %%%%%%%%%%%%%%%%%%%%%%%% % [sortvar, windex] = sort(meanvar); windex = windex(ncomps:-1:1); % order large to small meanvar = meanvar(windex); % %%%%%%%%%%%%%%%%%%%%% Filter data using final weights %%%%%%%%%%%%%%%%%% % if nargout>2, % if activations are to be returned if verbose, fprintf('Permuting the activation wave forms ...\n'); end activations = activations(windex,:); else clear activations end weights = weights(windex,:);% reorder the weight matrix bias = bias(windex); % reorder them signs = diag(signs); % vectorize the signs matrix signs = signs(windex); % reorder them else fprintf('Components not ordered by variance.\n'); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % return if nargout > 6 u=weights*data + bias*ones(1,frames); y = zeros(size(u)); for c=1:chans for f=1:frames y(c,f) = 1/(1+exp(-u(c,f))); end end end
github
lcnbeapp/beapp-master
headmovie.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/headmovie.m
8,690
utf_8
38629f7b7a3e0c3097687e8c0aaf3250
% ########## This function is deprecated. Use eegmovie instead. ########## % % headmovie() - Record a Matlab movie of scalp data. % Use seemovie() to display the movie. % % Usage: >> [Movie,Colormap] = headmovie(data,elec_loc,spline_file); % >> [Movie,Colormap,minc,maxc] = headmovie(data,elec_loc,spline_file,... % srate,title,camerapath,movieframes,minmax,startsec); % Inputs: % data = (chans,frames) EEG data set to plot % elec_loc = electrode locations file for eegplot {default 'chan.loc'} % spline_file = headplot() produced spline 'filename' {default 'chan.spline'} % srate = sampling rate in Hz {default|0 -> 256 Hz} % title = 'plot title' {default|0 -> none} % camerapath = [az_start az_step el_start el_step] {default [-127 0 30 0]} % Setting all four non-0 creates a spiral camera path % Partial entries allowed, e.g. [az_start] % Subsequent rows [movieframe az_step 0 el_step] adapt step % sizes allowing starts/stops, panning back and forth, etc. % movieframes = vector of data frames to animate {default|0 -> all} % minmax = Data [lower_bound, upper_bound] Lower->blue, upper->red % {default|0 -> +/-abs max of data} % startsec = starting time in seconds {default|0 -> 0.0} % % Note: BUG IN MATLAB 5.0-5.1 -- CANT SHOW MOVIES IN CORRECT COLORS % % Authors: Scott Makeig & Colin Humphries, SCCN/INC/UCSD, La Jolla, 2/1998 % % See also: seemovie(), eegmovie(), headplot() % Copyright (C) 2.6.98 Scott Makeig & Colin Humphries, 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 [Movie, Colormap, minc, maxc] = headmovie(data,eloc_file,spline_file,srate,titl,camerapath,movieframes,minmax,startsec,varargin) if nargin<1 help headmovie return end clf [chans,frames] = size(data); icadefs; % read DEFAULT_SRATE; if nargin<9 startsec = 0; end if nargin<8 minmax = 0; end if size(minmax)==[1 1] & minmax ~= 0 minmax = [-minmax minmax]; end if minmax ==0, minc = min(min(data)); maxc = max(max(data)); absmax = max([abs(minc), abs(maxc)]); fudge = 0.05*(maxc-minc); % allow for slight extrapolation minc = -absmax-fudge; maxc = absmax+fudge; minmax = [minc maxc]; end if nargin <7 movieframes = 0; end if nargin<6 camerapath = 0; end if movieframes == 0 movieframes = 1:frames; % default end if nargin <5 titl = ''; end if titl == 0 titl = ''; end if nargin <4 srate = 0; end if nargin <3 spline_file = 0; end if nargin <2 eloc_file = 0; end if movieframes(1) < 1 | movieframes(length(movieframes))>frames fprintf('headmovie(): specified movieframes not in data!\n'); return end if srate ==0, srate = DEFAULT_SRATE; end mframes = length(movieframes); fprintf('Making a movie of %d frames\n',mframes) Movie = moviein(mframes,gcf); if size(camerapath) == [1,1] if camerapath==0 camerapath = [-127 0 30 0]; fprintf('Using default view [-127 0 30 0].'); else camerapath = [camerapath 0 30 0]; end elseif size(camerapath,2) == 2 camerapath(1,:) = [camerapath(1,1) camerapath(1,2) 30 0] elseif size(camerapath,2) == 3 camerapath(1,:) = [camerapath(1,1) camerapath(1,2) camerapath(1,3) 0] elseif size(camerapath,2) > 4 help headmovie return end if size(camerapath,1) > 1 & size(camerapath,2)~=4 help headmovie return end azimuth = camerapath(1,1); % initial camerapath variables az_step = camerapath(1,2); elevation = camerapath(1,3); el_step = camerapath(1,4); if ~isstruct(eloc_file) && eloc_file(1) == 0 eloc_file = 'chan.angles'; end if spline_file(1) == 0 spline_file = 'chan.spline'; end figure(gcf); % bring figure to front clf % clear figure %%%%%%%%%%%%%%%%%%%%% eegplot() of data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% axeegplot = axes('Units','Normalized','Position',[.75 .05 .2 .9]); if isstruct(eloc_file) eegplotold('noui',-data,srate,0,[],startsec,'r'); %eegplotsold(-data,srate,[],' ',0,frames/srate,'r',startsec); %CJH else eegplotold('noui',-data,srate,0,eloc_file,startsec,'r'); %eegplotsold(-data,srate,eloc_file,' ',0,frames/srate,'r',startsec); %CJH end; set(axeegplot,'XTick',[]) %%CJH % plot negative up limits = get(axeegplot,'Ylim'); % list channel numbers only set(axeegplot,'GridLineStyle',':') set(axeegplot,'Xgrid','off') set(axeegplot,'Ygrid','on') axcolor = get(gcf,'Color'); %%%%%%%%%%%%%%%%%%%%%%% print title text %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% axtitle = axes('Units','Normalized','Position',[0 .9 .72 .1],'Color',axcolor); axes(axtitle) text(0.5,0.5,titl,'FontSize',16,'horizontalalignment','center') axis('off') %%%%%%%%%%%%%%%%%%%%%%% display colorbar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% axcolorbar = axes('Units','Normalized','Position',[.05 .05 .055 .18]); axes(axcolorbar) if exist('colorbar_tp')==2 h=colorbar_tp(axcolorbar); % Slightly altered Matlab colorbar() routine else h=colorbar(axcolorbar); % Note: there is a minor problem with this call. end % Write authors for further information. hkids=get(h,'children'); for k=1:1 delete(hkids(k)); end set(axcolorbar,'Ytick',[0 0.5 1.0],'Yticklabel',[' - ';' 0 ';' + '],'FontSize',16); axis('off') %%%%%%%%%%%%%%%%%%%%%%%%%%%% "Roll'em!" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% axheadplot = axes('Units','Normalized','Position',[0 .1 .72 .8],'Color',axcolor); TPAXCOLOR = get(axheadplot,'Color'); Colormap = [jet(64);TPAXCOLOR]; fprintf('Warning: do not resize plot window during movie creation ...\n '); newpan = length(movieframes)+1; posrow = 2; if size(camerapath,1) > 1 newpan = camerapath(posrow,1); % pick up next frame to change camerapos step values end for i = movieframes % make the movie, frame by frame fprintf('%d ',i-movieframes(1)+1); axes(axeegplot) x1 = startsec+(i-1)/srate; l1 = line([x1 x1],limits,'color','b'); % draw vertical line at data frame timetext = num2str(x1,3); % Note: Matlab4 doesn't take '%4.3f' set(axeegplot,'Xtick',x1,'XtickLabel',num2str(x1,'%4.3f')); axes(axheadplot) cla set(axheadplot,'Color',axcolor); headplot(data(:,i),spline_file,'maplimits',minmax,... 'view',[azimuth elevation],'verbose','off', varargin{:}); if i== newpan % adapt camerapath step sizes az_step = camerapath(posrow,2); el_step = camerapath(posrow,4); posrow = posrow+1; if size(camerapath,1)>=posrow newpan = camerapath(posrow,1); else newpan = length(movieframes)+1; end end azimuth = azimuth+az_step; % update camera position elevation = elevation+el_step; if elevation>=90 fprintf('headplot(): warning -- elevation out of range!\n'); elevation = 89.99; end if elevation<=-90 fprintf('headplot(): warning -- elevation out of range!\n'); elevation = -89.99; end set(axheadplot,'Units','pixels',... 'CameraViewAngleMode','manual',... 'YTickMode','manual','ZTickMode','manual',... 'PlotBoxAspectRatioMode','manual',... 'DataAspectRatioMode','manual'); % keep camera distance constant txt = [int2str(i-movieframes(1)+1)]; text(0.45,-0.45,txt,'Color','k','FontSize',14); % show frame number [Movie(:,i+1-movieframes(1))] = getframe(gcf); % can't show this - colors wrong! % known Matlab 5.0-5.1 bug! % [M,Cmap] = getframe(gcf); % if i==1 % [m,n] = size(M); % Movie = zeros(m,n*length(movieframes)); % whos Movie % end % Movie((i-1)*m+1:i*m,(i-1)*n+1:i*n) = M; drawnow delete(l1) end % colormap(Cmap); % montage(Movie) % Movie = immovie(Movie,[m n length(movieframes)]); % whos Movie fprintf('\nDone!\n');
github
lcnbeapp/beapp-master
arrow.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/arrow.m
51,888
utf_8
6310afbf5a0ed2b3cfdc0469d9b0c9cd
% arrow() - Draw a line with an arrowhead. % % Usage: % >> arrow('Property1',PropVal1,'Property2',PropVal2,...) % >> arrow(H,'Prop1',PropVal1,...) % >> arrow(Start,Stop) % >> arrow(Start,Stop,Length,BaseAngle,TipAngle,Width,Page,CrossDir) % >> arrow demo %2-D demos of the capabilities of arrow() % >> arrow demo2 %3-D demos of the capabilities of arrow() % % Inputs: % H - vector of handles to previously created arrows and/or % line objects, will update the previously-created % arrows according to the current view and any specified % properties, and will convert two-point line objects to % corresponding arrows. Note that arrow(H) will update the % arrows if the current view has changed. % Start - vectors of length 2 or 3, or matrices with 2 or 3 columns % Stop - same as Start % 'Start' - The starting points. B % 'Stop' - The end points. /|\ ^ % 'Length' - Length of the arrowhead in pixels. /|||\ | % 'BaseAngle' - Base angle in degrees (ADE). //|||\\ L| % 'TipAngle' - Tip angle in degrees (ABC). ///|||\\\ e| % 'Width' - Width of the base in pixels. ////|||\\\\ n| % 'Page' - Use hardcopy proportions. /////|D|\\\\\ g| % 'CrossDir' - Vector || to arrowhead plane. //// ||| \\\\ t| % 'NormalDir' - Vector out of arrowhead plane. /// ||| \\\ h| % 'Ends' - Which end has an arrowhead. //<----->|| \\ | % 'ObjectHandles' - Vector of handles to update. / base ||| \ V % 'LineStyle' - The linestyle of the arrow. E angle||<-------->C % 'LineWidth' - Line thicknesses. |||tipangle % 'FaceColor' - FaceColor of patch arrows. ||| % 'EdgeColor' - EdgeColor/Color of patch/line arrows. ||| % 'Color' - Set FaceColor & EdgeColor properties. -->|A|<-- width % % Notes: % A property list can follow any specified normal argument list, e.g., % ARROW([1 2 3],[0 0 0],36,'BaseAngle',60) creates an arrow from (1,2,3) to % the origin, with an arrowhead of length 36 pixels and 60-degree base angle. % % The basic arguments or properties can generally be vectorized to create % multiple arrows with the same call. This is done by passing a property % with one row per arrow, or, if all arrows are to have the same property % value, just one row may be specified. % % You may want to execute AXIS(AXIS) before calling ARROW so it doesn't change % the axes on you; ARROW determines the sizes of arrow components BEFORE the % arrow is plotted, so if ARROW changes axis limits, arrows may be malformed. % % ARROW uses features of Matlab 4.2c and later, so earlier versions may be % incompatible; call ARROW VERSION for more details. % % Author: Erik A. Johnson <[email protected]>, 1995 % Copyright (c)1995, Erik A. Johnson <[email protected]>, 10/6/95 % Many thanks to Keith Rogers <[email protected]> for his many excellent % suggestions and beta testing. Check out his shareware package MATDRAW. % He has permission to distribute ARROW with MATDRAW. % $Log: arrow.m,v $ % Revision 1.5 2009/10/20 22:19:56 dev % % added log to file % function [h,yy,zz] = arrow(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8, ... arg9,arg10,arg11,arg12,arg13,arg14,arg15,arg16, ... arg17,arg18,arg19,arg20,arg21,arg22,arg23,arg24) % Are we doing the demo? c = sprintf('\n'); if (nargin==1), if (ischar(arg1)), arg1 = lower([arg1 ' ']); if (strcmp(arg1(1:4),'prop')), disp([c ... 'ARROW Properties: Default values are given in [square brackets], and other' c ... ' acceptable equivalent property names are in (parenthesis).' c c ... ' Start The starting points. For N arrows, B' c ... ' this should be a Nx2 or Nx3 matrix. /|\ ^' c ... ' Stop The end points. For N arrows, this /|||\ |' c ... ' should be a Nx2 or Nx3 matrix. //|||\\ L|' c ... ' Length Length of the arrowhead (in pixels on ///|||\\\ e|' c ... ' screen, points on a page). [16] (Len) ////|||\\\\ n|' c ... ' BaseAngle Angle (degrees) of the base angle /////|D|\\\\\ g|' c ... ' ADE. For a simple stick arrow, use //// ||| \\\\ t|' c ... ' BaseAngle=TipAngle. [90] (Base) /// ||| \\\ h|' c ... ' TipAngle Angle (degrees) of tip angle ABC. //<----->|| \\ |' c ... ' [16] (Tip) / base ||| \ V' c ... ' Width Width of the base in pixels. Not E angle ||<-------->C' c ... ' the ''LineWidth'' prop. [0] (Wid) |||tipangle' c ... ' Page If provided, non-empty, and not NaN, |||' c ... ' this causes ARROW to use hardcopy |||' c ... ' rather than onscreen proportions. A' c ... ' This is important if screen aspect --> <-- width' c ... ' ratio and hardcopy aspect ratio are ----CrossDir---->' c ... ' vastly different. []' c... ' CrossDir A vector giving the direction towards which the fletches' c ... ' on the arrow should go. [computed such that it is perpen-' c ... ' dicular to both the arrow direction and the view direction' c ... ' (i.e., as if it was pasted on a normal 2-D graph)] (Note' c ... ' that CrossDir is a vector; if an axis is plotted on a log' c ... ' scale, then the corresponding component of CrossDir must' c ... ' also be set appropriately, i.e., to 1 for no change in' c ... ' that direction, >1 for a positive change, >0 and <1 for' c ... ' negative change.)' c ... ' NormalDir A vector normal to the fletch direction (CrossDir is then' c ... ' computed by the vector cross product {Line}x{NormalDir}). []' c ... ' Ends Set which end has an arrowhead. Valid values are ''none'',' c ... ' ''stop'', ''start'', and ''both''. [''stop''] (End)' c... ' ObjectHandles Vector of handles to previously-created arrows to be' c ... ' updated or line objects to be converted to arrows.' c ... ' [] (Object,Handle)' c ... ' LineStyle The linestyle of the arrow. If anything other than ''-'',' c ... ' the arrow will be drawn with a line object, otherwise it' c ... ' will be drawn with a patch. [''-''] (LineS)' c ... ' LineWidth Same as used in SET commands, but may be passed a vector' c ... ' for multiple arrows. [default of the line or patch]' c ... ' FaceColor Set the FaceColor of patch arrows. May be one of' c ... ' ''ymcrgbwkfn'' (f=flat,n=none) or a column-vector colorspec' c ... ' (or Nx3 matrix for N arrows). [1 1 1] (FaceC)' c ... ' EdgeColor Set the EdgeColor of patch arrows and Color of line' c ... ' arrows. [1 1 1] (EdgeC)' c ... ' Color Sets both FaceColor and EdgeColor properties.' c ... ' Included for compatibility with line objects.' c c ... ' ARROW(''Start'',P,''Stop'',[]) or ARROW(''Start'',[],''Stop'',P), with size(P)=[N 3]' c ... ' will create N-1 arrows, just like ARROW(''Start'',P1,''Stop'',P2), where' c c ... ' / x1 y1 z1 \ / x1 y1 z1 \ / x2 y2 z2 \' c ... ' | . . . | | . . . | | . . . |' c ... ' P = | . . . | P1 = | . . . | P2 = | . . . |' c ... ' | . . . | | . . . | | . . . |' c ... ' \ xN yN zN / \ xN-1 yN-1 zN-1 / \ xN yN zN /' c]); elseif (strcmp(arg1(1:4),'vers')), disp([c ... 'ARROW Version: There are two compatibility problems for ARROW in Matlab' c ... ' versions earlier than 4.2c:' c c c ... ' 1) In Matlab <4.2, the ''Tag'' property does not exist. ARROW uses this' c ... ' ''Tag'' to identify arrow objects for subsequent calls to ARROW.' c c ... ' Solution: (a) delete all instances of the string' c c ... ' ,''Tag'',ArrowTag' c c ... ' (b) and replace all instances of the string' c c ... ' strcmp(get(oh,''Tag''),ArrowTag)' c c ... ' with the string' c c ... ' all(size(ud)==[1 15])' c c c ... ' 2) In Matlab <4.2c, FINDOBJ is buggy (it can cause Matlab to crash if' c ... ' more than 100 objects are returned). ARROW uses FINDOBJ to make sure' c ... ' that any handles it receives are truly handles to existing objects.' c c ... ' Solution: replace the line' c c ... ' objs = findobj;' c c ... ' with the lines' c c ... ' objs=0; k=1;' c ... ' while (k<=length(objs)),' c ... ' objs = [objs; get(objs(k),''Children'')];' c ... ' if (strcmp(get(objs(k),''Type''),''axes'')),' c ... ' objs=[objs;get(objs(k),''XLabel''); ...' c ... ' get(objs(k),''YLabel''); ...' c ... ' get(objs(k),''ZLabel''); ...' c ... ' get(objs(k),''Title'')];' c ... ' end;' c ... ' k=k+1;' c ... ' end;' c c]); elseif (strcmp(arg1(1:4),'demo')), % demo % create the data [x,y,z] = peaks; [ddd,iii]=max(z(:)); axlim = [min(x(:)) max(x(:)) min(y(:)) max(y(:)) min(z(:)) max(z(:))]; % modify it by inserting some NaN's [m,n] = size(z); m = floor(m/2); n = floor(n/2); z(1:m,1:n) = NaN*ones(m,n); % graph it clf('reset'); hs=surf(x,y,z); xlabel('x'); ylabel('y'); if (~strcmp(arg1(1:5),'demo2')), % set the view axis(axlim); zlabel('z'); %shading('interp'); set(hs,'EdgeColor','k'); view(viewmtx(-37.5,30,20)); title('Demo of the capabilities of the ARROW function in 3-D'); % Normal yellow arrow h1 = arrow([axlim(1) axlim(4) 4],[-.8 1.2 4], ... 'EdgeColor','y','FaceColor','y'); % Normal white arrow, clipped by the surface h2 = arrow(axlim([1 4 6]),[0 2 4]); t=text(-2.4,2.7,7.7,'arrow clipped by surf'); % Baseangle<90 h3 = arrow([3 .125 3.5],[1.375 0.125 3.5],30,50); t2=text(3.1,.125,3.5,'local maximum'); % Baseangle<90, fill and edge colors different h4 = arrow(axlim(1:2:5)*.5,[0 0 0],36,60,25, ... 'EdgeColor','b','FaceColor','c'); t3=text(axlim(1)*.5,axlim(3)*.5,axlim(5)*.5-.75,'origin'); set(t3,'HorizontalAlignment','center'); % Baseangle>90, black fill h5 = arrow([-2.9 2.9 3],[-1.3 .4 3.2],30,120,[],6, ... 'EdgeColor','r','FaceColor','k','LineWidth',2); % Baseangle>90, no fill h6 = arrow([-2.9 2.9 1.3],[-1.3 .4 1.5],30,120,[],6, ... 'EdgeColor','r','FaceColor','none','LineWidth',2); % Stick arrow h7 = arrow([-1.6 -1.65 -6.5],[0 -1.65 -6.5],[],16,16); t4=text(-1.5,-1.65,-7.25,'global mininum'); set(t4,'HorizontalAlignment','center'); % Normal, black fill h8 = arrow([-1.4 0 -7.2],[-1.4 0 -3],'FaceColor','k'); t5=text(-1.5,0,-7.75,'local minimum'); set(t5,'HorizontalAlignment','center'); % Gray fill, crossdir specified h9 = arrow([-3 2.2 -6],[-3 2.2 -.05],36,[],27,6,[],[0 -1 0], ... 'EdgeColor','w','FaceColor',.2*[1 1 1]); % a series of normal arrows, linearly spaced, crossdir specified h10y=(0:4)'/3; h10 = arrow([-3*ones(size(h10y)) h10y -6.5*ones(size(h10y))], ... [-3*ones(size(h10y)) h10y -.05*ones(size(h10y))], ... 12,[],[],[],[],[0 -1 0]); % a series of normal arrows, linearly spaced h11x=(1:.33:2.8)'; h11 = arrow([h11x -3*ones(size(h11x)) 6.5*ones(size(h11x))], ... [h11x -3*ones(size(h11x)) -.05*ones(size(h11x))]); % series of black-filled arrows, radially oriented, crossdir specified h12x=2; h12y=-3; h12z=axlim(5)/2; h12xr=1; h12zr=h12z; ir=.15;or=.81; h12t=(0:11)'/6*pi; h12 = arrow([h12x+h12xr*cos(h12t)*ir h12y*ones(size(h12t)) ... h12z+h12zr*sin(h12t)*ir],[h12x+h12xr*cos(h12t)*or ... h12y*ones(size(h12t)) h12z+h12zr*sin(h12t)*or], ... 10,[],[],[],[], ... [-h12xr*sin(h12t) zeros(size(h12t)) h12zr*cos(h12t)],... 'FaceColor','none','EdgeColor','m'); % series of normal arrows, tangentially oriented, crossdir specified or13=.91; h13t=(0:.5:12)'/6*pi; h13 = arrow([h12x+h12xr*cos(h13t)*or13 ... h12y*ones(size(h13t)) ... h12z+h12zr*sin(h13t)*or13],[],6); % arrow with no line ==> oriented upwards h14 = arrow([3 3 3],[3 3 3],30); t6=text(3,3,3.6,'no line'); set(t6,'HorizontalAlignment','center'); % arrow with -- linestyle h15 = arrow([-.5 -3 -3],[1 -3 -3],'LineStyle','--','EdgeColor','g'); if (nargout>=1), h=[h1;h2;h3;h4;h5;h6;h7;h8;h9;h10;h11;h12;h13;h14;h15]; end; else, set(hs,'YData',10.^get(hs,'YData')); shading('interp'); view(2); title('Demo of the capabilities of the ARROW function in 2-D'); hold on; [C,H]=contour(x,y,z,20); hold off; for k=H', set(k,'ZData',(axlim(6)+1)*ones(size(get(k,'XData'))),... 'YData',10.^get(k,'YData'),'Color','k'); end; set(gca,'YScale','log'); axis([axlim(1:2) 10.^axlim(3:4)]); % Normal yellow arrow h1 = arrow([axlim(1) 10^axlim(4) axlim(6)+2],[x(iii) 10^y(iii) axlim(6)+2], ... 'EdgeColor','y','FaceColor','y'); % three arrows with varying fill, width, and baseangle h2 = arrow([-3 10^(-3) 10; -3 10^(-1.5) 10; -1.5 10^(-3) 10], ... [-.03 10^(-.03) 10; -.03 10^(-1.5) 10; -1.5 10^(-.03) 10], ... 24,[90;60;120],[],[0;0;4]); set(h2(2),'EdgeColor','g','FaceColor','c'); set(h2(3),'EdgeColor','m','FaceColor','r'); if (nargout>=1), h=[h1;h2]; end; end; else, error(['ARROW got an unknown single-argument string ''' deblank(arg1) '''.']); end; return; end; end; % Check # of arguments if (nargin==0), help arrow ; return; elseif (nargout>3), error('ARROW produces at most 3 output arguments.'); end; % find first property number firstprop = nargin+1; if (nargin<=3), % to speed things up a bit if (nargin==1), elseif (ischar(arg1)), firstprop=1; elseif (ischar(arg2)), firstprop=2; elseif (nargin==3), if (ischar(arg3)), firstprop=3; end; end; else, for k=1:nargin, curarg = eval(['arg' num2str(k)]); if (ischar(curarg)), firstprop = k; break; end; end; end; % check property list if (firstprop<=nargin), for k=firstprop:2:nargin, curarg = eval(['arg' num2str(k)]); if ((~ischar(curarg))|(min(size(curarg))~=1)), error('ARROW requires that a property name be a single string.'); end; end; if (rem(nargin-firstprop,2)~=1), error(['ARROW requires that the property ''' eval(['arg' num2str(nargin)]) ... ''' be paired with a property value.']); end; end; % default output if (nargout>0), h=[]; end; if (nargout>1), yy=[]; end; if (nargout>2), zz=[]; end; % set values to empty matrices start = []; stop = []; len = []; baseangle = []; tipangle = []; wid = []; page = []; crossdir = []; ends = []; linewidth = []; linestyle = []; edgecolor = []; facecolor = []; ax = []; oldh = []; defstart = [NaN NaN NaN]; defstop = [NaN NaN NaN]; deflen = 16; defbaseangle = 90; deftipangle = 16; defwid = 0; defpage = 0; defcrossdir = [NaN NaN NaN]; defends = 1; deflinewidth = NaN; deflinestyle = '- '; defedgecolor = [1 1 1]; deffacecolor = [1 1 1]; defoldh = []; % The 'Tag' we'll put on our arrows ArrowTag = 'Arrow'; % check for oldstyle arguments if (firstprop>2), % if old style arguments, get them if (firstprop==3), start=arg1; stop=arg2; elseif (firstprop==4), start=arg1; stop=arg2; len=arg3(:); elseif (firstprop==5), start=arg1; stop=arg2; len=arg3(:); baseangle=arg4(:); elseif (firstprop==6), start=arg1; stop=arg2; len=arg3(:); baseangle=arg4(:); tipangle=arg5(:); elseif (firstprop==7), start=arg1; stop=arg2; len=arg3(:); baseangle=arg4(:); tipangle=arg5(:); wid=arg6(:); elseif (firstprop==8), start=arg1; stop=arg2; len=arg3(:); baseangle=arg4(:); tipangle=arg5(:); wid=arg6(:); page=arg7(:); elseif (firstprop==9), start=arg1; stop=arg2; len=arg3(:); baseangle=arg4(:); tipangle=arg5(:); wid=arg6(:); page=arg7(:); crossdir=arg8; else, error('ARROW takes at most 8 non-property arguments.'); end; elseif (firstprop==2), % assume arg1 is a set of handles oldh = arg1(:); end; % parse property pairs extraprops=char([]); for k=firstprop:2:nargin, prop = eval(['arg' num2str(k)]); val = eval(['arg' num2str(k+1)]); prop = [lower(prop(:)') ' ']; if (all(prop(1:5)=='start')), start = val; elseif (all(prop(1:4)=='stop')), stop = val; elseif (all(prop(1:3)=='len')), len = val(:); elseif (all(prop(1:4)=='base')), baseangle = val(:); elseif (all(prop(1:3)=='tip')), tipangle = val(:); elseif (all(prop(1:3)=='wid')), wid = val(:); elseif (all(prop(1:4)=='page')), page = val; elseif (all(prop(1:5)=='cross')), crossdir = val; elseif (all(prop(1:4)=='norm')), if (ischar(val)), crossdir=val; else, crossdir=val*sqrt(-1); end; elseif (all(prop(1:3)=='end')), ends = val; elseif (all(prop(1:5)=='linew')), linewidth = val(:); elseif (all(prop(1:5)=='lines')), linestyle = val; elseif (all(prop(1:5)=='color')), edgecolor = val; facecolor=val; elseif (all(prop(1:5)=='edgec')), edgecolor = val; elseif (all(prop(1:5)=='facec')), facecolor = val; elseif (all(prop(1:6)=='object')), oldh = val(:); elseif (all(prop(1:6)=='handle')), oldh = val(:); elseif (all(prop(1:5)=='userd')), %ignore it else, extraprops=[extraprops ',arg' num2str(k) ',arg' num2str(k+1)]; end; end; % Check if we got 'default' values if (ischar(start )), s=lower([start(:)' ' ']); if (all(s(1:3)=='def')), start = defstart; else, error(['ARROW does not recognize ''' start(:)' ''' as a valid ''Start'' string.']); end; end; if (ischar(stop )), s=lower([stop(:)' ' ']); if (all(s(1:3)=='def')), stop = defstop; else, error(['ARROW does not recognize ''' stop(:)' ''' as a valid ''Stop'' string.']); end; end; if (ischar(len )), s=lower([len(:)' ' ']); if (all(s(1:3)=='def')), len = deflen; else, error(['ARROW does not recognize ''' len(:)' ''' as a valid ''Length'' string.']); end; end; if (ischar(baseangle )), s=lower([baseangle(:)' ' ']); if (all(s(1:3)=='def')), baseangle = defbaseangle; else, error(['ARROW does not recognize ''' baseangle(:)' ''' as a valid ''BaseAngle'' string.']); end; end; if (ischar(tipangle )), s=lower([tipangle(:)' ' ']); if (all(s(1:3)=='def')), tipangle = deftipangle; else, error(['ARROW does not recognize ''' tipangle(:)' ''' as a valid ''TipAngle'' string.']); end; end; if (ischar(wid )), s=lower([wid(:)' ' ']); if (all(s(1:3)=='def')), wid = defwid; else, error(['ARROW does not recognize ''' wid(:)' ''' as a valid ''Width'' string.']); end; end; if (ischar(crossdir )), s=lower([crossdir(:)' ' ']); if (all(s(1:3)=='def')), crossdir = defcrossdir; else, error(['ARROW does not recognize ''' crossdir(:)' ''' as a valid ''CrossDir'' or ''NormalDir'' string.']); end; end; if (ischar(page )), s=lower([page(:)' ' ']); if (all(s(1:3)=='def')), page = defpage; else, error(['ARROW does not recognize ''' page(:)' ''' as a valid ''Page'' string.']); end; end; if (ischar(ends )), s=lower([ends(:)' ' ']); if (all(s(1:3)=='def')), ends = defends; end; end; if (ischar(linewidth )), s=lower([linewidth(:)' ' ']); if (all(s(1:3)=='def')), linewidth = deflinewidth; else, error(['ARROW does not recognize ''' linewidth(:)' ''' as a valid ''LineWidth'' string.']); end; end; if (ischar(linestyle )), s=lower([linestyle(:)' ' ']); if (all(s(1:3)=='def')), linestyle = deflinestyle; end; end; if (ischar(edgecolor )), s=lower([edgecolor(:)' ' ']); if (all(s(1:3)=='def')), edgecolor = defedgecolor; end; end; if (ischar(facecolor )), s=lower([facecolor(:)' ' ']); if (all(s(1:3)=='def')), facecolor = deffacecolor; end; end; if (ischar(oldh )), s=lower([oldh(:)' ' ']); if (all(s(1:3)=='def')), oldh = []; else, error(['ARROW does not recognize ''' oldh(:)' ''' as a valid ''ObjectHandles'' string.']); end; end; % check transpose on arguments; convert strings to numbers if (((size(start ,1)==2)|(size(start ,1)==3))&((size(start ,2)==1)|(size(start ,2)>3))), start = start'; end; if (((size(stop ,1)==2)|(size(stop ,1)==3))&((size(stop ,2)==1)|(size(stop ,2)>3))), stop = stop'; end; if (((size(crossdir,1)==2)|(size(crossdir,1)==3))&((size(crossdir,2)==1)|(size(crossdir,2)>3))), crossdir = crossdir'; end; if ((size(linestyle,2)>2)&(size(linestyle,1)<=2)), linestyle=linestyle'; end; if (all(size(edgecolor))), if (ischar(edgecolor)), col = lower(edgecolor(:,1)); edgecolor = zeros(length(col),3); ii=find(col=='y'); if (all(size(ii))), edgecolor(ii,:)=ones(length(ii),1)*[1 1 0]; end; ii=find(col=='m'); if (all(size(ii))), edgecolor(ii,:)=ones(length(ii),1)*[1 0 1]; end; ii=find(col=='c'); if (all(size(ii))), edgecolor(ii,:)=ones(length(ii),1)*[0 1 1]; end; ii=find(col=='r'); if (all(size(ii))), edgecolor(ii,:)=ones(length(ii),1)*[1 0 0]; end; ii=find(col=='g'); if (all(size(ii))), edgecolor(ii,:)=ones(length(ii),1)*[0 1 0]; end; ii=find(col=='b'); if (all(size(ii))), edgecolor(ii,:)=ones(length(ii),1)*[0 0 1]; end; ii=find(col=='w'); if (all(size(ii))), edgecolor(ii,:)=ones(length(ii),1)*[1 1 1]; end; ii=find(col=='k'); if (all(size(ii))), edgecolor(ii,:)=ones(length(ii),1)*[0 0 0]; end; ii=find(col=='f'); if (all(size(ii))), edgecolor(ii,:)=ones(length(ii),1)*[1 1 1]*inf; end; ii=find(col=='n'); if (all(size(ii))), edgecolor(ii,:)=ones(length(ii),1)*[1 1 1]*(-inf); end; elseif ((size(edgecolor,2)~=3)&(size(edgecolor,1)==3)), edgecolor=edgecolor'; elseif (size(edgecolor,2)~=3), error('ARROW requires that color specifications must be a ?x3 RGB matrix.'); end; end; if (all(size(facecolor))), if (ischar(facecolor)), col = lower(facecolor(:,1)); facecolor = zeros(length(col),3); ii=find(col=='y'); if (all(size(ii))), facecolor(ii,:)=ones(length(ii),1)*[1 1 0]; end; ii=find(col=='m'); if (all(size(ii))), facecolor(ii,:)=ones(length(ii),1)*[1 0 1]; end; ii=find(col=='c'); if (all(size(ii))), facecolor(ii,:)=ones(length(ii),1)*[0 1 1]; end; ii=find(col=='r'); if (all(size(ii))), facecolor(ii,:)=ones(length(ii),1)*[1 0 0]; end; ii=find(col=='g'); if (all(size(ii))), facecolor(ii,:)=ones(length(ii),1)*[0 1 0]; end; ii=find(col=='b'); if (all(size(ii))), facecolor(ii,:)=ones(length(ii),1)*[0 0 1]; end; ii=find(col=='w'); if (all(size(ii))), facecolor(ii,:)=ones(length(ii),1)*[1 1 1]; end; ii=find(col=='k'); if (all(size(ii))), facecolor(ii,:)=ones(length(ii),1)*[0 0 0]; end; ii=find(col=='f'); if (all(size(ii))), facecolor(ii,:)=ones(length(ii),1)*[1 1 1]*inf; end; ii=find(col=='n'); if (all(size(ii))), facecolor(ii,:)=ones(length(ii),1)*[1 1 1]*(-inf); end; elseif ((size(facecolor,2)~=3)&(size(facecolor,1)==3)), facecolor=facecolor'; elseif (size(facecolor,2)~=3), error('ARROW requires that color specifications must be a ?x3 RGB matrix.'); end; end; if (all(size(ends))), if (ischar(ends)), endsorig = ends; col = lower([ends(:,1:min(3,size(ends,2))) ones(size(ends,1),max(0,3-size(ends,2)))*' ']); ends = NaN*ones(size(ends,1),1); oo = ones(1,size(ends,1)); ii=find(all(col'==['non']'*oo)'); if (all(size(ii))), ends(ii)=ones(length(ii),1)*0; end; ii=find(all(col'==['sto']'*oo)'); if (all(size(ii))), ends(ii)=ones(length(ii),1)*1; end; ii=find(all(col'==['sta']'*oo)'); if (all(size(ii))), ends(ii)=ones(length(ii),1)*2; end; ii=find(all(col'==['bot']'*oo)'); if (all(size(ii))), ends(ii)=ones(length(ii),1)*3; end; if (any(isnan(ends))), ii = min(find(isnan(ends))); error(['ARROW does not recognize ''' deblank(endsorig(ii,:)) ''' as a valid ''Ends'' value.']); end; else, ends = ends(:); end; end; oldh = oldh(:); % check object handles if (all(size(oldh))), oldh = oldh.'; objs = findobj; if (length(objs)==0), error('ARROW found no graphics handles.'); elseif (length(objs)==1), objs=[objs;objs]; end; if (~all(any(objs(:,ones(1,length(oldh)))==oldh(ones(length(objs),1),:)))), error('ARROW got invalid object handles.'); end; oldh = oldh.'; end; % Check for an empty Start or Stop (but not both) with no object handles if ((~all(size(oldh)))&(all(size(start))~=all(size(stop)))), if (~all(size(start))), start=stop; end; ii = find(all(diff(start)'==0)'); if (size(start,1)==1), stop = start; elseif (length(ii)==size(start,1)-1) stop = start(1,:); start = stop; else, if (all(size(ii))), jj = (1:size(start,1))'; jj(ii) = zeros(length(ii),1); jj = jj(find(jj>0)); start = start(jj,:); end; stop = start(2:size(start,1),:); start = start(1:size(start,1)-1,:); end; end; % largest argument length argsizes = [length(oldh) size(start,1) size(stop,1) ... length(len) length(baseangle) length(tipangle) ... length(wid) length(page) size(crossdir,1) length(ends) ... length(linewidth) size(edgecolor,1) size(facecolor,1)]; args=['length(ObjectHandle) '; ... '#rows(Start) '; ... '#rows(Stop) '; ... 'length(Length) '; ... 'length(BaseAngle) '; ... 'length(TipAngle) '; ... 'length(Width) '; ... 'length(Page) '; ... '#rows(CrossDir) '; ... '#rows(Ends) '; ... 'length(LineWidth) '; ... '#colors in EdgeColor '; ... '#colors in FaceColor ']; if (any(imag(crossdir(:))~=0)), args(9,:) = '#rows(NormalDir) '; end; if (~all(size(oldh))), narrows = max(argsizes); else, narrows = length(oldh); end; % Check size of arguments ii = find((argsizes~=0)&(argsizes~=1)&(argsizes~=narrows)); if (all(size(ii))), s = args(ii',:); while ((size(s,2)>1)&((abs(s(:,size(s,2)))==0)|(abs(s(:,size(s,2)))==abs(' ')))), s = s(:,1:size(s,2)-1); end; s = [ones(length(ii),1)*'ARROW requires that ' s ... ones(length(ii),1)*[' equal the # of arrows (' num2str(narrows) ').' c]]; s = s'; s = s(:)'; s = s(1:length(s)-1); error(char(s)); end; % check element length in Start, Stop, and CrossDir if (all(size(start))), if (size(start,2)==2), start = [start NaN*ones(size(start,1),1)]; elseif (size(start,2)~=3), error('ARROW requires 2- or 3-element Start points.'); end; end; if (all(size(stop))), if (size(stop,2)==2), stop = [stop NaN*ones(size(stop,1),1)]; elseif (size(stop,2)~=3), error('ARROW requires 2- or 3-element Stop points.'); end; end; if (all(size(crossdir))), if (size(crossdir,2)<3), crossdir = [crossdir NaN*ones(size(crossdir,1),3-size(crossdir,2))]; elseif (size(crossdir,2)~=3), if (all(imag(crossdir(:))==0)), error('ARROW requires 2- or 3-element CrossDir vectors.'); else, error('ARROW requires 2- or 3-element NormalDir vectors.'); end; end; end; % fill empty arguments if (~all(size(start ))), start = [NaN NaN NaN]; end; if (~all(size(stop ))), stop = [NaN NaN NaN]; end; if (~all(size(len ))), len = NaN; end; if (~all(size(baseangle ))), baseangle = NaN; end; if (~all(size(tipangle ))), tipangle = NaN; end; if (~all(size(wid ))), wid = NaN; end; if (~all(size(page ))), page = NaN; end; if (~all(size(crossdir ))), crossdir = [NaN NaN NaN]; end; if (~all(size(ends ))), ends = NaN; end; if (~all(size(linewidth ))), linewidth = NaN; end; if (~all(size(linestyle ))), linestyle = char(['-']); end; % was NaN if (~all(size(edgecolor ))), edgecolor = [NaN NaN NaN]; end; if (~all(size(facecolor ))), facecolor = [NaN NaN NaN]; end; % expand single-column arguments o = ones(narrows,1); if (size(start ,1)==1), start = o * start ; end; if (size(stop ,1)==1), stop = o * stop ; end; if (length(len )==1), len = o * len ; end; if (length(baseangle )==1), baseangle = o * baseangle ; end; if (length(tipangle )==1), tipangle = o * tipangle ; end; if (length(wid )==1), wid = o * wid ; end; if (length(page )==1), page = o * page ; end; if (size(crossdir ,1)==1), crossdir = o * crossdir ; end; if (length(ends )==1), ends = o * ends ; end; if (length(linewidth )==1), linewidth = o * linewidth ; end; if (size(linestyle ,1)==1), linestyle = o * linestyle ; end; if (size(edgecolor ,1)==1), edgecolor = o * edgecolor ; end; if (size(facecolor ,1)==1), facecolor = o * facecolor ; end; ax = o * gca; if (size(linestyle ,2)==1), linestyle = char([linestyle o*' ']); end; linestyle = char(linestyle); % if we've got handles, get the defaults from the handles oldlinewidth = NaN*ones(narrows,1); oldlinestyle = char(zeros(narrows,2)); oldedgecolor = NaN*ones(narrows,3); oldfacecolor = NaN*ones(narrows,3); if (all(size(oldh))), fromline = zeros(narrows,1); for k=1:narrows, oh = oldh(k); ud = get(oh,'UserData'); isarrow = strcmp(get(oh,'Tag'),ArrowTag); ohtype = get(oh,'Type'); ispatch = strcmp(ohtype,'patch'); isline = strcmp(ohtype,'line'); if (isarrow|isline), % arrow UserData format: [start' stop' len base tip wid page crossdir' ends] if (isarrow), start0 = ud(1:3); stop0 = ud(4:6); if (isnan(len(k))), len(k) = ud( 7); end; if (isnan(baseangle(k))), baseangle(k) = ud( 8); end; if (isnan(tipangle(k))), tipangle(k) = ud( 9); end; if (isnan(wid(k))), wid(k) = ud(10); end; if (isnan(page(k))), page(k) = ud(11); end; if (isnan(crossdir(k,1))), crossdir(k,1) = ud(12); end; if (isnan(crossdir(k,2))), crossdir(k,2) = ud(13); end; if (isnan(crossdir(k,3))), crossdir(k,3) = ud(14); end; if (isnan(ends(k))), ends(k) = ud(15); end; end; if (isline), fromline(k) = 1; if (isarrow), fc = -inf*[1 1 1]; else, fc = get(oh,'Color'); x = get(oh,'XData'); y = get(oh,'YData'); z = get(oh,'ZData'); if (any(size(x)~=[1 2])|any(size(y)~=[1 2])), error('ARROW only converts two-point lines.'); end; if (~all(size(z))), z=NaN*ones(size(x)); end; start0 = [x(1) y(1) z(1)]; stop0 = [x(2) y(2) z(2)]; end; ec = get(oh,'Color'); ls = [get(oh,'LineStyle') ' ']; ls=char(ls(1:2)); lw = get(oh,'LineWidth'); else, % an arrow patch fc = get(oh,'FaceColor');if (ischar(fc)), if (strcmp(fc,'none')), fc=-inf*[1 1 1]; elseif (strcmp(fc,'flat')), fc=inf*[1 1 1]; else, fc=[1 1 1]; end; end; ec = get(oh,'EdgeColor');if (ischar(ec)), if (strcmp(ec,'none')), ec=-inf*[1 1 1]; elseif (strcmp(ec,'flat')), ec=inf*[1 1 1]; else, ec=[1 1 1]; end; end; ls = char('- '); lw = get(oh,'LineWidth'); end; ax(k) = get(oh,'Parent'); else, error(['ARROW cannot convert ' ohtype ' objects.']); end; oldlinewidth(k) = lw; oldlinestyle(k,:) = ls; oldedgecolor(k,:) = ec; oldfacecolor(k,:) = fc; ii=find(isnan(start(k,:))); if (all(size(ii))), start(k,ii)=start0(ii); end; ii=find(isnan(stop( k,:))); if (all(size(ii))), stop( k,ii)=stop0( ii); end; if (isnan(linewidth(k))), linewidth(k) = lw; end; if (isnan(linestyle(k,1))), linestyle(k,1:2) = ls; end; if (any(isnan(facecolor(k,:)))), facecolor(k,:) = fc; end; if (any(isnan(edgecolor(k,:)))), edgecolor(k,:) = ec; end; end; else fromline = []; end; % set up the UserData data % (do it here so it is not corrupted by log10's and such) ud = [start stop len baseangle tipangle wid page crossdir ends]; % Set Page defaults if isnan(page) page = ~isnan(page); end; % Get axes limits, range, min; correct for aspect ratio and log scale axm = zeros(3,narrows); axr = zeros(3,narrows); ap = zeros(2,narrows); xyzlog = zeros(3,narrows); limmin = zeros(2,narrows); limrange = zeros(2,narrows); oneax = all(ax==ax(1)); if (oneax), T = zeros(4,4); invT = zeros(4,4); else, T = zeros(16,narrows); invT = zeros(16,narrows); end; axnotdone = ones(size(ax)); while (any(axnotdone)), ii = min(find(axnotdone)); curax = ax(ii); curpage = page(ii); % get axes limits and aspect ratio axl = [get(curax,'XLim'); get(curax,'YLim'); get(curax,'ZLim')]; ar = get(curax,'DataAspectRatio'); % get axes size in pixels (points) u = get(curax,'Units'); axposoldunits = get(curax,'Position'); if (curpage), curfig = get(curax,'Parent'); pu = get(curfig,'PaperUnits'); set(curfig,'PaperUnits','points'); pp = get(curfig,'PaperPosition'); set(curfig,'PaperUnits',pu); set(curax,'Units','normalized'); curap = get(curax,'Position'); curap = pp.*curap; else, set(curax,'Units','pixels'); curap = get(curax,'Position'); end; set(curax,'Units',u); set(curax,'Position',axposoldunits); % adjust limits for log scale on axes curxyzlog = [strcmp(get(curax,'XScale'),'log'); ... strcmp(get(curax,'YScale'),'log'); ... strcmp(get(curax,'ZScale'),'log')]; if (any(curxyzlog)), ii = find([curxyzlog;curxyzlog]); if (any(axl(ii)<=0)), error('ARROW does not support non-positive limits on log-scaled axes.'); else, axl(ii) = log10(axl(ii)); end; end; % correct for aspect ratio if (~isnan(ar(1))), if (curap(3) < ar(1)*curap(4)), curap(2) = curap(2) + (curap(4)-curap(3)/ar(1))/2; curap(4) = curap(3)/ar(1); else, curap(1) = curap(1) + (curap(3)-curap(4)*ar(1))/2; curap(3) = curap(4)*ar(1); end; end; % correct for 'equal' % may only want to do this for 2-D views, but seems right for 3-D also if (~isnan(ar(2))), if ((curap(3)/(axl(1,2)-axl(1,1)))/(curap(4)/(axl(2,2)-axl(2,1)))>ar(2)), incr = curap(3)*(axl(2,2)-axl(2,1))/(curap(4)*ar(2)) - (axl(1,2)-axl(1,1)); axl(1,:) = axl(1,:) + incr/2*[-1 1]; else, incr = ar(2)*(axl(1,2)-axl(1,1))*curap(4)/curap(3) - (axl(2,2)-axl(2,1)); axl(2,:) = axl(2,:) + incr/2*[-1 1]; end; end; % compute the range of 2-D values curT = get(curax,'Xform'); lim = curT*[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1;0 0 0 0 1 1 1 1;1 1 1 1 1 1 1 1]; lim = lim(1:2,:)./([1;1]*lim(4,:)); curlimmin = min(lim')'; curlimrange = max(lim')' - curlimmin; curinvT = inv(curT); if (~oneax), curT = curT.'; curinvT = curinvT.'; curT = curT(:); curinvT = curinvT(:); end; % check which arrows to which cur corresponds ii = find((ax==curax)&(page==curpage)); oo = ones(1,length(ii)); axr(:,ii) = diff(axl')' * oo; axm(:,ii) = axl(:,1) * oo; ap(:,ii) = curap(3:4)' * oo; xyzlog(:,ii) = curxyzlog * oo; limmin(:,ii) = curlimmin * oo; limrange(:,ii) = curlimrange * oo; if (oneax), T = curT; invT = curinvT; else, T(:,ii) = curT * oo; invT(:,ii) = curinvT * oo; end; axnotdone(ii) = zeros(1,length(ii)); end; % correct for log scales curxyzlog = xyzlog.'; ii = find(curxyzlog(:)); if (all(size(ii))), start( ii) = real(log10(start( ii))); stop( ii) = real(log10(stop( ii))); if (all(imag(crossdir(ii))==0)), crossdir(ii) = real(log10(crossdir(ii))); else, jj = find(imag(crossdir(ii))==0); if (all(size(jj))), crossdir(jj) = real(log10(crossdir(jj))); end; jj = find(imag(crossdir(ii))~=0); if (all(size(jj))), crossdir(jj) = real(log10(imag(crossdir(jj))))*sqrt(-1); end; end; end; % take care of defaults, page was done above ii=find(isnan(start(:) )); if (all(size(ii))), start(ii) = axm(ii)+axr(ii)/2; end; ii=find(isnan(stop(:) )); if (all(size(ii))), stop(ii) = axm(ii)+axr(ii)/2; end; ii=find(isnan(crossdir(:) )); if (all(size(ii))), crossdir(ii) = zeros(length(ii),1); end; ii=find(isnan(len )); if (all(size(ii))), len(ii) = ones(length(ii),1)*deflen; end; ii=find(isnan(baseangle )); if (all(size(ii))), baseangle(ii) = ones(length(ii),1)*defbaseangle; end; ii=find(isnan(tipangle )); if (all(size(ii))), tipangle(ii) = ones(length(ii),1)*deftipangle; end; ii=find(isnan(wid )); if (all(size(ii))), wid(ii) = ones(length(ii),1)*defwid; end; ii=find(isnan(ends )); if (all(size(ii))), ends(ii) = ones(length(ii),1)*defends; end; ii=find(isnan(linewidth )); if (all(size(ii))), linewidth(ii) = ones(length(ii),1)*deflinewidth; end; ii=find(any(isnan(edgecolor'))); if (all(size(ii))), edgecolor(ii,:) = ones(length(ii),1)*defedgecolor; end; ii=find(any(isnan(facecolor'))); if (all(size(ii))), facecolor(ii,:) = ones(length(ii),1)*deffacecolor; end; ii=find(isnan(linestyle(:,1) )); if (all(size(ii))), linestyle(ii,:) = ones(length(ii),1)*deflinestyle; end; ii=find(isnan(linestyle(:,2) )); if (all(size(ii))), linestyle(ii,2) = ones(length(ii),1)*' '; end; %just in case % transpose all values start = start.'; stop = stop.'; len = len.'; baseangle = baseangle.'; tipangle = tipangle.'; wid = wid.'; page = page.'; crossdir = crossdir.'; ends = ends.'; linewidth = linewidth.'; linestyle = linestyle.'; facecolor = facecolor.'; edgecolor = edgecolor.'; fromline = fromline.'; ax = ax.'; oldlinewidth = oldlinewidth.'; oldlinestyle = oldlinestyle.'; oldedgecolor = oldedgecolor.'; oldfacecolor = oldfacecolor.'; % given x, a 3xN matrix of points in 3-space; % want to convert to X, the corresponding 4xN 2-space matrix % % tmp1=[(x-axm)./axr; ones(1,size(x,1))]; % if (oneax), X=T*tmp1; % else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; % tmp2=zeros(4,4*N); tmp2(:)=tmp1(:); % X=zeros(4,N); X(:)=sum(tmp2)'; end; % X = X ./ (X(:,4)*ones(1,4)); % for all points with start==stop, start=stop-(verysmallvalue)*(up-direction); ii = find(all(start==stop)); if (all(size(ii))), % find an arrowdir vertical on screen and perpendicular to viewer % transform to 2-D tmp1 = [(stop(:,ii)-axm(:,ii))./axr(:,ii);ones(1,length(ii))]; if (oneax), twoD=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); twoD=zeros(4,length(ii)); twoD(:)=sum(tmp2)'; end; twoD=twoD./(ones(4,1)*twoD(4,:)); % move the start point down just slightly tmp1 = twoD + [0;-1/1000;0;0]*(limrange(2,ii)./ap(2,ii)); % transform back to 3-D if (oneax), threeD=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); threeD=zeros(4,length(ii)); threeD(:)=sum(tmp2)'; end; start(:,ii) = (threeD(1:3,:)./(ones(3,1)*threeD(4,:))).*axr(:,ii)+axm(:,ii); end; % compute along-arrow points % transform Start points tmp1=[(start-axm)./axr;ones(1,narrows)]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); X0=zeros(4,narrows); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % transform Stop points tmp1=[(stop-axm)./axr;ones(1,narrows)]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); Xf=zeros(4,narrows); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute pixel distance between points D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*(ap./limrange)).^2)); % compute and modify along-arrow distances len1 = len; len2 = len - (len.*tan(tipangle/180*pi)-wid/2).*tan((90-baseangle)/180*pi); slen0 = zeros(1,narrows); slen1 = len1 .* ((ends==2)|(ends==3)); slen2 = len2 .* ((ends==2)|(ends==3)); len0 = zeros(1,narrows); len1 = len1 .* ((ends==1)|(ends==3)); len2 = len2 .* ((ends==1)|(ends==3)); % for no start arrowhead ii=find((ends==1)&(D<len2)); if (all(size(ii))), slen0(ii) = D(ii)-len2(ii); end; % for no end arrowhead ii=find((ends==2)&(D<slen2)); if (all(size(ii))), len0(ii) = D(ii)-slen2(ii); end; len1 = len1 + len0; len2 = len2 + len0; slen1 = slen1 + slen0; slen2 = slen2 + slen0; % compute stoppoints tmp1=X0.*(ones(4,1)*(len0./D))+Xf.*(ones(4,1)*(1-len0./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; stoppoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute tippoints tmp1=X0.*(ones(4,1)*(len1./D))+Xf.*(ones(4,1)*(1-len1./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; tippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute basepoints tmp1=X0.*(ones(4,1)*(len2./D))+Xf.*(ones(4,1)*(1-len2./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; basepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute startpoints tmp1=X0.*(ones(4,1)*(1-slen0./D))+Xf.*(ones(4,1)*(slen0./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; startpoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute stippoints tmp1=X0.*(ones(4,1)*(1-slen1./D))+Xf.*(ones(4,1)*(slen1./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; stippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute sbasepoints tmp1=X0.*(ones(4,1)*(1-slen2./D))+Xf.*(ones(4,1)*(slen2./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; sbasepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute cross-arrow directions for arrows with NormalDir specified if (any(imag(crossdir(:))~=0)), ii = find(any(imag(crossdir)~=0)); crossdir(:,ii) = cross((stop(:,ii)-start(:,ii))./axr(:,ii), ... imag(crossdir(:,ii))).*axr(:,ii); end; % compute cross-arrow directions basecross = crossdir + basepoint; tipcross = crossdir + tippoint; sbasecross = crossdir + sbasepoint; stipcross = crossdir + stippoint; ii = find(all(crossdir==0)|any(isnan(crossdir))); if (all(size(ii))), numii = length(ii); % transform start points tmp1 = [basepoint(:,ii) tippoint(:,ii) sbasepoint(:,ii) stippoint(:,ii)]; tmp1 = (tmp1-axm(:,[ii ii ii ii])) ./ axr(:,[ii ii ii ii]); tmp1 = [tmp1; ones(1,4*numii)]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); X0=zeros(4,4*numii); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % transform stop points tmp1 = [(2*stop(:,ii)-start(:,ii)-axm(:,ii))./axr(:,ii);ones(1,numii)]; tmp1 = [tmp1 tmp1 tmp1 tmp1]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xf=zeros(4,4*numii); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute perpendicular directions pixfact = ((limrange(1,ii)./limrange(2,ii)).*(ap(2,ii)./ap(1,ii))).^2; pixfact = [pixfact pixfact pixfact pixfact]; pixfact = [pixfact;1./pixfact]; [dummyval,jj] = max(abs(Xf(1:2,:)-X0(1:2,:))); jj1 = ((1:4)'*ones(1,length(jj))==ones(4,1)*jj); jj2 = ((1:4)'*ones(1,length(jj))==ones(4,1)*(3-jj)); jj3 = jj1(1:2,:); Xp = X0; Xp(jj2) = X0(jj2) + ones(sum(jj2(:)),1); Xp(jj1) = X0(jj1) - (Xf(jj2)-X0(jj2))./(Xf(jj1)-X0(jj1)) .* pixfact(jj3); % inverse transform the cross points if (oneax), Xp=invT*Xp; else, tmp1=[Xp;Xp;Xp;Xp]; tmp1=invT(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xp=zeros(4,4*numii); Xp(:)=sum(tmp2)'; end; Xp=(Xp(1:3,:)./(ones(3,1)*Xp(4,:))).*axr(:,[ii ii ii ii])+axm(:,[ii ii ii ii]); basecross(:,ii) = Xp(:,0*numii+(1:numii)); tipcross(:,ii) = Xp(:,1*numii+(1:numii)); sbasecross(:,ii) = Xp(:,2*numii+(1:numii)); stipcross(:,ii) = Xp(:,3*numii+(1:numii)); end; % compute all points % compute start points axm11 = [axm axm axm axm axm axm axm axm axm axm axm]; axr11 = [axr axr axr axr axr axr axr axr axr axr axr]; st = [stoppoint tippoint basepoint sbasepoint stippoint startpoint stippoint sbasepoint basepoint tippoint stoppoint]; tmp1 = (st - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); X0=zeros(4,11*narrows); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % compute stop points tmp1 = ([start tipcross basecross sbasecross stipcross stop stipcross sbasecross basecross tipcross start] ... - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); Xf=zeros(4,11*narrows); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute lengths len0 = len.*((ends==1)|(ends==3)).*tan(tipangle/180*pi); slen0 = len.*((ends==2)|(ends==3)).*tan(tipangle/180*pi); le = [zeros(1,narrows) len0 wid/2 wid/2 slen0 zeros(1,narrows) -slen0 -wid/2 -wid/2 -len0 zeros(1,narrows)]; aprange = ap./limrange; aprange = [aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange]; D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*aprange).^2)); Dii=find(D==0); if (all(size(Dii))), D=D+(D==0); le(Dii)=zeros(1,length(Dii)); end; %should fix DivideByZero warnings tmp1 = X0.*(ones(4,1)*(1-le./D)) + Xf.*(ones(4,1)*(le./D)); % inverse transform if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[invT invT invT invT invT invT invT invT invT invT invT].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,11*narrows); tmp3(:)=sum(tmp2)'; end; pts = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)) .* axr11 + axm11; % correct for ones where the crossdir was specified ii = find(~(all(crossdir==0)|any(isnan(crossdir)))); if (all(size(ii))), D1 = [pts(:,1*narrows+ii)-pts(:,9*narrows+ii) ... pts(:,2*narrows+ii)-pts(:,8*narrows+ii) ... pts(:,3*narrows+ii)-pts(:,7*narrows+ii) ... pts(:,4*narrows+ii)-pts(:,6*narrows+ii) ... pts(:,6*narrows+ii)-pts(:,4*narrows+ii) ... pts(:,7*narrows+ii)-pts(:,3*narrows+ii) ... pts(:,8*narrows+ii)-pts(:,2*narrows+ii) ... pts(:,9*narrows+ii)-pts(:,1*narrows+ii)]/2; ii = ii'*ones(1,8) + ones(length(ii),1)*[1:4 6:9]*narrows; ii = ii(:)'; pts(:,ii) = st(:,ii) + D1; end; % readjust for log scale on axes tmp1=[xyzlog xyzlog xyzlog xyzlog xyzlog xyzlog xyzlog xyzlog xyzlog xyzlog xyzlog]; ii = find(tmp1(:)); if (all(size(ii))), pts(ii)=10.^pts(ii); end; % compute the x,y,z coordinates of the patches; ii = narrows*(0:10)'*ones(1,narrows) + ones(11,1)*(1:narrows); ii = ii(:)'; x = zeros(11,narrows); y = zeros(11,narrows); z = zeros(11,narrows); x(:) = pts(1,ii)'; y(:) = pts(2,ii)'; z(:) = pts(3,ii)'; % do the output if (nargout<=1), % % create or modify the patches p = (linestyle(1,:)=='-')&(linestyle(2,:)==' '); if (all(size(oldh))), H = oldh; else, fromline = p; H = zeros(narrows,1); end; % % new patches ii = find(p&fromline); if (all(size(ii))), if (all(size(oldh))), delete(oldh(ii)); end; H(ii) = patch(x(:,ii),y(:,ii),z(:,ii),zeros(11,length(ii)),'Tag',ArrowTag); end; % % new lines ii = find((~p)&(~fromline)); if (all(size(ii))), if (all(size(oldh))), delete(oldh(ii)); end; H(ii) = line(x(:,ii),y(:,ii),z(:,ii),'Tag',ArrowTag); end; % % additional properties for k=1:narrows, s = 'set(H(k),''UserData'',ud(k,:)'; if (p(k)~=fromline(k)), % modifying the data s = [s ',''XData'',x(:,k)'',''YData'',y(:,k)'',''ZData'',z(:,k)''']; end; if ((~isnan(linewidth(k)))&(linewidth(k)~=oldlinewidth(k))), s=[s ',''LineWidth'',linewidth(k)']; end; if (p(k)), % a patch if (any(edgecolor(:,k)~=oldedgecolor(:,k))|(fromline(k))), if (edgecolor(1,k)==inf), s=[s ',''EdgeColor'',''flat''']; elseif (edgecolor(1,k)==-inf), s=[s ',''EdgeColor'',''none''']; else, s=[s ',''EdgeColor'',edgecolor(:,k)''']; end; end; if (any(facecolor(:,k)~=oldfacecolor(:,k))|(fromline(k))), if (facecolor(1,k)==inf), s=[s ',''FaceColor'',''flat''']; elseif (facecolor(1,k)==-inf), s=[s ',''FaceColor'',''none''']; else, s=[s ',''FaceColor'',facecolor(:,k)''']; end; end; else, % a line s = [s ',''LineStyle'',''' deblank(char(linestyle(:,k)')) '''']; if (any(facecolor(:,k)~=oldfacecolor(:,k))|any(edgecolor(:,k)~=oldedgecolor(:,k))), % a line if (isinf(edgecolor(1,k))&(facecolor(1,k)~=-inf)), s = [s ',''Color'',facecolor(:,k)''']; else, s = [s ',''Color'',edgecolor(:,k)''']; end; end; end; eval([s extraprops ');']); end; % set the output if (nargout>0), h=H; end; else, % don't create the patch, just return the data h=x; yy=y; zz=z; end;
github
lcnbeapp/beapp-master
runpca.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/runpca.m
2,702
utf_8
6fff3a9e04e75993c00583d5969ea9ec
% runpca() - perform principal component analysis (PCA) using singular value % decomposition (SVD) using Matlab svd() or svds() % >> inv(eigvec)*data = pc; % Usage: % >> [pc,eigvec,sv] = runpca(data); % >> [pc,eigvec,sv] = runpca(data,num,norm) % % Inputs: % data - input data matrix (rows are variables, columns observations) % num - number of principal comps to return {def|0|[] -> rows in data} % norm - 1/0 = do/don't normalize the eigvec's to be equivariant % {def|0 -> no normalization} % Outputs: % pc - the principal components, i.e. >> inv(eigvec)*data = pc; % eigvec - the inverse weight matrix (=eigenvectors). >> data = eigvec*pc; % sv - the singular values (=eigenvalues) % % Author: Colin Humphries, CNL / Salk Institute, 1997 % % See also: runica() % Copyright (C) Colin Humphries, CNL / Salk Institute, Aug, 1997 % % 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/31/00 renamed runpca() and improved usage message -sm % 01-25-02 reformated help & license, added links -ad function [pc,M,S] = runpca(data,N,norm) BIG_N = 50; % for efficiency, switch to sdvs() when BIG_N<=N or N==rows if nargin < 1 help runpca return end rows = size(data,1); % remove the mean for i = 1:rows data(i,:) = data(i,:) - mean(data(i,:)); end if nargin < 3 norm = 0; elseif isempty(norm) norm = 0; end if nargin < 2 N = 0; end if isempty(N) N = 0; end if N == 0 | N == rows N = rows; [U,S,V] = svd(data',0); % performa SVD if norm == 0 pc = U'; M = (S*V')'; else % norm pc = (U*S)'; M = V; end else if N > size(data,1) error('N must be <= the number of rows in data.') end %if N <= BIG_N | N == rows %[U,S,V] = svd(data',0); %else [U,S,V] = svds(data',N); %end if norm == 0 pc = U'; M = (S*V')'; else % norm pc = (U*S)'; M = V; end %if N > BIG_N & N < rows %pc = pc(1:N,:); %M = M(:,1:N); %end end %S = diag(S(1:N,1:N));
github
lcnbeapp/beapp-master
dendplot.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/dendplot.m
2,407
utf_8
b7fd4f2ab62ff9c468fbca95378a2da7
% DENDPLOT: Plots a dendrogram given a topology matrix. % % Usage: dendplot(topology,{labels},{fontsize}) % % 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 % labels = optional [n x q] matrix of group labels for dendrogram. % fontsize = optional font size for labels [default = 10]. % % RE Strauss, 5/27/98 % 8/20/99 - miscellaneous changes for Matlab v5 function dendplot(topology,labels,fontsize) if (nargin<2) labels = []; end; if (nargin < 3) fontsize = []; end; if (isempty(fontsize)) % Default font size for labels fontsize = 10; end; r = size(topology,1); n = r+1; % Number of taxa links = dendhier([],topology,n-1); % Find dendrogram links (branches) otu_indx = find(links(:,1)<=n); % Get sequence of OTUs otus = links(otu_indx,1); y = zeros(2*n-1,1); % Y-coords for plot y(otus) = 0.5:(n-0.5); for i = 1:(n-1) y(topology(i,3)) = mean([y(topology(i,1)),y(topology(i,2))]); end; clf; % Begin plot hold on; for i = 1:(2*n-2) % Horizontal lines desc = links(i,1); anc = links(i,2); X = [links(i,3) links(i,4)]; Y = [y(desc) y(desc)]; plot(X,Y,'k'); end; for i = (n+1):(2*n-1) % Vertical lines indx = find(links(:,2)==i); X = [links(indx,4)]; Y = [y(links(indx(1),1)) y(links(indx(2),1))]; plot(X,Y,'k'); end; maxdist = max(links(:,4)); for i = 1:n % OTU labels if (~isempty(labels)) h = text(-.02*maxdist,y(i),labels(i,:)); % For OTUs on right set(h,'fontsize',fontsize); else h = text(-.02*maxdist,y(i),num2str(i)); % For OTUs on right set(h,'fontsize',fontsize); % text(-.06*maxdist,y(i),num2str(i)); % For UTOs on left end; end; axis([0 maxdist+0.03*maxdist 0 n]); % Axes axis('square'); set(gca,'Ytick',[]); % Suppress y-axis labels and tick marks set(gca,'Ycolor','w'); % Make y-axes invisible set(gca,'Xdir','reverse'); % For OTUs on right hold off; return;
github
lcnbeapp/beapp-master
qrtimax.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/qrtimax.m
4,605
utf_8
64e79c295baa267e2aacf1bcca2c6769
% qrtimax() - perform Quartimax rotation of rows of a data matrix. % % Usage: >> [Q,B] = qrtimax(data); % >> [Q,B] = qrtimax(data,tol,'[no]reorder'); % % Inputs: % data - input matrix % tol - the termination tolerance {default: 1e-4} % noreorder - rotate without negation/reordering % % Outputs: % B - B=Q*A the Quartimax rotation of A % Q - the orthogonal rotation matrix % % Author: Sigurd Enghoff, CNL / Salk Institute, 6/18/98 % 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: Jack O. Nehaus and Charles Wrigley (1954) % The Quartimax Method: an analytic approach to orthogonal % simple structure, Br J Stat Psychol, 7:81-91. % 01-25-02 reformated help & license -ad function [Q,B] = qrtimax(A,tol,reorder) if nargin < 1 help qrtimax return end DEFAULT_TOL = 1e-4; MAX_ITERATIONS = 50; if nargin < 3 reorder = 1; elseif isempty(reorder) | reorder == 0 reorder = 1; % set default else reorder = strcmp('reorder',reorder); end if nargin < 2 eps1 = DEFAULT_TOL; eps2 = DEFAULT_TOL; else eps1 = tol; eps2 = tol; end % Do unto 'Q' what is done to A Q = eye(size(A,1)); % Compute the cross-products of the rows of the squared loadings, % i.e. the cost function. % % --- --- % \ \ 2 2 % / / f f % --- --- ij ik % i j<k % % See reference, p. 85, line 3 B = tril((A.^2)*(A.^2)'); crit = [sum(sum(B)) - trace(B) , 0]; % Initialize variables inoim = 0; iflip = 1; ict = 0; % Main iterative loop: keep looping while no two consecutive trials % satisfy tolerance constraint AND less than MAX_ITERATIONS trials % AND one or more rotations were performed during last trial. while inoim < 2 & ict < MAX_ITERATIONS & iflip, iflip = 0; % Run through all combinations of j and k for j = 1:size(A,1)-1, for k = j+1:size(A,1), % % --- --- % \ 2 2 \ 2 2 2 2 2 % fnum = 4 / [f f (f - f )] , fden = / [(f - f ) - 4 f f ] % --- ki kj ki kj --- ki kj ki kj % k k % % See equation (5) u = A(j,:) .^ 2 - A(k,:) .^2; v = 2 * A(j,:) .* A(k,:); c = sum(u .^ 2 - v .^ 2); d = sum(u .* v); fden = c; fnum = 2 * d; % Skip rotation if angle is too small if abs(fnum) > eps1 * abs(fden) iflip = 1; angl = atan2(fnum, fden); % Set angle of rotation according to Table I if fnum > 0 if fden > 0 angl = .25 * angl; else angl = .25 * (pi - angl); end else if fden > 0 angl = .25 * (2 * pi - angl); else angl = .25 * (pi + angl); end end % Perform rotation tmp = cos(angl) * Q(j,:) + sin(angl) * Q(k,:); Q(k,:) = -sin(angl) * Q(j,:) + cos(angl) * Q(k,:); Q(j,:) = tmp; tmp = cos(angl) * A(j,:) + sin(angl) * A(k,:); A(k,:) = -sin(angl) * A(j,:) + cos(angl) * A(k,:); A(j,:) = tmp; end end end % Compute cost function. B = tril((A.^2)*(A.^2)'); crit = [sum(sum(B)) - trace(B) , crit(1)]; inoim = inoim + 1; ict = ict + 1; fprintf('#%d - crit = %g\n',ict,(crit(1)-crit(2))/crit(1)); % Check relative change of cost function (termination criterion). if (crit(1) - crit(2)) / crit(1) > eps2 inoim = 0; end end % Reorder and negate if required. Determine new row order based on % row norms and reorder accordingly. Negate those rows in which the % accumulated sum is negative. if reorder fprintf('Reordering rows...'); [fnorm index] = sort(sum(A'.^2)); Q = Q .* ((2 * (sum(A') > 0) - 1)' * ones(1, size(Q,2))); A = A .* ((2 * (sum(A') > 0) - 1)' * ones(1, size(A,2))); Q = Q(fliplr(index),:); A = A(fliplr(index),:); fprintf('\n'); else fprintf('Not reordering rows.\n'); end B=A;
github
lcnbeapp/beapp-master
matcorr.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/matcorr.m
5,853
utf_8
d0e3089eda2df7656eb20c1f476894f8
% matcorr() - 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). % % Usage: >> [corr,indx,indy,corrs] = matcorr(x,y,rmmean,method,weighting); % % Inputs: % x = first input matrix % y = matrix with same number of columns as x % % 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 % 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] = matcorr(x,y,rmmean,method,weighting) % if nargin < 2 | nargin > 5 help matcorr return end if nargin < 4 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>3 & 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 n~=q error('Rows in the two input matrices must be the same length.'); end if nargin < 3 | 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 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 > 4 && ~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
github
lcnbeapp/beapp-master
seemovie.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/seemovie.m
2,366
utf_8
e435662809faced2ec20372ec434b114
% seemovie() - see an EEG movie produced by eegmovie() % % Usage: >> seemovie(Movie,ntimes,Colormap) % % Inputs: % Movie = Movie matrix returned by eegmovie() % ntimes = Number of times to display {0 -> -10} % If ntimes < 0, movie will play forward|backward % Colormap = Color map returned by eegmovie() {0 -> default} % % Author: Scott Makeig & Colin Humphries, CNL / Salk Institute, 6/3/97 % % See also: eegmovie() % Copyright (C) 6/3/97 Scott Makeig & Colin Humphries, CNL / Salk Institute, La Jolla CA % % 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 % 10-31-97 changed test for user-defined colormap -ch & sm % 1-8-98 added '\n' at end, improved help msg -sm % 01-25-02 reformated help, added link -ad function seemovie(Movie,ntimes,Colormap) fps = 10; % projetion speed (requested frames per second) if nargin<1 help seemovie return end if nargin<3 Colormap = 0; end if nargin<2 ntimes = -10; % default to playing foward|backward endlessly end if ntimes == 0 ntimes = -10; end clf axes('Position',[0 0 1 1]); if size(Colormap,2) == 3 % if colormap user-defined colormap(Colormap) else colormap([jet(64);0 0 0]); % set up the default topoplot color map end if ntimes > 0, fprintf('Movie will play slowly once, then %d times faster.\n',ntimes); else fprintf('Movie will play slowly once, then %d times faster forwards and backwards.\n',-ntimes); end if abs(ntimes) > 7 fprintf(' Close figure to abort: '); end %%%%%%%%%%%%%%%%%%%%%%%% Show the movie %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% movie(Movie,ntimes,fps); %%%%%%%%%%%%%%%%%%%%%%%% The End %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if abs(ntimes) > 7 fprintf('\n'); end
github
lcnbeapp/beapp-master
abspeak.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/abspeak.m
2,026
utf_8
2258e70a7386f00bc23dd3f8620aa48b
% abspeak() - find peak amps/latencies in each row of a single-epoch data matrix % % Usage: % >> [amps,frames,signs] = abspeak(data); % >> [amps,frames,signs] = abspeak(data,frames); % % Inputs: % data - single-epoch data matrix % frames - frames per epoch in data {default|0 -> whole data} % % Outputs: % amps - amplitude array % frames - array of indexes % sign - sign array % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 1998 % Copyright (C) 1998 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-9-98 added frames arg -sm % 01-25-02 reformated help & license -ad function [amps,frames,signs]= abspeak(data,fepoch); if nargin < 1 help abspeak return end [chans,ftot] = size(data); if nargin < 2 fepoch = 0; end if fepoch == 0 fepoch = ftot; end epochs = floor(ftot/fepoch); if fepoch*epochs ~= ftot fprintf('abspeak(): frames arg does not divide data length.\n') return end amps = zeros(chans,epochs); frames = zeros(chans,epochs); signs = zeros(chans,epochs); for e=1:epochs for c=1:chans dat = abs(matsel(data,fepoch,0,c,e))'; [sdat,si] = sort(dat); amps(c,e) = dat(si(fepoch)); % abs value at peak frames(c,e) = si(fepoch); % peak frame signs(c,e) = sign(data(c,frames(c,e))); % sign at peak end end
github
lcnbeapp/beapp-master
eegplotgold.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/eegplotgold.m
12,958
utf_8
d4c4acff7303a59ede1e32c3911c3af7
% eegplotgold() - display EEG data in a clinical format % % Usage: % >> eegplotgold('dataname', samplerate, 'chanfile', 'title', yscaling, range) % % Inputs: % 'dataname' - quoted name of a desktop global variable (see Ex. below) % samplerate - EEG sampling rate in Hz (0 -> default 256 Hz) % 'chanfile' - file of channel info in topoplot() style % (0 -> channel numbers) % 'title' - plot title string (0 -> 'eegplotgold()') % yscaling - initial y scaling factor (0 - default is 300) % range - how many seconds to display in window (0 -> 10) % % Note: this version of eegplotgold() reguires that your data matrix % be defined as a global variable before running this routine. % % Example: >> global dataname % >> eegplotgold('dataname') % % Author: Colin Humphries, CNL, Salk Institute, La Jolla, 3/97 % % See also: eegplot(), eegplotold(), 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 % 4-4-97 shortened name to eegplotgold() -sm % 5-20-97 added read of icadefs.m for MAXEEGPLOTCHANS -sm % 8-10-97 Clarified chanfile type -sm % 01-25-02 reformated help & license, added links -ad %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = eegplotold(dataname, samplerate, channamefile, titleval, yscaling, range) eval (['global ',dataname]) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Define defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% icadefs; % set initial spacing eval(['DEFAULT_SPACING = max(max(',dataname,''')-min(',dataname,'''));']) % spacing_var/20 = microvolts/millimeter with 21 channels % for n channels: 21/n * spacing_var/20 = microvolts/mm % for clinical data. DEFAULT_SAMPLERATE = 256; % default rate in Hz. DEFAULT_PLOTTIME = 10; % default 10 second window DEFAULT_TITLE = 'eegplotgold()'; errorcode=0; % initialize error indicator %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Allow for different numbers of arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin < 6 PLOT_TIME = DEFAULT_PLOTTIME; else PLOT_TIME = range; end if nargin < 5 spacing_var = DEFAULT_SPACING; else spacing_var = yscaling; end if spacing_var == 0 spacing_var = DEFAULT_SPACING; end if nargin < 4 titleval = DEFAULT_TITLE; end if titleval == 0 titleval = DEFAULT_TITLE; end if nargin < 3 channamefile = 0; end if nargin < 2 samplerate = DEFAULT_SAMPLERATE; end if samplerate == 0, samplerate = DEFAULT_SAMPLERATE; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Define internal variables %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SAMPLE_RATE = samplerate; time = 0; eval(['[chans,frames] = size(',dataname,');']) %size of data matrix maxtime = frames / samplerate; %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; icadefs; % read MAXEEGPLOTCHANS from icadefs.m if errorcode==0, channames = fscanf(chid,'%s',[6 MAXEEGPLOTCHANS]); channames = channames'; [r c] = size(channames); for i=1:r for j=1:c if channames(i,j)=='.', channames(i,j)=' '; 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 Xlab = num2str(time); for j = 1:1:PLOT_TIME Q = num2str(time+j); Xlab = str2mat(Xlab, Q); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Set Graph Characteristics %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% figure; % plot a new figure fighandle = gcf; orient landscape % choose landscape printer mode hold on; set(gcf,'NumberTitle','off') if VERS >= 8.04 set(gcf,'Name',['EEGPLOTOLD #',num2str(fighandle.Number)]); else set(gcf,'Name',['EEGPLOTOLD #',num2str(gcf)]); end set (gca, 'xgrid', 'on') %Xaxis gridlines only set (gca, 'GridLineStyle','-') %Solid grid lines set (gca, 'XTickLabels', Xlab) %Use Xlab for tick labels set (gca, 'Box', 'on') set (gca, 'XTick', time*samplerate:1.0*samplerate:PLOT_TIME*samplerate) set (gca, 'Ytick', 0:spacing_var:chans*spacing_var) % ytickspacing on channels set (gca, 'TickLength', [0.001 0.001]) title(titleval) % title is titleval axis([0 PLOT_TIME*samplerate 0 (chans+1)*spacing_var]); % set axis values set (gca, 'YTickLabels', flipud(channames)) % write channel names %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot the selected EEG data epoch %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for i = 1:chans if (maxtime-time>PLOT_TIME) eval(['F = ',dataname,'(chans-i+1,(time*samplerate)+1:(time+PLOT_TIME*samplerate));']) else eval(['F = ',dataname,'(chans-i+1,(time*samplerate)+1:(maxtime*samplerate));']) end F = F - mean(F) + i*spacing_var; plot (F,'clipping','off') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot Scaling I %%%%%%%%%%%%%%%%%%%%%%%%%%%%% line([(PLOT_TIME+.3)*samplerate,(PLOT_TIME+.3)*samplerate],[1.5*spacing_var 2.5*spacing_var],'clipping','off','color','w') line([(PLOT_TIME+.3)*samplerate-10,(PLOT_TIME+.3)*samplerate+10],[2.5*spacing_var,2.5*spacing_var],'clipping','off','color','w') line([(PLOT_TIME+.3)*samplerate-10,(PLOT_TIME+.3)*samplerate+10],[1.5*spacing_var,1.5*spacing_var],'clipping','off','color','w') text((PLOT_TIME+.5)*samplerate,2*spacing_var,num2str(round(spacing_var)),'clipping','off') %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % User Control Routines %%%%%%%%%%%%%%%%%%%%%%%%%%%%% slider_position = [.125 .030 .3 .024]; % position of user-controlled slider edit_position = [.65 .025 .1 .05]; % position of edit box slider_position2 = [.8 .03 .1 .024]; b1_position = [.175 .022 .09 .047]; b2_position = [.29 .022 .09 .047]; b3_position = [.125 .022 .045 .047]; b4_position = [.385 .022 .045 .047]; Max_Space = 1; Min_Space = DEFAULT_SPACING*2; % User_Data_Mat = [data;zeros(1,length(data))]; axhandle = gca; User_Data_Mat(1) = samplerate; User_Data_Mat(2) = PLOT_TIME; User_Data_Mat(3) = spacing_var; User_Data_Mat(4) = time; User_Data_Mat(5) = maxtime; User_Data_Mat(6) = axhandle; User_Data_Mat(7) = 1; % color User_Data_Mat(8) = frames; User_Data_Mat(9) = chans; User_Data_Mat(12) = 1; tstring1 = 'data1973 = get(gcf,''UserData'');'; tstring2 = 'set(gcf,''UserData'',data1973);'; tstring3 = 'eegdrawgv(gcf);'; TIMESTRING = [tstring1,'if (data1973(4)-data1973(2))<0;','data1973(4) = 0;','else;','data1973(4) = data1973(4) - data1973(2);','end;',tstring2,tstring3,'clear data1973']; hb = uicontrol('Style','PushButton','Units','Normalized','position',b1_position,'String','PREV','Callback',TIMESTRING); TIMESTRING = [tstring1,'if (data1973(4)+data1973(2))>=data1973(5);','data1973(4)=data1973(4);','else;','data1973(4) = data1973(4) + data1973(2);','end;',tstring2,tstring3,'clear data1973']; hf = uicontrol('Style','PushButton','Units','Normalized','position',b2_position,'String','NEXT','Callback',TIMESTRING); TIMESTRING = [tstring1,'if (data1973(4)-1)<0;','data1973(4) = 0;','else;','data1973(4) = data1973(4) - 1;','end;',tstring2,tstring3,'clear data1973']; hbos = uicontrol('Style','PushButton','Units','Normalized','position',b3_position,'String','<<','Callback',TIMESTRING); TIMESTRING = [tstring1,'if (data1973(4)+1)>=data1973(5);','data1973(4)=data1973(4);','else;','data1973(4) = data1973(4) + 1;','end;',tstring2,tstring3,'clear data1973']; hfos = uicontrol('Style','PushButton','Units','Normalized','position',b4_position,'String','>>','Callback',TIMESTRING); TIMESTRING = [tstring1,'time1973 = get(gco,''string'');','time1973 = str2num(time1973);','data1973(4) = time1973;',tstring2,tstring3,'clear time1973 data1973']; w=uicontrol('style','edit','units','normalized','HorizontalAlignment','left','position',edit_position,'UserData',axhandle,'callback',TIMESTRING); TIMESTRING = [tstring1,'data1973(3) = get(gco,''value'');',tstring2,tstring3,'clear time1973 data1973']; u=uicontrol('style','slider','units','normalized','position',slider_position2,'Max',Max_Space,'Min',Min_Space,'value',spacing_var,'UserData',axhandle,'callback',TIMESTRING); %%%%%%%%%%%%%%%%%%%%%%%%% %Set up ui menus %%%%%%%%%%%%%%%%%%%%%%%%% %Window menu: TIMESTRING = ['fighand1973 = gcf;','delete(fighand1973);','clear fighand1973;']; fm1 = uimenu('Label','Window'); fm2 = uimenu(fm1,'Label','Close ','UserData',fighandle,'Callback',TIMESTRING); %Display menu: TIMESTRING = [tstring1,'out1973 = gettext(''Input new windowlength(sec).'');','if isempty(out1973);','out1973 = 0;','else;','data1973(2) = str2num(out1973);',tstring2,tstring3,'end;','clear data1973 out1973']; dm1 = uimenu('Label','Display'); dm2 = uimenu(dm1,'Label',' Window Length','Interruptible','on','Callback',TIMESTRING); dm3 = uimenu(dm1,'Label',' Color'); TIMESTRING = [tstring1,'data1973(7) = 1;',tstring2,tstring3,'clear data1973;']; dm4 = uimenu(dm3,'Label','Yellow ','UserData',axhandle,'Interruptible','on','Callback',TIMESTRING); TIMESTRING = [tstring1,'data1973(7) = 2;',tstring2,tstring3,'clear data1973;']; dm5 = uimenu(dm3,'Label','White ','UserData',axhandle,'Interruptible','on','Callback',TIMESTRING); TIMESTRING = ['label1973 = gettext(''Enter new title.'');','if isempty(label1973);','label1973 = 0;','else;','title(label1973);','end;','clear label1973;']; dm6 = uimenu(dm1,'Label','Title ','Interruptible','on','Callback',TIMESTRING); TIMESTRING = [tstring1,'Check1973 = get(data1973(10),''checked'');','if (Check1973(1:2) == ''on'');','set(data1973(10),''Checked'',''off'');','set(data1973(6),''XGrid'',''off'');','else;','set(data1973(10),''Checked'',''on'');','set(data1973(6),''XGrid'',''on'');','end;','clear data1973 Check1973;']; dm7 = uimenu(dm1,'Label','Grid','Checked','on','Callback',TIMESTRING); User_Data_Mat(10) = dm7; TIMESTRING = [tstring1,'Check1973 = get(data1973(11),''checked'');','if (Check1973(1:2) == ''on'');','set(data1973(11),''Checked'',''off'');','data1973(12)= 0;','else;','set(data1973(11),''Checked'',''on'');','data1973(12) = 1;','end;',tstring2,tstring3,'clear data1973 Check1973;']; dm8 = uimenu(dm1,'Label','Scaling I','Checked','on','Callback',TIMESTRING); User_Data_Mat(11) = dm8; %Settings menu: sm1 = uimenu('Label','Settings'); TIMESTRING = [tstring1,'Srate1973 = gettext(''Enter new samplerate'');','if isempty(Srate1973);','Srate1973 = 0;','else;','data1973(1) = str2num(Srate1973);','data1973(5) = data1973(8)/data1973(1);','data1973(4) = 0;',tstring2,tstring3,'end;','clear Srate1973 data1973']; sm2 = uimenu(sm1,'Label','Samplerate','Interruptible','on','Callback',TIMESTRING); %Electrodes menu: em1 = uimenu('Label','Electrodes'); TIMESTRING = [tstring1,'ChanNamefile1973 = gettext(''Enter Electrode file to load.'');','if isempty(ChanNamefile1973);','ChanNamefile1973=0;','else;','ChanNames1973 = loadelec(ChanNamefile1973);','set(data1973(6),''YTickLabels'',flipud(ChanNames1973));','end;','clear data1973 ChanNamefile1973 ChanNames1973']; em2 = uimenu(em1,'Label','Load Electrode File ','Interruptible','on','Callback',TIMESTRING); TIMESTRING = [tstring1,'ChanNames1973 = makeelec(data1973(9));','if isempty(ChanNames1973);','ChanNames1973=0;','else;','set(data1973(6),''YTickLabels'',flipud(ChanNames1973));','end;','clear data1973 ChanNames1973']; em3 = uimenu(em1,'Label','Make Electrode File ','Interruptible','on','Callback',TIMESTRING); set(axhandle,'UserData',dataname) set(fighandle,'UserData',User_Data_Mat)
github
lcnbeapp/beapp-master
makehelpfiles.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/makehelpfiles.m
4,318
utf_8
8a0860d1b106b9754aedcaed8ace4442
% makehelpfiles() - generate function help pages % % Usage: % >> makehelpfiles(list); % % Input: % 'folder' - [string] folder name to process % 'outputfile' - [string] file in which to write the help % 'title' - [string] title for the help % % Author: Arnaud Delorme, UCSD, 2013 % % Example: Generate EEGLAB help menus for adminfunc folder % makehelpfiles('folder', 'adminfunc' ,'title', 'Admin functions', 'outputfile','adminfunc/eeg_helpadmin.m' ); % makehelpfiles('folder', 'guifunc' ,'title', 'Graphic interface builder functions', 'outputfile','adminfunc/eeg_helpgui.m' ); % makehelpfiles('folder', 'miscfunc' ,'title', 'Miscelaneous functions not used by EEGLAB graphic interface', 'outputfile','adminfunc/eeg_helpmisc.m' ); % makehelpfiles('folder', 'popfunc' ,'title', 'EEGLAB graphic interface functions', 'outputfile','adminfunc/eeg_helppop.m' ); % makehelpfiles('folder', 'sigprocfunc' ,'title', 'EEGLAB signal processing functions', 'outputfile','adminfunc/eeg_helpsigproc.m' ); % makehelpfiles('folder', 'statistics' ,'title', 'EEGLAB statistics functions', 'outputfile','adminfunc/eeg_helpstatistics.m' ); % makehelpfiles('folder', 'studyfunc' ,'title', 'EEGLAB group processing (STUDY) functions', 'outputfile','adminfunc/eeg_helpstudy.m' ); % makehelpfiles('folder', 'timefreqfunc','title', 'EEGLAB time-frequency functions', 'outputfile','adminfunc/eeg_helptimefreq.m' ); % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 2002 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function makehelpfiles( varargin ); if nargin < 1 help makehelpfiles; return; end; opt = finputcheck( varargin, { 'folder' 'string' { } ''; 'outputfile' 'string' { } ''; 'title' 'string' { } '' }, 'makehelpfiles'); if isstr(opt), error(opt); end; if isempty(opt.folder), error('You need to specify a folder'); end; if isempty(opt.outputfile), error('You need to specify an output file'); end; fo = fopen( opt.outputfile, 'w'); if ~isempty(opt.title) fprintf(fo, '%%%s (%s folder):\n', opt.title, opt.folder); else fprintf(fo, '%% *Content of %s folder:*\n', opt.folder); end; dirContent = dir(fullfile(opt.folder, '*.m')); dirContent = { dirContent.name }; for iFile = 1:length(dirContent) fileName = dirContent{iFile}; fidTmp = fopen(fullfile(opt.folder, fileName), 'r'); firstLine = fgetl(fidTmp); % get help from the first line if isempty(firstLine) || firstLine(1) ~= '%' firstLine = fgetl(fidTmp); end; fclose(fidTmp); if isempty(firstLine) || firstLine(1) ~= '%' firstLineText = 'No help information'; else indexMinus = find(firstLine == '-'); if ~isempty(indexMinus) firstLineText = deblank(firstLine(indexMinus(1)+1:end)); else firstLineText = deblank(firstLine(2:end)); end; if isempty(firstLineText), firstLineText = 'No help information'; end; if firstLineText(1) == ' ', firstLineText(1) = []; end; if firstLineText(1) == ' ', firstLineText(1) = []; end; if firstLineText(1) == ' ', firstLineText(1) = []; end; firstLineText(1) = upper(firstLineText(1)); if firstLineText(end) ~= '.', firstLineText = [ firstLineText '...' ]; end; end; refFunction = sprintf('<a href="matlab:helpwin %s">%s</a>', fileName(1:end-2), fileName(1:end-2)); fprintf(fo, '%% %-*s - %s\n', 50+length(fileName(1:end-2)), refFunction, firstLineText); end; fclose( fo );
github
lcnbeapp/beapp-master
gauss2d.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/gauss2d.m
2,336
utf_8
eb62296c929c63d59753f67dac83f70d
% gauss2d() - generate a 2-dimensional gaussian matrix % % Usage: % >> [ gaussmatrix ] = gauss2d( rows, columns, ... % sigmaR, sigmaC, peakR, peakC, mask) % % Example: % >> imagesc(gauss2d(50, 50)); % image a size (50,50) 2-D gaussian matrix % % Inputs: % rows - number of rows in matrix % columns - number of columns in matrix % sigmaR - width of standard deviation in rows (default: rows/5) % sigmaC - width of standard deviation in columns (default: columns/5) % peakR - location of the peak in each row (default: rows/2) % peakC - location of the peak in each column (default: columns/2) % mask - (0->1) portion of the matrix to mask with zeros (default: 0) % % Ouput: % gaussmatrix - 2-D gaussian matrix % % 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 mat = gauss2d( sizeX, sizeY, sigmaX, sigmaY, meanX, meanY, cut); if nargin < 2 help gauss2d return; end; if nargin < 3 sigmaX = sizeX/5; end; if nargin < 4 sigmaY = sizeY/5; end; if nargin < 5 meanX = (sizeX+1)/2; end; if nargin < 6 meanY = (sizeY+1)/2; end; if nargin < 7 cut = 0; end; X = linspace(1, sizeX, sizeX)'* ones(1,sizeY); Y = ones(1,sizeX)' * linspace(1, sizeY, sizeY); %[-sizeX/2:sizeX/2]'*ones(1,sizeX+1); %Y = ones(1,sizeY+1)' *[-sizeY/2:sizeY/2]; mat = exp(-0.5*( ((X-meanX)/sigmaX).*((X-meanX)/sigmaX)... +((Y-meanY)/sigmaY).*((Y-meanY)/sigmaY)))... /((sigmaX*sigmaY)^(0.5)*pi); if cut > 0 maximun = max(max(mat))*cut; I = find(mat < maximun); mat(I) = 0; end; return;
github
lcnbeapp/beapp-master
logimagesc.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/logimagesc.m
3,574
utf_8
343cd485721e4ef9c77204704ae0180c
% logimagesc() - make an imagesc(0) plot with log y-axis values (ala semilogy()) % % Usage: >> [logfreqs,dataout] = logimagesc(times,freqs,data); % % Input: % times = vector of x-axis values % freqs = vector of y-axis values % data = matrix of size (freqs,times) % % Optional Input: % plot = ['on'|'off'] plot image or return output (default 'on'). % % Note: Entering text() onto the image requires specifying (x,log(y)). % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 4/2000 % Copyright (C) 4/2000 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 % 08-07-00 made ydir normal -sm % 01-25-02 reformated help & license -ad function [lgfreqs,datout, h, yt, yl] = logimagesc(times,freqs,data,varargin) if nargin < 1 help logimagesc; return end; if size(data,1) ~= length(freqs) fprintf('logfreq(): data matrix must have %d rows!\n',length(freqs)); datout = data; return end if size(data,2) ~= length(times) fprintf('logfreq(): data matrix must have %d columns!\n',length(times)); datout = data; return end if min(freqs)<= 0 fprintf('logfreq(): frequencies must be > 0!\n'); datout = data; return end try, icadefs; catch, warning('Using MATLAB default colormap'); end lfreqs = log(freqs); lgfreqs = linspace(lfreqs(1),lfreqs(end),length(lfreqs)); lgfreqs = lgfreqs(:); lfreqs = lfreqs(:); [mesht meshf] = meshgrid(times,lfreqs); try datout = griddata(mesht,meshf,double(data),times,lgfreqs); catch fprintf('error in logimagesc.m calling griddata.m, trying v4 method.'); datout = griddata(mesht,meshf,data,times,lgfreqs,'v4'); end datout(find(isnan(datout(:)))) = 0; if ~isempty(varargin) plot = varargin{2}; else plot = 'on'; end if strcmp(plot, 'on') imagesc(times,freqs,data); try colormap(DEFAULT_COLORMAP); catch, end; nt = ceil(min(freqs)); % new tick - round up min y to int ht = floor(max(freqs)); % high freq - round down yt=get(gca,'ytick'); yl=get(gca,'yticklabel'); h=imagesc(times,lgfreqs,datout); % plot the image set(gca,'ydir','normal') i = 0; yt = []; yl = cell(1,100); tickscale = 1.618; % log scaling power for frequency ticks while (nt*tickscale^i < ht ) yt = [yt log(round(nt*tickscale^i))]; yl{i+1}=int2str(round(nt*tickscale^i)); i=i+1; end if ht/(nt*tickscale^(i-1)) > 1.35 yt = [yt log(ht)]; yl{i+1} = ht; else i=i-1; end yl = {yl{1:i+1}}; set(gca,'ytick',yt); set(gca,'yticklabel',yl); % if nt > min(yt), % set(gca,'ytick',log([nt yt])); % set(gca,'yticklabel',{int2str(nt) yl}); % else % set(gca,'ytick',log([yt])); % set(gca,'yticklabel',{yl}); % end end
github
lcnbeapp/beapp-master
eucl.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/eucl.m
4,052
utf_8
d05e24c412ee9044fefe12a801a4f9aa
% EUCL: Calculates the euclidean distances among a set of points, or between a % reference point and a set of points, or among all possible pairs of two % sets of points, in P dimensions. Returns a single distance for two points. % % Syntax: dists = eucl(crds1,crds2) % % crds1 = [N1 x P] matrix of point coordinates. If N=1, it is taken to % be the reference point. % crds2 = [N2 x P] matrix of point coordinates. If N=1, it is taken to % be the reference point. % ----------------------------------------------------------------------- % dists = [N1 x N1] symmetric matrix of pairwise distances (if only crds1 % is specified); % [N1 x 1] col vector of euclidean distances (if crds1 & ref % are specified); % [1 x N2] row vector of euclidean distances (if ref & crds2 % are specified); % [N1 x N2] rectangular matrix of pairwise distances (if crds1 % & crds2 are specified); % [1 x 1] scalar (if crds1 is a [2 x P] matrix or ref1 & ref2 % are specified); % % RE Strauss, 5/4/94 % 10/28/95 - output row (rather than column) vector for the (reference % point)-(set of points) case; still outputs column vector for the % (set of points)-(reference point) case. % 10/30/95 - for double for-loops, put one matrix-col access in outer loop % to increase speed. % 10/12/96 - vectorize inner loop to increase speed. % 6/12/98 - allow for P=1. % 11/11/03 - initialize dists to NaN for error return. function dists = eucl(crds1,crds2) if nargin == 0, help eucl; return; end; dists = NaN; if (nargin < 2) % If only crds1 provided, [N,P] = size(crds1); if (N<2) error(' EUCL: need at least two points'); end; crds1 = crds1'; % Transpose crds dists = zeros(N,N); % Calculate pairwise distances for i = 1:N-1 c1 = crds1(:,i) * ones(1,N-i); if (P>1) d = sqrt(sum((c1-crds1(:,(i+1:N))).^2)); else d = abs(c1-crds1(:,(i+1:N))); end; dists(i,(i+1:N)) = d; dists((i+1:N),i) = d'; end; if (N==2) % Single distance for two points dists = dists(1,2); end; else % If crds1 & crds2 provided, [N1,P1] = size(crds1); [N2,P2] = size(crds2); if (P1~=P2) error(' EUCL: sets of coordinates must be of same dimension'); else P = P1; end; crds1 = crds1'; % Transpose crds crds2 = crds2'; if (N1>1 & N2>1) % If two matrices provided, dists = zeros(N1,N2); % Calc all pairwise distances between them for i = 1:N1 c1 = crds1(:,i) * ones(1,N2); if (P>1) d = sqrt(sum((c1-crds2).^2)); else d = abs(c1-crds2); end; dists(i,:) = d; end; end; if (N1==1 & N2==1) % If two vectors provided, dists = sqrt(sum((crds1-crds2).^2)); % Calc scalar end; if (N1>1 & N2==1) % If matrix & reference point provided, crds1 = crds1 - (ones(N1,1)*crds2')'; % Center points on reference point if (P>1) % Calc euclidean distances in P-space dists = sqrt(sum(crds1.^2))'; else dists = abs(crds1)'; end; end; % Return column vector if (N1==1 & N2>1) % If reference point & matrix provided, crds2 = crds2 - (ones(N2,1)*crds1')'; % Center points on reference point if (P>1) % Calc euclidean distances in P-space dists = sqrt(sum(crds2.^2)); else dists = abs(crds2); end; end; % Return row vector end; return;
github
lcnbeapp/beapp-master
uniquef.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/uniquef.m
2,819
utf_8
81584771d690f2251ea088c5ccfebb54
% UNIQUEF: Given a matrix containing group labels, returns a vector containing % a list of unique group labels, in the sequence found, and a % vector of corresponding frequencies of each group. % Optionally sorts the indices into ascending sequence. % % Note: it might be necessary to truncate ('de-fuzz') real numbers to % some arbitrary number of decimal positions (see TRUNCATE) before % finding unique values. % % Syntax: [value,freq,index] = uniquef(grp,sortflag) % % grp - matrix of a set of labels. % sortflag - boolean flag indicating that list of labels, and % corresponding frequencies, are to be so sorted % [default=0, =FALSE]. % ------------------------------------------------------------ % value - column vector of unique labels. % freq - corresponding absolute frequencies. % index - indices of the first observation having each value. % % RE Strauss, 6/5/95 % 6/29/98 - modified to return indices. % 1/25/00 - changed name from unique to uniquef to avoid conflict with % Matlab v5 function. function [value,freq,index] = uniquef(grp,sortflag) if (nargin < 2) sortflag = []; end; get_index = 0; if (nargout > 2) get_index = 1; end; if (isempty(sortflag)) sortflag = 0; end; tol = eps * 10.^4; grp = grp(:); % Convert input matrix to vector if (get_index) % Create vector of indices ind = [1:length(grp)]'; end; if (any([~isfinite(grp)])) % Remove NaN's and infinite values i = find(~isfinite(grp)); % from input vector and index vector grp(i) = []; if (get_index) ind(i) = []; end; end; value = []; freq = []; for i = 1:length(grp) % For each element of grp, b = (abs(value-grp(i)) < tol); % check if already in value list if (sum(b) > 0) % If so, freq(b) = freq(b) + 1; % increment frequency counter else % If not, value = [value; grp(i)]; % add to value list freq = [freq; 1]; % and initialize frequency counter end; end; if (sortflag) [value,i] = sort(value); freq = freq(i); end; if (get_index) nval = length(value); % Number of unique values index = zeros(nval,1); % Allocate vector of indices for v = 1:nval % For each unique value, i = find(grp == value(v)); % Find observations having value index(v) = ind(i(1)); % Save first end; end; return;
github
lcnbeapp/beapp-master
getipsph.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/getipsph.m
2,850
utf_8
d0e227ab4596c6de73b76d9f3bd83f99
% getipsph() - Compute "in place" (m by n) sphering or quasi-sphering matrix for an (n by t) % input data matrix. Quasi-sphering reduces dimensionality of the data, while % maintaining approximately the "original" positions of the axes. That is, % quasi-sphering "rotates back" as much as possible into the original channel % axes, versus simple PCA reduction to the principal subspace (i.e., projecting % the data onto a largest eigenvector basis). % Usage: % >> S = getipsph(x,m) % % Input: % x size [n,t] input n-channel data matrix % % Optional input: % m (int <= n) Reduce output dimensions to [n,m]. If m is not present, or m==n, % then the usual sphering matrix (the symmetric square root of the data % covariance matrix) is returned. {default: [], return usual sphering matrix). % Output: % % S size [m,n] (if m==n) sphering matrix, or (if m < n) quasi-sphering matrix % Example: % >> x = nrand(10,1000); % random (10,1000) matrix % >> S = getipsph(x,8); % return quasi-sphering matrix reducing dimension to 8 % >> d = S*x; % d is the quasi-sphered 8-dimensional data % % % % If ICA decomposition is performed on d, as >> [w] = runica(d,'sphering','off'); % % then the mixing matrix containing the 8 component maps in original channel % % coordinates is >> A = pinv(W*S); % where A is size [n,m] % % Author: Jason Palmer, SCCN / INC / UCSD, 2008 % Copyright (C) Jason Palmer, SCCN / INC / UCSD , La Jolla 2008 % % 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 S = getipsph(x,m) [n,N] = size(x); if nargin < 2 m = n; end if m>n help getipsph return end mn = mean(x,2); for i = 1:n x(i,:) = x(i,:) - mn(i); end Sxx = x*x'/N; Sxx = (Sxx+Sxx')/2; [U,D,V] = svd(Sxx); ds = diag(D); if m == n S = U * pinv(diag(sqrt(ds))) * U'; elseif m < n [sd,so] = sort(diag(Sxx),1,'descend'); [uv,sv,vv] = svd(U(so(1:m),1:m)); S = uv * vv' * pinv(diag(sqrt(ds(1:m)))) * U(:,1:m)'; else error('m must be less than or equal to n'); end
github
lcnbeapp/beapp-master
gauss3d.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/gauss3d.m
2,601
utf_8
8b9e654379dccd6f84b0036766f86da3
% gauss3d() - generate a 3-dimensional gaussian matrix % % Usage: % >> [ gaussmatrix ] = gauss2d( nX, nY, nZ); % >> [ gaussmatrix ] = gauss2d( nX, nY, nZ, ... % sigmaX, sigmaY, sigmaZ, ... % centerX, centerY, centerZ, mask) % % Example: % >> gauss3d(3,3,3); % generate a 3x3x3 gaussian matrix % % Inputs: % nX - number of values in first dimension % nY - number of values in second dimension % nZ - number of values in third dimension % sigmaX - width of standard deviation in first dim (default: nX/5) % sigmaY - width of standard deviation in second dim (default: nY/5) % sigmaZ - width of standard deviation in third dim (default: nZ/5) % centerX - location of center (default: nX/2) % centerY - location of center (default: nY/2) % centerZ - location of center (default: nZ/2) % mask - (0->1) percentage of low values in the matrix to mask % with zeros (default: 0 or none) % % Ouput: % gaussmatrix - 3-D gaussian matrix % % Author: Arnaud Delorme, 2009 % Copyright (C) 2009 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 mat = gauss3d( sizeX, sizeY, sizeZ, sigmaX, sigmaY, sigmaZ, meanX, meanY, meanZ, cut); if nargin < 2 help gauss2d return; end; if nargin < 4 sigmaX = sizeX/5; end; if nargin < 5 sigmaY = sizeY/5; end; if nargin < 6 sigmaZ = sizeZ/5; end; if nargin < 7 meanX = (sizeX+1)/2; end; if nargin < 8 meanY = (sizeY+1)/2; end; if nargin < 9 meanZ = (sizeZ+1)/2; end; if nargin < 10 cut = 0; end; [X,Y,Z] = ndgrid(1:sizeX,1:sizeY,1:sizeZ); mat = exp(-0.5*( ((X-meanX)/sigmaX).*((X-meanX)/sigmaX)... +((Y-meanY)/sigmaY).*((Y-meanY)/sigmaY)... +((Z-meanZ)/sigmaZ).*((Z-meanZ)/sigmaZ)))... /((sigmaX*sigmaY*sigmaZ)^(0.5)*pi); if cut > 0 maximun = max(mat(:))*cut; I = find(mat < maximun); mat(I) = 0; end; return;
github
lcnbeapp/beapp-master
means.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/means.m
2,133
utf_8
9692b1df9d31cb08b359424b637cfeff
% MEANS: Means, standard errors and variances. For column vectors, means(x) % returns the mean value. For matrices or row vectors, means(x) is a % row vector containing the mean value of each column. The basic % difference from the Matlab functions mean() and var() is for a row vector, % where means() returns the row vector instead of the mean value of the % elements of the row. Also allows for missing data, passed as NaNs. % % If an optional grouping vector is supplied, returns a vector of means % for each group in collating sequence. % % Usage: [M,stderr,V,grpids] = means(X,{grps}) % % X = [n x p] data matrix. % grps = optional [n x 1] grouping vector for k groups. % ----------------------------------------------------------------------- % M = [k x p] matrix of group means. % stderr = corresponding [k x 1] vector of standard errors of the means. % V = corresponding vector of variances. % grpids = corresponding vector of group identifiers, for multiple % groups. % % RE Strauss, 2/2/99 % 12/26/99 - added standard errors. % 10/19/00 - sort group-identifiers into collating sequence. % 12/21/00 - corrected problem with uninitialized 'fg' for single group. % 2/24/02 - added estimation of variances. % 10/15/02 - corrected documentation. function [M,stderr,V,grpids] = means(X,grps) if nargin == 0, help means; return; end; if (nargin < 2) grps = []; end; [n,p] = size(X); if (isempty(grps)) grps = ones(n,1); ug = 1; fg = n; k = 1; else [ug,fg] = uniquef(grps,1); k = length(ug); end; grpids = ug; M = zeros(k,p); stderr = zeros(k,p); for ik = 1:k ir = find(grps==ug(ik)); for c = 1:p x = X(ir,c); ic = find(isfinite(x)); if (isempty(ic)) M(ik,c) = NaN; stderr(ik,c) = NaN; else M(ik,c) = mean(x(ic)); s = std(x(ic)); stderr(ik,c) = s./sqrt(fg(ik)); V(ik,c) = s.^2; end; end; end; return;
github
lcnbeapp/beapp-master
eegdrawg.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/eegdrawg.m
3,602
utf_8
5bf94e46002cff31e2f4befee9f9d78f
% eegdrawg() - subroutine used by eegplotgold() to plot data. % % Author: Colin Humphries, CNL, Salk Institute, La Jolla, 7/96 % Copyright (C) Colin Humphries, CNL, Salk Institute 7/96 from eegplot() % % 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 % 4-4-97 shortened name to eegdrawq() -sm % 4-7-97 allowed data names other than 'data' -ch % 01-25-02 reformated help & license -ad function y = eegdrawg(fighandle) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Extract variables from figure and axes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% userdata = get(fighandle,'UserData'); samplerate = userdata(1); PLOT_TIME = userdata(2); spacing_var = userdata(3); time = userdata(4); maxtime = userdata(5); axhandle = userdata(6); plotcolor = userdata(7); disp_scale = userdata(12); colors = ['y','w']; dataname = get(axhandle,'UserData'); eval(['global ',dataname]) cla % Clear figure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Define internal variables %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% eval(['[chans,frames] = size(',dataname,');']); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Label x-axis % This routine relabels the x-axis based on the new value of time. % Labels are placed on one second intervals %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Xlab = num2str(time); for j = 1:1:PLOT_TIME Q = num2str(time+j); Xlab = str2mat(Xlab, Q); end set (gca, 'Ytick', 0:spacing_var:chans*spacing_var) set (gca, 'XTickLabels', Xlab) set (gca, 'XTick',(0:samplerate:PLOT_TIME*samplerate)) axis([0 PLOT_TIME*samplerate 0 (chans+1)*spacing_var]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plotting routine %%%%%%%%%%%%%%%%%%%%%%%%%%%%% for i = 1:chans %repeat for each channel if (maxtime-time>PLOT_TIME) eval(['F = ',dataname,'(chans-i+1,(time*samplerate)+1:((time+PLOT_TIME)*samplerate));']) else eval(['F = ',dataname,'(chans-i+1,(time*samplerate)+1:(maxtime*samplerate));']) end F = F - mean(F) + i*spacing_var; plot (F,'clipping','off','color',colors(plotcolor)) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot Scaling I %%%%%%%%%%%%%%%%%%%%%%%%%%%%% if disp_scale == 1 line([(PLOT_TIME+.3)*samplerate,(PLOT_TIME+.3)*samplerate],[1.5*spacing_var 2.5*spacing_var],'clipping','off','color','w') line([(PLOT_TIME+.3)*samplerate-10,(PLOT_TIME+.3)*samplerate+10],[2.5*spacing_var,2.5*spacing_var],'clipping','off','color','w') line([(PLOT_TIME+.3)*samplerate-10,(PLOT_TIME+.3)*samplerate+10],[1.5*spacing_var,1.5*spacing_var],'clipping','off','color','w') text((PLOT_TIME+.5)*samplerate,2*spacing_var,num2str(round(spacing_var)),'clipping','off') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Set slider=edit % This routine resets the value of the user controls so that % they agree. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% H = findobj(fighandle,'style','slider'); D = findobj(fighandle,'style','edit'); set (D, 'string', num2str(time));
github
lcnbeapp/beapp-master
averef.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/averef.m
2,628
utf_8
a00dedfa26c8a0304625f45a9689b499
% averef() - convert common-reference EEG data to average reference % Note that this old function is not being used in EEGLAB. The % function used by EEGLAB is reref(). % % Usage: % >> data = averef(data); % >> [data_out W_out S_out meandata] = averef(data,W); % % Inputs: % data - 2D data matrix (chans,frames*epochs) % W - ICA weight matrix % % Outputs: % data_out - Input data converted to average reference. % W_out - ICA weight matrix converted to average reference % S_out - ICA sphere matrix converted to eye() % meandata - (1,dataframes) mean removed from each data frame (point) % % Note: If 2 args, also converts the weight matrix W to average reference: % If ica_act = W*data, then data = inv(W)*ica_act; % If R*data is the average-referenced data, % R*data=(R*inv(W))*ica_act and W_out = inv(R*inv(W)); % The average-reference ICA maps are the columns of inv(W_out). % % Authors: Scott Makeig and Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 1999 % % See also: reref() % Copyright (C) 1999 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 % 12/16/99 Corrected denomiator on the suggestion of Ian Nimmo-Smith, Cambridge UK % 01-25-02 reformated help & license -ad function [data, W, S, meandata] = averef(data, W, S) if nargin<1 help averef return end chans = size(data,1); if chans < 2 help averef return end % avematrix = eye(chans)-ones(chans)*1/chans; % data = avematrix*data; % implement as a matrix multiply % else (faster?) meandata = sum(data)/chans; data = data - ones(chans,1)*meandata; % treat optional ica parameters if nargin == 2 winv = pinv(W); size1 = size(winv,1); avematrix = eye(size1)-ones(size1)*1/size1; W = pinv(avematrix*winv); end; if nargin >= 3 winv = pinv(W*S); size1 = size(winv,1); avematrix = eye(size1)-ones(size1)*1/size1; W = pinv(avematrix*winv); S = eye(chans); end;
github
lcnbeapp/beapp-master
laplac2d.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/laplac2d.m
2,365
utf_8
1b371aaa27a868a1cba1dfb75b3ed92d
% laplac2d() - generate a 2 dimensional gaussian matrice % % Usage : % >> [ gaussmatrix ] = laplac2d( rows, columns, sigma, ... % meanR, meanC, cut) % % Example : % >> laplac2d( 5, 5) % % Inputs: % rows - number of rows % columns - number of columns % sigma - standart deviation (default: rows/5) % meanR - mean for rows (default: center of the row) % meanC - mean for columns (default: center of the column) % cut - percentage (0->1) of the maximum value for removing % values in the matrix (default: 0) % % Note: this function implements a simple laplacian for exploratory % research. For a more rigorous validated approach use the freely % available Current Source Density Matlab toolbox. % % See also: eeg_laplac() % % 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 mat = laplac2d( sizeX, sizeY, sigma, meanX, meanY, cut); if nargin < 2 help laplac2d return; end; if nargin < 3 sigma = sizeX/5; end; if nargin < 4 meanX = (sizeX+1)/2; end; if nargin < 5 meanY = (sizeY+1)/2; end; if nargin < 6 cut = 0; end; X = linspace(1, sizeX, sizeX)'* ones(1,sizeY); Y = ones(1,sizeX)' * linspace(1, sizeY, sizeY); %[-sizeX/2:sizeX/2]'*ones(1,sizeX+1); %Y = ones(1,sizeY+1)' *[-sizeY/2:sizeY/2]; r2 = (X-meanX).*(X-meanX) + (Y-meanY).*(Y-meanY); sigma2 = sigma*sigma; mat = - exp(-0.5*r2/sigma2) .* ((r2 - sigma2)/(sigma2*sigma2)); % zeros crossing at r = -/+ sigma; % mat = r2; if cut > 0 maximun = max(max(mat))*cut; I = find(mat < maximun); mat(I) = 0; end; return;
github
lcnbeapp/beapp-master
varsort.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/varsort.m
3,451
utf_8
f28836747df60204b4cb5eba5a4f1810
% varsort() - reorder ICA components, largest to smallest, by % the size of their MEAN projected variance % across all time points % Usage: % >> [windex,meanvar] = varsort(activations,weights,sphere); % % Inputs: % activations = (chans,framestot) the runica() activations % weights = ica weight matrix from runica() % sphere = sphering matrix from runica() % % Outputs: % windex = order of projected component mean variances (large to small) % meanvar = projected component mean variance (in windex order) % % Author: Scott Makeig & Martin McKeown, SCCN/INC/UCSD, La Jolla, 09-01-1997 % % See also: runica() % Copyright (C) 9-01-1997 Scott Makeig & Martin McKeown, 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 simplified, replaced grandmean with datamean info in calculation, % made function return mean projected variance across the data, % changed var() to diag(cov()) -sm % 05-20-97 use sum-of-squares instead of diag() to allow long data sets -sm % 06-07-97 changed order of args to conform to runica, fixed meanvar computation -sm % 07-25-97 removed datamean -sm % 01-25-02 reformated help & license, added link -ad function [windex,meanvar] = varsort(activations,weights,sphere) % if nargin ~= 3 % needs all 3 args help varsort return end [chans,framestot] = size(activations); if framestot==0, fprintf('Gvarsort(): cannot process an empty activations array.\n\n'); return end; [srows,scols] = size(sphere); [wrows,wcols] = size(weights); if nargin<3, fprintf('Gvarsort(): needs at least 3 arguments.\n\n'); return end; % activations = (wrows,wcols)X(srows,scols)X(chans,framestot) if chans ~= scols | srows ~= wcols, fprintf('varsort(): input data dimensions do not match.\n'); fprintf(' i.e., Either %d ~= %d or %d ~= %d\n',... chans,scols,srows,wcols); return end %%%%%%%%%%%%%%%%%%%% Find mean variances %%%%%%%%%%%%%%%%%%%%%%%%%%%%% fprintf('Computing mean projected variance for all %d components:\n',wrows); meanvar = zeros(wrows,1); % size of the projections winv = inv(weights*sphere); for s=1:wrows fprintf('%d ',s); % construct single-component data matrix % project to scalp, then add row means compproj = winv(:,s)*activations(s,:); meanvar(s) = mean(sum(compproj.*compproj)/(size(compproj,1)-1)); % compute mean variance end % at all scalp channels %%%%%%%%%%%%%%%%%%% sort by mean variance %%%%%%%%%%%%%%%%%%%%%%%%%%%%% [sortvar, windex] = sort(meanvar); windex = windex(wrows:-1:1);% order large to small meanvar = meanvar(windex); fprintf('\n');
github
lcnbeapp/beapp-master
eegdraw.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/eegdraw.m
3,816
utf_8
8cf02a8c097d9de09a6aa145d4bfba65
% eegdraw() - subroutine used by eegplotold() to plot data. % % Author: Colin Humphries, CNL, Salk Institute, La Jolla, 7/96 % Copyright (C) Colin Humphries, CNL, Salk Institute 7/96 from eegplot() % % 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-07-97 fix incorrect start times -Scott Makeig % 01-25-02 reformated help & license -ad function y = eegdraw(fighandle) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Extract variables from figure and axes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% userdata = get(fighandle,'UserData'); samplerate = userdata(1); PLOT_TIME = userdata(2); spacing_var = userdata(3); time = userdata(4); maxtime = userdata(5); axhandle = userdata(6); plotcolor = userdata(7); disp_scale = userdata(12); colors = ['y','w']; data = get(axhandle,'UserData'); if samplerate <=0 fprintf('Samplerate too small! Resetting it to 1.0.\n') samplerate = 1.0; end if PLOT_TIME < 2/samplerate PLOT_TIME = 2/samplerate; fprintf('Window width too small! Resetting it to 2 samples.\n'); end if time >= maxtime % fix incorrect start time time = max(maxtime-PLOT_TIME,0); fprintf('Start time too large! Resetting it to %f.\n',time) elseif time < 0 time = 0; fprintf('Start time cannot be negative! Resetting it to 0.\n') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Define internal variables %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [chans,frames] = size(data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Label x-axis - relabel the x-axis based on % the new value of time. % Labels are placed at one-second intervals %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% cla % Clear figure Xlab = num2str(time); for j = 1:1:PLOT_TIME Q = num2str(time+j); Xlab = str2mat(Xlab, Q); end set (gca, 'Ytick', 0:spacing_var:chans*spacing_var) set (gca, 'XTickLabels', Xlab) % needs TickLabels with s in Matlab 4.2 set (gca, 'XTick',(0:samplerate:PLOT_TIME*samplerate)) axis([0 PLOT_TIME*samplerate 0 (chans+1)*spacing_var]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for i = 1:chans %repeat for each channel if (maxtime-time>PLOT_TIME) F = data(chans-i+1,(time*samplerate)+1:((time+PLOT_TIME)*samplerate)); else F = data(chans-i+1,(time*samplerate)+1:(maxtime*samplerate)); end F = F - mean(F) + i*spacing_var; plot (F,'clipping','off','color',colors(plotcolor)) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Plot scaling I %%%%%%%%%%%%%%%%%%%%%%%%%%%%% if disp_scale == 1 ps = PLOT_TIME*samplerate; sv = spacing_var; line([1.03*ps,1.03*ps],[1.5*sv 2.5*sv],'clipping','off','color','w') line([1.01*ps,1.05*ps],[2.5*sv,2.5*sv],'clipping','off','color','w') line([1.01*ps,1.05*ps],[1.5*sv,1.5*sv],'clipping','off','color','w') text(1.05*ps,2*sv,num2str(round(sv)),'clipping','off') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Set slider=edit - reset the value of % the user controls so they agree. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% H = findobj(fighandle,'style','slider'); D = findobj(fighandle,'style','edit'); set (D, 'string', num2str(time));
github
lcnbeapp/beapp-master
eegmovie.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/eegmovie.m
10,994
utf_8
e8d4266027ffe169448945aed8f2b937
% eegmovie() - Compile and view a Matlab movie. % Uses scripts eegplotold() and topoplot(). % Use seemovie() to display the movie. % Usage: % >> [Movie,Colormap] = eegmovie(data,srate,elec_locs, 'key', val, ...); % % Or legacy call % >> [Movie,Colormap] = eegmovie(data,srate,elec_locs,title,movieframes,minmax,startsec,...); % % Inputs: % data = (chans,frames) EEG data set to plot % srate = sampling rate in Hz % elec_locs = electrode locations structure or file % % Optional inputs: % 'mode' = ['2D'|'3D'] plot in 2D using topoplot or in 3D using % headplot. Default is 2D. % 'headplotopt' = [cell] optional inputs for headplot. Default is none. % 'topoplotopt' = [cell] optional inputs for topoplot. Default is none. % 'title' = plot title. Default is none. % 'movieframes' = vector of frames indices to animate. Default is all. % 'minmax' = [blue_lower_bound, red_upper_bound]. Default is % +/-abs max of data. % 'startsec' = starting time in seconds. Default is 0. % 'timecourse' = ['on'|'off'] show time course for all electrodes. Default is 'on'. % 'framenum' = ['on'|'off'] show frame number. Default is 'on'. % 'time' = ['on'|'off'] show time in ms. Default is 'off'. % 'vert' = [float] plot vertical lines at given latencies. Default is none. % 'camerapath' = [az_start az_step el_start el_step] {default [-127 0 30 0]} % Setting all four non-0 creates a spiral camera path % Subsequent rows [movieframe az_step 0 el_step] adapt step % sizes allowing starts/stops, panning back and forth, etc. % % Legacy inputs: % data = (chans,frames) EEG data set to plot % srate = sampling rate in Hz {0 -> 256 Hz} % elec_locs = ascii file of electrode locations {0 -> 'chan_file'} % title = 'plot title' {0 -> none} % movieframes = vector of frames to animate {0 -> all} % minmax = [blue_lower_bound, red_upper_bound] % {0 -> +/-abs max of data} % startsec = starting time in seconds {0 -> 0.0} % additional options from topoplot are allowed % % Author: Arnaud Delorme, Colin Humphries & Scott Makeig, CNL, Salk Institute, La Jolla, 3/97 % % See also: seemovie(), eegplotold(), topoplot() % Copyright (C) 6/4/97 Colin Humphries & Scott Makeig, CNL / Salk Institute / La Jolla CA % % 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/6/97 added movieframes arg -sm % 6/12/97 removed old 'startframes' var., fixed vertical line frame selection -sm % 6/27/97 debugged vertical line position -sm % 10/4/97 clarified order of srate and eloc_locs -sm % 3/18/97 changed eegplots -> eegplot('noui') -sm % 10/10/99 added newlines to frame print at suggestion of Ian Lee, Singapore -sm % 01/05/01 debugged plot details -sm % 01/24/02 updated eegplot to eegplotold -ad % 01-25-02 reformated help & license, added links -ad function [Movie, Colormap] = eegmovie(data,srate,eloc_locs,varargin); %titl,movieframes,minmax,startsec,varargin) if nargin<1 help eegmovie return end clf [chans,frames] = size(data); icadefs; % read DEFAULT_SRATE; if nargin <2 srate = 0; end if nargin <3 eloc_locs = 0; end if nargin > 5 && ~ischar(varargin{3}) || nargin == 4 && ~ischar(varargin{2}) % legacy mode options = {}; if nargin>=8, options = { options{:} 'topoplotopt' varargin(5:end) }; end if nargin>=7, options = { options{:} 'startsec' varargin{4} }; end if nargin>=6, options = { options{:} 'minmax' varargin{3} }; end if nargin>=5, options = { options{:} 'movieframes' varargin{2} }; end if nargin>=4, options = { options{:} 'title' varargin{1} }; end else options = varargin; end; opt = finputcheck(options, { 'startsec' 'real' {} 0; 'minmax' 'real' {} 0; 'movieframes' 'integer' {} 0; 'title' 'string' {} ''; 'vert' 'real' {} []; 'mode' 'string' { '2D' '3D' } '2D'; 'timecourse' 'string' { 'on' 'off' } 'on'; 'framenum' 'string' { 'on' 'off' } 'on'; 'camerapath' 'real' [] 0; 'time' 'string' { 'on' 'off' } 'off'; 'topoplotopt' 'cell' {} {}; 'headplotopt' 'cell' {} {} }, 'eegmovie'); if isstr(opt), error(opt); end; if opt.minmax ==0, datamin = min(min(data)); datamax = max(max(data)); absmax = max([abs(datamin), abs(datamax)]); fudge = 0.05*(datamax-datamin); % allow for slight extrapolation datamin = -absmax-fudge; datamax = absmax+fudge; opt.minmax = [datamin datamax]; end if opt.movieframes == 0 opt.movieframes = 1:frames; end if opt.movieframes(1) < 1 || opt.movieframes(length(opt.movieframes))>frames fprintf('eegmovie(): specified movieframes not in data!\n'); return end if srate ==0, srate = DEFAULT_SRATE; end if strcmpi(opt.time, 'on'), opt.framenum = 'off'; end; mframes = length(opt.movieframes); fprintf('Making a movie of %d frames\n',mframes) Movie = moviein(mframes,gcf); %%%%%%%%%%%%%%%%%%%%% eegplot() of data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(opt.timecourse, 'on') axeegplot = axes('Units','Normalized','Position',[.75 .05 .2 .9]); % >> eegplotold('noui',data,srate,spacing,eloc_file,startsec,color) if isstruct(eloc_locs) fid = fopen('tmp_file.loc', 'w'); adddots = '...'; for iChan = 1:length(eloc_locs) fprintf(fid, '0 0 0 %s\n', [ eloc_locs(iChan).labels adddots(length(eloc_locs(iChan).labels):end) ]); end; fclose(fid); eegplotold('noui',-data,srate,0,'tmp_file.loc',opt.startsec,'r'); else eegplotold('noui',-data,srate,0,eloc_locs,opt.startsec,'r'); end; % set(axeegplot,'XTick',[]) %%CJH % plot negative up limits = get(axeegplot,'Ylim'); % list channel numbers only set(axeegplot,'GridLineStyle','none') set(axeegplot,'Xgrid','off') set(axeegplot,'Ygrid','on') for ind = 1:length(opt.vert) frameind = (opt.vert(ind)-opt.startsec)*srate+1; line([frameind frameind],limits,'color','k'); % draw vertical line at map timepoint set(axeegplot,'Xtick',frameind,'XtickLabel',num2str(opt.vert(ind),'%4.3f')); end; end; %%%%%%%%%%%%%%%%%%%%% topoplot/headplot axis %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% axcolor = get(gcf,'Color'); axtopoplot = axes('Units','Normalized','Position',[0 .1 .72 .8],'Color',axcolor); TPAXCOLOR = get(axtopoplot,'Color'); %%CJH Colormap = [jet(64);TPAXCOLOR]; %%CJH fprintf('Warning: do not resize plot window during movie creation ...\n '); h = textsc(opt.title, 'title'); set(h,'FontSize',16) %%%%%%%%%%%%%%%%%%%%% headplot setup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmpi(opt.mode, '3d') headplot('setup',eloc_locs, 'tmp.spl', opt.headplotopt{:}); if isequal(opt.camerapath, 0) opt.camerapath = [-127 0 30 0]; fprintf('Using default view [-127 0 30 0].'); end; if size(opt.camerapath,2)~=4 error('Camerapath parameter must have exact 4 columns'); end newpan = length(opt.movieframes)+1; posrow = 2; if size(opt.camerapath,1) > 1 newpan = opt.camerapath(posrow,1); % pick up next frame to change camerapos step values end azimuth = opt.camerapath(1,1); % initial camerapath variables az_step = opt.camerapath(1,2); elevation = opt.camerapath(1,3); el_step = opt.camerapath(1,4); end; %%%%%%%%%%%%%%%%%%%%%%%%% "Roll'em!" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for f = 1:length(opt.movieframes) % make the movie, frame by frame indFrame = opt.movieframes(f); % show time course if strcmpi(opt.timecourse, 'on') axes(axeegplot) x1 = opt.startsec+(indFrame-1)/srate; l1 = line([indFrame indFrame],limits,'color','b'); % draw vertical line at map timepoint set(axeegplot,'Xtick',indFrame,'XtickLabel',num2str(x1,'%4.3f')); end; % plot headplot or topoplot axes(axtopoplot) cla set(axtopoplot,'Color',axcolor); if strcmpi(opt.mode, '2d') topoplot(data(:,indFrame),eloc_locs,'maplimits',opt.minmax, opt.topoplotopt{:}); else headplot(data(:,indFrame),'tmp.spl','view',[azimuth elevation], opt.headplotopt{:}); % adapt camerapath step sizes if indFrame == newpan az_step = opt.camerapath(posrow,2); el_step = opt.camerapath(posrow,4); posrow = posrow+1; if size(opt.camerapath,1)>=posrow newpan = opt.camerapath(posrow,1); else newpan = length(opt.movieframes)+1; end end % update camera position azimuth = azimuth+az_step; elevation = elevation+el_step; if elevation>=90 fprintf('headplot(): warning -- elevation out of range!\n'); elevation = 89.99; end if elevation<=-90 fprintf('headplot(): warning -- elevation out of range!\n'); elevation = -89.99; end set(axtopoplot,'Units','pixels',... 'CameraViewAngleMode','manual',... 'YTickMode','manual','ZTickMode','manual',... 'PlotBoxAspectRatioMode','manual',... 'DataAspectRatioMode','manual'); % keep camera distance constant end; % show frame number if strcmpi(opt.framenum, 'on') txt = [ int2str(f)]; text(-0.5,-0.5,txt,'FontSize',14); elseif strcmpi(opt.time, 'on') txt = sprintf('%3.3f s', opt.startsec+(indFrame-1)/srate); text(-0.5,-0.5,txt,'FontSize',14); end; Movie(:,f) = getframe(gcf); drawnow if strcmpi(opt.timecourse, 'on') delete(l1) end; % print advancement fprintf('.',f); if rem(indFrame,10) == 0, fprintf('%d',f); end; if rem(indFrame,50) == 0, fprintf('\n'); end end fprintf('\nDone\n');
github
lcnbeapp/beapp-master
gabor2d.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/gabor2d.m
3,449
utf_8
669aa44c02685a4e73e5568196a23efb
% gabor2d() - generate a two-dimensional gabor matrice. % % Usage: % >> [ matrix ] = gabor2d(rows, columns); % >> [ matrix ] = gabor2d( rows, columns, freq, ... % angle, sigmaR, sigmaC, meanR, meanC, dephase, cut) % Example : % >> imagesc(gabor2d( 50, 50)) % % Inputs: % rows - number of rows % columns - number of columns % freq - frequency of the sinusoidal function in degrees (default: 360/rows) % angle - angle of rotation of the resulting 2-D array in % degrees of angle {default: 0}. % sigmaR - standard deviation for rows {default: rows/5} % sigmaC - standard deviation for columns {default: columns/5} % meanR - mean for rows {default: center of the row} % meanC - mean for columns {default: center of the column} % dephase - phase offset in degrees {default: 0}. A complex Gabor wavelet % can be build using gabor2dd(...., 0) + i*gabor2d(...., 90), % 0 and 90 being the phase offset of the real and imaginary parts % cut - percentage (0->1) of maximum value below which to remove values % from the matrix {default: 0} % Ouput: % matrix - output gabor matrix % % 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 mat = gabor2d( sizeX, sizeY, freq, angle, sigmaX, sigmaY, meanX, ... meanY, dephase, cut); if nargin < 2 help gabor2d return; end; if nargin < 3 freq = 360/sizeX; end; if nargin < 4 angle = 0; end; if nargin < 5 sigmaX = sizeX/5; end; if nargin < 6 sigmaY = sizeY/5; end; if nargin < 7 meanX = (sizeX+1)/2; end; if nargin < 8 meanY = (sizeY+1)/2; end; if nargin < 9 dephase = 0; end; if nargin < 10 cut = 0; end; freq = freq/180*pi; X = linspace(1, sizeX, sizeX)'* ones(1,sizeY); Y = ones(1,sizeX)' * linspace(1, sizeY, sizeY); %[-sizeX/2:sizeX/2]'*ones(1,sizeX+1); %Y = ones(1,sizeY+1)' *[-sizeY/2:sizeY/2]; rotatedmat = ((X-meanX)+i*(Y-meanY)) * exp(i*angle/180*pi); mat = sin(real(rotatedmat)*freq + dephase/180*pi).*exp(-0.5*( ((X-meanX)/sigmaX).*((X-meanX)/sigmaX)... +((Y-meanY)/sigmaY).*((Y-meanY)/sigmaY)))... /((sigmaX*sigmaY)^(0.5)*pi); if cut > 0 maximun = max(max(mat))*cut; I = find(mat < maximun); mat(I) = 0; end; return; % other solution % -------------- for X = 1:sizeX for Y = 1:sizeY mat(X,Y) = sin(real((X-meanX+j*(Y-meanY))*exp(i*angle/180*pi))*freq + dephase/180*pi) ... .*exp(-0.5*( ((X-meanX)/sigmaX).*((X-meanX)/sigmaX)... +((Y-meanY)/sigmaY).*((Y-meanY)/sigmaY)))... /((sigmaX*sigmaY)^(0.5)*pi); end; end; return;
github
lcnbeapp/beapp-master
makehtml.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/makehtml.m
13,268
utf_8
ab43eb5b6d347b47f14edde57f938911
% makehtml() - generate .html function-index page and function help pages % composed automatically from formatted Matlab function help messages % % Usage: % >> makehtml(list, outputdir); % >> makehtml(list, outputdir, 'key1', val1, 'key2', val2, ...); % % Input: % list - (1) List (cell array) of filenames to convert. % Ex: {'filename1' 'filename2' 'filename3'} % By default, the filename extension .m is understood. % (2) Cell array of filenames to convert and the text link % on the summary page for them. % {{'filename1' 'link1'} {'filename2' 'link2'}} ... % Ex: 'link1' = 'Reject by kurtosis'. % (3) Cell array of 2 or 3 cell array elements containing % info to generate .html function-index and help pages. % Ex: { {'directory1' 'heading1' 'dirindexfunc1'} ... % {'directory2' 'heading2' 'dirindexfunc2'} } % - 'directory': Function file directory name % - 'heading': Index-file heading for the directory functions % - 'dirindexfunc': A optional Matlab pop-up help function for % referencing the directory functions {default: none} % (4) To scan several directories under the same heading, use % {{{'directory1' 'directory2'} 'heading1' 'dirindexfunc1' ... } % outputdir - Directory for output .html help files % % Optional inputs: % 'outputfile' - Output file name. {default: 'index.html'} % 'header' - Command to insert in the header of all .html files (e.g., javascript % declaration or meta-tag). {default: javascript 'openhelp()' % function. See help2htm() code for details.} % 'footer' - Command to insert at the end of all .html files (e.g., back % button. {default: reference back to the function-index file} % 'refcall' - Syntax format to call references. {default is % 'javascript:openhelp(''%s.js'')'} Use '%s.html' for an .html link. % 'font' - Font name (default: 'Helvetica') % 'background' - Background HTML body section. Include "<" and ">". % 'outputlink' - Help page calling command for the function index page. {default is % 'javascript:openhelp(''%s.js'')'. Use '%s.html' to use a % standard .html page link instead.} % 'fontindex' - Font for the .html index file (default: 'Helvetica') % 'backindex' - Background tag for the index file (c.f. 'background') % 'mainheader' - Text file to insert at the beggining of the index page. Default is % none. % 'mainonly' - ['on'|'off'] 'on' -> Generate the index page only. % {default: 'off' -> generate both the index and help pages} % % Author: Arnaud Delorme, CNL / Salk Institute, 2002 % % Example: Generate EEGLAB help menus at SCCN: % makehtml({ { 'adminfunc' 'Admin functions' 'adminfunc/eeg_helpadmin.m' } ... % { 'popfunc', 'Interactive pop_functions' 'adminfunc/eeg_helppop.m' } ... % { { 'toolbox', 'toolbox2' } 'Signal processing functions' 'adminfunc/eeg_helpsigproc.m' }}, ... % '/home/www/eeglab/allfunctions', 'mainheader', '/data/common/matlab/indexfunchdr.txt'); % % See also: help2html2() % Copyright (C) Arnaud Delorme, CNL / Salk Institute, 2002 % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function makehtml( directorylist, outputdir, varargin ); if nargin < 2 help makehtml; return; end; if outputdir(end) ~= '/', outputdir(end+1) = '/'; end; if ~isempty( varargin ) g = struct( varargin{:} ); else g = []; end; try, g.mainonly; catch, g.mainonly = 'off'; end; try, g.mainheader; catch, g.mainheader = ''; end; try, g.outputfile; catch, g.outputfile = 'index.html'; end; try, g.fontindex; catch, g.fontindex = 'Helvetica'; end; try, g.backindex; catch, g.backindex = '<body bgcolor="#fcffff">'; end; try, g.header; catch, g.header = [ '<script language="JavaScript"><!--' 10 'function openhelp(fnc){' 10 'self.window.location = fnc;' 10 '}' 10 '//--></script>' ]; end; try, g.background; catch, g.background = '<body bgcolor="#fcffff">'; end; %try, g.background; catch, g.background = '<body BACKGROUND="cream_stucco.jpg" bgproperties="fixed" bgcolor="#ffffe5">'; end; try, g.refcall; catch, g.refcall = 'javascript:openhelp(''%s.html'')'; end; try, g.font; catch, g.font = 'Helvetica'; end; try, g.footer; catch, g.footer = '<A HREF ="index.html">Back to functions</A>'; end; try, g.outputlink; catch, g.outputlink = [ '<tr><td VALIGN=TOP ALIGN=RIGHT NOSAVE><A HREF="javascript:openhelp(''%s.html'')">%s</A></td><td>%s</td></tr>' ]; end; % read header text file % --------------------- if ~isempty(g.mainheader) doc = []; fid = fopen(g.mainheader , 'r'); if (fid == -1), error(['Can not open file ''' g.mainheader '''' ]); end; str = fgets( fid ); while ~feof(fid) str = deblank(str(1:end-1)); doc = [ doc str(1:end) ]; str = fgets( fid ); end; g.backindex = [ g.backindex doc ]; end; options = { 'footer', g.footer, 'background', g.background, ... 'refcall', g.refcall, 'font', g.font, 'header', g.header, 'outputlink', g.outputlink}; if strcmpi( g.mainonly, 'on') options = { options{:}, 'outputonly', g.mainonly }; end; % ------------------------------------------- % scrips which generate a web page for eeglab % ------------------------------------------- STYLEHEADER = '<BR><a name="%s"></a><H2>%s</H2>\n'; OPENWIN = [ '<script language="JavaScript"><!--' 10 'function openhelp(fnc){' 10 ... 'self.window.location = fnc;' 10 '}' 10 '//--></script>']; ORIGIN = pwd; % determine mode % -------------- if iscell(directorylist{1}) & exist(directorylist{1}{1}) == 7 fprintf('First cell array element is not a file\n'); fprintf('Scanning directories...\n'); mode = 'dir'; % scan directories % ---------------- for index = 1:length( directorylist ) direct{ index } = scandir( directorylist{index}{1} ); end; else fprintf('First cell array element has been identified as a file\n'); fprintf('Scanning all files...\n'); mode = 'files'; end; % remove . directory % ------------------ rmpath('.'); % write .html file % ---------------- fo = fopen([ outputdir g.outputfile], 'w'); if fo == -1, error(['cannot open file ''' [ outputdir g.outputfile] '''']); end; fprintf(fo, '<HTML><HEAD>%s</HEAD>%s<FONT FACE="%s">\n', OPENWIN, g.backindex, g.fontindex); if strcmp(mode, 'files') makehelphtml( directorylist, fo, 'MAIN TITLE', STYLEHEADER, outputdir, mode, options, g.mainonly ); else % direcotry for index = 1:length( directorylist ) makehelphtml( direct{ index }, fo, directorylist{index}{2}, STYLEHEADER, outputdir, mode, options, g.mainonly ); end; end; fprintf( fo, '</FONT></BODY></HTML>'); fclose( fo ); if isunix chmodcom = sprintf('!chmod 777 %s*', outputdir); eval(chmodcom); end; % ------------------------------ % Generate help files for EEGLAB % ------------------------------ if strcmp(mode, 'dir') for index = 1:length( directorylist ) if length(directorylist{index}) > 2 makehelpmatlab( directorylist{index}{3}, direct{ index },directorylist{index}{2}); end; end; end; addpath('.'); return; % scan directory list or directory % -------------------------------- function filelist = scandir( dirlist ) filelist = {}; if iscell( dirlist ) for index = 1:length( dirlist ) tmplist = scandir( dirlist{index} ); filelist = { filelist{:} tmplist{:} }; end; else if dirlist(end) ~= '/', dirlist(end+1) = '/'; end; if exist(dirlist) ~= 7 error([ dirlist ' is not a directory']); end; tmpdir = dir([dirlist '*.m']); filelist = { tmpdir(:).name }; end; filelist = sort( filelist ); return; % ------------------------------ Function to generate help for a bunch of files - function makehelphtml( files, fo, title, STYLEHEADER, DEST, mode, options, mainonly); % files = cell array of string containing file names or % cell array of 2-strings cell array containing titles and filenames % fo = output file % title = title of the page or section tmpdir = pwd; if strcmp(mode, 'files') % processing subtitle and File fprintf(fo, '<UL>' ); for index = 1:length(files) if iscell(files{index}) filename = files{index}{1}; filelink = files{index}{2}; else filename = files{index}; filelink = ''; end; fprintf('Processing (mode file) %s:%s\n', filename, filelink ); if ~isempty(filename) if ~exist(fullfile(DEST, [ filename(1:end-1) 'html' ])) cd(DEST); try, delete([ DEST filename ]); catch, end; help2html2( filename, [], 'outputtext', filelink, options{:}); cd(tmpdir); if strcmp(mainonly,'off') inputfile = which( filename); try, copyfile( inputfile, [ DEST filename ]); % asuming the file is in the path catch, fprintf('Cannot copy file %s\n', inputfile); end; end; indexdot = find(filename == '.'); end; if ~isempty(filelink) com = [ space2html(filelink) ' -- ' space2html([ filename(1:indexdot(end)-1) '()'], ... [ '<A HREF="' filename(1:indexdot(end)-1) '.html">' ], '</A><BR>')]; else com = [ space2html([ filename(1:indexdot(end)-1) '()'], ... [ '<A HREF="' filename(1:indexdot(end)-1) '.html">' ], '</A><BR>')]; end; else com = space2html(filelink, '<B>', '</B><BR>'); end; fprintf( fo, '%s', com); end; fprintf(fo, '</UL>' ); else fprintf(fo, STYLEHEADER, title, title ); fprintf(fo, '<table WIDTH="100%%" NOSAVE>' ); for index = 1:length(files) % Processing file only if ~exist(fullfile(DEST, [ files{index}(1:end-1) 'html' ])) fprintf('Processing %s\n', files{index}); cd(DEST); com = help2html2( files{index}, [], options{:}); cd(tmpdir); fprintf( fo, '%s', com); if strcmp(mainonly,'off') inputfile = which( files{index}); try, copyfile( inputfile, [ DEST files{index} ]); % asuming the file is in the path catch, fprintf('Cannot copy file %s\n', inputfile); end; end; else fprintf('Skipping %s\n', files{index}); cd(DEST); com = help2html2( files{index}, [], options{:}, ... 'outputonly','on'); fprintf( fo, '%s', com); cd(tmpdir); end end; fprintf(fo, '</table>' ); end; return; % ------------------------------ Function to pop-out a Matlab help window -------- function makehelpmatlab( filename, directory, titlewindow); fo = fopen( filename, 'w'); fprintf(fo, '%%%s() - Help file for EEGLAB\n\n', filename); fprintf(fo, 'function noname();\n\n'); fprintf(fo, 'command = { ...\n'); for index = 1:length(directory) fprintf(fo, '''pophelp(''''%s'''');'' ...\n', directory{index}); end; fprintf(fo, '};\n'); fprintf(fo, 'text = { ...\n'); for index = 1:length(directory) fprintf(fo, '''%s'' ...\n', directory{index}); end; fprintf(fo, '};\n'); fprintf(fo, ['textgui( text, command,' ... '''fontsize'', 15, ''fontname'', ''times'', ''linesperpage'', 18, ', ... '''title'',strvcat( ''%s'', ''(Click on blue text for help)''));\n'], titlewindow); fprintf(fo, 'icadefs; set(gcf, ''COLOR'', BACKCOLOR);'); fprintf(fo, 'h = findobj(''parent'', gcf, ''style'', ''slider'');'); fprintf(fo, 'set(h, ''backgroundcolor'', GUIBACKCOLOR);'); fprintf(fo, 'return;\n'); fclose( fo ); return % convert spaces for .html function strout = space2html(strin, linkb, linke) strout = []; index = 1; while strin(index) == ' ' strout = [ strout '&nbsp; ']; index = index+1; end; if nargin == 3 strout = [strout linkb strin(index:end) linke]; else strout = [strout strin(index:end)]; end;
github
lcnbeapp/beapp-master
covary.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/covary.m
1,482
utf_8
be5b9b3870c8f6344a4441160ea51bf0
% covary() - For vectors, covary(X) returns the variance of X. % For matrices, covary(X)is a row vector containing the % variance of each column of X. % % Notes: % covary(X) normalizes by N-1 where N is the sequence length. % This makes covary(X) the best unbiased estimate of the % covariance if X are from a normal distribution. % Does not require the Matlab Signal Processing Toolbox % % Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000 % Copyright (C) 2000 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 -ad function covout = covary(data) data = data - mean(mean(data)); if size(data,1) == 1 data = data'; % make column vector end covout = sum(data.*data)/(size(data,1)-1);
github
lcnbeapp/beapp-master
convolve.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
textgui.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
kmeans_st.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
caliper.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
help2html2.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
getallmenus.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_regepochs.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eegplotold.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
chanproj.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
zica.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
rotatematlab.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
del2map.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
readlocsold.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
crossfreq.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
upgma.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
mapcorr.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
uniqe_cell_string.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
make_timewarp.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
fieldtrip2eeglab.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
rmart.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
vectdata.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
matperm.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
varimax.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
pcsquash.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
nan_std.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
plotproj.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
numdim.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
eeg_ms2f.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
compsort.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
compheads.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
logspec.m
.m
beapp-master/Packages/eeglab14_1_2b/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
lcnbeapp/beapp-master
tftopo.m
.m
beapp-master/Packages/eeglab14_1_2b/functions/miscfunc/tftopo.m
25,662
utf_8
927788fa42a8c1c1676c74297725af98
% 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),(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 % for topoplot if length(size(tfdata)) >= 4 tfdataori = mean(tfdata,4); else tfdataori = tfdata; end % 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) % MATLAB version >= 8.04 try ft = str2num(cell2mat(tmpval)); catch % To avoid bug in matlab cell2mat. i.e. when tmpval = {'0';'0.5'} for i = 1:length(tmpval) ft(i,1) = str2num(cell2mat(tmpval(i))); end end else % MATLAB version < 8.04 ft = str2num(tmpval); 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