├── Readme.md ├── calculateSegmentSpectrum.m ├── cleanLineNoise.m ├── cleanline.m ├── cleanline_check.m ├── demofigs └── CleanLineDemo.png ├── eegplugin_cleanline.m ├── external ├── bcilab_partial.zip ├── bcilab_partial │ ├── arguments │ │ ├── arg.m │ │ ├── arg_define.m │ │ ├── arg_extract.m │ │ ├── arg_guidialog.m │ │ ├── arg_guidialog_ex.m │ │ ├── arg_guidialog_old.m │ │ ├── arg_guipanel.m │ │ ├── arg_issuereport.m │ │ ├── arg_nogui.m │ │ ├── arg_norep.m │ │ ├── arg_report.m │ │ ├── arg_setdirect.m │ │ ├── arg_specifier.m │ │ ├── arg_sub.m │ │ ├── arg_subswitch.m │ │ ├── arg_subtoggle.m │ │ ├── arg_tovals.m │ │ ├── arg_toworkspace.m │ │ ├── declare_properties.m │ │ ├── invoke_arg_internal.m │ │ └── parse_help.m │ ├── bcilab_demo_argsys.m │ ├── dependencies │ │ └── CStrAinBP-2009-09-13 │ │ │ ├── BCILAB.readme │ │ │ ├── CStrAinBP.c │ │ │ ├── CStrAinBP.cpp │ │ │ ├── build-Gracing.local │ │ │ ├── CStrAinBP.mexmaci │ │ │ ├── CStrAinBP.mexmaci.md5 │ │ │ └── env_add.m │ │ │ ├── build-Jordan │ │ │ ├── CStrAinBP.mexw64 │ │ │ ├── CStrAinBP.mexw64.md5 │ │ │ └── env_add.m │ │ │ ├── build-bluffing-vm │ │ │ ├── CStrAinBP.mexw32 │ │ │ ├── CStrAinBP.mexw32.md5 │ │ │ └── env_add.m │ │ │ ├── build-bluffing │ │ │ ├── CStrAinBP.mexa64 │ │ │ ├── CStrAinBP.mexa64.md5 │ │ │ └── env_add.m │ │ │ ├── build-client64-120.sdsc.edu │ │ │ ├── CStrAinBP.mexmaci64 │ │ │ ├── CStrAinBP.mexmaci64.md5 │ │ │ └── env_add.m │ │ │ ├── env_add.m │ │ │ ├── env_compile.m │ │ │ ├── fast_setdiff.m │ │ │ ├── license.txt │ │ │ └── temphull.mat │ ├── environment │ │ ├── env_handleerror.m │ │ ├── env_showmenu.m │ │ ├── env_startup.asv │ │ ├── env_startup.m │ │ └── env_translatepath.m │ ├── helpers │ │ ├── hlp_aggregatestructs.m │ │ ├── hlp_applyscaling.m │ │ ├── hlp_beginschedule.m │ │ ├── hlp_collect_datasets.m │ │ ├── hlp_config.m │ │ ├── hlp_cpuload.m │ │ ├── hlp_cryptohash.m │ │ ├── hlp_deserialize.m │ │ ├── hlp_endschedule.m │ │ ├── hlp_findscaling.m │ │ ├── hlp_fingerprint.m │ │ ├── hlp_flattensearch.m │ │ ├── hlp_gcc_version.m │ │ ├── hlp_getcaller.m │ │ ├── hlp_getresult.m │ │ ├── hlp_handleerror.m │ │ ├── hlp_homedir.m │ │ ├── hlp_hostip.m │ │ ├── hlp_hostname.m │ │ ├── hlp_inoutargs.m │ │ ├── hlp_iscaller.m │ │ ├── hlp_lookup_symbol.m │ │ ├── hlp_makefunction.m │ │ ├── hlp_matlab_version.m │ │ ├── hlp_memavail.m │ │ ├── hlp_memfree.m │ │ ├── hlp_microcache.m │ │ ├── hlp_reschedule_policy.m │ │ ├── hlp_resolve.m │ │ ├── hlp_resolveall.m │ │ ├── hlp_rewrite.m │ │ ├── hlp_schedule.m │ │ ├── hlp_scope.m │ │ ├── hlp_serialize.m │ │ ├── hlp_sort_namevalues.m │ │ ├── hlp_split.m │ │ ├── hlp_struct2varargin.m │ │ ├── hlp_superimposedata.m │ │ ├── hlp_tostring.m │ │ ├── hlp_trycompile.m │ │ ├── hlp_varargin2struct.m │ │ ├── hlp_worker.m │ │ ├── hlp_wrapresults.m │ │ └── private │ │ │ └── dialogs_disabled │ │ │ ├── errordlg.m │ │ │ ├── errordlg2.m │ │ │ ├── inputdlg.m │ │ │ ├── inputdlg2.m │ │ │ ├── inputgui.m │ │ │ ├── questdlg.m │ │ │ └── questdlg2.m │ ├── keywords │ │ ├── Blank.m │ │ ├── Condition.m │ │ ├── Evaluate.m │ │ ├── Hold.m │ │ ├── Lambda.m │ │ ├── Pattern.m │ │ ├── Rule.m │ │ ├── Set.m │ │ ├── SetDelayed.m │ │ ├── Symbol.m │ │ ├── mandatory.m │ │ ├── search.m │ │ └── unassigned.m │ ├── para_dataflow.m │ └── queries │ │ ├── check_1d_distributed.m │ │ ├── check_discrete.m │ │ ├── get_function_symbol.m │ │ ├── has_canonical_representation.m │ │ ├── has_function_symbol.m │ │ ├── is_1d_distributed.m │ │ ├── is_1d_regression.m │ │ ├── is_Nd_distributed.m │ │ ├── is_Nd_regression.m │ │ ├── is_atom.m │ │ ├── is_builtin_function.m │ │ ├── is_custom_distributed.m │ │ ├── is_dataset.m │ │ ├── is_discrete.m │ │ ├── is_distributed.m │ │ ├── is_evaluated.m │ │ ├── is_gaussian.m │ │ ├── is_impure_expression.m │ │ ├── is_needing_search.m │ │ ├── is_point.m │ │ ├── is_pure_expression.m │ │ ├── is_raw_dataset.m │ │ ├── is_search.m │ │ ├── is_stateful.m │ │ ├── is_structured.m │ │ ├── is_symbol.m │ │ ├── is_symbolic_lambda.m │ │ └── is_undefined_function.m ├── chronux_2_modified │ ├── License.txt │ └── spectral_analysis │ │ ├── continuous │ │ ├── CrossSpecMatc.m │ │ ├── chron_findpeaks.m │ │ ├── coherencyc.m │ │ ├── coherencyc_unequal_length_trials.m │ │ ├── coherencysegc.m │ │ ├── cohgramc.m │ │ ├── cohmatrixc.m │ │ ├── createdatamatc.m │ │ ├── evoked.m │ │ ├── extractdatac.m │ │ ├── fitlinesc.m │ │ ├── ftestc.m │ │ ├── ftestmovingwinc.m │ │ ├── locdetrend.m │ │ ├── locsmooth.m │ │ ├── mtdspecgramc.m │ │ ├── mtdspectrumc.m │ │ ├── mtfftc.m │ │ ├── mtpowerandfstatc.m │ │ ├── mtspecgramc.m │ │ ├── mtspecgramtrigc.m │ │ ├── mtspectrum_of_spectrumc.m │ │ ├── mtspectrumc.m │ │ ├── mtspectrumc_unequal_length_trials.m │ │ ├── mtspectrumsegc.m │ │ ├── mtspectrumtrigc.m │ │ ├── nonst_stat.m │ │ ├── quadcof.m │ │ ├── quadinv.m │ │ ├── rmlinesc.m │ │ ├── rmlinesmovingwinc.m │ │ ├── runline.m │ │ └── spsvd.m │ │ └── helper │ │ ├── change_row_to_column.m │ │ ├── check_consistency.m │ │ ├── coherr.m │ │ ├── cohmathelper.m │ │ ├── den_jack.m │ │ ├── dpsschk.m │ │ ├── getfgrid.m │ │ ├── getparams.m │ │ ├── jackknife.m │ │ └── specerr.m └── shadowplot │ ├── license.txt │ └── shadowplot.m ├── fitSignificantFrequencies.m ├── getStructureParameters.m ├── license.txt ├── pop_cleanline.m ├── private ├── checkTapers.m ├── design_fir.m ├── filter_fast.m ├── filtfilt_fast.m ├── hlp_microcache.m └── spherical_interpolate.m ├── removeLinesMovingWindow.m ├── testSignificantFrequencies.m └── utils └── hlp_vrect.m /calculateSegmentSpectrum.m: -------------------------------------------------------------------------------- 1 | function [S, f] = calculateSegmentSpectrum(data, lineNoise) 2 | % Multi-taper segmented spectrum for a univariate continuous process 3 | % 4 | % Usage: 5 | % [S, f] = calculateSegmentSpectrum(data, lineNoise) 6 | % 7 | % Parameters: 8 | % data (single channel) -- required 9 | % lineNoise structure with various parameters set 10 | % 11 | % The lineNoise structure has the following fields set: 12 | % fPassBand Frequency band used 13 | % Fs Sampling frequency 14 | % pad FFT padding factor 15 | % tapers Precomputed tapers from dpss 16 | % taperWindowSize Taper sliding window length 17 | % 18 | % Output: 19 | % S Spectrum 20 | % f Frequencies 21 | % 22 | 23 | %% Check input arguments for consistency 24 | if nargin < 2 25 | error('calculateSegmentSpectrum:NotEnoughArguments', ... 26 | 'Need to provide data and segment information arguments'); 27 | end 28 | 29 | data = change_row_to_column(data); 30 | if size(data, 2) ~= 1; 31 | error('calculateSegmentSpectrum:DataNot1Dim', ... 32 | 'Data must beunivariate time series'); 33 | end 34 | %% Extract argument values 35 | win = getStructureParameters(lineNoise, 'taperWindowSize', 4); 36 | Fs = getStructureParameters(lineNoise, 'Fs', 1); 37 | pad = getStructureParameters(lineNoise, 'pad', 0); 38 | fpass = getStructureParameters(lineNoise, 'fPassBand', [0 lineNoise.Fs/2]); 39 | 40 | %% Create the segmented data for the calculation of the spectrum 41 | N = size(data, 1); % length of segmented data 42 | dt = 1/Fs; % sampling interval 43 | T = N*dt; % length of data in seconds 44 | E = 0:win:(T - win); % fictitious event triggers 45 | win = [0, win]; % use window length to define left and right limits of windows around triggers 46 | data = createdatamatc(data, E, Fs, win); % segmented data 47 | N = size(data,1); % length of segmented data 48 | nfft = max(2^(nextpow2(N) + pad), N); 49 | [f, findx] = getfgrid(Fs, nfft, fpass); 50 | tapers = lineNoise.tapers; 51 | J = mtfftc(data, tapers, nfft, Fs); % compute tapered fourier transforms 52 | J = J(findx, :, :); % restrict to specified frequencies 53 | S = squeeze(mean(conj(J).*J, 2)); % spectra of non-overlapping segments (average over tapers) 54 | S = squeeze(mean(S, 2)); % Mean of the spectrum averaged across segments 55 | -------------------------------------------------------------------------------- /cleanLineNoise.m: -------------------------------------------------------------------------------- 1 | function [signal, lineNoiseOut] = cleanLineNoise(signal, lineNoiseIn) 2 | % Remove sharp spectral peaks from signal using Sleppian filters 3 | % 4 | % Usage: 5 | % signal = cleanLineNoise(signal) 6 | % [signal, lineNoiseOut] = hcleanLineNoise(signal, lineNoiseIn) 7 | % 8 | % Parameters: 9 | % signal Structure with .data and .srate fields 10 | % lineNoiseIn Input structure with fields described below 11 | % 12 | % Structure parameters (lineNoiseIn): 13 | % fPassBand Frequency band used (default [0, Fs/2] = entire band) 14 | % Fs Sampling frequency 15 | % fScanBandWidth +/- bandwidth centered on each f0 to scan for significant 16 | % lines (TM) 17 | % lineFrequencies Line frequencies to be removed (default 18 | % [60, 120, 180, 240, 300]) 19 | % lineNoiseChannels Channels to remove line noise from (default 20 | % size(data, 1)) 21 | % maximumIterations Maximum times to iterate removal (default = 10) 22 | % p Significance level cutoff (default = 0.01) 23 | % pad FFT padding factor ( -1 corresponds to no padding, 24 | % 0 corresponds to padding to next highest power of 2 25 | % etc.) (default is 0) 26 | % pnts 27 | % tapers Precomputed tapers from dpss 28 | % taperBandWidth Taper bandwidth (default 2 Hz) 29 | % taperWindowSize Taper sliding window length (default 4 sec) 30 | % taperWindowStep Sliding window step size (default 4 sec = no overlap) 31 | % tau Window overlap smoothing factor (default 100) 32 | % 33 | % This function is based on code originally written by Tim Mullen in a 34 | % package called tmullen-cleanline which is based on the chronux_2 35 | % libraries. 36 | % 37 | 38 | lineNoiseOut = lineNoiseIn; 39 | %% Remove line frequencies that are greater than Nyquist frequencies 40 | tooLarge = lineNoiseOut.lineFrequencies >= lineNoiseOut.Fs/2; 41 | if any(tooLarge) 42 | warning('cleanLineNoise:LineFrequenciesTooLarge', ... 43 | 'Eliminating frequencies greater than half the sampling rate'); 44 | lineNoiseOut.lineFrequencies(tooLarge) = []; 45 | lineNoiseOut.lineFrequencies = squeeze(lineNoiseOut.lineFrequencies); 46 | end 47 | 48 | %% Set up multi-taper parameters 49 | hbw = lineNoiseOut.taperBandWidth/2; % half-bandwidth 50 | lineNoiseOut.taperTemplate = [hbw, lineNoiseOut.taperWindowSize, 1]; 51 | Nwin = round(lineNoiseOut.Fs*lineNoiseOut.taperWindowSize); % number of samples in window 52 | lineNoiseOut.tapers = checkTapers(lineNoiseOut.taperTemplate, Nwin, lineNoiseOut.Fs); 53 | 54 | %% Perform the calculation for each channel separately 55 | data = double(signal.data); 56 | chans = sort(lineNoiseOut.lineNoiseChannels); 57 | parfor ch = chans 58 | data(ch, :) = removeLinesMovingWindow(squeeze(data(ch, :)), lineNoiseOut); 59 | end 60 | signal.data = data; 61 | clear data; 62 | 63 | -------------------------------------------------------------------------------- /cleanline_check.m: -------------------------------------------------------------------------------- 1 | function [EEG, Sorig, Sclean, f, amps, freqs, g] = cleanline_check(varargin) 2 | % CLEANLINE_CHECK confirms CLEANLINE input parameters without actually 3 | % running the function. 4 | % Reason for a sseprate function is the incompatibility of two backend 5 | % fucntions, one for handling the inptu arguments (ARG_GUIDIALOG) and the 6 | % other for running fucntions EEG structure arrays (EEG_EVAL). 7 | % 8 | % Seyed Yahya Shirazi, 7/2024, SCCN, INC, UCSD 9 | 10 | EEG = arg_extract(varargin,'EEG',[],[]); 11 | 12 | if isempty(EEG) 13 | EEG = eeg_emptyset; 14 | end 15 | 16 | if ~isempty(EEG.icawinv); 17 | defSigType = {'Components','Channels'}; 18 | else 19 | defSigType = {'Channels'}; 20 | end 21 | 22 | g = arg_define([0 1], varargin, ... 23 | arg_norep('EEG',mandatory), ... 24 | arg({'linefreqs','LineFrequencies'}, 60, [],'Line noise frequencies to remove.'),... 25 | arg({'scanforlines','ScanForLines'},false,[],'Scan for line noise. This will scan for the exact line frequency in a narrow range around the specified LineFrequencies'),... 26 | arg({'p','LineAlpha','alpha'},0.01,[0 1],'p-value for detection of significant sinusoid'), ... 27 | arg({'bandwidth','Bandwidth'},2,[],'Bandwidth (Hz). This is the width of a spectral peak for a sinusoid at fixed frequency. As such, this defines the multi-taper frequency resolution.'), ... 28 | arg({'sigtype','SignalType','chantype'},defSigType{1},defSigType,'Type of signal to clean. Cleaned ICA components will be backprojected to channels. If channels are cleaned, ICA activations are reconstructed based on clean channels.'), ... 29 | arg({'chanlist','ChanCompIndices','ChanComps'},sprintf('1:%d',EEG.nbchan),[1 EEG.nbchan],'Indices of Channels/Components to clean.','type','expression'),... 30 | arg({'taperbandwidth','TaperBandWidth'},2,[0 Inf],'Taper bandwidth'), ... 31 | arg({'winsize','SlidingWinLength'},fastif(EEG.trials==1,4,EEG.pnts/EEG.srate),[0 EEG.pnts/EEG.srate],'Sliding window length (sec). Default for epoched data is the epoch length. Default for continuous data is 4 seconds'), ... 32 | arg({'winstep','SlidingWinStep'},fastif(EEG.trials==1,1,EEG.pnts/EEG.srate),[0 EEG.pnts/EEG.srate],'Sliding window step size (sec). This determines the amount of overlap between sliding windows. Default for epoched data is window length (no overlap). Default for continuous data is 1 second.'), ... 33 | arg({'tau','SmoothingFactor'},100,[1 Inf],'Window overlap smoothing factor. A value of 1 means (nearly) linear smoothing between adjacent sliding windows. A value of Inf means no smoothing. Intermediate values produce sigmoidal smoothing between adjacent windows.'), ... 34 | arg({'pad','PaddingFactor'},2,[-1 Inf],'FFT padding factor. Signal will be zero-padded to the desired power of two greater than the sliding window length. The formula is NFFT = 2^nextpow2(SlidingWinLen*(PadFactor+1)). e.g. For N = 500, if PadFactor = -1, we do not pad; if PadFactor = 0, we pad the FFT to 512 points, if PadFactor=1, we pad to 1024 points etc.'), ... 35 | arg({'computepower','ComputeSpectralPower'},true,[],'Visualize Original and Cleaned Spectra. Original and clean spectral power will be computed and visualized at end'), ... 36 | arg({'normSpectrum','NormalizeSpectrum'},false,[],'Normalize log spectrum by detrending. Not generally recommended.'), ... 37 | arg({'verb','VerboseOutput','VerbosityLevel'},true,[],'Produce verbose output.'), ... 38 | arg({'plotfigures','PlotFigures'},false,[],'Plot Individual Figures. This will generate figures of F-statistic, spectrum, etc for each channel/comp while processing'), ... 39 | arg({'newversion','Newversion'},false,[],'Use new implementation (send us feedback)') ... 40 | ); -------------------------------------------------------------------------------- /demofigs/CleanLineDemo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/demofigs/CleanLineDemo.png -------------------------------------------------------------------------------- /eegplugin_cleanline.m: -------------------------------------------------------------------------------- 1 | % eegplugin_cleanline() - EEGLAB plugin for removing line noise 2 | % 3 | % Usage: 4 | % >> eegplugin_cleanline(fig, trystrs, catchstrs); 5 | % 6 | % Inputs: 7 | % fig - [integer] EEGLAB figure 8 | % trystrs - [struct] "try" strings for menu callbacks. 9 | % catchstrs - [struct] "catch" strings for menu callbacks. 10 | % 11 | % Notes: 12 | % This plugins consist of the following Matlab files: 13 | % 14 | % Create a plugin: 15 | % For more information on how to create an EEGLAB plugin see the 16 | % help message of eegplugin_besa() or visit http://www.sccn.ucsd.edu/eeglab/contrib.html 17 | % 18 | % 19 | % See also: pop_cleanline(), cleanline() 20 | 21 | % Copyright (C) 2011 Tim Mullen, SCCN/INC/UCSD 22 | % 23 | % This program is free software; you can redistribute it and/or modify 24 | % it under the terms of the GNU General Public License as published by 25 | % the Free Software Foundation; either version 2 of the License, or 26 | % (at your option) any later version. 27 | % 28 | % This program is distributed in the hope that it will be useful, 29 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 30 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 31 | % GNU General Public License for more details. 32 | % 33 | % You should have received a copy of the GNU General Public License 34 | % along with this program; if not, write to the Free Software 35 | % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 36 | 37 | function vers = eegplugin_cleanline(fig, trystrs, catchstrs) 38 | 39 | vers = 'cleanline2.1'; 40 | if nargin < 3 41 | error('eegplugin_cleanline requires 3 arguments'); 42 | end; 43 | 44 | % add folder to path 45 | % ------------------ 46 | if exist('cleanline', 'file') 47 | p = which('eegplugin_cleanline.m'); 48 | p = p(1:findstr(p,'eegplugin_cleanline.m')-1); 49 | addpath(genpath(p)); 50 | end; 51 | 52 | % find import data menu 53 | % --------------------- 54 | menu = findobj(fig, 'tag', 'tools'); 55 | 56 | % menu callbacks 57 | % -------------- 58 | comcnt = [ trystrs.no_check '[EEG LASTCOM] = pop_cleanline(EEG);' catchstrs.new_and_hist ]; 59 | 60 | % create menus 61 | % ------------ 62 | uimenu( menu, 'label', 'CleanLine', 'callback', comcnt,'separator', 'on', 'position',length(get(menu,'children'))+1); 63 | -------------------------------------------------------------------------------- /external/bcilab_partial.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial.zip -------------------------------------------------------------------------------- /external/bcilab_partial/arguments/arg_extract.m: -------------------------------------------------------------------------------- 1 | function x = arg_extract(args,names,position,default) 2 | % Extract arguments from Args; simple version, see notes. 3 | % Value = arg_extract(Args,Names,Position,Default) 4 | % 5 | % In: 6 | % Args : the varargin of the calling function 7 | % 8 | % Names : name by which the argument is referenced, or a cell array of names 9 | % 10 | % Position: the 1-based position of the argument, if it can be listed positionally, or [] 11 | % if not (default: []) 12 | % 13 | % Default : optional default value, if the argument was not given 14 | % (can only be specified if position is [], see notes) 15 | % 16 | % Out: 17 | % Value : The extracted value 18 | % 19 | % Notes: 20 | % This version of arg_extract assumes that the argument of interest, if it can be specified 21 | % positionally, must be contained in Args (i.e., either by name, or by position). To enforce this, 22 | % no Default can be assigned if the listed Position is non-empty. 23 | % 24 | % The second limitation is on the allowed values of all arguments in Args: No struct-typed 25 | % argument may contain any of the Names as a valid field name, and no string-typed argument may 26 | % allow any of the Names as its value; otherwise, these fields may be accidentally picked out by 27 | % arg_extract. 28 | % 29 | % Examples: 30 | % % extract the ALLEEG argument (by name or position) 31 | % x = arg_extract(varargin,'ALLEEG',1) ; 32 | % 33 | % % extract the sampling rate argument (by name, give an error if missing) 34 | % x = arg_extract(varargin,{'srate','SamplingRate'}); 35 | % 36 | % % extract the sapling rate argument (by name, and fall back to some default if missing) 37 | % x = arg_extract(varargin,{'srate','SamplingRate'},[],200); 38 | % 39 | % See also: 40 | % arg_define 41 | % 42 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 43 | % 2010-09-24 44 | 45 | if ~iscell(names) 46 | names = {names}; end 47 | if ~iscell(args) 48 | error('Args must be given as a cell array...'); end 49 | 50 | % collect the indices where the argument can appear in the Args 51 | indices = cellfun('isclass',args,'struct'); 52 | for n = 1:length(names) 53 | indices = indices | strcmp(args,names{n}); end 54 | indices = find(indices); 55 | 56 | % search the argument by name 57 | for k = indices(end:-1:1) 58 | if ischar(args{k}) && k 1 19 | for k=1:numel(X) 20 | X(k) = arg_setdirect(X(k),value); end 21 | else 22 | for fn=fieldnames(X)' 23 | X.(fn{1}) = arg_setdirect(X.(fn{1}),value); 24 | if strcmp(fn{1},'arg_direct') 25 | X.(fn{1}) = value; end 26 | end 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /external/bcilab_partial/arguments/arg_specifier.m: -------------------------------------------------------------------------------- 1 | function spec = arg_specifier(varargin) 2 | % Internal: create a base specifier struct for an argument. 3 | % Specifier = arg_specifier(Overrides...) 4 | % 5 | % In: 6 | % Overrides... : name-value pairs of fields that should be overridden 7 | % 8 | % Out: 9 | % A specifier that is recognized by arg_define. 10 | % 11 | % See also: 12 | % arg_define 13 | % 14 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 15 | % 2010-09-25 16 | 17 | spec = struct(... 18 | ... % core properties 19 | 'head',{@arg_specifier},...% the expression type that generated this specifier (@arg, @arg_sub, ...) 20 | 'names',{{}}, ... % cell array of argument names; first is the "code" name (reported to the function), second (if present) is the human-readable name (reported to the GUI) 21 | 'value',{[]}, ... % the assigned value of the argument; can be any data structure 22 | 'assigner',{@assign},...% function to be invoked in order to assign a new value the specifier 23 | ... % properties for (possibly dependent) child arguments 24 | 'children',{{}}, ... % cell array of child arguments (returned to the function in a struct, and made available to the GUI in a subgroup) 25 | 'mapper',@(x)x, ... % mapping function: maps a value into the index space of alternatives (possibly via range) 26 | 'alternatives',{{}}, ...% cell array of alternative children structures; only used for arg_subtoggle, arg_subswitch 27 | 'merge',{true},... % whether the value (a cell array of arguments) should completely replace the default, or be merged with it, such that sub-arguments are only selectively overridden 28 | ... % type-related properties 29 | 'range',{[]}, ... % the allowed range of the argument (for type checking in GUI and elsewhere); can be [], [lo hi], {'option1','option2','option3',...} 30 | 'type',{[]}, ... % the type of the argument: string, only touches the type-checking system & GUI 31 | 'shape',{[]}, ... % the shape of the argument: empty. scalar, row, column, matrix 32 | ... % user interface properties 33 | 'help',{''}, ... % the help text / description for the argument 34 | 'cat',{''}, ... % the human-readable category of the argument 35 | ... % misc attributes 36 | 'to_double',{true}, ... % convert numeric values to double before returning them to the function 37 | 'reportable',{true},... % whether the argument can be reported to outer function (given that it is assigned), or not (true/false) 38 | 'displayable',{true}... % whether the argument may be displayed by GUIs (true/false) 39 | ); 40 | 41 | % selectively override fields 42 | for k=1:2:length(varargin) 43 | spec.(varargin{k}) = varargin{k+1}; end 44 | 45 | function spec = assign(spec,value) 46 | spec.value = value; 47 | -------------------------------------------------------------------------------- /external/bcilab_partial/arguments/arg_tovals.m: -------------------------------------------------------------------------------- 1 | function res = arg_tovals(spec,direct) 2 | % Convert a 'rich' argument report into a 'vals' report. 3 | % Vals = arg_tovals(Rich) 4 | % 5 | % In: 6 | % Rich : a 'rich' argument report, as obtained via arg_report('rich',some_function) 7 | % 8 | % Direct : whether to endow the result with an 'arg_direct' flag set to true, which indicates to 9 | % the function taking the Vals struct that the contents of the struct directly correspond 10 | % to workspace variables of the function. If enabled, contents of Vals must be changed 11 | % with care - for example, removing/renaming fields will likely lead to errors in the 12 | % function. (default: true) 13 | % 14 | % Out: 15 | % Vals : a 'vals' argument report, as obtained via arg_report('vals',some_function) this data 16 | % structure can be used as a valid argument to some_function. 17 | % 18 | % Examples: 19 | % % report arguments of myfunction 20 | % report = arg_report('rich',@myfunction) 21 | % % convert the report to a valid argument to the function 22 | % values = arg_tovals(report); 23 | % 24 | % See also: 25 | % arg_define 26 | % 27 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 28 | % 2010-10-18 29 | 30 | if ~exist('direct','var') 31 | direct = false; end 32 | 33 | % remove unassigned specifiers 34 | spec = spec(~strcmp(unassigned,{spec.value})); 35 | % evaluate expressions 36 | expressions = strcmp('expression',{spec.type}) & cellfun('isclass',{spec.value},'char'); 37 | if any(expressions) 38 | try 39 | [spec(expressions).value] = dealout(evalin('base',format_cellstr({spec(expressions).value}))); 40 | catch 41 | for e=find(expressions) 42 | try 43 | spec(e).value = evalin('base',spec(e).value); 44 | catch 45 | end 46 | end 47 | end 48 | end 49 | % and replace by structs 50 | res = struct('arg_direct',{direct}); 51 | for k=1:length(spec) 52 | if isstruct(spec(k).children) 53 | % has children: replace by struct 54 | val = arg_tovals(spec(k).children,direct); 55 | else 56 | % no children: take value (and possibly convert to double) 57 | val = spec(k).value; 58 | if spec(k).to_double && isinteger(val) 59 | val = double(val); end 60 | end 61 | % and assign the value 62 | res.(spec(k).names{1}) = val; 63 | end 64 | res.arg_direct = direct; 65 | 66 | 67 | % like deal(), except that the inputs are given as a cell array instead of a comma-separated list 68 | function varargout = dealout(argin) 69 | varargout = argin; 70 | 71 | 72 | % format a non-empty cell-string array into a string 73 | function x = format_cellstr(x) 74 | x = ['{' sprintf('%s, ',x{1:end-1}) x{end} '}']; -------------------------------------------------------------------------------- /external/bcilab_partial/arguments/arg_toworkspace.m: -------------------------------------------------------------------------------- 1 | function arg_toworkspace(args) 2 | % Copy the arguments in the given Struct into the workspace of the calling function. 3 | % arg_toworkspace(Struct) 4 | % 5 | % In: 6 | % Struct : an argument structure, as produced by arg_define 7 | % 8 | % Examples: 9 | % function myfunction(varargin) 10 | % opts = arg_define(varargin, ... 11 | % arg(...), ... 12 | % arg(...)); 13 | % 14 | % arg_toworkspace(opts); 15 | % 16 | % See also: 17 | % arg_define 18 | % 19 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 20 | % 2010-09-24 21 | 22 | % place the variables in the caller's workspace 23 | for fn=fieldnames(args)' 24 | assignin('caller',fn{1},args.(fn{1})); end 25 | -------------------------------------------------------------------------------- /external/bcilab_partial/arguments/parse_help.m: -------------------------------------------------------------------------------- 1 | function help = parse_help(help,summary_len) 2 | % helper function for the arg* specifiers, to parse the help into a first and second part. 3 | % Help = parse_help(Help,SummaryLength) 4 | % 5 | % In: 6 | % Help: some help specification (as it appears in the arg* functions 7 | % 8 | % SummaryLength : the maximum length for the executive summary portion 9 | % 10 | % Out: 11 | % Help: a cell array of {executive summary, description} 12 | % 13 | % See also: 14 | % arg_define 15 | % 16 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 17 | % 2010-09-24 18 | 19 | if ~exist('summary_len','var') 20 | summary_len = 60; end 21 | 22 | if ischar(help) 23 | % string: split at the end of the first sentence and put into a cell array 24 | [a,b] = regexp(help,'\.\s+[A-Z]','once'); 25 | if ~isempty(a) 26 | help = {help(1:a-1), help(b-1:end)}; 27 | else 28 | help = {help}; 29 | end 30 | elseif ~iscellstr(help) 31 | error('The help text must be a string.'); 32 | end 33 | 34 | % remove trailing dot 35 | if length(help{1}) > 1 && help{1}(end) == '.' 36 | help{1} = help{1}(1:end-1); end 37 | 38 | % check for length limit 39 | if length(help{1}) > summary_len 40 | % Note: The first sentence in the description is used in some GUIs which have a size limit; 41 | % to prevent text from being cut off, please use a shorter wording in the first sentence. 42 | % 43 | % Also note that if this sentence is not followed by a capital letter, the remaining part 44 | % is not considered separate. 45 | error(['The executive summary for the given argument is too long (' help{1} ')']); 46 | end 47 | -------------------------------------------------------------------------------- /external/bcilab_partial/bcilab_demo_argsys.m: -------------------------------------------------------------------------------- 1 | % turn off advanced expression facilities and load a dataset 2 | exp_eval(Set(@disable_expressions,1)) 3 | eeg = io_loadset('data:/christian/Demo/imag.vhdr'); 4 | 5 | 6 | % run a filter on some data with some arguments using positional syntax (rest using defaults) 7 | eeg = flt_fir(eeg, [], [5 10 25 30], 'bandpass'); 8 | % run a filter on some data with name-value pair syntax, leaving out a few parameters 9 | eeg = flt_fir('signal',eeg, 'fspec',[5 10 25 30], 'fmode','bandpass', 'ftype','minimum-phase'); 10 | % run a filter on some data with name-value pair syntax, but using alternative (long) property names 11 | eeg = flt_fir('signal',eeg, 'Frequencies',[5 10 25 30], 'Mode','bandpass', 'Type','minimum-phase'); 12 | % run a filter on some data with name-value pair syntax, and using a struct for good measure 13 | eeg = flt_fir('signal',eeg, 'Frequencies',[5 10 25 30], struct('Mode','bandpass', 'Type','minimum-phase'), 'passripple',-20,'stopripple',-30); 14 | 15 | % edit parameters for flt_fir, starting with some parameters 16 | x=arg_guidialog(@flt_fir,'params',{'fspec',[5 10 25 30]}) 17 | % run the filter on some data using edited parameters, using the name-value-pair/struct syntax 18 | % (any name-value pair may be replaced by a struct unambiguously) 19 | eeg = flt_fir('signal',eeg,x); 20 | % run the filter on some data using edited parameters x, but with overridden filter type 21 | eeg = flt_fir('signal',eeg,x,'ftype','zero-phase'); 22 | 23 | 24 | % edit subset of flt_ica arguments for its default config 25 | x=arg_guidialog(@flt_ica,'subset',{'variant.max_iter','variant.scheduler',[],'variant.pdftype','variant.num_models'}) 26 | 27 | % edit all ICA arguments for a particular config 28 | x=arg_guidialog(@flt_ica,'params',{'variant','infomax', 'clean',{'strong', 'windows',{'window_len',200}}}) 29 | 30 | % edit all ICA arguments for the default config... 31 | x=arg_guidialog(@flt_ica) 32 | 33 | % show an editable panel for ICA arguments (note that, e.g., the variant is switchable) 34 | % the relative geometry has not been refined yet 35 | h = arg_guipanel('Function',@flt_ica); 36 | uiwait(gcf); 37 | x = arg_tovals(h.GetPropertySpecification()) 38 | 39 | 40 | % show an editable panel for a simple BCI paradigm (note that many filters can be enabled and configured) 41 | h = arg_guipanel('Function',@para_csp) 42 | 43 | % show an editable panel for a particular variant of a BCI paradigm 44 | h = arg_guipanel('Function',@para_speccsp,'Parameters',{'flt', {'iir',[7 30]}, 'ml',{'learner',{'svmperf','Loss','ROC'}}}) 45 | 46 | % show an editable panel for a custom paradigm (try replacing the learner by hkl (hierarchical kernel learning) 47 | h = arg_guipanel('Function',@para_multimodel) 48 | 49 | 50 | % obtain partially overridden defaults for some function (note the 51 | x = arg_report('vals',@ml_trainhkl,{'loss','squared', 'display',1}) 52 | 53 | 54 | 55 | % side feature: obtain the defaults set for a function 56 | % here one that has uncertain values for its hyper-parameters (here: cost & g) 57 | x = arg_report('vals',@ml_trainsvmlight) 58 | % form the cartesian product over parameter search ranges for these arguments, yielding a set of argument combinations to the function over which to search... 59 | % (done automatically by the machine learning tools) 60 | x = hlp_flattensearch(x) 61 | x.parts{50} 62 | 63 | 64 | % test 65 | h = arg_guipanel('Function',@set_inject_events); 66 | uiwait(gcf); 67 | x = arg_tovals(h.GetPropertySpecification());x.segment 68 | 69 | -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/BCILAB.readme: -------------------------------------------------------------------------------- 1 | This fast setdiff implementation is important for the speed of certain BCILAB infrastructure functions (namely the arg system). 2 | 3 | If you get a warning that the regular setdiff() is used as a fallback, please try to recompile the file for your architecture and put it in a subfolder (together with 4 | a copy of an env_add.m file from the other platform directories -- do not copy the env_add.m file from the directory in which this readme file is located). 5 | -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-Gracing.local/CStrAinBP.mexmaci: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-Gracing.local/CStrAinBP.mexmaci -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-Gracing.local/CStrAinBP.mexmaci.md5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-Gracing.local/CStrAinBP.mexmaci.md5 -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-Gracing.local/env_add.m: -------------------------------------------------------------------------------- 1 | any(cellfun(@exist,{'CStrAinBP', 'CStrAinBP'})==3) -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-Jordan/CStrAinBP.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-Jordan/CStrAinBP.mexw64 -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-Jordan/CStrAinBP.mexw64.md5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-Jordan/CStrAinBP.mexw64.md5 -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-Jordan/env_add.m: -------------------------------------------------------------------------------- 1 | any(cellfun(@exist,{'CStrAinBP', 'CStrAinBP'})==3) -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-bluffing-vm/CStrAinBP.mexw32: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-bluffing-vm/CStrAinBP.mexw32 -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-bluffing-vm/CStrAinBP.mexw32.md5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-bluffing-vm/CStrAinBP.mexw32.md5 -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-bluffing-vm/env_add.m: -------------------------------------------------------------------------------- 1 | any(cellfun(@exist,{'CStrAinBP', 'CStrAinBP'})==3) -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-bluffing/CStrAinBP.mexa64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-bluffing/CStrAinBP.mexa64 -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-bluffing/CStrAinBP.mexa64.md5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-bluffing/CStrAinBP.mexa64.md5 -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-bluffing/env_add.m: -------------------------------------------------------------------------------- 1 | any(cellfun(@exist,{'CStrAinBP', 'CStrAinBP'})==3) -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-client64-120.sdsc.edu/CStrAinBP.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-client64-120.sdsc.edu/CStrAinBP.mexmaci64 -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-client64-120.sdsc.edu/CStrAinBP.mexmaci64.md5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-client64-120.sdsc.edu/CStrAinBP.mexmaci64.md5 -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/build-client64-120.sdsc.edu/env_add.m: -------------------------------------------------------------------------------- 1 | any(cellfun(@exist,{'CStrAinBP', 'CStrAinBP'})==3) -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/env_add.m: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/env_compile.m: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/fast_setdiff.m: -------------------------------------------------------------------------------- 1 | function A = fast_setdiff(A,B) 2 | % A fast version of setdiff for cell arrays of strings. 3 | 4 | try 5 | if isempty(A) 6 | A = {}; 7 | else 8 | A(CStrAinBP(A,B)) = []; 9 | end 10 | catch 11 | disp_once('Using the slower MATLAB fallback for setdiff(). Consider setting up a compiler to get much improved BCILAB performance (in some areas).'); 12 | A = setdiff(A,B); 13 | end 14 | 15 | -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/license.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009, Jan Simon 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in 12 | the documentation and/or other materials provided with the distribution 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 18 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | POSSIBILITY OF SUCH DAMAGE. 25 | -------------------------------------------------------------------------------- /external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/temphull.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sccn/cleanline/117bffa6e1fbc6d042a7e75cec9e289e1aa5be72/external/bcilab_partial/dependencies/CStrAinBP-2009-09-13/temphull.mat -------------------------------------------------------------------------------- /external/bcilab_partial/environment/env_handleerror.m: -------------------------------------------------------------------------------- 1 | function varargout = env_handleerror(varargin) 2 | % Displays a formatted error message for some error object, including a full stack trace. 3 | % env_handleerror(Error, Indent) 4 | % 5 | % In: 6 | % Error : error object, as received from lasterror or via a catch clause 7 | % (if omitted, lasterror is used) 8 | % Indent : optional indentation level, in characters 9 | % 10 | % Out: 11 | % Formatted : optionally the formatted error report 12 | % 13 | % Example: 14 | % % display an error message including stack trace in case of an error and continue without 15 | % % terminating 16 | % try 17 | % ... 18 | % catch e 19 | % env_handleerror(e); 20 | % end 21 | % 22 | % See also: 23 | % lasterror, MException, catch 24 | % 25 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 26 | % 2010-04-22 27 | 28 | 29 | [varargout{1:nargout}] = hlp_handleerror(varargin{:}); 30 | -------------------------------------------------------------------------------- /external/bcilab_partial/environment/env_translatepath.m: -------------------------------------------------------------------------------- 1 | function filename = env_translatepath(filename) 2 | % Translates platform-independent directories into a system-specific directories. 3 | % SystemPath = env_translatepath(IndependentPath) 4 | % 5 | % BCILAB supports platform-independent paths for all its scripts and IO functions, which allows for 6 | % script portability from system to system. It is especially important when data paths are mounted 7 | % at different locations, depending on access mode and operating system. A side effect of portable 8 | % path names is that there is one unique expression which computes any given data set, such as 9 | % "flt_iir(flt_reref((flt_resample(io_loadset('data:/Projects/Test/test1.vhdr'),[],200))),[],[4 6 25 10 | % 30])", and this in turn allows to share the same data set caches (which are indexed by expression) 11 | % across machines and operating systems, minimizing redundant computations. 12 | % 13 | % In: 14 | % IndependentPath : platform-independent path; may contain forward and/or backward slashes 15 | % (forward slashes generally preferred), and may refer to locations such as 16 | % store:/ (the store path) or data:/ (one of the data paths); can also be a 17 | % relative path 18 | % 19 | % Out: 20 | % SystemPath : system-specific path (with slashes corrected and locations resolved) 21 | % if multiple data paths are present, the one where the minimum number of 22 | % directories (and files) would have to be created to write to the given file is 23 | % selected. 24 | % 25 | % Examples: 26 | % % translate a platform-independent reference to a subdirectory of the data path to one that is 27 | % % recognized by the operating system (output might be, e.g., 'C:\Projects\mydata\test.mat') 28 | % env_translatepath('data:/projects/test.mat'); 29 | % 30 | % % resolve a reference to the storage directory 31 | % env_translatepath('store:/studyXY/result.mat') 32 | % 33 | % % resolve a reference to the BCILAB root directory 34 | % env_translatepath('bcilab:/userscripts/myscript.m') 35 | % 36 | % % resolve a reference to the user's home directory 37 | % env_translatepath('home:/myconfig.m') 38 | % 39 | % % resolve a reference to the current temp directory (as specified in the startup options) 40 | % env_translatepath('temp:/output/001.mat') 41 | % 42 | % % resolve a reference to the resources directory 43 | % env_translatepath('resources:/workspaces/testing.mat') 44 | % 45 | % 46 | % See also: 47 | % env_startup, io_loadset 48 | % 49 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 50 | % 2010-06-29 51 | 52 | global tracking; 53 | 54 | % turn the path into a system-dependent one 55 | filename = strrep(strrep(filename,'\',filesep),'/',filesep); 56 | 57 | % resolve location references 58 | if strncmp('store:',filename,6) 59 | filename = [tracking.paths.store_path filename(1+length('store:'):end)]; 60 | elseif strncmp('resources:',filename,10) 61 | filename = [tracking.paths.resource_path filename(1+length('resources:'):end)]; 62 | elseif strncmp('temp:',filename,5) 63 | filename = [tracking.paths.temp_path filename(1+length('temp:'):end)]; 64 | elseif strncmp('functions:',filename,10) 65 | filename = [tracking.paths.function_path filename(1+length('functions:'):end)]; 66 | elseif strncmp('bcilab:',filename,7) 67 | filename = [tracking.paths.bcilab_path filename(1+length('bcilab:'):end)]; 68 | elseif strncmp('dependencies:',filename,13) 69 | filename = [tracking.paths.dependency_path filename(1+length('dependencies:'):end)]; 70 | elseif strncmp('home:',filename,5) 71 | filename = [hlp_homedir filename(1+length('home:'):end)]; 72 | elseif strncmp('data:',filename,5) 73 | rest = filename(1+length('data:'):end); 74 | bestpath = 1; bestlen = -1; 75 | if length(tracking.paths.data_paths) > 1 76 | fpieces = hlp_split(rest,filesep); 77 | % find the data path that contains the longest prefix of the filename 78 | for pidx=1:length(tracking.paths.data_paths) 79 | p = tracking.paths.data_paths{pidx}; 80 | % for each prefix of the filename (starting with the longest one) 81 | for k=length(fpieces):-1:0 82 | % check if the data path plus the first k pieces of the filename exists 83 | if exist([p sprintf([filesep '%s'],fpieces{1:k})],'file') 84 | % found a match - check if it is a new length record among all our data paths... 85 | if k>bestlen 86 | bestlen = k; 87 | bestpath = pidx; 88 | end 89 | break; 90 | end 91 | end 92 | end 93 | end 94 | % resolve the reference using that data path which matches most of the filename, 95 | % where, if multiple data paths are equally well suited, the first one of them is taken 96 | filename = [tracking.paths.data_paths{bestpath} rest]; 97 | end 98 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_applyscaling.m: -------------------------------------------------------------------------------- 1 | function X = hlp_applyscaling(X, si) 2 | % Apply some previously determined scaling structure 3 | % X = hlp_applyscaling(X, ScaleInfo) 4 | % 5 | % This is just a convenience tool to implement simple data (e.g. feature) scaling operations. 6 | % 7 | % Examples: 8 | % scaleinfo = hlp_findscaling(data,'whiten') 9 | % hlp_applyscaling(data,scaleinfo) 10 | % 11 | % See also: 12 | % hlp_findscaling 13 | % 14 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 15 | % 2010-03-28 16 | 17 | if isfield(si,'add') 18 | X = X+repmat(si.add,[size(X,1),1]); end 19 | if isfield(si,'mul') 20 | X = X.*repmat(si.mul,[size(X,1),1]); end 21 | if isfield(si,'project') 22 | X = X*si.project; end 23 | if isfield(si,{'add','mul','project'}) 24 | X(~isfinite(X(:))) = 0; end 25 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_cpuload.m: -------------------------------------------------------------------------------- 1 | function result = hlp_cpuload 2 | % Get the relative CPU load 3 | osbean = java.lang.management.ManagementFactory.getOperatingSystemMXBean(); 4 | result = osbean.getSystemLoadAverage() / osbean.getAvailableProcessors(); 5 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_cryptohash.m: -------------------------------------------------------------------------------- 1 | function hash = hlp_cryptohash(data,fromfile) 2 | % Compute an MD5 hash of a file, string or generic data structure. 3 | % Hash = hlp_cryptohash(Data,FromFile) 4 | % 5 | % In: 6 | % Data : data to be hashed; can be a filename, a string, or any other MATLAB data structure. 7 | % 8 | % FromFile : if true, data is interpreted as a file name (default: false) 9 | % 10 | % Out: 11 | % Hash : MD5 hash (decimal, lowercase) of the Data 12 | % 13 | % Examples: 14 | % % calculate an md5 hash of a file 15 | % hlp_cryptohash('myscript.m',true); 16 | % 17 | % % calculate an md5 hash of a data structure 18 | % hlp_cryptohash(lastmodel); 19 | % 20 | % See also: 21 | % hlp_fingerprint, hlp_serialize 22 | 23 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 24 | % 2010-10-10 25 | 26 | 27 | if exist('fromfile','var') && fromfile 28 | % take data as a file name 29 | if ~ischar(data) 30 | error('To represent a file name, Data should be a string.'); end 31 | if ~exist(data,'file') 32 | error('The file %s does not exist.',data); end 33 | f = fopen(data,'r'); 34 | try 35 | data = fread(f,Inf); 36 | fclose(f); 37 | catch e 38 | try 39 | fclose(f); 40 | catch,end 41 | rethrow(e); 42 | end 43 | else 44 | % take data literally 45 | if ~ischar(data) 46 | data = hlp_serialize(data); end 47 | end 48 | 49 | % use Java to hash the data (idea from Michael Kleder) 50 | hasher = java.security.MessageDigest.getInstance('MD5'); 51 | hasher.update(uint8(data)); 52 | hash = dec2hex(typecast(hasher.digest,'uint8'),2)'; 53 | hash = lower(hash(:)'); 54 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_endschedule.m: -------------------------------------------------------------------------------- 1 | function [results,errors] = hlp_endschedule(sched,varargin) 2 | % Wait for completion of a scheduling operation and return results and errors. 3 | % [Results, Errors] = hlp_endschedule(Id, Options...) 4 | % 5 | % In: 6 | % Id : scheduler id, obtained from hlp_beginschedule 7 | % 8 | % Out: 9 | % Results : cell array of results of the scheduled computations (evaluated strings) 10 | % Errors : cell array of exception structs for those results that could not be evaluated (in no particular order) 11 | % 12 | % See also: 13 | % hlp_beginschedule, hlp_worker 14 | % 15 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 16 | % 2010-08-29 17 | 18 | results = {}; 19 | errors = {}; 20 | 21 | % read options 22 | opts = hlp_varargin2struct(varargin,'keep',false, 'spin_interval',0.1); 23 | 24 | if iscell(sched) 25 | % locally computed results 26 | for r=1:length(sched) 27 | results{r} = sched{r}{2}; end 28 | else 29 | % BLS scheduling 30 | 31 | % wait for the scheduler to finish (note: we cannot wait on a condition variable here, 32 | % as we need the MATLAB thread to be active for managing the reschedule policy) 33 | while (~sched.done()) 34 | pause(opts.spin_interval); end 35 | 36 | % obtain raw results & convert to cell-string array 37 | strings = sched.results(); 38 | for k=1:length(strings) 39 | raw{k} = char(strings(k)); end 40 | 41 | % terminate scheduler 42 | if ~opts.keep 43 | sched.terminate(); end 44 | 45 | % evaluate & reorder the string-formatted results 46 | for r=1:length(raw) 47 | try 48 | % evaluate 49 | [tmp,raw{r}] = evalc(raw{r}); %#ok 50 | try 51 | % put into results 52 | results{raw{r}{1}} = raw{r}{2}; 53 | catch 54 | % contains no order id (e.g. was an exception record), put into errors 55 | errors{end+1} = raw{r}; 56 | end 57 | catch 58 | % error evaluating result, put into errors 59 | errors{end+1} = lasterror; %#ok 60 | end 61 | end 62 | 63 | end -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_findscaling.m: -------------------------------------------------------------------------------- 1 | function res = hlp_findscaling(X, scaling) 2 | % Obtain information necessary to scale the given data. Works with hlp_applyscaling. 3 | % Scale-Info = hlp_findscaling(Data, Scale-Mode) 4 | % 5 | % This is just a convenience tool to implement simple data (e.g. feature) scaling operations. 6 | % 7 | % In: 8 | % Data : data matrix of [Observations x Variables] 9 | % Scale-Mode : scaling mode, one of {std,minmax,whiten} 10 | % 11 | % Out: 12 | % Scale-Info : scaling structure that can be used with hlp_applyscaling, to scale data 13 | % 14 | % Examples: 15 | % scaleinfo = hlp_findscaling(data,'whiten') 16 | % hlp_applyscaling(data,scaleinfo) 17 | % 18 | % See also: 19 | % hlp_applyscaling 20 | % 21 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 22 | % 2010-03-28 23 | 24 | if ~exist('scaling','var') 25 | scaling = 'minmax'; end 26 | 27 | switch scaling 28 | case 'center' 29 | res = struct('add',{-mean(X)}); 30 | case 'std' 31 | res = struct('add',{-mean(X)}, 'mul',{1./ std(X)}); 32 | res.mul(~isfinite(res.mul(:))) = 1; 33 | case 'minmax' 34 | res = struct('add',{-min(X)}, 'mul',{1./ (max(X) - min(X))}); 35 | res.mul(~isfinite(res.mul(:))) = 1; 36 | case 'whiten' 37 | [Uc,Lc] = eig(cov(X)); 38 | res = struct('add',{-mean(X)},'project',{Uc * sqrt(inv(Lc))'}); 39 | res.project(~isfinite(res.project(:))) = 1; 40 | otherwise 41 | if ~isempty(scaling) && ~strcmp(scaling,'none') 42 | error('hlp_findscaling: unknown scaling mode specified'); end 43 | res = struct(); 44 | end 45 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_flattensearch.m: -------------------------------------------------------------------------------- 1 | function x = hlp_flattensearch(x,form) 2 | % Flatten search() clauses in a nested data structure into a flat search() clause. 3 | % Result = hlp_flattensearch(Expression, Output-Form) 4 | % 5 | % Internal tool used by utl_gridsearch to enable the specification of search parameters using 6 | % search() clauses. 7 | % 8 | % In: 9 | % Expression : some data structure, usually an argument to utl_gridsearch, may or may not contain 10 | % nested search clauses. 11 | % 12 | % Output-Form : form of the output (default: 'search') 13 | % * 'search': the output shall be a flattened search clause (or a plain value if no 14 | % search) 15 | % * 'cell': the output shall be a cell array of elements to search over 16 | % 17 | % Out: 18 | % Result : a flattened search clause (or plain value), or a cell array of search possibilities. 19 | % 20 | % See also: 21 | % search, utl_gridsearch 22 | % 23 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 24 | % 2010-06-29 25 | 26 | 27 | x = flatten(x); 28 | 29 | if ~exist('form','var') || isempty(form) || strcmp(form,'search') 30 | % turn from cell format into search format 31 | if isscalar(x) 32 | % just one option: return the plain value 33 | x = x{1}; 34 | else 35 | % multiple options: return a search expression 36 | x = struct('head',{@search},'parts',{x}); 37 | end 38 | elseif ~strcmp(form,'cell') 39 | error(['Unsupported output form: ' form]); 40 | end 41 | 42 | 43 | % recursively factor search expressions out of a data structure, to give an overall search 44 | % expression (output format is cell array of search options) 45 | function parts = flatten(x) 46 | if isstruct(x) 47 | if isfield(x,{'data','srate','chanlocs','event','epoch'}) 48 | % data set? do not descend further 49 | parts = {x}; 50 | elseif all(isfield(x,{'head','parts'})) && numel(x)==1 && strcmp(char(x.head),'search') 51 | % search expression: flatten any nested searches... 52 | parts = cellfun(@flatten,x.parts,'UniformOutput',false); 53 | % ... and splice their parts in 54 | parts = [parts{:}]; 55 | else 56 | % generic structure: create a cartesian product over field-wise searches 57 | if isscalar(x) 58 | parts = {x}; 59 | % flatten per-field contents 60 | fields = cellfun(@flatten,struct2cell(x),'UniformOutput',false); 61 | lengths = cellfun('length',fields); 62 | % was any one a search? 63 | if any(lengths>1) 64 | fnames = fieldnames(x); 65 | % for each field that is a search... 66 | for k=find(lengths>1)' 67 | % replicate all parts once for each search item in the current field 68 | partnum = length(parts); 69 | parts = repmat(parts,1,lengths(k)); 70 | % and fill each item into the appropriate place 71 | for j=1:length(parts) 72 | parts{j}.(fnames{k}) = fields{k}{ceil(j/partnum)}; end 73 | end 74 | end 75 | elseif ~isempty(x) 76 | % struct array (either with nested searches or a concatenation of search() expressions): 77 | % handle as a cell array of structs 78 | parts = flatten(arrayfun(@(s){s},x)); 79 | % got a search? 80 | if ~isscalar(parts) 81 | % re-concatenate the cell contents of each part of the search expression into 82 | % struct arrays 83 | for i=1:length(parts) 84 | parts{i} = reshape([parts{i}{:}],size(parts{i})); end 85 | else 86 | parts = {x}; 87 | end 88 | else 89 | parts = {x}; 90 | end 91 | end 92 | elseif iscell(x) 93 | % cell array: create a cartesian product over cell-wise searches 94 | parts = {x}; 95 | x = cellfun(@flatten,x,'UniformOutput',false); 96 | % for each cell that is a search... 97 | for c=find(cellfun('length',x(:)')>1) 98 | % replicate all parts once for each search item in the current cell 99 | partnum = length(parts); 100 | parts = repmat(parts,1,length(x{c})); 101 | % and fill in the new item in the appropriate place 102 | for j=1:length(parts) 103 | parts{j}{c} = x{c}{ceil(j/partnum)}; end 104 | end 105 | else 106 | % anything else: wrap 107 | parts = {x}; 108 | end 109 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_gcc_version.m: -------------------------------------------------------------------------------- 1 | function v = hlp_gcc_version() 2 | % Get the GCC version in a numeric format that can be compared with <, >, etc. 3 | % returns [] if the GCC compiler is not installed. 4 | [a,b]=system('gcc --version'); v= str2num(strrep(b(11:15),'.','')); %#ok -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_getcaller.m: -------------------------------------------------------------------------------- 1 | function [name,file] = hlp_getcaller(indirection) 2 | % Find the name & file of the calling function. 3 | % [Name,File] = hlp_getcaller(Indirection) 4 | % 5 | % In: 6 | % Indirection : optional level of indirection (default: 1) 7 | % 8 | % Out: 9 | % Name: MATLAB name of the calling function, if any 10 | % File: file name of the calling function, if any 11 | % 12 | % Example: 13 | % % in a function, get the name of the calling function (if any) 14 | % mycaller = hlp_getcaller; 15 | % 16 | % % in a function, get the name of the function that called the calling function 17 | % mycallerscaller = hlp_getcaller(2); 18 | % 19 | % See also: 20 | % hlp_iscaller 21 | % 22 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 23 | % 2010-04-15 24 | 25 | try 26 | throw; %#ok % fast way to get an exception 27 | catch context 28 | if ~exist('indirection','var') 29 | indirection = 1; end 30 | if length(context.stack) > indirection+1 31 | name = context.stack(indirection+2).name; 32 | file = context.stack(indirection+2).file; 33 | else 34 | name = []; 35 | file = []; 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_getresult.m: -------------------------------------------------------------------------------- 1 | function varargout = hlp_getresult(idx,f,varargin) 2 | % Returns the Result-Idx's output of the function, given the supplied arguments. 3 | % Results... = hlp_getresult(Result-Idx, Function, Arguments...) 4 | % 5 | % In: 6 | % Result-Idx : index of the result (output) of the given function application; can also 7 | % be a vector of indices, then re-emitting those outputs as outputs. 8 | % note: if this is passed as a cell array, the outputs will be wrapped into a cell 9 | % array. 10 | % 11 | % Function : function to apply to the Arguments 12 | % 13 | % Arguments... : list of arguments to the function 14 | % 15 | % Out: 16 | % Results... : one or more outputs, selected according to Result-Idx from the outputs of 17 | % Function(Arguments...), and optionally wrapped into a cell array. 18 | % 19 | % Examples: 20 | % % get the second output of the sort() function, when applied to some data 21 | % hlp_getresult(2,@sort,[1 4 2 5 2 1 0 6]) 22 | % 23 | % See also: 24 | % hlp_wrapresults 25 | % 26 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 27 | % 2010-03-28 28 | 29 | if isnumeric(idx) 30 | [tmp{1:max(idx)}] = f(varargin{:}); 31 | varargout = tmp(idx); 32 | elseif iscell(idx) 33 | [tmp{1:max([idx{:}])}] = f(varargin{:}); 34 | varargout = {tmp([idx{:}])}; 35 | else 36 | error('unsupported index format.'); 37 | end -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_handleerror.m: -------------------------------------------------------------------------------- 1 | function s = hlp_handleerror(e,level) 2 | % Displays a formatted error message for some error object, including a full stack trace. 3 | % hlp_handleerror(Error, Indent) 4 | % 5 | % In: 6 | % Error : error object, as received from lasterror or via a catch clause 7 | % (if omitted, lasterror is used) 8 | % Indent : optional indentation level, in characters 9 | % 10 | % Out: 11 | % Formatted : optionally the formatted error report 12 | % 13 | % Example: 14 | % % display an error message including stack trace in case of an error and continue without 15 | % % terminating 16 | % try 17 | % ... 18 | % catch e 19 | % hlp_handleerror(e); 20 | % end 21 | % 22 | % See also: 23 | % lasterror, MException, catch 24 | 25 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 26 | % 2010-04-22 27 | 28 | try 29 | if ~exist('e','var') 30 | e = lasterror; end %#ok 31 | 32 | % compute the appropriate indentation level 33 | if ~exist('level','var') 34 | level = ''; 35 | else 36 | level = repmat(' ',1,level); 37 | end 38 | 39 | if nargout == 0 40 | % display the message 41 | for message = hlp_split(e.message,[10 13]) 42 | fprintf('%s %s\n',level,message{1}); end 43 | fprintf('%s occurred in: \n',level); 44 | for st = e.stack' 45 | if ~isdeployed 46 | try 47 | fprintf('%s %s: %i\n',level,st.file,st.line,st.name,st.line); 48 | catch 49 | fprintf('%s %s: %i\n',level,st.file,st.name,st.line); 50 | end 51 | else 52 | % links are not supported in deployed mode 53 | fprintf('%s %s: %i\n',level,st.file,st.line); 54 | end 55 | end 56 | else 57 | % print message into a string 58 | s = []; 59 | for message = hlp_split(e.message,[10 13]) 60 | s = [s sprintf('%s %s\n',level,message{1})]; end 61 | s = [s sprintf('%s occurred in: \n',level)]; 62 | for st = e.stack' 63 | s = [s sprintf('%s %s: %i\n',level,st.file,st.line)]; end 64 | end 65 | catch 66 | disp('An error occurred, but the traceback could not be displayed due to another error...'); 67 | end 68 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_homedir.m: -------------------------------------------------------------------------------- 1 | function res = hlp_homedir 2 | % Get the user's home directory 3 | res = char(java.lang.System.getProperty('user.home')); 4 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_hostip.m: -------------------------------------------------------------------------------- 1 | function hostip = hlp_hostip() 2 | % Find the host IP address in a platform-independent fashion. 3 | import java.net.InetAddress; 4 | hostip = char(InetAddress.getLocalHost()); 5 | hostip = hostip(find(hostip=='/',1)+1:end); -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_hostname.m: -------------------------------------------------------------------------------- 1 | function hostname = hlp_hostname() 2 | % Find the hostname in a platform-independent fashion. 3 | import java.net.InetAddress; 4 | hostname = char(InetAddress.getLocalHost()); 5 | hostname = hostname(1:find(hostname=='/',1)-1); -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_inoutargs.m: -------------------------------------------------------------------------------- 1 | function [inargs,outargs,h1] = hlp_inoutargs(filename,funcname) 2 | % Retrieve the names of input/output arguments of the given m file. 3 | % [In-Args,Out-Args,H1-Line] = hlp_inoutargs(Filename,Function-Name) 4 | % 5 | % In: 6 | % Filename : full path to an m-file 7 | % Function-Name : optional, name of a (possibly nested) function in the file, for which the args 8 | % shall be retrieved 9 | % 10 | % Out: 11 | % In-Args : cell array of input argument names for the function 12 | % Out-Args : cell array of output argument names for the function 13 | % H1-Line : first line of help text 14 | % 15 | % Notes: 16 | % For heavy use, utl_fileversion is to be preferred (which caches the result of this function properly). 17 | % 18 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 19 | % 2010-04-14 20 | 21 | h1 = []; 22 | 23 | if ~exist('funcname','var') 24 | funcname = []; end 25 | 26 | if ~exist(filename,'file') 27 | error(['there is no file named ' filename]); end 28 | f = fopen(filename,'r'); 29 | if f == -1 30 | error(['Cannot open the file named ' filename]); end 31 | try 32 | while 1 33 | % read the file line by line 34 | l = fgetl(f); 35 | if ~ischar(l) 36 | error(['definition of the function ' funcname ' not found in ' filename]); end 37 | % remove commented part 38 | commpos = strfind(l,'%'); 39 | if ~isempty(commpos) 40 | l = l(1:commpos(1)-1); end 41 | % see if it contains a function declaration 42 | funcpos = strfind(l,'function'); 43 | if ~isempty(funcpos) && isempty(strtrim(l(1:funcpos-1))) 44 | % we have the declaration line, find out where the input/output args are 45 | ostart = strfind(l,'[')+1; 46 | oend = strfind(l,']')-1; 47 | if isempty(ostart) || isempty(oend) 48 | ostart = funcpos+length('function'); 49 | oend = strfind(l, '=')-1; 50 | end 51 | istart = strfind(l,'(')+1; 52 | iend = strfind(l,')')-1; 53 | % and read them in (note: both ranges could be empty) 54 | if ~(isempty(istart) || isempty(iend)) 55 | inargs = hlp_split(l(istart:iend),', '); 56 | else 57 | inargs = {}; 58 | end 59 | if ~(isempty(ostart) || isempty(oend)) 60 | outargs = hlp_split(l(ostart:oend),', '); 61 | else 62 | outargs = {}; 63 | end 64 | inargs = inargs(~cellfun(@isempty,inargs)); 65 | outargs = outargs(~cellfun(@isempty,outargs)); 66 | if ~isempty(funcname) 67 | % and also make sure that we have the correct function name 68 | if ~isempty(oend) 69 | nstart = strfind(l,'=')+1; 70 | else 71 | nstart = ostart; 72 | end 73 | if ~isempty(istart) 74 | nend = istart-2; 75 | else 76 | nend = length(l); 77 | end 78 | if strcmp(strtrim(l(nstart:nend)), funcname) 79 | % match: we're done 80 | break; 81 | end 82 | else 83 | % we're done 84 | break; 85 | end 86 | end 87 | end 88 | try 89 | % check if we find a commented line... this would be the h1 line 90 | l = fgetl(f); 91 | comm = find(l=='%',1); 92 | if ~isempty(comm) 93 | h1 = strtrim(l(comm+1:end)); end 94 | catch 95 | end 96 | fclose(f); 97 | catch e 98 | if f ~= -1 99 | fclose(f); end 100 | rethrow(e); 101 | end 102 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_iscaller.m: -------------------------------------------------------------------------------- 1 | function result = hlp_iscaller(func, level) 2 | % Test whether some function is calling this function at some level(s) of indirection. 3 | % Result = hlp_iscaller(Function, Levels) 4 | % 5 | % It can be specified what levels of nesting outside the function which runs hlp_iscaller are considered. 6 | % 7 | % In: 8 | % Function : function handle to a function to be tested 9 | % Levels : nesting level(s) that shall be tested (default: all) 10 | % level 1 is the function that invokes hlp_iscaller 11 | % 12 | % Out: 13 | % Result : whether the current code is called by the Caller 14 | % 15 | % Examples: 16 | % % in a function, test if the calling function, or the caller of the calling function, is named 17 | % % 'somefunction' 18 | % hlp_iscaller('somefunction',1:2) 19 | % 20 | % See also: 21 | % hlp_getcaller 22 | % 23 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 24 | % 2010-04-14 25 | 26 | try 27 | throw; %#ok % fastest way to get an exception 28 | catch context 29 | if ~exist('level','var') 30 | level = 2:length(context.stack); end 31 | level = level+1; 32 | level(level < 1 | level > length(context.stack)) = []; 33 | result = any(strcmp(char(func),{context.stack(level).name})); 34 | end 35 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_lookup_symbol.m: -------------------------------------------------------------------------------- 1 | function outargs = hlp_lookup_symbol(x,context) 2 | % Internal. Look up a symbol from the current ult_block / workspace scope. 3 | % Data = hlp_lookup_symbol(Symbol,Context) 4 | % 5 | % More precisely, perform a lookup for a symbol in the current (dynamic) scope formed by (possibly nested) utl_block(s) 6 | % returns a cell array of all the values associated with the symbol. 7 | % Used to implement dynamic scoping across functions, used by parts of the expression system. 8 | % 9 | % In: 10 | % Symbol : a symbol (function handle or string). 11 | % 12 | % Context : Optionally the execution context (stack) at this point, if known. 13 | % Can be obtained via try/catch. 14 | % 15 | % Out: 16 | % Data : the data associated with the symbol, or the symbol itself, if the lookup failed. 17 | % 18 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 19 | % 2010-05-03 20 | global bcilab; 21 | 22 | % the symbol of interest... 23 | symbol = char(x); 24 | 25 | try 26 | % obtain the current stack frame entries from context 27 | entries = {context.stack.name}; 28 | catch 29 | % context did not exist: obtain it 30 | context = lasterror; %#ok 31 | % and get entries, too 32 | entries = {context.stack.name}; 33 | end 34 | 35 | % check for all entries whether they refer to a stack frame... 36 | for k=find(strncmp(entries,'utl_block/@(x,active_stackframe__',33)) 37 | frameid = entries{k}(34:end-12); 38 | % ...to look up the symbol in question 39 | if isfield(bcilab.stackframes.ov.(frameid),symbol) 40 | outargs = {bcilab.stackframes.ov.(frameid).(symbol)}; 41 | return; 42 | end 43 | end 44 | 45 | if ~isfield(bcilab.workspace.ov,symbol) 46 | % symbol is not in the global workspace: remains unsubstituted 47 | outargs = {x}; 48 | else 49 | % symbol is fetched from the global workspace 50 | outargs = {bcilab.workspace.ov.(symbol)}; 51 | end 52 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_makefunction.m: -------------------------------------------------------------------------------- 1 | function f = hlp_makefunction(decl,workspace) 2 | % Create a function handle from code and a workspace of variables. For hlp_serialize(). 3 | % Function = hlp_makefunction(Declaration,Workspace) 4 | % 5 | % In: 6 | % Declaration : The function's declaration string, e.g. '@(x) x*A + B' 7 | % 8 | % Workspace : Struct that holds the (non-parameter) variables being referenced in the declaration 9 | % (A and B in the above example) 10 | % 11 | % Out: 12 | % Function : A function handle that can subsequently be evaluated. 13 | % 14 | % Examples: 15 | % f = hlp_makefunction('@(x)x*A+B',struct('A',2,'B',10)); 16 | % f(2) --> yields 14 17 | % 18 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 19 | % 2010-08-30 20 | 21 | % create workspace 22 | for fn=fieldnames(workspace)' 23 | eval([fn{1} ' = workspace.(fn{1}) ;']); end 24 | 25 | % evaluate declaration 26 | f = eval(decl); -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_matlab_version.m: -------------------------------------------------------------------------------- 1 | function v = hlp_matlab_version() 2 | % Get the MATLAB version in a numeric format that can be compared with <, >, etc. 3 | persistent vers; 4 | try 5 | v = vers(1); 6 | catch 7 | v = strsplit(version,'.'); v = str2num(v{1})*100 + str2num(v{2}); 8 | vers = v; 9 | end 10 | 11 | % Split a string according to some delimiter(s). Not as fast as hlp_split (and doesn't fuse 12 | % delimiters), but doesn't need bsxfun(). 13 | function strings = strsplit(string, splitter) 14 | ix = strfind(string, splitter); 15 | strings = cell(1,numel(ix)+1); 16 | ix = [0 ix numel(string)+1]; 17 | for k = 2 : numel(ix) 18 | strings{k-1} = string(ix(k-1)+1:ix(k)-1); end 19 | strings = strings(~cellfun('isempty',strings)); 20 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_memavail.m: -------------------------------------------------------------------------------- 1 | function result = hlp_memavail() 2 | % Get the amount of potentially available memory, in bytes 3 | % This is usually more than what is reported by hlp_memfree, because some memory is tentatively 4 | % allocated by the OS for caches, etc. 5 | bean = java.lang.management.ManagementFactory.getOperatingSystemMXBean(); 6 | result = bean.getTotalPhysicalMemorySize - bean.getCommittedVirtualMemorySize; 7 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_memfree.m: -------------------------------------------------------------------------------- 1 | function result = hlp_memfree 2 | % Get the amount of free physical memory, in bytes 3 | result = java.lang.management.ManagementFactory.getOperatingSystemMXBean().getFreePhysicalMemorySize(); 4 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_resolve.m: -------------------------------------------------------------------------------- 1 | function outargs = hlp_resolve(x,default,context) 2 | % Look up a symbol from the current hlp_scope scope. 3 | % Data = hlp_resolve(Symbol,Default,Context) 4 | % 5 | % More precisely, perform a lookup for a symbol in the current (dynamic) scope formed by (possibly 6 | % nested) hlp_scope(s). Returns a cell array of all the values associated with the symbol. Used to 7 | % implement dynamic scoping across functions, used by parts of the expression & online system. 8 | % 9 | % In: 10 | % Symbol : a symbol (string or function handle) to look up; if omitted, the entire symbol frame 11 | % will be returned as a struct 12 | % 13 | % Default : the default value, if the symbol does not exist (note: you may also omit the default 14 | % if you prefer to get an error in case the symbol does not exist) 15 | % 16 | % Context : Optionally the execution context (stack) at this point, if known. 17 | % Can be obtained via try/catch. 18 | % 19 | % Out: 20 | % Data : the data associated with the symbol, or the symbol itself, if the lookup failed 21 | % 22 | % Examples: 23 | % % resolve the value of the symbol 'test' against the current dynamic scope 24 | % value = hlp_resolve('test') 25 | % 26 | % See also: 27 | % hlp_scope 28 | % 29 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 30 | % 2010-05-03 31 | 32 | global tracking; 33 | 34 | try 35 | % obtain the current stack frame entries from the context 36 | entries = {context.stack.name}; 37 | catch context 38 | % or get the entries from the exception that was just thrown 39 | entries = {context.stack.name}; 40 | end 41 | 42 | % check for all entries whether they refer to a stack frame... 43 | marker = 'make_func/@(f,a,frame__'; 44 | frames = find(strncmp(entries,marker,23)); 45 | 46 | % the symbol of interest... 47 | symbol = char(x); 48 | for k=frames 49 | frameid = entries{k}(24:end-14); 50 | % ...to look up the symbol in question 51 | if isfield(tracking.stack.frames.(frameid),symbol) 52 | outargs = tracking.stack.frames.(frameid).(symbol); 53 | return; 54 | end 55 | end 56 | 57 | try 58 | if isfield(tracking.stack.base,symbol) 59 | % symbol is fetched from the base workspace 60 | outargs = tracking.stack.base.(symbol); 61 | else 62 | % symbol is not in the base workspace: remains unsubstituted 63 | outargs = default; 64 | end 65 | catch 66 | % base workspace doesn't exist yet: create it... 67 | tracking.stack.base = struct(); 68 | outargs = default; 69 | end 70 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_resolveall.m: -------------------------------------------------------------------------------- 1 | function outargs = hlp_resolveall(context) 2 | % Look up all symbols in the current hlp_scope scope. 3 | % Scope = hlp_resolveall(Context) 4 | % 5 | % In: 6 | % Context : Optionally the execution context (stack) at this point, if known. 7 | % Can be obtained via try/catch. 8 | % 9 | % Out: 10 | % Scope : a struct with values assigned to symbol names 11 | % 12 | % See also: 13 | % hlp_resolve 14 | % 15 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 16 | % 2010-05-03 17 | 18 | global tracking; 19 | 20 | try 21 | % obtain the current stack frame entries from the context 22 | entries = {context.stack.name}; 23 | catch context 24 | % or get the entries from the exception that was just thrown 25 | entries = {context.stack.name}; 26 | end 27 | 28 | % check for all entries whether they refer to a stack frame... 29 | marker = 'make_func/@(f,a,frame__'; 30 | frames = find(strncmp(entries,marker,23)); 31 | 32 | % start with the base scope 33 | try 34 | scope = tracking.stack.base; 35 | catch 36 | scope = struct(); 37 | tracking.stack.base = scope; 38 | end 39 | % and walk up the stack, overriding existing symbols 40 | for k=frames(end:-1:1) 41 | frame = tracking.stack.frames.(entries{k}(24:end-14)); 42 | for fn=fieldnames(frame)' 43 | scope.(fn{1}) = frame.(fn{1}); end 44 | end 45 | outargs = scope; 46 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_rewrite.m: -------------------------------------------------------------------------------- 1 | function data = hlp_rewrite(data,varargin) 2 | % Rewrite (replace) an input data structure into an output data structure. 3 | % Output = hlp_rewrite(Input,Rules...) 4 | % 5 | % In: 6 | % Input : some data structure to be rewritten 7 | % 8 | % Rules... : a comma-separated list of rewrite rules (oldval,newval,oldval,newval,oldval,newval, ...) 9 | % 10 | % Out: 11 | % Output : the input data structure, but rewritten according to the rules (where they matched). 12 | % 13 | % 14 | % Notes: 15 | % * No two oldval's may be equal. 16 | % * If there is no match, data remains unchanged. 17 | % 18 | % Examples: 19 | % % rewrite short forms of some string into corresponding long forms 20 | % hlp_rewrite(myinput, 'hp','highpass', 'lp','lowpass', 'bp','bandpass') 21 | % 22 | % % rewrite true to 'on' and false to 'off' 23 | % hlp_rewrite(myinput, true,'on', false,'off') 24 | % 25 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 26 | % 2010-09-26 27 | 28 | old = varargin(1:2:end); 29 | new = varargin(2:2:end); 30 | 31 | if iscellstr(old) 32 | % mapping from strings 33 | match = strcmp(data,old); 34 | if any(match) 35 | data = new{match}; end 36 | else 37 | % mapping from general structures 38 | match = cellfun(@(x)isequalwithequalnans(x,data),old); 39 | if any(match) 40 | data = new{match}; end 41 | end 42 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_schedule.m: -------------------------------------------------------------------------------- 1 | function [results,errors] = hlp_schedule(tasks,varargin) 2 | % Schedule the given tasks across a pool of (possibly remote) workers. 3 | % Results = hlp_schedule(Tasks, Options...) 4 | % 5 | % In: 6 | % Tasks : cell array of tasks; formatted as 7 | % * (evaluatable) string 8 | % * {function_handle, arg1,arg2,arg3, ...} 9 | % * struct('head',function_handle, 'parts',{{arg1,arg2,arg3, ...}}) 10 | % (see also hlp_beginschedule for further details) 11 | % 12 | % Options...: optional name-value pairs; see hlp_beginschedule and hlp_endschedule for the options 13 | % 14 | % 'keep': keep this scheduler (and its connections) alive for later re-use (default: true) 15 | % if false, the scheduler will be destroyed after use, and re-created during the next run 16 | % 17 | % Out: 18 | % Results : cell array of results of the scheduled computations (evaluated tasks) 19 | % Errors : cell array of exception structs for those results that could not be evaluated (in no particular order) 20 | % 21 | % See also: 22 | % hlp_worker, hlp_beginschedule, hlp_endschedule 23 | % 24 | % Example: 25 | % results = hlp_schedule({'sin(randn(10))','exp(randn(10))'},'pool',{'localhost:32547','localhost:32548'}) 26 | % 27 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 28 | % 2010-08-29 29 | 30 | opts = hlp_varargin2struct(varargin, 'keep',true); 31 | 32 | id = hlp_beginschedule(tasks,opts); 33 | [results,errors] = hlp_endschedule(id,opts); 34 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_scope.m: -------------------------------------------------------------------------------- 1 | function varargout = hlp_scope(assignments, f, varargin) 2 | % Execute a function within a dynamic scope of values assigned to symbols. 3 | % Results... = hlp_scope(Assignments, Function, Arguments...) 4 | % 5 | % This is the only completely reliable way in MATLAB to ensure that symbols that should be assigned 6 | % while a function is running get cleared after the function returns orderly, crashes, segfaults, 7 | % the user slams Ctrl+C, and so on. Symbols can be looked up via hlp_resolve(). 8 | % 9 | % In: 10 | % Assignments : Cell array of name-value pairs or a struct. Values are associated with symbols of 11 | % the given names. The names should be valid MATLAB identifiers. These assigments 12 | % form a dynamic scope for the execution of the function; scopes can also be 13 | % nested, and assignments in inner scopes override those of outer scopes. 14 | % 15 | % Function : a function handle to invoke 16 | % 17 | % Arguments... : arguments to pass to the function 18 | % 19 | % Out: 20 | % Results... : return value(s) of the function 21 | % 22 | % See also: 23 | % hlp_resolve 24 | % 25 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 26 | % 2010-05-03 27 | 28 | % add a new stack frame with the evaluated assignments & get its unique id 29 | id = make_stackframe(assignments); 30 | % also take care that it gets reclaimed after we're done 31 | reclaimer = onCleanup(@()return_stackframe(id)); 32 | 33 | % make a function that is tagged by id 34 | func = make_func(id); 35 | 36 | % evaluate the function with the id introduced into MATLAB's own stack 37 | [varargout{1:nargout}] = func(f,varargin); 38 | 39 | 40 | 41 | function func = make_func(id) 42 | persistent funccache; % (cached, since the eval() below is a bit slow) 43 | try 44 | func = funccache.(id); 45 | catch 46 | func = eval(['@(f,a,frame__' id ')feval(f,a{:})']); 47 | funccache.(id) = func; 48 | end 49 | 50 | 51 | function id = make_stackframe(assignments) 52 | % put the assignments into a struct 53 | if iscell(assignments) 54 | assignments = cell2struct(assignments(2:2:end),assignments(1:2:end),2); end 55 | % get a fresh frame id 56 | global tracking; 57 | try 58 | id = tracking.stack.frameids.removeLast(); 59 | catch 60 | if ~isfield(tracking,'stack') || ~isfield(tracking.stack,'frameids') 61 | % need to create the id repository first 62 | tracking.stack.frameids = java.util.concurrent.LinkedBlockingDeque(); 63 | for k=50000:-1:1 64 | tracking.stack.frameids.addLast(sprintf('f%d',k)); end 65 | else 66 | if tracking.stack.frameids.size() == 0 67 | % if this happens then either you have 10.000s of parallel executions of hlp_scope(), 68 | % or you have a very deep recursion level (the MATLAB default is 500), or your function 69 | % has crashed 10.000s of times in a way that keeps onCleanup from doing its job, or you have 70 | % substituted onCleanup by a dummy class or function that doesn't actually work (e.g. on 71 | % pre-2008a systems). 72 | error('We ran out of stack frame ids. This should not happen under normal conditions. Please make sure that your onCleanup implementation is not consistently failing to execute.'); 73 | end 74 | end 75 | id = tracking.stack.frameids.removeLast(); 76 | end 77 | % and store the assignments under it 78 | tracking.stack.frames.(id) = assignments; 79 | 80 | 81 | function return_stackframe(id) 82 | % finally return the frame id again... 83 | global tracking; 84 | tracking.stack.frameids.addLast(id); 85 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_sort_namevalues.m: -------------------------------------------------------------------------------- 1 | function res = hlp_sort_namevalues(varargin) 2 | % Sort name-value pairs by name. 3 | % Sorted-NVPs = hlp_sort_namevalues(NVPs) 4 | % 5 | % Since the toolbox occasionally caches results of function calls, 6 | % this is practical to uniformize arguments that lead to the same results, but look superficially different. 7 | % 8 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 9 | % 2010-03-28 10 | 11 | names = varargin(1:2:end); 12 | [names, I] = sort(names); I=([I*2-1; I*2]); I=I(:); %#ok 13 | res = varargin(I); 14 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_split.m: -------------------------------------------------------------------------------- 1 | function res = hlp_split(str,delims) 2 | % Split a string according to some delimiter(s). 3 | % Result = hlp_split(String,Delimiters) 4 | % 5 | % In: 6 | % String : a string (char vector) 7 | % 8 | % Delimiters : a vector of delimiter characters (includes no special support for escape sequences) 9 | % 10 | % Out: 11 | % Result : a cell array of (non-empty) non-Delimiter substrings in String 12 | % 13 | % Examples: 14 | % % split a string at colons and semicolons; returns a cell array of four parts 15 | % hlp_split('sdfdf:sdfsdf;sfdsf;;:sdfsdf:',':;') 16 | % 17 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 18 | % 2010-11-05 19 | 20 | pos = find(diff([0 ~sum(bsxfun(@eq,str(:)',delims(:)),1) 0])); 21 | res = cell(~isempty(pos),length(pos)/2); 22 | for k=1:length(res) 23 | res{k} = str(pos(k*2-1):pos(k*2)-1); end 24 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_struct2varargin.m: -------------------------------------------------------------------------------- 1 | function args = hlp_struct2varargin(struc,varargin) 2 | % Convert a struct into a sequence of name-value pairs; inverse to hlp_varargin2struct. 3 | % Args = hlp_struct2varargin(Struct,Options...) 4 | % 5 | % In: 6 | % Struct: a 1x1 structure array 7 | % Options: optional name-value pairs; 8 | % 'suppress': suppress the output names listed in the following cell array 9 | % 'rewrite' : rewrite some names in the struct, if present (executed after suppress and before restrict) 10 | % specified as a cell array of {oldname,newname,oldname,newname, ....} 11 | % 'restrict': restrict the output names to those listed in the following cell array 12 | % 13 | % Out: 14 | % Args: a list of name-value pairs 15 | % 16 | % Examples: 17 | % % in the given cell array of name-value pairs, remove occurrences of myarg1 and myarg2 parameters 18 | % hlp_struct2varargin(options,'suppress',{'myarg1','myarg2'}); 19 | % 20 | % % rewrite any occurrences of a 'channel' parameter into 'chns', and likewise for samplerate 21 | % hlp_struct2varargin(options,'rewrite',{'channels','chns','samplerate','srate'}); 22 | % 23 | % % restrict the given name-value pairs to those whose name is either test, arg1, or arg2. 24 | % hlp_struct2varargin(options,'restrict',{'test','arg1','arg2'}); 25 | % 26 | % See also: 27 | % hlp_varargin2struct 28 | % 29 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 30 | % 2010-03-28 31 | 32 | if isempty(struc), args = {}; return; end 33 | 34 | opts = hlp_varargin2struct(varargin,'restrict',[],'suppress',[],'rewrite',[]); 35 | 36 | fields = fieldnames(struc)'; 37 | data = struct2cell(struc)'; 38 | % suppress some of the original field names 39 | if ~isempty(opts.suppress) 40 | [fields,I] = setdiff(fields,opts.suppress); 41 | data = data(I); 42 | end 43 | % rewrite some of the original field names into new field names 44 | for c=1:2:length(opts.rewrite) 45 | fields(strcmp(fields,opts.rewrite{c})) = opts.rewrite(c+1); end 46 | % restrict to a subset of old/new field names 47 | if ~isempty(opts.restrict) 48 | [fields,I,J] = intersect(fields,opts.restrict); %#ok 49 | data = data(I); 50 | end 51 | 52 | args = vertcat(fields,data); 53 | args = args(:)'; 54 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/hlp_wrapresults.m: -------------------------------------------------------------------------------- 1 | function a = hlp_wrapresults(f,varargin) 2 | % Wraps all outputs produced by function f for the given arguments into a cell array. 3 | % Results = hlp_wrapresults(Function, Arguments...) 4 | % 5 | % In: 6 | % Function : some function handle to execute 7 | % 8 | % Arguments... : list of arguments to pass to the function 9 | % 10 | % Out: 11 | % Results : cell array of all function results 12 | % 13 | % 14 | % Notes: 15 | % It is not (currently) possible to efficiently determine the number of out-args for a 16 | % varargout function; in this case, at most 10 outputs are supported. 17 | % 18 | % Examples: 19 | % % wrap both outputs of a particualr sort() call into a cell array 20 | % results = hlp_wrapresults(@sort,[1 4 2 1 3 6 0]) 21 | % 22 | % See also: 23 | % hlp_getresult 24 | % 25 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 26 | % 2010-03-28 27 | 28 | % find out how many arguments f can maximally produce 29 | len = nargout(f); 30 | if len < 0 31 | % for varargout functions, we assume at most 10 32 | len = 10; end 33 | % ... then invoke the function 34 | while len >= 1 35 | try 36 | % get the appropriate number of results from f() 37 | [a{1:len}] = f(varargin{:}); 38 | return; 39 | catch e 40 | % got an exception, check if it is outarg-related 41 | if ~any(strcmp(e.identifier,{'MATLAB:TooManyOutputs','MATLAB:maxlhs','MATLAB:unassignedOutputs'})) 42 | % it isn't: rethrow 43 | rethrow(e); end 44 | % but if it was, we need to retry with fewer out-arguments 45 | len = len-1; 46 | end 47 | end 48 | 49 | % len = 0: f produces no outputs 50 | f(varargin{:}); 51 | a = {}; 52 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/private/dialogs_disabled/errordlg.m: -------------------------------------------------------------------------------- 1 | function varargout = questdlg2(varargin) 2 | error('dialogs disabled.'); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/private/dialogs_disabled/errordlg2.m: -------------------------------------------------------------------------------- 1 | function varargout = questdlg2(varargin) 2 | error('dialogs disabled.'); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/private/dialogs_disabled/inputdlg.m: -------------------------------------------------------------------------------- 1 | function varargout = questdlg2(varargin) 2 | error('dialogs disabled.'); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/private/dialogs_disabled/inputdlg2.m: -------------------------------------------------------------------------------- 1 | function varargout = questdlg2(varargin) 2 | error('dialogs disabled.'); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/private/dialogs_disabled/inputgui.m: -------------------------------------------------------------------------------- 1 | function varargout = questdlg2(varargin) 2 | error('dialogs disabled.'); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/private/dialogs_disabled/questdlg.m: -------------------------------------------------------------------------------- 1 | function varargout = questdlg2(varargin) 2 | error('dialogs disabled.'); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/helpers/private/dialogs_disabled/questdlg2.m: -------------------------------------------------------------------------------- 1 | function varargout = questdlg2(varargin) 2 | error('dialogs disabled.'); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/Blank.m: -------------------------------------------------------------------------------- 1 | function res = Blank(varargin) 2 | % shortcut form for exp_blank() 3 | res = exp_blank(varargin{:}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/Condition.m: -------------------------------------------------------------------------------- 1 | function res = Condition(varargin) 2 | % shortcut form for exp_condition() 3 | res = exp_condition(varargin{:}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/Evaluate.m: -------------------------------------------------------------------------------- 1 | function res = Evaluate(varargin) 2 | % alternative form for exp_eval() 3 | res = exp_eval(varargin{:}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/Hold.m: -------------------------------------------------------------------------------- 1 | function res = Hold(varargin) 2 | % shortcut form for exp_hold() 3 | res = exp_hold(varargin{:}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/Lambda.m: -------------------------------------------------------------------------------- 1 | function res = Lambda(varargin) 2 | % shortcut form for exp_lambda() 3 | res = exp_lambda(varargin{:}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/Pattern.m: -------------------------------------------------------------------------------- 1 | function res = Pattern(varargin) 2 | % shortcut form for exp_pattern() 3 | res = exp_pattern(varargin{:}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/Rule.m: -------------------------------------------------------------------------------- 1 | function res = Rule(varargin) 2 | % shortcut form for exp_rule() 3 | res = exp_rule(varargin{:}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/Set.m: -------------------------------------------------------------------------------- 1 | function res = Set(varargin) 2 | % shortcut form for exp_set() 3 | res = exp_set(varargin{:}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/SetDelayed.m: -------------------------------------------------------------------------------- 1 | function res = SetDelayed(varargin) 2 | % shortcut form for exp_setdelayed() 3 | res = exp_setdelayed(varargin{:}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/Symbol.m: -------------------------------------------------------------------------------- 1 | function res = Symbol(varargin) 2 | % shortcut form for exp_symbol() 3 | res = exp_symbol(varargin{:}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/mandatory.m: -------------------------------------------------------------------------------- 1 | function res = mandatory 2 | % Special keyword (constant function) that can be used in arg*() specifications. 3 | % Used for the default values of arguments that must be specified by the caller. 4 | % 5 | % See also: 6 | % arg_define 7 | 8 | res = '__arg_mandatory__'; 9 | -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/search.m: -------------------------------------------------------------------------------- 1 | function res = search(varargin) 2 | % Special keyword to declare parameter values to search over. 3 | % search(x,y,z,...) or search([x,y,z,....]) or search({x,y,z,...}) expresses 4 | % a parameter range (i.e. set of possible parameter values, to be searched for) in a grid search. 5 | % 6 | % Note: 7 | % search() may also be nested inside a data structure, to indicate that all instances of that data structure, 8 | % with each instances having one of the specified values substituted in it, shall be searched. 9 | % 10 | % search() returns an expression data structure that encapsulates the specifies search range, 11 | % for use as argument to utl_gridsearch, utl_searchmodel, utl_nested_crossval, etc. 12 | % 13 | % See also: 14 | % utl_gridsearch, utl_searchmodel, utl_nested_crossval 15 | % 16 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 17 | % 2010-04-22 18 | 19 | 20 | if length(varargin) == 1 21 | if iscell(varargin{1}) 22 | varargin = varargin{1}; 23 | elseif isnumeric(varargin{1}) 24 | varargin = num2cell(varargin{1}); 25 | end 26 | end 27 | 28 | res = struct('head',{@search},'parts',{varargin}); -------------------------------------------------------------------------------- /external/bcilab_partial/keywords/unassigned.m: -------------------------------------------------------------------------------- 1 | function res = unassigned 2 | % Special keyword that can be used in arg*() specifications. 3 | % Used for the default values of arguments that do not show up in the function's workspace (or the GUI) unless explicitly assigned 4 | % 5 | % See also: 6 | % arg_define 7 | 8 | res = '__arg_unassigned__'; -------------------------------------------------------------------------------- /external/bcilab_partial/queries/check_1d_distributed.m: -------------------------------------------------------------------------------- 1 | function x = check_1d_distributed(x) 2 | standard_distributions = {'bino','chi2','exp','ev','f','gam','gev','gp','geo','hyge','logn','nbin','ncf','nct','ncx2','norm', 'poiss','rayl','t','unif','unid','wbl'}; 3 | x = is_1d_distributed(x) && any(strcmp(x{1},standard_distributions)) && isnumeric(x{2}); 4 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/check_discrete.m: -------------------------------------------------------------------------------- 1 | function x = check_discrete(x) 2 | x = is_discrete(x) && ischar(x{1}) && strcmp(x{1},'disc') && isnumeric(x{2}) && isnumeric(x{3}) && size(x{2},2) == size(x{3},1); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/get_function_symbol.m: -------------------------------------------------------------------------------- 1 | function result___ = get_function_symbol(expression___) 2 | % internal: some function_handle expressions have a function symbol (an @name expression), and this function obtains it 3 | 4 | % note: we are using funny names here to bypass potential name conflicts within the eval() clause further below 5 | if ~isa(expression___,'function_handle') 6 | error('the expression has no associated function symbol.'); end 7 | 8 | string___ = char(expression___); 9 | if string___(1) == '@' 10 | % we are dealing with a lambda function 11 | if is_symbolic_lambda(expression___) 12 | result___ = eval(string___(27:end-21)); 13 | else 14 | error('cannot derive a function symbol from a non-symbolic lambda function.'); 15 | end 16 | else 17 | % we are dealing with a regular function handle 18 | result___ = expression___; 19 | end -------------------------------------------------------------------------------- /external/bcilab_partial/queries/has_canonical_representation.m: -------------------------------------------------------------------------------- 1 | function res = has_canonical_representation(x) 2 | % determine whether an expression is represented as a struct with the fields 'head' and 'parts'. 3 | res = all(isfield(x,{'head','parts'})); 4 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/has_function_symbol.m: -------------------------------------------------------------------------------- 1 | function res = has_function_symbol(x) 2 | % internal: a function_handle from which we can obtain a function symbol: every function handle except for non-symbolic lambdas. 3 | res = isa(x,'function_handle') && (isempty(strmatch('@',char(x))) || is_symbolic_lambda(x)); 4 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_1d_distributed.m: -------------------------------------------------------------------------------- 1 | function x = is_1d_distributed(x) 2 | x = iscell(x) && length(x) == 2 && ischar(x{1}) && isnumeric(x{2}); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_1d_regression.m: -------------------------------------------------------------------------------- 1 | function x = is_1d_regression(x) 2 | x = isnumeric(x) && size(x,2) == 1; 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_Nd_distributed.m: -------------------------------------------------------------------------------- 1 | function x = is_Nd_distributed(x) 2 | x = iscell(x) && length(x) == 2 && ischar(x{1}) && strcmp(x{1},'mvn') && iscell(x{2}); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_Nd_regression.m: -------------------------------------------------------------------------------- 1 | function x = is_Nd_regression(x) 2 | x = isnumeric(x) && size(x,2) > 1; 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_atom.m: -------------------------------------------------------------------------------- 1 | function res = is_atom(x) 2 | % Determine whether an expression can be further subdivided into parts 3 | % literal matlab expressions (including matrices, most structs, strings, function_handles) are considered atomic 4 | % 5 | % The exceptions are: 6 | % * struct with .head / .part fields (canonically represented expression) 7 | % * struct with .tracking.expression field (impure expression, i.e. expression with value) 8 | % 9 | % Notes: 10 | % in the future, more data structures may be made accessible to the expression system 11 | % 12 | % See also: 13 | % exp_eval, exp_head, exp_parts 14 | % 15 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 16 | % 2010-04-15 17 | 18 | if isfield(x,{'head','parts'}) 19 | res = true; 20 | elseif isfield(x,'tracking') && isfield(x.tracking,'expression') 21 | res = is_atom(x.tracking.expression); 22 | else 23 | res = false; 24 | end -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_builtin_function.m: -------------------------------------------------------------------------------- 1 | function res = is_builtin_function(x) 2 | % check if the given object is a valid handle to a builtin function 3 | res = isa(x,'function_handle') && exist(char(x),'builtin') && ~exist(char(x),'file'); -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_custom_distributed.m: -------------------------------------------------------------------------------- 1 | function x = is_custom_distributed(x) 2 | x = iscell(x) && length(x) == 2 && ischar(x{1}) && isa(x{1},'function_handle') && iscell(x{2}); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_dataset.m: -------------------------------------------------------------------------------- 1 | function res = is_dataset(x) 2 | % Determine whether some object is a data set. 3 | res = all(isfield(x,{'data','srate'})); 4 | 5 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_discrete.m: -------------------------------------------------------------------------------- 1 | function x = is_discrete(x) 2 | x = iscell(x) && length(x) == 3 && strcmp(x{1},'disc'); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_distributed.m: -------------------------------------------------------------------------------- 1 | function x = is_distributed(x) 2 | x = is_1d_distributed(x) || is_Nd_distributed(x) || is_discrete(x) || is_custom_distributed(x); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_evaluated.m: -------------------------------------------------------------------------------- 1 | function r = is_evaluated(x) 2 | % determine whether an expression can be taken as a fully evaluated MATLAB value 3 | % this holds for both impure expressions and literal expressions (almost all MATLAB data structures; see exp_eval for a detailed list) 4 | % it excludes: 5 | % * canonical expression structs (with the only fields being head and parts) 6 | % * undefined functions (which are not valid MATLAB values and serve as a shorthand notation for unevaluated symbols, e.g. @x) 7 | % * lambda functions which yield canonical expression structs when invoked (such as those lambdas created by exp_symbol or exp_declare) 8 | % 9 | % Notes: 10 | % Evaluated(x) := impure(x) || ~(canonical(x) || undefined(x) || symbolic_lambda(x)); 11 | % 12 | % See also: 13 | % exp_eval 14 | 15 | r = (isfield(x,'tracking') && isfield(x.tracking,'expression')) || ~( all(isfield(x,{'head','parts'})) || (isa(x,'function_handle') && (is_undefined_function(x) || ~isempty(regexp(char(x),'@\(varargin\)struct\(''head'',\{.*\},''parts'',\{varargin\}\)','once'))))); -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_gaussian.m: -------------------------------------------------------------------------------- 1 | function x = is_gaussian(x) 2 | x = iscell(x) && length(x) == 3 && strcmp(x{1},'norm'); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_impure_expression.m: -------------------------------------------------------------------------------- 1 | function res = is_impure_expression(x) 2 | % an impure expression is a MATLAB structure with a .tracking.expression field 3 | res = isfield(x,'tracking') && isfield(x.tracking,'expression'); -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_needing_search.m: -------------------------------------------------------------------------------- 1 | function res = is_needing_search(argform,args) 2 | % test whether some argument pack requires a search or not (according to the specified argument format) 3 | 4 | if strcmp(argform,'direct') 5 | % a search is specified by multielement arguments 6 | res = prod(max(1,cellfun(@length,args))) > 1; 7 | elseif strcmp(argform,'clauses') 8 | % a search is specified by (possibly nested) search clauses 9 | res = contains_search(args); 10 | else 11 | error('unsupported argument form.'); 12 | end 13 | 14 | % test whether the given data structure contains a search clause 15 | function res = contains_search(x) 16 | if has_canonical_representation(x) && isequal(x.head,@search) 17 | res = true; 18 | elseif iscell(x) 19 | res = any(cellfun(@contains_search,x)); 20 | elseif isstruct(x) && numel(x) == 1 21 | res = contains_search(struct2cell(x)); 22 | else 23 | res = false; 24 | end -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_point.m: -------------------------------------------------------------------------------- 1 | function x = is_point(x) 2 | x = is_1d_regression(x) || is_Nd_regression(x); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_pure_expression.m: -------------------------------------------------------------------------------- 1 | function res = is_pure_expression(x) 2 | % a pure expression is anything except for impure expressions 3 | res = ~is_impure_expression(x); -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_raw_dataset.m: -------------------------------------------------------------------------------- 1 | % determine whether some object is a raw EEGLAB data set with no BCILAB constituents 2 | function res = is_raw_dataset(x) 3 | res = all(isfield(x,{'data','srate'})) && ~isfield(x,'tracking'); 4 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_search.m: -------------------------------------------------------------------------------- 1 | function x = is_search(x) 2 | % Determine whether some object is a search() expression. 3 | x = all(isfield(x,{'head','parts'})) && numel(x)==1 && strcmp(char(x.head),'search'); 4 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_stateful.m: -------------------------------------------------------------------------------- 1 | function r = is_stateful(f,varargin) 2 | % check whether a filter function is stateful (for some arguments) 3 | % stateful filter functions are characterized by a second output 4 | 5 | nout = nargout(f); 6 | if nout >= 0 7 | % usually, nargout tells us this 8 | r = nout > 1; 9 | else 10 | % but in some cases (e.g., when the function is wrapped by a lambda), we must look more closely 11 | try 12 | [a,b] = f(varargin{:}); %#ok 13 | r = true; 14 | catch e 15 | r = ~any(strcmp(e.identifier,{'MATLAB:TooManyOutputs','MATLAB:maxlhs'})); 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_structured.m: -------------------------------------------------------------------------------- 1 | function x = is_structured(x) 2 | x = iscell(x) && length(x) == 2 && ischar(x{1}) && strcmp(x{1},'struct') && iscell(x{2}); 3 | -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_symbol.m: -------------------------------------------------------------------------------- 1 | function res = is_symbol(x) 2 | % check whether an expression is a symbol 3 | res = isequal(exp_head(x),@Symbol); -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_symbolic_lambda.m: -------------------------------------------------------------------------------- 1 | function res = is_symbolic_lambda(x) 2 | % internal: a symbolic lambda function is one which generates expressions when invoked with arguments (this is what exp_symbol generates) 3 | res = isa(x,'function_handle') && ~isempty(regexp(char(x),'@\(varargin\)struct\(''head'',\{.*\},''parts'',\{varargin\}\)','once')); -------------------------------------------------------------------------------- /external/bcilab_partial/queries/is_undefined_function.m: -------------------------------------------------------------------------------- 1 | function res = is_undefined_function(exp) 2 | % test if a given function handle has no associated code (i.e. it is neither a lambda nor a reference to a known m-file) 3 | res = false; 4 | cexp = char(exp); 5 | if cexp(1) ~= '@' && ~exist(cexp,'builtin') 6 | try 7 | % this section is a performance optimization due to the lack of a function exist(...,'mfileinpath'); the code is correct in all cases. 8 | % * for undefined functions, this line yields immediately a MATLAB:UndefinedFunction exception 9 | % * for all other functions, this line either yields, in almost all cases (excluding varargin+vararout functions), 10 | % immediately a 'MATLAB:TooManyOutputs' or 'MATLAB:TooManyInputs' (and the like) exception 11 | % or in the remaining cases either some exception further into the function's code or it succeeds. 12 | z=@someuncommontype; 13 | [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,t,u,v,w,x,y] = exp(z,z,z,z,z,z,z,z,z,z,z,z,z,z,z,z,z,z,z,z); %#ok 14 | catch e 15 | % side note: below we make sure that the UndefinedFunction error is generated here and not deeper into a potentially defined exp()'s code 16 | res = strcmp(e.identifier,'MATLAB:UndefinedFunction') && strcmp(e.stack(1).name,mfilename); 17 | end 18 | end -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/CrossSpecMatc.m: -------------------------------------------------------------------------------- 1 | function [Sc,Cmat,Ctot,Cvec,Cent,f]=CrossSpecMatc(data,win,params) 2 | % Multi-taper cross-spectral matrix - another routine, allows for multiple trials and channels 3 | % Does not do confidence intervals. Also this routine always averages over trials - continuous process 4 | % 5 | % Usage: 6 | % 7 | % [Sc,Cmat,Ctot,Cvec,Cent,f]=CrossSpecMatc(data,win,params) 8 | % Input: 9 | % Note units have to be consistent. See chronux.m for more information. 10 | % data (in form samples x channels x trials) 11 | % win (duration of non-overlapping window) 12 | % params: structure with fields tapers, pad, Fs, fpass 13 | % - optional 14 | % tapers : precalculated tapers from dpss or in the one of the following 15 | % forms: 16 | % (1) A numeric vector [TW K] where TW is the 17 | % time-bandwidth product and K is the number of 18 | % tapers to be used (less than or equal to 19 | % 2TW-1). 20 | % (2) A numeric vector [W T p] where W is the 21 | % bandwidth, T is the duration of the data and p 22 | % is an integer such that 2TW-p tapers are used. In 23 | % this form there is no default i.e. to specify 24 | % the bandwidth, you have to specify T and p as 25 | % well. Note that the units of W and T have to be 26 | % consistent: if W is in Hz, T must be in seconds 27 | % and vice versa. Note that these units must also 28 | % be consistent with the units of params.Fs: W can 29 | % be in Hz if and only if params.Fs is in Hz. 30 | % The default is to use form 1 with TW=3 and K=5 31 | % 32 | % pad (padding factor for the FFT) - optional. Defaults to 0. 33 | % e.g. For N = 500, if PAD = 0, we pad the FFT 34 | % to 512 points; if PAD = 2, we pad the FFT 35 | % to 2048 points, etc. 36 | % Fs (sampling frequency) - optional. Default 1. 37 | % fpass (frequency band to be used in the calculation in the form 38 | % [fmin fmax])- optional. 39 | % Default all frequencies between 0 and Fs/2 40 | % Output: 41 | % Sc (cross spectral matrix frequency x channels x channels) 42 | % Cmat Coherence matrix frequency x channels x channels 43 | % Ctot Total coherence: SV(1)^2/sum(SV^2) (frequency) 44 | % Cvec leading Eigenvector (frequency x channels) 45 | % Cent A different measure of total coherence: GM/AM of SV^2s 46 | % f (frequencies) 47 | d=ndims(data); 48 | if d<2, error('Need multidimensional array'); end 49 | if d==2, [N,C]=size(data); end; 50 | if d==3, [N,C,Ntr]=size(data); end; 51 | if nargin < 3; params=[]; end; 52 | [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params); 53 | clear err trialave params 54 | nwin=round(win*Fs); nfft=max(2^(nextpow2(nwin)+pad),nwin); 55 | [f,findx]=getfgrid(Fs,nfft,fpass); 56 | tapers=dpsschk(tapers,nwin,Fs); % check tapers 57 | Sc=zeros(length(findx),C,C); 58 | 59 | Nwins=floor(N/nwin); 60 | 61 | if d==3, % If there are multiple trials 62 | for iwin=1:Nwins, 63 | for i=1:Ntr, 64 | data1=squeeze(data(1+(iwin-1)*nwin:iwin*nwin,:,i)); 65 | J1=mtfftc(detrend(data1),tapers,nfft,Fs); 66 | J1=J1(findx,:,:); 67 | for k=1:C, 68 | for l=1:C, 69 | spec=squeeze(mean(conj(J1(:,:,k)).*J1(:,:,l),2)); 70 | Sc(:,k,l)=Sc(:,k,l)+spec; 71 | end 72 | end 73 | end 74 | end 75 | Sc=Sc/(Nwins*Ntr); 76 | end 77 | 78 | if d==2, % only one trial 79 | for iwin=1:Nwins, 80 | data1=squeeze(data(1+(iwin-1)*nwin:iwin*nwin,:)); 81 | J1=mtfftc(data1,tapers,nfft,Fs); 82 | J1=J1(findx,:,:); 83 | for k=1:C, 84 | for l=1:C, 85 | Sc(:,k,l)=Sc(:,k,l)+squeeze(mean(conj(J1(:,:,k)).*J1(:,:,l),2)); 86 | end 87 | end 88 | end 89 | Sc=Sc/Nwins; 90 | end 91 | 92 | Cmat=Sc; 93 | Sdiag=zeros(length(findx),C); 94 | for k=1:C, 95 | Sdiag(:,k)=squeeze(Sc(:,k,k)); 96 | end 97 | 98 | for k=1:C, 99 | for l=1:C, 100 | Cmat(:,k,l)=Sc(:,k,l)./sqrt(abs(Sdiag(:,k).*Sdiag(:,l))); 101 | end 102 | end 103 | 104 | Ctot=zeros(length(findx),1); Cent=Ctot; 105 | Cvec=zeros(length(findx),C); 106 | for i=1:length(findx), 107 | [u s]=svd(squeeze(Sc(i,:,:)));s=diag(s); 108 | Ctot(i)=s(1).^2/sum(s.^2); Cent(i)=exp(mean(log(s.^2)))/mean(s.^2); 109 | Cvec(i,:)=transpose(u(:,1)); 110 | end 111 | 112 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/chron_findpeaks.m: -------------------------------------------------------------------------------- 1 | function xmax=chron_findpeaks(data,threshold) 2 | % Helper function to find peaks in a given continuous valued time series x 3 | % Usage: xmax=chron_findpeaks(data,threshold) 4 | % Input: 5 | % data (data in time x channels/trials form or a single vector) 6 | % threshold (if specified returns locations of peaks at which data exceeds threshold) - optional 7 | % Output: 8 | % xmax (locations of local maxima of data in a structure array of dimensions channels/trials) 9 | if nargin < 1; error('Need data'); end; 10 | data=change_row_to_column(data); 11 | C=size(data,2); 12 | pp1=[data(1,:);data(1:end-1,:)]; 13 | pp2=[data(2:end,:);data(end,:)]; 14 | xmax(1:C)=struct('loc',[]); 15 | for ch=1:C, 16 | if nargin ==1 17 | xmax(ch).loc=[xmax(ch).loc; find(data(:,ch)-pp1(:,ch)>0 & data(:,ch)-pp2(:,ch)>0)]; 18 | else 19 | xmax(ch).loc=[xmax(ch).loc; find(data(:,ch)-pp1(:,ch)>0 & data(:,ch)-pp2(:,ch)>0 & data(:,ch)>threshold)]; 20 | end 21 | end -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/cohmatrixc.m: -------------------------------------------------------------------------------- 1 | function [C,phi,S12,f,confC,phistd,Cerr]=cohmatrixc(data,params) 2 | % Multi-taper coherency,cross-spectral matrix - continuous process 3 | % 4 | % Usage: 5 | % 6 | % [C,phi,S12,f,confC,phistd,Cerr]=cohmatrixc(data,params) 7 | % Input: 8 | % Note units have to be consistent. See chronux.m for more information. 9 | % data (in form samples x channels) -- required 10 | % params: structure with fields tapers, pad, Fs, fpass, err 11 | % - optional 12 | % tapers : precalculated tapers from dpss or in the one of the following 13 | % forms: 14 | % (1) A numeric vector [TW K] where TW is the 15 | % time-bandwidth product and K is the number of 16 | % tapers to be used (less than or equal to 17 | % 2TW-1). 18 | % (2) A numeric vector [W T p] where W is the 19 | % bandwidth, T is the duration of the data and p 20 | % is an integer such that 2TW-p tapers are used. In 21 | % this form there is no default i.e. to specify 22 | % the bandwidth, you have to specify T and p as 23 | % well. Note that the units of W and T have to be 24 | % consistent: if W is in Hz, T must be in seconds 25 | % and vice versa. Note that these units must also 26 | % be consistent with the units of params.Fs: W can 27 | % be in Hz if and only if params.Fs is in Hz. 28 | % The default is to use form 1 with TW=3 and K=5 29 | % 30 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 31 | % -1 corresponds to no padding, 0 corresponds to padding 32 | % to the next highest power of 2 etc. 33 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 34 | % to 512 points, if pad=1, we pad to 1024 points etc. 35 | % Defaults to 0. 36 | % Fs (sampling frequency) - optional. Default 1. 37 | % fpass (frequency band to be used in the calculation in the form 38 | % [fmin fmax])- optional. 39 | % Default all frequencies between 0 and Fs/2 40 | % err (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars 41 | % [0 p] or 0 - no error bars) - optional. Default 0. 42 | % Output: 43 | % C (magnitude of coherency frequency x channels x channels) 44 | % phi (phase of coherency frequency x channels x channels) 45 | % S12 (cross-spectral matrix frequency x channels x channels) 46 | % f (frequencies) 47 | % confC (confidence level for C at 1-p %) - only for err(1)>=1 48 | % phistd - theoretical/jackknife (depending on err(1)=1/err(1)=2) standard deviation for phi 49 | % Note that phi + 2 phistd and phi - 2 phistd will give 95% confidence 50 | % bands for phi - only for err(1)>=1 51 | % Cerr (Jackknife error bars for C - use only for Jackknife - err(1)=2) 52 | 53 | if nargin < 1; error('need data'); end; 54 | if nargin < 2; params=[]; end; 55 | [N,Ch]=size(data); 56 | if Ch==1; error('Need at least two channels of data'); end; 57 | [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params); 58 | clear trialave params 59 | if nargout > 6 && err(1)~=2; 60 | error('Cerr computed only for Jackknife. Correct inputs and run again'); 61 | end; 62 | if nargout >= 4 && err(1)==0; 63 | % Errors computed only if err(1) is nonzero. Need to change params and run again. 64 | error('When errors are desired, err(1) has to be non-zero.'); 65 | end; 66 | nfft=max(2^(nextpow2(N)+pad),N); 67 | [f,findx]=getfgrid(Fs,nfft,fpass); 68 | tapers=dpsschk(tapers,N,Fs); % check tapers 69 | J=mtfftc(data,tapers,nfft,Fs); 70 | J=J(findx,:,:); 71 | if err(1)==0; 72 | [C,phi,S12]=cohmathelper(J,err); 73 | elseif err(1)==1; 74 | [C,phi,S12,confC,phistd]=cohmathelper(J,err); 75 | elseif err(1)==2; 76 | [C,phi,S12,confC,phistd,Cerr]=cohmathelper(J,err); 77 | end 78 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/createdatamatc.m: -------------------------------------------------------------------------------- 1 | function data=createdatamatc(data,E,Fs,win) 2 | % Helper function to create an event triggered matrix from univariate 3 | % continuous data 4 | % Usage: data=createdatamatc(data,E,Fs,win) 5 | % Inputs: 6 | % data (input time series as a column vector) - required 7 | % E (events to use as triggers) - required 8 | % Fs (sampling frequency of data) - required 9 | % win (window around triggers to use data matrix -[winl winr]) - required 10 | % e.g [1 1] uses a window starting 1 * Fs samples before E and 11 | % ending 1*Fs samples after E. 12 | % Note that E, Fs, and win must have consistent units 13 | % 14 | % Outputs: 15 | % data (event triggered data) 16 | % 17 | if nargin < 4; error('Need all arguments'); end; 18 | NE=length(E); 19 | nwinl=round(win(1)*Fs); 20 | nwinr=round(win(2)*Fs); 21 | nE=floor(E*Fs)+1; 22 | datatmp=[]; 23 | for n=1:NE; 24 | indx=nE(n)-nwinl:nE(n)+nwinr-1; 25 | datatmp=[datatmp data(indx)]; 26 | end 27 | data=datatmp; -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/evoked.m: -------------------------------------------------------------------------------- 1 | function [V,t,Err] = evoked(data,Fs,win,width,plt,err) 2 | % Function to calculate the evoked response given continuous data in the 3 | % form time x channels 4 | % Usage [V,t,Err] = evoked(data,Fs,win,width,plt,err) 5 | % 6 | % Inputs 7 | % Note that all times can be in arbitrary units. But the units have to be 8 | % consistent. So, if win is in secs, width is in secs and Fs has to be Hz. 9 | % If win is in samples, so is width and Fs=1. 10 | % 11 | % data(times, channels/trials or a single vector) (required) 12 | % Fs sampling frequency (required) 13 | % win subsection of data to be used. Default all available data 14 | % width (s) of smoothing kernel. Default 50 samples 15 | % plt plot 'n' for no plot, otherwise plot color. Default blue colored lines. 16 | % err = 0/1. Default 1=calculate bootstrap errorbars. 17 | % 18 | % Outputs 19 | % V = evoked potential 20 | % t = times of evaluation 21 | % Err = bootstrap statdard deviation 22 | 23 | if nargin < 2;error('Data, sampling frequency required');end 24 | data=change_row_to_column(data); 25 | N=size(data,1); 26 | data=data'; 27 | if nargin <3; win = [0 (N-1)/Fs];end 28 | if nargin <4; width = 50/Fs;end 29 | if nargin <5; plt = 'b';end 30 | if nargin <6;err = 1;end 31 | T=win; 32 | if isempty(T); T = [0 (N-1)/Fs];end 33 | if isempty(width); width = 50/Fs;end 34 | if isempty(plt); plt = 'b';end 35 | if isempty(err);err = 1;end 36 | 37 | t = min(T):1/Fs:max(T); 38 | if nargin >= 5 39 | indx = find(t>T(1) & t (t(length(t))-t(1))/2 45 | disp('Width is too large for data segment: should be in seconds') 46 | disp('Turn off smoothing') 47 | width = 0; 48 | end 49 | 50 | s = t(2)-t(1); 51 | N = fix(width/s); 52 | NT = length(data(:,1)); 53 | 54 | if NT > 1 55 | mdata = mean(data); 56 | else 57 | mdata = data; 58 | end 59 | if N > 4 60 | smdata = locsmooth(mdata,N,fix(N/2)); 61 | else 62 | smdata = mdata; 63 | end 64 | 65 | % if errorbars requested then do a bootstrap over trials... 66 | 67 | Err = 0; 68 | if NT < 4; 69 | disp('Too few trials: no errorbars calculated') 70 | err = 0; 71 | end 72 | 73 | if err ~= 0 && NT > 1 74 | Nboot = 10; 75 | bevk = 0; 76 | sevk = 0; 77 | for b=1:Nboot 78 | indx = floor(NT*rand(1,NT)) + 1; 79 | evktmp = mean(data(indx,:)); 80 | if N > 4 81 | evktmp = locsmooth(evktmp,N,fix(N/2)); 82 | end 83 | bevk = bevk + evktmp; 84 | sevk = sevk + evktmp.^2; 85 | end 86 | stdevk = sqrt((sevk/Nboot - bevk.^2/Nboot^2)); 87 | Err = stdevk; 88 | end 89 | 90 | V = smdata; 91 | if plt ~= 'n' 92 | plot(t,smdata,plt) 93 | hold on 94 | mn = mean(smdata); 95 | ax = get(gca,'xlim'); 96 | line(ax,mn*[1 1],'color','k') 97 | if err 98 | line(ax,(mn+2*mean(stdevk))*[1 1],'color','r') 99 | line(ax,(mn-2*mean(stdevk))*[1 1],'color','r') 100 | hold off 101 | end 102 | end 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/extractdatac.m: -------------------------------------------------------------------------------- 1 | function data=extractdatac(data,Fs,t) 2 | % Extract segements of continuous data between t(1) and t(2) 3 | % Usage: data=extractdatac(data,Fs,t) 4 | % 5 | % Input: 6 | % data: continous data in the form samples x channels or a single vector 7 | % Fs: sampling frequency 8 | % t : time as a 2d vector [t(1) t(2)] 9 | % Note that sampling frequency and t have to be in consistent units 10 | % Output: 11 | % data: data between t(1) and t(2) 12 | 13 | if nargin < 3; 14 | error('need all three arguments'); 15 | end; 16 | if t(1) < 0 || t(2)<=t(1); 17 | error('times cannot be negative and t(2) has to greater than t(1)'); 18 | end; 19 | data=change_row_to_column(data); 20 | N=size(data,1); 21 | tt=(0:N-1)/Fs; 22 | indx=find(tt>=t(1) & ttTw; error('Use step size shorter than window size'); end; 21 | n=round(Fs*Tw); 22 | dn=round(Fs*Ts); 23 | if ~isreal(data) 24 | yr=real(data); 25 | yi=imag(data); 26 | if n==N; 27 | yr=detrend(yr); 28 | yi=detrend(yi); 29 | data=yr+i*yi; 30 | else; 31 | for ch=1:C 32 | tmp=runline(yr(:,ch),n,dn); 33 | yr=yr-tmp; 34 | tmp=runline(yi(:,ch),n,dn); 35 | yi=yi-tmp; 36 | data(:,ch)=yr+i*yi; 37 | end; 38 | end; 39 | else 40 | if n==N; 41 | data=detrend(data); 42 | else; 43 | for ch=1:C; 44 | tmp=runline(data(:,ch),n,dn); 45 | data(:,ch)=data(:,ch)-tmp; 46 | end; 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/locsmooth.m: -------------------------------------------------------------------------------- 1 | function data=locsmooth(data,Fs,Tw,Ts) 2 | % Running line fit (using local linear regression) - 1d only, continuous 3 | % processes 4 | % Usage: data=locsmooth(data,Fs,Tw,Ts) 5 | % Inputs: 6 | % Note that units of Fs, movinwin have to be consistent. 7 | % data (single vector) 8 | % Fs (sampling frequency) - optional. Default 1 9 | % Tw (length of moving window) - optional. Default. full length of data (global detrend) 10 | % Ts (step size) - optional. Default Tw/2. 11 | % 12 | % Output: 13 | % data (locally smoothed data). 14 | data=change_row_to_column(data); 15 | N=size(data,1); 16 | if nargin < 2; Fs=1; end; 17 | if nargin < 3; Tw=N/Fs; end; 18 | if nargin < 4; Ts=Tw/2; end; 19 | 20 | n=round(Fs*Tw); 21 | dn=round(Fs*Ts); 22 | if ~isreal(data) 23 | yr=real(data); 24 | yi=imag(data); 25 | tmp=runline(yr,n,dn); 26 | yr=tmp'; 27 | tmp=runline(yi,n,dn); 28 | yi=tmp'; 29 | data=yr+i*yi; 30 | else 31 | tmp=runline(data,n,dn); 32 | data=tmp'; 33 | end 34 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/mtdspecgramc.m: -------------------------------------------------------------------------------- 1 | function [dS,t,f]=mtdspecgramc(data,movingwin,phi,params) 2 | % Multi-taper derivative of the time-frequency spectrum - continuous process 3 | % 4 | % Usage: 5 | % 6 | % [dS,t,f]=mtdspecgramc(data,movingwin,phi,params) 7 | % Input: 8 | % Note that all times can be in arbitrary units. But the units have to be 9 | % consistent. So, if E is in secs, win, t have to be in secs, and Fs has to 10 | % be Hz. If E is in samples, so are win and t, and Fs=1. In case of spike 11 | % times, the units have to be consistent with the units of data as well. 12 | % 13 | % data (in form samples x channels/trials or a single vector) -- required 14 | % movingwin (in the form [window winstep] i.e length of moving 15 | % window and step size. 16 | % Note that units here have 17 | % to be consistent with 18 | % units of Fs - required 19 | % phi (angle for evaluation of derivative) -- required 20 | % e.g. phi=[0,pi/2] giving the time and frequency 21 | % derivatives 22 | % params: structure with fields tapers, pad, Fs, fpass, trialave 23 | % -optional 24 | % tapers : precalculated tapers from dpss or in the one of the following 25 | % forms: 26 | % (1) A numeric vector [TW K] where TW is the 27 | % time-bandwidth product and K is the number of 28 | % tapers to be used (less than or equal to 29 | % 2TW-1). 30 | % (2) A numeric vector [W T p] where W is the 31 | % bandwidth, T is the duration of the data and p 32 | % is an integer such that 2TW-p tapers are used. In 33 | % this form there is no default i.e. to specify 34 | % the bandwidth, you have to specify T and p as 35 | % well. Note that the units of W and T have to be 36 | % consistent: if W is in Hz, T must be in seconds 37 | % and vice versa. Note that these units must also 38 | % be consistent with the units of params.Fs: W can 39 | % be in Hz if and only if params.Fs is in Hz. 40 | % The default is to use form 1 with TW=3 and K=5 41 | % Note that T has to be equal to movingwin(1). 42 | % 43 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 44 | % -1 corresponds to no padding, 0 corresponds to padding 45 | % to the next highest power of 2 etc. 46 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 47 | % to 512 points, if pad=1, we pad to 1024 points etc. 48 | % Defaults to 0. 49 | % Fs (sampling frequency) - optional. Default 1. 50 | % fpass (frequency band to be used in the calculation in the form 51 | % [fmin fmax])- optional. 52 | % Default all frequencies between 0 and Fs/2 53 | % trialave - (average over trials/channels when 1, don't average when 0) - optional. Default 0 54 | % Output: 55 | % dS (spectral derivative in form phi x time x frequency x channels/trials if trialave=0; 56 | % in form phi x time x frequency if trialave=1) 57 | % t (times) 58 | % f (frequencies) 59 | 60 | if nargin < 3; error('Need data, window parameters and angle'); end; 61 | if nargin < 4; params=[]; end; 62 | 63 | if length(params.tapers)==3 & movingwin(1)~=params.tapers(2); 64 | error('Duration of data in params.tapers is inconsistent with movingwin(1), modify params.tapers(2) to proceed') 65 | end 66 | 67 | [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params); 68 | clear err 69 | data=change_row_to_column(data); 70 | [N,C]=size(data); 71 | Nwin=round(Fs*movingwin(1)); % number of samples in window 72 | Nstep=round(movingwin(2)*Fs); % number of samples to step through 73 | nfft=max(2^(nextpow2(Nwin)+pad),Nwin); 74 | f=getfgrid(Fs,nfft,fpass); Nf=length(f); 75 | params.tapers=dpsschk(tapers,Nwin,Fs); % check tapers 76 | params.tapers=tapers; 77 | winstart=1:Nstep:N-Nwin+1; 78 | nw=length(winstart); 79 | if trialave==0; dS=zeros(length(phi),nw,Nf,C); else dS=zeros(length(phi),nw,Nf); end; 80 | for n=1:nw; 81 | indx=winstart(n):winstart(n)+Nwin-1; 82 | datawin=data(indx,:); 83 | [ds,f]=mtdspectrumc(datawin,phi,params); 84 | dS(:,n,:,:)=ds; 85 | end; 86 | dS=squeeze(dS); 87 | sz=size(dS); 88 | % if length(sz)==3; 89 | % dS=permute(dS,[2 1 3 4]); 90 | % elseif length(phi)>1 91 | % dS=permute(dS,[2 1 3]); 92 | % end; 93 | winmid=winstart+round(Nwin/2); 94 | t=winmid/Fs; 95 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/mtdspectrumc.m: -------------------------------------------------------------------------------- 1 | function [dS,f]=mtdspectrumc(data,phi,params) 2 | % Multi-taper frequency derivative of the spectrum - continuous process 3 | % 4 | % Usage: 5 | % 6 | % [dS,f]=mtdspectrumc(data,phi,params) 7 | % Input: 8 | % Note that all times can be in arbitrary units. But the units have to be 9 | % consistent. So, if E is in secs, win, t have to be in secs, and Fs has to 10 | % be Hz. If E is in samples, so are win and t, and Fs=1. In case of spike 11 | % times, the units have to be consistent with the units of data as well. 12 | % data (in form samples x channels/trials or a single vector) -- required 13 | % phi (angle for evaluation of derivative) -- required. 14 | % e.g. phi=[0,pi/2] gives the time and frequency derivatives 15 | % params: structure with fields tapers, pad, Fs, fpass, trialave 16 | % - optional 17 | % tapers : precalculated tapers from dpss or in the one of the following 18 | % forms: 19 | % (1) A numeric vector [TW K] where TW is the 20 | % time-bandwidth product and K is the number of 21 | % tapers to be used (less than or equal to 22 | % 2TW-1). 23 | % (2) A numeric vector [W T p] where W is the 24 | % bandwidth, T is the duration of the data and p 25 | % is an integer such that 2TW-p tapers are used. In 26 | % this form there is no default i.e. to specify 27 | % the bandwidth, you have to specify T and p as 28 | % well. Note that the units of W and T have to be 29 | % consistent: if W is in Hz, T must be in seconds 30 | % and vice versa. Note that these units must also 31 | % be consistent with the units of params.Fs: W can 32 | % be in Hz if and only if params.Fs is in Hz. 33 | % The default is to use form 1 with TW=3 and K=5 34 | % 35 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 36 | % -1 corresponds to no padding, 0 corresponds to padding 37 | % to the next highest power of 2 etc. 38 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 39 | % to 512 points, if pad=1, we pad to 1024 points etc. 40 | % Defaults to 0. 41 | % Fs (sampling frequency) - optional. Default 1. 42 | % fpass (frequency band to be used in the calculation in the form 43 | % [fmin fmax])- optional. 44 | % Default all frequencies between 0 and Fs/2 45 | % trialave (average over trials/channels when 1, don't average when 0) - optional. Default 0 46 | % Output: 47 | % dS (spectral derivative in form phi x frequency x channels/trials if trialave=0 or 48 | % in form phi x frequency if trialave=1) 49 | % f (frequencies) 50 | 51 | if nargin < 2; error('Need data and angle'); end; 52 | if nargin < 3; params=[]; end; 53 | [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params); 54 | clear err params 55 | data=change_row_to_column(data); 56 | N=size(data,1); 57 | nfft=max(2^(nextpow2(N)+pad),N); 58 | [f,findx]=getfgrid(Fs,nfft,fpass); 59 | tapers=dpsschk(tapers,N,Fs); % check tapers 60 | K=size(tapers,2); 61 | J=mtfftc(data,tapers,nfft,Fs); 62 | J=J(findx,:,:); 63 | A=sqrt(1:K-1); 64 | A=repmat(A,[size(J,1) 1]); 65 | A=repmat(A,[1 1 size(J,3)]); 66 | S=squeeze(mean(J(:,1:K-1,:).*A.*conj(J(:,2:K,:)),2)); 67 | if trialave; S=squeeze(mean(S,2));end; 68 | nphi=length(phi); 69 | for p=1:nphi; 70 | dS(p,:,:)=real(exp(i*phi(p))*S); 71 | end; 72 | dS=squeeze(dS); 73 | dS=change_row_to_column(dS); 74 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/mtfftc.m: -------------------------------------------------------------------------------- 1 | function J=mtfftc(data,tapers,nfft,Fs) 2 | % Multi-taper fourier transform - continuous data 3 | % 4 | % Usage: 5 | % J=mtfftc(data,tapers,nfft,Fs) - all arguments required 6 | % Input: 7 | % data (in form samples x channels/trials or a single vector) 8 | % tapers (precalculated tapers from dpss) 9 | % nfft (length of padded data) 10 | % Fs (sampling frequency) 11 | % 12 | % Output: 13 | % J (fft in form frequency index x taper index x channels/trials) 14 | if nargin < 4; error('Need all input arguments'); end; 15 | data=change_row_to_column(data); 16 | [NC,C]=size(data); % size of data 17 | [NK K]=size(tapers); % size of tapers 18 | if NK~=NC; error('length of tapers is incompatible with length of data'); end; 19 | tapers=tapers(:,:,ones(1,C)); % add channel indices to tapers 20 | data=data(:,:,ones(1,K)); % add taper indices to data 21 | data=permute(data,[1 3 2]); % reshape data to get dimensions to match those of tapers 22 | data_proj=data.*tapers; % product of data with tapers 23 | J=fft(data_proj,nfft)/Fs; % fft of projected data 24 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/mtpowerandfstatc.m: -------------------------------------------------------------------------------- 1 | function [P,Fstat,f0]=mtpowerandfstatc(data,params,f0) 2 | % Multi-taper computation of the power and the fstatistic for a particular frequency - continuous process 3 | % 4 | % Usage: 5 | % 6 | % [P,Fstat,f0]=mtpowerandfstatc(data,params,f0) 7 | % Input: 8 | % Note units have to be consistent. See chronux.m for more information. 9 | % data (in form samples x channels/trials or a single vector) -- required 10 | % params: structure with fields tapers, pad, Fs, fpass, err, trialave 11 | % -optional 12 | % tapers : precalculated tapers from dpss or in the one of the following 13 | % forms: 14 | % (1) A numeric vector [TW K] where TW is the 15 | % time-bandwidth product and K is the number of 16 | % tapers to be used (less than or equal to 17 | % 2TW-1). 18 | % (2) A numeric vector [W T p] where W is the 19 | % bandwidth, T is the duration of the data and p 20 | % is an integer such that 2TW-p tapers are used. In 21 | % this form there is no default i.e. to specify 22 | % the bandwidth, you have to specify T and p as 23 | % well. Note that the units of W and T have to be 24 | % consistent: if W is in Hz, T must be in seconds 25 | % and vice versa. Note that these units must also 26 | % be consistent with the units of params.Fs: W can 27 | % be in Hz if and only if params.Fs is in Hz. 28 | % The default is to use form 1 with TW=3 and K=5 29 | % 30 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 31 | % -1 corresponds to no padding, 0 corresponds to padding 32 | % to the next highest power of 2 etc. 33 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 34 | % to 512 points, if pad=1, we pad to 1024 points etc. 35 | % Defaults to 0. 36 | % Fs (sampling frequency) - optional. Default 1. 37 | % f0 (frequency of calculation) 38 | % Output: 39 | % P (integrated power within the frequency range of interest (trapezoidal integration)) 40 | % Fstat (F-statistic) 41 | % f0 (frequency) 42 | 43 | if nargin < 1; error('Need data'); end; 44 | if nargin < 2; params=[]; end; 45 | [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params); 46 | clear fpass err trialave params 47 | data=change_row_to_column(data); 48 | [N,C]=size(data); 49 | tapers=dpsschk(tapers,N,Fs); % calculate the tapers 50 | [N,K]=size(tapers); 51 | nfft=max(2^(nextpow2(N)+pad),N);% number of points in fft 52 | %[f0,findx]=getfgrid(Fs,nfft,f0);% frequency grid to be returned 53 | 54 | tapers=tapers(:,:,ones(1,C)); % add channel indices to tapers 55 | data=data(:,:,ones(1,K)); % add taper indices to data 56 | data=permute(data,[1 3 2]); % reshape data to get dimensions to match those of tapers 57 | data_proj=data.*tapers; % product of data with tapers in the form time x tapers x channels 58 | t=(0:N-1)'/Fs; 59 | fourier=exp(-i*2*pi*f0*t); 60 | fourier=fourier(:,ones(1,K),ones(1,C)); 61 | J=squeeze(sum(fourier.*data_proj))/Fs; 62 | 63 | Kodd=1:2:K; 64 | Keven=2:2:K; 65 | tapers=tapers(:,:,ones(1,C)); % add channel indices to the tapers - t x K x C 66 | H0 = squeeze(sum(tapers(:,Kodd,:),1)); % calculate sum of tapers for even prolates - K x C 67 | 68 | if C==1; H0=H0'; J=J'; end; 69 | P=squeeze(mean(J.*conj(J),1)); 70 | Jp=J(Kodd,:); % drop the even ffts 71 | H0sq=sum(H0.*H0,1);% sum of squares of H0^2 across taper indices - dimensions C 72 | JpH0=sum(Jp.*H0,1);% sum of the product of Jp and H0 across taper indices - f x C\ 73 | A=squeeze(JpH0./H0sq); % amplitudes for all frequencies and channels 74 | Kp=size(Jp,1); % number of even prolates 75 | Ap=A(ones(1,Kp),:); % add the taper index to C 76 | Jhat=Ap.*H0; % fitted value for the fft 77 | 78 | num=(K-1).*(abs(A).^2).*squeeze(H0sq);%numerator for F-statistic 79 | den=squeeze(sum(abs(Jp-Jhat).^2,1)+sum(abs(J(Keven,:)).^2,1));% denominator for F-statistic 80 | Fstat=num./den; % F-statisitic 81 | 82 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/mtspecgramtrigc.m: -------------------------------------------------------------------------------- 1 | function [S,t,f,Serr]=mtspecgramtrigc(data,E,win,movingwin,params) 2 | % Multi-taper event triggered time-frequency spectrum - continuous process 3 | % 4 | % Usage: 5 | % 6 | % [S,t,f,Serr]=mtspecgramtrigc(data,E,win,movingwin,params) 7 | % Input: 8 | % Note units have to be consistent. Thus, if movingwin is in seconds, Fs 9 | % has to be in Hz. see chronux.m for more information. 10 | % data (single channel data) -- required 11 | % E (event times) -- required 12 | % win (in the form [winl winr] i.e window around each event) 13 | % required 14 | % movingwin (in the form [window winstep] i.e length of moving 15 | % window and step size) - 16 | % required 17 | % Note that units for the windows have 18 | % to be consistent with 19 | % units of Fs 20 | % params: structure with fields tapers, pad, Fs, fpass, err, trialave 21 | % - optional 22 | % tapers : precalculated tapers from dpss or in the one of the following 23 | % forms: 24 | % (1) A numeric vector [TW K] where TW is the 25 | % time-bandwidth product and K is the number of 26 | % tapers to be used (less than or equal to 27 | % 2TW-1). 28 | % (2) A numeric vector [W T p] where W is the 29 | % bandwidth, T is the duration of the data and p 30 | % is an integer such that 2TW-p tapers are used. In 31 | % this form there is no default i.e. to specify 32 | % the bandwidth, you have to specify T and p as 33 | % well. Note that the units of W and T have to be 34 | % consistent: if W is in Hz, T must be in seconds 35 | % and vice versa. Note that these units must also 36 | % be consistent with the units of params.Fs: W can 37 | % be in Hz if and only if params.Fs is in Hz. 38 | % The default is to use form 1 with TW=3 and K=5 39 | % Note that T has to be equal to movingwin(1). 40 | % 41 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 42 | % -1 corresponds to no padding, 0 corresponds to padding 43 | % to the next highest power of 2 etc. 44 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 45 | % to 512 points, if pad=1, we pad to 1024 points etc. 46 | % Defaults to 0. 47 | % Fs (sampling frequency) - optional. Default 1. 48 | % fpass (frequency band to be used in the calculation in the form 49 | % [fmin fmax])- optional. 50 | % Default all frequencies between 0 and Fs/2 51 | % err (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars 52 | % [0 p] or 0 - no error bars) - optional. Default 0. 53 | % trialave (average over events when 1, don't average when 0) - optional. Default 0 54 | % Output: 55 | % S (triggered spectrum in form time x frequency x events for trialave=0; 56 | % or in the form time x frequency trialave=1) 57 | % t (times) 58 | % f (frequencies) 59 | % Serr (error bars) only for err(1)>=1 60 | 61 | if nargin < 4; error('Need data, events and parameters for the windows'); end; 62 | if nargin < 5; params=[]; end; 63 | 64 | if length(params.tapers)==3 & movingwin(1)~=params.tapers(2); 65 | error('Duration of data in params.tapers is inconsistent with movingwin(1), modify params.tapers(2) to proceed') 66 | end 67 | 68 | [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params); 69 | clear tapers pad fpass trialave 70 | if nargout > 3 && err(1)==0; 71 | % Cannot compute error bars with err(1)=0. change params and run again. 72 | error('When Serr is desired, err(1) has to be non-zero.'); 73 | end; 74 | data=change_row_to_column(data); 75 | data=createdatamatc(data,E,Fs,win); 76 | if nargout==4; 77 | [S,t,f,Serr]=mtspecgramc(data,movingwin,params); 78 | else 79 | [S,t,f]=mtspecgramc(data,movingwin,params); 80 | end; 81 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/mtspectrumc.m: -------------------------------------------------------------------------------- 1 | function [S,f,Serr]=mtspectrumc(data,params) 2 | % Multi-taper spectrum - continuous process 3 | % 4 | % Usage: 5 | % 6 | % [S,f,Serr]=mtspectrumc(data,params) 7 | % Input: 8 | % Note units have to be consistent. See chronux.m for more information. 9 | % data (in form samples x channels/trials) -- required 10 | % params: structure with fields tapers, pad, Fs, fpass, err, trialave 11 | % -optional 12 | % tapers : precalculated tapers from dpss or in the one of the following 13 | % forms: 14 | % (1) A numeric vector [TW K] where TW is the 15 | % time-bandwidth product and K is the number of 16 | % tapers to be used (less than or equal to 17 | % 2TW-1). 18 | % (2) A numeric vector [W T p] where W is the 19 | % bandwidth, T is the duration of the data and p 20 | % is an integer such that 2TW-p tapers are used. In 21 | % this form there is no default i.e. to specify 22 | % the bandwidth, you have to specify T and p as 23 | % well. Note that the units of W and T have to be 24 | % consistent: if W is in Hz, T must be in seconds 25 | % and vice versa. Note that these units must also 26 | % be consistent with the units of params.Fs: W can 27 | % be in Hz if and only if params.Fs is in Hz. 28 | % The default is to use form 1 with TW=3 and K=5 29 | % 30 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 31 | % -1 corresponds to no padding, 0 corresponds to padding 32 | % to the next highest power of 2 etc. 33 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 34 | % to 512 points, if pad=1, we pad to 1024 points etc. 35 | % Defaults to 0. 36 | % Fs (sampling frequency) - optional. Default 1. 37 | % fpass (frequency band to be used in the calculation in the form 38 | % [fmin fmax])- optional. 39 | % Default all frequencies between 0 and Fs/2 40 | % err (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars 41 | % [0 p] or 0 - no error bars) - optional. Default 0. 42 | % trialave (average over trials/channels when 1, don't average when 0) - optional. Default 0 43 | % Output: 44 | % S (spectrum in form frequency x channels/trials if trialave=0; 45 | % in the form frequency if trialave=1) 46 | % f (frequencies) 47 | % Serr (error bars) only for err(1)>=1 48 | 49 | if nargin < 1; error('Need data'); end; 50 | if nargin < 2; params=[]; end; 51 | [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params); 52 | if nargout > 2 && err(1)==0; 53 | % Cannot compute error bars with err(1)=0. Change params and run again. 54 | error('When Serr is desired, err(1) has to be non-zero.'); 55 | end; 56 | data=change_row_to_column(data); 57 | N=size(data,1); 58 | nfft=max(2^(nextpow2(N)+pad),N); 59 | [f,findx]=getfgrid(Fs,nfft,fpass); 60 | tapers=dpsschk(tapers,N,Fs); % check tapers 61 | J=mtfftc(data,tapers,nfft,Fs); 62 | J=J(findx,:,:); 63 | S=squeeze(mean(conj(J).*J,2)); 64 | if trialave; S=squeeze(mean(S,2));end; 65 | if nargout==3; 66 | Serr=specerr(S,J,err,trialave); 67 | end; 68 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/mtspectrumsegc.m: -------------------------------------------------------------------------------- 1 | function [S,f,varS,C,Serr]=mtspectrumsegc(data,win,params,segave) 2 | % Multi-taper segmented spectrum for a univariate continuous process 3 | % 4 | % Usage: 5 | % 6 | % [S,f,varS,C,Serr]=mtspectrumsegc(data,win,params,segave) 7 | % Input: 8 | % Note units have to be consistent. See chronux.m for more information. 9 | % data (single channel) -- required 10 | % win (duration of the segments) - required. 11 | % params: structure with fields tapers, pad, Fs, fpass, err, trialave 12 | % - optional 13 | % tapers : precalculated tapers from dpss or in the one of the following 14 | % forms: 15 | % (1) A numeric vector [TW K] where TW is the 16 | % time-bandwidth product and K is the number of 17 | % tapers to be used (less than or equal to 18 | % 2TW-1). 19 | % (2) A numeric vector [W T p] where W is the 20 | % bandwidth, T is the duration of the data and p 21 | % is an integer such that 2TW-p tapers are used. In 22 | % this form there is no default i.e. to specify 23 | % the bandwidth, you have to specify T and p as 24 | % well. Note that the units of W and T have to be 25 | % consistent: if W is in Hz, T must be in seconds 26 | % and vice versa. Note that these units must also 27 | % be consistent with the units of params.Fs: W can 28 | % be in Hz if and only if params.Fs is in Hz. 29 | % The default is to use form 1 with TW=3 and K=5 30 | % 31 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 32 | % -1 corresponds to no padding, 0 corresponds to padding 33 | % to the next highest power of 2 etc. 34 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 35 | % to 512 points, if pad=1, we pad to 1024 points etc. 36 | % Defaults to 0. 37 | % Fs (sampling frequency) - optional. Default 1. 38 | % fpass (frequency band to be used in the calculation in the form 39 | % [fmin fmax])- optional. 40 | % Default all frequencies between 0 and Fs/2 41 | % err (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars 42 | % [0 p] or 0 - no error bars) - optional. Default 0. 43 | % trialave - not used 44 | % segave - optional 0 for don't average over segments, 1 for average - default 45 | % 1 46 | % Output: 47 | % S (spectrum in form frequency x segments if segave=0; in the form frequency if segave=1) 48 | % f (frequencies) 49 | % varS (variance of the log spectrum) 50 | % C (covariance matrix of the log spectrum - frequency x 51 | % frequency matrix) 52 | % Serr (error bars) only for err(1)>=1 53 | 54 | if nargin < 2; error('Need data and segment information'); end; 55 | data=change_row_to_column(data); 56 | if size(data,2)~=1; error('works for only univariate time series'); end; 57 | if nargin < 3 ; params=[]; end; 58 | if nargin < 4 || isempty(segave); segave=1; end; 59 | [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params); clear trialave 60 | if nargout==4 && err(1)==0; 61 | % Errors can't be computed if err(1)=0. Need to change params and run again. 62 | error('When Serr is desired, err(1) has to be non-zero.'); 63 | end; 64 | N=size(data,1); % length of segmented data 65 | dt=1/Fs; % sampling interval 66 | T=N*dt; % length of data in seconds 67 | E=0:win:T-win; % fictitious event triggers 68 | win=[0 win]; % use window length to define left and right limits of windows around triggers 69 | data=createdatamatc(data,E,Fs,win); % segmented data 70 | if ~isempty(params.detrend) 71 | data = detrend(data,params.detrend); 72 | end 73 | N=size(data,1); % length of segmented data 74 | nfft=max(2^(nextpow2(N)+pad),N); 75 | [f,findx]=getfgrid(Fs,nfft,fpass); 76 | tapers=dpsschk(tapers,N,Fs); % check tapers 77 | J=mtfftc(data,tapers,nfft,Fs); % compute tapered fourier transforms 78 | J=J(findx,:,:); % restrict to specified frequencies 79 | S=squeeze(mean(conj(J).*J,2)); % spectra of non-overlapping segments (average over tapers) 80 | if segave==1; SS=squeeze(mean(S,2)); else; SS=S;end; % mean of the spectrum averaged across segments 81 | if nargout > 2 82 | lS=log(S); % log spectrum for nonoverlapping segments 83 | varS=var(lS',1)'; % variance of log spectrum 84 | % varS=var(lS',1)';% variance of the log spectrum R13 85 | if nargout > 3 86 | C=cov(lS'); % covariance matrix of the log spectrum 87 | if nargout==5; 88 | Serr=specerr(SS,J,err,segave); 89 | end; 90 | end; 91 | end; 92 | S=SS; 93 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/mtspectrumtrigc.m: -------------------------------------------------------------------------------- 1 | function [S,f,Serr]=mtspectrumtrigc(data,E,win,params) 2 | % Multi-taper event triggered time-frequency spectrum - continuous process 3 | % 4 | % Usage: 5 | % 6 | % [S,f,Serr]=mtspectrumtrigc(data,E,win,params) 7 | % Input: 8 | % Note units have to be consistent. See chronux.m for more information. 9 | % data (single channel) -- required 10 | % E (event times) -- required 11 | % win (in the form [winl winr] i.e window around each event 12 | % required) 13 | % Note that units here have 14 | % to be consistent with 15 | % units of Fs 16 | % params: structure with fields tapers, pad, Fs, fpass, err, trialave 17 | % -optional 18 | % tapers : precalculated tapers from dpss or in the one of the following 19 | % forms: 20 | % (1) A numeric vector [TW K] where TW is the 21 | % time-bandwidth product and K is the number of 22 | % tapers to be used (less than or equal to 23 | % 2TW-1). 24 | % (2) A numeric vector [W T p] where W is the 25 | % bandwidth, T is the duration of the data and p 26 | % is an integer such that 2TW-p tapers are used. In 27 | % this form there is no default i.e. to specify 28 | % the bandwidth, you have to specify T and p as 29 | % well. Note that the units of W and T have to be 30 | % consistent: if W is in Hz, T must be in seconds 31 | % and vice versa. Note that these units must also 32 | % be consistent with the units of params.Fs: W can 33 | % be in Hz if and only if params.Fs is in Hz. 34 | % The default is to use form 1 with TW=3 and K=5 35 | % 36 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 37 | % -1 corresponds to no padding, 0 corresponds to padding 38 | % to the next highest power of 2 etc. 39 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 40 | % to 512 points, if pad=1, we pad to 1024 points etc. 41 | % Defaults to 0. 42 | % Fs (sampling frequency) - optional. Default 1. 43 | % fpass (frequency band to be used in the calculation in the form 44 | % [fmin fmax])- optional. 45 | % Default all frequencies between 0 and Fs/2 46 | % err (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars 47 | % [0 p] or 0 - no error bars) - optional. Default 0. 48 | % trialave (average over events when 1, don't average when 0) - optional. Default 0 49 | % Output: 50 | % S (triggered spectrum in form frequency x events for trialave=0 - 51 | % or as a function of frequency for trialave=1) 52 | % f (frequencies) 53 | % Serr (error bars) only for err(1)>=1 54 | 55 | if nargin < 3; error('Need data, events and window parameters'); end; 56 | if nargin < 4; params=[]; end; 57 | [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params); 58 | clear tapers pad fpass trialave 59 | if nargout > 2 && err(1)==0; 60 | % Cannot compute error bars with err(1)=0. Change params and run again. 61 | error('When Serr is desired, err(1) has to be non-zero.'); 62 | end; 63 | data=change_row_to_column(data); 64 | data=createdatamatc(data,E,Fs,win); 65 | if nargout==3; 66 | [S,f,Serr]=mtspectrumc(data,params); 67 | else 68 | [S,f]=mtspectrumc(data,params); 69 | end; 70 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/nonst_stat.m: -------------------------------------------------------------------------------- 1 | function sigma = nonst_stat(data,A,sumV,params) 2 | 3 | % Nonstationarity test - continuous process 4 | % 5 | % Usage: 6 | % 7 | % sigma=nonst_test(data,A,sumV,params) 8 | % Input: 9 | % Note units have to be consistent. See chronux.m for more information. 10 | % data (1d array in samples) -- required 11 | % A quadratic coefficient matrix - (Compute this separately since 12 | % the computation is time consuming - [A,sumV]=quadcof(N,NW,order). order 13 | % has to < 4NW.) 14 | % sumV sum of the quadratic inverse basis vectors 15 | % params: structure with fields tapers, pad, Fs, fpass, err, trialave 16 | % -optional 17 | % tapers : precalculated tapers from dpss or in the one of the following 18 | % forms: 19 | % (1) A numeric vector [TW K] where TW is the 20 | % time-bandwidth product and K is the number of 21 | % tapers to be used (less than or equal to 22 | % 2TW-1). 23 | % (2) A numeric vector [W T p] where W is the 24 | % bandwidth, T is the duration of the data and p 25 | % is an integer such that 2TW-p tapers are used. In 26 | % this form there is no default i.e. to specify 27 | % the bandwidth, you have to specify T and p as 28 | % well. Note that the units of W and T have to be 29 | % consistent: if W is in Hz, T must be in seconds 30 | % and vice versa. Note that these units must also 31 | % be consistent with the units of params.Fs: W can 32 | % be in Hz if and only if params.Fs is in Hz. 33 | % The default is to use form 1 with TW=3 and K=5 34 | % 35 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 36 | % -1 corresponds to no padding, 0 corresponds to padding 37 | % to the next highest power of 2 etc. 38 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 39 | % to 512 points, if pad=1, we pad to 1024 points etc. 40 | % Defaults to 0. 41 | % Fs (sampling frequency) - optional. Default 1. 42 | % Output: 43 | % sigma (nonstationarity index Thomson, 2000) 44 | 45 | 46 | if nargin < 1; error('Need data'); end; 47 | if nargin < 2; params=[]; end; 48 | 49 | order = length(A); 50 | N = length(data); 51 | %nfft=max(2^(nextpow2(N)+pad),N); 52 | [tapers,pad,Fs]=getparams(params); 53 | tapers=dpsschk(tapers,N,Fs); % check tapers 54 | 55 | alpha=zeros(1,order); 56 | for j=1:order 57 | alpha(j) = trace(squeeze(A(:,:,j))*squeeze(A(:,:,j))); 58 | end; 59 | 60 | tmp=mtfftc(data,tapers,N,Fs); 61 | %tmp=mtfftc(data,tapers,nfft,Fs); 62 | sigma = zeros(length(data),1); 63 | % Pbar = sum(abs(tmp).^2,2)./sum(weights.^2,2); 64 | Pbar=mean(abs(tmp).^2,2); 65 | for ii=1:order 66 | a0=real(sum(tmp'.*(squeeze(A(:,:,ii))*tmp.')))'/alpha(ii); 67 | sigma=sigma+alpha(ii)*(a0./Pbar-sumV(ii)).^2; 68 | end; 69 | 70 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/quadcof.m: -------------------------------------------------------------------------------- 1 | function [A,sumV] = quadcof(N,NW,order) 2 | % Helper function to calculate the nonstationary quadratic inverse matrix 3 | % Usage: [A,sumV] = quadcof(N,NW,order) 4 | % N (number of samples) 5 | % NW: Time bandwidth product 6 | % order: order (number of coefficients, upto 4NW) 7 | % 8 | % Outputs: 9 | % 10 | % A: quadratic inverse coefficient matrix 11 | % sumV: sum of the quadratic inverse eigenvectors 12 | 13 | A = zeros(2*NW-2,2*NW-2,order); 14 | V = quadinv(N,NW); 15 | [P,alpha] = dpss(N,NW,'calc'); 16 | 17 | for ii = 1:order 18 | 19 | for jj = 1:2*NW 20 | for kk = 1:2*NW 21 | A(jj,kk,ii) = sqrt(alpha(jj)*alpha(kk))*... 22 | sum(P(:,jj).*P(:,kk).*V(:,ii)); 23 | end; 24 | end; 25 | end; 26 | sumV=sum(V)/N; 27 | 28 | 29 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/quadinv.m: -------------------------------------------------------------------------------- 1 | function [V,E] = quadinv(N,NW) 2 | 3 | % calculates the quadratic inverse eigenvectors 4 | % 5 | % Input 6 | % N: number of samples 7 | % NW: time-bandwidth product 8 | % 9 | % Output 10 | % V: The quadratic inverse eigenvectors 11 | % E: the quadratic inverse eigenvalues 12 | 13 | 14 | x = 0:N-1; 15 | indx = find(x); 16 | y = ones(size(x))*(2*NW/N)^2; 17 | 18 | y(indx) = (sin(2*pi*NW*x(indx)/N)./(pi*x(indx))).^2; 19 | 20 | M = toeplitz(y); 21 | [C,D] = eig(N*M); 22 | 23 | tmp = diag(D); 24 | 25 | K = 4*NW; 26 | 27 | V = sqrt(N)*C(:,N:-1:N-K+1); 28 | 29 | E = tmp(N:-1:N-K+1); 30 | 31 | for ii =1:K 32 | if(sum((N-1-2*x)'.*V(:,ii))<0) 33 | V(:,ii) = flipud(V(:,ii)); 34 | end; 35 | end; 36 | 37 | return; 38 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/runline.m: -------------------------------------------------------------------------------- 1 | function y_line=runline(y,n,dn) 2 | % Running line fit (local linear regression) 3 | % 4 | % Usage: y_line=runline(y,n,dn); 5 | % 6 | % Inputs: 7 | % y: input 1-d time series (real) 8 | % n: length of running window in samples 9 | % dn: stepsize of window in samples 10 | % 11 | % Outputs: 12 | % y_line: local line fit to data 13 | y=y(:); 14 | nt=length(y); 15 | y_line=zeros(nt,1); 16 | norm=y_line; 17 | nwin=ceil((nt-n)/dn); 18 | yfit=zeros(nwin,n); 19 | xwt=((1:n)-n/2)/(n/2); 20 | wt=(1-abs(xwt).^3).^3; 21 | for j=1:nwin, 22 | tseg=y(dn*(j-1)+1:dn*(j-1)+n); 23 | y1=mean(tseg); 24 | y2=mean((1:n)'.*tseg)*2/(n+1); 25 | a=(y2-y1)*6/(n-1); b=y1-a*(n+1)/2; 26 | yfit(j,:)=(1:n)*a+b; 27 | y_line((j-1)*dn+(1:n))=y_line((j-1)*dn+(1:n))+(yfit(j,:).*wt)'; 28 | norm((j-1)*dn+(1:n))=norm((j-1)*dn+(1:n))+wt'; 29 | end 30 | mask=find(norm>0); y_line(mask)=y_line(mask)./norm(mask); 31 | indx=(nwin-1)*dn+n-1; 32 | npts=length(y)-indx+1; 33 | y_line(indx:end)=(n+1:n+npts)'*a+b; 34 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/continuous/spsvd.m: -------------------------------------------------------------------------------- 1 | function [sv,sp,fm] = spsvd(data,params,mdkp) 2 | % Space frequency SVD of input data - continuous processes 3 | % Usage: [sv,sp,fm] = spsvd(data,params,mdkp) 4 | % Inputs: 5 | % data (data matrix in timexchannels form)-required 6 | % params structure containing parameters - params has the 7 | % following fields: tapers, Fs, fpass, pad 8 | % tapers : precalculated tapers from dpss or in the one of the following 9 | % forms: 10 | % (1) A numeric vector [TW K] where TW is the 11 | % time-bandwidth product and K is the number of 12 | % tapers to be used (less than or equal to 13 | % 2TW-1). 14 | % (2) A numeric vector [W T p] where W is the 15 | % bandwidth, T is the duration of the data and p 16 | % is an integer such that 2TW-p tapers are used. In 17 | % this form there is no default i.e. to specify 18 | % the bandwidth, you have to specify T and p as 19 | % well. Note that the units of W and T have to be 20 | % consistent: if W is in Hz, T must be in seconds 21 | % and vice versa. Note that these units must also 22 | % be consistent with the units of params.Fs: W can 23 | % be in Hz if and only if params.Fs is in Hz. 24 | % The default is to use form 1 with TW=3 and K=5 25 | % 26 | % Fs (sampling frequency) -- optional. Defaults to 1. 27 | % fpass (frequency band to be used in the calculation in the form 28 | % [fmin fmax])- optional. 29 | % Default all frequencies between 0 and Fs/2 30 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 31 | % -1 corresponds to no padding, 0 corresponds to padding 32 | % to the next highest power of 2 etc. 33 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 34 | % to 512 points, if pad=1, we pad to 1024 points etc. 35 | % Defaults to 0. 36 | % mdkp (number of dimensions to be kept)-optional. Default is the 37 | % maximum possible modes determined by taper parameters 38 | % 39 | % Outputs: 40 | % sv sp fm : singular values, space modes, frequency modes 41 | 42 | 43 | if nargin < 1; error('Need data'); end; 44 | if nargin < 2 || isempty(params); params=[]; end; 45 | [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params); 46 | clear err trialave params 47 | [N,NCHAN]=size(data); 48 | tapers=dpsschk(tapers,N,Fs); 49 | nfft=max(2^(nextpow2(N)+pad),N);% number of points in fft 50 | [N,K]=size(tapers); 51 | if nargin<3 || isempty(mdkp); mdkp=min(K,NCHAN); 52 | elseif mdkp > min(K,NCHAN); error('mdkp has to be less than both K and NCHAN');end; 53 | 54 | tvec=(1:N)'; 55 | tvec=repmat(tvec,[1 K]); 56 | tvec=tvec*2*pi*i; 57 | f=getfgrid(Fs,nfft,fpass); 58 | nf=length(f); 59 | sp=zeros(NCHAN,nf,mdkp); 60 | sp=sp+i*sp; 61 | fm=zeros(K,nf,mdkp); 62 | fm=fm+i*fm; 63 | sv=zeros(nf,min([K,NCHAN])); 64 | for j=1:nf 65 | % for k=1:K 66 | % proj(:,k)=tapers(:,k).*exp(-f0*tvec'); 67 | % end 68 | proj=tapers.*exp(-f(j)*tvec); 69 | tmp=data'*proj; % projected data 70 | [u,s,v]= svd(tmp,0); % svd 71 | for mk=1:mdkp, 72 | sp(:,j,mk)=u(:,mk)'; 73 | fm(:,j,mk)=v(:,mk)'; 74 | end 75 | sv(j,:)=diag(s); 76 | end; 77 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/helper/change_row_to_column.m: -------------------------------------------------------------------------------- 1 | function data=change_row_to_column(data) 2 | % Helper routine to transform 1d arrays into column vectors that are needed 3 | % by other routines in Chronux 4 | % 5 | % Usage: data=change_row_to_column(data) 6 | % 7 | % Inputs: 8 | % data -- required. If data is a matrix, it is assumed that it is of the 9 | % form samples x channels/trials and it is returned without change. If it 10 | % is a vector, it is transformed to a column vector. If it is a struct 11 | % array of dimension 1, it is again returned as a column vector. If it is a 12 | % struct array with multiple dimensions, it is returned without change 13 | % Note that the routine only looks at the first field of a struct array. 14 | % 15 | % Ouputs: 16 | % data (in the form samples x channels/trials) 17 | % 18 | 19 | dtmp=[]; 20 | if isstruct(data); 21 | C=length(data); 22 | if C==1; 23 | fnames=fieldnames(data); 24 | eval(['dtmp=data.' fnames{1} ';']) 25 | data=dtmp(:); 26 | end 27 | else 28 | [N,C]=size(data); 29 | if N==1 || C==1; 30 | data=data(:); 31 | end; 32 | end; 33 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/helper/check_consistency.m: -------------------------------------------------------------------------------- 1 | function [N,C]=check_consistency(data1,data2,sp) 2 | % Helper routine to check consistency of data dimensions 3 | % Usage: [N,C]=check_consistency(data1,data2,sp) 4 | % Inputs: 5 | % data1 - first dataset 6 | % data2 - second dataset 7 | % sp - optional argument to be input as 1 when one of the two data sets is 8 | % spikes times stored as a 1d array. 9 | % Outputs: 10 | % Dimensions of the datasets - data1 or data2 (note that 11 | % routine stops with an error message if dimensions don't match - [N,C] 12 | % N left empty for structure arrays 13 | N1=[]; N2=[]; 14 | if nargin < 3 || isempty(sp); sp=0; end; 15 | if isstruct(data1); 16 | C1=length(data1); 17 | else 18 | [N1,C1]=size(data1); 19 | end; 20 | if isstruct(data2); 21 | C2=length(data2); 22 | else 23 | [N2,C2]=size(data2); 24 | end; 25 | if C1~=C2; error('inconsistent dimensions'); end; 26 | if sp==0; 27 | if ~isstruct(data1) && ~isstruct(data2); 28 | if N1~=N2; error('inconsistent dimensions'); end; 29 | end; 30 | end; 31 | N=N1; C=C1; -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/helper/cohmathelper.m: -------------------------------------------------------------------------------- 1 | function [C,phi,S12,confC,phierr,Cerr]=cohmathelper(J,err,Nsp) 2 | % Helper function called by coherency matrix computations. 3 | % 4 | % Usage: [C,phi,S12,confC,phierr,Cerr]=cohmathelper(J,err,Nsp) 5 | % Inputs: 6 | % J : Fourier transforms of data 7 | % err : [0 p] or 0 for no errors; [1 p] for theoretical confidence level, 8 | % [2 p] for Jackknife (p - p value) 9 | % Nsp : pass the number of spikes in each channel if finite size corrections are desired 10 | % 11 | % Outputs: 12 | % 13 | % C : coherence 14 | % phi : phase of coherency 15 | % S12 : cross spectral matrix 16 | % confC : confidence level for coherency - only for err(1)>=1 17 | % phierr - standard deviation for phi (note that the routine gives phierr as phierr(1,...) 18 | % and phierr(2,...) in order to incorporate Jackknife (eventually). 19 | % Currently phierr(1,...)=phierr(2,...). Note that phi + 2 phierr(1,...) and phi -2 20 | % phierr(2,...) will give 95% confidence bands for phi - only for err(1)>=1 21 | % Cerr : error bars for coherency (only for Jackknife estimates)-only for err(1)=2 22 | % 23 | 24 | errtype=err(1); 25 | trialave=0; 26 | [nf,K,Ch]=size(J); 27 | clear K 28 | confC=zeros(Ch,Ch); 29 | C=zeros(nf,Ch,Ch); 30 | S12=zeros(nf,Ch,Ch); 31 | phi=zeros(nf,Ch,Ch); 32 | phierr=zeros(2,nf,Ch,Ch); 33 | if errtype==2; Cerr=zeros(2,nf,Ch,Ch);end; 34 | 35 | for ch1=1:Ch; 36 | J1=squeeze(J(:,:,ch1)); 37 | C(1:nf,ch1,ch1)=1; 38 | phi(1:nf,ch1,ch1)=0; 39 | % if errtype==2; 40 | % phierr(1:nf,ch1,ch1)=0; 41 | % Cerr(1:2,1:nf,ch1,ch1)=0; 42 | % elseif errtype==1 43 | % phierr(1:2,1:nf,ch1,ch1)=0; 44 | % end; 45 | s1=squeeze(mean(conj(J1).*J1,2)); 46 | for ch2=1:ch1-1; 47 | J2=squeeze(J(:,:,ch2)); 48 | s12=squeeze(mean(conj(J1).*J2,2)); 49 | s2=squeeze(mean(conj(J2).*J2,2)); 50 | C12=s12./sqrt(s1.*s2); 51 | C(:,ch1,ch2)=abs(C12); 52 | C(:,ch2,ch1)=C(:,ch1,ch2); 53 | phi(:,ch1,ch2)=angle(C12); 54 | phi(:,ch2,ch1)=phi(:,ch1,ch2); 55 | S12(:,ch1,ch2)=s12; 56 | S12(:,ch2,ch1)=S12(:,ch1,ch2); 57 | if errtype==2 58 | if nargin<3; 59 | [conf,phie,Ce]=coherr(abs(C12),J1,J2,err,trialave); 60 | else 61 | [conf,phie,Ce]=coherr(abs(C12),J1,J2,err,trialave,Nsp(ch1),Nsp(ch2)); 62 | end 63 | confC(ch1,ch2)=conf; 64 | phierr(1,:,ch1,ch2)=phie;phierr(2,:,ch1,ch2)=phie; 65 | Cerr(1,:,ch1,ch2)=Ce(1,:); 66 | Cerr(2,:,ch1,ch2)=Ce(2,:); 67 | confC(ch2,ch1)=conf; 68 | phierr(1,:,ch2,ch1)=phie;phierr(2,:,ch2,ch1)=phie; 69 | Cerr(:,:,ch2,ch1)=Ce; 70 | elseif errtype==1 71 | if nargin<3; 72 | [conf,phie]=coherr(abs(C12),J1,J2,err,trialave); 73 | else 74 | [conf,phie]=coherr(abs(C12),J1,J2,err,trialave,Nsp(ch1),Nsp(ch2)); 75 | end 76 | confC(ch1,ch2)=conf; 77 | phierr(1,:,ch1,ch2)=phie;phierr(2,:,ch1,ch2)=phie; 78 | confC(ch2,ch1)=conf; 79 | phierr(1,:,ch2,ch1)=phie;phierr(2,:,ch2,ch1)=phie; 80 | end; 81 | end; 82 | end; 83 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/helper/den_jack.m: -------------------------------------------------------------------------------- 1 | function [m,ll,ul,llj,ulj]=den_jack(X,family,varargin) 2 | % Function to compute smooth estimates of the mean of x using locfit, 3 | % the corresponding confidence intervals, and jackknife estimates of 4 | % the confidence intervals 5 | % Usage: [m,ll,ul,llj,ulj]=den_jack(x) 6 | % 7 | % Inputs: 8 | % X: data in the form samples x trials 9 | % family: 'density' or 'reg' for regression 10 | % If the family is density, the entire input matrix X is considered 11 | % as data. If the family is regression then the first column of X is 12 | % taken to be the independent variable and the remaining columns are 13 | % regressed on this variable (for example, the first column may be 14 | % the centers of the bins for binned spike count data) 15 | % varargin is the set of arguments used by locfit to perform the smoothing 16 | % 17 | % Outputs: 18 | % m : smoothed estimate of the mean 19 | % ll : estimate of the lower confidence level 20 | % ul : estimate of the upper confidence level 21 | % llj : jackknife estimate of the lower confidence level (+2\sigma 22 | % where sigma is the jackknife variance) 23 | % llu : jackknife estimate of the upper confidence level (-2\sigma 24 | % where sigma is the jackknife variance) 25 | [N,NT]=size(X); 26 | if strcmp(family,'reg'); 27 | yy=X(:,2:end); 28 | y=mean(yy,2); 29 | x=X(:,1); 30 | z=scb(x,y,varargin{:}); 31 | figure; 32 | plot(z(:,1),z(:,2)); 33 | hold on; 34 | plot(z(:,1),z(:,3),'b:'); 35 | plot(z(:,1),z(:,4),'b:'); 36 | title('Smoothed density estimate, all data'); 37 | 38 | % fit=locfit(x,y,varargin{:}); 39 | % xfit = lfmarg(fit); 40 | % yfit = predict(fit,xfit); 41 | % z = invlink(yfit,fit{4}{5}); 42 | % 43 | for tr=1:NT-1; 44 | % i=setdiff(1:NT-1,tr); 45 | % y=mean(yy(:,i),2); 46 | y=yy(:,tr); 47 | fit=locfit(x,y,varargin{:}); 48 | xfit = lfmarg(fit); 49 | yfit = predict(fit,xfit); 50 | yfit = invlink(yfit,fit{4}{5}); 51 | zz(:,tr)=yfit; 52 | % theta(:,tr)=NT*z-(NT-1)*yfit; 53 | end; 54 | % thetam=mean(theta,2); 55 | % variance=var(theta,0,2); 56 | % standard_dev=sqrt(variance); 57 | % figure; plot(xfit{1},thetam,'b'); 58 | % hold on; plot(xfit{1},thetam+2*standard_dev,'r'); 59 | % plot(xfit{1},thetam-2*standard_dev,'r'); 60 | % pause; 61 | [m,jsd]=jackknife(zz); 62 | % plot(xfit{1},m,'r'); 63 | hold on; 64 | plot(xfit{1},m+2*jsd,'r:'); 65 | plot(xfit{1},m-2*jsd,'r:'); 66 | figure; 67 | plot(xfit{1},zz); 68 | title('All trials'); 69 | else 70 | x=mean(X,2); 71 | fit=locfit(x,varargin{:}); 72 | figure;lfplot(fit); 73 | lfband(fit); 74 | end; 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/helper/dpsschk.m: -------------------------------------------------------------------------------- 1 | function [tapers,eigs]=dpsschk(tapers,N,Fs) 2 | % Helper function to calculate tapers and, if precalculated tapers are supplied, 3 | % to check that they (the precalculated tapers) the same length in time as 4 | % the time series being studied. The length of the time series is specified 5 | % as the second input argument N. Thus if precalculated tapers have 6 | % dimensions [N1 K], we require that N1=N. 7 | % Usage: tapers=dpsschk(tapers,N,Fs) 8 | % Inputs: 9 | % tapers (tapers in the form of: 10 | % (i) precalculated tapers or, 11 | % (ii) [NW K] - time-bandwidth product, number of tapers) 12 | % 13 | % N (number of samples) 14 | % Fs (sampling frequency - this is required for nomalization of 15 | % tapers: we need tapers to be such 16 | % that integral of the square of each taper equals 1 17 | % dpss computes tapers such that the 18 | % SUM of squares equals 1 - so we need 19 | % to multiply the dpss computed tapers 20 | % by sqrt(Fs) to get the right 21 | % normalization) 22 | % Outputs: 23 | % tapers (calculated or precalculated tapers) 24 | % eigs (eigenvalues) 25 | if nargin < 3; error('Need all arguments'); end 26 | sz=size(tapers); 27 | if sz(1)==1 && sz(2)==2; 28 | [tapers,eigs]=dpss(N,tapers(1),tapers(2)); 29 | tapers = tapers*sqrt(Fs); 30 | elseif N~=sz(1); 31 | error('seems to be an error in your dpss calculation; the number of time points is different from the length of the tapers'); 32 | end; 33 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/helper/getfgrid.m: -------------------------------------------------------------------------------- 1 | function [f,findx]=getfgrid(Fs,nfft,fpass) 2 | % Helper function that gets the frequency grid associated with a given fft based computation 3 | % Called by spectral estimation routines to generate the frequency axes 4 | % Usage: [f,findx]=getfgrid(Fs,nfft,fpass) 5 | % Inputs: 6 | % Fs (sampling frequency associated with the data)-required 7 | % nfft (number of points in fft)-required 8 | % fpass (band of frequencies at which the fft is being calculated [fmin fmax] in Hz)-required 9 | % Outputs: 10 | % f (frequencies) 11 | % findx (index of the frequencies in the full frequency grid). e.g.: If 12 | % Fs=1000, and nfft=1048, an fft calculation generates 512 frequencies 13 | % between 0 and 500 (i.e. Fs/2) Hz. Now if fpass=[0 100], findx will 14 | % contain the indices in the frequency grid corresponding to frequencies < 15 | % 100 Hz. In the case fpass=[0 500], findx=[1 512]. 16 | if nargin < 3; error('Need all arguments'); end; 17 | df=Fs/nfft; 18 | f=0:df:Fs; % all possible frequencies 19 | f=f(1:nfft); 20 | if length(fpass)~=1; 21 | findx=find(f>=fpass(1) & f<=fpass(end)); 22 | else 23 | [fmin,findx]=min(abs(f-fpass)); 24 | clear fmin 25 | end; 26 | f=f(findx); 27 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/helper/getparams.m: -------------------------------------------------------------------------------- 1 | function [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params) 2 | % Helper function to convert structure params to variables used by the 3 | % various routines - also performs checks to ensure that parameters are 4 | % defined; returns default values if they are not defined. 5 | % 6 | % Usage: [tapers,pad,Fs,fpass,err,trialave,params]=getparams(params) 7 | % 8 | % Inputs: 9 | % params: structure with fields tapers, pad, Fs, fpass, err, trialave 10 | % - optional 11 | % tapers : precalculated tapers from dpss or in the one of the following 12 | % forms: 13 | % (1) A numeric vector [TW K] where TW is the 14 | % time-bandwidth product and K is the number of 15 | % tapers to be used (less than or equal to 16 | % 2TW-1). 17 | % (2) A numeric vector [W T p] where W is the 18 | % bandwidth, T is the duration of the data and p 19 | % is an integer such that 2TW-p tapers are used. In 20 | % this form there is no default i.e. to specify 21 | % the bandwidth, you have to specify T and p as 22 | % well. Note that the units of W and T have to be 23 | % consistent: if W is in Hz, T must be in seconds 24 | % and vice versa. Note that these units must also 25 | % be consistent with the units of params.Fs: W can 26 | % be in Hz if and only if params.Fs is in Hz. 27 | % The default is to use form 1 with TW=3 and K=5 28 | % 29 | % pad (padding factor for the FFT) - optional (can take values -1,0,1,2...). 30 | % -1 corresponds to no padding, 0 corresponds to padding 31 | % to the next highest power of 2 etc. 32 | % e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT 33 | % to 512 points, if pad=1, we pad to 1024 points etc. 34 | % Defaults to 0. 35 | % Fs (sampling frequency) - optional. Default 1. 36 | % fpass (frequency band to be used in the calculation in the form 37 | % [fmin fmax])- optional. 38 | % Default all frequencies between 0 and Fs/2 39 | % err (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars 40 | % [0 p] or 0 - no error bars) - optional. Default 0. 41 | % trialave (average over trials when 1, don't average when 0) - optional. Default 0 42 | % Outputs: 43 | % The fields listed above as well as the struct params. The fields are used 44 | % by some routines and the struct is used by others. Though returning both 45 | % involves overhead, it is a safer, simpler thing to do. 46 | 47 | if ~isfield(params,'tapers') || isempty(params.tapers); %If the tapers don't exist 48 | display('tapers unspecified, defaulting to params.tapers=[3 5]'); 49 | params.tapers=[3 5]; 50 | end; 51 | if ~isempty(params) && length(params.tapers)==3 52 | % Compute timebandwidth product 53 | TW = params.tapers(2)*params.tapers(1); 54 | % Compute number of tapers 55 | K = floor(2*TW - params.tapers(3)); 56 | params.tapers = [TW K]; 57 | end 58 | 59 | if ~isfield(params,'pad') || isempty(params.pad); 60 | params.pad=0; 61 | end; 62 | if ~isfield(params,'Fs') || isempty(params.Fs); 63 | params.Fs=1; 64 | end; 65 | if ~isfield(params,'fpass') || isempty(params.fpass); 66 | params.fpass=[0 params.Fs/2]; 67 | end; 68 | if ~isfield(params,'err') || isempty(params.err); 69 | params.err=0; 70 | end; 71 | if ~isfield(params,'trialave') || isempty(params.trialave); 72 | params.trialave=0; 73 | end; 74 | if ~isfield(params,'detrend') 75 | params.detrend = ''; 76 | end 77 | 78 | tapers=params.tapers; 79 | pad=params.pad; 80 | Fs=params.Fs; 81 | fpass=params.fpass; 82 | err=params.err; 83 | trialave=params.trialave; -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/helper/jackknife.m: -------------------------------------------------------------------------------- 1 | function [m,jsd]=jackknife(x) 2 | % Compute jackknife estimates of the mean and standard deviation of input data x 3 | % Usage: [m,jsd]=jackknife(x) 4 | % 5 | % Inputs: 6 | % x : data in the form samples x trials 7 | % 8 | % Outputs: 9 | % m : estimate of the mean (across trials) 10 | % jsd: jackknife estimate of the standard deviation (across trials) 11 | 12 | [N,C]=size(x); 13 | if C==1; error('Need multiple trials'); end; 14 | m=mean(x,2); 15 | theta=zeros(N,C); 16 | for tr=1:C; 17 | i=setdiff((1:C),tr); % drop 1 trial 18 | y=sum(x(:,i),2)/(C-1); % mean over remaining trials 19 | theta(:,tr)=C*m-(C-1)*y; % pseudo values 20 | % yy(:,tr)=y; 21 | end; 22 | jm=mean(theta,2); 23 | jm=repmat(jm,[1 C]); 24 | % jm2=mean(yy,2); 25 | % jm2=repmat(jm2,[1 C]); 26 | jsd=sqrt(sum((theta-jm).^2,2)/(C*(C-1))); 27 | % jsd2=sqrt((C-1)*sum((yy-jm2).^2,2)/C); 28 | % jsd 29 | % jsd2 30 | -------------------------------------------------------------------------------- /external/chronux_2_modified/spectral_analysis/helper/specerr.m: -------------------------------------------------------------------------------- 1 | function Serr=specerr(S,J,err,trialave,numsp) 2 | % Function to compute lower and upper confidence intervals on the spectrum 3 | % Usage: Serr=specerr(S,J,err,trialave,numsp) 4 | % Outputs: Serr (Serr(1,...) - lower confidence level, Serr(2,...) upper confidence level) 5 | % 6 | % Inputs: 7 | % S - spectrum 8 | % J - tapered fourier transforms 9 | % err - [errtype p] (errtype=1 - asymptotic estimates; errchk=2 - Jackknife estimates; 10 | % p - p value for error estimates) 11 | % trialave - 0: no averaging over trials/channels 12 | % 1 : perform trial averaging 13 | % numsp - number of spikes in each channel. specify only when finite 14 | % size correction required (and of course, only for point 15 | % process data) 16 | % 17 | % Outputs: 18 | % Serr - error estimates. Only for err(1)>=1. If err=[1 p] or [2 p] Serr(...,1) and Serr(...,2) 19 | % contain the lower and upper error bars with the specified method. 20 | if nargin < 4; error('Need at least 4 input arguments'); end; 21 | if err(1)==0; error('Need err=[1 p] or [2 p] for error bar calculation. Make sure you are not asking for the output of Serr'); end; 22 | [nf,K,C]=size(J); 23 | errchk=err(1); 24 | p=err(2); 25 | pp=1-p/2; 26 | qq=1-pp; 27 | 28 | if trialave 29 | dim=K*C; 30 | C=1; 31 | dof=2*dim; 32 | if nargin==5; dof = fix(1/(1/dof + 1/(2*sum(numsp)))); end 33 | J=reshape(J,nf,dim); 34 | else 35 | dim=K; 36 | dof=2*dim*ones(1,C); 37 | for ch=1:C; 38 | if nargin==5; dof(ch) = fix(1/(1/dof + 1/(2*numsp(ch)))); end 39 | end; 40 | end; 41 | Serr=zeros(2,nf,C); 42 | if errchk==1; 43 | Qp=chi2inv(pp,dof); 44 | Qq=chi2inv(qq,dof); 45 | Serr(1,:,:)=dof(ones(nf,1),:).*S./Qp(ones(nf,1),:); 46 | Serr(2,:,:)=dof(ones(nf,1),:).*S./Qq(ones(nf,1),:); 47 | elseif errchk==2; 48 | tcrit=tinv(pp,dim-1); 49 | for k=1:dim; 50 | indices=setdiff(1:dim,k); 51 | Jjk=J(:,indices,:); % 1-drop projection 52 | eJjk=squeeze(sum(Jjk.*conj(Jjk),2)); 53 | Sjk(k,:,:)=eJjk/(dim-1); % 1-drop spectrum 54 | end; 55 | sigma=sqrt(dim-1)*squeeze(std(log(Sjk),1,1)); if C==1; sigma=sigma'; end; 56 | conf=repmat(tcrit,nf,C).*sigma; 57 | conf=squeeze(conf); 58 | Serr(1,:,:)=S.*exp(-conf); Serr(2,:,:)=S.*exp(conf); 59 | end; 60 | Serr=squeeze(Serr); -------------------------------------------------------------------------------- /external/shadowplot/license.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2007, The MathWorks, Inc. 2 | Copyright (c) 1997, Christophe COUVREUR 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are 7 | met: 8 | 9 | * Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | * Redistributions in binary form must reproduce the above copyright 12 | notice, this list of conditions and the following disclaimer in 13 | the documentation and/or other materials provided with the distribution 14 | * Neither the name of the The MathWorks, Inc. nor the names 15 | of its contributors may be used to endorse or promote products derived 16 | from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /fitSignificantFrequencies.m: -------------------------------------------------------------------------------- 1 | function [datafit, f0Significant, FvalSig, aSig, fSig, sig]= ... 2 | fitSignificantFrequencies(data, f0, lineNoise) 3 | % Fits significant sine waves to specified peaks in continuous data 4 | % 5 | % Usage: 6 | % [datafit, f0Significant] = fitSignificantFrequencies(data, f0, lineNoise) 7 | % 8 | % Parameters: 9 | % data Single channel -- required 10 | % f0 Vector with the line frequencies to be removed 11 | % lineNoise Structure with various parameters set 12 | % 13 | % The lineNoise structure has the following fields set: 14 | % fPassBand Frequency band used 15 | % fScanBandWidth +/- bandwidth centered on each f0 to scan for significant 16 | % lines (TM) 17 | % Fs Sampling frequency 18 | % p Significance level cutoff 19 | % pad FFT padding factor 20 | % tapers Precomputed tapers from dpss 21 | % taperWindowSize Taper sliding window length 22 | % 23 | % Outputs: 24 | % datafit Linear superposition of fitted sine waves 25 | % f0Significant f0 values found to be significant 26 | % 27 | data = change_row_to_column(data); 28 | N = size(data, 1); 29 | 30 | fscanbw = getStructureParameters(lineNoise, 'fScanBandWidth'); 31 | Fs = getStructureParameters(lineNoise, 'Fs'); 32 | 33 | [Fval, A, f, sig] = testSignificantFrequencies(data, lineNoise); 34 | datafit = zeros(N, 1); 35 | 36 | frequencyMask = false(1, length(f)); 37 | f0Significant = false(1, length(f0)); 38 | if ~isempty(fscanbw) 39 | % For each line f0(n), scan f0+-BW/2 for largest significant peak of Fval 40 | for n = 1:length(f0) 41 | % Extract scan range around f0 ( f0 +- fscanbw/2 ) 42 | [~, ridx(1)] = min(abs(f - (f0(n) - fscanbw/2))); 43 | [~, ridx(2)] = min(abs(f - (f0(n) + fscanbw/2))); 44 | 45 | Fvalscan = Fval(ridx(1):ridx(2)); 46 | Fvalscan(Fvalscan < sig) = 0; 47 | if any(Fvalscan) 48 | % If there's a significant line, pull the max one 49 | [~, rmaxidx] = max(Fvalscan); 50 | indx = ridx(1) + rmaxidx - 1; 51 | frequencyMask(indx) = true; 52 | f0Significant(n) = true; 53 | end 54 | end 55 | else 56 | % Remove exact lines if significant 57 | for n = 1:length(f0); 58 | [~, itemp] = min(abs(f - f0(n))); 59 | frequencyMask(itemp) = Fval(itemp) >= sig; 60 | f0Significant(n) = frequencyMask(itemp); 61 | end; 62 | end 63 | 64 | % Estimate the contribution of any significant f0 lines 65 | fSig = f(frequencyMask); 66 | aSig = A(frequencyMask); 67 | FvalSig = Fval(frequencyMask); 68 | if ~isempty(fSig) 69 | datafit = exp(1i*2*pi*(0:(N - 1))'*fSig/Fs)* aSig ... 70 | + exp(-1i*2*pi*(0:(N - 1))'*fSig/Fs)*conj(aSig); 71 | end -------------------------------------------------------------------------------- /getStructureParameters.m: -------------------------------------------------------------------------------- 1 | function p = getStructureParameters(mystruct, myfield, value) 2 | % Sets p to mystruct.myfield if it exists, other assigns it to value 3 | if ~exist('value', 'var') && ~isfield(mystruct, myfield) 4 | error('Either value of mystruct.myfield must exist'); 5 | elseif exist('value', 'var') && ~isfield(mystruct, myfield) 6 | p = value; 7 | else 8 | p = mystruct.(myfield); 9 | end 10 | -------------------------------------------------------------------------------- /pop_cleanline.m: -------------------------------------------------------------------------------- 1 | function [EEGclean, commstr, g, Sorig, Sclean, f, amps, freqs] = pop_cleanline(EEG, varargin) 2 | 3 | % Mandatory Information 4 | % -------------------------------------------------------------------------------------------------- 5 | % EEG EEGLAB data structure 6 | % -------------------------------------------------------------------------------------------------- 7 | % 8 | % Optional Information 9 | % -------------------------------------------------------------------------------------------------- 10 | % Type 'doc cleanline' for additional arguments 11 | % 12 | % See Also: cleanline() 13 | 14 | % Author: Tim Mullen, SCCN/INC/UCSD Copyright (C) 2011 15 | % Date: Nov 20, 2011 16 | % 17 | % 18 | % This program is free software; you can redistribute it and/or modify 19 | % it under the terms of the GNU General Public License as published by 20 | % the Free Software Foundation; either version 3 of the License, or 21 | % (at your option) any later version. 22 | % 23 | % This program is distributed in the hope that it will be useful, 24 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | % GNU General Public License for more details. 27 | % 28 | % You should have received a copy of the GNU General Public License 29 | % along with this program; if not, write to the Free Software 30 | % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 31 | 32 | 33 | % defaults 34 | EEGclean = EEG; 35 | [commstr, Sorig, Sclean, f, amps, freqs, g] = deal([]); 36 | 37 | 38 | if nargin<2 39 | % render GUI 40 | g = arg_guidialog(@cleanline_check,'Parameters',{'EEG',EEG},'Title','CleanLine Options','Invoke',false); 41 | 42 | if isempty(g) 43 | return; 44 | end 45 | else 46 | g = hlp_varargin2struct(varargin); 47 | end 48 | 49 | if length(EEG) > 1 50 | [EEGclean , com] = eeg_eval('cleanline', EEG, 'params', varargin); 51 | else 52 | [EEGclean, Sorig, Sclean, f, amps, freqs, g] = cleanline(EEG, g); 53 | end 54 | 55 | % 06/22/2018 Makoto. Disabled. 56 | % 57 | % if ~isempty(Sorig) 58 | % 59 | % % plot the original and cleaned spectra 60 | % eegplot(Sorig,'data2',Sclean, ... 61 | % 'title',sprintf('Original and Cleaned %s spectra for selected %s',fastif(g.normSpectrum,'normalized',''),g.sigtype),'srate',length(f)/f(end), ... 62 | % 'winlength',f(end),'submean','on'); %,'trialstag',1/length(f)); 63 | % 64 | % ax = findobj(gcf,'tag','eegaxis'); 65 | % xlabel(ax,'Frequency (Hz)'); 66 | % title(ax,sprintf('Original and Cleaned %s spectra for selected %s',fastif(g.normSpectrum,'normalized',''),g.sigtype)); 67 | % set(ax,'Yticklabel',[{''}; cellstr(num2str(g.chanlist(end:-1:1)'))]); 68 | % % set(ax,'Xtick',1:10:length(f)); 69 | % % set(ax,'Xticklabel',f(1:10:end)); 70 | % plts = get(ax,'children'); 71 | % legend([plts(end) plts(1)],'original','cleaned'); 72 | % 73 | % end 74 | 75 | commstr = sprintf('EEG = pop_cleanline(EEG, %s);', vararg2str(hlp_struct2varargin(g,'suppress',{'arg_direct','EEG','report_args'}))); 76 | 77 | -------------------------------------------------------------------------------- /private/checkTapers.m: -------------------------------------------------------------------------------- 1 | function [tapers, eigs]= checkTapers(tapers, N, Fs) 2 | % Helper function to calculate tapers and, if precalculated tapers are supplied, 3 | % to check that they (the precalculated tapers) the same length in time as 4 | % the time series being studied. The length of the time series is specified 5 | % as the second input argument N. Thus if precalculated tapers have 6 | % dimensions [N1 K], we require that N1=N. 7 | % Usage: tapers=dpsschk(tapers,N,Fs) 8 | % Inputs: 9 | % tapers (tapers in the form of: 10 | % (i) precalculated tapers or, 11 | % (ii) [NW K] - time-bandwidth product, number of tapers) 12 | % 13 | % N (number of samples) 14 | % Fs (sampling frequency - this is required for nomalization of 15 | % tapers: we need tapers to be such 16 | % that integral of the square of each taper equals 1 17 | % dpss computes tapers such that the 18 | % SUM of squares equals 1 - so we need 19 | % to multiply the dpss computed tapers 20 | % by sqrt(Fs) to get the right 21 | % normalization) 22 | % Outputs: 23 | % tapers (calculated or precalculated tapers) 24 | % eigs (eigenvalues) 25 | if nargin < 3; error('Need all arguments'); end 26 | if length(tapers) == 3 % Fix taper specification 27 | % Compute timebandwidth product 28 | TW = tapers(2)* tapers(1); 29 | % Compute number of tapers 30 | K = floor(2*TW - tapers(3)); 31 | tapers = [TW, K]; 32 | end 33 | sz = size(tapers); 34 | if sz(1) == 1 && sz(2) == 2; 35 | [tapers, eigs] = dpss(N, tapers(1), tapers(2)); 36 | tapers = tapers*sqrt(Fs); 37 | elseif N ~= sz(1); 38 | error('seems to be an error in your dpss calculation; the number of time points is different from the length of the tapers'); 39 | end; 40 | -------------------------------------------------------------------------------- /private/design_fir.m: -------------------------------------------------------------------------------- 1 | function B = design_fir(N,F,A,nfft,W) 2 | % B = design_fir(N,F,A,nFFT,W) 3 | % Design an FIR filter using the frequency-sampling method. 4 | % 5 | % The frequency response is interpolated cubically between the specified 6 | % frequency points. 7 | % 8 | % In: 9 | % N : order of the filter 10 | % 11 | % F : vector of frequencies at which amplitudes shall be defined 12 | % (starts with 0 and goes up to 1; try to avoid too 13 | % sharp transitions) 14 | % 15 | % A : vector of amplitudes, one value per specified frequency 16 | % 17 | % nFFT : optionally number of FFT bins to use 18 | % 19 | % W : optionally the window function to use (default: Hamming) 20 | % 21 | % Out: 22 | % B : designed filter kernel 23 | % 24 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 25 | % 2013-08-14 26 | 27 | % Copyright (C) Christian Kothe, SCCN, 2013, ckothe@ucsd.edu 28 | % 29 | % This program is free software; you can redistribute it and/or modify it under the terms of the GNU 30 | % General Public License as published by the Free Software Foundation; either version 2 of the 31 | % License, or (at your option) any later version. 32 | % 33 | % This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 34 | % even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 35 | % General Public License for more details. 36 | % 37 | % You should have received a copy of the GNU General Public License along with this program; if not, 38 | % write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 39 | % USA 40 | 41 | if nargin < 4 || isempty(nfft) 42 | nfft = max(512,2^ceil(log(N)/log(2))); end 43 | if nargin < 5 44 | W = 0.54 - 0.46*cos(2*pi*(0:N)/N); end 45 | 46 | % calculate interpolated frequency response 47 | F = interp1(round(F*nfft),A,(0:nfft),'pchip'); 48 | 49 | % set phase & transform into time domain 50 | F = F .* exp(-(0.5*N)*sqrt(-1)*pi*(0:nfft)./nfft); 51 | B = real(ifft([F conj(F(end-1:-1:2))])); 52 | 53 | % apply window to kernel 54 | B = B(1:N+1).*W(:)'; 55 | -------------------------------------------------------------------------------- /private/filtfilt_fast.m: -------------------------------------------------------------------------------- 1 | function X = filtfilt_fast(varargin) 2 | % Like filtfilt(), but faster when filter and signal are long (and A=1). 3 | % Y = filtfilt_fast(B,A,X) 4 | % 5 | % Uses FFT convolution (needs fftfilt). The function is faster than filter when approx. 6 | % length(B)>256 and size(X,Dim)>1024, otherwise slower (due size-testing overhead). 7 | % 8 | % Note: 9 | % Can also be called with four arguments, as Y = filtfilt_fast(N,F,A,X), in which case an Nth order 10 | % FIR filter is designed that has the desired frequency response A at normalized frequencies F; F 11 | % must be a vector of numbers increasing from 0 to 1. 12 | % 13 | % See also: 14 | % filtfilt, filter 15 | % 16 | % Christian Kothe, Swartz Center for Computational Neuroscience, UCSD 17 | % 2010-07-14 18 | 19 | % Copyright (C) Christian Kothe, SCCN, 2010, ckothe@ucsd.edu 20 | % 21 | % This program is free software; you can redistribute it and/or modify it under the terms of the GNU 22 | % General Public License as published by the Free Software Foundation; either version 2 of the 23 | % License, or (at your option) any later version. 24 | % 25 | % This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 26 | % even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 27 | % General Public License for more details. 28 | % 29 | % You should have received a copy of the GNU General Public License along with this program; if not, 30 | % write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 31 | % USA 32 | 33 | if nargin == 3 34 | [B A X] = deal(varargin{:}); 35 | elseif nargin == 4 36 | [N F M X] = deal(varargin{:}); 37 | B = design_fir(N,F,sqrt(M)); A = 1; % note: we use the sqrt() because we run forward and backward 38 | else 39 | help filtfilt_fast; 40 | return; 41 | end 42 | 43 | if A == 1 44 | was_single = strcmp(class(X),'single'); 45 | w = length(B); t = size(X,1); 46 | % extrapolate 47 | X = double([bsxfun(@minus,2*X(1,:),X(1+mod(((w+1):-1:2)-1,t),:)); X; bsxfun(@minus,2*X(t,:),X(1+mod(((t-1):-1:(t-w))-1,t),:))]); 48 | % filter, reverse 49 | X = filter_fast(B,A,X); X = X(length(X):-1:1,:); 50 | % filter, reverse 51 | X = filter_fast(B,A,X); X = X(length(X):-1:1,:); 52 | % remove extrapolated pieces 53 | X([1:w t+w+(1:w)],:) = []; 54 | if was_single 55 | X = single(X); end 56 | else 57 | % fall back to filtfilt for the IIR case 58 | X = filtfilt(B,A,X); 59 | end 60 | -------------------------------------------------------------------------------- /private/spherical_interpolate.m: -------------------------------------------------------------------------------- 1 | function [W, Gss, Gds, Hds] = ... 2 | spherical_interpolate(src, dest, lambda, order, type, tol) 3 | % Caclulate an interpolation matrix for spherical interpolation 4 | % 5 | % W = sphericalSplineInterpolate(src, dest, lambda, order, type, tol) 6 | % 7 | % Inputs: 8 | % src - [3 x N] old electrode positions 9 | % dest - [3 x M] new electrode positions 10 | % lambda - [float] regularisation parameter for smoothing the estimates (1e-5) 11 | % order - [float] order of the polynomial interpolation to use (4) 12 | % type - [str] one of; ('spline') 13 | % 'spline' - spherical Spline 14 | % 'slap' - surface Laplacian (aka. CSD) 15 | % tol - [float] tolerance for the legendre poly approx (1e-7) 16 | % 17 | % Outputs: 18 | % W - [M x N] linear mapping matrix between old and new co-ords 19 | % 20 | % Based upon the paper: Perrin89 21 | 22 | % Copyright 2009- by Jason D.R. Farquhar (jdrf@zepler.org) 23 | % Permission is granted for anyone to copy, use, or modify this 24 | % software and accompanying documents, provided this copyright 25 | % notice is retained, and note is made of any changes that have been 26 | % made. This software and documents are distributed without any 27 | % warranty, express or implied. 28 | % 29 | % Modified by Kay Robbins 8/24/2014: Minor cleanup and simplification 30 | % Warning --- still in progress 31 | 32 | if ( nargin < 3 || isempty(lambda) ) lambda = 1e-5; end; %#ok 33 | if ( nargin < 4 || isempty(order) ) order = 4; end; %#ok 34 | if ( nargin < 5 || isempty(type)) type = 'spline'; end; %#ok 35 | if ( nargin < 6 || isempty(tol) ) tol = eps; end; %#ok 36 | 37 | % Map the positions onto the sphere (not using repop, by JMH) 38 | src = src./repmat(sqrt(sum(src.^2)), size(src, 1), 1); 39 | dest = dest./repmat(sqrt(sum(dest.^2)), size(dest, 1), 1); 40 | 41 | % Calculate the cosine of the angle between the new and old electrodes. If 42 | % the vectors are on top of each other, the result is 1, if they are 43 | % pointing the other way, the result is -1 44 | cosSS = src'*src; % angles between source positions 45 | cosDS = dest'*src; % angles between destination positions 46 | 47 | % Compute the interpolation matrix to tolerance tol 48 | [Gss] = interpMx(cosSS, order, tol); % [nSrc x nSrc] 49 | [Gds, Hds] = interpMx(cosDS, order, tol); % [nDest x nSrc] 50 | 51 | % Include the regularisation 52 | if lambda > 0 53 | Gss = Gss + lambda*eye(size(Gss)); 54 | end 55 | 56 | % Compute the mapping to the polynomial coefficients space % [nSrc+1 x nSrc+1] 57 | % N.B. this can be numerically unstable so use the PINV to solve.. 58 | muGss = 1; % Used to improve condition number when inverting. Probably unnecessary 59 | C = [Gss muGss*ones(size(Gss, 1),1); muGss*ones(1, size(Gss,2)) 0]; 60 | iC = pinv(C); 61 | 62 | % Compute the mapping from source measurements and positions to destination positions 63 | if ( strcmpi(type, 'spline') ) 64 | W = [Gds ones(size(Gds, 1), 1).*muGss]*iC(:, 1:end-1); % [nDest x nSrc] 65 | elseif (strcmpi(type, 'slap')) 66 | W = Hds*iC(1:end-1, 1:end-1); % [nDest x nSrc] 67 | end 68 | return; 69 | %-------------------------------------------------------------------------- 70 | function [G, H]=interpMx(cosEE, order, tol) 71 | % compute the interpolation matrix for this set of point pairs 72 | if ( nargin < 3 || isempty(tol) ) 73 | tol = 1e-10; 74 | end 75 | G = zeros(size(cosEE)); H = zeros(size(cosEE)); 76 | for i = 1:numel(cosEE); 77 | x = cosEE(i); 78 | n = 1; Pns1 = 1; Pn = x; % seeds for the legendre ploy recurrence 79 | tmp = ( (2*n + 1) * Pn ) / ((n*n + n).^order); 80 | G(i) = tmp ; % 1st element in the sum 81 | H(i) = (n*n + n)*tmp; % 1st element in the sum 82 | dG = abs(G(i)); dH = abs(H(i)); 83 | for n = 2:500; % do the sum 84 | Pns2 = Pns1; Pns1 = Pn; 85 | Pn=((2*n - 1)*x*Pns1 - (n - 1)*Pns2)./n; % legendre poly recurrence 86 | oGi = G(i); oHi = H(i); 87 | tmp = ((2*n+1) * Pn) / ((n*n+n).^order); 88 | G(i) = G(i) + tmp; % update function estimate, spline interp 89 | H(i) = H(i) + (n*n + n)*tmp; % update function estimate, SLAP 90 | dG = (abs(oGi - G(i)) + dG)/2; 91 | dH = (abs(oHi - H(i)) + dH)/2; % moving ave gradient est for convergence 92 | if (dG < tol && dH < tol) 93 | break; 94 | end; % stop when tol reached 95 | end 96 | end 97 | G = G./(4*pi); 98 | H = H./(4*pi); 99 | return; 100 | 101 | -------------------------------------------------------------------------------- /removeLinesMovingWindow.m: -------------------------------------------------------------------------------- 1 | function data = removeLinesMovingWindow(data, lineNoise) 2 | % Removes significant sine waves from (continuous) data using overlapping windows. 3 | % 4 | % Usage: 5 | % data = removeLinesMovingWindow(data, lineNoise) 6 | % 7 | % Parameters 8 | % data data in [N,1] (a single time column vector) 9 | % lineNoise structure with various parameters set 10 | % 11 | % The lineNoise structure has the following fields set: 12 | % fPassBand Frequency band used 13 | % Fs Sampling frequency 14 | % fScanBandWidth +/- bandwidth centered on each f0 to scan for significant 15 | % lines (TM) 16 | % lineFrequencies Line frequencies to be removed 17 | % maximumIterations Maximum times to iterate removal 18 | % p Significance level cutoff 19 | % pad FFT padding factor 20 | % tapers Precomputed tapers from dpss 21 | % taperWindowSize Taper sliding window length (seconds) 22 | % taperWindowStep Sliding window step size (seconds) 23 | % tau Window overlap smoothing factor 24 | % 25 | % Output: 26 | % data Cleaned up data 27 | % 28 | if nargin < 2 29 | error('removeLinesMovingWindow:NotEnoughArguments', ... 30 | 'Need data and window parameters'); 31 | end; 32 | Fs = getStructureParameters(lineNoise, 'Fs'); 33 | tau = getStructureParameters(lineNoise, 'tau'); 34 | 35 | % Window,overlap and frequency information 36 | data = change_row_to_column(data); 37 | N = size(data, 1); 38 | Nwin = round(Fs*lineNoise.taperWindowSize); % number of samples in window 39 | Nstep = round(lineNoise.taperWindowStep*Fs); % number of samples to step through 40 | Noverlap = Nwin - Nstep; % number of points in overlap 41 | x = (1:Noverlap)'; 42 | smooth = 1./(1+exp(-tau.*(x - Noverlap/2)/Noverlap)); % sigmoidal function 43 | winstart = 1:Nstep:(N - Nwin + 1); 44 | nw = length(winstart); 45 | datafit = zeros(winstart(nw) + Nwin - 1, 1); 46 | 47 | fidx = zeros(length(lineNoise.lineFrequencies), 1); 48 | f0 = lineNoise.lineFrequencies; 49 | [initialSpectrum, f] = calculateSegmentSpectrum(data, lineNoise); 50 | initialSpectrum = 10*log10(initialSpectrum); 51 | for fk = 1:length(lineNoise.lineFrequencies) 52 | [dummy, fidx(fk)] = min(abs(f - lineNoise.lineFrequencies(fk))); %#ok 53 | end 54 | 55 | for iteration = 1:lineNoise.maximumIterations 56 | f0Mask = false(1, length(f0)); 57 | for n = 1:nw 58 | indx = winstart(n):(winstart(n) + Nwin - 1); 59 | datawin = data(indx); 60 | [datafitwin, f0Sig] = ... 61 | fitSignificantFrequencies(datawin, f0, lineNoise); 62 | 63 | f0Mask = f0Mask | f0Sig; 64 | % datafitwin0 = datafitwin; incorrectly placed 65 | if n > 1 66 | datafitwin(1:Noverlap)= smooth.*datafitwin(1:Noverlap) + ... 67 | (1 - smooth).*datafitwin0((Nwin - Noverlap + 1):Nwin); 68 | end; 69 | datafit(indx, :) = datafitwin; 70 | datafitwin0 = datafitwin; % Moved from above the if statement 71 | end 72 | 73 | data(1:size(datafit, 1)) = data(1:size(datafit, 1)) - datafit; 74 | if sum(f0Mask) > 0 75 | % Now find the line frequencies that have converged 76 | cleanedSpectrum = calculateSegmentSpectrum(data, lineNoise); 77 | cleanedSpectrum = 10*log10(cleanedSpectrum); 78 | dBReduction = initialSpectrum - cleanedSpectrum; 79 | tIndex = (dBReduction(fidx) < 0)'; 80 | f0(tIndex | ~f0Mask) = []; 81 | fidx(tIndex | ~f0Mask) = []; 82 | initialSpectrum = cleanedSpectrum; 83 | end 84 | if isempty(f0) 85 | break; 86 | end 87 | end 88 | data = data'; -------------------------------------------------------------------------------- /testSignificantFrequencies.m: -------------------------------------------------------------------------------- 1 | function [Fval, A, f, sig ] = testSignificantFrequencies(data, lineNoise) 2 | % Computes the F-statistic for sine wave in locally-white noise (continuous data). 3 | % 4 | % Usage: 5 | % [Fval, A, f, sig ,sd] = testSignificantFrequencies(data,lineNoise) 6 | % 7 | % Parameters: 8 | % data Single channel -- required 9 | % lineNoise Structure with various parameters set 10 | % 11 | % The lineNoise structure has the following fields set: 12 | % fPassBand Frequency band used 13 | % Fs Sampling frequency 14 | % p Significance level cutoff 15 | % pad FFT padding factor 16 | % tapers Precomputed tapers from dpss 17 | % taperWindowSize Taper sliding window length 18 | % 19 | % Outputs: 20 | % Fval F-statistic in frequency x 1 form 21 | % A Line amplitude for X in frequency x 1 22 | % f Frequencies of evaluation 23 | % sig F distribution (1-p)% confidence level 24 | % 25 | 26 | %% Process the input arguments 27 | if nargin < 1 28 | error('testSignificantFrequencies:NoData', ... 29 | 'Must provide data as the first argument'); 30 | elseif nargin < 2 31 | error('testSignificantFrequencies:NoParameters', ... 32 | 'Must provide a lineNoise parameter structure as second argument'); 33 | end 34 | pad = getStructureParameters(lineNoise, 'pad'); 35 | Fs = getStructureParameters(lineNoise, 'Fs'); 36 | fpass = getStructureParameters(lineNoise, 'fPassBand'); 37 | 38 | data = change_row_to_column(data); 39 | C = size(data, 2); 40 | p = getStructureParameters(lineNoise, 'p', 0.01); 41 | tapers = getStructureParameters(lineNoise, 'tapers'); % Calculate the actual tapers 42 | if isempty(tapers) 43 | error('testSignificantFrequencies:NoTapers', ... 44 | 'Must provide a tapers field in the lineNoise parameter structure'); 45 | end 46 | 47 | [N, K] = size(tapers); 48 | nfft = max(2^(nextpow2(N) + pad), N);% number of points in fft 49 | [f, findx] = getfgrid(Fs, nfft, fpass);% frequency grid to be returned 50 | 51 | %% Now compute the taper spectrum 52 | Kodd = 1:2:K; 53 | Keven = 2:2:K; 54 | J = mtfftc(data, tapers, nfft, Fs);% tapered fft of data - f x K x C 55 | Jp = J(findx, Kodd, :); % drop the even ffts and restrict fft to specified frequency grid - f x K x C 56 | tapers = tapers(:, :, ones(1, C)); % add channel indices to the tapers - t x K x C 57 | H0 = squeeze(sum(tapers(:, Kodd, :), 1)); % calculate sum of tapers for even prolates - K x C 58 | if C == 1 59 | H0=H0'; 60 | end; 61 | Nf = length(findx); % Number of frequencies 62 | H0 = H0(:, :, ones(1, Nf)); % Add frequency indices to H0 - K x C x f 63 | H0 = permute(H0,[3, 1, 2]); % Permute H0 to get dimensions to match those of Jp - f x K x C 64 | H0sq = sum(H0.*H0, 2); % Sum of squares of H0^2 across taper indices - f x C 65 | JpH0 = sum(Jp.*squeeze(H0), 2);% sum of the product of Jp and H0 across taper indices - f x C 66 | A = squeeze(JpH0./H0sq); % amplitudes for all frequencies and channels 67 | Kp = size(Jp, 2); % number of even prolates 68 | Ap = A(:, :, ones(1, Kp)); % add the taper index to C 69 | Ap = permute(Ap,[1, 3, 2]); % permute indices to match those of H0 70 | Jhat = Ap.*H0; % fitted value for the fft 71 | 72 | num = (K - 1).*(abs(A).^2).*squeeze(H0sq);%numerator for F-statistic 73 | den = squeeze(sum(abs(Jp - Jhat).^2, 2) + ... 74 | sum(abs(J(findx, Keven, :)).^2, 2));% denominator for F-statistic 75 | Fval = num./den; % F-statisitic 76 | sig = finv(1 - p, 2, 2*K - 2); % F-distribution based 1-p% point 77 | A = A*Fs; 78 | 79 | -------------------------------------------------------------------------------- /utils/hlp_vrect.m: -------------------------------------------------------------------------------- 1 | function [patchHandles textHandles] = hlp_vrect(x, varargin) 2 | % Tim Mullen, 2011, SCCN/INC/UCSD 3 | 4 | g = finputcheck(varargin, ... 5 | {'yscale' 'real' [] 1; ... % vertical scaling (relative to ylimits) 6 | 'dock' 'string' {'bottom','top','none'} 'top'; ... % whether to 'dock' the patch at the top or bottom of the axis. If 'none' then scale is location on yaxis of [bottom top] of rect 7 | 'label' '' [] {}; ... 8 | 'axesHandle' '' [] gca; ... 9 | 'textPosition' 'real' [0 1] [0.5 0.02]; ... 10 | 'textProperties' 'cell' [] {}; ... 11 | 'patchProperties' 'cell' [] {'FaceColor',[0.7 0.7 1],'FaceAlpha',0.5,'EdgeColor',[0.2 0.2 0.2],'EdgeAlpha',0.5} ... 12 | },'hlp_vrect','error','quiet'); 13 | 14 | if ischar(g) 15 | help hlp_vrect; 16 | error(g); 17 | end 18 | 19 | pp = hlp_varargin2struct(g.patchProperties); 20 | if ~isfield(pp,'FaceColor'); 21 | FaceColor = [0.7 0.7 1]; 22 | else 23 | FaceColor = pp.FaceColor; 24 | end 25 | clear pp; 26 | 27 | xsize = size(x); 28 | if( xsize(2)~=2 ) 29 | error('x must have two columns'); 30 | end 31 | 32 | if ~iscell(g.label) 33 | g.label = {g.label}; 34 | end 35 | 36 | if length(g.label)~=xsize(1) 37 | g.label = repmat(g.label,xsize(1),1); 38 | end 39 | 40 | if size(g.textPosition,2) ~= 2 41 | error('textPosition must have two columns [ (x,y) position ]'); 42 | end 43 | 44 | if size(g.textPosition,1)~=xsize(1) 45 | g.textPosition=repmat(g.textPosition,xsize(1),1); 46 | end 47 | 48 | textPositionX = g.textPosition(:,1); 49 | textPositionY = g.textPosition(:,2); 50 | 51 | holdState = ishold(g.axesHandle); 52 | hold(g.axesHandle, 'on'); 53 | 54 | if strcmpi(g.dock,'none') 55 | yLimits = g.yscale; 56 | else 57 | yl = get(g.axesHandle,'ylim'); % Row vector 58 | yLimits = yl.*g.yscale; 59 | end 60 | 61 | if any(g.yscale<1) 62 | switch g.dock 63 | case 'bottom' 64 | yLimits = yLimits-(yLimits(1)-yl(1))+0.001*diff(yLimits); 65 | case 'top' 66 | yLimits = yLimits+(yl(2)-yLimits(2))-0.001*diff(yLimits); 67 | end 68 | end 69 | 70 | % bring desired axes into focus 71 | set(gcf,'CurrentAxes',g.axesHandle); 72 | 73 | patchHandles = zeros(1,xsize(1)); 74 | textHandles = []; 75 | 76 | for k=1:xsize(1) 77 | % for each patch 78 | patchHandles(k) = patch([x(k,1) x(k,1) x(k,2) x(k,2)], [yLimits yLimits(end:-1:1)],FaceColor,g.patchProperties{:}); 79 | 80 | 81 | if( ~isempty(g.label) ) 82 | % xLimits = get(g.axesHandle,'xlim'); 83 | % xLowerLimit = xLimits(1); 84 | % xUpperLimit = xLimits(2); 85 | % xRange = xUpperLimit - xLowerLimit; 86 | xPosition = x(k,1) + textPositionX(k,:)*(x(k,2)-x(k,1)); 87 | 88 | yUpperLimit = yLimits(2); 89 | yLowerLimit = yLimits(1); 90 | yRange = yUpperLimit - yLowerLimit; 91 | Yposition = yLowerLimit + textPositionY(k,:)*yRange; 92 | % Yposition = repmat(yPosition, length(x), 1); 93 | 94 | % textHandle is a vector corresponding to the line 95 | textHandles(k) = text(xPosition, Yposition, g.label{k}, 'Parent', g.axesHandle,g.textProperties{:}); 96 | % center text 97 | extent = get(textHandles(k),'Extent'); 98 | set(textHandles(k),'Position',[xPosition-extent(3)/2 Yposition]); 99 | 100 | end 101 | end 102 | 103 | 104 | if( holdState==false ) 105 | hold(g.axesHandle, 'off'); 106 | end 107 | --------------------------------------------------------------------------------