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
wangsuyuan/Imageprocesingtoobox-master
iccProfileCache.m
.m
Imageprocesingtoobox-master/colorspaces/private/iccProfileCache.m
3,125
utf_8
0d1af3e6d092b20833195eaf5a969ff5
function requestedProfiles = iccProfileCache(requestedDir) %iccProfileCache Cache ICC profiles into memory, return in a cell array. % % PROFILES = iccProfileCache(DIRECTORY) loads all of the valid ICC % profiles in the given DIRECTORY into a persistent memory cache and % returns the cache as a cell array in the PROFILES variable. % % All profiles in the default ICC profiles repository as well as profiles % in the most recently queried directory are cached (but in separate % caches). % Copyright 1993-2012 The MathWorks, Inc. % Keep track of the iccroot and last requested directory's profiles. persistent currentProfiles iccrootProfiles lastDir if ( (~isempty(currentProfiles)) && (isequal(requestedDir, lastDir)) ) % Requesting the same profiles as the last query. requestedProfiles = currentProfiles; return elseif ( (~isempty(iccrootProfiles)) && (isequal(requestedDir, iccroot)) ) % Requesting the cached iccroot profiles. requestedProfiles = iccrootProfiles; return end % Build the cache of profiles. d = dir(fullfile(requestedDir, '*.ic*')); profileCount = numel(d); requestedProfiles = cell(profileCount, 1); hWait = createWaitbar(profileCount); for idx = 1:profileCount try requestedProfiles{idx} = iccread(fullfile(requestedDir, d(idx).name)); catch requestedProfiles{idx} = []; end updateWaitbar(hWait, idx ./ profileCount); end % Remove empty entries for invalid profiles. requestedProfiles = cleanupEmpties(requestedProfiles); % Clean up waitbar. deleteWaitbar(hWait) % Set persistent variables before exiting. try if (isequal(requestedDir, iccroot)) iccrootProfiles = requestedProfiles; end catch iccrootProfiles = []; end currentProfiles = requestedProfiles; lastDir = requestedDir; %------------------------------------------------------------------------- function hWait = createWaitbar(profileCount) % For a small number of profiles don't display a waitbar. if profileCount <= 10 || ~images.internal.isFigureAvailable() hWait = []; else hWait = waitbar(0, getStaticText); end %------------------------------------------------------------------------- function updateWaitbar(hWait, pct) if (~isempty(hWait)) waitbar(pct, hWait, sprintf('%s %d%%', getStaticText, round(100*pct))); end %------------------------------------------------------------------------- function deleteWaitbar(hWait) if (~isempty(hWait)) delete(hWait) end %------------------------------------------------------------------------- function titleStaticText = getStaticText titleStaticText = getString(message('images:iccProfileCache:waitBarTitle')); %------------------------------------------------------------------------- function cleanedCells = cleanupEmpties(allCells) empties = []; for idx = 1:numel(allCells) if (isempty(allCells{idx})) empties(end + 1) = idx; end end cleanedCells = allCells; if (~isempty(empties)) cleanedCells(empties) = []; end
github
wangsuyuan/Imageprocesingtoobox-master
encode_color.m
.m
Imageprocesingtoobox-master/colorspaces/private/encode_color.m
7,766
utf_8
5884b63dee82439e9564de83ec2ffc49
function out = encode_color(in, cspace, encode_in, encode_out) %ENCODE_COLOR Convert encoding of color data. % OUT = ENCODE_COLOR(IN, CSPACE, ENCODE_IN, ENCODE_OUT) changes % the encoding of the data in IN from ENCODE_IN to ENCODE_OUT, % returning the results in OUT. ENCODE_IN and ENCODE_OUT % can be 'double', 'uint8', or 'uint16'. The encoding also % is dependent on CSPACE, which specifies the color space. % Supported device-independent color spaces include % 'lab', 'xyz', 'xyl', 'uvl', 'upvpl', and 'lch'. Supported % device-dependent spaces include 'gray', 'rgb', 'cmyk', and % 'color_n', where n can range from 2 to 15. % % See also APPLYCFORM. % Copyright 2002-2010 The MathWorks, Inc. % Original Authors: Scott Gregory, Toshia McCabe 12/04/02 cspace = lower(cspace); if strncmp(cspace, 'color_', 6) cspace = 'color_n'; end [cspace, encode_in] = check_input(cspace,encode_in); encode_out = lower(encode_out); if strcmp(encode_in,encode_out) out = in; else enc = getEncodingTable(); % Choose the encoding conversion function func = enc.(cspace).(encode_in).(encode_out); % Do the encoding conversion out = func(in); end %----------------------------------------- function out = labdouble_to_labuint8(in) % Do the scale and offset and cast to uint8 out = round([(255 * (in(:,1)/100)) in(:,2)+128 in(:,3)+128]); out = max(0, min(255, out)); out = uint8(out); %----------------------------------------- function out = labuint8_to_labdouble(in) out = double(in); out(:,1) = 100 * (out(:,1) / 255); out(:,2) = out(:,2) - 128; out(:,3) = out(:,3) - 128; %----------------------------------------- function out = labdouble_to_labuint16(in) % Do the scale and offset and cast to uint16 out = in; out(:,1) = round(65535 * out(:,1) / (100 + (25500/65280))); out(:,2) = round(65535 * ((128 + out(:,2)) / (255 + (255/256)))); out(:,3) = round(65535 * ((128 + out(:,3)) / (255 + (255/256)))); out = max(0, min(65535, out)); out = uint16(out); %----------------------------------------- function out = labuint16_to_labdouble(in) out = double(in); out(:,1) = (out(:,1) * (100 + (25500/65280))) / 65535; out(:,2) = ((out(:,2) * (255 + (255/256))) / 65535) - 128; out(:,3) = ((out(:,3) * (255 + (255/256))) / 65535) - 128; %----------------------------------------- function out = xyzdouble_to_xyzuint16(in) out = round(65535 * (in / (1 + (32767/32768)))); out = max(0, min(65535, out)); out = uint16(out); %----------------------------------------- function out = xyzuint16_to_xyzdouble(in) out = (double(in)/65535) * (1 + (32767/32768)); %----------------------------------------- function out = double_to_uint8(in) out = round((in) * 255); out = max(0, min(255, out)); out = uint8(out); %----------------------------------------- function out = uint8_to_double(in) out = double(in) / 255; %------------------------------------------ function out = double_to_uint16(in) out = round((in) * 65535); out = max(0, min(65535, out)); out = uint16(out); %----------------------------------------- function out = uint16_to_double(in) out = double(in) / 65535; %----------------------------------------- function out = labuint8_to_labuint16(in) out = uint16(round(double(in)*256)); %----------------------------------------- function out = labuint16_to_labuint8(in) out = round(double(in)/256); out = max(0, min(255, out)); out = uint8(out); %----------------------------------------- function out = uint8_to_uint16(in) out = uint16(round((double(in) / 255) * 65535)); %----------------------------------------- function out = uint16_to_uint8(in) out = uint8(round((double(in) / 65535) * 255)); %----------------------------------------- function out = output_encoding_ignored(in) % This is just a fix for the situation such as one % goes in as uint8, and comes out as XYZ. Since there % is no defined encoding for 8 bit XYZ, the output must % be uint16! out = in; warning(message('images:encode_color:outputEncodingIgnored')) %-------------------------------------------------------------------------- function [cspace,encoding] = check_input(cspace,encode_in) valid_cspaces = {'lab', 'xyz', 'lch', 'upvpl', 'uvl', 'xyl', ... 'gray', 'rgb', 'cmyk', 'color_n'}; cspace = validatestring(cspace, valid_cspaces, 'encode_color', ... 'COLORSPACE', 2); switch cspace case 'lab' valid_encodings = {'double', 'uint8', 'uint16'}; case 'xyz' valid_encodings = {'double', 'uint16'}; case 'lch' valid_encodings = {'double'}; case 'upvpl' valid_encodings = {'double'}; case 'uvl' valid_encodings = {'double'}; case 'xyl' valid_encodings = {'double'}; case 'gray' valid_encodings = {'double', 'uint8', 'uint16'}; case 'rgb' valid_encodings = {'double', 'uint8', 'uint16'}; case 'cmyk' valid_encodings = {'double', 'uint8', 'uint16'}; case 'color_n' valid_encodings = {'double', 'uint8', 'uint16'}; end encoding = validatestring(encode_in, valid_encodings, ... 'encode_color', 'ENCODING_IN', 3); %-------------------------------------------------------------------------- function table = getEncodingTable() % Populate a struct that maps the encoding function by indexing % colorspace, input encoding, and output encoding persistent enctab; if isempty(enctab) enctab.lab.double.uint8 = @labdouble_to_labuint8; enctab.lab.uint8.double = @labuint8_to_labdouble; enctab.lab.double.uint16 = @labdouble_to_labuint16; enctab.lab.uint16.double = @labuint16_to_labdouble; enctab.lab.uint8.uint16 = @labuint8_to_labuint16; enctab.lab.uint16.uint8 = @labuint16_to_labuint8; enctab.xyz.double.uint16 = @xyzdouble_to_xyzuint16; enctab.xyz.double.uint8 = @output_encoding_ignored; enctab.xyz.uint16.double = @xyzuint16_to_xyzdouble; enctab.xyz.uint16.uint8 = @output_encoding_ignored; enctab.gray.double.uint8 = @double_to_uint8; enctab.gray.uint8.double = @uint8_to_double; enctab.gray.uint16.double = @uint16_to_double; enctab.gray.double.uint16 = @double_to_uint16; enctab.gray.uint8.uint16 = @uint8_to_uint16; enctab.gray.uint16.uint8 = @uint16_to_uint8; enctab.rgb.double.uint8 = @double_to_uint8; enctab.rgb.uint8.double = @uint8_to_double; enctab.rgb.uint16.double = @uint16_to_double; enctab.rgb.double.uint16 = @double_to_uint16; enctab.rgb.uint8.uint16 = @uint8_to_uint16; enctab.rgb.uint16.uint8 = @uint16_to_uint8; enctab.cmyk.double.uint8 = @double_to_uint8; enctab.cmyk.uint8.double = @uint8_to_double; enctab.cmyk.uint16.double = @uint16_to_double; enctab.cmyk.double.uint16 = @double_to_uint16; enctab.cmyk.uint8.uint16 = @uint8_to_uint16; enctab.cmyk.uint16.uint8 = @uint16_to_uint8; enctab.color_n.double.uint8 = @double_to_uint8; enctab.color_n.uint8.double = @uint8_to_double; enctab.color_n.uint16.double = @uint16_to_double; enctab.color_n.double.uint16 = @double_to_uint16; enctab.color_n.uint8.uint16 = @uint8_to_uint16; enctab.color_n.uint16.uint8 = @uint16_to_uint8; enctab.lch.double.uint8 = @output_encoding_ignored; enctab.lch.double.uint16 = @output_encoding_ignored; enctab.upvpl.double.uint8 = @output_encoding_ignored; enctab.upvpl.double.uint16 = @output_encoding_ignored; enctab.uvl.double.uint8 = @output_encoding_ignored; enctab.uvl.double.uint16 = @output_encoding_ignored; enctab.xyl.double.uint8 = @output_encoding_ignored; enctab.xyl.double.uint16 = @output_encoding_ignored; end table = enctab;
github
wangsuyuan/Imageprocesingtoobox-master
applyclut.m
.m
Imageprocesingtoobox-master/colorspaces/private/applyclut.m
14,307
utf_8
1f9f958d5637f3116dafff4fb178d679
function out = applyclut(varargin) %APPLYCLUT Convert color data using ICC CLUT-based transform. % OUT = APPLYCLUT(IN, LUTTAG, ISXYZIN, ISXYZOUT) converts data % from one space to another -- including the ICC profile connection % spaces (XYZ and L*a*b*), various device spaces, or a gamut alarm % -- using a CLUT-based transform. LUTTAG is a field of a profile % structure, such as that returned by ICCREAD, corresponding to a % profile lut tag (lut8Type, lut16Type, lutAtoBType, lutBtoAType). % OUT will have the same number of rows as IN, the number of data % points to be processed. The number of columns may differ, % since it is the number of channels in the respective color % spaces (input and output): A connection space must have 3 channels, % device spaces are limited to 15 channels by the ICC spec, and a % gamut alarm has a single (Boolean) output channel. IN and OUT % are represented in one of the standard ICC encodings for % device spaces or device-independent spaces, as uint8 or uint16. % ISXYZIN is optional and defaults to 0; it should be set to 1 % if IN is represented in the XYZ connection space. ISXYZOUT % is also optional and defaults to 0; it should be set to 1 if % OUT is represented in the XYZ connection space. % % See also MAKECFORM, APPLYCFORM. % Copyright 2002-2010 The MathWorks, Inc. % Original author: Scott Gregory, 10/20/02 % Check input arguments narginchk(2, 4); in = varargin{1}; validateattributes(in,{'uint8','uint16'},{'real','2d','nonsparse','finite'},... 'applyclut','IN',1); % Check the luttag luttag = varargin{2}; validateattributes(luttag,{'struct'},{'nonempty'},'applyclut','LUTTAG',1); checkLutTag(luttag); % Determine intrinsic data type of luttag if luttag.MFT == 1 luttagbytes = 1; % all tables are uint8 scale = 255; elseif luttag.MFT <= 4 luttagbytes = 2; % all tables are uint16, except possibly for % the CLUT in lutAtoBType and lutBtoAType scale = 65535; else error(message('images:applyclut:unrecognizedLutType')) end % Check the input and output colorspaces if nargin > 2 isxyzin = varargin{3}; else isxyzin = false; end if nargin > 3 isxyzout = varargin{4}; else isxyzout = false; end % Check that incoming data type matches that of luttag if (isa(in, 'uint8') && luttagbytes == 2) || ... (isa(in, 'uint16') && luttagbytes == 1) error(message('images:applyclut:datatypeMismatch')) end % Convert inputs to double, scaled to [0, 1] out = double(in) / scale; % Adjust v.2 16-bit Lab encoding to v. 4 if luttag.MFT == 4 && ~isxyzin % lutBtoAType out = out * 257 / 256; end % Apply 1D pre-shapers, if present if ~isempty(luttag.PreShaper) out = cellinterp(out, luttag.PreShaper); end % Apply pre-matrix, if present and if, % for v. 2, input space is XYZ if ~isempty(luttag.PreMatrix) && (isxyzin || luttag.MFT > 2) out = out * luttag.PreMatrix(1:3, 1:3)' ... + ones(size(out, 1), 1) * luttag.PreMatrix(1:3, 4)'; end % Apply 1D input tables, if present if ~isempty(luttag.InputTables) out = cellinterp(out, luttag.InputTables); end % Apply multidimensional grid tables, if present % Note: In v. 4, 8-bit CLUT might have to process 16-bit data. if ~isempty(luttag.CLUT) [chan_in, chan_out] = luttagchans(luttag); if isa(in, 'uint16') && isa(luttag.CLUT, 'uint8') % v. 4 option clut_scale = scale / 257; else clut_scale = scale; end out = clut_scale * out; % rescale for clutinterp switch chan_in case 3 out = clutinterp_tet3(out, luttag.CLUT, chan_in, chan_out); case 4 out = clutinterp_tet4(out, luttag.CLUT, chan_in, chan_out); otherwise out = clutinterp(out, luttag.CLUT, chan_in, chan_out); end out = out / clut_scale; % scale back to [0, 1] end % Apply 1D output tables, if present if ~isempty(luttag.OutputTables) out = cellinterp(out, luttag.OutputTables); end % Apply post-matrix, if present if ~isempty(luttag.PostMatrix) out = out * luttag.PostMatrix(1:3, 1:3)' ... + ones(size(out, 1), 1) * luttag.PostMatrix(1:3, 4)'; end % Apply 1D post-shapers, if present if ~isempty(luttag.PostShaper) out = cellinterp(out, luttag.PostShaper); end % Adjust v. 4 16-bit lab encoding values to v. 2 if luttag.MFT == 3 && ~isxyzout % lutAtoBType out = out * 256 / 257; end % Re-encode according to luttag data type if luttagbytes == 1 out = uint8(scale * out); else out = uint16(scale * out); end %========================================================================== function checkLutTag(luttag) if ~isfield(luttag, 'MFT') || ... ~isfield(luttag, 'PreShaper') || ... ~isfield(luttag, 'PreMatrix') || ... ~isfield(luttag, 'InputTables') || ... ~isfield(luttag, 'CLUT') || ... ~isfield(luttag, 'OutputTables') || ... ~isfield(luttag, 'PostMatrix') || ... ~isfield(luttag, 'PostShaper') error(message('images:applyclut:invalidLuttag')); end %-------------------------------------------------------------------------- %========================================================================== function out = cellinterp(in, shapers) % Process data through cell array of 1D shapers % Check number of channels chan_in = size(shapers, 2); if size(in, 2) ~= chan_in error(message('images:applyclut:numberOfChannels')) end % Evaluate shapers, channel by channel out = zeros(size(in)); for chan = 1 : chan_in out(:, chan) = applycurve(in(:, chan), shapers{chan}); end %-------------------------------------------------------------------------- %========================================================================== function out = clutinterp(in, clut, chan_in, chan_out) % Interpolate in multi-dimensional grid tables % Note: order of arguments must be reversed, since % ICC format requires row-major order, while % Matlab uses column-major. Thus, a function % f(R, G, B) is treated as f(B, G, R). if size(in, 2) ~= chan_in error(message('images:applyclut:dataMismatch')); end % Clip grid_index values before calling interpn to make sure it doesn't % return NaNs. if isa(clut, 'uint8') scale = 255; else scale = 65535; end in = min(in, scale); in = max(in, 0); % Construct sampling grids for interpn csiz = size(clut); % clut dimensions, including output channels siz = csiz(1 : chan_in); % grid dimensions samples = cell(size(siz)); for k = 1 : chan_in samples{k} = linspace(0, scale, size(clut, k)); end % Put arguments for interpn into cell array interpargs = cell(1, 2 * chan_in + 1); [interpargs{1 : chan_in}] = ndgrid(samples{:}); % Xi arguments for i = 1 : chan_in % Yi arguments, in reverse order (see help text) interpargs{chan_in + 1 + i} = in(:, chan_in + 1 - i); end % Allocate and initialize output array out = zeros(size(in, 1), chan_out); % Interpolate for each output channel clut2 = reshape(clut, prod(siz), chan_out); for i = 1 : chan_out clut3 = reshape(clut2(:, i), siz); % Select by output channel interpargs{chan_in + 1} = double(clut3); % V argument for interpn out(:, i) = interpn(interpargs{:}); end %-------------------------------------------------------------------------- %========================================================================== function res = clutinterp_tet3(in, clut, chan_in, chan_out) % Interpolate in multi-dimensional grid tables using tetrahedral method % of Sakamoto % Note: order of arguments must be reversed, since % ICC format requires row-major order, while % Matlab uses column-major. Thus, a function % f(R, G, B) is treated as f(B, G, R). % Preconditions if size(in, 2) ~= chan_in error(message('images:applyclut:dataMismatch')) end % Compute possible cube corner offsets from base vertex csiz = size(clut); % clut dimensions, including output channels siz = csiz(1 : chan_in); % grid dimensions % Recall that last channel varies most rapidly in table offs = [siz(2)*siz(1), siz(1), 1]; %tmp = { 1, 2, 3, [1 2], [1 3], [2 3], [1 2 3]}; tmp = { 1, 3, 2, [1 2], [1 3], [2 3], [1 2 3]}; offs_list = zeros(1,8); for i = 1 : 7 offs_list(i+1) = sum(offs(tmp{i})); end % Scaling of clut is either [0,255] or [0,65535] if isa(clut, 'uint8') scale = 255; else scale = 65535; end % Setup 8x4 tables indexing into wgts and offsets for each simplex % in order to allow vectorized computation wgt_ids = ones(8, 4); off_ids = zeros(8, 4); off_ids(8, :) = offs_list([1 2 5 8]); off_ids(4, :) = offs_list([1 2 6 8]); off_ids(2, :) = offs_list([1 3 6 8]); off_ids(1, :) = offs_list([1 3 7 8]); off_ids(5, :) = offs_list([1 4 7 8]); off_ids(7, :) = offs_list([1 4 5 8]); wgt_ids(8, :) = [1 4 6 9]; wgt_ids(4, :) = [1 5 6 8]; wgt_ids(2, :) = [3 5 4 8]; wgt_ids(1, :) = [3 6 4 7]; wgt_ids(5, :) = [2 6 5 7]; wgt_ids(7, :) = [2 4 5 9]; wgt_ids = wgt_ids - 1; % Separate input values into integer and fractional components integ = zeros(size(in, 1), 3); frac = zeros(size(in, 1), 3); for i = 1 : 3 tmp = double(in(:, i)) * (siz(i) - 1) / scale; integ(:, i) = min(siz(i) - 2, floor(tmp)); % 0-based frac(:, i) = tmp - integ(:, i); end tmp = []; %#ok<NASGU> % Compute indices of base of cubes base_inds = integ * offs' + 1; integ = []; %#ok<NASGU> % Compute an id in [1,8] indicating which part of the cube the point is in ids = ( frac(:, [1 1 2]) > frac(:, [2 3 3])) * [1 2 4]' + 1; % Compute possible weighting factors wgts = [ 1 - frac, abs(frac(:, [1 1 2]) - frac(:, [2 3 3])), frac]; % Accumulate result n = size(ids,1); clut2 = reshape(double(clut), prod(siz), chan_out); wgt_inds = (1 : n)' + wgt_ids(ids, 1) * n; res = bsxfun(@times, wgts(wgt_inds), clut2(base_inds,:)); for i = 2 : 4 inds = base_inds + off_ids(ids, i); wgt_inds = (1 : n)' + wgt_ids(ids, i) * n; res = res + bsxfun(@times, wgts(wgt_inds), clut2(inds,:)); end %-------------------------------------------------------------------------- %========================================================================== function res = clutinterp_tet4(in, clut, chan_in, chan_out) % Interpolate in multi-dimensional grid tables using 4d tetrahedral equivalent % method of Sakamoto % Note: order of arguments must be reversed, since % ICC format requires row-major order, while % Matlab uses column-major. Thus, a function % f(R, G, B) is treated as f(B, G, R). % Preconditions if size(in, 2) ~= chan_in error(message('images:applyclut:dataMismatch')) end % Compute possible hypercube corner offsets from base vertex csiz = size(clut); % clut dimensions, including output channels siz = csiz(1 : chan_in); % grid dimensions % Recall that last channel varies most rapidly in table offs = [siz(3)*siz(2)*siz(1), siz(2)*siz(1), siz(1), 1]; tmp = { 1, 2, 3, 4, [ 1 2], [1 3], [1 4], [2 3], [2 4], [3 4], ... [1 2 3], [1 2 4], [1 3 4], [2 3 4], [1 2 3 4]}; offs_list = zeros(1,16); for i = 1 : 15 offs_list(i+1) = sum(offs(tmp{i})); end % Scaling of clut is either [0,255] or [0,65535] if isa(clut, 'uint8') scale = 255; else scale = 65535; end % Setup 64x5 tables indexing into wgts and offsets for each simplex % in order to allow vectorized computation wgt_ids = ones(64, 5); off_ids = zeros(64, 5); off_ids(64, :) = offs_list([1 2 6 12 16]); off_ids(32, :) = offs_list([1 2 6 13 16]); off_ids(56, :) = offs_list([1 2 7 12 16]); off_ids(40, :) = offs_list([1 2 7 14 16]); off_ids(16, :) = offs_list([1 2 8 13 16]); off_ids( 8, :) = offs_list([1 2 8 14 16]); off_ids(63, :) = offs_list([1 3 6 12 16]); off_ids(31, :) = offs_list([1 3 6 13 16]); off_ids(61, :) = offs_list([1 3 9 12 16]); off_ids(57, :) = offs_list([1 3 9 15 16]); off_ids(27, :) = offs_list([1 3 10 13 16]); off_ids(25, :) = offs_list([1 3 10 15 16]); off_ids(54, :) = offs_list([1 4 7 12 16]); off_ids(38, :) = offs_list([1 4 7 14 16]); off_ids(53, :) = offs_list([1 4 9 12 16]); off_ids(49, :) = offs_list([1 4 9 15 16]); off_ids(33, :) = offs_list([1 4 11 15 16]); off_ids(34, :) = offs_list([1 4 11 14 16]); off_ids(12, :) = offs_list([1 5 8 13 16]); off_ids( 4, :) = offs_list([1 5 8 14 16]); off_ids(11, :) = offs_list([1 5 10 13 16]); off_ids( 9, :) = offs_list([1 5 10 15 16]); off_ids( 2, :) = offs_list([1 5 11 14 16]); off_ids( 1, :) = offs_list([1 5 11 15 16]); wgt_ids(64, :) = [1 5 8 10 14]; wgt_ids(32, :) = [1 5 9 10 13]; wgt_ids(56, :) = [1 6 8 9 14]; wgt_ids(40, :) = [1 6 10 9 12]; wgt_ids(16, :) = [1 7 9 8 13]; wgt_ids( 8, :) = [1 7 10 8 12]; wgt_ids(63, :) = [2 5 6 10 14]; wgt_ids(31, :) = [2 5 7 10 13]; wgt_ids(61, :) = [2 8 6 7 14]; wgt_ids(57, :) = [2 8 10 7 11]; wgt_ids(27, :) = [2 9 7 6 13]; wgt_ids(25, :) = [2 9 10 6 11]; wgt_ids(54, :) = [3 6 5 9 14]; wgt_ids(38, :) = [3 6 7 9 12]; wgt_ids(53, :) = [3 8 5 7 14]; wgt_ids(49, :) = [3 8 9 7 11]; wgt_ids(33, :) = [3 10 9 5 11]; wgt_ids(34, :) = [3 10 7 5 12]; wgt_ids(12, :) = [4 7 5 8 13]; wgt_ids( 4, :) = [4 7 6 8 12]; wgt_ids(11, :) = [4 9 5 6 13]; wgt_ids( 9, :) = [4 9 8 6 11]; wgt_ids( 2, :) = [4 10 6 5 12]; wgt_ids( 1, :) = [4 10 8 5 11]; wgt_ids = wgt_ids - 1; % Separate input values into integer and fractional components integ = zeros(size(in, 1), 4); frac = zeros(size(in, 1), 4); for i = 1 : 4 tmp = double(in(:, i)) * (siz(i) - 1) / scale; integ(:, i) = min(siz(i) - 2, floor(tmp)); % 0-based frac(:, i) = tmp - integ(:, i); end tmp = []; %#ok<NASGU> % Compute indices of base of hypercubes base_inds = integ * offs' + 1; integ = []; %#ok<NASGU> % Compute an id in [1,64] indicating which part of the hypercube the point is in ids = ( frac(:, [1 1 1 2 2 3]) > frac(:, [2 3 4 3 4 4])) * ... [1 2 4 8 16 32]' + 1; % Compute possible weighting factors wgts = [ 1 - frac, abs(frac(:, [1 1 1 2 2 3]) - frac(:, [2 3 4 3 4 4])), frac]; % Accumulate result n = size(ids,1); clut2 = reshape(double(clut), prod(siz), chan_out); wgt_inds = (1 : n)' + wgt_ids(ids, 1) * n; res = bsxfun(@times, wgts(wgt_inds), clut2(base_inds,:)); for i = 2 : 5 inds = base_inds + off_ids(ids, i); wgt_inds = (1 : n)' + wgt_ids(ids, i) * n; res = res + bsxfun(@times, wgts(wgt_inds), clut2(inds,:)); end %--------------------------------------------------------------------------
github
wangsuyuan/Imageprocesingtoobox-master
applycurve.m
.m
Imageprocesingtoobox-master/colorspaces/private/applycurve.m
4,109
utf_8
6ab9436f08a6f43a2a18bffda9532eab
function out = applycurve(in, curve, inverse, method) %APPLYCURVE processes vector data through a function % OUT = APPLYCURVE(IN, CURVE, INVERSE, METHOD) remaps the input % vector IN through a tag of curveType or parametricCurveType % to compute the output vector OUT. The tag is defined by % CURVE, which is a uint8 or uint16 vector for curveType or a % structure, of specific form, for parametricCurveType. % INVERSE is an optional argument, defaulting to zero, for % selecting between forward or inverse evaluation of the function: % non-zero values imply the inverse. METHOD is a string specifying % the method of interpolation for interp1; the default is 'linear'. % Copyright 2005-2011 The MathWorks, Inc. % Poe % Original author: Robert Poe 10/15/05 % Check input arguments narginchk(2, 4); validateattributes(in, {'double'}, ... {'real', 'vector', 'nonsparse', 'finite'}, ... 'applycurve', 'IN', 1); if nargin < 3 isfwd = true; else isfwd = (inverse == 0); end if nargin < 4 method = 'linear'; end % Clip input to [0, 1] in = min(max(in, 0.0), 1.0); % Detect parametricCurveType and evaluate if isstruct(curve) if isfield(curve, 'FunctionType') funtype = curve.FunctionType; else error(message('images:applycurve:noParametricCurveTypeFunction')) end if isfield(curve, 'Params') && isa(curve.Params, 'double') params = curve.Params; else error(message('images:applycurve:noParametricCurveTypeParams')) end out = applyparametric(in, funtype, isfwd, params); % Handle curveType else if isa(curve, 'uint8') scale = 255.0; elseif isa(curve, 'uint16') scale = 65535.0; else error(message('images:applycurve:invalidDataType')) end clength = length(curve); if clength > 1 % 1D LUT % Rescale LUT to [0, 1] lut1d = double(curve) / scale; samples = linspace(0.0, 1.0, clength)'; if isfwd % Evaluate in forward direction out = interp1(samples, lut1d, in, method); else % Make inverse LUT monotonic for backward direction [Xi, Yi] = monotonicize(lut1d, samples); out = interp1(Xi, Yi, in, method); end elseif scale == 65535.0 % power law if isfwd gamma = double(curve) / 256.0; else if curve == 0 gamma = 1.0; else gamma = 256.0 / double(curve); end end out = in .^ gamma; else error(message('images:applycurve:numLutEntries')); end end % Clip output to [0, 1] out = max(min(out, 1.0), 0.0); %----------------------------------------------- function [xout, yout] = monotonicize(xin, yin) % Remove non-monotonic values from XIN, along with % corresponding rows from YIN, copying the remaining % rows into XOUT and YOUT, respectively. if ~isvector(xin) || length(xin) < 2 error(message('images:applygraytrc_inv:BadInputXi')) end nin = length(xin); xin = reshape(xin, nin, 1); % make column vector if size(yin, 1) ~= nin error(message('images:applygraytrc_inv:BadInputYi')) end % Determine overall polarity of XIN % Flip rows, if necessary, to make it an increasing sequence fliprows = xin(nin) < xin(1); if fliprows xin = flip(xin, 1); yin = flip(yin, 1); end xout = []; yout = []; % Find start of first increasing sequence iin = 1; while iin < nin && xin(iin + 1, 1) <= xin(iin, 1) iin = iin + 1; end igood = iin; % Keep this row and move on iout = 1; xout(iout, 1) = xin(igood, 1); yout(iout, :) = yin(igood, :); iin = iin + 1; while iin <= nin % Save rows only when increasing if xin(iin, 1) > xin(igood, 1) igood = iin; iout = iout + 1; xout(iout, 1) = xin(igood, 1); %#ok<AGROW> yout(iout, :) = yin(igood, :); %#ok<AGROW> end iin = iin + 1; end % Flip output arrays, if inputs were flipped if fliprows xout = flip(xout, 1); yout = flip(yout, 1); end
github
ZijingMao/baselineeegtest-master
eeglab.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/eeglab.m
110,746
utf_8
56cbc9c3855016194dd332ea1e3634fd
% eeglab() - Matlab graphic user interface environment for % electrophysiological data analysis incorporating the ICA/EEG toolbox % (Makeig et al.) developed at CNL / The Salk Institute, 1997-2001. % Released 11/2002- as EEGLAB (Delorme, Makeig, et al.) at the Swartz Center % for Computational Neuroscience, Institute for Neural Computation, % University of California San Diego (http://sccn.ucsd.edu/). % User feedback welcome: email [email protected] % % Authors: Arnaud Delorme and Scott Makeig, with substantial contributions % from Colin Humphries, Sigurd Enghoff, Tzyy-Ping Jung, plus % contributions % from Tony Bell, Te-Won Lee, Luca Finelli and many other contributors. % % Description: % EEGLAB is Matlab-based software for processing continuous or event-related % EEG or other physiological data. It is designed for use by both novice and % expert Matlab users. In normal use, the EEGLAB graphic interface calls % graphic functions via pop-up function windows. The EEGLAB history mechanism % can save the resulting Matlab calls to disk for later incorporation into % Matlab scripts. A single data structure ('EEG') containing all dataset % parameters may be accessed and modified directly from the Matlab commandline. % EEGLAB now recognizes "plugins," sets of EEGLAB functions linked to the EEGLAB % main menu through an "eegplugin_[name].m" function (Ex. >> help eeplugin_besa.m). % % Usage: 1) To (re)start EEGLAB, type % >> eeglab % Ignores any loaded datasets % 2) To redaw and update the EEGLAB interface, type % >> eeglab redraw % Scans for non-empty datasets % >> eeglab rebuild % Closes and rebuilds the EEGLAB window % >> eeglab versions % State EEGLAB version number % % >> type "license.txt" % the GNU public license % >> web http://sccn.ucsd.edu/eeglab/tutorial/ % the EEGLAB tutorial % >> help eeg_checkset % the EEG dataset structure % % GUI Functions calling eponymous processing and plotting functions: % ------------------------------------------------------------------ % <a href="matlab:helpwin pop_eegfilt">pop_eegfilt</a> - bandpass filter data (eegfilt()) % <a href="matlab:helpwin pop_eegplot">pop_eegplot</a> - scrolling multichannel data viewer (eegplot()) % <a href="matlab:helpwin pop_eegthresh">pop_eegthresh</a> - simple thresholding method (eegthresh()) % <a href="matlab:helpwin pop_envtopo">pop_envtopo</a> - plot ERP data and component contributions (envtopo()) % <a href="matlab:helpwin pop_epoch">pop_epoch</a> - extract epochs from a continuous dataset (epoch()) % <a href="matlab:helpwin pop_erpimage">pop_erpimage</a> - plot single epochs as an image (erpimage()) % <a href="matlab:helpwin pop_jointprob">pop_jointprob</a> - reject epochs using joint probability (jointprob()) % <a href="matlab:helpwin pop_loaddat">pop_loaddat</a> - load Neuroscan .DAT info file (loaddat()) % <a href="matlab:helpwin pop_loadcnt">pop_loadcnt</a> - load Neuroscan .CNT data (lndcnt()) % <a href="matlab:helpwin pop_loadeeg">pop_loadeeg</a> - load Neuroscan .EEG data (loadeeg()) % <a href="matlab:helpwin pop_loadbva">pop_loadbva</a> - load Brain Vision Analyser matlab files % <a href="matlab:helpwin pop_plotdata">pop_plotdata</a> - plot data epochs in rectangular array (plotdata()) % <a href="matlab:helpwin pop_readegi">pop_readegi</a> - load binary EGI data file (readegi()) % <a href="matlab:helpwin pop_rejkurt">pop_rejkurt</a> - compute data kurtosis (rejkurt()) % <a href="matlab:helpwin pop_rejtrend">pop_rejtrend</a> - reject EEG epochs showing linear trends (rejtrend()) % <a href="matlab:helpwin pop_resample">pop_resample</a> - change data sampling rate (resample()) % <a href="matlab:helpwin pop_rmbase">pop_rmbase</a> - remove epoch baseline (rmbase()) % <a href="matlab:helpwin pop_runica">pop_runica</a> - run infomax ICA decomposition (runica()) % <a href="matlab:helpwin pop_newtimef">pop_newtimef</a> - event-related time-frequency (newtimef()) % <a href="matlab:helpwin pop_timtopo">pop_timtopo</a> - plot ERP and scalp maps (timtopo()) % <a href="matlab:helpwin pop_topoplot">pop_topoplot</a> - plot scalp maps (topoplot()) % <a href="matlab:helpwin pop_snapread">pop_snapread</a> - read Snapmaster .SMA files (snapread()) % <a href="matlab:helpwin pop_newcrossf">pop_newcrossf</a> - event-related cross-coherence (newcrossf()) % <a href="matlab:helpwin pop_spectopo">pop_spectopo</a> - plot all channel spectra and scalp maps (spectopo()) % <a href="matlab:helpwin pop_plottopo">pop_plottopo</a> - plot a data epoch in a topographic array (plottopo()) % <a href="matlab:helpwin pop_readedf">pop_readedf</a> - read .EDF EEG data format (readedf()) % <a href="matlab:helpwin pop_headplot">pop_headplot</a> - plot a 3-D data scalp map (headplot()) % <a href="matlab:helpwin pop_reref">pop_reref</a> - re-reference data (reref()) % <a href="matlab:helpwin pop_signalstat">pop_signalstat</a> - plot signal or component statistic (signalstat()) % % Other GUI functions: % ------------------- % <a href="matlab:helpwin pop_chanevent">pop_chanevent</a> - import events stored in data channel(s) % <a href="matlab:helpwin pop_comments">pop_comments</a> - edit dataset comment ('about') text % <a href="matlab:helpwin pop_compareerps">pop_compareerps</a> - compare two dataset ERPs using plottopo() % <a href="matlab:helpwin pop_prop">pop_prop</a> - plot channel or component properties (erpimage, spectra, map) % <a href="matlab:helpwin pop_copyset">pop_copyset</a> - copy dataset % <a href="matlab:helpwin pop_dispcomp">pop_dispcomp</a> - display component scalp maps with reject buttons % <a href="matlab:helpwin pop_editeventfield">pop_editeventfield</a> - edit event fields % <a href="matlab:helpwin pop_editeventvals">pop_editeventvals</a> - edit event values % <a href="matlab:helpwin pop_editset">pop_editset</a> - edit dataset information % <a href="matlab:helpwin pop_export">pop_export</a> - export data or ica activity to ASCII file % <a href="matlab:helpwin pop_expica">pop_expica</a> - export ica weights or inverse matrix to ASCII file % <a href="matlab:helpwin pop_icathresh">pop_icathresh</a> - choose rejection thresholds (in development) % <a href="matlab:helpwin pop_importepoch">pop_importepoch</a> - import epoch info ASCII file % <a href="matlab:helpwin pop_importevent">pop_importevent</a> - import event info ASCII file % <a href="matlab:helpwin pop_importpres">pop_importpres</a> - import Presentation info file % <a href="matlab:helpwin pop_importev2">pop_importev2</a> - import Neuroscan ev2 file % <a href="matlab:helpwin pop_loadset">pop_loadset</a> - load dataset % <a href="matlab:helpwin pop_mergeset">pop_mergeset</a> - merge two datasets % <a href="matlab:helpwin pop_rejepoch">pop_rejepoch</a> - reject pre-identified epochs in a EEG dataset % <a href="matlab:helpwin pop_rejspec">pop_rejspec</a> - reject based on spectrum (computes spectrum -% eegthresh) % <a href="matlab:helpwin pop_saveh">pop_saveh</a> - save EEGLAB command history % <a href="matlab:helpwin pop_saveset">pop_saveset</a> - save dataset % <a href="matlab:helpwin pop_select">pop_select</a> - select data (epochs, time points, channels ...) % <a href="matlab:helpwin pop_selectevent">pop_selectevent</a> - select events % <a href="matlab:helpwin pop_subcomp">pop_subcomp</a> - subtract components from data % % Non-GUI functions use for handling the EEG structure: % ---------------------------------------------------- % <a href="matlab:helpwin eeg_checkset">eeg_checkset</a> - check dataset parameter consistency % <a href="matlab:helpwin eeg_context">eeg_context</a> - return info about events surrounding given events % <a href="matlab:helpwin pop_delset">pop_delset</a> - delete dataset % <a href="matlab:helpwin pop_editoptions">pop_editoptions</a> - edit the option file % <a href="matlab:helpwin eeg_emptyset">eeg_emptyset</a> - empty dataset % <a href="matlab:helpwin eeg_epochformat">eeg_epochformat</a> - convert epoch array to structure % <a href="matlab:helpwin eeg_eventformat">eeg_eventformat</a> - convert event array to structure % <a href="matlab:helpwin eeg_getepochevent">eeg_getepochevent</a> - return event values for a subset of event types % <a href="matlab:helpwin eeg_global">eeg_global</a> - global variables % <a href="matlab:helpwin eeg_multieegplot">eeg_multieegplot</a> - plot several rejections (using different colors) % <a href="matlab:helpwin eeg_options">eeg_options</a> - option file % <a href="matlab:helpwin eeg_rejsuperpose">eeg_rejsuperpose</a> - use by rejmenu to superpose all rejections % <a href="matlab:helpwin eeg_rejmacro">eeg_rejmacro</a> - used by all rejection functions % <a href="matlab:helpwin pop_rejmenu">pop_rejmenu</a> - rejection menu (with all rejection methods visible) % <a href="matlab:helpwin eeg_retrieve">eeg_retrieve</a> - retrieve dataset from ALLEEG % <a href="matlab:helpwin eeg_store">eeg_store</a> - store dataset into ALLEEG % % Help functions: % -------------- % <a href="matlab:helpwin eeg_helpadmin">eeg_helpadmin</a> - help on admin function % <a href="matlab:helpwin eeg_helphelp">eeg_helphelp</a> - help on help % <a href="matlab:helpwin eeg_helpmenu">eeg_helpmenu</a> - EEG help menus % <a href="matlab:helpwin eeg_helppop">eeg_helppop</a> - help on pop_ and eeg_ functions % <a href="matlab:helpwin eeg_helpsigproc">eeg_helpsigproc</a> - help on % Copyright (C) 2001 Arnaud Delorme and Scott Makeig, Salk Institute, % [email protected], [email protected]. % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function varargout = eeglab( onearg ) if nargout > 0 varargout = { [] [] 0 {} [] }; %[ALLEEG, EEG, CURRENTSET, ALLCOM] end; % check Matlab version % -------------------- vers = version; tmpv = which('version'); if ~isempty(findstr(lower(tmpv), 'biosig')) [tmpp tmp] = fileparts(tmpv); rmpath(tmpp); end; if str2num(vers(1)) < 7 && str2num(vers(1)) >= 5 tmpWarning = warning('backtrace'); warning backtrace off; warning('You are using a Matlab version older than 7.0'); warning('This Matlab version is too old to run the current EEGLAB'); warning('Download EEGLAB 4.3b at http://sccn.ucsd.edu/eeglab/eeglab4.5b.teaching.zip'); warning('This version of EEGLAB is compatible with all Matlab version down to Matlab 5.3'); warning(tmpWarning); return; end; % check Matlab version % -------------------- vers = version; indp = find(vers == '.'); if str2num(vers(indp(1)+1)) > 1, vers = [ vers(1:indp(1)) '0' vers(indp(1)+1:end) ]; end; indp = find(vers == '.'); vers = str2num(vers(1:indp(2)-1)); if vers < 7.06 tmpWarning = warning('backtrace'); warning backtrace off; warning('You are using a Matlab version older than 7.6 (2008a)'); warning('Some of the EEGLAB functions might not be functional'); warning('Download EEGLAB 4.3b at http://sccn.ucsd.edu/eeglab/eeglab4.5b.teaching.zip'); warning('This version of EEGLAB is compatible with all Matlab version down to Matlab 5.3'); warning(tmpWarning); end; % check for duplicate versions of EEGLAB % -------------------------------------- eeglabpath = mywhich('eeglab.m'); eeglabpath = eeglabpath(1:end-length('eeglab.m')); if nargin < 1 eeglabpath2 = ''; if strcmpi(eeglabpath, pwd) || strcmpi(eeglabpath(1:end-1), pwd) cd('functions'); warning('off', 'MATLAB:rmpath:DirNotFound'); rmpath(eeglabpath); warning('on', 'MATLAB:rmpath:DirNotFound'); eeglabpath2 = mywhich('eeglab.m'); cd('..'); else try, rmpath(eeglabpath); catch, end; eeglabpath2 = mywhich('eeglab.m'); end; if ~isempty(eeglabpath2) evalin('base', 'clear classes updater;'); eeglabpath2 = eeglabpath2(1:end-length('eeglab.m')); tmpWarning = warning('backtrace'); warning backtrace off; disp('******************************************************'); warning('There are at least two versions of EEGLAB in your path'); warning(sprintf('One is at %s', eeglabpath)); warning(sprintf('The other one is at %s', eeglabpath2)); warning(tmpWarning); end; addpath(eeglabpath); end; % add the paths % ------------- if strcmpi(eeglabpath, './') || strcmpi(eeglabpath, '.\'), eeglabpath = [ pwd filesep ]; end; % solve BIOSIG problem % -------------------- pathtmp = mywhich('wilcoxon_test'); if ~isempty(pathtmp) try, rmpath(pathtmp(1:end-15)); catch, end; end; % test for local SCCN copy % ------------------------ if ~iseeglabdeployed2 addpathifnotinlist(eeglabpath); if exist( fullfile( eeglabpath, 'functions', 'adminfunc') ) ~= 7 warning('EEGLAB subfolders not found'); end; end; % determine file format % --------------------- fileformat = 'maclinux'; comp = computer; try if strcmpi(comp(1:3), 'GLN') | strcmpi(comp(1:3), 'MAC') | strcmpi(comp(1:3), 'SOL') fileformat = 'maclinux'; elseif strcmpi(comp(1:5), 'pcwin') fileformat = 'pcwin'; end; end; % add paths % --------- if ~iseeglabdeployed2 myaddpath( eeglabpath, 'eeg_checkset.m', [ 'functions' filesep 'adminfunc' ]); myaddpath( eeglabpath, 'eeg_checkset.m', [ 'functions' filesep 'adminfunc' ]); myaddpath( eeglabpath, ['@mmo' filesep 'mmo.m'], 'functions'); myaddpath( eeglabpath, 'readeetraklocs.m', [ 'functions' filesep 'sigprocfunc' ]); myaddpath( eeglabpath, 'supergui.m', [ 'functions' filesep 'guifunc' ]); myaddpath( eeglabpath, 'pop_study.m', [ 'functions' filesep 'studyfunc' ]); myaddpath( eeglabpath, 'pop_loadbci.m', [ 'functions' filesep 'popfunc' ]); myaddpath( eeglabpath, 'statcond.m', [ 'functions' filesep 'statistics' ]); myaddpath( eeglabpath, 'timefreq.m', [ 'functions' filesep 'timefreqfunc' ]); myaddpath( eeglabpath, 'icademo.m', [ 'functions' filesep 'miscfunc' ]); myaddpath( eeglabpath, 'eeglab1020.ced', [ 'functions' filesep 'resources' ]); myaddpath( eeglabpath, 'startpane.m', [ 'functions' filesep 'javachatfunc' ]); addpathifnotinlist(fullfile(eeglabpath, 'plugins')); eeglab_options; % remove path to to fmrlab if neceecessary path_runica = fileparts(mywhich('runica')); if length(path_runica) > 6 && strcmpi(path_runica(end-5:end), 'fmrlab') rmpath(path_runica); end; % add path if toolboxes are missing % --------------------------------- signalpath = fullfile(eeglabpath, 'functions', 'octavefunc', 'signal'); optimpath = fullfile(eeglabpath, 'functions', 'octavefunc', 'optim'); if option_donotusetoolboxes p1 = fileparts(mywhich('ttest')); p2 = fileparts(mywhich('filtfilt')); p3 = fileparts(mywhich('optimtool')); p4 = fileparts(mywhich('gray2ind')); if ~isempty(p1), rmpath(p1); end; if ~isempty(p2), rmpath(p2); end; if ~isempty(p3), rmpath(p3); end; if ~isempty(p4), rmpath(p4); end; end; if ~license('test','signal_toolbox') || exist('pwelch') ~= 2 warning('off', 'MATLAB:dispatcher:nameConflict'); addpath( signalpath ); else warning('off', 'MATLAB:rmpath:DirNotFound'); rmpathifpresent( signalpath ); rmpathifpresent(optimpath); warning('on', 'MATLAB:rmpath:DirNotFound'); end; if ~license('test','optim_toolbox') && ~ismatlab addpath( optimpath ); else warning('off', 'MATLAB:rmpath:DirNotFound'); rmpathifpresent( optimpath ); warning('on', 'MATLAB:rmpath:DirNotFound'); end; else eeglab_options; end; if nargin == 1 && strcmp(onearg, 'redraw') if evalin('base', 'exist(''EEG'')', '0') == 1 evalin('base', 'eeg_global;'); end; end; eeg_global; % remove empty datasets in ALLEEG while ~isempty(ALLEEG) && isempty(ALLEEG(end).data) ALLEEG(end) = []; end; if ~isempty(ALLEEG) && max(CURRENTSET) > length(ALLEEG) CURRENTSET = 1; EEG = eeg_retrieve(ALLEEG, CURRENTSET); end; % for the history function % ------------------------ comtmp = 'warning off MATLAB:mir_warning_variable_used_as_function'; evalin('base' , comtmp, ''); evalin('caller', comtmp, ''); evalin('base', 'eeg_global;'); if nargin < 1 | exist('EEG') ~= 1 clear global EEG ALLEEG CURRENTSET ALLCOM LASTCOM STUDY; CURRENTSTUDY = 0; eeg_global; EEG = eeg_emptyset; eegh('[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;'); if ismatlab && get(0, 'screendepth') <= 8 disp('Warning: screen color depth too low, some colors will be inaccurate in time-frequency plots'); end; end; if nargin == 1 if strcmp(onearg, 'versions') disp( [ 'EEGLAB v' eeg_getversion ] ); elseif strcmp(onearg, 'nogui') if nargout < 1, clear ALLEEG; end; % do not return output var return; elseif strcmp(onearg, 'redraw') if ~ismatlab,return; end; W_MAIN = findobj('tag', 'EEGLAB'); if ~isempty(W_MAIN) updatemenu; if nargout < 1, clear ALLEEG; end; % do not return output var return; else eegh('eeglab(''redraw'');'); end; elseif strcmp(onearg, 'rebuild') if ~ismatlab,return; end; W_MAIN = findobj('tag', 'EEGLAB'); close(W_MAIN); eeglab; return; else eegh('[ALLEEG EEG CURRENTSET ALLCOM] = eeglab(''rebuild'');'); end; else onearg = 'rebuild'; end; ALLCOM = ALLCOM; try, eval('colordef white;'); catch end; % default option folder % --------------------- if ~iseeglabdeployed2 eeglab_options; fprintf('eeglab: options file is %s%seeg_options.m\n', homefolder, filesep); end; % checking strings % ---------------- e_try = 'try,'; e_catch = 'catch, eeglab_error; LASTCOM= ''''; clear EEGTMP ALLEEGTMP STUDYTMP; end;'; nocheck = e_try; ret = 'if ~isempty(LASTCOM), if LASTCOM(1) == -1, LASTCOM = ''''; return; end; end;'; check = ['[EEG LASTCOM] = eeg_checkset(EEG, ''data'');' ret ' eegh(LASTCOM);' e_try]; checkcont = ['[EEG LASTCOM] = eeg_checkset(EEG, ''contdata'');' ret ' eegh(LASTCOM);' e_try]; checkica = ['[EEG LASTCOM] = eeg_checkset(EEG, ''ica'');' ret ' eegh(LASTCOM);' e_try]; checkepoch = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'');' ret ' eegh(LASTCOM);' e_try]; checkevent = ['[EEG LASTCOM] = eeg_checkset(EEG, ''event'');' ret ' eegh(LASTCOM);' e_try]; checkbesa = ['[EEG LASTCOM] = eeg_checkset(EEG, ''besa'');' ret ' eegh(''% no history yet for BESA dipole localization'');' e_try]; checkepochica = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''ica'');' ret ' eegh(LASTCOM);' e_try]; checkplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''chanloc'');' ret ' eegh(LASTCOM);' e_try]; checkicaplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''ica'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try]; checkepochplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try]; checkepochicaplot = ['[EEG LASTCOM] = eeg_checkset(EEG, ''epoch'', ''ica'', ''chanloc'');' ret ' eegh(LASTCOM);' e_try]; % check string and backup old dataset % ----------------------------------- backup = [ 'if CURRENTSET ~= 0,' ... ' [ ALLEEG EEG ] = eeg_store(ALLEEG, EEG, CURRENTSET, ''savegui'');' ... ' eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET, ''''savedata'''');'');' ... 'end;' ]; storecall = '[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET); eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);'');'; storenewcall = '[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''study'', ~isempty(STUDY)+0); eegh(LASTCOM);'; storeallcall = [ 'if ~isempty(ALLEEG) & ~isempty(ALLEEG(1).data), ALLEEG = eeg_checkset(ALLEEG);' ... 'EEG = eeg_retrieve(ALLEEG, CURRENTSET); eegh(''ALLEEG = eeg_checkset(ALLEEG); EEG = eeg_retrieve(ALLEEG, CURRENTSET);''); end;' ]; testeegtmp = 'if exist(''EEGTMP'') == 1, EEG = EEGTMP; clear EEGTMP; end;'; % for backward compatibility ifeeg = 'if ~isempty(LASTCOM) & ~isempty(EEG),'; ifeegnh = 'if ~isempty(LASTCOM) & ~isempty(EEG) & ~isempty(findstr(''='',LASTCOM)),'; % nh = no dataset history % ----------------------- e_storeall_nh = [e_catch 'eegh(LASTCOM);' ifeeg storeallcall 'disp(''Done.''); end; eeglab(''redraw'');']; e_hist_nh = [e_catch 'eegh(LASTCOM);']; % same as above but also save history in dataset % ---------------------------------------------- e_newset = [e_catch 'EEG = eegh(LASTCOM, EEG);' testeegtmp ifeeg storenewcall 'disp(''Done.''); end; eeglab(''redraw'');']; e_store = [e_catch 'EEG = eegh(LASTCOM, EEG);' ifeegnh storecall 'disp(''Done.''); end; eeglab(''redraw'');']; e_hist = [e_catch 'EEG = eegh(LASTCOM, EEG);']; e_histdone = [e_catch 'EEG = eegh(LASTCOM, EEG); if ~isempty(LASTCOM), disp(''Done.''); end;' ]; % study checking % -------------- e_load_study = [e_catch 'if ~isempty(LASTCOM), STUDY = STUDYTMP; STUDY = eegh(LASTCOM, STUDY); ALLEEG = ALLEEGTMP; EEG = ALLEEG; CURRENTSET = [1:length(EEG)]; eegh(''CURRENTSTUDY = 1; EEG = ALLEEG; CURRENTSET = [1:length(EEG)];''); CURRENTSTUDY = 1; disp(''Done.''); end; clear ALLEEGTMP STUDYTMP; eeglab(''redraw'');']; e_plot_study = [e_catch 'if ~isempty(LASTCOM), STUDY = STUDYTMP; STUDY = eegh(LASTCOM, STUDY); disp(''Done.''); end; clear ALLEEGTMP STUDYTMP; eeglab(''redraw'');']; % ALLEEG not modified % build structures for plugins % ---------------------------- trystrs.no_check = e_try; trystrs.check_data = check; trystrs.check_ica = checkica; trystrs.check_cont = checkcont; trystrs.check_epoch = checkepoch; trystrs.check_event = checkevent; trystrs.check_epoch_ica = checkepochica; trystrs.check_chanlocs = checkplot; trystrs.check_epoch_chanlocs = checkepochplot; trystrs.check_epoch_ica_chanlocs = checkepochicaplot; catchstrs.add_to_hist = e_hist; catchstrs.store_and_hist = e_store; catchstrs.new_and_hist = e_newset; catchstrs.new_non_empty = e_newset; catchstrs.update_study = e_plot_study; % create eeglab figure % -------------------- javaobj = eeg_mainfig(onearg); % detecting icalab % ---------------- if exist('icalab') disp('ICALAB toolbox detected (algo. added to "run ICA" interface)'); end; if ~iseeglabdeployed2 % check for older version of Fieldtrip and presence of topoplot % ------------------------------------------------------------- if ismatlab ptopoplot = fileparts(mywhich('cbar')); ptopoplot2 = fileparts(mywhich('topoplot')); if ~strcmpi(ptopoplot, ptopoplot2), %disp(' Warning: duplicate function topoplot.m in Fieldtrip and EEGLAB'); %disp(' EEGLAB function will prevail and call the Fieldtrip one when appropriate'); addpath(ptopoplot); end; end; end; cb_importdata = [ nocheck '[EEG LASTCOM] = pop_importdata;' e_newset ]; cb_readegi = [ nocheck '[EEG LASTCOM] = pop_readegi;' e_newset ]; cb_readsegegi = [ nocheck '[EEG LASTCOM] = pop_readsegegi;' e_newset ]; cb_readegiepo = [ nocheck '[EEG LASTCOM] = pop_importegimat;' e_newset ]; cb_loadbci = [ nocheck '[EEG LASTCOM] = pop_loadbci;' e_newset ]; cb_snapread = [ nocheck '[EEG LASTCOM] = pop_snapread;' e_newset ]; cb_loadcnt = [ nocheck '[EEG LASTCOM] = pop_loadcnt;' e_newset ]; cb_loadeeg = [ nocheck '[EEG LASTCOM] = pop_loadeeg;' e_newset ]; cb_biosig = [ nocheck '[EEG LASTCOM] = pop_biosig; ' e_newset ]; cb_fileio = [ nocheck '[EEG LASTCOM] = pop_fileio; ' e_newset ]; cb_fileio2 = [ nocheck '[EEG LASTCOM] = pop_fileiodir;' e_newset ]; cb_importepoch = [ checkepoch '[EEG LASTCOM] = pop_importepoch(EEG);' e_store ]; cb_loaddat = [ checkepoch '[EEG LASTCOM]= pop_loaddat(EEG);' e_store ]; cb_importevent = [ check '[EEG LASTCOM] = pop_importevent(EEG);' e_store ]; cb_chanevent = [ check '[EEG LASTCOM]= pop_chanevent(EEG);' e_store ]; cb_importpres = [ check '[EEG LASTCOM]= pop_importpres(EEG);' e_store ]; cb_importev2 = [ check '[EEG LASTCOM]= pop_importev2(EEG);' e_store ]; cb_export = [ check 'LASTCOM = pop_export(EEG);' e_histdone ]; cb_expica1 = [ check 'LASTCOM = pop_expica(EEG, ''weights'');' e_histdone ]; cb_expica2 = [ check 'LASTCOM = pop_expica(EEG, ''inv'');' e_histdone ]; cb_expevents = [ check 'LASTCOM = pop_expevents(EEG);' e_histdone ]; cb_expdata = [ check 'LASTCOM = pop_writeeeg(EEG);' e_histdone ]; cb_loadset = [ nocheck '[EEG LASTCOM] = pop_loadset;' e_newset]; cb_saveset = [ check '[EEG LASTCOM] = pop_saveset(EEG, ''savemode'', ''resave'');' e_store ]; cb_savesetas = [ check '[EEG LASTCOM] = pop_saveset(EEG);' e_store ]; cb_delset = [ nocheck '[ALLEEG LASTCOM] = pop_delset(ALLEEG, -CURRENTSET);' e_hist_nh 'eeglab redraw;' ]; cb_study1 = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_study([], ALLEEG , ''gui'', ''on'');' e_load_study]; cb_study2 = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_study([], isempty(ALLEEG), ''gui'', ''on'');' e_load_study]; cb_studyerp = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_studyerp;' e_load_study]; cb_loadstudy = [ nocheck 'pop_stdwarn; [STUDYTMP ALLEEGTMP LASTCOM] = pop_loadstudy; if ~isempty(LASTCOM), STUDYTMP = std_renamestudyfiles(STUDYTMP, ALLEEGTMP); end;' e_load_study]; cb_savestudy1 = [ check '[STUDYTMP ALLEEGTMP LASTCOM] = pop_savestudy(STUDY, EEG, ''savemode'', ''resave'');' e_load_study]; cb_savestudy2 = [ check '[STUDYTMP ALLEEGTMP LASTCOM] = pop_savestudy(STUDY, EEG);' e_load_study]; cb_clearstudy = 'LASTCOM = ''STUDY = []; CURRENTSTUDY = 0; ALLEEG = []; EEG=[]; CURRENTSET=[];''; eval(LASTCOM); eegh( LASTCOM ); eeglab redraw;'; cb_editoptions = [ nocheck 'if isfield(ALLEEG, ''nbchan''), LASTCOM = pop_editoptions(length([ ALLEEG.nbchan ]) >1);' ... 'else LASTCOM = pop_editoptions(0); end;' e_storeall_nh]; cb_plugin1 = [ nocheck 'if plugin_extract(''import'', PLUGINLIST) , close(findobj(''tag'', ''EEGLAB'')); eeglab redraw; end;' e_hist_nh ]; cb_plugin2 = [ nocheck 'if plugin_extract(''process'', PLUGINLIST), close(findobj(''tag'', ''EEGLAB'')); eeglab redraw; end;' e_hist_nh ]; cb_saveh1 = [ nocheck 'LASTCOM = pop_saveh(EEG.history);' e_hist_nh]; cb_saveh2 = [ nocheck 'LASTCOM = pop_saveh(ALLCOM);' e_hist_nh]; cb_runsc = [ nocheck 'LASTCOM = pop_runscript;' e_hist ]; cb_quit = [ 'close(gcf); disp(''To save the EEGLAB command history >> pop_saveh(ALLCOM);'');' ... 'clear global EEG ALLEEG LASTCOM CURRENTSET;']; cb_editset = [ check '[EEG LASTCOM] = pop_editset(EEG);' e_store]; cb_editeventf = [ checkevent '[EEG LASTCOM] = pop_editeventfield(EEG);' e_store]; cb_editeventv = [ checkevent '[EEG LASTCOM] = pop_editeventvals(EEG);' e_store]; cb_comments = [ check '[EEG.comments LASTCOM] =pop_comments(EEG.comments, ''About this dataset'');' e_store]; cb_chanedit = [ 'disp(''IMPORTANT: After importing/modifying data channels, you must close'');' ... 'disp(''the channel editing window for the changes to take effect in EEGLAB.'');' ... 'disp(''TIP: Call this function directy from the prompt, ">> pop_chanedit([]);"'');' ... 'disp('' to convert between channel location file formats'');' ... '[EEG TMPINFO TMP LASTCOM] = pop_chanedit(EEG); if ~isempty(LASTCOM), EEG = eeg_checkset(EEG, ''chanlocsize'');' ... 'clear TMPINFO TMP; EEG = eegh(LASTCOM, EEG);' storecall 'end; eeglab(''redraw'');']; cb_select = [ check '[EEG LASTCOM] = pop_select(EEG);' e_newset]; cb_rmdat = [ checkevent '[EEG LASTCOM] = pop_rmdat(EEG);' e_newset]; cb_selectevent = [ checkevent '[EEG TMP LASTCOM] = pop_selectevent(EEG); clear TMP;' e_newset ]; cb_copyset = [ check '[ALLEEG EEG CURRENTSET LASTCOM] = pop_copyset(ALLEEG, CURRENTSET); eeglab(''redraw'');' e_hist_nh]; cb_mergeset = [ check '[EEG LASTCOM] = pop_mergeset(ALLEEG);' e_newset]; cb_resample = [ check '[EEG LASTCOM] = pop_resample(EEG);' e_newset]; cb_eegfilt = [ check '[EEG LASTCOM] = pop_eegfilt(EEG);' e_newset]; cb_interp = [ check '[EEG LASTCOM] = pop_interp(EEG); ' e_newset]; cb_reref = [ check '[EEG LASTCOM] = pop_reref(EEG);' e_newset]; cb_eegplot = [ checkcont '[LASTCOM] = pop_eegplot(EEG, 1);' e_hist]; cb_epoch = [ check '[EEG tmp LASTCOM] = pop_epoch(EEG); clear tmp;' e_newset check '[EEG LASTCOM] = pop_rmbase(EEG);' e_newset]; cb_rmbase = [ check '[EEG LASTCOM] = pop_rmbase(EEG);' e_store]; cb_runica = [ check '[EEG LASTCOM] = pop_runica(EEG);' e_store]; cb_subcomp = [ checkica '[EEG LASTCOM] = pop_subcomp(EEG);' e_newset]; %cb_chanrej = [ check 'pop_rejchan(EEG); LASTCOM = '''';' e_hist]; cb_chanrej = [ check '[EEG tmp1 tmp2 LASTCOM] = pop_rejchan(EEG); clear tmp1 tmp2;' e_hist]; cb_autorej = [ checkepoch '[EEG tmpp LASTCOM] = pop_autorej(EEG); clear tmpp;' e_hist]; cb_rejcont = [ check '[EEG tmp1 tmp2 LASTCOM] = pop_rejcont(EEG); clear tmp1 tmp2;' e_hist]; cb_rejmenu1 = [ check 'pop_rejmenu(EEG, 1); LASTCOM = '''';' e_hist]; cb_eegplotrej1 = [ check '[LASTCOM] = pop_eegplot(EEG, 1);' e_hist]; cb_eegthresh1 = [ checkepoch '[TMP LASTCOM] = pop_eegthresh(EEG, 1); clear TMP;' e_hist]; cb_rejtrend1 = [ checkepoch '[EEG LASTCOM] = pop_rejtrend(EEG, 1);' e_store]; cb_jointprob1 = [ checkepoch '[EEG LASTCOM] = pop_jointprob(EEG, 1);' e_store]; cb_rejkurt1 = [ checkepoch '[EEG LASTCOM] = pop_rejkurt(EEG, 1);' e_store]; cb_rejspec1 = [ checkepoch '[EEG Itmp LASTCOM] = pop_rejspec(EEG, 1); clear Itmp;' e_store]; cb_rejsup1 = [ checkepochica '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 1,1,1,1,1,1,1,1); eegh(LASTCOM);' ... 'LASTCOM = ''EEG.reject.icarejmanual = EEG.reject.rejglobal;''; eval(LASTCOM);' e_store ]; cb_rejsup2 = [ checkepoch '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 1,1,1,1,1,1,1,1); EEG = eegh(LASTCOM, EEG);' ... '[EEG LASTCOM] = pop_rejepoch(EEG);' e_newset]; cb_selectcomps = [ checkicaplot '[EEG LASTCOM] = pop_selectcomps(EEG);' e_store]; cb_rejmenu2 = [ checkepochica 'pop_rejmenu(EEG, 0); LASTCOM ='''';' e_hist]; cb_eegplotrej2 = [ checkica '[LASTCOM] = pop_eegplot(EEG, 0);' e_hist]; cb_eegthresh2 = [ checkepochica '[TMP LASTCOM] = pop_eegthresh(EEG, 0); clear TMP;' e_hist]; cb_rejtrend2 = [ checkepochica '[EEG LASTCOM] = pop_rejtrend(EEG, 0);' e_store]; cb_jointprob2 = [ checkepochica '[EEG LASTCOM] = pop_jointprob(EEG, 0);' e_store]; cb_rejkurt2 = [ checkepochica '[EEG LASTCOM] = pop_rejkurt(EEG, 0);' e_store]; cb_rejspec2 = [ checkepochica '[EEG Itmp LASTCOM] = pop_rejspec(EEG, 1); clear Itmp;' e_store]; cb_rejsup3 = [ checkepochica '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 0,1,1,1,1,1,1,1); eegh(LASTCOM);' ... 'LASTCOM = ''EEG.reject.rejmanual = EEG.reject.rejglobal;''; eval(LASTCOM);' e_store ]; cb_rejsup4 = [ checkepochica '[EEG LASTCOM] = eeg_rejsuperpose(EEG, 0,1,1,1,1,1,1,1); EEG = eegh(LASTCOM, EEG);' ... '[EEG LASTCOM] = pop_rejepoch(EEG);' e_newset ]; cb_topoblank1 = [ checkplot 'LASTCOM = [''figure; topoplot([],EEG.chanlocs, ''''style'''', ''''blank'''', ' ... '''''electrodes'''', ''''labelpoint'''', ''''chaninfo'''', EEG.chaninfo);'']; eval(LASTCOM);' e_hist]; cb_topoblank2 = [ checkplot 'LASTCOM = [''figure; topoplot([],EEG.chanlocs, ''''style'''', ''''blank'''', ' ... '''''electrodes'''', ''''numpoint'''', ''''chaninfo'''', EEG.chaninfo);'']; eval(LASTCOM);' e_hist]; cb_eegplot1 = [ check 'LASTCOM = pop_eegplot(EEG, 1, 1, 1);' e_hist]; cb_spectopo1 = [ check 'LASTCOM = pop_spectopo(EEG, 1);' e_hist]; cb_prop1 = [ checkplot 'LASTCOM = pop_prop(EEG,1);' e_hist]; cb_erpimage1 = [ checkepoch 'LASTCOM = pop_erpimage(EEG, 1, eegh(''find'',''pop_erpimage(EEG,1''));' e_hist]; cb_timtopo = [ checkplot 'LASTCOM = pop_timtopo(EEG);' e_hist]; cb_plottopo = [ check 'LASTCOM = pop_plottopo(EEG);' e_hist]; cb_topoplot1 = [ checkplot 'LASTCOM = pop_topoplot(EEG, 1);' e_hist]; cb_headplot1 = [ checkplot '[EEG LASTCOM] = pop_headplot(EEG, 1);' e_store]; cb_comperp1 = [ checkepoch 'LASTCOM = pop_comperp(ALLEEG);' e_hist]; cb_eegplot2 = [ checkica '[LASTCOM] = pop_eegplot(EEG, 0, 1, 1);' e_hist]; cb_spectopo2 = [ checkicaplot 'LASTCOM = pop_spectopo(EEG, 0);' e_hist]; cb_topoplot2 = [ checkicaplot 'LASTCOM = pop_topoplot(EEG, 0);' e_hist]; cb_headplot2 = [ checkicaplot '[EEG LASTCOM] = pop_headplot(EEG, 0);' e_store]; cb_prop2 = [ checkicaplot 'LASTCOM = pop_prop(EEG,0);' e_hist]; cb_erpimage2 = [ checkepochica 'LASTCOM = pop_erpimage(EEG, 0, eegh(''find'',''pop_erpimage(EEG,0''));' e_hist]; cb_envtopo1 = [ checkica 'LASTCOM = pop_envtopo(EEG);' e_hist]; cb_envtopo2 = [ checkica 'if length(ALLEEG) == 1, error(''Need at least 2 datasets''); end; LASTCOM = pop_envtopo(ALLEEG);' e_hist]; cb_plotdata2 = [ checkepochica '[tmpeeg LASTCOM] = pop_plotdata(EEG, 0); clear tmpeeg;' e_hist]; cb_comperp2 = [ checkepochica 'LASTCOM = pop_comperp(ALLEEG, 0);' e_hist]; cb_signalstat1 = [ check 'LASTCOM = pop_signalstat(EEG, 1);' e_hist]; cb_signalstat2 = [ checkica 'LASTCOM = pop_signalstat(EEG, 0);' e_hist]; cb_eventstat = [ checkevent 'LASTCOM = pop_eventstat(EEG);' e_hist]; cb_timef1 = [ check 'LASTCOM = pop_newtimef(EEG, 1, eegh(''find'',''pop_newtimef(EEG,1''));' e_hist]; cb_crossf1 = [ check 'LASTCOM = pop_newcrossf(EEG, 1,eegh(''find'',''pop_newcrossf(EEG,1''));' e_hist]; cb_timef2 = [ checkica 'LASTCOM = pop_newtimef(EEG, 0, eegh(''find'',''pop_newtimef(EEG,0''));' e_hist]; cb_crossf2 = [ checkica 'LASTCOM = pop_newcrossf(EEG, 0,eegh(''find'',''pop_newcrossf(EEG,0''));' e_hist]; cb_study3 = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_study(STUDY, ALLEEG, ''gui'', ''on'');' e_load_study]; cb_studydesign = [ nocheck '[STUDYTMP LASTCOM] = pop_studydesign(STUDY, ALLEEG); ALLEEGTMP = ALLEEG;' e_plot_study]; cb_precomp = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_precomp(STUDY, ALLEEG);' e_plot_study]; cb_chanplot = [ nocheck '[STUDYTMP LASTCOM] = pop_chanplot(STUDY, ALLEEG); ALLEEGTMP=ALLEEG;' e_plot_study]; cb_precomp2 = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_precomp(STUDY, ALLEEG, ''components'');' e_plot_study]; cb_preclust = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_preclust(STUDY, ALLEEG);' e_plot_study]; cb_clust = [ nocheck '[STUDYTMP ALLEEGTMP LASTCOM] = pop_clust(STUDY, ALLEEG);' e_plot_study]; cb_clustedit = [ nocheck 'ALLEEGTMP = ALLEEG; [STUDYTMP LASTCOM] = pop_clustedit(STUDY, ALLEEG);' e_plot_study]; % % % add STUDY plugin menus % if exist('eegplugin_stderpimage') % structure.uilist = { { } ... % {'style' 'pushbutton' 'string' 'Plot ERPimage' 'Callback' 'stderpimageplugin_plot(''onecomp'', gcf);' } { } ... % {'style' 'pushbutton' 'string' 'Plot ERPimage(s)' 'Callback' 'stderpimageplugin_plot(''oneclust'', gcf);' } }; % structure.geometry = { [1] [1 0.3 1] }; % arg = vararg2str( { structure } ); % cb_clustedit = [ nocheck 'ALLEEGTMP = ALLEEG; [STUDYTMP LASTCOM] = pop_clustedit(STUDY, ALLEEG, [], ' arg ');' e_load_study]; % end; % menu definition % --------------- if ismatlab % defaults % -------- % startup:on % study:off % chanloc:off % epoch:on % continuous:on on = 'study:on'; onnostudy = ''; ondata = 'startup:off'; onepoch = 'startup:off;continuous:off'; ondatastudy = 'startup:off;study:on'; onchannel = 'startup:off;chanloc:on'; onepochchan = 'startup:off;continuous:off;chanloc:on'; onstudy = 'startup:off;epoch:off;continuous:off;study:on'; W_MAIN = findobj('tag', 'EEGLAB'); EEGUSERDAT = get(W_MAIN, 'userdata'); set(W_MAIN, 'MenuBar', 'none'); file_m = uimenu( W_MAIN, 'Label', 'File' , 'userdata', on); import_m = uimenu( file_m, 'Label', 'Import data' , 'userdata', onnostudy); neuro_m = uimenu( import_m, 'Label', 'Using EEGLAB functions and plugins' , 'tag', 'import data' , 'userdata', onnostudy); epoch_m = uimenu( file_m, 'Label', 'Import epoch info', 'tag', 'import epoch', 'userdata', onepoch); event_m = uimenu( file_m, 'Label', 'Import event info', 'tag', 'import event', 'userdata', ondata); exportm = uimenu( file_m, 'Label', 'Export' , 'tag', 'export' , 'userdata', ondata); edit_m = uimenu( W_MAIN, 'Label', 'Edit' , 'userdata', ondata); tools_m = uimenu( W_MAIN, 'Label', 'Tools', 'tag', 'tools' , 'userdata', ondatastudy); plot_m = uimenu( W_MAIN, 'Label', 'Plot', 'tag', 'plot' , 'userdata', ondata); loc_m = uimenu( plot_m, 'Label', 'Channel locations' , 'userdata', onchannel); std_m = uimenu( W_MAIN, 'Label', 'Study', 'tag', 'study' , 'userdata', onstudy); set_m = uimenu( W_MAIN, 'Label', 'Datasets' , 'userdata', ondatastudy); help_m = uimenu( W_MAIN, 'Label', 'Help' , 'userdata', on); uimenu( neuro_m, 'Label', 'From ASCII/float file or Matlab array' , 'CallBack', cb_importdata); %uimenu( neuro_m, 'Label', 'From Netstation .mff (FILE-IO toolbox)', 'CallBack', cb_fileio2, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From Netstation binary simple file' , 'CallBack', cb_readegi, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From Multiple seg. Netstation files' , 'CallBack', cb_readsegegi); uimenu( neuro_m, 'Label', 'From Netstation Matlab files' , 'CallBack', cb_readegiepo); uimenu( neuro_m, 'Label', 'From BCI2000 ASCII file' , 'CallBack', cb_loadbci, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From Snapmaster .SMA file' , 'CallBack', cb_snapread, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From Neuroscan .CNT file' , 'CallBack', cb_loadcnt, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From Neuroscan .EEG file' , 'CallBack', cb_loadeeg); % BIOSIG MENUS % ------------ uimenu( neuro_m, 'Label', 'From Biosemi BDF file (BIOSIG toolbox)', 'CallBack' , cb_biosig, 'Separator', 'on'); uimenu( neuro_m, 'Label', 'From EDF/EDF+/GDF files (BIOSIG toolbox)', 'CallBack', cb_biosig); uimenu( epoch_m, 'Label', 'From Matlab array or ASCII file' , 'CallBack', cb_importepoch); uimenu( epoch_m, 'Label', 'From Neuroscan .DAT file' , 'CallBack', cb_loaddat); uimenu( event_m, 'Label', 'From Matlab array or ASCII file' , 'CallBack', cb_importevent); uimenu( event_m, 'Label', 'From data channel' , 'CallBack', cb_chanevent); uimenu( event_m, 'Label', 'From Presentation .LOG file' , 'CallBack', cb_importpres); uimenu( event_m, 'Label', 'From E-Prime ASCII (text) file' , 'CallBack', cb_importevent); uimenu( event_m, 'Label', 'From Neuroscan .ev2 file' , 'CallBack', cb_importev2); uimenu( exportm, 'Label', 'Data and ICA activity to text file' , 'CallBack', cb_export); uimenu( exportm, 'Label', 'Weight matrix to text file' , 'CallBack', cb_expica1); uimenu( exportm, 'Label', 'Inverse weight matrix to text file' , 'CallBack', cb_expica2); uimenu( exportm, 'Label', 'Events to text file' , 'CallBack', cb_expevents); uimenu( exportm, 'Label', 'Data to EDF/BDF/GDF file' , 'CallBack', cb_expdata, 'separator', 'on'); uimenu( file_m, 'Label', 'Load existing dataset' , 'userdata', onnostudy, 'CallBack', cb_loadset, 'Separator', 'on'); uimenu( file_m, 'Label', 'Save current dataset(s)' , 'userdata', ondatastudy, 'CallBack', cb_saveset); uimenu( file_m, 'Label', 'Save current dataset as' , 'userdata', ondata, 'CallBack', cb_savesetas); uimenu( file_m, 'Label', 'Clear dataset(s)' , 'userdata', ondata, 'CallBack', cb_delset); std2_m = uimenu( file_m, 'Label', 'Create study' , 'userdata', on , 'Separator', 'on'); uimenu( std2_m, 'Label', 'Using all loaded datasets' , 'userdata', ondata , 'Callback', cb_study1); uimenu( std2_m, 'Label', 'Browse for datasets' , 'userdata', on , 'Callback', cb_study2); uimenu( std2_m, 'Label', 'Simple ERP STUDY' , 'userdata', on , 'Callback', cb_studyerp); uimenu( file_m, 'Label', 'Load existing study' , 'userdata', on , 'CallBack', cb_loadstudy,'Separator', 'on' ); uimenu( file_m, 'Label', 'Save current study' , 'userdata', onstudy, 'CallBack', cb_savestudy1); uimenu( file_m, 'Label', 'Save current study as' , 'userdata', onstudy, 'CallBack', cb_savestudy2); uimenu( file_m, 'Label', 'Clear study / Clear all' , 'userdata', ondatastudy, 'CallBack', cb_clearstudy); uimenu( file_m, 'Label', 'Memory and other options' , 'userdata', on , 'CallBack', cb_editoptions, 'Separator', 'on'); hist_m = uimenu( file_m, 'Label', 'History scripts' , 'userdata', on , 'Separator', 'on'); uimenu( hist_m, 'Label', 'Save dataset history script' , 'userdata', ondata , 'CallBack', cb_saveh1); uimenu( hist_m, 'Label', 'Save session history script' , 'userdata', ondatastudy, 'CallBack', cb_saveh2); uimenu( hist_m, 'Label', 'Run script' , 'userdata', on , 'CallBack', cb_runsc); plugin_m = uimenu( file_m, 'Label', 'Manage EEGLAB extensions' , 'userdata', on); uimenu( plugin_m, 'Label', 'Data import extensions' , 'userdata', on , 'CallBack', cb_plugin1); uimenu( plugin_m, 'Label', 'Data processing extensions' , 'userdata', on , 'CallBack', cb_plugin2); uimenu( file_m, 'Label', 'Quit' , 'userdata', on , 'CallBack', cb_quit, 'Separator', 'on'); uimenu( edit_m, 'Label', 'Dataset info' , 'userdata', ondata, 'CallBack', cb_editset); uimenu( edit_m, 'Label', 'Event fields' , 'userdata', ondata, 'CallBack', cb_editeventf); uimenu( edit_m, 'Label', 'Event values' , 'userdata', ondata, 'CallBack', cb_editeventv); uimenu( edit_m, 'Label', 'About this dataset' , 'userdata', ondata, 'CallBack', cb_comments); uimenu( edit_m, 'Label', 'Channel locations' , 'userdata', ondata, 'CallBack', cb_chanedit); uimenu( edit_m, 'Label', 'Select data' , 'userdata', ondata, 'CallBack', cb_select, 'Separator', 'on'); uimenu( edit_m, 'Label', 'Select data using events' , 'userdata', ondata, 'CallBack', cb_rmdat); uimenu( edit_m, 'Label', 'Select epochs or events' , 'userdata', ondata, 'CallBack', cb_selectevent); uimenu( edit_m, 'Label', 'Copy current dataset' , 'userdata', ondata, 'CallBack', cb_copyset, 'Separator', 'on'); uimenu( edit_m, 'Label', 'Append datasets' , 'userdata', ondata, 'CallBack', cb_mergeset); uimenu( edit_m, 'Label', 'Delete dataset(s) from memory' , 'userdata', ondata, 'CallBack', cb_delset); uimenu( tools_m, 'Label', 'Change sampling rate' , 'userdata', ondatastudy, 'CallBack', cb_resample); filter_m = uimenu( tools_m, 'Label', 'Filter the data' , 'userdata', ondatastudy, 'tag', 'filter'); uimenu( filter_m, 'Label', 'Basic FIR filter (legacy)' , 'userdata', ondatastudy, 'CallBack', cb_eegfilt); uimenu( tools_m, 'Label', 'Re-reference' , 'userdata', ondata, 'CallBack', cb_reref); uimenu( tools_m, 'Label', 'Interpolate electrodes' , 'userdata', ondata, 'CallBack', cb_interp); uimenu( tools_m, 'Label', 'Reject continuous data by eye' , 'userdata', ondata, 'CallBack', cb_eegplot); uimenu( tools_m, 'Label', 'Extract epochs' , 'userdata', ondata, 'CallBack', cb_epoch, 'Separator', 'on'); uimenu( tools_m, 'Label', 'Remove baseline' , 'userdata', ondatastudy, 'CallBack', cb_rmbase); uimenu( tools_m, 'Label', 'Run ICA' , 'userdata', ondatastudy, 'CallBack', cb_runica, 'foregroundcolor', 'b', 'Separator', 'on'); uimenu( tools_m, 'Label', 'Remove components' , 'userdata', ondata, 'CallBack', cb_subcomp); uimenu( tools_m, 'Label', 'Automatic channel rejection' , 'userdata', ondata, 'CallBack', cb_chanrej, 'Separator', 'on'); uimenu( tools_m, 'Label', 'Automatic continuous rejection' , 'userdata', ondata, 'CallBack', cb_rejcont); uimenu( tools_m, 'Label', 'Automatic epoch rejection' , 'userdata', onepoch, 'CallBack', cb_autorej); rej_m1 = uimenu( tools_m, 'Label', 'Reject data epochs' , 'userdata', onepoch); rej_m2 = uimenu( tools_m, 'Label', 'Reject data using ICA' , 'userdata', ondata ); uimenu( rej_m1, 'Label', 'Reject data (all methods)' , 'userdata', onepoch, 'CallBack', cb_rejmenu1); uimenu( rej_m1, 'Label', 'Reject by inspection' , 'userdata', onepoch, 'CallBack', cb_eegplotrej1); uimenu( rej_m1, 'Label', 'Reject extreme values' , 'userdata', onepoch, 'CallBack', cb_eegthresh1); uimenu( rej_m1, 'Label', 'Reject by linear trend/variance' , 'userdata', onepoch, 'CallBack', cb_rejtrend1); uimenu( rej_m1, 'Label', 'Reject by probability' , 'userdata', onepoch, 'CallBack', cb_jointprob1); uimenu( rej_m1, 'Label', 'Reject by kurtosis' , 'userdata', onepoch, 'CallBack', cb_rejkurt1); uimenu( rej_m1, 'Label', 'Reject by spectra' , 'userdata', onepoch, 'CallBack', cb_rejspec1); uimenu( rej_m1, 'Label', 'Export marks to ICA reject' , 'userdata', onepoch, 'CallBack', cb_rejsup1, 'separator', 'on'); uimenu( rej_m1, 'Label', 'Reject marked epochs' , 'userdata', onepoch, 'CallBack', cb_rejsup2, 'separator', 'on', 'foregroundcolor', 'b'); uimenu( rej_m2, 'Label', 'Reject components by map' , 'userdata', ondata , 'CallBack', cb_selectcomps); uimenu( rej_m2, 'Label', 'Reject data (all methods)' , 'userdata', onepoch, 'CallBack', cb_rejmenu2, 'Separator', 'on'); uimenu( rej_m2, 'Label', 'Reject by inspection' , 'userdata', onepoch, 'CallBack', cb_eegplotrej2); uimenu( rej_m2, 'Label', 'Reject extreme values' , 'userdata', onepoch, 'CallBack', cb_eegthresh2); uimenu( rej_m2, 'Label', 'Reject by linear trend/variance' , 'userdata', onepoch, 'CallBack', cb_rejtrend2); uimenu( rej_m2, 'Label', 'Reject by probability' , 'userdata', onepoch, 'CallBack', cb_jointprob2); uimenu( rej_m2, 'Label', 'Reject by kurtosis' , 'userdata', onepoch, 'CallBack', cb_rejkurt2); uimenu( rej_m2, 'Label', 'Reject by spectra' , 'userdata', onepoch, 'CallBack', cb_rejspec2); uimenu( rej_m2, 'Label', 'Export marks to data reject' , 'userdata', onepoch, 'CallBack', cb_rejsup3, 'separator', 'on'); uimenu( rej_m2, 'Label', 'Reject marked epochs' , 'userdata', onepoch, 'CallBack', cb_rejsup4, 'separator', 'on', 'foregroundcolor', 'b'); uimenu( loc_m, 'Label', 'By name' , 'userdata', onchannel, 'CallBack', cb_topoblank1); uimenu( loc_m, 'Label', 'By number' , 'userdata', onchannel, 'CallBack', cb_topoblank2); uimenu( plot_m, 'Label', 'Channel data (scroll)' , 'userdata', ondata , 'CallBack', cb_eegplot1, 'Separator', 'on'); uimenu( plot_m, 'Label', 'Channel spectra and maps' , 'userdata', ondata , 'CallBack', cb_spectopo1); uimenu( plot_m, 'Label', 'Channel properties' , 'userdata', ondata , 'CallBack', cb_prop1); uimenu( plot_m, 'Label', 'Channel ERP image' , 'userdata', onepoch, 'CallBack', cb_erpimage1); ERP_m = uimenu( plot_m, 'Label', 'Channel ERPs' , 'userdata', onepoch); uimenu( ERP_m, 'Label', 'With scalp maps' , 'CallBack', cb_timtopo); uimenu( ERP_m, 'Label', 'In scalp/rect. array' , 'CallBack', cb_plottopo); topo_m = uimenu( plot_m, 'Label', 'ERP map series' , 'userdata', onepochchan); uimenu( topo_m, 'Label', 'In 2-D' , 'CallBack', cb_topoplot1); uimenu( topo_m, 'Label', 'In 3-D' , 'CallBack', cb_headplot1); uimenu( plot_m, 'Label', 'Sum/Compare ERPs' , 'userdata', onepoch, 'CallBack', cb_comperp1); uimenu( plot_m, 'Label', 'Component activations (scroll)' , 'userdata', ondata , 'CallBack', cb_eegplot2,'Separator', 'on'); uimenu( plot_m, 'Label', 'Component spectra and maps' , 'userdata', ondata , 'CallBack', cb_spectopo2); tica_m = uimenu( plot_m, 'Label', 'Component maps' , 'userdata', onchannel); uimenu( tica_m, 'Label', 'In 2-D' , 'CallBack', cb_topoplot2); uimenu( tica_m, 'Label', 'In 3-D' , 'CallBack', cb_headplot2); uimenu( plot_m, 'Label', 'Component properties' , 'userdata', ondata , 'CallBack', cb_prop2); uimenu( plot_m, 'Label', 'Component ERP image' , 'userdata', onepoch, 'CallBack', cb_erpimage2); ERPC_m = uimenu( plot_m, 'Label', 'Component ERPs' , 'userdata', onepoch); uimenu( ERPC_m, 'Label', 'With component maps' , 'CallBack', cb_envtopo1); uimenu( ERPC_m, 'Label', 'With comp. maps (compare)' , 'CallBack', cb_envtopo2); uimenu( ERPC_m, 'Label', 'In rectangular array' , 'CallBack', cb_plotdata2); uimenu( plot_m, 'Label', 'Sum/Compare comp. ERPs' , 'userdata', onepoch, 'CallBack', cb_comperp2); stat_m = uimenu( plot_m, 'Label', 'Data statistics', 'Separator', 'on', 'userdata', ondata ); uimenu( stat_m, 'Label', 'Channel statistics' , 'CallBack', cb_signalstat1); uimenu( stat_m, 'Label', 'Component statistics' , 'CallBack', cb_signalstat2); uimenu( stat_m, 'Label', 'Event statistics' , 'CallBack', cb_eventstat); spec_m = uimenu( plot_m, 'Label', 'Time-frequency transforms', 'Separator', 'on', 'userdata', ondata); uimenu( spec_m, 'Label', 'Channel time-frequency' , 'CallBack', cb_timef1); uimenu( spec_m, 'Label', 'Channel cross-coherence' , 'CallBack', cb_crossf1); uimenu( spec_m, 'Label', 'Component time-frequency' , 'CallBack', cb_timef2,'Separator', 'on'); uimenu( spec_m, 'Label', 'Component cross-coherence' , 'CallBack', cb_crossf2); uimenu( std_m, 'Label', 'Edit study info' , 'userdata', onstudy, 'CallBack', cb_study3); uimenu( std_m, 'Label', 'Select/Edit study design(s)' , 'userdata', onstudy, 'CallBack', cb_studydesign); uimenu( std_m, 'Label', 'Precompute channel measures' , 'userdata', onstudy, 'CallBack', cb_precomp, 'separator', 'on'); uimenu( std_m, 'Label', 'Plot channel measures' , 'userdata', onstudy, 'CallBack', cb_chanplot); uimenu( std_m, 'Label', 'Precompute component measures' , 'userdata', onstudy, 'CallBack', cb_precomp2, 'separator', 'on'); clust_m = uimenu( std_m, 'Label', 'PCA clustering (original)' , 'userdata', onstudy); uimenu( clust_m, 'Label', 'Build preclustering array' , 'userdata', onstudy, 'CallBack', cb_preclust); uimenu( clust_m, 'Label', 'Cluster components' , 'userdata', onstudy, 'CallBack', cb_clust); uimenu( std_m, 'Label', 'Edit/plot clusters' , 'userdata', onstudy, 'CallBack', cb_clustedit); if ~iseeglabdeployed2 %newerVersionMenu = uimenu( help_m, 'Label', 'Upgrade to the Latest Version' , 'userdata', on, 'ForegroundColor', [0.6 0 0]); uimenu( help_m, 'Label', 'About EEGLAB' , 'userdata', on, 'CallBack', 'pophelp(''eeglab'');'); uimenu( help_m, 'Label', 'About EEGLAB help' , 'userdata', on, 'CallBack', 'pophelp(''eeg_helphelp'');'); uimenu( help_m, 'Label', 'EEGLAB menus' , 'userdata', on, 'CallBack', 'pophelp(''eeg_helpmenu'');','separator','on'); help_1 = uimenu( help_m, 'Label', 'EEGLAB functions', 'userdata', on); uimenu( help_1, 'Label', 'Admin. functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpadmin'');'); uimenu( help_1, 'Label', 'Interactive pop_ functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helppop'');'); uimenu( help_1, 'Label', 'Signal processing functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpsigproc'');'); uimenu( help_1, 'Label', 'Group data (STUDY) functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpstudy'');'); uimenu( help_1, 'Label', 'Time-frequency functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helptimefreq'');'); uimenu( help_1, 'Label', 'Statistical functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpstatistics'');'); uimenu( help_1, 'Label', 'Graphic interface builder functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpgui'');'); uimenu( help_1, 'Label', 'Misc. command line functions' , 'userdata', on, 'Callback', 'pophelp(''eeg_helpmisc'');'); uimenu( help_m, 'Label', 'EEGLAB license' , 'userdata', on, 'CallBack', 'pophelp(''eeglablicense.txt'', 1);'); else uimenu( help_m, 'Label', 'About EEGLAB' , 'userdata', on, 'CallBack', 'abouteeglab;'); uimenu( help_m, 'Label', 'EEGLAB license' , 'userdata', on, 'CallBack', 'pophelp(''eeglablicense.txt'', 1);'); end; uimenu( help_m, 'Label', 'EEGLAB tutorial' , 'userdata', on, 'CallBack', 'tutorial;', 'Separator', 'on'); uimenu( help_m, 'Label', 'Email the EEGLAB team' , 'userdata', on, 'CallBack', 'web(''mailto:[email protected]'');'); end; if iseeglabdeployed2 disp('Adding FIELDTRIP toolbox functions'); disp('Adding BIOSIG toolbox functions'); disp('Adding FILE-IO toolbox functions'); funcname = { 'eegplugin_VisEd' ... 'eegplugin_eepimport' ... 'eegplugin_bdfimport' ... 'eegplugin_brainmovie' ... 'eegplugin_bva_io' ... 'eegplugin_ctfimport' ... 'eegplugin_dipfit' ... 'eegplugin_erpssimport' ... 'eegplugin_fmrib' ... 'eegplugin_iirfilt' ... 'eegplugin_ascinstep' ... 'eegplugin_loreta' ... 'eegplugin_miclust' ... 'eegplugin_4dneuroimaging' }; for indf = 1:length(funcname) try vers = feval(funcname{indf}, gcf, trystrs, catchstrs); disp(['EEGLAB: adding "' vers '" plugin' ]); catch feval(funcname{indf}, gcf, trystrs, catchstrs); disp(['EEGLAB: adding plugin function "' funcname{indf} '"' ]); end; end; else pluginlist = []; plugincount = 1; p = mywhich('eeglab.m'); p = p(1:findstr(p,'eeglab.m')-1); if strcmpi(p, './') || strcmpi(p, '.\'), p = [ pwd filesep ]; end; % scan deactivated plugin folder % ------------------------------ dircontent = dir(fullfile(p, 'deactivatedplugins')); dircontent = { dircontent.name }; for index = 1:length(dircontent) funcname = ''; pluginVersion = ''; if exist([p 'deactivatedplugins' filesep dircontent{index}]) == 7 if ~strcmpi(dircontent{index}, '.') & ~strcmpi(dircontent{index}, '..') tmpdir = dir([ p 'deactivatedplugins' filesep dircontent{index} filesep 'eegplugin*.m' ]); [ pluginName pluginVersion ] = parsepluginname(dircontent{index}); if ~isempty(tmpdir) funcname = tmpdir(1).name(1:end-2); end; end; else if ~isempty(findstr(dircontent{index}, 'eegplugin')) && dircontent{index}(end) == 'm' funcname = dircontent{index}(1:end-2); % remove .m [ pluginName pluginVersion ] = parsepluginname(dircontent{index}(10:end-2)); end; end; if ~isempty(pluginVersion) pluginlist(plugincount).plugin = pluginName; pluginlist(plugincount).version = pluginVersion; pluginlist(plugincount).foldername = dircontent{index}; if ~isempty(funcname) pluginlist(plugincount).funcname = funcname(10:end); else pluginlist(plugincount).funcname = ''; end if length(pluginlist(plugincount).funcname) > 1 && pluginlist(plugincount).funcname(1) == '_' pluginlist(plugincount).funcname(1) = []; end; pluginlist(plugincount).status = 'deactivated'; plugincount = plugincount+1; end; end; % scan plugin folder % ------------------ dircontent = dir(fullfile(p, 'plugins')); dircontent = { dircontent.name }; for index = 1:length(dircontent) % find function % ------------- funcname = ''; pluginVersion = []; if exist([p 'plugins' filesep dircontent{index}]) == 7 if ~strcmpi(dircontent{index}, '.') & ~strcmpi(dircontent{index}, '..') newpath = [ 'plugins' filesep dircontent{index} ]; tmpdir = dir([ p 'plugins' filesep dircontent{index} filesep 'eegplugin*.m' ]); addpathifnotinlist(fullfile(eeglabpath, newpath)); [ pluginName pluginVersion ] = parsepluginname(dircontent{index}); if ~isempty(tmpdir) %myaddpath(eeglabpath, tmpdir(1).name, newpath); funcname = tmpdir(1).name(1:end-2); end; % special case of subfolder for Fieldtrip % --------------------------------------- if ~isempty(findstr(lower(dircontent{index}), 'fieldtrip')) addpathifnotexist( fullfile(eeglabpath, newpath, 'compat') , 'electrodenormalize' ); addpathifnotexist( fullfile(eeglabpath, newpath, 'forward'), 'ft_sourcedepth.m'); addpathifnotexist( fullfile(eeglabpath, newpath, 'utilities'), 'ft_datatype.m'); ptopoplot = fileparts(mywhich('cbar')); ptopoplot2 = fileparts(mywhich('topoplot')); if ~isequal(ptopoplot, ptopoplot2) addpath(ptopoplot); end; end; % special case of subfolder for BIOSIG % ------------------------------------ if ~isempty(findstr(lower(dircontent{index}), 'biosig')) && isempty(findstr(lower(dircontent{index}), 'biosigplot')) addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 't200_FileAccess'), 'sopen.m'); addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 't250_ArtifactPreProcessingQualityControl'), 'regress_eog.m' ); addpathifnotexist( fullfile(eeglabpath, newpath, 'biosig', 'doc'), 'DecimalFactors.txt'); end; end; else if ~isempty(findstr(dircontent{index}, 'eegplugin')) && dircontent{index}(end) == 'm' funcname = dircontent{index}(1:end-2); % remove .m [ pluginName pluginVersion ] = parsepluginname(dircontent{index}(10:end-2)); end; end; % execute function % ---------------- if ~isempty(pluginVersion) || ~isempty(funcname) if isempty(funcname) disp([ 'EEGLAB: adding "' pluginName '" to the path; subfolders (if any) might be missing from the path' ]); pluginlist(plugincount).plugin = pluginName; pluginlist(plugincount).version = pluginVersion; pluginlist(plugincount).foldername = dircontent{index}; pluginlist(plugincount).status = 'ok'; plugincount = plugincount+1; else pluginlist(plugincount).plugin = pluginName; pluginlist(plugincount).version = pluginVersion; vers = pluginlist(plugincount).version; % version vers2 = ''; status = 'ok'; try, %eval( [ 'vers2 =' funcname '(gcf, trystrs, catchstrs);' ]); vers2 = feval(funcname, gcf, trystrs, catchstrs); catch try, eval( [ funcname '(gcf, trystrs, catchstrs)' ]); catch disp([ 'EEGLAB: error while adding plugin "' funcname '"' ] ); disp([ ' ' lasterr] ); status = 'error'; end; end; pluginlist(plugincount).funcname = funcname(10:end); pluginlist(plugincount).foldername = dircontent{index}; [tmp pluginlist(plugincount).versionfunc] = parsepluginname(vers2); if length(pluginlist(plugincount).funcname) > 1 && pluginlist(plugincount).funcname(1) == '_' pluginlist(plugincount).funcname(1) = []; end; if strcmpi(status, 'ok') if isempty(vers), vers = pluginlist(plugincount).versionfunc; end; if isempty(vers), vers = '?'; end; fprintf('EEGLAB: adding "%s" v%s (see >> help %s)\n', ... pluginlist(plugincount).plugin, vers, funcname); end; pluginlist(plugincount).status = status; plugincount = plugincount+1; end; end; end; global PLUGINLIST; PLUGINLIST = pluginlist; end; % iseeglabdeployed2 if ~ismatlab, return; end; % add other import ... % -------------------- cb_others = [ 'pophelp(''troubleshooting_data_formats'');' ]; uimenu( import_m, 'Label', 'Using the FILE-IO interface', 'CallBack', cb_fileio, 'separator', 'on'); uimenu( import_m, 'Label', 'Using the BIOSIG interface' , 'CallBack', cb_biosig); uimenu( import_m, 'Label', 'Troubleshooting data formats...', 'CallBack', cb_others); % changing plugin menu color % -------------------------- fourthsub_m = findobj('parent', tools_m); plotsub_m = findobj('parent', plot_m); importsub_m = findobj('parent', neuro_m); epochsub_m = findobj('parent', epoch_m); eventsub_m = findobj('parent', event_m); editsub_m = findobj('parent', edit_m); exportsub_m = findobj('parent', exportm); filter_m = findobj('parent', filter_m); icadefs; % containing PLUGINMENUCOLOR if length(fourthsub_m) > 11, set(fourthsub_m(1:end-11), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(plotsub_m) > 17, set(plotsub_m (1:end-17), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(importsub_m) > 9, set(importsub_m(1:end-9) , 'foregroundcolor', PLUGINMENUCOLOR); end; if length(epochsub_m ) > 3 , set(epochsub_m (1:end-3 ), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(eventsub_m ) > 4 , set(eventsub_m (1:end-4 ), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(exportsub_m) > 4 , set(exportsub_m(1:end-4 ), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(editsub_m) > 10, set(editsub_m( 1:end-10), 'foregroundcolor', PLUGINMENUCOLOR); end; if length(filter_m) > 3 , set(filter_m (1:end-1 ), 'foregroundcolor', PLUGINMENUCOLOR); end; EEGMENU = uimenu( set_m, 'Label', '------', 'Enable', 'off'); eval('set(W_MAIN, ''userdat'', { EEGUSERDAT{1} EEGMENU javaobj });'); eeglab('redraw'); if nargout < 1 clear ALLEEG; end; %% automatic updater try [dummy eeglabVersionNumber currentReleaseDateString] = eeg_getversion; if isempty(eeglabVersionNumber) eeglabVersionNumber = 'dev'; end; eeglabUpdater = up.updater(eeglabVersionNumber, 'http://sccn.ucsd.edu/eeglab/updater/latest_version.php', 'EEGLAB', currentReleaseDateString); % create a new GUI item (e.g. under Help) %newerVersionMenu = uimenu(help_m, 'Label', 'Upgrade to the Latest Version', 'visible', 'off', 'userdata', 'startup:on;study:on'); % set the callback to bring up the updater GUI icadefs; % for getting background color eeglabFolder = fileparts(mywhich('eeglab.m')); %eeglabUpdater.menuItemHandle = []; %newerVersionMenu; %eeglabUpdater.menuItemCallback = {@command_on_update_menu_click, eeglabUpdater, eeglabFolder, true, BACKEEGLABCOLOR}; % place it in the base workspace. assignin('base', 'eeglabUpdater', eeglabUpdater); % only start timer if the function is called from the command line % (which means that the stack should only contain one element) stackVar = dbstack; if length(stackVar) == 1 if option_checkversion eeglabUpdater.checkForNewVersion({'eeglab_event' 'setup'}); if strcmpi(eeglabVersionNumber, 'dev') return; end; newMajorRevision = 0; if ~isempty(eeglabUpdater.newMajorRevision) fprintf('\nA new major version of EEGLAB (EEGLAB%s - beta) is now <a href="http://sccn.ucsd.edu/eeglab/">available</a>.\n', eeglabUpdater.newMajorRevision); newMajorRevision = 1; end; if eeglabUpdater.newerVersionIsAvailable eeglabv = num2str(eeglabUpdater.latestVersionNumber); posperiod = find(eeglabv == '.'); if isempty(posperiod), posperiod = length(eeglabv)+1; eeglabv = [ eeglabv '.0' ]; end; if length(eeglabv(posperiod+1:end)) < 2, eeglabv = [ eeglabv '0' ]; end; %if length(eeglabv(posperiod+1:end)) < 3, eeglabv = [ eeglabv '0' ]; end; eeglabv = [ eeglabv(1:posperiod+1) '.' eeglabv(posperiod+2) ]; %'.' eeglabv(posperiod+3) ]; stateWarning = warning('backtrace'); warning('backtrace', 'off'); if newMajorRevision fprintf('\n'); warning( sprintf(['\nA critical revision of EEGLAB%d (%s) is also available <a href="%s">here</a>\n' ... 'See <a href="matlab: web(''%s'', ''-browser'')">Release notes</a> for more informations\n' ... 'You may disable this message using the Option menu\n' ], ... floor(eeglabVersionNumber), eeglabv, eeglabUpdater.downloadUrl, ... [ 'http://sccn.ucsd.edu/wiki/EEGLAB_revision_history_version_13' ])); else warning( sprintf(['\nA newer version of EEGLAB (%s) is available <a href="%s">here</a>\n' ... 'See <a href="matlab: web(''%s'', ''-browser'')">Release notes</a> for more informations\n' ... 'You may disable this message using the Option menu\n' ], ... eeglabv, eeglabUpdater.downloadUrl, ... [ 'http://sccn.ucsd.edu/wiki/EEGLAB_revision_history_version_13' ])); end; warning('backtrace', stateWarning.state); % make the Help menu item dark red set(help_m, 'foregroundColor', [0.6, 0 0]); elseif isempty(eeglabUpdater.lastTimeChecked) fprintf('Could not check for the latest EEGLAB version (internet may be disconnected).\n'); fprintf('To prevent long startup time, disable checking for new EEGLAB version (FIle > Memory and other options).\n'); else if ~newMajorRevision fprintf('You are using the latest version of EEGLAB.\n'); else fprintf('You are currently using the latest revision of EEGLAB%d (no critical update available).\n', floor(eeglabVersionNumber)); end; end; else eeglabtimers = timerfind('name', 'eeglabupdater'); if ~isempty(eeglabtimers) stop(eeglabtimers); delete(eeglabtimers); end; % This is disabled because it cause Matlab to hang in case % there is no connection or the connection is available but not % usable % start(timer('TimerFcn','try, eeglabUpdater.checkForNewVersion({''eeglab_event'' ''setup''}); catch, end; clear eeglabUpdater;', 'name', 'eeglabupdater', 'StartDelay', 20.0)); end; end; catch if option_checkversion fprintf('Updater could not be initialized.\n'); end; end; % REMOVED MENUS %uimenu( tools_m, 'Label', 'Automatic comp. reject', 'enable', 'off', 'CallBack', '[EEG LASTCOM] = pop_rejcomp(EEG); eegh(LASTCOM); if ~isempty(LASTCOM), eeg_store(CURRENTSET); end;'); %uimenu( tools_m, 'Label', 'Reject (synthesis)' , 'Separator', 'on', 'CallBack', '[EEG LASTCOM] = pop_rejall(EEG); eegh(LASTCOM); if ~isempty(LASTCOM), eeg_store; end; eeglab(''redraw'');'); function command_on_update_menu_click(callerHandle, tmp, eeglabUpdater, installDirectory, goOneFolderLevelIn, backGroundColor) postInstallCallbackString = 'clear all function functions; eeglab'; eeglabUpdater.launchGui(installDirectory, goOneFolderLevelIn, backGroundColor, postInstallCallbackString); % % -------------------- % draw the main figure % -------------------- function tb = eeg_mainfig(onearg); icadefs; COLOR = BACKEEGLABCOLOR; WINMINX = 17; WINMAXX = 260; WINYDEC = 13; NBLINES = 16; WINY = WINYDEC*NBLINES; javaChatFlag = 1; BORDERINT = 4; BORDEREXT = 10; comp = computer; if strcmpi(comp(1:3), 'GLN') || strcmpi(comp(1:3), 'MAC') || strcmpi(comp(1:3), 'PCW') FONTNAME = 'courier'; FONTSIZE = 8; % Magnify figure under MATLAB 2012a vers = version; dotPos = find(vers == '.'); vernum = str2num(vers(1:dotPos(1)-1)); subvernum = str2num(vers(dotPos(1)+1:dotPos(2)-1)); if vernum > 7 || (vernum >= 7 && subvernum >= 14) FONTSIZE = FONTSIZE+2; WINMAXX = WINMAXX*1.3; WINY = WINY*1.3; end; else FONTNAME = ''; FONTSIZE = 11; end; hh = findobj('tag', 'EEGLAB'); if ~isempty(hh) disp('EEGLAB warning: there can be only one EEGLAB window, closing old one'); close(hh); end; if strcmpi(onearg, 'remote') figure( 'name', [ 'EEGLAB v' eeg_getversion ], ... 'numbertitle', 'off', ... 'Position',[200 100 (WINMINX+WINMAXX+2*BORDERINT+2*BORDEREXT) 30 ], ... 'color', COLOR, ... 'Tag','EEGLAB', ... 'Userdata', {[] []}); %'resize', 'off', ... return; end; W_MAIN = figure('Units','points', ... ... % 'Colormap','gray', ... 'PaperPosition',[18 180 576 432], ... 'PaperUnits','points', ... 'name', [ 'EEGLAB v' eeg_getversion ], ... 'numbertitle', 'off', ... 'Position',[200 100 (WINMINX+WINMAXX+2*BORDERINT+2*BORDEREXT) (WINY+2*BORDERINT+2*BORDEREXT) ], ... 'color', COLOR, ... 'Tag','EEGLAB', ... 'visible', 'off', ... 'Userdata', {[] []}); % 'resize', 'off', ... % java chat eeglab_options; if option_chat == 1 if is_sccn disp('Starting chat...'); tmpp = fileparts(mywhich('startpane.m')); if isempty(tmpp) || ~ismatlab disp('Cannot start chat'); tb = []; else disp(' ----------------------------------- '); disp('| EEGLAB chat 0.9 |'); disp('| The chat currently only works |'); disp('| at the University of CA San Diego |'); disp(' ----------------------------------- '); javaaddpath(fullfile(tmpp, 'Chat_with_pane.jar')); eval('import client.EEGLABchat.*;'); eval('import client.VisualToolbar;'); eval('import java.awt.*;'); eval('import javax.swing.*;'); try tb = VisualToolbar('137.110.244.26'); F = W_MAIN; tb.setPreferredSize(Dimension(0, 75)); javacomponent(tb,'South',F); javaclose = ['userdat = get(gcbf, ''userdata'');' ... 'try,'... ' tb = userdat{3};' ... 'clear userdat; delete(gcbf); tb.close; clear tb;'... 'catch,end;']; set(gcf, 'CloseRequestFcn',javaclose); refresh(F); catch, tb = []; end; end; else tb = []; end; else tb = []; end; try, set(W_MAIN, 'NextPlot','new'); catch, end; if ismatlab BackgroundColor = get(gcf, 'color'); %[0.701960784313725 0.701960784313725 0.701960784313725]; H_MAIN(1) = uicontrol('Parent',W_MAIN, ... 'Units','points', ... 'BackgroundColor',COLOR, ... 'ListboxTop',0, ... 'HorizontalAlignment', 'left',... 'Position',[BORDEREXT BORDEREXT (WINMINX+WINMAXX+2*BORDERINT) (WINY)], ... 'Style','frame', ... 'Tag','Frame1'); set(H_MAIN(1), 'unit', 'normalized'); geometry = { [1] [1] [1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1 1] [1] }; listui = { { 'style', 'text', 'string', 'Parameters of the current set', 'tag', 'win0' } { } ... { 'style', 'text', 'tag', 'win1', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win2', 'string', 'Channels per frame', 'userdata', 'datinfo'} ... { 'style', 'text', 'tag', 'val2', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win3', 'string', 'Frames per epoch', 'userdata', 'datinfo'} ... { 'style', 'text', 'tag', 'val3', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win4', 'string', 'Epochs', 'userdata', 'datinfo'} ... { 'style', 'text', 'tag', 'val4', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win5', 'string', 'Events', 'userdata', 'datinfo'} ... { 'style', 'text', 'tag', 'val5', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win6', 'string', 'Sampling rate (Hz)', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val6', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win7', 'string', 'Epoch start (sec)', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val7', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win8', 'string', 'Epoch end (sec)', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val8', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win9', 'string', 'Average reference', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val9', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win10', 'string', 'Channel locations', 'userdata', 'datinfo'} ... { 'style', 'text', 'tag', 'val10', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win11', 'string', 'ICA weights', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val11', 'string', ' ', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'win12', 'string', 'Dataset size (Mb)', 'userdata', 'datinfo' } ... { 'style', 'text', 'tag', 'val12', 'string', ' ', 'userdata', 'datinfo' } {} }; supergui(gcf, geometry, [], listui{:}); geometry = { [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] [1] }; listui = { { } ... { } ... { 'style', 'text', 'tag', 'mainwin1', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin2', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin3', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin4', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin5', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin6', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin7', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin8', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin9', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin10', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin11', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin12', 'string', ' ', 'userdata', 'fullline' } ... { 'style', 'text', 'tag', 'mainwin13', 'string', ' ', 'userdata', 'fullline' } {} }; supergui(gcf, geometry, [], listui{:}); titleh = findobj('parent', gcf, 'tag', 'win0'); alltexth = findobj('parent', gcf, 'style', 'text'); alltexth = setdiff_bc(alltexth, titleh); set(gcf, 'Position',[200 100 (WINMINX+WINMAXX+2*BORDERINT+2*BORDEREXT) (WINY+2*BORDERINT+2*BORDEREXT) ]); set(titleh, 'fontsize', 14, 'fontweight', 'bold'); set(alltexth, 'fontname', FONTNAME, 'fontsize', FONTSIZE); set(W_MAIN, 'visible', 'on'); end; return; % eeglab(''redraw'')() - Update EEGLAB menus based on values of global variables. % % Usage: >> eeglab(''redraw'')( ); % % Author: Arnaud Delorme, CNL / Salk Institute, 2001 % % See also: eeg_global(), eeglab() % WHEN THIS FUNCTION WAS SEPARATED % Revision 1.21 2002/04/23 19:09:25 arno % adding automatic dataset search % Revision 1.20 2002/04/18 20:02:23 arno % retrIeve % Revision 1.18 2002/04/18 16:28:28 scott % EEG.averef printed as 'Yes' or 'No' -sm % Revision 1.16 2002/04/18 16:03:15 scott % editted "Events/epoch info (nb) -> Events -sm % Revision 1.14 2002/04/18 14:46:58 scott % editted main window help msg -sm % Revision 1.10 2002/04/18 03:02:17 scott % edited opening instructions -sm % Revision 1.9 2002/04/11 18:23:33 arno % Oups, typo which crashed EEGLAB % Revision 1.8 2002/04/11 18:07:59 arno % adding average reference variable % Revision 1.7 2002/04/11 17:49:40 arno % corrected operator precedence problem % Revision 1.6 2002/04/11 15:36:55 scott % added parentheses to final ( - & - ), line 84. ARNO PLEASE CHECK -sm % Revision 1.5 2002/04/11 15:34:50 scott % put isempty(CURRENTSET) first in line ~80 -sm % Revision 1.4 2002/04/11 15:31:47 scott % added test isempty(CURRENTSET) line 78 -sm % Revision 1.3 2002/04/11 01:41:27 arno % checking dataset ... and inteligent menu update % Revision 1.2 2002/04/09 20:47:41 arno % introducing event number into gui function updatemenu(); eeg_global; W_MAIN = findobj('tag', 'EEGLAB'); EEGUSERDAT = get(W_MAIN, 'userdata'); H_MAIN = EEGUSERDAT{1}; EEGMENU = EEGUSERDAT{2}; if length(EEGUSERDAT) > 2 tb = EEGUSERDAT{3}; else tb = []; end; if ~isempty(tb) && ~isstr(tb) eval('tb.RefreshToolbar();'); end; if exist('CURRENTSET') ~= 1, CURRENTSET = 0; end; if isempty(ALLEEG), ALLEEG = []; end; if isempty(EEG), EEG = []; end; % test if the menu is present try figure(W_MAIN); set_m = findobj( 'parent', W_MAIN, 'Label', 'Datasets'); catch, return; end; index = 1; indexmenu = 1; MAX_SET = max(length( ALLEEG ), length(EEGMENU)-1); clear functions; eeglab_options; if isempty(ALLEEG) && ~isempty(EEG) && ~isempty(EEG.data) ALLEEG = EEG; end; % setting the dataset menu % ------------------------ while( index <= MAX_SET) try set( EEGMENU(index), 'Label', '------', 'checked', 'off'); catch, if mod(index, 30) == 0 tag = [ 'More (' int2str(index/30) ') ->' ]; tmp_m = findobj('label', tag); if isempty(tmp_m) set_m = uimenu( set_m, 'Label', tag, 'userdata', 'study:on'); else set_m = tmp_m; end; end; try set( EEGMENU(index), 'Label', '------', 'checked', 'off'); catch, EEGMENU(index) = uimenu( set_m, 'Label', '------', 'Enable', 'on'); end; end; set( EEGMENU(index), 'Enable', 'on', 'separator', 'off' ); try, ALLEEG(index).data; if ~isempty( ALLEEG(index).data) cb_retrieve = [ '[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''retrieve'', ' int2str(index) ', ''study'', ~isempty(STUDY)+0);' ... 'if CURRENTSTUDY & ~isempty(LASTCOM), CURRENTSTUDY = 0; LASTCOM = [ ''CURRENTSTUDY = 0;'' LASTCOM ]; end; eegh(LASTCOM);' ... 'eeglab(''redraw'');' ]; menutitle = sprintf('Dataset %d:%s', index, ALLEEG(index).setname); set( EEGMENU(index), 'Label', menutitle, 'userdata', 'study:on'); set( EEGMENU(index), 'CallBack', cb_retrieve ); set( EEGMENU(index), 'Enable', 'on' ); if any(index == CURRENTSET), set( EEGMENU(index), 'checked', 'on' ); end; end; catch, end; index = index+1; end; hh = findobj( 'parent', set_m, 'Label', '------'); set(hh, 'Enable', 'off'); % menu for selecting several datasets % ----------------------------------- if index ~= 0 cb_select = [ 'nonempty = find(~cellfun(''isempty'', { ALLEEG.data } ));' ... 'tmpind = pop_chansel({ ALLEEG(nonempty).setname }, ''withindex'', nonempty);' ... 'if ~isempty(tmpind),' ... ' [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''retrieve'', nonempty(tmpind), ''study'', ~isempty(STUDY)+0);' ... ' eegh(LASTCOM);' ... ' eeglab(''redraw'');' ... 'end;' ... 'clear tmpind nonempty;' ]; if MAX_SET == length(EEGMENU), EEGMENU(end+1) = uimenu( set_m, 'Label', '------', 'Enable', 'on'); end; set(EEGMENU(end), 'enable', 'on', 'Label', 'Select multiple datasets', ... 'callback', cb_select, 'separator', 'on', 'userdata', 'study:on'); end; % STUDY consistency % ----------------- exist_study = 0; if exist('STUDY') & exist('CURRENTSTUDY') % if study present, check study consistency with loaded datasets % -------------------------------------------------------------- if ~isempty(STUDY) if length(ALLEEG) > length(STUDY.datasetinfo) || ~isfield(ALLEEG, 'data') || any(cellfun('isempty', {ALLEEG.data})) if strcmpi(STUDY.saved, 'no') res = questdlg2( strvcat('The study is not compatible with the datasets present in memory', ... 'It is self consistent but EEGLAB is not be able to process it.', ... 'Do you wish to save the study as it is (EEGLAB will prompt you to', ... 'enter a file name) or do you wish to remove it'), 'Study inconsistency', 'Save and remove', 'Remove', 'Remove' ); if strcmpi(res, 'Remove') STUDY = []; CURRENTSTUDY = 0; else pop_savestudy(STUDY, ALLEEG); STUDY = []; CURRENTSTUDY = 0; end; else warndlg2( strvcat('The study was not compatible any more with the datasets present in memory.', ... 'Since it had not changed since last saved, it was simply removed from', ... 'memory.') ); STUDY = []; CURRENTSTUDY = 0; end; end; end; if ~isempty(STUDY) exist_study = 1; end; end; % menu for selecting STUDY set % ---------------------------- if exist_study cb_select = [ '[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''retrieve'', [STUDY.datasetinfo.index], ''study'', 1);' ... 'if ~isempty(LASTCOM), CURRENTSTUDY = 1; LASTCOM = [ LASTCOM ''CURRENTSTUDY = 1;'' ]; end;' ... 'eegh(LASTCOM);' ... 'eeglab(''redraw'');' ]; tmp_m = findobj('label', 'Select the study set'); delete(tmp_m); % in case it is not at the end tmp_m = uimenu( set_m, 'Label', 'Select the study set', 'Enable', 'on', 'userdata', 'study:on'); set(tmp_m, 'enable', 'on', 'callback', cb_select, 'separator', 'on'); else delete( findobj('label', 'Select the study set') ); end; EEGUSERDAT{2} = EEGMENU; set(W_MAIN, 'userdata', EEGUSERDAT); if (isempty(CURRENTSET) | length(ALLEEG) < CURRENTSET(1) | CURRENTSET(1) == 0 | isempty(ALLEEG(CURRENTSET(1)).data)) CURRENTSET = 0; for index = 1:length(ALLEEG) if ~isempty(ALLEEG(index).data) CURRENTSET = index; break; end; end; if CURRENTSET ~= 0 eegh([ '[EEG ALLEEG CURRENTSET] = eeg_retrieve(ALLEEG,' int2str(CURRENTSET) ');' ]) [EEG ALLEEG] = eeg_retrieve(ALLEEG, CURRENTSET); else EEG = eeg_emptyset; end; end; if (isempty(EEG) | isempty(EEG(1).data)) & CURRENTSET(1) ~= 0 eegh([ '[EEG ALLEEG CURRENTSET] = eeg_retrieve(ALLEEG,' int2str(CURRENTSET) ');' ]) [EEG ALLEEG] = eeg_retrieve(ALLEEG, CURRENTSET); end; % test if dataset has changed % --------------------------- if length(EEG) == 1 if ~isempty(ALLEEG) & CURRENTSET~= 0 & ~isequal(EEG.data, ALLEEG(CURRENTSET).data) & ~isnan(EEG.data(1)) % the above comparison does not work for ome structures %tmpanswer = questdlg2(strvcat('The current EEG dataset has changed. What should eeglab do with the changes?', ' '), ... % 'Dataset change detected', ... % 'Keep changes', 'Delete changes', 'New dataset', 'Make new dataset'); disp('Warning: for some reason, the backup dataset in EEGLAB memory does not'); disp(' match the current dataset. The dataset in memory has been overwritten'); [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET); eegh('[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);'); %if tmpanswer(1) == 'D' % delete changes % [EEG ALLEEG] = eeg_retrieve(ALLEEG, CURRENTSET); % eegh('[EEG ALLEEG] = eeg_retrieve( ALLEEG, CURRENTSET);'); %elseif tmpanswer(1) == 'K' % keep changes % [ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET); % eegh('[ALLEEG EEG CURRENTSET] = eeg_store(ALLEEG, EEG, CURRENTSET);'); %else % make new dataset % [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET); % eegh(LASTCOM); % MAX_SET = max(length( ALLEEG ), length(EEGMENU)); %end; end; end; % print some information on the main figure % ------------------------------------------ g = myguihandles(gcf); if ~isfield(g, 'win0') % no display return; end; study_selected = 0; if exist('STUDY') & exist('CURRENTSTUDY') if CURRENTSTUDY == 1, study_selected = 1; end; end; menustatus = {}; if study_selected menustatus = { menustatus{:} 'study' }; hh = findobj('parent', gcf, 'userdata', 'fullline'); set(hh, 'visible', 'off'); hh = findobj('parent', gcf, 'userdata', 'datinfo'); set(hh, 'visible', 'on'); % head string % ----------- set( g.win0, 'String', sprintf('STUDY set: %s', STUDY.name) ); % dataset type % ------------ datasettype = unique_bc( [ EEG.trials ] ); if datasettype(1) == 1 & length(datasettype) == 1, datasettype = 'continuous'; elseif datasettype(1) == 1, datasettype = 'epoched and continuous'; else datasettype = 'epoched'; end; % number of channels and channel locations % ---------------------------------------- chanlen = unique_bc( [ EEG.nbchan ] ); chanlenstr = vararg2str( mattocell(chanlen) ); anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) ); if length(anyempty) == 2, chanlocs = 'mixed, yes and no'; elseif anyempty == 0, chanlocs = 'yes'; else chanlocs = 'no'; end; % ica weights % ----------- anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) ); if length(anyempty) == 2, studystatus = 'Missing ICA dec.'; elseif anyempty == 0, studystatus = 'Ready to precluster'; else studystatus = 'Missing ICA dec.'; end; % consistency & other parameters % ------------------------------ [EEG epochconsist] = eeg_checkset(EEG, 'epochconsist'); % epoch consistency [EEG chanconsist ] = eeg_checkset(EEG, 'chanconsist'); % channel consistency [EEG icaconsist ] = eeg_checkset(EEG, 'icaconsist'); % ICA consistency totevents = num2str(sum( cellfun( 'length', { EEG.event }) )); % total number of events totsize = whos('STUDY', 'ALLEEG'); % total size if isempty(STUDY.session), sessionstr = ''; else sessionstr = vararg2str(STUDY.session); end; if isempty(STUDY.condition), condstr = ''; else condstr = vararg2str(STUDY.condition); end; % determine study status % ---------------------- if isfield(STUDY.etc, 'preclust') if ~isempty( STUDY.etc.preclust ) studystatus = 'Pre-clustered'; elseif length(STUDY.cluster) > 1 studystatus = 'Clustered'; end; elseif length(STUDY.cluster) > 1 studystatus = 'Clustered'; end; % text % ---- set( g.win2, 'String', 'Study task name'); set( g.win3, 'String', 'Nb of subjects'); set( g.win4, 'String', 'Nb of conditions'); set( g.win5, 'String', 'Nb of sessions'); set( g.win6, 'String', 'Nb of groups'); set( g.win7, 'String', 'Epoch consistency'); set( g.win8, 'String', 'Channels per frame'); set( g.win9, 'String', 'Channel locations'); set( g.win10, 'String', 'Clusters'); set( g.win11, 'String', 'Status'); set( g.win12, 'String', 'Total size (Mb)'); % values % ------ fullfilename = fullfile( STUDY.filepath, STUDY.filename); if length(fullfilename) > 26 set( g.win1, 'String', sprintf('Study filename: ...%s\n', fullfilename(max(1,length(fullfilename)-26):end) )); else set( g.win1, 'String', sprintf('Study filename: %s\n' , fullfilename)); end; condconsist = std_checkconsist(STUDY, 'uniform', 'condition'); groupconsist = std_checkconsist(STUDY, 'uniform', 'group'); sessconsist = std_checkconsist(STUDY, 'uniform', 'session'); txtcond = fastif(condconsist , ' per subject', ' (some missing)'); txtgroup = fastif(groupconsist, ' per subject', ' (some missing)'); txtsess = fastif(sessconsist , ' per subject', ' (some missing)'); set( g.val2, 'String', STUDY.task); set( g.val3, 'String', int2str(max(1, length(STUDY.subject)))); set( g.val4, 'String', [ int2str(max(1, length(STUDY.condition))) txtcond ]); set( g.val5, 'String', [ int2str(max(1, length(STUDY.session))) txtsess ]); set( g.val6, 'String', [ int2str(max(1, length(STUDY.group))) txtgroup ]); set( g.val7, 'String', epochconsist); set( g.val8, 'String', chanlenstr); set( g.val9, 'String', chanlocs); set( g.val10, 'String', length(STUDY.cluster)); set( g.val11, 'String', studystatus); set( g.val12, 'String', num2str(round(sum( [ totsize.bytes] )/1E6*10)/10)); elseif (exist('EEG') == 1) & ~isnumeric(EEG) & ~isempty(EEG(1).data) hh = findobj('parent', gcf, 'userdata', 'fullline'); set(hh, 'visible', 'off'); hh = findobj('parent', gcf, 'userdata', 'datinfo'); set(hh, 'visible', 'on'); if length(EEG) > 1 % several datasets menustatus = { menustatus{:} 'multiple_datasets' }; % head string % ----------- strsetnum = 'Datasets '; for i = CURRENTSET strsetnum = [ strsetnum int2str(i) ',' ]; end; strsetnum = strsetnum(1:end-1); set( g.win0, 'String', strsetnum); % dataset type % ------------ datasettype = unique_bc( [ EEG.trials ] ); if datasettype(1) == 1 & length(datasettype) == 1, datasettype = 'continuous'; elseif datasettype(1) == 1, datasettype = 'epoched and continuous'; else datasettype = 'epoched'; end; % number of channels and channel locations % ---------------------------------------- chanlen = unique_bc( [ EEG.nbchan ] ); chanlenstr = vararg2str( mattocell(chanlen) ); anyempty = unique_bc( cellfun( 'isempty', { EEG.chanlocs }) ); if length(anyempty) == 2, chanlocs = 'mixed, yes and no'; elseif anyempty == 0, chanlocs = 'yes'; else chanlocs = 'no'; end; % ica weights % ----------- anyempty = unique_bc( cellfun( 'isempty', { EEG.icaweights }) ); if length(anyempty) == 2, icaweights = 'mixed, yes and no'; elseif anyempty == 0, icaweights = 'yes'; else icaweights = 'no'; end; % consistency & other parameters % ------------------------------ [EEG epochconsist] = eeg_checkset(EEG, 'epochconsist'); % epoch consistency [EEG chanconsist ] = eeg_checkset(EEG, 'chanconsist'); % channel consistency [EEG icaconsist ] = eeg_checkset(EEG, 'icaconsist'); % ICA consistency totevents = num2str(sum( cellfun( 'length', { EEG.event }) )); % total number of events srate = vararg2str( mattocell( unique( [ EEG.srate ] ) )); % sampling rate totsize = whos('EEG'); % total size % text % ---- set( g.win2, 'String', 'Number of datasets'); set( g.win3, 'String', 'Dataset type'); set( g.win4, 'String', 'Epoch consistency'); set( g.win5, 'String', 'Channels per frame'); set( g.win6, 'String', 'Channel consistency'); set( g.win7, 'String', 'Channel locations'); set( g.win8, 'String', 'Events (total)'); set( g.win9, 'String', 'Sampling rate (Hz)'); set( g.win10, 'String', 'ICA weights'); set( g.win11, 'String', 'Identical ICA'); set( g.win12, 'String', 'Total size (Mb)'); % values % ------ set( g.win1, 'String', sprintf('Groupname: -(soon)-\n')); set( g.val2, 'String', int2str(length(EEG))); set( g.val3, 'String', datasettype); set( g.val4, 'String', epochconsist); set( g.val5, 'String', chanlenstr); set( g.val6, 'String', chanconsist); set( g.val7, 'String', chanlocs); set( g.val8, 'String', totevents); set( g.val9, 'String', srate); set( g.val10, 'String', icaweights); set( g.val11, 'String', icaconsist); set( g.val12, 'String', num2str(round(totsize.bytes/1E6*10)/10)); else % one continous dataset selected menustatus = { menustatus{:} 'continuous_dataset' }; % text % ---- set( g.win2, 'String', 'Channels per frame'); set( g.win3, 'String', 'Frames per epoch'); set( g.win4, 'String', 'Epochs'); set( g.win5, 'String', 'Events'); set( g.win6, 'String', 'Sampling rate (Hz)'); set( g.win7, 'String', 'Epoch start (sec)'); set( g.win8, 'String', 'Epoch end (sec)'); set( g.win9, 'String', 'Reference'); set( g.win10, 'String', 'Channel locations'); set( g.win11, 'String', 'ICA weights'); set( g.win12, 'String', 'Dataset size (Mb)'); if CURRENTSET == 0, strsetnum = ''; else strsetnum = ['#' int2str(CURRENTSET) ': ']; end; maxchar = 28; if ~isempty( EEG.setname ) if length(EEG.setname) > maxchar+2 set( g.win0, 'String', [strsetnum EEG.setname(1:min(maxchar,length(EEG.setname))) '...' ]); else set( g.win0, 'String', [strsetnum EEG.setname ]); end; else set( g.win0, 'String', [strsetnum '(no dataset name)' ] ); end; fullfilename = fullfile(EEG.filepath, EEG.filename); if ~isempty(fullfilename) if length(fullfilename) > 26 set( g.win1, 'String', sprintf('Filename: ...%s\n', fullfilename(max(1,length(fullfilename)-26):end) )); else set( g.win1, 'String', sprintf('Filename: %s\n', fullfilename)); end; else set( g.win1, 'String', sprintf('Filename: none\n')); end; set( g.val2, 'String', int2str(fastif(isempty(EEG.data), 0, size(EEG.data,1)))); set( g.val3, 'String', int2str(EEG.pnts)); set( g.val4, 'String', int2str(EEG.trials)); set( g.val5, 'String', fastif(isempty(EEG.event), 'none', int2str(length(EEG.event)))); set( g.val6, 'String', int2str( round(EEG.srate)) ); if round(EEG.xmin) == EEG.xmin & round(EEG.xmax) == EEG.xmax set( g.val7, 'String', sprintf('%d\n', EEG.xmin)); set( g.val8, 'String', sprintf('%d\n', EEG.xmax)); else set( g.val7, 'String', sprintf('%6.3f\n', EEG.xmin)); set( g.val8, 'String', sprintf('%6.3f\n', EEG.xmax)); end; % reference if isfield(EEG(1).chanlocs, 'ref') [curref tmp allinds] = unique_bc( { EEG(1).chanlocs.ref }); maxind = 1; for ind = unique_bc(allinds) if length(find(allinds == ind)) > length(find(allinds == maxind)) maxind = ind; end; end; curref = curref{maxind}; if isempty(curref), curref = 'unknown'; end; else curref = 'unknown'; end; set( g.val9, 'String', curref); if isempty(EEG.chanlocs) set( g.val10, 'String', 'No'); else if ~isfield(EEG.chanlocs, 'theta') | all(cellfun('isempty', { EEG.chanlocs.theta })) set( g.val10, 'String', 'No (labels only)'); else set( g.val10, 'String', 'Yes'); end; end; set( g.val11, 'String', fastif(isempty(EEG.icasphere), 'No', 'Yes')); tmp = whos('EEG'); if ~isa(EEG.data, 'memmapdata') && ~isa(EEG.data, 'mmo') set( g.val12, 'String', num2str(round(tmp.bytes/1E6*10)/10)); else set( g.val12, 'String', [ num2str(round(tmp.bytes/1E6*10)/10) ' (file mapped)' ]); end; if EEG.trials > 1 menustatus = { menustatus{:} 'epoched_dataset' }; else menustatus = { menustatus{:} 'continuous_dataset' }; end if ~isfield(EEG.chanlocs, 'theta') menustatus = { menustatus{:} 'chanloc_absent' }; end; if isempty(EEG.icaweights) menustatus = { menustatus{:} 'ica_absent' }; end; end; else menustatus = { menustatus{:} 'startup' }; hh = findobj('parent', gcf, 'userdata', 'fullline'); set(hh, 'visible', 'on'); hh = findobj('parent', gcf, 'userdata', 'datinfo'); set(hh, 'visible', 'off'); set( g.win0, 'String', 'No current dataset'); set( g.mainwin1, 'String', '- Create a new or load an existing dataset:'); set( g.mainwin2, 'String', ' Use "File > Import data" (new)'); set( g.mainwin3, 'String', ' Or "File > Load existing dataset" (old)'); set( g.mainwin4, 'String', '- If new,'); set( g.mainwin5, 'String', ' "File > Import epoch info" (data epochs) else'); set( g.mainwin6, 'String', ' "File > Import event info" (continuous data)'); set( g.mainwin7, 'String', ' "Edit > Dataset info" (add/edit dataset info)'); set( g.mainwin8, 'String', ' "File > Save dataset" (save dataset)'); set( g.mainwin9, 'String', '- Prune data: "Edit > Select data"'); set( g.mainwin10,'String', '- Reject data: "Tools > Reject continuous data"'); set( g.mainwin11,'String', '- Epoch data: "Tools > Extract epochs"'); set( g.mainwin12,'String', '- Remove baseline: "Tools > Remove baseline"'); set( g.mainwin13,'String', '- Run ICA: "Tools > Run ICA"'); end; % ERPLAB if exist('ALLERP') == 1 && ~isempty(ALLERP) menustatus = { menustatus{:} 'erp_dataset' }; end; % enable selected menu items % -------------------------- allmenus = findobj( W_MAIN, 'type', 'uimenu'); allstrs = get(allmenus, 'userdata'); if any(strcmp(menustatus, 'startup')) set(allmenus, 'enable', 'on'); eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''startup:off''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'off'); elseif any(strcmp(menustatus, 'study')) eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''study:on''))), allstrs);'); set(allmenus , 'enable', 'off'); set(allmenus(indmatchvar), 'enable', 'on'); elseif any(strcmp(menustatus, 'multiple_datasets')) eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''study:on''))), allstrs);'); set(allmenus , 'enable', 'off'); set(allmenus(indmatchvar), 'enable', 'on'); set(findobj('parent', W_MAIN, 'label', 'Study'), 'enable', 'off'); % -------------------------------- % Javier Lopez-Calderon for ERPLAB elseif any(strcmp(menustatus, 'epoched_dataset')) set(allmenus, 'enable', 'on'); eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''epoch:off''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'off'); % end, Javier Lopez-Calderon for ERPLAB % -------------------------------- elseif any(strcmp(menustatus, 'continuous_dataset')) set(allmenus, 'enable', 'on'); eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''continuous:off''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'off'); end; if any(strcmp(menustatus, 'chanloc_absent')) eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''chanloc:on''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'off'); end; if any(strcmp(menustatus, 'ica_absent')) eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''ica:on''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'off'); end; % -------------------------------- % Javier Lopez-Calderon for ERPLAB if any(strcmp(menustatus, 'erp_dataset')) eval('indmatchvar = cellfun(@(x)(~isempty(findstr(num2str(x), ''erpset:on''))), allstrs);'); set(allmenus(indmatchvar), 'enable', 'on'); end % end, Javier Lopez-Calderon for ERPLAB % -------------------------------- % adjust title extent % ------------------- poswin0 = get(g.win0, 'position'); extwin0 = get(g.win0, 'extent'); set(g.win0, 'position', [poswin0(1:2) extwin0(3) extwin0(4)]); % adjust all font sizes (RMC fix MATLAB 2014 compatibility) % ------------------- handlesname = fieldnames(g); for i = 1:length(handlesname) if isprop(eval(['g.' handlesname{i}]),'Style') & ~strcmp(handlesname{i},'win0') propval = get(eval(['g.' handlesname{i}]), 'Style'); if strcmp(propval,'text') set(eval(['g.' handlesname{i}]),'FontSize',TEXT_FONTSIZE); end end end return; function num = popask( text ) ButtonName=questdlg2( text, ... 'Confirmation', 'Cancel', 'Yes','Yes'); switch lower(ButtonName), case 'cancel', num = 0; case 'yes', num = 1; end; function g = myguihandles(fig) g = []; hh = findobj('parent', gcf); for index = 1:length(hh) if ~isempty(get(hh(index), 'tag')) g = setfield(g, get(hh(index), 'tag'), hh(index)); end; end; function rmpathifpresent(newpath); comp = computer; if strcmpi(comp(1:2), 'PC') newpath = [ newpath ';' ]; else newpath = [ newpath ':' ]; end; if ismatlab p = matlabpath; else p = path; end; ind = strfind(p, newpath); if ~isempty(ind) rmpath(newpath); end; % add path only if it is not already in the list % ---------------------------------------------- function addpathifnotinlist(newpath); comp = computer; if strcmpi(comp(1:2), 'PC') newpathtest = [ newpath ';' ]; else newpathtest = [ newpath ':' ]; end; if ismatlab p = matlabpath; else p = path; end; ind = strfind(p, newpathtest); if isempty(ind) if exist(newpath) == 7 addpath(newpath); end; end; function addpathifnotexist(newpath, functionname); tmpp = mywhich(functionname); if isempty(tmpp) addpath(newpath); end; % find a function path and add path if not present % ------------------------------------------------ function myaddpath(eeglabpath, functionname, pathtoadd); tmpp = mywhich(functionname); tmpnewpath = [ eeglabpath pathtoadd ]; if ~isempty(tmpp) tmpp = tmpp(1:end-length(functionname)); if length(tmpp) > length(tmpnewpath), tmpp = tmpp(1:end-1); end; % remove trailing filesep if length(tmpp) > length(tmpnewpath), tmpp = tmpp(1:end-1); end; % remove trailing filesep %disp([ tmpp ' | ' tmpnewpath '(' num2str(~strcmpi(tmpnewpath, tmpp)) ')' ]); if ~strcmpi(tmpnewpath, tmpp) warning('off', 'MATLAB:dispatcher:nameConflict'); addpath(tmpnewpath); warning('on', 'MATLAB:dispatcher:nameConflict'); end; else %disp([ 'Adding new path ' tmpnewpath ]); addpathifnotinlist(tmpnewpath); end; function val = iseeglabdeployed2; %val = 1; return; if exist('isdeployed') val = isdeployed; else val = 0; end; function buildhelpmenu; % parse plugin function name % -------------------------- function [name, vers] = parsepluginname(dirName); ind = find( dirName >= '0' & dirName <= '9' ); if isempty(ind) name = dirName; vers = ''; else ind = length(dirName); while ind > 0 && ((dirName(ind) >= '0' & dirName(ind) <= '9') || dirName(ind) == '.' || dirName(ind) == '_') ind = ind - 1; end; name = dirName(1:ind); vers = dirName(ind+1:end); vers(find(vers == '_')) = '.'; end; % required here because path not added yet % to the admin folder function res = ismatlab; v = version; if v(1) > '4' res = 1; else res = 0; end; function res = mywhich(varargin); try res = which(varargin{:}); catch fprintf('Warning: permission error accesssing %s\n', varargin{1}); end;
github
ZijingMao/baselineeegtest-master
display.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/display.m
1,180
utf_8
d3d679b5764eca6d062540923f669f7b
% display() - display an EEG data class underlying structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function b = display(a) i.type = '()'; i.subs = { ':' ':' ':' }; b = subsref(a, i); % note that subsref cannot be called directly return; %struct(a) %return; if ~strcmpi(a.fileformat, 'transposed') a.data.data.x; else permute(a, [3 1 2]); end;
github
ZijingMao/baselineeegtest-master
reshape.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/reshape.m
1,449
utf_8
d59a7e256f6fc43fe77f3be9319fcc46
% reshape() - reshape of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function a = reshape(a,d1,d2,d3) % decode length % ------------- if nargin > 3 d1 = [ d1 d2 d3 ]; elseif nargin > 2 d1 = [ d1 d2 ]; end; if prod(size(a)) ~= prod(d1) error('Wrong dimensions for reshaping'); end; if ~strcmpi(a.fileformat, 'transposed') a.data.format{2} = d1; else if length(d1) == 1 a.data.format{2} = d1; elseif length(d1) == 2 a.data.format{2} = [d1(2) d1(1)]; else a.data.format{2} = d1([2 3 1]); end; end;
github
ZijingMao/baselineeegtest-master
end.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/end.m
901
utf_8
0e38d125a547083cb574fbd3bb455fbd
% end() - last index to memmapdata array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function s = end(a, k, n); s = size(a, k);
github
ZijingMao/baselineeegtest-master
subsasgn.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/subsasgn.m
1,590
utf_8
6b2894eb17dab5aae0637b84992ffb7d
% subsasgn() - define index assignment for eegdata objects % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function b = subsasgn(a,index,val) i.type = '()'; i.subs = { ':' ':' ':' }; b = subsref(a, i); % note that subsref cannot be called directly c = subsref(val, i); b = builtin('subsasgn', b, index, c); return; switch index.type case '()' switch length(index.subs) case 1, a.data(index.subs{1}) = val; case 2, a.data(index.subs{1}, index.subs{2}) = val; case 3, a.data(index.subs{1}, index.subs{2}, index.subs{3}) = val; case 4, a.data(index.subs{1}, index.subs{2}, index.subs{3}, index.subs{4}) = val; end; case '.' switch index.subs case 'srate' a.srate = val; case 'nbchan' a.nbchan = val; otherwise error('Invalid field name') end end
github
ZijingMao/baselineeegtest-master
isnumeric.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/isnumeric.m
877
utf_8
34baf204e1b984ee69cf7f462fe2e524
% isnumeric() - returns 1 % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function r = isnumeric(a) r = 1;
github
ZijingMao/baselineeegtest-master
length.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/length.m
913
utf_8
f0841237745a123f3215e00164cc4a1a
% length() - length of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function s = length(a) s = size(a,1);
github
ZijingMao/baselineeegtest-master
sum.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/sum.m
1,913
utf_8
dbd7353e16ccf6a1a0b69875cd9050cb
% sum() - sum of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [s] = sum(a,dim) if nargin < 2 dim = 1; end; %b = (:,:,:); if ~strcmpi(a.fileformat, 'transposed') s = sum(a.data.data.x, dim); else alldim = [3 1 2]; if length(size(a)) == 3 dim = alldim(dim); s = sum(a.data.data.x, dim); s = permute(s, [3 1 2]); else if dim == 1 dim = 2; else dim = 1; end; s = sum(a.data.data.x, dim)'; end; end; return; % do pnts by pnts if dim = 1 % if dim == 1 & length( % % s = zeros(size(a,2), size(a,3)); % for i=1:size(a,2) % s(i,:) = mean(a.data.data.x(:,i,:)); % end; % elseif dim == 1 % s = zeros(size(a,1), size(a,1)); % for i=1:size(a,1) % s(i,:) = mean(a.data.data.x(:,:,:)); % end; % % % s = builtin('sum', rand(10,10), dim); %if length(size(a)) > 2 %else s = sum(a(:,:,:), dim); %end;
github
ZijingMao/baselineeegtest-master
size.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/size.m
1,383
utf_8
c7033b3ab1405ded2c8794f2c214beb9
% size() - size of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [s s2 s3] = size(a,dim) if isnumeric(a.data), s = size(a.data) else s = a.data.format{2}; if strcmpi(a.fileformat, 'transposed') if length(s) == 2, s = s([2 1]); elseif length(s) == 3 s = [s(3) s(1) s(2)]; end; end; end; if nargin > 1 s = [s 1]; s = s(dim); end; if nargout > 2 s3 = s(3); end; if nargout > 1 s2 = s(2); s = s(1); end;
github
ZijingMao/baselineeegtest-master
subsref.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/subsref.m
4,622
utf_8
096fd75b6454f11ffee5a172000a64c1
% subsref() - index eegdata class % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function b = subsref(a,s) if s(1).type == '.' b = builtin('subsref', struct(a), s); return; end; subs = s(1).subs; finaldim = cellfun('length', subs); % one dimension input % ------------------- if length(s(1).subs) == 1 if isstr(subs{1}) subs{1} = [1:size(a,1)]; subs{2} = [1:size(a,2)]; if ndims(a) == 3, subs{3} = [1:size(a,3)]; end; finaldim = prod(size(a)); end; % two dimension input % ------------------- elseif length(s(1).subs) == 2 if isstr(subs{1}), subs{1} = [1:size(a,1)]; end; if isstr(subs{2}), subs{2} = [1:size(a,2)]; if ndims(a) == 3, subs{3} = [1:size(a,3)]; end; end; if length(subs) == 3 finaldim = [ length(subs{1}) length(subs{2})*length(subs{3}) ]; else finaldim = [ length(subs{1}) length(subs{2}) ]; end; % three dimension input % --------------------- elseif length(s(1).subs) == 3 if isstr(subs{1}), subs{1} = [1:size(a,1)]; end; if isstr(subs{2}), subs{2} = [1:size(a,2)]; end; if ndims(a) == 2, subs(3) = []; else if isstr(subs{3}), subs{3} = [1:size(a,3)]; end; end; finaldim = cellfun('length', subs); end; % non-transposed data % ------------------- if ~strcmpi(a.fileformat, 'transposed') if length(subs) == 1, b = a.data.data.x(subs{1}); end; if length(subs) == 2, b = a.data.data.x(subs{1}, subs{2}); end; if length(subs) == 3, b = a.data.data.x(subs{1}, subs{2}, subs{3}); end; else if ndims(a) == 2 %if length(s) == 0, b = transpose(a.data.data.x); return; end; if length(s(1).subs) == 1, b = a.data.data.x(s(1).subs{1})'; end; if length(s(1).subs) == 2, b = a.data.data.x(s(1).subs{2}, s(1).subs{1})'; end; if length(s(1).subs) == 3, b = a.data.data.x(s(1).subs{2}, s(1).subs{1})'; end; else %if length(s) == 0, b = permute(a.data.data.x, [3 1 2]); return; end; if length(subs) == 1, inds1 = mod(subs{1}-1, size(a,1))+1; inds2 = mod((subs{1}-inds1)/size(a,1), size(a,2))+1; inds3 = ((subs{1}-inds1)/size(a,1)-inds2+1)/size(a,2)+1; inds = (inds1-1)*size(a,2)*size(a,3) + (inds3-1)*size(a,2) + inds2; b = a.data.data.x(inds); else if length(subs) < 2, subs{3} = 1; end; % repmat if several indices in different dimensions % ------------------------------------------------- len = cellfun('length', subs); subs{1} = repmat(reshape(subs{1}, [len(1) 1 1]), [1 len(2) len(3)]); subs{2} = repmat(reshape(subs{2}, [1 len(2) 1]), [len(1) 1 len(3)]); subs{3} = repmat(reshape(subs{3}, [1 1 len(3)]), [len(1) len(2) 1]); inds = (subs{1}-1)*a.data.Format{2}(1)*a.data.Format{2}(2) + (subs{3}-1)*a.data.Format{2}(1) + subs{2}; inds = reshape(inds, [1 prod(size(inds))]); b = a.data.data.x(inds); end; end; end; if length(finaldim) == 1, finaldim(2) = 1; end; b = reshape(b, finaldim); % 2 dims %inds1 = mod(myinds-1, size(a,1))+1; %inds2 = (myinds-inds1)/size(a,1)+1; %inds = (inds2-1)*size(a,1) + inds1; % 3 dims %inds1 = mod(myinds-1, size(a,1))+1; %inds2 = mod((myinds-inds1)/size(a,1), size(a,2))+1; %inds3 = ((myinds-inds1)/size(a,1)-inds2)/size(a,2)+1; %inds = (inds3-1)*size(a,1)*size(a,2) + inds2*size(a,1) + inds1;
github
ZijingMao/baselineeegtest-master
ndims.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/ndims.m
1,169
utf_8
8c3ed2dde450e1422a2552d22e9c150b
% ndims() - number of dimension of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function s = ndims(a) if ~strcmpi(a.fileformat, 'transposed') if a.data.Format{2}(3) == 1, s = 2; else s = 3; end; else if a.data.Format{2}(2) == 1, s = 2; else s = 3; end; end;
github
ZijingMao/baselineeegtest-master
memmapdata.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@memmapdata/memmapdata.m
1,994
utf_8
5f967fcb7b637954900e09789144dde6
% memmapdata() - create a memory-mapped data class % % Usage: % >> data_class = memmapdata(data); % % Inputs: % data - input data or data file % % Outputs: % data_class - output dataset class % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function dataout = memmapdata(data, datadims); dataout.fileformat = 'normal'; if isstr(data) if length(data) > 3 if strcmpi('.dat', data(end-3:end)) dataout.fileformat = 'transposed'; end; end; % check that the file is not empty % -------------------------------- a = dir(data); if isempty(a) error([ 'Data file ''' data '''not found' ]); elseif a(1).bytes == 0 error([ 'Empty data file ''' data '''' ]); end; if ~strcmpi(dataout.fileformat, 'transposed') dataout.data = memmapfile(data, 'writable', false, 'format', { 'single' datadims 'x' }); else dataout.data = memmapfile(data, 'writable', false, 'format', { 'single' [ datadims(2:end) datadims(1) ] 'x' }); end; dataout = class(dataout,'memmapdata'); else dataout = data; end;
github
ZijingMao/baselineeegtest-master
display.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/display.m
1,161
utf_8
b43db5e3387d5dcb39fafa9aa03939f9
% display() - display an EEG data class underlying structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function display(obj); tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); if obj.transposed, disp('Warning: data does not display properly for memory mapped file which have been transposed'); end; disp(tmpMMO.data.x);
github
ZijingMao/baselineeegtest-master
reshape.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/reshape.m
1,242
utf_8
cc03295fbaa6179eb2e8b266daf6b644
% reshape() - reshape of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function obj = reshape(obj,d1,d2,d3) % decode length % ------------- if nargin > 3 d1 = [ d1 d2 d3 ]; elseif nargin > 2 d1 = [ d1 d2 ]; end; if prod(size(obj)) ~= prod(d1) error('Wrong dimensions for reshaping'); end; if obj.transposed d1 = [d1(2:end) d1(1)]; end; obj.dimensions = d1;
github
ZijingMao/baselineeegtest-master
subsasgn_old.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/subsasgn_old.m
9,802
utf_8
0fc68a1bfa60e3118b3a4b6efd10fa52
% subsasgn() - define index assignment for eegdata objects % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function obj = subsasgn(obj,ss,val) % check stack % ----------- stack = dbstack; stack(1) = []; stack = rmfield(stack, 'line'); ncopies = 0; if ~isempty(stack) % check if we are in a different workspace if ~isequal(stack, obj.workspace) % if subfunction, must be a copie if ~isempty(obj.workspace) && strcmpi(stack(end).file, obj.workspace(end).file) && ... ~strcmpi(stack(end).name, obj.workspace(end).name) % We are within a subfunction. The MMO must have % been passed as an argument (otherwise the current % workspace and the workspace variable would be % equal). ncopies = 2; else tmpVar = evalin('caller', 'nargin;'); % this does not work if ~isscript(stack(1).file) ncopies = 2; % we are within a function. The MMO must have % been passed as an argument (otherwise the current % workspace and the workspace variable would be % equal). else % we cannot be in a function with 0 argument % (otherwise the current workspace and the workspace % variable would be equal). We must assume that % we are in a script. while ~isempty(stack) && ~isequal(stack, obj.workspace) stack(1) = []; end; if ~isequal(stack, obj.workspace) ncopies = 2; end; end; end; end; end; % check local variables % --------------------- if ncopies < 2 s = evalin('caller', 'whos'); for index = 1:length(s) if strcmpi(s(index).class, 'struct') || strcmpi(s(index).class, 'cell') tmpVar = evalin('caller', s(index).name); ncopies = ncopies + checkcopies_local(obj, tmpVar); elseif strcmpi(s(index).class, 'mmo') if s(index).persistent || s(index).global disp('Warning: mmo objects should not be made persistent or global. Behavior is unpredictable.'); end; tmpVar = evalin('caller', s(index).name); if isequal(tmpVar, obj), ncopies = ncopies + 1; end; if ncopies > 1, break; end; end; end; end; % removing some entries % --------------------- if isempty(val) newdim1 = obj.dimensions; newdim2 = obj.dimensions; % create new array of new size % ---------------------------- tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9)); % find non singleton dimension % ---------------------------- nonSingleton = []; for index = 1:length(subs) if ~isstr(subs{index}) % can only be ":" nonSingleton(end+1) = index; subs2 = setdiff_bc([1:newdim1(index)], subs{index}); % invert selection end; end; if length(nonSingleton) > 1, error('A null assignment can have only one non-colon index'); end; if isempty(nonSingleton), obj = []; return; end; % compute new final dimension % --------------------------- if length(ss(1).subs) == 1 fid = fopen(newFileName, 'w'); newdim2 = prod(newdim2)-length(ss(1).subs{1}); newindices = setdiff_bc([1:prod(newdim1)], ss(1).subs{1}); for index = newindices fwrite(fid, tmpMMO.Data.x(index), 'float'); end; fclose(fid); else newdim2(nonSingleton) = newdim2(nonSingleton)-length(subs{index}); tmpdata = builtin('subsref', tmpMMO.Data.x, s); fid = fopen(newFileName, 'w'); fwrite(fid, tmpMMO.Data.x(index), 'float'); fclose(fid); end; % delete file if necessary if ncopies == 1 && obj.writable delete(obj.dataFile); end; if obj.debug, disp('new copy created, old deleted (length 1)'); end; obj.dimensions = [1 newdim2]; obj.dataFile = newFileName; obj.writable = true; clear tmpMMO; return; elseif ncopies == 1 && obj.writable for index = 1:length(ss(1).subs) newdim2(notOneDim) = newdim2(notOneDim)-length(ss(1).subs{1}); if index > length(newdim2) newdim2(index) = max(ss(1).subs{index}); else newdim2(index) = max(max(ss(1).subs{index}), newdim2(index)); end; end; % create new array of new size % ----------------------------------------- tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9)); % copy file row by row % -------------------- fid = fopen(newFileName, 'w'); tmpdata = zeros(prod(newdim2(1)) - prod(newdim1(1)), 1, 'single'); for index = 1:prod(newdim1(2:end)) fwrite(fid, tmpMMO.Data.x(:,index), 'float'); fwrite(fid, tmpdata, 'float'); end; if prod(newadim1(2:end)) ~= prod(newdim2(2:end)) tmpdata = zeros(newdim2(1), 1, 'single'); for index = prod(newdim1(2:end))+1:prod(newdim2(2:end)) fwrite(fid, tmpdata, 'float'); end; end; fclose(fid); % delete file if necessary if ncopies == 1 && obj.writable delete(obj.dataFile); end; if obj.debug, disp('new copy created, old deleted'); end; obj.dimensions = newdim2; obj.dataFile = newFileName; obj.writable = true; clear tmpMMO; else % check size % ---------- newdim1 = obj.dimensions; newdim2 = obj.dimensions; if length(ss(1).subs) == 1 if max(ss(1).subs{1}) > prod(newdim2) notOneDim = find(newdim2 > 1); if length(notOneDim) == 1 newdim2(notOneDim) = max(ss(1).subs{1}); end; end; else for index = 1:length(ss(1).subs) if index > length(newdim2) newdim2(index) = max(ss(1).subs{index}); else newdim2(index) = max(max(ss(1).subs{index}), newdim2(index)); end; end; end; % create new array of new size if necessary % ----------------------------------------- if ~isequal(newdim1, newdim2) tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9)); % copy file row by row % -------------------- fid = fopen(newFileName, 'w'); tmpdata = zeros(prod(newdim2(1)) - prod(newdim1(1)), 1, 'single'); for index = 1:prod(newdim1(2:end)) fwrite(fid, tmpMMO.Data.x(:,index), 'float'); fwrite(fid, tmpdata, 'float'); end; if prod(newdim1(2:end)) ~= prod(newdim2(2:end)) tmpdata = zeros(newdim2(1), 1, 'single'); for index = prod(newdim1(2:end))+1:prod(newdim2(2:end)) fwrite(fid, tmpdata, 'float'); end; end; fclose(fid); % delete file if necessary if ncopies == 1 && obj.writable delete(obj.dataFile); end; if obj.debug, disp('new copy created, old deleted'); end; obj.dimensions = newdim2; obj.dataFile = newFileName; obj.writable = true; clear tmpMMO; % create copy if necessary % ------------------------ elseif ncopies > 1 || ~obj.writable newFileName = sprintf('memapdata_%.9d%.9d.fdt', round(rand(1)*10^9), round(rand(1)*10^9)); copyfile(obj.dataFile, newFileName); obj.dataFile = newFileName; obj.writable = true; if obj.debug, disp('new copy created'); end; else if obj.debug, disp('using same copy'); end; end; tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss, val); end; return; % i.type = '()'; % i.subs = { ':' ':' ':' }; % res = subsref(obj, i); % note that subsref cannot be called directly % subfunction checking the number of copies % ----------------------------------------- function ncopies = checkcopies_local(obj, arg); ncopies = 0; if isstruct(arg) for ilen = 1:length(arg) for index = fieldnames(arg)' ncopies = ncopies + checkcopies_local(obj, arg(ilen).(index{1})); if ncopies > 1, return; end; end; end; elseif iscell(arg) for index = 1:length(arg(:)) ncopies = ncopies + checkcopies_local(obj, arg{index}); if ncopies > 1, return; end; end; elseif isa(arg, 'mmo') && isequal(obj, arg) ncopies = 1; else ncopies = 0; end;
github
ZijingMao/baselineeegtest-master
end.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/end.m
901
utf_8
0e38d125a547083cb574fbd3bb455fbd
% end() - last index to memmapdata array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function s = end(a, k, n); s = size(a, k);
github
ZijingMao/baselineeegtest-master
subsasgn.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/subsasgn.m
10,331
utf_8
5788e61c5645defe830043553e4122ff
% subsasgn() - define index assignment for eegdata objects % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function obj = subsasgn(obj,ss,val) % check empty assignement % ----------------------- for index = 1:length(ss(1).subs) if isempty(ss(1).subs{index}), return; end; end; % remove useless ":" % ------------------ while length(obj.dimensions) < length(ss(1).subs) if isequal(ss(1).subs{end}, ':') ss(1).subs(end) = []; else break; end; end; % deal with transposed data % ------------------------- if obj.transposed, ss = transposeindices(obj, ss); end; % check stack and local variables % --------------------- ncopies = checkworkspace(obj); if ncopies < 2 if isempty(inputname(1)) vers = version; indp = find(vers == '.'); if str2num(vers(indp(1)+1)) > 1, vers = [ vers(1:indp(1)) '0' vers(indp(1)+1:end) ]; end; indp = find(vers == '.'); vers = str2num(vers(1:indp(2)-1)); if vers >= 7.13 % the problem with Matlab 2012a/2011b is that if the object called is % in a field of a structure (empty inputname), the evaluation % in the caller of the object variable is empty in 2012a. A bug % repport has been submitted to Matlab - Arno ncopies = ncopies + 1; end; end; s = evalin('caller', 'whos'); for index = 1:length(s) if strcmpi(s(index).class, 'struct') || strcmpi(s(index).class, 'cell') tmpVar = evalin('caller', s(index).name); ncopies = ncopies + checkcopies_local(obj, tmpVar); elseif strcmpi(s(index).class, 'mmo') if s(index).persistent || s(index).global disp('Warning: mmo objects should not be made persistent or global. Behavior is unpredictable.'); end; tmpVar = evalin('caller', s(index).name); if isequal(tmpVar, obj), ncopies = ncopies + 1; end; if ncopies > 1, break; end; end; end; end; % removing some entries % --------------------- if isempty(val) newdim1 = obj.dimensions; newdim2 = obj.dimensions; % create new array of new size % ---------------------------- tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); newFileName = mmo.getnewfilename; % find non singleton dimension % ---------------------------- nonSingleton = []; ss2 = ss; for index = 1:length(ss(1).subs) if ~isstr(ss(1).subs{index}) % can only be ":" nonSingleton(end+1) = index; ss2(1).subs{index} = setdiff_bc([1:newdim1(index)], ss(1).subs{index}); % invert selection end; end; if length(nonSingleton) > 1, error('A null assignment can have only one non-colon index'); end; if isempty(nonSingleton), obj = []; return; end; % compute new final dimension and copy data % ----------------------------------------- if length(ss(1).subs) == 1 fid = fopen(newFileName, 'w'); newdim2 = [ prod(newdim2)-length(ss(1).subs{1}) ]; if ~(newdim1(1) > 1 && all(newdim1(2:end) == 1)), newdim2 = [1 newdim2]; else newdim2 = [newdim2 1]; end; newindices = setdiff_bc([1:prod(newdim1)], ss(1).subs{1}); for index = newindices fwrite(fid, tmpMMO.Data.x(index), 'float'); end; fclose(fid); else if length(ss(1).subs) < length(newdim2) newdim2(length(ss(1).subs)) = prod(newdim2(length(ss(1).subs):end)); newdim2(length(ss(1).subs)+1:end) = []; if nonSingleton == length(ss(1).subs) ss2(1).subs{end} = setdiff_bc([1:newdim2(end)], ss(1).subs{end}); end; end; newdim2(nonSingleton) = newdim2(nonSingleton)-length(ss(1).subs{nonSingleton}); if isstr(ss2.subs{end}) ss2.subs{end} = [1:prod(newdim1(length(ss2.subs):end))]; end; ss3 = ss2; fid = fopen(newFileName, 'w'); % copy large blocks alllen = cellfun(@length, ss2.subs); inc = ceil(250000/prod(alllen(1:end-1))); % 1Mb block for index = 1:inc:length(ss2.subs{end}) ss3.subs{end} = ss2.subs{end}(index:min(index+inc, length(ss2.subs{end}))); tmpdata = subsref(tmpMMO.Data.x, ss3); fwrite(fid, tmpdata, 'float'); end; fclose(fid); end; % delete file if necessary if ncopies == 1 && obj.writable delete(obj.dataFile); end; if obj.debug, disp('new copy created, old deleted (length 1)'); end; obj.dimensions = newdim2; obj.dataFile = newFileName; obj.writable = true; obj = updateWorkspace(obj); clear tmpMMO; return; else % check size to see if it increases % --------------------------------- newdim1 = obj.dimensions; newdim2 = newdim1; if length(ss(1).subs) == 1 if ~isstr(ss(1).subs{1}) && max(ss(1).subs{1}) > prod(newdim1) if length(newdim1) > 2 error('Attempt to grow array along ambiguous dimension.'); end; end; if max(ss(1).subs{1}) > prod(newdim2) notOneDim = find(newdim2 > 1); if length(notOneDim) == 1 newdim2(notOneDim) = max(ss(1).subs{1}); end; end; else if length(newdim1) == 3 && newdim1(3) == 1, newdim1(end) = []; end; if length(ss(1).subs) == 2 && length(newdim1) == 3 if ~isstr(ss(1).subs{2}) && max(ss(1).subs{2}) > prod(newdim1(2:end)) error('Attempt to grow array along ambiguous dimension.'); end; if isnumeric(ss(1).subs{1}), newdim2(1) = max(max(ss(1).subs{1}), newdim2(1)); end; else for index = 1:length(ss(1).subs) if isnumeric(ss(1).subs{index}) if index > length(newdim2) newdim2(index) = max(ss(1).subs{index}); else newdim2(index) = max(max(ss(1).subs{index}), newdim2(index)); end; end; end; end; end; % create new array of new size if necessary % ----------------------------------------- if ~isequal(newdim1, newdim2) tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); newFileName = mmo.getnewfilename; % copy file row by row % -------------------- fid = fopen(newFileName, 'w'); dim1 = [ newdim1 1 1 1 1 ]; dim2 = [ newdim2 1 1 1 1 ]; tmpdata1 = zeros(prod(dim2(1:1)) - prod(dim1(1:1)), 1, 'single'); tmpdata2 = zeros((dim2(2) - dim1(2))*dim2(1), 1, 'single'); tmpdata3 = zeros((dim2(3) - dim1(3))*prod(dim2(1:2)), 1, 'single'); % copy new data (copy first array) % ------------- for index3 = 1:dim1(3) if dim1(1) == dim2(1) && dim1(2) == dim2(2) fwrite(fid, tmpMMO.Data.x(:,:,index3), 'float'); else for index2 = 1:dim1(2) if dim1(1) == dim2(1) fwrite(fid, tmpMMO.Data.x(:,index2,index3), 'float'); else for index1 = 1:dim1(1) fwrite(fid, tmpMMO.Data.x(index1,index2,index3), 'float'); end; end; fwrite(fid, tmpdata1, 'float'); end; end; fwrite(fid, tmpdata2, 'float'); end; fwrite(fid, tmpdata3, 'float'); fclose(fid); % delete file if necessary if ncopies == 1 && obj.writable delete(obj.dataFile); end; if obj.debug, disp('new copy created, old deleted'); end; obj.dimensions = newdim2; obj.dataFile = newFileName; obj.writable = true; clear tmpMMO; % create copy if necessary % ------------------------ elseif ncopies > 1 || ~obj.writable newFileName = mmo.getnewfilename; copyfile(obj.dataFile, newFileName); obj.dataFile = newFileName; obj.writable = true; if obj.debug, disp('new copy created'); end; else if obj.debug, disp('using same copy'); end; end; % copy new data tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); if ~isa(val, 'mmo') tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss, val); else % copy memory mapped array if ndims(val) == 2 && (size(val,1) == 1 || size(val,2) == 1) % vector direct copy ss2.type = '()'; ss2.subs = { ':' ':' ':' }; tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss, subsref(val,ss2)); else ss2.type = '()'; ss2.subs = { ':' ':' ':' }; ss3 = ss; % array, copy each channel for index1 = 1:size(val,1) ss2(1).subs{1} = index1; if isstr(ss(1).subs{1}) ss3(1).subs{1} = index1; else ss3(1).subs{1} = ss(1).subs{1}(index1); end; tmpMMO.Data.x = builtin('subsasgn', tmpMMO.Data.x, ss3, subsref(val,ss2)); end; end; end; obj = updateWorkspace(obj); end;
github
ZijingMao/baselineeegtest-master
isnumeric.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/isnumeric.m
877
utf_8
34baf204e1b984ee69cf7f462fe2e524
% isnumeric() - returns 1 % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function r = isnumeric(a) r = 1;
github
ZijingMao/baselineeegtest-master
checkcopies_local.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/checkcopies_local.m
634
utf_8
8eb8d5fec95c91346e91a09010082b47
% subfunction checking the number of local copies % ----------------------------------------------- function ncopies = checkcopies_local(obj, arg); ncopies = 0; if isstruct(arg) for ilen = 1:length(arg) for index = fieldnames(arg)' ncopies = ncopies + checkcopies_local(obj, arg(ilen).(index{1})); if ncopies > 1, return; end; end; end; elseif iscell(arg) for index = 1:length(arg(:)) ncopies = ncopies + checkcopies_local(obj, arg{index}); if ncopies > 1, return; end; end; elseif isa(arg, 'mmo') && isequal(obj, arg) ncopies = 1; else ncopies = 0; end;
github
ZijingMao/baselineeegtest-master
changefile.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/changefile.m
187
utf_8
e75127c90da43ddce182d36cf0abbdee
% this function is called when the file is being saved function obj = changefile(obj, newfile) movefile(obj.dataFile, newfile); obj.dataFile = newfile; obj.writable = false;
github
ZijingMao/baselineeegtest-master
var.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/var.m
1,416
utf_8
2360192fa42b3c35ebd7743ffe4fe8b6
% var() - variance of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function sumval = var(obj,flag,dim) if nargin < 2 flag = 0; end; if nargin < 3 dim = 1; end; meanvalsq = mean(obj,dim).^2; sumval = 0; s1 = size(obj); ss.type = '()'; ss.subs(1:length(s1)) = { ':' }; for index = 1:s1(dim) ss.subs{dim} = index; tmpdata = subsref(obj, ss); sumval = sumval + tmpdata.*tmpdata - meanvalsq; end; if isempty(flag) || flag == 0 sumval = sumval/(size(obj,dim)-1); else sumval = sumval/size(obj,dim); end;
github
ZijingMao/baselineeegtest-master
length.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/length.m
913
utf_8
f0841237745a123f3215e00164cc4a1a
% length() - length of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function s = length(a) s = size(a,1);
github
ZijingMao/baselineeegtest-master
sum.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/sum.m
1,212
utf_8
2fbce1d1b6e2a5edf32742897441a732
% sum() - sum of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function sumval = sum(obj,dim) if nargin < 2 dim = 1; end; s1 = size(obj); ss.type = '()'; ss.subs(1:length(s1)) = { ':' }; for index = 1:s1(dim) ss.subs{dim} = index; if index == 1 sumval = subsref(obj, ss); else sumval = sumval + subsref(obj, ss); end; end;
github
ZijingMao/baselineeegtest-master
size.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/size.m
1,751
utf_8
daf6932de04161ccb2df3df31b45203a
% size() - size of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [s varargout] = size(obj,dim) if obj.transposed if length(obj.dimensions) ~= 2 && length(obj.dimensions) ~= 3 error('Transposed array must be 2 or 3 dims'); end; if length(obj.dimensions) == 2 tmpdimensions = [obj.dimensions(2) obj.dimensions(1)]; else tmpdimensions = [obj.dimensions(3) obj.dimensions(1:end-1)]; end; else tmpdimensions = obj.dimensions; end; s = tmpdimensions; if nargin > 1 if dim >length(s) s = 1; else s = s(dim); end; else if nargout > 1 s = [s 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]; alls = s; s = s(1); for index = 1:max(nargout,1)-1 varargout{index} = alls(index+1); end; end; end;
github
ZijingMao/baselineeegtest-master
subsref.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/subsref.m
2,711
utf_8
1da2db6dbbc53f36d6d2954f095f9064
% subsref() - index eegdata class % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function res = subsref(obj,s) if strcmpi(s(1).type, '.') res = builtin('subsref', obj, s); return; end; tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' }); subs = s(1).subs; finaldim = cellfun('length', subs); % one dimension input % ------------------- if length(s) > 1 || ~strcmpi(s(1).type, '()') error('MMO can only map single array data files'); end; % deal with transposed data % ------------------------- if obj.transposed, s = transposeindices(obj, s); end; % convert : to real sizes % ----------------------- lastdim = length(subs); if isstr(subs{end}) && ndims(obj) > lastdim for index = lastdim+1:ndims(obj) if index > length(obj.dimensions) subs{index} = 1; else subs{index} = [1:obj.dimensions(index)]; end; end; end; for index = 1:length(subs) if isstr(subs{index}) % can only be ":" if index > length(obj.dimensions) subs{index} = 1; else subs{index} = [1:obj.dimensions(index)]; end; end; end; finaldim = cellfun(@length, subs); finaldim(lastdim) = prod(finaldim(lastdim:end)); finaldim(lastdim+1:end) = []; % non-transposed data % ------------------- res = tmpMMO.data.x(subs{:}); if length(finaldim) == 1, finaldim(2) = 1; end; res = reshape(res, finaldim); if obj.transposed if finaldim(end) == 1, finaldim(end) = []; end; if length(finaldim) <= 2, res = res'; else res = reshape(res, [finaldim(1)*finaldim(2) finaldim(3)])'; res = reshape(res, [finaldim(3) finaldim(1) finaldim(2)]); end; end;
github
ZijingMao/baselineeegtest-master
ndims.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/@mmo/ndims.m
1,095
utf_8
7ddcbafa2aaf95308a1a4de4a272f0ae
% ndims() - number of dimension of memory mapped underlying array % % Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function res = ndims(obj) if length(obj.dimensions) <= 2 || all(obj.dimensions(3:end) == 1), res = 2; else res = length(obj.dimensions); end;
github
ZijingMao/baselineeegtest-master
correctfit.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/timefreqfunc/correctfit.m
3,222
utf_8
69c8b2f965023329820bdfd3c7e82176
% correctfit() - correct fit using observed p-values. Use this function % if for some reason, the distribution of p values is % not uniform between 0 and 1 % % Usage: % >> [p phat pci zerofreq] = correctfit(pval, 'key', 'val'); % % Inputs: % pval - input p value % % Optional inputs: % 'allpval' - [float array] collection of p values drawn from random % distributions (theoritically uniform). % 'gamparams' - [phat pci zerofreq] parameter for gamma function fitting. % zerofreq is the frequency of occurence of p=0. % 'zeromode' - ['on'|'off'] enable estimation of frequency of pval=0 % (this might lead to hight pval). Default is 'on'. % % Outputs: % p - corrected p value. % phat - phat gamfit() parameter. % pci - phat gamfit() parameter. % zerofreq - frequency of occurence of p=0. % % Authors: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2003- % % See also: bootstat() % Copyright (C) 7/02/03 Arnaud Delorme, SCCN/INC/UCSD % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [pval, PHAT, PCI, zerofreq] = correctfit(pval, varargin) if nargin < 2 help correctfit; disp('You need to specify one optional input'); return; end; g = finputcheck( varargin, { 'allpval' 'real' [0 1] []; 'zeromode' 'string' {'on','off'} 'on'; 'gamparams' 'real' [] []}, 'correctfit'); if isstr(g), error(g); end; if ~isempty(g.gamparams) PHAT = g.gamparams(1); PCI = g.gamparams(2); zerofreq = g.gamparams(3); elseif ~isempty(g.allpval) nonzero = find(g.allpval(:) ~= 0); zerofreq = (length(g.allpval(:))-length(nonzero))/ length(g.allpval(:)); tmpdat = -log10( g.allpval(nonzero) ) + 1E-10; [PHAT, PCI] = gamfit( tmpdat ); PHAT = PHAT(1); PCI = PCI(2); end; if pval == 0 if strcmpi(g.zeromode, 'on') pval = zerofreq; end; else tmppval = -log10( pval ) + 1E-10; pval = 1-gamcdf( tmppval, PHAT, PCI); end; if 1 % plotting if exist('tmpdat') == 1 figure; hist(tmpdat, 100); hold on; mult = ylim; tmpdat = linspace(0.00001,10, 300); normy = gampdf( tmpdat, PHAT, PCI); plot( tmpdat, normy/max(normy)*mult(2)*3, 'r'); end; end;
github
ZijingMao/baselineeegtest-master
timef.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/timefreqfunc/timef.m
42,818
utf_8
6663467d76d01722baccf168fec18e1b
% timef() - Returns estimates and plots of mean event-related spectral % perturbation (ERSP) and inter-trial coherence (ITC) changes % across event-related trials (epochs) of a single input time series. % * Uses either fixed-window, zero-padded FFTs (fastest), wavelet % 0-padded DFTs (both Hanning-tapered), OR multitaper spectra ('mtaper'). % * 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, then bootstrap statistics are computed % (from a distribution of 'naccu' surrogate data trials) and % non-significant features of the output plots are zeroed out % (i.e., plotted in green). % * Given a 'topovec' scalp map weights vector and an 'elocs' electrode % location file or structure, the figure also shows a topoplot() % image of the specified scalp map. % % * Note: Left-click on subplots to view and zoom in separate windows. % Usage: % >> [ersp,itc,powbase,times,freqs,erspboot,itcboot,itcphase] = ... % timef(data,frames,tlimits,srate,cycles,... % 'key1',value1,'key2',value2, ... ); % NOTE: % * For more detailed information about timef(), >> timef details % * Default values may differ when called from pop_timef() % % Required inputs: % data = Single-channel data vector (1,frames*ntrials) (required) % frames = Frames per trial {def|[]: datalength} % tlimits = [mintime maxtime] (ms) Epoch time limits % {def|[]: from frames,srate} % srate = data sampling rate (Hz) {def:250} % cycles = If 0 -> Use FFTs (with constant window length) {0 = FFT} % If >0 -> Number of cycles in each analysis wavelet % If [wavecycles factor] -> wavelet cycles increase with % frequency beginning at wavecyles (0<factor<1; factor=1 % -> no increase, standard wavelets; factor=0 -> fixed epoch % length, as in FFT. Else, 'mtaper' -> multitaper decomp. % % Optional Inter-Irial Coherence (ITC) type: % 'type' = ['coher'|'phasecoher'] Compute either linear coherence % ('coher') or phase coherence ('phasecoher') also known % as the phase coupling factor {'phasecoher'}. % Optional detrending: % 'detret' = ['on'|'off'], Detrend data in time. {'off'} % 'detrep' = ['on'|'off'], Detrend data across trials {'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 {~frames/8} % 'timesout' = Number of output times (int<frames-winframes) {200} % 'padratio' = FFT-length/winframes (2^k) {2} % Multiplies the number of output frequencies by % dividing their spacing. When cycles==0, frequency % spacing is (low_freq/padratio). % 'maxfreq' = Maximum frequency (Hz) to plot (& to output if cycles>0) % If cycles==0, all FFT frequencies are output. {50} % 'baseline' = Spectral baseline window center end-time (in ms). {0} % 'powbase' = Baseline spectrum (power, not dB) to normalize the data. % {def|NaN->from data} % % Optional multitaper parameters: % '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], uses 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} % % Optional bootstrap parameters: % 'alpha' = If non-0, compute two-tailed bootstrap significance prob. % level. Show non-signif. output values in green {0} % 'naccu' = Number of bootstrap replications to accumulate {200} % 'baseboot' = Bootstrap baseline to subtract (1 -> use 'baseline'(above) % 0 -> use whole trial) {1} % Optional scalp map: % 'topovec' = Scalp topography (map) to plot {none} % 'elocs' = Electrode location file for scalp map % File should be ascii in format of >> topoplot example % May also be an EEG.chanlocs struct. % {default: file named in icadefs.m} % Optional plotting parameters: % 'hzdir' = ['up'|'down'] Direction of the frequency axes; reads default % from icadefs.m {'up'} % 'plotersp' = ['on'|'off'] Plot power spectral perturbations {'on'} % 'plotitc' = ['on'|'off'] Plot inter trial coherence {'on'} % 'plotphase' = ['on'|'off'] Plot sign of the phase in the ITC panel, i.e. % green->red, pos.-phase ITC, green->blue, neg.-phase ITC {'on'} % 'erspmax' = [real dB] set the ERSP max. for the scale (min= -max){auto} % 'itcmax' = [real<=1] set the ITC maximum for the scale {auto} % 'title' = Optional figure title {none} % 'marktimes' = Non-0 times to mark with a dotted vertical line (ms) {none} % 'linewidth' = Line width for 'marktimes' traces (thick=2, thin=1) {2} % 'pboot' = Bootstrap power limits (e.g., from timef()) {from data} % 'rboot' = Bootstrap ITC limits (e.g., from timef()) {from data} % 'axesfont' = Axes text font size {10} % 'titlefont' = Title text font size {8} % 'vert' = [times_vector] -> plot vertical dashed lines at given ms. % 'verbose' = ['on'|'off'] print text {'on'} % % Outputs: % ersp = Matrix (nfreqs,timesout) of log spectral diffs. from % baseline (in dB). NB: Not masked for significance. % Must do this using erspboot % itc = Matrix of inter-trial coherencies (nfreqs,timesout) % (range: [0 1]) NB: Not masked for significance. % Must do this using itcboot % powbase = Baseline power spectrum (NOT in dB, used to norm. the ERSP) % times = Vector of output times (sub-window centers) (in ms) % freqs = Vector of frequency bin centers (in Hz) % erspboot = Matrix (2,nfreqs) of [lower;upper] ERSP significance diffs % itcboot = Matrix (2,nfreqs) of [lower;upper] ITC thresholds (not diffs) % itcphase = Matrix (nfreqs,timesout) of ITC phase (in radians) % % 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). % % Author: Sigurd Enghoff, Arnaud Delorme & Scott Makeig % CNL / Salk Institute 1998- | SCCN/INC, UCSD 2002- % % Known problems: % Significance masking currently fails for linear coherence. % % See also: crossf() % Copyright (C) 1998 Sigurd Enghoff, Scott Makeig, Arnaud Delorme, % CNL / Salk Institute 8/1/98-8/28/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 % 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,times,freqs,Pboot,Rboot,Rphase,PA] = timef(X,frames,tlimits,Fs,varwin,varargin); % Note: undocumented arg PA is output of 'phsamp','on' %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 linear 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), % the ITC is the phase coherence between the data time series and the % time-locking event time series. % Read system-wide / dir-wide constants: icadefs % 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. % Commandline arg defaults: DEFAULT_EPOCH = NaN; % Frames per trial DEFAULT_TIMLIM = NaN; % Time range of g.frames (ms) DEFAULT_FS = 250; % Sampling frequency (Hz) 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 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 nargout>7 Rphase = []; % initialize in case Rphase asked for, but ITC not computed end if (nargin < 1) help timef return end if isstr(X) & strcmp(X,'details') more on help timefdetails more off return end if (min(size(X))~=1 | length(X)<2) error('Data must be a row or column vector.'); end if nargin < 2 | isempty(frames) | isnan(frames) frames = DEFAULT_EPOCH; 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.'); elseif (rem(length(X),frames) ~= 0) error('Length of data vector must be divisible by frames.'); end if isnan(frames) | isempty(frames) frames = length(X); end if nargin < 3 | isnan(tlimits) | isempty(tlimits) 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_FS; 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 isnan(tlimits) | isempty(tlimits) hlim = 1000*frames/Fs; % fit default tlimits to srate and frames tlimits = [0 hlim]; end framesdiff = frames - Fs*(tlimits(2)-tlimits(1))/1000; if abs(framesdiff) > 1 error('Given time limits, frames and sampling rate are incompatible'); elseif framesdiff ~= 0 tlimits(1) = tlimits(1) - 0.5*framesdiff*1000/Fs; tlimits(2) = tlimits(2) + 0.5*framesdiff*1000/Fs; fprintf('Adjusted time limits slightly, to [%.1f,%.1f] ms, to match frames and srate.\n',tlimits(1),tlimits(2)); end if (nargin < 5) varwin = DEFAULT_VARWIN; elseif (~isnumeric(varwin) | length(varwin)>2) error('Value of cycles must be a number.'); elseif (varwin < 0) error('Value of cycles must be zero or positive.'); end % consider structure for these arguments % -------------------------------------- if ~isempty(varargin) try, g = struct(varargin{:}); catch, error('Argument error in the {''param'', value} sequence'); end; end; g.tlimits = tlimits; g.frames = frames; g.srate = Fs; g.cycles = varwin(1); if length(varwin)>1 g.cyclesfact = varwin(2); else g.cyclesfact = 1; end; try, g.title; catch, g.title = DEFAULT_TITLE; end; try, g.winsize; catch, g.winsize = max(pow2(nextpow2(g.frames)-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 = DEFAULT_ELOC; end; try, g.alpha; catch, g.alpha = DEFAULT_ALPHA; end; try, g.marktimes; catch, g.marktimes = DEFAULT_MARKTIME; end; try, g.powbase; catch, g.powbase = NaN; end; try, g.pboot; catch, g.pboot = NaN; end; try, g.rboot; catch, g.rboot = NaN; end; try, g.plotersp; catch, g.plotersp = 'on'; end; try, g.plotitc; catch, g.plotitc = 'on'; end; try, g.detrep; catch, g.detrep = 'off'; end; try, g.detret; catch, g.detret = 'off'; end; try, g.baseline; catch, g.baseline = 0; end; try, g.baseboot; catch, g.baseboot = 1; end; try, g.linewidth; catch, g.linewidth = 2; end; try, g.naccu; catch, g.naccu = 200; end; try, g.mtaper; catch, g.mtaper = []; end; try, g.vert; catch, g.vert = []; end; try, g.type; catch, g.type = 'phasecoher'; end; try, g.phsamp; catch, g.phsamp = 'off'; end; try, g.plotphase; catch, g.plotphase = 'on'; end; try, g.itcmax; catch, g.itcmax = []; end; try, g.erspmax; catch, g.erspmax = []; end; try, g.verbose; catch, g.verbose = 'on'; end; try, g.chaninfo; catch, g.chaninfo = []; end; try, g.hzdir; catch, g.hzdir = HZDIR; end; % default from icadefs lasterr(''); % testing arguments consistency % ----------------------------- if strcmp(g.hzdir,'up') g.hzdir = 'normal'; elseif strcmp(g.hzdir,'down') g.hzdir = 'reverse'; else error('unknown ''hzdir'' value - not ''up'' or ''down'''); end switch lower(g.verbose) case { 'on', 'off' }, ; otherwise error('verbose must be either on or off'); end; 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.frames) error('Value of winsize must be less than frames per epoch.'); 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.frames-g.winsize) g.timesout = g.frames-g.winsize; disp(['Value of timesout must be <= frames-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 maxfreq must be a number.'); elseif (g.maxfreq <= 0) error('Value of maxfreq must be positive.'); elseif (g.maxfreq > Fs/2) myprintf(g.verbose,['Warning: value of maxfreq reduced to Nyquist rate' ... ' (%3.2f)\n\n'], Fs/2); g.maxfreq = Fs/2; end if isempty(g.topovec) g.topovec = []; if isempty(g.elocs) error('Channel location file must be specified.'); end; end if isempty(g.elocs) g.elocs = DEFAULT_ELOC; 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) myprintf(g.verbose,'Value of g.alpha is out of the normal range [%g,0.5]\n',2/g.naccu); g.naccu = round(2/g.alpha); myprintf(g.verbose,' 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 myprintf(g.verbose,'Bootstrap analysis will use data in baseline (pre-0 centered) subwindows only.\n') else myprintf(g.verbose,'Bootstrap analysis will use data in all subwindows.\n') end end if ~isnumeric(g.vert) error('vertical line(s) option must be a vector'); else if min(g.vert) < g.tlimits(1) | max(g.vert) > g.tlimits(2) error('vertical line(s) time out-of-bound'); end; end; if ~isnan (g.rboot) if size(g.rboot) == [1,1] if g.cycles == 0 g.rboot = g.rboot*ones(g.winsize*g.padratio/2); end end end; if ~isempty(g.mtaper) % mutitaper, inspired from 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 higher 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); % not used any more %g.padratio = 2*nfk(2)/g.winsize; g.padratio = g.pad/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 work in the case of a FFT end; switch lower(g.plotphase) case { 'on', 'off' }, ; otherwise error('plotphase must be either on or off'); end; switch lower(g.plotersp) case { 'on', 'off' }, ; otherwise error('plotersp must be either on or off'); end; switch lower(g.plotitc) case { 'on', 'off' }, ; otherwise error('plotitc must be either on or off'); end; switch lower(g.detrep) case { 'on', 'off' }, ; otherwise error('detrep must be either on or off'); end; switch lower(g.detret) case { 'on', 'off' }, ; otherwise error('detret must be either on or off'); end; switch lower(g.phsamp) case { 'on', 'off' }, ; otherwise error('phsamp must be either on or off'); end; if ~isnumeric(g.linewidth) error('linewidth must be numeric'); end; if ~isnumeric(g.naccu) error('naccu must be numeric'); end; if ~isnumeric(g.baseline) error('baseline must be numeric'); end; switch g.baseboot case {0,1}, ; otherwise, error('baseboot must be 0 or 1'); end; switch g.type case { 'coher', 'phasecoher', 'phasecoher2' },; otherwise error('Type must be either ''coher'' or ''phasecoher'''); end; if isnan(g.baseline) g.unitpower = 'uV/Hz'; else g.unitpower = 'dB'; end; if (g.cycles == 0) %%%%%%%%%%%%%% constant window-length FFTs %%%%%%%%%%%%%%%% freqs = linspace(0, g.srate/2, g.padratio*g.winsize/2+1); freqs = freqs(2:end); win = hanning(g.winsize); P = zeros(g.padratio*g.winsize/2,g.timesout); % summed power PP = zeros(g.padratio*g.winsize/2,g.timesout); % power R = zeros(g.padratio*g.winsize/2,g.timesout); % mean coherence RR = zeros(g.padratio*g.winsize/2,g.timesout); % (coherence) Pboot = zeros(g.padratio*g.winsize/2,g.naccu); % summed bootstrap power Rboot = zeros(g.padratio*g.winsize/2,g.naccu); % summed bootstrap coher Rn = zeros(1,g.timesout); Rbn = 0; switch g.type case { 'coher' 'phasecoher2' }, cumulX = zeros(g.padratio*g.winsize/2,g.timesout); cumulXboot = zeros(g.padratio*g.winsize/2,g.naccu); case 'phasecoher' switch g.phsamp case 'on' cumulX = zeros(g.padratio*g.winsize/2,g.timesout); end end; else % %%%%%%%%%%%%%%%%%% cycles>0, Constant-Q (wavelet) DFTs %%%%%%%%%%%%%%%%%%%% freqs = g.srate*g.cycles/g.winsize*[2:2/g.padratio:g.winsize]/2; dispf = find(freqs <= g.maxfreq); freqs = freqs(dispf); win = dftfilt(g.winsize,g.maxfreq/g.srate,g.cycles,g.padratio,g.cyclesfact); P = zeros(size(win,2),g.timesout); % summed power R = zeros(size(win,2),g.timesout); % mean coherence PP = repmat(NaN,size(win,2),g.timesout); % initialize with NaN RR = repmat(NaN,size(win,2),g.timesout); % initialize with NaN Pboot = zeros(size(win,2),g.naccu); % summed bootstrap power Rboot = zeros(size(win,2),g.naccu); % summed bootstrap coher Rn = zeros(1,g.timesout); Rbn = 0; switch g.type case { 'coher' 'phasecoher2' }, cumulX = zeros(size(win,2),g.timesout); cumulXboot = zeros(size(win,2),g.naccu); case 'phasecoher' switch g.phsamp case 'on' cumulX = zeros(size(win,2),g.timesout); end end; end switch g.phsamp case 'on' PA = zeros(size(P,1),size(P,1),g.timesout); % NB: (freqs,freqs,times) end % phs amp wintime = 1000/g.srate*(g.winsize/2); % (1000/g.srate)*(g.winsize/2); times = [g.tlimits(1)+wintime:(g.tlimits(2)-g.tlimits(1)-2*wintime)/(g.timesout-1):g.tlimits(2)-wintime]; ERPtimes = [g.tlimits(1):(g.tlimits(2)-g.tlimits(1))/(g.frames-1):g.tlimits(2)+0.000001]; ERPindices = []; for ti=times [tmp indx] = min(abs(ERPtimes-ti)); ERPindices = [ERPindices indx]; end ERPtimes = ERPtimes(ERPindices); % subset of ERP frames on t/f window centers if ~isempty(find(times < g.baseline)) baseln = find(times < g.baseline); % subtract means of pre-0 (centered) windows else baseln = 1:length(times); % use all times as baseline end if ~isnan(g.alpha) & length(baseln)==0 myprintf(g.verbose,'timef(): no window centers in baseline (times<%g) - shorten (max) window length.\n', g.baseline) return elseif ~isnan(g.alpha) & g.baseboot myprintf(g.verbose,' %d bootstrap windows in baseline (center times < %g).\n',... length(baseln), g.baseline) end dispf = find(freqs <= g.maxfreq); stp = (g.frames-g.winsize)/(g.timesout-1); myprintf(g.verbose,'Computing Event-Related Spectral Perturbation (ERSP) and\n'); switch g.type case 'phasecoher', myprintf(g.verbose,' Inter-Trial Phase Coherence (ITC) images based on %d trials\n',length(X)/g.frames); case 'phasecoher2', myprintf(g.verbose,' Inter-Trial Phase Coherence 2 (ITC) images based on %d trials\n',length(X)/g.frames); case 'coher', myprintf(g.verbose,' Linear Inter-Trial Coherence (ITC) images based on %d trials\n',length(X)/g.frames); end; myprintf(g.verbose,' of %d frames sampled at %g Hz.\n',g.frames,g.srate); myprintf(g.verbose,'Each trial contains samples from %d ms before to\n',g.tlimits(1)); myprintf(g.verbose,' %.0f ms after the timelocking event.\n',g.tlimits(2)); myprintf(g.verbose,'The window size used is %d samples (%g ms) wide.\n',g.winsize,2*wintime); myprintf(g.verbose,'The window is applied %d times at an average step\n',g.timesout); myprintf(g.verbose,' size of %g samples (%g ms).\n',stp,1000*stp/g.srate); myprintf(g.verbose,'Results are oversampled %d times; the %d frequencies\n',g.padratio,length(dispf)); myprintf(g.verbose,' displayed are from %2.1f Hz to %3.1f Hz.\n',freqs(dispf(1)),freqs(dispf(end))); if ~isnan(g.alpha) myprintf(g.verbose,'Only significant values (bootstrap p<%g) will be colored;\n',g.alpha) myprintf(g.verbose,' non-significant values will be plotted in green\n'); end trials = length(X)/g.frames; baselength = length(baseln); myprintf(g.verbose,'\nOf %d trials total, processing trial:',trials); % detrend over epochs (trials) if requested % ----------------------------------------- switch g.detrep case 'on' X = reshape(X, g.frames, length(X)/g.frames); X = X - mean(X,2)*ones(1, length(X(:))/g.frames); X = X(:)'; end; for i=1:trials if (rem(i,100)==0) myprintf(g.verbose,'\n'); end if (rem(i,10) == 0) myprintf(g.verbose,'%d',i); elseif (rem(i,2) == 0) myprintf(g.verbose,'.'); end ERP = blockave(X,g.frames); % compute the ERP trial average Wn = zeros(1,g.timesout); for j=1:g.timesout, tmpX = X([1:g.winsize]+floor((j-1)*stp)+(i-1)*g.frames); % pull out data g.frames tmpX = tmpX - mean(tmpX); % remove the mean for that window switch g.detret, case 'on', tmpX = detrend(tmpX); end; if ~any(isnan(tmpX)) if (g.cycles == 0) % FFT if ~isempty(g.mtaper) % apply multitaper (no hanning window) tmpXMT = fft(g.alltapers .* ... (tmpX(:) * ones(1,size(g.alltapers,2))), g.pad); %tmpXMT = tmpXMT(nfk(1)+1:nfk(2),:); tmpXMT = tmpXMT(2:g.padratio*g.winsize/2+1,:); PP(:,j) = mean(abs(tmpXMT).^2, 2); % power; can also ponderate multitaper by their eigenvalues v tmpX = win .* tmpX(:); tmpX = fft(tmpX, g.pad); tmpX = tmpX(2:g.padratio*g.winsize/2+1); else % TF and MC (12/2006): Calculation changes made so that % power can be correctly calculated from ERSP. tmpX = win .* tmpX(:); tmpX = fft(tmpX,g.padratio*g.winsize); tmpX = tmpX / g.winsize; % TF and MC (12/11/2006): normalization, divide by g.winsize tmpX = tmpX(2:g.padratio*g.winsize/2+1); PP(:,j) = 2/0.375*abs(tmpX).^2; % power % TF and MC (12/14/2006): multiply by 2 account for negative frequencies, % Counteract the reduction by a factor 0.375 % that occurs as a result of cosine (Hann) tapering. Refer to Bug 446 end; else % wavelet if ~isempty(g.mtaper) % apply multitaper tmpXMT = g.alltapers .* (tmpX(:) * ones(1,size(g.alltapers,2))); tmpXMT = transpose(win) * tmpXMT; PP(:,j) = mean(abs(tmpXMT).^2, 2); % power tmpX = transpose(win) * tmpX(:); else tmpX = transpose(win) * tmpX(:); PP(:,j) = abs(tmpX).^2; % power end end if abs(tmpX) < eps % If less than smallest possible machine value % (i.e. if it's zero) then call it 0. RR(:,j) = zeros(size(RR(:,j))); else switch g.type case { 'coher' }, RR(:,j) = tmpX; cumulX(:,j) = cumulX(:,j)+abs(tmpX).^2; case { 'phasecoher2' }, RR(:,j) = tmpX; cumulX(:,j) = cumulX(:,j)+abs(tmpX); case 'phasecoher', RR(:,j) = tmpX ./ abs(tmpX); % normalized cross-spectral vector switch g.phsamp case 'on' cumulX(:,j) = cumulX(:,j)+abs(tmpX); % accumulate for PA end end; end Wn(j) = 1; end switch g.phsamp case 'on' % PA (freq x freq x time) PA(:,:,j) = PA(:,:,j) + (tmpX ./ abs(tmpX)) * ((PP(:,j)))'; % cross-product: unit phase (column) % times amplitude (row) end end % window if ~isnan(g.alpha) % save surrogate data for bootstrap analysis j = 1; goodbasewins = find(Wn==1); if g.baseboot % use baseline windows only goodbasewins = find(goodbasewins<=baselength); end ngdbasewins = length(goodbasewins); if ngdbasewins>1 while j <= g.naccu i=ceil(rand*ngdbasewins); i=goodbasewins(i); Pboot(:,j) = Pboot(:,j) + PP(:,i); Rboot(:,j) = Rboot(:,j) + RR(:,i); switch g.type case 'coher', cumulXboot(:,j) = cumulXboot(:,j)+abs(tmpX).^2; case 'phasecoher2', cumulXboot(:,j) = cumulXboot(:,j)+abs(tmpX); end; j = j+1; end Rbn = Rbn + 1; end end % bootstrap Wn = find(Wn>0); if length(Wn)>0 P(:,Wn) = P(:,Wn) + PP(:,Wn); % add non-NaN windows R(:,Wn) = R(:,Wn) + RR(:,Wn); Rn(Wn) = Rn(Wn) + ones(1,length(Wn)); % count number of addends end end % trial % if coherence, perform the division % ---------------------------------- switch g.type case 'coher', R = R ./ ( sqrt( trials*cumulX ) ); if ~isnan(g.alpha) Rboot = Rboot ./ ( sqrt( trials*cumulXboot ) ); end; case 'phasecoher2', R = R ./ ( cumulX ); if ~isnan(g.alpha) Rboot = Rboot ./ cumulXboot; end; case 'phasecoher', R = R ./ (ones(size(R,1),1)*Rn); end; switch g.phsamp case 'on' tmpcx(1,:,:) = cumulX; % allow ./ below for j=1:g.timesout PA(:,:,j) = PA(:,:,j) ./ repmat(PP(:,j)', [size(PP,1) 1]); end end if min(Rn) < 1 myprintf(g.verbose,'timef(): No valid timef estimates for windows %s of %d.\n',... int2str(find(Rn==0)),length(Rn)); Rn(find(Rn<1))==1; return end P = P ./ (ones(size(P,1),1) * Rn); if isnan(g.powbase) myprintf(g.verbose,'\nComputing the mean baseline spectrum\n'); mbase = mean(P(:,baseln),2)'; else myprintf(g.verbose,'Using the input baseline spectrum\n'); mbase = g.powbase; end if ~isnan( g.baseline ) & ~isnan( mbase ) P = 10 * (log10(P) - repmat(log10(mbase(1:size(P,1)))',[1 g.timesout])); % convert to (10log10) dB else P = 10 * log10(P); end; Rsign = sign(imag(R)); if nargout > 7 for lp = 1:size(R,1) Rphase(lp,:) = rem(angle(R(lp,:)),2*pi); % replaced obsolete phase() -sm 2/1/6 end Rphase(find(Rphase>pi)) = 2*pi-Rphase(find(Rphase>pi)); Rphase(find(Rphase<-pi)) = -2*pi-Rphase(find(Rphase<-pi)); end R = abs(R); % convert coherence vector to magnitude if ~isnan(g.alpha) % if bootstrap analysis included . . . if Rbn>0 i = round(g.naccu*g.alpha); if isnan(g.pboot) Pboot = Pboot / Rbn; % normalize if ~isnan( g.baseline ) Pboot = 10 * (log10(Pboot) - repmat(log10(mbase)',[1 g.naccu])); else Pboot = 10 * log10(Pboot); end; Pboot = sort(Pboot'); Pboot = [mean(Pboot(1:i,:)) ; mean(Pboot(g.naccu-i+1:g.naccu,:))]; else Pboot = g.pboot; end if isnan(g.rboot) Rboot = abs(Rboot) / Rbn; Rboot = sort(Rboot'); Rboot = mean(Rboot(g.naccu-i+1:g.naccu,:)); else Rboot = g.rboot; end else myprintf(g.verbose,'No valid bootstrap trials...!\n'); end 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 myprintf(g.verbose,'\nNow plotting...\n'); set(gcf,'DefaultAxesFontSize',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)]; end; switch lower(g.plotersp) case 'on' % %%%%%%% image the ERSP %%%%%%%%%%%%%%%%%%%%%%%%%% % h(1) = subplot('Position',[.1 ordinate1 .9 height].*s+q); PP = P; % PP will be ERSP power after if ~isnan(g.alpha) % zero out nonsignif. power differences PP(find((PP > repmat(Pboot(1,:)',[1 g.timesout])) ... & (PP < repmat(Pboot(2,:)',[1 g.timesout])))) = 0; end if ERSP_CAXIS_LIMIT == 0 ersp_caxis = [-1 1]*1.1*max(max(abs(P(dispf,:)))); else ersp_caxis = ERSP_CAXIS_LIMIT*[-1 1]; end if ~isnan( g.baseline ) imagesc(times,freqs(dispf),PP(dispf,:),ersp_caxis); else imagesc(times,freqs(dispf),PP(dispf,:)); end; set(gca,'ydir',g.hzdir); % make frequency ascend or descend if ~isempty(g.erspmax) caxis([-g.erspmax g.erspmax]); end; hold on plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); % plot time 0 if ~isnan(g.marktimes) % plot marked time for mt = g.marktimes(:)' plot([mt mt],[0 freqs(max(dispf))],'--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(dispf)) max(freqs(dispf))], '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 ')' ]) E = [min(P(dispf,:));max(P(dispf,:))]; h(4) = subplot('Position',[.1 ordinate1-0.1 .8 .1].*s+q); % plot marginal ERSP means % below the ERSP image plot(times,E,[0 0],... [min(E(1,:))-max(max(abs(E)))/3 max(E(2,:))+max(max(abs(E)))/3], ... '--m','LineWidth',g.linewidth) axis([min(times) max(times) ... min(E(1,:))-max(max(abs(E)))/3 max(E(2,:))+max(max(abs(E)))/3]) 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 ) E = 10 * log10(mbase(dispf)); h(5) = subplot('Position',[0 ordinate1 .1 height].*s+q); % plot mean spectrum % to left of ERSP image plot(freqs(dispf),E,'LineWidth',g.linewidth) if ~isnan(g.alpha) hold on; plot(freqs(dispf),Pboot(:,dispf)+[E;E],'g', 'LineWidth',g.linewidth); plot(freqs(dispf),Pboot(:,dispf)+[E;E],'k:','LineWidth',g.linewidth) end axis([freqs(1) freqs(max(dispf)) min(E)-max(abs(E))/3 max(E)+max(abs(E))/3]) tick = get(h(5),'YTick'); if (length(tick)>1) set(h(5),'YTick',[tick(1) ; tick(end-1)]) end set(h(5),'TickLength',[0.020 0.025]); set(h(5),'View',[90 90]) xlabel('Frequency (Hz)') ylabel( g.unitpower ) if strcmp(g.hzdir,'normal') freqdir = 'reverse'; else freqdir = 'normal'; end set(h(5),'xdir',freqdir); % make frequency ascend or descend end; switch lower(g.plotitc) case 'on' % %%%%%%%%%%%% Image the ITC %%%%%%%%%%%%%%%%%% % h(6) = subplot('Position',[.1 ordinate2 .9 height].*s+q); % ITC image RR = R; % RR is the masked ITC (R) if ~isnan(g.alpha) RR(find(RR < repmat(Rboot(1,:)',[1 g.timesout]))) = 0; end if ITC_CAXIS_LIMIT == 0 coh_caxis = min(max(max(R(dispf,:))),1)*[-1 1]; % 1 WAS 0.4 ! else coh_caxis = ITC_CAXIS_LIMIT*[-1 1]; end if exist('Rsign') & strcmp(g.plotphase, 'on') imagesc(times,freqs(dispf),Rsign(dispf,:).*RR(dispf,:),coh_caxis); % <--- else imagesc(times,freqs(dispf),RR(dispf,:),coh_caxis); % <--- end if ~isempty(g.itcmax) caxis([-g.itcmax g.itcmax]); end; tmpcaxis = caxis; set(gca,'ydir',g.hzdir); % make frequency ascend or descend hold on plot([0 0],[0 freqs(max(dispf))],'--m','LineWidth',g.linewidth); if ~isnan(g.marktimes) for mt = g.marktimes(:)' plot([mt mt],[0 freqs(max(dispf))],'--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(dispf)) max(freqs(dispf))], ... 'linewidth', 1, 'color', 'm'); end; end; h(7) = gca; h(8) = cbar('vert'); %h(9) = get(h(8),'Children'); set(h(7),'Position',[.1 ordinate2 .8 height].*s+q) set(h(8),'Position',[.95 ordinate2 .05 height].*s+q) set(h(8),'YLim',[0 tmpcaxis(2)]); title('ITC') % %%%%% plot the ERP below the ITC image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % E = mean(R(dispf,:)); ERPmax = max(ERP); ERPmin = min(ERP); ERPmax = ERPmax + 0.1*(ERPmax-ERPmin); ERPmin = ERPmin - 0.1*(ERPmax-ERPmin); h(10) = subplot('Position',[.1 ordinate2-0.1 .8 .1].*s+q); % ERP plot(ERPtimes,ERP(ERPindices),... [0 0],[ERPmin ERPmax],'--m','LineWidth',g.linewidth); hold on; plot([times(1) times(length(times))],[0 0], 'k'); axis([min(ERPtimes) max(ERPtimes) ERPmin ERPmax]); 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 = mean(R(dispf,:)'); h(11) = subplot('Position',[0 ordinate2 .1 height].*s+q); % plot the marginal mean % ITC left of the ITC image if ~isnan(g.alpha) plot(freqs(dispf),E,'LineWidth',g.linewidth); hold on; plot(freqs(dispf),Rboot(dispf),'g', 'LineWidth',g.linewidth); plot(freqs(dispf),Rboot(dispf),'k:','LineWidth',g.linewidth); axis([freqs(1) freqs(max(dispf)) 0 max([E Rboot(dispf)])+max(E)/3]) else plot(freqs(dispf),E,'LineWidth',g.linewidth) axis([freqs(1) freqs(max(dispf)) min(E)-max(E)/3 max(E)+max(E)/3]) end tick = get(h(11),'YTick'); set(h(11),'YTick',[tick(1) ; tick(length(tick))]) set(h(11),'View',[90 90]) set(h(11),'TickLength',[0.020 0.025]); xlabel('Frequency (Hz)') ylabel('ERP') if strcmp(g.hzdir,'normal') freqdir = 'reverse'; else freqdir = 'normal'; end set(gca,'xdir',freqdir); % make frequency ascend or descend % %%%%%%%%%%%%%%% plot a topoplot() %%%%%%%%%%%%%%%%%%%%%%% % if (~isempty(g.topovec)) h(12) = subplot('Position',[-.1 .43 .2 .14].*s+q); 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 end; % switch if g.plot try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if (length(g.title) > 0) 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',TITLE_FONT); end axcopy(gcf); end; % symmetric Hanning tapering 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 function myprintf(verbose, varargin) if strcmpi(verbose, 'on') fprintf(varargin{:}); end;
github
ZijingMao/baselineeegtest-master
rsadjust.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
newcrossf.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
crossf.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/timefreqfunc/crossf.m
59,309
utf_8
7d2f2a441e7b0fe30b888345f54f4a47
% 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(lower(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(lower(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
ZijingMao/baselineeegtest-master
dftfilt2.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
newtimef.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/timefreqfunc/newtimef.m
97,226
utf_8
0d13409bc327af6c60c24ec01c7f89a5
% 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} % epochlim = [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]} % srate = data sampling rate (Hz) {default: read from icadefs.m or 250} % 'cycles' = [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') 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]; g.speclim = [min(mbase)-max(abs(mbase))/3 max(mbase)+max(abs(mbase))/3]; % RMC: Just for plotting 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 set(h(1), 'tag', 'itc'); 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 % toby 10.02.2006 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
ZijingMao/baselineeegtest-master
rspdfsolv.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
dftfilt.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
rspfunc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
correct_mc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
pac.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
bootstat.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
timefreq.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
pac_cont.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
dftfilt3.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
rsget.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
rsfit.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
timewarp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
angtimewarp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/timefreqfunc/angtimewarp.m
4,506
utf_8
f97d91021b5c9c68983b7721b21206fb
% 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)) % $$$ keyboard; 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)); angdataw = zeros(1, max(newLatency)-min(newLatency)+1); k = 0; for i=1:length(angdataw) while i > ts(k+1) k = k+1; end % $$$ k = k-1; % $$$ keyboard; if k == 0 % Check wether i == ts(1) and i == 1 % In that case, M(1,1) = 1 % $$$ keyboard; % $$$ M(1,1) = 1; angdataw(1) = angdata(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)); %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 i == 13 % $$$ keyboard; %so we get a chance to check wether 0<theta2(3)<2pi % $$$ end 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
github
ZijingMao/baselineeegtest-master
shortread.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
scanfold.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
datlim.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
lapplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
compmap.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
topoimage.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
getallmenuseeglab.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
loglike.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
corrimage.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
dendhier.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
runicalowmem.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
eeg_time2prev.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
helpforexe.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
imagesclogy.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
gauss.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
runpca2.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
loc_subsets.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
pcexpand.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/miscfunc/pcexpand.m
2,210
utf_8
23a7b8149ced0eebf1a7428fbd14244f
% 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
ZijingMao/baselineeegtest-master
detectmalware.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
loadelec.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
erpregout.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
compdsp.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
perminv.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
runicatest.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
headmovie.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
arrow.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
runpca.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
dendplot.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
qrtimax.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
matcorr.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
seemovie.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
abspeak.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
eegplotgold.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
makehelpfiles.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
gauss2d.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
logimagesc.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
eucl.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
uniquef.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
getipsph.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
gauss3d.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
means.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
eegdrawg.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
averef.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
laplac2d.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
varsort.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
eegdraw.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
eegmovie.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
gabor2d.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
makehtml.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
ZijingMao/baselineeegtest-master
covary.m
.m
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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);