plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
P-Chao/acfdetect-master
checkNumArgs.m
.m
acfdetect-master/toolbox/matlab/checkNumArgs.m
3,796
utf_8
726c125c7dc994c4989c0e53ad4be747
function [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag ) % Helper utility for checking numeric vector arguments. % % Runs a number of tests on the numeric array x. Tests to see if x has all % integer values, all positive values, and so on, depending on the values % for intFlag and signFlag. Also tests to see if the size of x matches siz % (unless siz==[]). If x is a scalar, x is converted to a array simply by % creating a matrix of size siz with x in each entry. This is why the % function returns x. siz=M is equivalent to siz=[M M]. If x does not % satisfy some criteria, an error message is returned in er. If x satisfied % all the criteria er=''. Note that error('') has no effect, so can use: % [ x, er ] = checkNumArgs( x, ... ); error(er); % which will throw an error only if something was wrong with x. % % USAGE % [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag ) % % INPUTS % x - numeric array % siz - []: does not test size of x % - [if not []]: intended size for x % intFlag - -1: no need for integer x % 0: error if non integer x % 1: error if non odd integers % 2: error if non even integers % signFlag - -2: entires of x must be strictly negative % -1: entires of x must be negative % 0: no contstraints on sign of entries in x % 1: entires of x must be positive % 2: entires of x must be strictly positive % % OUTPUTS % x - if x was a scalar it may have been replicated into a matrix % er - contains error msg if anything was wrong with x % % EXAMPLE % a=1; [a, er]=checkNumArgs( a, [1 3], 2, 0 ); a, error(er) % % See also NARGCHK % % Piotr's Computer Vision Matlab Toolbox Version 2.0 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] xname = inputname(1); er=''; if( isempty(siz) ); siz = size(x); end; if( length(siz)==1 ); siz=[siz siz]; end; % first check that x is numeric if( ~isnumeric(x) ); er = [xname ' not numeric']; return; end; % if x is a scalar, simply replicate it. xorig = x; if( length(x)==1); x = x(ones(siz)); end; % regardless, must have same number of x as n if( length(siz)~=ndims(x) || ~all(size(x)==siz) ) er = ['has size = [' num2str(size(x)) '], ']; er = [er 'which is not the required size of [' num2str(siz) ']']; er = createErrMsg( xname, xorig, er ); return; end % check that x are the right type of integers (unless intFlag==-1) switch intFlag case 0 if( ~all(mod(x,1)==0)) er = 'must have integer entries'; er = createErrMsg( xname, xorig, er); return; end; case 1 if( ~all(mod(x,2)==1)) er = 'must have odd integer entries'; er = createErrMsg( xname, xorig, er); return; end; case 2 if( ~all(mod(x,2)==0)) er = 'must have even integer entries'; er = createErrMsg( xname, xorig, er ); return; end; end; % check sign of entries in x (unless signFlag==0) switch signFlag case -2 if( ~all(x<0)) er = 'must have strictly negative entries'; er = createErrMsg( xname, xorig, er ); return; end; case -1 if( ~all(x<=0)) er = 'must have negative entries'; er = createErrMsg( xname, xorig, er ); return; end; case 1 if( ~all(x>=0)) er = 'must have positive entries'; er = createErrMsg( xname, xorig, er ); return; end; case 2 if( ~all(x>0)) er = 'must have strictly positive entries'; er = createErrMsg( xname, xorig, er ); return; end end function er = createErrMsg( xname, x, er ) if(numel(x)<10) er = ['Numeric input argument ' xname '=[' num2str(x) '] ' er '.']; else er = ['Numeric input argument ' xname ' ' er '.']; end
github
P-Chao/acfdetect-master
fevalDistr.m
.m
acfdetect-master/toolbox/matlab/fevalDistr.m
11,227
utf_8
7e4d5077ef3d7a891b2847cb858a2c6c
function [out,res] = fevalDistr( funNm, jobs, varargin ) % Wrapper for embarrassingly parallel function evaluation. % % Runs "r=feval(funNm,jobs{i}{:})" for each job in a parallel manner. jobs % should be a cell array of length nJob and each job should be a cell array % of parameters to pass to funNm. funNm must be a function in the path and % must return a single value (which may be a dummy value if funNm writes % results to disk). Different forms of parallelization are supported % depending on the hardware and Matlab toolboxes available. The type of % parallelization is determined by the parameter 'type' described below. % % type='LOCAL': jobs are executed using a simple "for" loop. This implies % no parallelization and is the default fallback option. % % type='PARFOR': jobs are executed using a "parfor" loop. This option is % only available if the Matlab *Parallel Computing Toolbox* is installed. % Make sure to setup Matlab workers first using "matlabpool open". % % type='DISTR': jobs are executed on the Caltech cluster. Distributed % queuing system must be installed separately. Currently this option is % only supported on the Caltech cluster but could easily be installed on % any Linux cluster as it requires only SSH and a shared filesystem. % Parameter pLaunch is used for controller('launchQueue',pLaunch{:}) and % determines cluster machines used (e.g. pLaunch={48,401:408}). % % type='COMPILED': jobs are executed locally in parallel by first compiling % an executable and then running it in background. This option requires the % *Matlab Compiler* to be installed (but does NOT require the Parallel % Computing Toolbox). Compiling can take 1-10 minutes, so use this option % only for large jobs. (On Linux alter startup.m by calling addpath() only % if ~isdeployed, otherwise will get error about "CTF" after compiling). % Note that relative paths will not work after compiling so all paths used % by funNm must be absolute paths. % % type='WINHPC': jobs are executed on a Windows HPC Server 2008 cluster. % Similar to type='COMPILED', except after compiling, the executable is % queued to the HPC cluster where all computation occurs. This option % likewise requires the *Matlab Compiler*. Paths to data, etc., must be % absolute paths and available from HPC cluster. Parameter pLaunch must % have two fields 'scheduler' and 'shareDir' that define the HPC Server. % Extra parameters in pLaunch add finer control, see fedWinhpc for details. % For example, at MSR one possible cluster is defined by scheduler = % 'MSR-L25-DEV21' and shareDir = '\\msr-arrays\scratch\msr-pool\L25-dev21'. % Note call to 'job submit' from Matlab will hang unless pwd is saved % (simply call 'job submit' from cmd prompt and enter pwd). % % USAGE % [out,res] = fevalDistr( funNm, jobs, [varargin] ) % % INPUTS % funNm - name of function that will process jobs % jobs - [1xnJob] cell array of parameters for each job % varargin - additional params (struct or name/value pairs) % .type - ['local'], 'parfor', 'distr', 'compiled', 'winhpc' % .pLaunch - [] extra params for type='distr' or type='winhpc' % .group - [1] send jobs in batches (only relevant if type='distr') % % OUTPUTS % out - 1 if jobs completed successfully % res - [1xnJob] cell array containing results of each job % % EXAMPLE % % Note: in this case parallel versions are slower since conv2 is so fast % n=16; jobs=cell(1,n); for i=1:n, jobs{i}={rand(500),ones(25)}; end % tic, [out,J1] = fevalDistr('conv2',jobs,'type','local'); toc, % tic, [out,J2] = fevalDistr('conv2',jobs,'type','parfor'); toc, % tic, [out,J3] = fevalDistr('conv2',jobs,'type','compiled'); toc % [isequal(J1,J2), isequal(J1,J3)], figure(1); montage2(cell2array(J1)) % % See also matlabpool mcc % % Piotr's Computer Vision Matlab Toolbox Version 3.26 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] dfs={'type','local','pLaunch',[],'group',1}; [type,pLaunch,group]=getPrmDflt(varargin,dfs,1); store=(nargout==2); if(isempty(jobs)), res=cell(1,0); out=1; return; end switch lower(type) case 'local', [out,res]=fedLocal(funNm,jobs,store); case 'parfor', [out,res]=fedParfor(funNm,jobs,store); case 'distr', [out,res]=fedDistr(funNm,jobs,pLaunch,group,store); case 'compiled', [out,res]=fedCompiled(funNm,jobs,store); case 'winhpc', [out,res]=fedWinhpc(funNm,jobs,pLaunch,store); otherwise, error('unkown type: ''%s''',type); end end function [out,res] = fedLocal( funNm, jobs, store ) % Run jobs locally using for loop. nJob=length(jobs); res=cell(1,nJob); out=1; tid=ticStatus('collecting jobs'); for i=1:nJob, r=feval(funNm,jobs{i}{:}); if(store), res{i}=r; end; tocStatus(tid,i/nJob); end end function [out,res] = fedParfor( funNm, jobs, store ) % Run jobs locally using parfor loop. nJob=length(jobs); res=cell(1,nJob); out=1; parfor i=1:nJob, r=feval(funNm,jobs{i}{:}); if(store), res{i}=r; end; end end function [out,res] = fedDistr( funNm, jobs, pLaunch, group, store ) % Run jobs using Linux queuing system. if(~exist('controller.m','file')) msg='distributed queuing not installed, switching to type=''local''.'; warning(msg); [out,res]=fedLocal(funNm,jobs,store); return; %#ok<WNTAG> end nJob=length(jobs); res=cell(1,nJob); controller('launchQueue',pLaunch{:}); if( group>1 ) nJobGrp=ceil(nJob/group); jobsGrp=cell(1,nJobGrp); k=0; for i=1:nJobGrp, k1=min(nJob,k+group); jobsGrp{i}={funNm,jobs(k+1:k1),'type','local'}; k=k1; end nJob=nJobGrp; jobs=jobsGrp; funNm='fevalDistr'; end jids=controller('jobsAdd',nJob,funNm,jobs); k=0; fprintf('Sent %i jobs...\n',nJob); tid=ticStatus('collecting jobs'); while( 1 ) jids1=controller('jobProbe',jids); if(isempty(jids1)), pause(.1); continue; end jid=jids1(1); [r,err]=controller('jobRecv',jid); if(~isempty(err)), disp('ABORTING'); out=0; break; end k=k+1; if(store), res{jid==jids}=r; end tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end end; controller('closeQueue'); end function [out,res] = fedCompiled( funNm, jobs, store ) % Run jobs locally in background in parallel using compiled code. nJob=length(jobs); res=cell(1,nJob); tDir=jobSetup('.',funNm,'',{}); cmd=[tDir 'fevalDistrDisk ' funNm ' ' tDir ' ']; i=0; k=0; Q=feature('numCores'); q=0; tid=ticStatus('collecting jobs'); while( 1 ) % launch jobs until queue is full (q==Q) or all jobs launched (i==nJob) while(q<Q && i<nJob), q=q+1; i=i+1; jobSave(tDir,jobs{i},i); if(ispc), system2(['start /B /min ' cmd int2str2(i,10)],0); else system2([cmd int2str2(i,10) ' &'],0); end end % collect completed jobs (k1 of them), release queue slots done=jobFileIds(tDir,'done'); k1=length(done); k=k+k1; q=q-k1; for i1=done, res{i1}=jobLoad(tDir,i1,store); end pause(1); tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end end for i=1:10, try rmdir(tDir,'s'); break; catch,pause(1),end; end %#ok<CTCH> end function [out,res] = fedWinhpc( funNm, jobs, pLaunch, store ) % Run jobs using Windows HPC Server. nJob=length(jobs); res=cell(1,nJob); dfs={'shareDir','REQ','scheduler','REQ','executable','fevalDistrDisk',... 'mccOptions',{},'coresPerTask',1,'minCores',1024,'priority',2000}; p = getPrmDflt(pLaunch,dfs,1); tDir = jobSetup(p.shareDir,funNm,p.executable,p.mccOptions); for i=1:nJob, jobSave(tDir,jobs{i},i); end hpcSubmit(funNm,1:nJob,tDir,p); k=0; ticId=ticStatus('collecting jobs'); while( 1 ) done=jobFileIds(tDir,'done'); k=k+length(done); for i1=done, res{i1}=jobLoad(tDir,i1,store); end pause(5); tocStatus(ticId,k/nJob); if(k==nJob), out=1; break; end end for i=1:10, try rmdir(tDir,'s'); break; catch,pause(5),end; end %#ok<CTCH> end function tids = hpcSubmit( funNm, ids, tDir, pLaunch ) % Helper: send jobs w given ids to HPC cluster. n=length(ids); tids=cell(1,n); if(n==0), return; end; scheduler=[' /scheduler:' pLaunch.scheduler ' ']; m=system2(['cluscfg view' scheduler],0); minCores=(hpcParse(m,'total number of nodes',1) - ... hpcParse(m,'Unreachable nodes',1) - 1)*8; minCores=min([minCores pLaunch.minCores n*pLaunch.coresPerTask]); m=system2(['job new /numcores:' int2str(minCores) '-*' scheduler ... '/priority:' int2str(pLaunch.priority)],1); jid=hpcParse(m,'created job, id',0); s=min(ids); e=max(ids); p=n>1 && isequal(ids,s:e); if(p), jid1=[jid '.1']; else jid1=jid; end for i=1:n, tids{i}=[jid1 '.' int2str(i)]; end cmd0=''; if(p), cmd0=['/parametric:' int2str(s) '-' int2str(e)]; end cmd=@(id) ['job add ' jid scheduler '/workdir:' tDir ' /numcores:' ... int2str(pLaunch.coresPerTask) ' ' cmd0 ' /stdout:stdout' id ... '.txt ' pLaunch.executable ' ' funNm ' ' tDir ' ' id]; if(p), ids1='*'; n=1; else ids1=int2str2(ids); end if(n==1), ids1={ids1}; end; for i=1:n, system2(cmd(ids1{i}),1); end system2(['job submit /id:' jid scheduler],1); disp(repmat(' ',1,80)); end function v = hpcParse( msg, key, tonum ) % Helper: extract val corresponding to key in hpc msg. t=regexp(msg,': |\n','split'); t=strtrim(t(1:floor(length(t)/2)*2)); keys=t(1:2:end); vals=t(2:2:end); j=find(strcmpi(key,keys)); if(isempty(j)), error('key ''%s'' not found in:\n %s',key,msg); end v=vals{j}; if(tonum==0), return; elseif(isempty(v)), v=0; return; end if(tonum==1), v=str2double(v); return; end v=regexp(v,' ','split'); v=str2double(regexp(v{1},':','split')); if(numel(v)==4), v(5)=0; end; v=((v(1)*24+v(2))*60+v(3))*60+v(4)+v(5)/1000; end function tDir = jobSetup( rtDir, funNm, executable, mccOptions ) % Helper: prepare by setting up temporary dir and compiling funNm t=clock; t=mod(t(end),1); t=round((t+rand)/2*1e15); tDir=[rtDir filesep sprintf('fevalDistr-%015i',t) filesep]; mkdir(tDir); if(~isempty(executable) && exist(executable,'file')) fprintf('Reusing compiled executable...\n'); copyfile(executable,tDir); else t=clock; fprintf('Compiling (this may take a while)...\n'); [~,f,e]=fileparts(executable); if(isempty(f)), f='fevalDistrDisk'; end mcc('-m','fevalDistrDisk','-d',tDir,'-o',f,'-a',funNm,mccOptions{:}); t=etime(clock,t); fprintf('Compile complete (%.1f seconds).\n',t); if(~isempty(executable)), copyfile([tDir filesep f e],executable); end end end function ids = jobFileIds( tDir, type ) % Helper: get list of job files ids on disk of given type fs=dir([tDir '*-' type '*']); fs={fs.name}; n=length(fs); ids=zeros(1,n); for i=1:n, ids(i)=str2double(fs{i}(1:10)); end end function jobSave( tDir, job, ind ) %#ok<INUSL> % Helper: save job to temporary file for use with fevalDistrDisk() save([tDir int2str2(ind,10) '-in'],'job'); end function r = jobLoad( tDir, ind, store ) % Helper: load job and delete temporary files from fevalDistrDisk() f=[tDir int2str2(ind,10)]; if(store), r=load([f '-out']); r=r.r; else r=[]; end fs={[f '-done'],[f '-in.mat'],[f '-out.mat']}; delete(fs{:}); pause(.1); for i=1:3, k=0; while(exist(fs{i},'file')==2) %#ok<ALIGN> warning('Waiting to delete %s.',fs{i}); %#ok<WNTAG> delete(fs{i}); pause(5); k=k+1; if(k>12), break; end; end; end end function msg = system2( cmd, show ) % Helper: wraps system() call if(show), disp(cmd); end [status,msg]=system(cmd); msg=msg(1:end-1); if(status), error(msg); end if(show), disp(msg); end end
github
P-Chao/acfdetect-master
medfilt1m.m
.m
acfdetect-master/toolbox/filters/medfilt1m.m
2,998
utf_8
a3733d27c60efefd57ada9d83ccbaa3d
function y = medfilt1m( x, r, z ) % One-dimensional adaptive median filtering with missing values. % % Applies a width s=2*r+1 one-dimensional median filter to vector x, which % may contain missing values (elements equal to z). If x contains no % missing values, y(j) is set to the median of x(j-r:j+r). If x contains % missing values, y(j) is set to the median of x(j-R:j+R), where R is the % smallest radius such that sum(valid(x(j-R:j+R)))>=s, i.e. the number of % valid values in the window is at least s (a value x is valid x~=z). Note % that the radius R is adaptive and can vary as a function of j. % % This function uses a modified version of medfilt1.m from Matlab's 'Signal % Processing Toolbox'. Note that if x contains no missing values, % medfilt1m(x) and medfilt1(x) are identical execpt at boundary regions. % % USAGE % y = medfilt1m( x, r, [z] ) % % INPUTS % x - [nx1] length n vector with possible missing entries % r - filter radius % z - [NaN] element that represents missing entries % % OUTPUTS % y - [nx1] filtered vector x % % EXAMPLE % x=repmat((1:4)',1,5)'; x=x(:)'; x0=x; % n=length(x); x(rand(n,1)>.8)=NaN; % y = medfilt1m(x,2); [x0; x; y; x0-y] % % See also MODEFILT1, MEDFILT1 % % Piotr's Computer Vision Matlab Toolbox Version 2.35 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] % apply medfilt1 (standard median filter) to valid locations in x if(nargin<3 || isempty(z)), z=NaN; end; x=x(:)'; n=length(x); if(isnan(z)), valid=~isnan(x); else valid=x~=z; end; v=sum(valid); if(v==0), y=repmat(z,1,n); return; end if(v<2*r+1), y=repmat(median(x(valid)),1,n); return; end y=medfilt1(x(valid),2*r+1); % get radius R needed at each location j to span s=2r+1 valid values % get start (a) and end (b) locations and map back to location in y C=[0 cumsum(valid)]; s=2*r+1; R=find(C==s); R=R(1)-2; pos=zeros(1,n); for j=1:n, R0=R; R=R0-1; a=max(1,j-R); b=min(n,j+R); if(C(b+1)-C(a)<s), R=R0; a=max(1,j-R); b=min(n,j+R); if(C(b+1)-C(a)<s), R=R0+1; a=max(1,j-R); b=min(n,j+R); end end pos(j)=(C(b+1)+C(a+1))/2; end y=y(floor(pos)); end function y = medfilt1( x, s ) % standard median filter (copied from medfilt1.m) n=length(x); r=floor(s/2); indr=(0:s-1)'; indc=1:n; ind=indc(ones(1,s),1:n)+indr(:,ones(1,n)); x0=x(ones(r,1))*0; X=[x0'; x'; x0']; X=reshape(X(ind),s,n); y=median(X,1); end % function y = medfilt1( x, s ) % % standard median filter (slow) % % get unique values in x % [vals,disc,inds]=unique(x); m=length(vals); n=length(x); % if(m>256), warning('x takes on large number of diff vals'); end %#ok<WNTAG> % % create quantized representation [H(i,j)==1 iff x(j)==vals(i)] % H=zeros(m,n); H(sub2ind2([m,n],[inds; 1:n]'))=1; % % create histogram [H(i,j) is count of x(j-r:j+r)==vals(i)] % H=localSum(H,[0 s],'same'); % % compute median for each j and map inds back to original vals % [disc,inds]=max(cumsum(H,1)>s/2,[],1); y=vals(inds); % end
github
P-Chao/acfdetect-master
FbMake.m
.m
acfdetect-master/toolbox/filters/FbMake.m
6,692
utf_8
b625c1461a61485af27e490333350b4b
function FB = FbMake( dim, flag, show ) % Various 1D/2D/3D filterbanks (hardcoded). % % USAGE % FB = FbMake( dim, flag, [show] ) % % INPUTS % dim - dimension % flag - controls type of filterbank to create % - if d==1 % 1: gabor filter bank for spatiotemporal stuff % - if d==2 % 1: filter bank from Serge Belongie % 2: 1st/2nd order DooG filters. Similar to Gabor filterbank. % 3: similar to Laptev&Lindberg ICPR04 % 4: decent seperable steerable? filterbank % 5: berkeley filterbank for textons papers % 6: symmetric DOOG filters % - if d==3 % 1: decent seperable steerable filterbank % show - [0] figure to use for optional display % % OUTPUTS % % EXAMPLE % FB = FbMake( 2, 1, 1 ); % % See also FBAPPLY2D % % Piotr's Computer Vision Matlab Toolbox Version 2.0 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] if( nargin<3 || isempty(show) ); show=0; end % create FB switch dim case 1 FB = FbMake1D( flag ); case 2 FB = FbMake2D( flag ); case 3 FB = FbMake3d( flag ); otherwise error( 'dim must be 1 2 or 3'); end % display FbVisualize( FB, show ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function FB = FbMake1D( flag ) switch flag case 1 %%% gabor filter bank for spatiotemporal stuff omegas = 1 ./ [3 4 5 7.5 11]; sigmas = [3 4 5 7.5 11]; FB = FbMakegabor1D( 15, sigmas, omegas ); otherwise error('none created.'); end function FB = FbMakegabor1D( r, sigmas, omegas ) for i=1:length(omegas) [feven,fodd]=filterGabor1d(r,sigmas(i),omegas(i)); if( i==1 ); FB=repmat(feven,[2*length(omegas) 1]); end FB(i*2-1,:)=feven; FB(i*2,:)=fodd; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function FB = FbMake2D( flag ) switch flag case 1 %%% filter bank from Berkeley / Serge Belongie r=15; FB = FbMakegabor( r, 6, 3, 3, sqrt(2) ); FB2 = FbMakeDOG( r, .6, 2.8, 4); FB = cat(3, FB, FB2); %FB = FB(:,:,1:2:36); %include only even symmetric filters %FB = FB(:,:,2:2:36); %include only odd symmetric filters case 2 %%% 1st/2nd order DooG filters. Similar to Gabor filterbank. FB = FbMakeDooG( 15, 6, 3, 5, .5) ; case 3 %%% similar to Laptev&Lindberg ICPR04 % Wierd filterbank of Gaussian derivatives at various scales % Higher order filters probably not useful. r = 9; dims=[2*r+1 2*r+1]; sigs = [.5 1 1.5 3]; % sigs = [1,1.5,2]; derivs = []; %derivs = [ derivs; 0 0 ]; % 0th order %derivs = [ derivs; 1 0; 0 1 ]; % first order %derivs = [ derivs; 2 0; 0 2; 1 1 ]; % 2nd order %derivs = [ derivs; 3 0; 0 3; 1 2; 2 1 ]; % 3rd order %derivs = [ derivs; 4 0; 0 4; 1 3; 3 1; 2 2 ]; % 4th order derivs = [ derivs; 0 1; 0 2; 0 3; 0 4; 0 5]; % 0n order derivs = [ derivs; 1 0; 2 0; 3 0; 4 0; 5 0]; % n0 order cnt=1; nderivs = size(derivs,1); for s=1:length(sigs) for i=1:nderivs dG = filterDoog( dims, [sigs(s) sigs(s)], derivs(i,:), 0 ); if(s==1 && i==1); FB=repmat(dG,[1 1 length(sigs)*nderivs]); end FB(:,:,cnt) = dG; cnt=cnt+1; %dG = filterDoog( dims, [sigs(s)*3 sigs(s)], derivs(i,:), 0 ); %FB(:,:,cnt) = dG; cnt=cnt+1; %dG = filterDoog( dims, [sigs(s) sigs(s)*3], derivs(i,:), 0 ); %FB(:,:,cnt) = dG; cnt=cnt+1; end end case 4 % decent seperable steerable? filterbank r = 9; dims=[2*r+1 2*r+1]; sigs = [.5 1.5 3]; derivs = [1 0; 0 1; 2 0; 0 2]; cnt=1; nderivs = size(derivs,1); for s=1:length(sigs) for i=1:nderivs dG = filterDoog( dims, [sigs(s) sigs(s)], derivs(i,:), 0 ); if(s==1 && i==1); FB=repmat(dG,[1 1 length(sigs)*nderivs]); end FB(:,:,cnt) = dG; cnt=cnt+1; end end FB2 = FbMakeDOG( r, .6, 2.8, 4); FB = cat(3, FB, FB2); case 5 %%% berkeley filterbank for textons papers FB = FbMakegabor( 7, 6, 1, 2, 2 ); case 6 %%% symmetric DOOG filters FB = FbMakeDooGSym( 4, 2, [.5 1] ); otherwise error('none created.'); end function FB = FbMakegabor( r, nOrient, nScales, lambda, sigma ) % multi-scale even/odd gabor filters. Adapted from code by Serge Belongie. cnt=1; for m=1:nScales for n=1:nOrient [F1,F2]=filterGabor2d(r,sigma^m,lambda,180*(n-1)/nOrient); if(m==1 && n==1); FB=repmat(F1,[1 1 nScales*nOrient*2]); end FB(:,:,cnt)=F1; cnt=cnt+1; FB(:,:,cnt)=F2; cnt=cnt+1; end end function FB = FbMakeDooGSym( r, nOrient, sigs ) % Adds symmetric DooG filters. These are similar to gabor filters. cnt=1; dims=[2*r+1 2*r+1]; for s=1:length(sigs) Fodd = -filterDoog( dims, [sigs(s) sigs(s)], [1 0], 0 ); Feven = filterDoog( dims, [sigs(s) sigs(s)], [2 0], 0 ); if(s==1); FB=repmat(Fodd,[1 1 length(sigs)*nOrient*2]); end for n=1:nOrient theta = 180*(n-1)/nOrient; FB(:,:,cnt) = imrotate( Feven, theta, 'bil', 'crop' ); cnt=cnt+1; FB(:,:,cnt) = imrotate( Fodd, theta, 'bil', 'crop' ); cnt=cnt+1; end end function FB = FbMakeDooG( r, nOrient, nScales, lambda, sigma ) % 1st/2nd order DooG filters. Similar to Gabor filterbank. % Defaults: nOrient=6, nScales=3, lambda=5, sigma=.5, cnt=1; dims=[2*r+1 2*r+1]; for m=1:nScales sigma = sigma * m^.7; Fodd = -filterDoog( dims, [sigma lambda*sigma^.6], [1,0], 0 ); Feven = filterDoog( dims, [sigma lambda*sigma^.6], [2,0], 0 ); if(m==1); FB=repmat(Fodd,[1 1 nScales*nOrient*2]); end for n=1:nOrient theta = 180*(n-1)/nOrient; FB(:,:,cnt) = imrotate( Feven, theta, 'bil', 'crop' ); cnt=cnt+1; FB(:,:,cnt) = imrotate( Fodd, theta, 'bil', 'crop' ); cnt=cnt+1; end end function FB = FbMakeDOG( r, sigmaStr, sigmaEnd, n ) % adds a serires of difference of Gaussian filters. sigs = sigmaStr:(sigmaEnd-sigmaStr)/(n-1):sigmaEnd; for s=1:length(sigs) FB(:,:,s) = filterDog2d(r,sigs(s),2); %#ok<AGROW> if( s==1 ); FB=repmat(FB,[1 1 length(sigs)]); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function FB = FbMake3d( flag ) switch flag case 1 % decent seperable steerable filterbank r = 25; dims=[2*r+1 2*r+1 2*r+1]; sigs = [.5 1.5 3]; derivs = [0 0 1; 0 1 0; 1 0 0; 0 0 2; 0 2 0; 2 0 0]; cnt=1; nderivs = size(derivs,1); for s=1:length(sigs) for i=1:nderivs dG = filterDoog( dims, repmat(sigs(s),[1 3]), derivs(i,:), 0 ); if(s==1 && i==1); FB=repmat(dG,[1 1 1 nderivs*length(sigs)]); end FB(:,:,:,cnt) = dG; cnt=cnt+1; end end otherwise error('none created.'); end
github
VGligorijevic/Patient-specific-DF-master
compute_clusters_ssnmtf.m
.m
Patient-specific-DF-master/code/compute_clusters_ssnmtf.m
1,509
utf_8
1c0d5ec6ded411b4117d1fdd63cb10b1
% Function for assigning entities to clusters % ------------------------------------------------------------------------------------------------------------- % Vladimir Gligorijevic % Imperial College London % [email protected] % Last updated: 5/07/2015 % -------------------------------------------------------------------------------------------------------------- % [Input]: % G: <Cell list>, Cell list containing cluster indicator matrices % label_list: <Cell string>, arrays of labels for each data source % file_list: <Cell string>, list of filenames for exporting figures and % clusters % -------------------------------------------------------------------------------------------------------------- function compute_clusters_ssnmtf(G, label_list, file_list) fprintf('################################\n'); fprintf('Computing cluster assignment....\n'); for i=1:length(G) % Cluster indicator matrix [n,k] = size(G{i}); if k > n G{i} = G{i}'; end; [y,index] = max(G{i},[],2); %find largest factor in column % Computing connectivity matrix C{i} = connectivity(G{i}); % Exporting cluster indices into file fWrite = fopen([file_list{i} '_clust.txt'],'w'); for ii=1:length(index) fprintf(fWrite,'%s %d\n',label_list{i}{ii},index(ii)); end; fclose(fWrite); % Writing connectivity matrix into file dlmwrite([file_list{i} '.mtrx'],C{i},'delimiter',','); fprintf('Dataset [%d] finished.\n',i); end;
github
VGligorijevic/Patient-specific-DF-master
run_simNMTF.m
.m
Patient-specific-DF-master/code/run_simNMTF.m
783
utf_8
285dc66390576a205f7e8f85292d2b41
% Test ranks function run_simNMTF(k, R, A, label_list, max_iter, initialization) ext = [num2str(k(1)) '_' num2str(k(2)) '_' num2str(k(3))]; [S, G] = factorization_ssnmtf(R,A,k,max_iter,initialization); file_list = {['./results/patients_final_' ext],... ['./results/genes_final_' ext],... ['./results/drugs_final_' ext]}; % Exporting clusters compute_clusters_ssnmtf(G, label_list, file_list); % Writing connectivity matrix into file dlmwrite(['./results/gclust-gclust_' ext '.mtrx'], full(S{2,2}), 'delimiter', ','); % Exporting predictions export_significant_associations(G, S, label_list, [2,2], ['./results/gene-gene_pred_' ext '.txt'], 'mix') export_significant_associations(G, S, label_list, [2,3], ['./results/gene-drug_pred_' ext '.txt'], 'mix')
github
VGligorijevic/Patient-specific-DF-master
export_significant_associations.m
.m
Patient-specific-DF-master/code/export_significant_associations.m
1,242
utf_8
67d20b3b1b17660dacf8b81935c247ef
% Reconstruct relation matrices -> only significant values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function export_significant_associations(G, S, label_list, pair_ind, sim_file, exp_type) tol = 1e-5; % scores below tol are considered zero fprintf('############################################\n'); fprintf('---Creating reconstructed relation matrix...\n'); gene_labels = label_list{2}; Rapprox = G{pair_ind(1)}*S{pair_ind(1),pair_ind(2)}*G{pair_ind(2)}'; Rapprox = Rapprox.*(Rapprox > tol); Rapprox = centric_rule(Rapprox,exp_type); if ( pair_ind(1) == pair_ind(2) ) Rapprox = triu(Rapprox); end; fprintf('---Finished\n\n'); %%%%%%% New export way (combination of row- and column-centric rules) [indx_i,indx_j] = find(Rapprox); indx_val = find(Rapprox); fprintf('--Exporting associations....\n'); fid = fopen(sim_file,'w'); fprintf(fid, 'Gene1 | Gene2 | Score\n'); for i=1:length(indx_val) fprintf(fid,'%s %s %f\n',label_list{pair_ind(1)}{indx_i(i)},label_list{pair_ind(2)}{indx_j(i)},full(Rapprox(indx_val(i)))); if (mod(i,500)==0) fprintf('Finished %d out of %d relations.\n',i,length(indx_val)); end; end; fprintf('--Writing significant associatons finished!');
github
HADESAngelia/Balance-Constraint-KMeans-master
munkres.m
.m
Balance-Constraint-KMeans-master/munkres.m
6,971
utf_8
d287696892e8ef857858223a49ad48fd
function [assignment,cost] = munkres(costMat) % MUNKRES Munkres (Hungarian) Algorithm for Linear Assignment Problem. % % [ASSIGN,COST] = munkres(COSTMAT) returns the optimal column indices, % ASSIGN assigned to each row and the minimum COST based on the assignment % problem represented by the COSTMAT, where the (i,j)th element represents the cost to assign the jth % job to the ith worker. % % Partial assignment: This code can identify a partial assignment is a full % assignment is not feasible. For a partial assignment, there are some % zero elements in the returning assignment vector, which indicate % un-assigned tasks. The cost returned only contains the cost of partially % assigned tasks. % This is vectorized implementation of the algorithm. It is the fastest % among all Matlab implementations of the algorithm. % Examples % Example 1: a 5 x 5 example %{ [assignment,cost] = munkres(magic(5)); disp(assignment); % 3 2 1 5 4 disp(cost); %15 %} % Example 2: 400 x 400 random data %{ n=400; A=rand(n); tic [a,b]=munkres(A); toc % about 2 seconds %} % Example 3: rectangular assignment with inf costs %{ A=rand(10,7); A(A>0.7)=Inf; [a,b]=munkres(A); %} % Example 4: an example of partial assignment %{ A = [1 3 Inf; Inf Inf 5; Inf Inf 0.5]; [a,b]=munkres(A) %} % a = [1 0 3] % b = 1.5 % Reference: % "Munkres' Assignment Algorithm, Modified for Rectangular Matrices", % http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html % version 2.3 by Yi Cao at Cranfield University on 11th September 2011 assignment = zeros(1,size(costMat,1)); cost = 0; validMat = costMat == costMat & costMat < Inf; bigM = 10^(ceil(log10(sum(costMat(validMat))))+1); costMat(~validMat) = bigM; % costMat(costMat~=costMat)=Inf; % validMat = costMat<Inf; validCol = any(validMat,1); validRow = any(validMat,2); nRows = sum(validRow); nCols = sum(validCol); n = max(nRows,nCols); if ~n return end maxv=10*max(costMat(validMat)); dMat = zeros(n) + maxv; dMat(1:nRows,1:nCols) = costMat(validRow,validCol); %************************************************* % Munkres' Assignment Algorithm starts here %************************************************* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % STEP 1: Subtract the row minimum from each row. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% minR = min(dMat,[],2); minC = min(bsxfun(@minus, dMat, minR)); %************************************************************************** % STEP 2: Find a zero of dMat. If there are no starred zeros in its % column or row start the zero. Repeat for each zero %************************************************************************** zP = dMat == bsxfun(@plus, minC, minR); starZ = zeros(n,1); while any(zP(:)) [r,c]=find(zP,1); starZ(r)=c; zP(r,:)=false; zP(:,c)=false; end while 1 %************************************************************************** % STEP 3: Cover each column with a starred zero. If all the columns are % covered then the matching is maximum %************************************************************************** if all(starZ>0) break end coverColumn = false(1,n); coverColumn(starZ(starZ>0))=true; coverRow = false(n,1); primeZ = zeros(n,1); [rIdx, cIdx] = find(dMat(~coverRow,~coverColumn)==bsxfun(@plus,minR(~coverRow),minC(~coverColumn))); while 1 %************************************************************************** % STEP 4: Find a noncovered zero and prime it. If there is no starred % zero in the row containing this primed zero, Go to Step 5. % Otherwise, cover this row and uncover the column containing % the starred zero. Continue in this manner until there are no % uncovered zeros left. Save the smallest uncovered value and % Go to Step 6. %************************************************************************** cR = find(~coverRow); cC = find(~coverColumn); rIdx = cR(rIdx); cIdx = cC(cIdx); Step = 6; while ~isempty(cIdx) uZr = rIdx(1); uZc = cIdx(1); primeZ(uZr) = uZc; stz = starZ(uZr); if ~stz Step = 5; break; end coverRow(uZr) = true; coverColumn(stz) = false; z = rIdx==uZr; rIdx(z) = []; cIdx(z) = []; cR = find(~coverRow); z = dMat(~coverRow,stz) == minR(~coverRow) + minC(stz); rIdx = [rIdx(:);cR(z)]; cIdx = [cIdx(:);stz(ones(sum(z),1))]; end if Step == 6 % ************************************************************************* % STEP 6: Add the minimum uncovered value to every element of each covered % row, and subtract it from every element of each uncovered column. % Return to Step 4 without altering any stars, primes, or covered lines. %************************************************************************** [minval,rIdx,cIdx]=outerplus(dMat(~coverRow,~coverColumn),minR(~coverRow),minC(~coverColumn)); minC(~coverColumn) = minC(~coverColumn) + minval; minR(coverRow) = minR(coverRow) - minval; else break end end %************************************************************************** % STEP 5: % Construct a series of alternating primed and starred zeros as % follows: % Let Z0 represent the uncovered primed zero found in Step 4. % Let Z1 denote the starred zero in the column of Z0 (if any). % Let Z2 denote the primed zero in the row of Z1 (there will always % be one). Continue until the series terminates at a primed zero % that has no starred zero in its column. Unstar each starred % zero of the series, star each primed zero of the series, erase % all primes and uncover every line in the matrix. Return to Step 3. %************************************************************************** rowZ1 = find(starZ==uZc); starZ(uZr)=uZc; while rowZ1>0 starZ(rowZ1)=0; uZc = primeZ(rowZ1); uZr = rowZ1; rowZ1 = find(starZ==uZc); starZ(uZr)=uZc; end end % Cost of assignment rowIdx = find(validRow); colIdx = find(validCol); starZ = starZ(1:nRows); vIdx = starZ <= nCols; assignment(rowIdx(vIdx)) = colIdx(starZ(vIdx)); pass = assignment(assignment>0); pass(~diag(validMat(assignment>0,pass))) = 0; assignment(assignment>0) = pass; cost = trace(costMat(assignment>0,assignment(assignment>0))); function [minval,rIdx,cIdx]=outerplus(M,x,y) ny=size(M,2); minval=inf; for c=1:ny M(:,c)=M(:,c)-(x+y(c)); minval = min(minval,min(M(:,c))); end [rIdx,cIdx]=find(M==minval);
github
HADESAngelia/Balance-Constraint-KMeans-master
hungarian.m
.m
Balance-Constraint-KMeans-master/evaluation/hungarian.m
11,320
utf_8
f198a6fac77b9686b122d31e51cecc74
function [C,T]=hungarian(A) %HUNGARIAN Solve the Assignment problem using the Hungarian method. % %[C,T]=hungarian(A) %A - a square cost matrix. %C - the optimal assignment. %T - the cost of the optimal assignment. %s.t. T = trace(A(C,:)) is minimized over all possible assignments. % Adapted from the FORTRAN IV code in Carpaneto and Toth, "Algorithm 548: % Solution of the assignment problem [H]", ACM Transactions on % Mathematical Software, 6(1):104-111, 1980. % v1.0 96-06-14. Niclas Borlin, [email protected]. % Department of Computing Science, Ume? University, % Sweden. % All standard disclaimers apply. % A substantial effort was put into this code. If you use it for a % publication or otherwise, please include an acknowledgement or at least % notify me by email. /Niclas [m,n]=size(A); if (m~=n) error('HUNGARIAN: Cost matrix must be square!'); end % Save original cost matrix. orig=A; % Reduce matrix. A=hminired(A); % Do an initial assignment. [A,C,U]=hminiass(A); % Repeat while we have unassigned rows. while (U(n+1)) % Start with no path, no unchecked zeros, and no unexplored rows. LR=zeros(1,n); LC=zeros(1,n); CH=zeros(1,n); RH=[zeros(1,n) -1]; % No labelled columns. SLC=[]; % Start path in first unassigned row. r=U(n+1); % Mark row with end-of-path label. LR(r)=-1; % Insert row first in labelled row set. SLR=r; % Repeat until we manage to find an assignable zero. while (1) % If there are free zeros in row r if (A(r,n+1)~=0) % ...get column of first free zero. l=-A(r,n+1); % If there are more free zeros in row r and row r in not % yet marked as unexplored.. if (A(r,l)~=0 & RH(r)==0) % Insert row r first in unexplored list. RH(r)=RH(n+1); RH(n+1)=r; % Mark in which column the next unexplored zero in this row % is. CH(r)=-A(r,l); end else % If all rows are explored.. if (RH(n+1)<=0) % Reduce matrix. [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR); end % Re-start with first unexplored row. r=RH(n+1); % Get column of next free zero in row r. l=CH(r); % Advance "column of next free zero". CH(r)=-A(r,l); % If this zero is last in the list.. if (A(r,l)==0) % ...remove row r from unexplored list. RH(n+1)=RH(r); RH(r)=0; end end % While the column l is labelled, i.e. in path. while (LC(l)~=0) % If row r is explored.. if (RH(r)==0) % If all rows are explored.. if (RH(n+1)<=0) % Reduce cost matrix. [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR); end % Re-start with first unexplored row. r=RH(n+1); end % Get column of next free zero in row r. l=CH(r); % Advance "column of next free zero". CH(r)=-A(r,l); % If this zero is last in list.. if(A(r,l)==0) % ...remove row r from unexplored list. RH(n+1)=RH(r); RH(r)=0; end end % If the column found is unassigned.. if (C(l)==0) % Flip all zeros along the path in LR,LC. [A,C,U]=hmflip(A,C,LC,LR,U,l,r); % ...and exit to continue with next unassigned row. break; else % ...else add zero to path. % Label column l with row r. LC(l)=r; % Add l to the set of labelled columns. SLC=[SLC l]; % Continue with the row assigned to column l. r=C(l); % Label row r with column l. LR(r)=l; % Add r to the set of labelled rows. SLR=[SLR r]; end end end % Calculate the total cost. T=sum(orig(logical(sparse(C,1:size(orig,2),1)))); function A=hminired(A) %HMINIRED Initial reduction of cost matrix for the Hungarian method. % %B=assredin(A) %A - the unreduced cost matris. %B - the reduced cost matrix with linked zeros in each row. % v1.0 96-06-13. Niclas Borlin, [email protected]. [m,n]=size(A); % Subtract column-minimum values from each column. colMin=min(A); A=A-colMin(ones(n,1),:); % Subtract row-minimum values from each row. rowMin=min(A')'; A=A-rowMin(:,ones(1,n)); % Get positions of all zeros. [i,j]=find(A==0); % Extend A to give room for row zero list header column. A(1,n+1)=0; for k=1:n % Get all column in this row. cols=j(k==i)'; % Insert pointers in matrix. A(k,[n+1 cols])=[-cols 0]; end function [A,C,U]=hminiass(A) %HMINIASS Initial assignment of the Hungarian method. % %[B,C,U]=hminiass(A) %A - the reduced cost matrix. %B - the reduced cost matrix, with assigned zeros removed from lists. %C - a vector. C(J)=I means row I is assigned to column J, % i.e. there is an assigned zero in position I,J. %U - a vector with a linked list of unassigned rows. % v1.0 96-06-14. Niclas Borlin, [email protected]. [n,np1]=size(A); % Initalize return vectors. C=zeros(1,n); U=zeros(1,n+1); % Initialize last/next zero "pointers". LZ=zeros(1,n); NZ=zeros(1,n); for i=1:n % Set j to first unassigned zero in row i. lj=n+1; j=-A(i,lj); % Repeat until we have no more zeros (j==0) or we find a zero % in an unassigned column (c(j)==0). while (C(j)~=0) % Advance lj and j in zero list. lj=j; j=-A(i,lj); % Stop if we hit end of list. if (j==0) break; end end if (j~=0) % We found a zero in an unassigned column. % Assign row i to column j. C(j)=i; % Remove A(i,j) from unassigned zero list. A(i,lj)=A(i,j); % Update next/last unassigned zero pointers. NZ(i)=-A(i,j); LZ(i)=lj; % Indicate A(i,j) is an assigned zero. A(i,j)=0; else % We found no zero in an unassigned column. % Check all zeros in this row. lj=n+1; j=-A(i,lj); % Check all zeros in this row for a suitable zero in another row. while (j~=0) % Check the in the row assigned to this column. r=C(j); % Pick up last/next pointers. lm=LZ(r); m=NZ(r); % Check all unchecked zeros in free list of this row. while (m~=0) % Stop if we find an unassigned column. if (C(m)==0) break; end % Advance one step in list. lm=m; m=-A(r,lm); end if (m==0) % We failed on row r. Continue with next zero on row i. lj=j; j=-A(i,lj); else % We found a zero in an unassigned column. % Replace zero at (r,m) in unassigned list with zero at (r,j) A(r,lm)=-j; A(r,j)=A(r,m); % Update last/next pointers in row r. NZ(r)=-A(r,m); LZ(r)=j; % Mark A(r,m) as an assigned zero in the matrix . . . A(r,m)=0; % ...and in the assignment vector. C(m)=r; % Remove A(i,j) from unassigned list. A(i,lj)=A(i,j); % Update last/next pointers in row r. NZ(i)=-A(i,j); LZ(i)=lj; % Mark A(r,m) as an assigned zero in the matrix . . . A(i,j)=0; % ...and in the assignment vector. C(j)=i; % Stop search. break; end end end end % Create vector with list of unassigned rows. % Mark all rows have assignment. r=zeros(1,n); rows=C(C~=0); r(rows)=rows; empty=find(r==0); % Create vector with linked list of unassigned rows. U=zeros(1,n+1); U([n+1 empty])=[empty 0]; function [A,C,U]=hmflip(A,C,LC,LR,U,l,r) %HMFLIP Flip assignment state of all zeros along a path. % %[A,C,U]=hmflip(A,C,LC,LR,U,l,r) %Input: %A - the cost matrix. %C - the assignment vector. %LC - the column label vector. %LR - the row label vector. %U - the %r,l - position of last zero in path. %Output: %A - updated cost matrix. %C - updated assignment vector. %U - updated unassigned row list vector. % v1.0 96-06-14. Niclas Borlin, [email protected]. n=size(A,1); while (1) % Move assignment in column l to row r. C(l)=r; % Find zero to be removed from zero list.. % Find zero before this. m=find(A(r,:)==-l); % Link past this zero. A(r,m)=A(r,l); A(r,l)=0; % If this was the first zero of the path.. if (LR(r)<0) ...remove row from unassigned row list and return. U(n+1)=U(r); U(r)=0; return; else % Move back in this row along the path and get column of next zero. l=LR(r); % Insert zero at (r,l) first in zero list. A(r,l)=A(r,n+1); A(r,n+1)=-l; % Continue back along the column to get row of next zero in path. r=LC(l); end end function [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR) %HMREDUCE Reduce parts of cost matrix in the Hungerian method. % %[A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR) %Input: %A - Cost matrix. %CH - vector of column of 'next zeros' in each row. %RH - vector with list of unexplored rows. %LC - column labels. %RC - row labels. %SLC - set of column labels. %SLR - set of row labels. % %Output: %A - Reduced cost matrix. %CH - Updated vector of 'next zeros' in each row. %RH - Updated vector of unexplored rows. % v1.0 96-06-14. Niclas Borlin, [email protected]. n=size(A,1); % Find which rows are covered, i.e. unlabelled. coveredRows=LR==0; % Find which columns are covered, i.e. labelled. coveredCols=LC~=0; r=find(~coveredRows); c=find(~coveredCols); % Get minimum of uncovered elements. m=min(min(A(r,c))); % Subtract minimum from all uncovered elements. A(r,c)=A(r,c)-m; % Check all uncovered columns.. for j=c % ...and uncovered rows in path order.. for i=SLR % If this is a (new) zero.. if (A(i,j)==0) % If the row is not in unexplored list.. if (RH(i)==0) % ...insert it first in unexplored list. RH(i)=RH(n+1); RH(n+1)=i; % Mark this zero as "next free" in this row. CH(i)=j; end % Find last unassigned zero on row I. row=A(i,:); colsInList=-row(row<0); if (length(colsInList)==0) % No zeros in the list. l=n+1; else l=colsInList(row(colsInList)==0); end % Append this zero to end of list. A(i,l)=-j; end end end % Add minimum to all doubly covered elements. r=find(coveredRows); c=find(coveredCols); % Take care of the zeros we will remove. [i,j]=find(A(r,c)<=0); i=r(i); j=c(j); for k=1:length(i) % Find zero before this in this row. lj=find(A(i(k),:)==-j(k)); % Link past it. A(i(k),lj)=A(i(k),j(k)); % Mark it as assigned. A(i(k),j(k))=0; end A(r,c)=A(r,c)+m;
github
BottjerLab/Acoustic_Similarity-master
loaderGUI.m
.m
Acoustic_Similarity-master/code/GUI/loaderGUI.m
6,021
utf_8
49a1b35d38cb2b26bbd2e1a53028094b
function varargout = loaderGUI(varargin) % LOADERGUI MATLAB code for loaderGUI.fig % LOADERGUI, by itself, creates a new LOADERGUI or raises the existing % singleton*. % % H = LOADERGUI returns the handle to a new LOADERGUI or the handle to % the existing singleton*. % % LOADERGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in LOADERGUI.M with the given input arguments. % % LOADERGUI('Property','Value',...) creates a new LOADERGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before loaderGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to loaderGUI_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help loaderGUI % Last Modified by GUIDE v2.5 12-Apr-2013 16:10:48 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @loaderGUI_OpeningFcn, ... 'gui_OutputFcn', @loaderGUI_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before loaderGUI is made visible. function loaderGUI_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to loaderGUI (see VARARGIN) % Choose default command line output for loaderGUI handles.output = hObject; % Update handles structure guidata(hObject, handles); %keyboard % Update settings structure to default setappdata(handles.settingsPanel, 'params', defaultParams); % UIWAIT makes loaderGUI wait for user response (see UIRESUME) % uiwait(handles.mainFigure); % --- Outputs from this function are returned to the command line. function varargout = loaderGUI_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure %keyboard varargout{1} = handles.output; % --- Executes on button press in LoadSpike. function LoadSpike_Callback(hObject, eventdata, handles) % hObject handle to LoadSpike (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [matFile, matpath] = uigetfile('*.mat','Please choose the song Spike2 file','data'); birdID = regexp(matpath, '\w{1,2}\d{1,3}','match'); if ~isempty(birdID) birdID = birdID{:}; else birdID = '?'; end sessionID = regexp(matFile, ... sprintf('(?<=%s_)\\d{1,2}_\\d{1,2}_\\d{1,3}',birdID),'match'); if ~isempty(sessionID) sessionID = sessionID{:}; else sessionID = '?'; end set(handles.birdField,'String', sprintf('Bird: %s', birdID)); set(handles.sessionField,'String', sprintf('Session: %s',sessionID)); % load file songStruct = load([matpath matFile]); % trick to get the main struct into a standard name, if there's only one % variable in the file fld=fieldnames(songStruct); songStruct=songStruct.(fld{1}); fs = 1/songStruct.interval; songStruct.fs = fs; songStruct.title = matFile; % set variables in the guiData setappdata(handles.mainFigure, 'songStruct', songStruct); % --- Executes on button press in FindSounds. function FindSounds_Callback(hObject, eventdata, handles) % hObject handle to FindSounds (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) hfig = figure; sounds = stepSpectrogram(getappdata(handles.mainFigure, 'songStruct'), ... getappdata(handles.settingsPanel, 'params'),... 'Nsplits',400,'plot',true); close(hfig); divs = guidata(handles.divisionsPanel); setappdata(handles.divisionsPanel, 'sounds', divs); % update workspace updateWorkspace(hObject, eventdata, handles); % --- Executes on button press in keyboardAccess. function keyboardAccess_Callback(hObject, eventdata, handles) % hObject handle to keyboardAccess (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) keyboard % update workspace updateWorkspace(hObject, eventdata, handles); % --- Executes on button press in loadVariables. function loadVariables_Callback(hObject, eventdata, handles) % hObject handle to loadVariables (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [tmpFile tmpPath] = uigetfile('*.mat','Select matfile to load'); tmpStruct = load([tmpPath filesep tmpFile]); varNames = fieldnames(tmpStruct); for ii = 1:numel(varNames); setappdata(handles.divisionsPanel, varNames{ii}, tmpStruct.(varNames{ii})); end % update workspace updateWorkspace(hObject, eventdata, handles); function updateWorkspace(hObject, eventdata, handles) values = getappdata(handles.divisionsPanel); fNames = fieldnames(values); fNames(strcmp('lastValidTag',fNames)) = []; set(handles.divisionsPanel,'String', fNames);
github
BottjerLab/Acoustic_Similarity-master
standardDistance.m
.m
Acoustic_Similarity-master/code/clustering/standardDistance.m
3,471
utf_8
fabe0ae08aad5c902142064cb4c9e7f6
function [totalDists, indivDists] = standardDistance(spectrum1, spectrum2, params, varargin) %STANDARDDISTANCE Running, sample by sample scan of two spectral feature sets % % COVAR = standardDistance(SPECTRUM1, SPECTRUM2) returns the similarity of two % sounds, sample by sample, according to the standardized difference found between % their features. The correlations are taken along ever calculated % feature of the sample (power, entropy, average pitch, etc.) and is a % VECTOR of values, one for each possible offset of the spectrum relative % to the other one. % % See also TIMEWARPEDDISTANCE %% argument handling if nargin < 3 params = defaultParams; end params = processArgs(params,varargin{:}); %% order by length % convert lengths len1 = length(spectrum1.times); len2 = length(spectrum2.times); if(len1 > len2) temp = spectrum1; spectrum1 = spectrum2; spectrum2 = temp; len1 = length(spectrum1.times); len2 = length(spectrum2.times); end %% name all features that should be compared featCatalog = params.featureCatalog; featureSel = false(1,numel(featCatalog)); for ii = 1:numel(featCatalog) featureSel(ii) = any(strcmp(fieldnames(spectrum1), featCatalog(ii).name)) && ... any(strcmp(fieldnames(spectrum2), featCatalog(ii).name)); end featCatalog = featCatalog(featureSel); nF = numel(featCatalog); %% convert structure to array to speed indexing % specArray1 = zeros(len1,nF); % specArray2 = zeros(len2,nF); % for ii = 1:nF % if featCatalog(ii).doLog % natVel1 = log(spectrum1.(featCatalog(ii).name)); % natVel2 = log(spectrum2.(featCatalog(ii).name)); % else % natVel1 = spectrum1.(featCatalog(ii).name); % natVel2 = spectrum2.(featCatalog(ii).name); % end % specArray1(:,ii) = (natVel1 - featCatalog(ii).median)/featCatalog(ii).MAD; % specArray2(:,ii) = (natVel2 - featCatalog(ii).median)/featCatalog(ii).MAD; % end % clear natVel1 natVel2 %% score differences % determine the time intervals that we want to run similarity nSkipMs = 0.4; % in ms nSkipSamples = ceil(nSkipMs/1000 / (spectrum1.times(2) - spectrum1.times(1))); nComparisons = numel(1:nSkipSamples:len2 - len1 + 1); indivDists = zeros(nComparisons, nF); for jj = 1:nF % loop over the features % get standardized vectors fv1 = getStdVector(spectrum1, featCatalog(jj)); fullfv2 = getStdVector(spectrum2,featCatalog(jj)); % loop over every nSkipSamples of the longer sound % (restrict to 1 for completeness) ctr = 1; for ii = 1:nSkipSamples:len2 - len1 + 1 indivDists(ctr,jj) = norm(fv1-fullfv2(ii:(ii + len1 - 1)))/len1; ctr = ctr+1; end end %% duration distance - append this to the distances durDev = 40; % this is an empirical number based on Lb189_4_25_5 durationDist = abs(spectrum1.times(end) - spectrum2.times(end)) / (durDev / 1000); indivDists(:,nF+1) = durationDist; %% combine scores along features - where weighting can be directly controlled weightVec = [params.featureCatalog.weights]; weightVec(end+1) = 0.5; %length is discouraged a little weightVec = weightVec/sum(weightVec); totalDists = weightVec * indivDists'; end function fv = getStdVector(spectrum, featEntry, sampStart, sampEnd) if nargin == 2 sampStart = 1; sampEnd = numel(spectrum.(featEntry.name)); end fv = spectrum.(featEntry.name)(sampStart:sampEnd); if featEntry.doLog fv = log(fv); end fv = (fv - featEntry.median) ./ featEntry.MAD; end
github
BottjerLab/Acoustic_Similarity-master
DRcluster.m
.m
Acoustic_Similarity-master/code/clustering/DRcluster.m
6,704
utf_8
4ad08210957bd0416d5be7155c27ad78
function [clustIdxs, empMatrices, distMatrices, empDistrs] = DRcluster(DRsylls, featureTable, spectra, params, varargin) timeFlag = ['T-' datestr(clock, 'mm_dd_HH_MM')]; featuresCached = (nargin >= 2); specsCached = (nargin >= 3); if nargin < 4 params = defaultParams; end params = processArgs(params, varargin{:}); % remove any syllables that are too short isTooShort = (params.fine.windowSize / 1000 > [DRsylls.stop] - [DRsylls.start]); DRsylls(isTooShort) = []; fprintf('Removing %d syllables that are too short...\n', sum(isTooShort)); % sort [DRsylls, sortedIdx] = sortBy(DRsylls, 'file'); N = numel(DRsylls);% = min(ceil(numel(allDRsylls)/2),1000); NC2 = nchoosek(N,2); if any(sortedIdx ~= 1:N) fprintf('NB: Check sorting...\n'); end nEmpD = min(NC2,2e4); distMatrices = struct(... 'warpedLocal' , zeros(1,NC2),... 'global' , zeros(1,NC2)); empMatrices = struct(... 'warpedLocal' , zeros(1,NC2),... 'global' , zeros(1,NC2)); empDistrs = struct(..., 'warpedLocal', zeros(2,nEmpD),... 'global' , zeros(2,nEmpD)); fieldsToKeep = {'AM','FM','pitchGoodness','wienerEntropy','fundamentalFreq','times'}; % store the feature-based spectra for all of them params.fine.features = {'wienerEntropy','deriv','harmonicPitch','fundamentalFreq'}; % get sampling rate [filePath, fileStem] = fileparts(DRsylls(1).file); metaFile = [filePath filesep 'meta-' fileStem]; metaStruct = []; load(metaFile); params.fine.fs = 1/metaStruct.interval; % calculate spectra if ~specsCached spectra = initEmptyStructArray(fieldsToKeep, N); if ~featuresCached featureTable = cell(1,N); end progressbar(sprintf('Calculating spectra & features for regions (# = %d)',N)); for ii = 1:N %get noisemask if ii==1 || ~strcmp(DRsylls(ii-1).file, DRsylls(ii).file) [filePath fileStem] = fileparts(DRsylls(ii).file); nMFile = [filePath filesep 'noiseMask-' fileStem '.mat']; if exist(nMFile, 'file') fprintf('Loading noise mask from %s...\n',nMFile); noiseMask = []; load(nMFile); end end cl = getClipAndProcess([],DRsylls(ii), params, 'noroll','doFilterNoise',true,'noiseFilter', noiseMask); tmpSpec = getMTSpectrumStats(cl, params.fine); for jj = 1:numel(fieldsToKeep) spectra(ii).(fieldsToKeep{jj}) = tmpSpec.(fieldsToKeep{jj}); end if ~featuresCached featureTable{ii} = extractFeatures(tmpSpec); end progressbar(ii/N); end end if ~featuresCached featureTable = [featureTable{:}]; save(['tmpFeatures-' timeFlag],'DRsylls','spectra','featureTable'); end % convert features from struct array to 2D array fn = fieldnames(featureTable); featureTable = cellfun(@(x) [featureTable.(x)]', fn', 'UniformOutput',false); featureTable = [featureTable{:}]; %% calculate local distances, fixed-time version, no %{ innerIdx = 0; progressbar('Unwarped Distance Calcs'); for ii = 1:N-1 for jj = ii+1:N innerIdx = innerIdx + 1; distMatrices.unwarpedLocal(innerIdx) = min(standardDistance(spectra(ii), spectra(jj), params)); progressbar(innerIdx/nchoosek(N,2)); end end save(['tmpDists-' timeFlag],'DRsylls','distMatrices'); %} %% calculate local distances, TIME WARPED version tic innerIdx = 0; progressbar('Saves','Time Warped Distance Calcs'); for ii = 1:N-1 iLen = DRsylls(ii).stop - DRsylls(ii).start; for jj = ii+1:N jLen = DRsylls(jj).stop - DRsylls(jj).start; innerIdx = innerIdx + 1; distMatrices.warpedLocal(innerIdx) = ... timeWarpedDistance(spectra(ii), spectra(jj), params) / mean([iLen, jLen]); progressbar([],innerIdx/nchoosek(N,2)); if rem(innerIdx, floor(sqrt(nchoosek(N,2)))) == 0 %save(['tmpDists-' timeFlag],'DRsylls','distMatrices'); progressbar(floor(innerIdx/floor(sqrt(nchoosek(N,2)))) / ... floor(nchoosek(N,2)/floor(sqrt(nchoosek(N,2))))) end end end save(['tmpDists-' timeFlag],'DRsylls','distMatrices'); progressbar(1); tt=toc; fprintf('Time warping took %0.2f s...\n', tt); %save([dataPath 'localSimTW-' birdID '.mat'],'clustSylls','twDistM'); %% step 5: measure global distances within pairs of syllables %seldFeaturesTable = allFeaturesTable; %clustSylls = allDRsylls(trainIdxs); %featureTable = allFeaturesTable(trainIdxs,:); % start with unnormalized table of features % step 1: normalize to z-scores fprintf('Calculating global dissimilarity scores...\n'); zNormedFeatures = zscore(featureTable); distMatrices.global = pdist(zNormedFeatures); save(['tmpDists-' timeFlag],'DRsylls','distMatrices'); %% get non-parametric (probability-rank) ordering of similarity scores fprintf('Calculating empirical scores...\n'); scoreTypes = fieldnames(distMatrices); for ii = 1:numel(scoreTypes) fld = scoreTypes{ii}; arr = distMatrices.(fld); [sArr,rord] = sort(arr); empMatrices.(fld)(rord) = [1:numel(arr)] / numel(arr); xx = linspace(0,1,nEmpD); if nEmpD == numel(arr) yy = sArr; else yy = interp1(linspace(0,1,numel(arr)), sArr, xx); end % prepare for interp1 by removing redundant entries redun = [diff(yy)==0 false]; if any(redun) xx = xx(~redun); % might be better to take a mean of the p-values instead of the max (as this implies) yy = yy(~redun); end empDistrs.(fld) = zeros(2,numel(xx)); empDistrs.(fld)(1,:) = xx; empDistrs.(fld)(2,:) = yy; save(['tmpEmp-' timeFlag],'DRsylls','empMatrices', 'empDistrs'); end %% construct co-similarity as fusion of local and global p-values fprintf('Calculating co-dissimilarity (correlation of dissimilarities, which is a similarity score)...\n'); fusedPVals = sqrt(empMatrices.warpedLocal .* empMatrices.global); distMatrices.cosim = pdist(squareform(fusedPVals), 'correlation'); % do the clustering - the easiest part nClusters = 4:25; pairLinks = linkage(distMatrices.cosim,'complete'); clustIdxs = cluster(pairLinks,'maxclust',nClusters); % undo sorting step clustIdxs(sortedIdx,:) = clustIdxs; scoreTypes = fieldnames(distMatrices); for ii = 1:numel(scoreTypes) distMatrices.(scoreTypes{ii}) = squareform(unsort2D(squareform(distMatrices.(scoreTypes{ii})), sortedIdx)); if isfield(empMatrices, scoreTypes{ii}) empMatrices.(scoreTypes{ii}) = squareform(unsort2D(squareform( empMatrices.(scoreTypes{ii})), sortedIdx)); end end end function mat = unsort2D(mat, sI) [coordsi, coordsj] = meshgrid(sI,sI); mat(sub2ind(size(mat),coordsi, coordsj)) = mat; end
github
BottjerLab/Acoustic_Similarity-master
searchClusterOrder.m
.m
Acoustic_Similarity-master/code/clustering/searchClusterOrder.m
2,564
utf_8
e8ce8804d0b9575a2138d12120d95103
function [bestSeq, bestSeqFreq] = searchClusterOrder(events, links, params, varargin) if nargin < 3; params = defaultParams; end; params = processArgs(params,varargin{:}); % separate syllables into separate clusters, % either clusters or number of possible clusters distCutoff = 0.7; clusterIdxs = cluster(links,'Cutoff', distCutoff,'criterion','Distance'); uClusters = unique(clusterIdxs); nClusters = numel(uClusters) + 1; transMatrix = zeros(nClusters); % let silence be the last transition possibility % build up first-order transition matrix nEvents = numel(events); silenceIdx = nEvents; silenceDuration = 2.0; % seconds, any currSyllType = clusterIdxs(1); seqList = currSyllType; for ii = 1:nEvents-1 % list transition matrix between pairs of events nextSyllType = clusterIdxs(ii+1); if events(ii+1).start - events(ii).stop > silenceDuration transMatrix(currSyllType, silenceIdx) = ... transMatrix(currSyllType, silenceIdx) + 1; transMatrix(silenceIdx, nextSyllType) = ... transMatrix(silenceIdx, nextSyllType) + 1; seqList = [seqList silenceIdx nextSyllType]; else transMatrix(currSyllType, nextSyllType) = ... transMatrix(currSyllType, nextSyllType) + 1; seqList = [seqList silenceIdx nextSyllType]; end currSyllType = nextSyllType; end % convert to probabilities nEventsPerCluster = sum(transMatrix,1); probMatrix = transMatrix; for ii = 1:nClusters probMatrix(:,ii) = probMatrix(:,ii) ./ nEventsPerCluster; end if params.plot imagesc(probMatrix); end %% find the most common subsequences of a certain length - % lookoup Algorithms on Strings, Trees and Sequences - Dan Gusfield minimumLength = 3; maximumArray = 1e5; if nClusters^minimumLength > maximumArray, error('TooManyPossibilities','We need to use a suffix tree...'); end; nSeq = numel(seqList); hashSubFreq = zeros(nClusters ^ minimumLength, 1); % brute force: hash a subsequence to a key for ii = 1:nSeq - minimumLength hashedIdx = enBase(seqList(ii:ii+minLength - 1)-1, nClusters) + 1; hashSubFreq(hashedIdx) = hashSubFreq(hashedIdx) + 1; end [sortFreq, idxFreq] = sort(hashSubFreq); seqFreq = 10000; ii = 1 bestSeq = zeros(10,minimumLength); while seqFreq > 100 && ii <= 10 bestSeq(ii,:) = unBase(idxFreq(ii) - 1) + 1 bestSeqFreq(ii) = hashSubFreq(idxFreq(ii)); end function ret = enBase(array, base) % ret = nBase(array(1:end-1)) * base + nBase(end); end function arr = unBase(num, base) % arr = [unBase(floor(num/base)) mod(num,base)]; end
github
BottjerLab/Acoustic_Similarity-master
DRclusterSaveOnDisk.m
.m
Acoustic_Similarity-master/code/clustering/DRclusterSaveOnDisk.m
7,006
utf_8
a2131d36c3d9304df43541f319f31267
function [clustIdxs, empMatricesFil, distMatricesFil, empDistrs] = ... DRclusterSaveOnDisk(DRsylls, featureTable, spectra, params, varargin) % we use this version of DRcluster if we have a large number of syllables % (>5000) for memory constraints % the two matrices are returned as files timeFlag = ['T-' datestr(clock, 'mm_dd_HH_MM')]; tmpDir = ['tmp-' timeFlag filesep]; featuresCached = (nargin >= 2); specsCached = (nargin >= 3); if nargin < 4 params = defaultParams; end params = processArgs(params, varargin{:}); % remove any syllables that are too short isTooShort = (params.fine.windowSize / 1000 > [DRsylls.stop] - [DRsylls.start]); DRsylls(isTooShort) = []; fprintf('Removing %d syllables that are too short...\n', sum(isTooShort)); % sort [DRsylls, sortedIdx] = sortBy(DRsylls, 'file'); N = numel(DRsylls);% = min(ceil(numel(allDRsylls)/2),1000); NC2 = nchoosek(N,2); if any(sortedIdx ~= 1:N) fprintf('NB: Check sorting...\n'); end nEmpD = min(NC2,2e4); distMatricesFil = matfile([tmpDir 'distMatrices.mat'],'Writable', true); distMatricesFil.warpedLocal = zeros(1,NC2); distMatricesFil.global = zeros(1,NC2); empMatricesFil = matfile([tmpDir 'empMatrices.mat'],'Writable', true); empMatricesFil.warpedLocal = zeros(1,NC2); empMatricesFil.global = zeros(1,NC2); empDistrs = struct(..., 'warpedLocal', zeros(2,nEmpD),... 'global' , zeros(2,nEmpD)); fieldsToKeep = {'AM','FM','pitchGoodness','wienerEntropy','fundamentalFreq','times'}; % store the feature-based spectra for all of them params.fine.features = {'wienerEntropy','deriv','harmonicPitch','fundamentalFreq'}; % get sampling rate [filePath, fileStem] = fileparts(DRsylls(1).file); metaFile = [filePath filesep 'meta-' fileStem]; metaStruct = []; load(metaFile); params.fine.fs = 1/metaStruct.interval; % calculate spectra if ~specsCached spectra = initEmptyStructArray(fieldsToKeep, N); if ~featuresCached featureTable = cell(1,N); end progressbar(sprintf('Calculating spectra & features for regions (# = %d)',N)); for ii = 1:N %get noisemask if ii==1 || ~strcmp(DRsylls(ii-1).file, DRsylls(ii).file) [filePath fileStem] = fileparts(DRsylls(ii).file); nMFile = [filePath filesep 'noiseMask-' fileStem '.mat']; if exist(nMFile, 'file') fprintf('Loading noise mask from %s...\n',nMFile); noiseMask = []; load(nMFile); end end cl = getClipAndProcess([],DRsylls(ii), params, 'noroll',... 'doFilterNoise',true,'noiseFilter', noiseMask); tmpSpec = getMTSpectrumStats(cl, params.fine); for jj = 1:numel(fieldsToKeep) spectra(ii).(fieldsToKeep{jj}) = tmpSpec.(fieldsToKeep{jj}); end if ~featuresCached featureTable{ii} = extractFeatures(tmpSpec); end progressbar(ii/N); end end if ~featuresCached featureTable = [featureTable{:}]; save(['tmpFeatures-' timeFlag],'DRsylls','spectra','featureTable'); end % convert features from struct array to 2D array fn = fieldnames(featureTable); featureTable = cellfun(@(x) [featureTable.(x)]', fn', 'UniformOutput',false); featureTable = [featureTable{:}]; %% calculate local distances, fixed-time version, no %{ innerIdx = 0; progressbar('Unwarped Distance Calcs'); for ii = 1:N-1 for jj = ii+1:N innerIdx = innerIdx + 1; distMatrices.unwarpedLocal(innerIdx) = min(standardDistance(spectra(ii), spectra(jj), params)); progressbar(innerIdx/nchoosek(N,2)); end end save(['tmpDists-' timeFlag],'DRsylls','distMatrices'); %} %% calculate local distances, TIME WARPED version tic innerIdx = 0; progressbar('Saves','Time Warped Distance Calcs'); for ii = 1:N-1 iLen = DRsylls(ii).stop - DRsylls(ii).start; for jj = ii+1:N jLen = DRsylls(jj).stop - DRsylls(jj).start; innerIdx = innerIdx + 1; % distance is normalized by the length of the syllables distMatricesFil.warpedLocal(innerIdx) = ... timeWarpedDistance(spectra(ii), spectra(jj), params) / mean([iLen, jLen]); progressbar([],innerIdx/nchoosek(N,2)); if rem(innerIdx, floor(sqrt(nchoosek(N,2)))) == 0 progressbar(floor(innerIdx/floor(sqrt(nchoosek(N,2)))) / ... floor(nchoosek(N,2)/floor(sqrt(nchoosek(N,2))))) end end end save(['tmpDists-' timeFlag],'DRsylls','distMatrices'); progressbar(1); tt=toc; fprintf('Time warping took %0.2f s...\n', tt); %save([dataPath 'localSimTW-' birdID '.mat'],'clustSylls','twDistM'); %% step 5: measure global distances within pairs of syllables %seldFeaturesTable = allFeaturesTable; %clustSylls = allDRsylls(trainIdxs); %featureTable = allFeaturesTable(trainIdxs,:); % start with unnormalized table of features % step 1: normalize to z-scores fprintf('Calculating global dissimilarity scores...\n'); zNormedFeatures = zscore(featureTable); distMatricesFil.global = pdist(zNormedFeatures); save(['tmpDists-' timeFlag],'DRsylls','distMatrices'); %% get non-parametric (probability-rank) ordering of similarity scores fprintf('Calculating empirical scores...\n'); scoreTypes = fieldnames(distMatricesFil); for ii = 1:numel(scoreTypes) fld = scoreTypes{ii}; arr = distMatricesFil.(fld); [sArr,rord] = sort(arr); empMatricesFil.(fld)(rord) = [1:numel(arr)] / numel(arr); xx = linspace(0,1,nEmpD); if nEmpD == numel(arr) yy = sArr; else yy = interp1(linspace(0,1,numel(arr)), sArr, xx); end % prepare for interp1 by removing redundant entries redun = [diff(yy)==0 false]; if any(redun) xx = xx(~redun); % might be better to take a mean of the p-values instead of the max (as this implies) yy = yy(~redun); end empDistrs.(fld) = zeros(2,numel(xx)); empDistrs.(fld)(1,:) = xx; empDistrs.(fld)(2,:) = yy; end %% construct co-similarity as fusion of local and global p-values fprintf('Calculating co-dissimilarity (correlation of dissimilarities, which is a similarity score)...\n'); fusedPVals = sqrt(empMatricesFil.warpedLocal .* empMatricesFil.global); distMatricesFil.cosim = pdist(squareform(fusedPVals), 'correlation'); % do the clustering - the easiest part nClusters = 4:25; pairLinks = linkage(distMatricesFil.cosim,'complete'); clustIdxs = cluster(pairLinks,'maxclust',nClusters); % undo sorting step clustIdxs(sortedIdx,:) = clustIdxs; scoreTypes = fieldnames(distMatricesFil); for ii = 1:numel(scoreTypes) distMatricesFil.(scoreTypes{ii}) = squareform(unsort2D(squareform(distMatricesFil.(scoreTypes{ii})), sortedIdx)); if isfield(empMatricesFil, scoreTypes{ii}) empMatricesFil.(scoreTypes{ii}) = squareform(unsort2D(squareform( empMatricesFil.(scoreTypes{ii})), sortedIdx)); end end end function mat = unsort2D(mat, sI) [coordsi, coordsj] = meshgrid(sI,sI); mat(sub2ind(size(mat),coordsi, coordsj)) = mat; end
github
BottjerLab/Acoustic_Similarity-master
similarityRegions.m
.m
Acoustic_Similarity-master/code/clustering/similarityRegions.m
846
utf_8
a2fa57b6fa30d6e2a1c0dba7bd8209f3
function sim = similarityRegions(songStruct, keyreg, otherRegs, noiseGate, params, varargin) %% parameter handling if nargin < 5; params = defaultParams; end params = processArgs(params, varargin{:}); fs = 1/songStruct.interval; %% preprocessing % filter out noise first [keyclip,keyspec] = cleanClip(keyreg); for ii = 1:numel(otherRegs) [iclip,ispec] = cleanClip(otherRegs(ii)); sim{ii} = similarityScan(keyspec, ispec); end function [clip,spec] = cleanClip(region) region = addPrePost(region,params); if nargin >= 3 clip = noiseGate(songStruct, region, noiseProfile); else clip = getClip(region, songStruct); end if ~params.quiet, playSound(clip,fs); end % high pass the result params.fs=fs; clip = highPassSample(clip,params); %% spectral analysis params.fine.fs = fs; spec = getSpectrumStats(clip, params.fine); end end
github
BottjerLab/Acoustic_Similarity-master
drawClustersUpdated.m
.m
Acoustic_Similarity-master/code/clustering/drawClustersUpdated.m
8,383
utf_8
2a5608d992b05217c84073336bf22e21
function drawClustersUpdated(birdID, age, params, varargin) if nargin < 3 || isempty(params) params = defaultParams; end params = processArgs(params, varargin{:}); dataDir = [pwd filesep 'data' filesep birdID filesep]; % clusterDir = ['data' filesep 'cluster-' birdID filesep]; % get sessions for a certain age rep = reportOnData(birdID); birdSessions = {rep.sessionID}; sessAges = getAgeOfSession(birdSessions); rep = rep(age == sessAges); % get syllables for a certain age by concatenating across different groups ageSylls = []; for ii = 1:numel(rep) mani = rep(ii).manifest; [~,fil] = findInManifest(mani, 'sAudio'); theseSylls = loadFromManifest(mani, 'approvedSyllables'); % minimum length used in DRcluster would be smaller than the % spectrogram window % remove syllables that are too short minLen = params.fine.windowSize / 1000; isTooShort = minLen > [theseSylls.stop] - [theseSylls.start]; theseSylls(isTooShort) = []; [theseSylls.file] = deal(fil); % get the labels labels = loadFromManifest(mani, 'acceptedLabels'); if isempty(labels) fprintf('No acceptedLabels for session %s, not retrieving...\n', rep(ii).sessionID); continue; end % apply labels num2cell(labels); [theseSylls.type] = ans{:}; ageSylls = [ageSylls theseSylls]; end % plot all syllables within each cluster as a mosaic labels = [ageSylls.type]; nClusts = nanmax([ageSylls.type]); clustLabels = unique(labels(~isnan(labels))); if any(isnan(labels)), clustLabels(end+1) = NaN; end mkdir('figures/',sprintf('%s-age%d', birdID, age)); redoneLabels = labels; for ii = 1:nClusts clustSylls = ageSylls(labels == ii); if isempty(clustSylls), continue; end; clustSylls = addPrePost(clustSylls, [], 'preroll', 5, 'postroll',5); maxMosaicLength = 6.5; [hfs, newLabels] = plotInPages(clustSylls, maxMosaicLength, ii, ... clustLabels, birdID, age, params); close(hfs) % updating syllable labels if params.manuallyUpdateClusters redoneLabels(labels == ii) = newLabels; redoneFile = sprintf('%sredoneLabels-%s-age%d.mat', dataDir, birdID, age, params); fprintf('Intermediate saving to %s...\n', redoneFile); save(redoneFile, 'redoneLabels'); end end unIDedSylls = ageSylls(isnan([ageSylls.type])); unIDedSylls = addPrePost(unIDedSylls, [], 'preroll', 5, 'postroll',5); maxMosaicLength = 6.5; [hfs, newLabels] = plotInPages(unIDedSylls, maxMosaicLength, NaN, clustLabels, birdID, age, params); % updating syllable labels if params.manuallyUpdateClusters redoneLabels(isnan(labels)) = newLabels; redoneFile = sprintf('%sredoneLabels-%s-age%d.mat', dataDir, birdID, age); fprintf('Final saving to %s...\n', redoneFile); save(redoneFile, 'redoneLabels'); end close(hfs) end function [hfs, newLabels] = plotInPages(sylls, pageLength, syllNum, clustLabels, birdID, age, params) % pageLength in seconds, max amount to plot, accounting for wasted margins on the mosaic % break down clustSylls into groups no longer than maxTime lens = [sylls.stop] - [sylls.start]; grpStarts = 1; grpEnds = numel(sylls); while sum(lens(grpStarts(end):end)) > pageLength newGrpStart = find(cumsum(lens) > pageLength, 1); grpStarts(end+1) = newGrpStart; grpEnds = [grpEnds(1:end-1) (newGrpStart-1) grpEnds(end)]; lens(1:newGrpStart-1) = 0; % zero out the lengths that are already accounted for end isClosed = false(1,numel(grpStarts)); hfs = zeros(1,numel(grpStarts)); newLabels = ones(1,numel(sylls)) * syllNum; for jj = 1:numel(hfs) figure; % get the figure handle and image handles [hfs(jj) hIms] = mosaicDRSpec(sylls(grpStarts(jj):grpEnds(jj)), [],... 'dgram.minContrast', 1e-11, 'doFilterNoise', false,... 'noroll', 'maxMosaicLength', Inf); set(hfs(jj), 'Name', sprintf('%s, syllable #%d, instances #%d-%d', ... birdID, syllNum, grpStarts(jj), grpEnds(jj))); % interactive portion % if params.manuallyUpdateClusters % get the axes objects hRowAxes = get(hIms,'Parent'); % de-cell hRowAxes = [hRowAxes{:}]; for kk = 1:numel(hRowAxes) hThisRowAxes = hRowAxes(kk); hThisIm = hIms(kk); sepH = findall(hThisRowAxes, 'Type','line','Color',[1 1 1]); nSeps = numel(sepH); % boundaries of the regions in figure x-coordinates xSeps = zeros(1,nSeps + 2); % ends of the separators xl = xlim(hThisRowAxes); xSeps(1:2) = xl; for ll = 1:nSeps xl = get(sepH(ll), 'XData'); xSeps(ll+2) = xl(1); % first x-coordinate of the line is x position end xSeps = sort(xSeps); % make red text labels axes(hThisRowAxes); for ll = 1:nSeps+1 %each segment hlabel = createTextLabel(mean(xSeps(ll:ll+1)), ... num2str(syllNum)); set(hlabel, 'UserData', ll); end % save bounds and current labels in figure data structure set(hThisIm,'UserData', ... struct('bounds', xSeps, ... 'currLabels', syllNum * ones(1,nSeps + 1))); hcmenu = uicontextmenu; for ll = 1:numel(clustLabels) uimenu(hcmenu,'Label',num2str(clustLabels(ll)),... 'Callback', @(hEntry, data) changeLabels(... clustLabels(ll), hThisIm)); % both input variables are dummy variables end uimenu(hcmenu,'Label','Done',... 'Callback', @(hEntry, data) ... stopLabeling(gcf)); %the data input dummy variables set(hThisIm,'uicontextmenu', hcmenu); end % set the close request function and a cleanup in case of % ctrl-c - this needs to be fixed so that c cleans up on ctrl-c % instead of on request to delete hfs(jj) set(hfs(jj),'CloseRequestFcn',@(hfig,event) set(hfig, 'Tag','Done')); c = onCleanup(@() resetCloseFcn(hfs(jj))); waitfor(hfs(jj),'Tag','Done') % change the labels by grabbing userdata from the images ptr = grpStarts(jj); for kk = 1:numel(hIms) foo = getfield(get(hIms(kk),'UserData'),'currLabels'); newLabels(ptr:ptr+numel(foo)-1) = foo; ptr = ptr + numel(foo); end % todo: delete the labels assert(ptr == grpEnds(jj)+1); nChanged = sum(newLabels~=syllNum); if isnan(syllNum) nChanged = sum(isnan(newLabels)); end fprintf('\tcluster #%d: %d labels changed...\n', syllNum, nChanged); end % end interactive portion % if params.saveplot fName = sprintf('figures/%s-age%d/%s-age%d-clust%02d-i%04d-%04d.jpg',... birdID,age, birdID,age, syllNum,grpStarts(jj), grpEnds(jj)); saveCurrFigure(fName); end isClosed(jj) = true; close(hfs(jj)); end hfs(isClosed) = []; end function resetCloseFcn(hfig) fprintf('Calling reset fxn\n'); if isvalid(hfig), set(hfig,'CloseRequestFcn','closereq'); end end function changeLabels(seldLabel, hIm) % seldLabel is the name of the label % hIm is the image handle that contains the track of labels in userData % get the current point of the click in normalized coordinates hCurrAxes = get(hIm,'Parent'); hCurrFig = get(hCurrAxes, 'Parent'); currPt = get(hCurrFig, 'CurrentPoint'); figDims = get(hCurrFig, 'Position'); currPt = currPt ./ figDims([3 4]); % bounds of array userData = get(hIm,'UserData'); xb = userData.bounds; % get the segment which was selected xpos = currPt(1); segNum = find(xb(1:end-1) < xpos & xb(2:end) >= xpos, 1); % reassign the label from the segment which was clicked userData.currLabels(segNum) = seldLabel; set(hIm,'UserData', userData); % rewrite the label hCurrLabel = findall(hCurrAxes, 'Type', 'text', 'UserData', segNum); set(hCurrLabel, 'String', num2str(seldLabel)); end function stopLabeling(gCurrFig) % set the done tag set(gCurrFig,'Tag','Done'); end
github
BottjerLab/Acoustic_Similarity-master
similarityScan.m
.m
Acoustic_Similarity-master/code/clustering/similarityScan.m
2,368
utf_8
a3651e090a6d323689f5c986b206dc7f
function [covar, indivDists] = similarityScan(spectrum1, spectrum2, params, varargin) %SIMILARITYSCAN Running, sample by sample scan of two spectral feature sets % COVAR = similarityScan(SPECTRUM1, SPECTRUM2) returns the similarity of two % sounds, sample by sample, according to the correlation found between % their features. The correlations are taken along ever calculated % feature of the sample (power, entropy, average pitch, etc.) and is a % VECTOR of values, one for each possible offset of the spectrum relative % to the other one. % %% argument handling if nargin < 3 params = defaultParams; end params = processArgs(params,varargin{:}); %% order by length % convert lengths len1 = length(spectrum1.times); len2 = length(spectrum2.times); if(len1 > len2) [covar, indivDists] = similarityScan(spectrum2, spectrum1, params); return; end %% find all features that can be correlated features = whichFeatures(spectrum1); nF = numel(features); %% look at x) / var(y)) over the different fields, for each matching window % TODO: make a better way to weight features %weightVec = [24.7557 629.1870 28.8207 24.3587 133.1410 679.5239 27.8380 63.5714 41.6093 55.1736]; % TODO: define similarity more robustly, with real euclidean distances and % more weight on frequency measures weightVec = ones(1,nF) / nF; % uniform weight, can be changed %weightVec = weightVec/sum(weightVec); % determine the time intervals that we want to run similarity nSkipMs = 0.2; % in ms nSkipSamples = floor(nSkipMs/1000 * params.fs); nComparisons = numel(1:nSkipSamples:len2 - len1 + 1); covar = zeros(1,nComparisons); ctr = 1; indivDists = zeros(nComparisons, nF); for ii = 1:nSkipSamples:len2 - len1 + 1 segStart = ii; segEnd = ii + len1 - 1; for jj = 1:nF % loop over the features fv1 = spectrum1.(features{jj}); fv2 = spectrum2.(features{jj})(segStart:segEnd); indivDists(ctr,jj) = 1 - pdist([fv1;fv2],'cosine'); %corr=cc(2,1); % this will happen when one of the vectors is constant % if isnan(corr), corr = 0; end covar(ctr) = covar(ctr) + indivDists(ctr,jj) * weightVec(jj); end ctr = ctr+1; end function ret = featsToArray(featSummary,features) nF = numel(features); nS = numel(featsToArray.times); ret = zeros(nF,nS); for ii = 1:nF ret(ii,:) = featSummary.(features{ii}); end
github
BottjerLab/Acoustic_Similarity-master
browseAndAccept.m
.m
Acoustic_Similarity-master/code/clustering/browseAndAccept.m
18,753
utf_8
621019bb5bcc42a29f290a11c46a03b1
function [acceptedLabels, augmentedLabels] = browseAndAccept(birdID) % interactive part of clustering post-machine step % several prompts based on the output results from recalcClusters* family %% close all; clusterDir = [pwd filesep 'data' filesep 'cluster-' birdID filesep]; dataDir = [pwd filesep 'data' filesep birdID filesep]; plotParams = processArgs(defaultParams,... 'dgram.minContrast', 1e-11, 'doFilterNoise', false,... 'preroll', 3, 'postroll', 3); % load the subset of syllables fprintf('Loading spectra for bird %s...', birdID); DRsylls = []; featureTable = []; spectra = []; load([dataDir 'allSpecs-' birdID '.mat'], 'DRsylls','featureTable'); fprintf(' done loading.\n'); % choose the cluster file [filName, pathName] = uigetfile([clusterDir '*.mat'],'Select the file to grab clusters from'); fprintf('Loading cluster file...'); %% % parse the age, subselect the syllables to save memory [~,foooo] = strtok(filName,'-'); thisAge = sscanf(foooo(2:end), '%d'); thisAge = thisAge(1); % make me less hacky.......... use a regexp clustSession = strrep(filName(1:end-5), 'altClustDataAge-',''); %% isAge = ([DRsylls.age] == thisAge); DRsylls = DRsylls(isAge); featureTable = featureTable(isAge); %% load cluster file clusterIdxs = []; load([pathName filesep filName], 'clusterIdxs'); fprintf('Now loading distance matrix for additional refinement... '); load([pathName filesep filName], 'distMats'); fprintf('done loading.\n'); %% % pick the kind of clustering if isstruct(clusterIdxs) fn = fieldnames(clusterIdxs); seldClusterType = fn{listdlg('ListString', fn, 'SelectionMode', 'single','Name', 'Which type of clustering?')}; if isempty(seldClusterType), error('Did not select option, buggin'' out.'); end % cIdxs = clusterIdxs.(seldClusterType); else % cIdxs = clusterIdxs; seldClusterType = 'cosim'; end %maxes = max(cIdxs,[],1); %% dists = squareform(distMats.(seldClusterType)); clear distMats; %% pick which level of clustering you want: nDefClusts = 12; maxes = 4:30; %% linktree = linkage(dists, 'complete'); cIdxs = cluster(linktree,'maxclust',maxes); %% nClusts = str2double(inputdlg(... sprintf('How many clusters are you looking for? (%d-%d)',min(maxes),max(maxes)),... 'Number of clusters', 1, {num2str(nDefClusts)})); thisSetPtr = find(maxes==nClusts); thisSetIdxs = cIdxs(:,thisSetPtr); counts = hist(thisSetIdxs,1:nClusts); %% loop through the different clusters in order of decreasing size [~, sortPerm] = sort(counts, 'descend'); acceptedLabels = -ones(size(thisSetIdxs)); isFused = false(1,nClusts); %% grpCtr = 1; for ii = 1:nClusts if isFused(sortPerm(ii)), continue; end; %% inspect cluster clf mosaicDRSpec(DRsylls(thisSetIdxs == sortPerm(ii)), plotParams, 'maxMosaicLength', 4.5); set(gcf,'Name',sprintf('Cluster #%d (%d/%d)',sortPerm(ii),ii,nClusts)); retry = true; while retry retry = false; switch nm_questdlg('How to treat this cluster?', ... sprintf('Cluster %d, # = %d', sortPerm(ii), sum(thisSetIdxs == sortPerm(ii))),... 'Accept', 'Reject', 'Edit', 'Accept') case 'Accept' acceptedLabels(thisSetIdxs == sortPerm(ii)) = grpCtr; grpCtr = grpCtr + 1; case 'Reject' acceptedLabels(thisSetIdxs == sortPerm(ii)) = -1; % sentinel for rejection continue; case 'Edit' % todo: report metrics of conformity/similarity? [newLabelGroups, retry] = editSub(thisSetIdxs, sortPerm(ii)); % implement labeling groups for jj = 1:numel(newLabelGroups) acceptedLabels(newLabelGroups{jj}) = grpCtr; grpCtr = grpCtr + 1; end end end end acceptedLabels(acceptedLabels == -1) = NaN; % save to an acceptedLabels file clusterIdxs = struct('accepted', acceptedLabels); saveFileName = [pwd filesep 'data' filesep birdID filesep 'acceptedLabels-' birdID '-age' num2str(thisAge) '.mat']; fprintf('Saving cluster identifies to %s...', saveFileName) save(saveFileName, 'clusterIdxs'); %% step 1.5: encourage review and merging of labels % goal: make more representative syllables regroupedLabels = mergeClustersByHand(DRsylls, dists, acceptedLabels); %% second pass: try to match labels to establish groups % find matches by looking at the distance % loop through the unlabeled syllables % look for matches within the range of acceptable distances augmentedLabels = semiLabelSyllables(DRsylls, dists, regroupedLabels); %% save to an acceptedLabels file clusterIdxs = struct('accepted', acceptedLabels, 'regrouped', regroupedLabels, 'augmented', augmentedLabels); saveFileName = [pwd filesep 'data' filesep birdID filesep 'acceptedLabels-' birdID '-age' num2str(thisAge) '.mat']; fprintf('Saving cluster identifies to %s...', saveFileName); save(saveFileName, 'clusterIdxs'); fprintf('done. hooray. \n'); %% function [newLabelGrps, tryAgain] = editSub(labels, oldLabel) nThisType = sum(labels == oldLabel); ttl = sprintf('Cluster %d, # = %d', oldLabel, nThisType); openFigures = []; tryAgain = false; newLabelGrps = {}; switch nm_questdlg('How to edit this cluster?', ttl, 'Merge', 'Split', 'Sort by Ear', 'Merge') case 'Merge' % follow the tree backwards mergedCluster = findMerge(thisSetPtr, oldLabel, cIdxs); % now presentIden and clustIden should fuse fprintf('Fusing candidate...'); figureName = sprintf('%sexpClusters-%s-%s-c%d.jpg', pathName, clustSession, ... seldClusterType, mergedCluster); if exist(figureName,'file') == 2; fOp = figure; openFigures = [openFigures fOp]; imshow(figureName); set(gcf,'Name',[figureName ' - candidate cluster for merging']); else end switch nm_questdlg('Fuse?',ttl,'Yes','No, reject all', 'Retry', 'Yes') case 'Yes' isFused(oldLabel) = true; isFused(mergedCluster) = true; newLabelGrps = [find(labels == oldLabel | labels == mergedCluster) newLabelGrps]; case 'Accept original' newLabelGrps = [find(labels == oldLabel) newLabelGrps]; case 'No, reject' % do nothing case 'Retry' tryAgain = true; end case 'Split' % how do we split? splitFeatOptions = ['tree'; fieldnames(featureTable)]; % follow the tree forwards repeatSplit = true; while repeatSplit % loop around try-catchtry for clustering robustness repeatSplit = false; [splitOpts, hitOk] = listdlg('ListString', splitFeatOptions, ... 'Name', 'Which features to split?'); if ~hitOk tryAgain = true; closeAll(openFigures); return; end if any(splitOpts == 1) [typeA, typeB] = findSplit(thisSetPtr, oldLabel, cIdxs); else % try a two-component mixture of gaussian clusters nFeats = numel(splitOpts); stats = zeros(nThisType, nFeats); omitFeature = false(1, nFeats); varStat = zeros(1,nFeats); for kk = 1:nFeats stats(:,kk) = [featureTable(labels == oldLabel).(splitFeatOptions{splitOpts(kk)})]; end varStat = var(stats); omitFeature = (varStat < eps(max(varStat))*nThisType); if all(omitFeature), warning('All features are constant...'); end; if any(omitFeature) omitStr = ''; omitList = splitOpts(omitFeature); % create the join string for kk = 1:numel(omitList), omitStr = strcat(omitStr , splitFeatOptions(omitList(kk))); if kk < nFeats, omitStr = strcat(omitStr,', '); end end omitStr = omitStr{1}; fprintf('Removing features %s...\n', omitStr); stats(:,omitFeature) = []; splitOpts(omitFeature) = []; nFeats = numel(splitOpts); end try fitObj = gmdistribution.fit(stats,2,'Regularize',0.0001); newIdxs = cluster(fitObj,stats); % do some plotting fTab = figure('Name','Clustergram'); openFigures = [openFigures fTab]; if size(stats,2) == 1 nBins = 40; bins = zeros(1,nBins); bins(2:end-1) = linspace(min(stats),max(stats),nBins-2); bins(end) = 2 * bins(end-1) - bins(end-2); bins(1) = 2 * bins(2) - bins(3); bar(bins,histc(stats, bins),1); xlim(bins([1 end])); hold on; plot(bins, pdf(fitObj,bins'),'r-', 'LineWidth', 2); hold off; xlabel(splitFeatOptions{splitOpts}, 'Interpreter','none'); ylabel('Count'); else % pick the two most diagnostic features dprime = zeros(1,nFeats); for kk = 1:size(stats,2) dMu = diff(fitObj.mu(:,kk)); sumSigma = sqrt(sum(fitObj.Sigma(kk,kk,:))); dprime(kk) = dMu/sumSigma; end [~,bestDims] = sort(dprime, 'descend'); bestDims = bestDims(1:2); plot(stats(:,bestDims(1)), stats(:,bestDims(2)),'k.'); xlabel(splitFeatOptions(splitOpts(bestDims(1))), 'Interpreter','none'); ylabel(splitFeatOptions(splitOpts(bestDims(2))), 'Interpreter','none'); end % split done subset = find(labels == oldLabel); typeA = subset(newIdxs == 1); typeB = subset(newIdxs == 2); catch err repeatSplit = questdlg(['Error in clustering: [', err.message, ']; try again?'],... 'Clustering Error', ... 'Yes','No','Yes'); repeatSplit = strcmp('Yes', repeatSplit); end end end % give option to view/sing/approve blind switch nm_questdlg(sprintf('How to review the split (A = %d,B = %d)?', ... numel(typeA), numel(typeB)), ... ttl,'View','Listen','Continue w/o review', 'View') case 'View' totalLenA = sum([DRsylls(typeA).stop] - [DRsylls(typeA).start]); totalLenB = sum([DRsylls(typeB).stop] - [DRsylls(typeB).start]); defaultVal = min(totalLenA, 4.0); tPrev = nm_inputdlg(... sprintf('Number of seconds to preview (max %.1fs): ', totalLenA),... 'Cluster A', 1, {num2str(defaultVal)}); if isempty(tPrev), tryAgain = true; return; else tPrev = str2double(tPrev); end fprintf('Plotting split cluster A (# = %d)...\n', numel(typeA)); figA = figure; openFigures = [openFigures figA]; mosaicDRSpec(DRsylls(typeA), plotParams, 'maxMosaicLength', tPrev); set(gcf,'Name',sprintf('Cluster A (# = %d)',numel(typeA))); defaultVal = min(totalLenB, tPrev); tPrev = nm_inputdlg(... sprintf('Number of seconds to preview (max %.1fs): ', totalLenB),... 'Cluster B', 1, {num2str(defaultVal)}); if isempty(tPrev), tryAgain = true; return; else tPrev = str2double(tPrev); end fprintf('Plotting split cluster B (# = %d)...\n', numel(typeB)); figB = figure; openFigures = [openFigures figB]; mosaicDRSpec(DRsylls(typeB), plotParams, 'maxMosaicLength', tPrev); set(gcf,'Name',sprintf('Cluster B (# = %d)',numel(typeB))); case 'Listen' % simply play the sounds: it's faster to load but % slower to be complete fprintf('Splitting candidate... branch A audio: \n'); markRegions([],DRsylls(typeA)); fprintf('Splitting candidate... branch B audio: \n'); markRegions([],DRsylls(typeB)); case 'Accept w/o review' end choices = {'Both','Branch A', 'Branch B','None'}; [respStr, isAccept] = nm_listdlg('Name', 'Which branches to accept (none is an option)?', 'ListString',choices, ... 'SelectionMode', 'Single','OKString','Accept',... 'CancelString','Retry'); if ~isAccept, tryAgain = true; closeAll(openFigures); return; end; respStr = choices{respStr}; switch respStr case 'Both' % will flatten these later newLabelGrps = {typeA, typeB}; case 'Branch A' newLabelGrps = {typeA}; case 'Branch B' newLabelGrps = {typeB}; case 'None' newLabelGrps= {}; end case 'Sort by Ear' fprintf('Split into no more than 10..., based on audio: \n'); newIdxs = multiMark([], DRsylls(labels == oldLabel)); if any(isnan(newIdxs)) if strcmp('Start over',questdlg(['Hand labeling is stopped early, accept or start over?'],... 'Labeling stopped', ... 'Accept','Start over','Start over')) tryAgain = true; closeAll(openFigures); return end end [~,~,rIdxs] = unique(newIdxs); newLabelGrps = cell(1,numel(rIdxs)); for kk = 1:numel(rIdxs) newLabelGrps{kk} = find(rIdxs == kk); end end closeAll(openFigures); end end function closeAll(figH) for kk = 1:numel(figH) close(figH(kk)); end end function [otherCluster, mergeDepth] = findMerge(grpPtr, origClust, clusterLabels) isMerged = false; origPtr = grpPtr; clustTrav = origClust; while ~isMerged && grpPtr > 1 ct = crosstab(clusterLabels(:,grpPtr), clusterLabels(:, grpPtr-1)); % the row that contains the current cluster - does it % contain another cluster? dstClusters = find(ct(clustTrav,:)>0); if sum(ct(:,dstClusters) > 0) > 1 otherCluster = sum(find(ct(:,dstClusters))) - clustTrav; isMerged = true; else clustTrav = dstClusters; grpPtr = grpPtr - 1; end end mergeDepth = grpPtr; % follow the new cluster back to the current division? (we % don't have to do this, it might split again) for jj = grpPtr:origPtr-1 ct = crosstab(clusterLabels(:,jj), clusterLabels(:,jj+1)); [~, otherCluster] = max(ct(otherCluster,:)); end end function [clusterInds, splitInds, splitDepth] = findSplit(grpPtr, origClust, clusterLabels) hasSplit = false; clustTrav = origClust; nClusterings = size(clusterLabels, 2); while ~hasSplit && grpPtr < nClusterings ct = crosstab(clusterLabels(:,grpPtr), clusterLabels(:, grpPtr+1)); % the row that contains the current cluster - does it % contain another cluster? dstClusters = find(ct(clustTrav,:) > 0); if numel(dstClusters) == 2 clustTrav = dstClusters(1); otherCluster = dstClusters(2); hasSplit = true; else clustTrav = dstClusters; end grpPtr = grpPtr + 1; end if hasSplit clusterInds = find(clusterLabels(:,grpPtr) == clustTrav); splitInds = find(clusterLabels(:,grpPtr) == otherCluster); splitDepth = grpPtr; else clusterInds = find(clusterLabels(:,grpPtr) == clustTrav); splitInds = []; splitDepth = nClusterings; % excepted end end
github
BottjerLab/Acoustic_Similarity-master
createAlphabet.m
.m
Acoustic_Similarity-master/code/clustering/createAlphabet.m
2,178
utf_8
36c3f166b9e69f24394fe2e97a135f24
function [vocString, clusterIdxs] = createAlphabet(syllables, distMatrix, songStruct, params, varargin) %CREATEALPHABET given distance matrix, cluster into groups % if nargin < 4 || isempty(params) params = defaultParams; end params = processArgs(params,varargin{:}); fs = 1/songStruct.interval; % cluster the syllables by distance - assumes triangular matrix %boutCorrVector = squareform(corrMatrix + corrMatrix' ... % - 2 * diag(diag(corrMatrix)),'tovector'); % dendTree = clusterAll(vocalizations, boutCorrMatrix, songStruct); %dendTree = linkage(1 - boutCorrVector, 'complete'); % TODO: try top-down instead of agglomerative? % for correlation matrices % dendTree = linkage(1 - corrMatrix, params.clusterMethod); % for distance matrices dendTree = linkage(distMatrix, params.clusterMethod); %% create clusters clusterIdxs = cluster(dendTree, 'maxClust', params.nClusters)'; %% reassign numbers to cluster letters - don't do this for now alphaFreq = histc(clusterIdxs,1:params.nClusters); % translate to string vocString = numToAlpha(clusterIdxs); freqs = hist(clusterIdxs, 1:params.nClusters) if params.plot asciied = double(vocString); hist(asciied,min(asciied):1:max(asciied)) xlim([min(asciied)-0.5 max(asciied)+0.5]) set(gca,'XTick',min(asciied):1:max(asciied)) set(gca,'XTickLabels',char(min(asciied):1:max(asciied))'); title('Distribution of labels'); end % sample the alphabet if params.playsample for ii = 1:params.nClusters % pick at most 5 example syllables and more if we have more nSamples = max(floor(sqrt(alphaFreq(ii))),min(5,alphaFreq(ii))); fprintf('Playing syllable %s (# = %d)...\n',numToAlpha(ii), freqs(ii)); sampleIdxs = find(clusterIdxs==ii,nSamples); for jj = 1:nSamples playSound(getClip(syllables(sampleIdxs(jj)), songStruct),fs,true); pause(0.25); end beep pause(0.25); end end end function str = numToAlpha(vec) vec(vec>= 27 & vec <=52) = vec(vec>= 27 & vec <=52) + double('A') - double('a') - 26; str = char(double('a' - 1 + vec)); end function vec = alphaToNum(str) vec = str - 'A' + 1; end
github
BottjerLab/Acoustic_Similarity-master
DRclusterMFCC.m
.m
Acoustic_Similarity-master/code/clustering/DRclusterMFCC.m
6,385
utf_8
e15c7f427391ef218dcc74553dfe1444
function [clustIdxs, empMatrices, distMatrices, empDistrs] = DRclusterMFCC(DRsylls, featureTable, spectra, params, varargin) timeFlag = ['T-' datestr(clock, 'mm_dd_HH_MM')]; featuresCached = (nargin >= 2); specsCached = (nargin >= 3); if nargin < 4 params = defaultParams; end params = processArgs(params, varargin{:}); % remove any syllables that are too short isTooShort = (params.fine.windowSize / 1000 > [DRsylls.stop] - [DRsylls.start]); DRsylls(isTooShort) = []; fprintf('Removing %d syllables that are too short...\n', sum(isTooShort)); % sort [DRsylls, sortedIdx] = sortBy(DRsylls, 'file'); N = numel(DRsylls);% = min(ceil(numel(allDRsylls)/2),1000); NC2 = nchoosek(N,2); if any(sortedIdx ~= 1:N) fprintf('NB: Check sorting...\n'); end nEmpD = min(NC2,2e4); distMatrices = struct(... 'warpedLocal' , zeros(1,NC2),... 'global' , zeros(1,NC2)); empMatrices = struct(... 'warpedLocal' , zeros(1,NC2),... 'global' , zeros(1,NC2)); empDistrs = struct(..., 'warpedLocal', zeros(2,nEmpD),... 'global' , zeros(2,nEmpD)); fieldsToKeep = {'AM','FM','pitchGoodness','wienerEntropy','fundamentalFreq','times'}; % store the feature-based spectra for all of them params.fine.features = {'wienerEntropy','deriv','harmonicPitch','fundamentalFreq'}; % get sampling rate [filePath, fileStem] = fileparts(DRsylls(1).file); metaFile = [filePath filesep 'meta-' fileStem]; metaStruct = []; load(metaFile); params.fine.fs = 1/metaStruct.interval; % calculate spectra if ~specsCached spectra = initEmptyStructArray(fieldsToKeep, N); if ~featuresCached featureTable = cell(1,N); end progressbar(sprintf('Calculating spectra & features for regions (# = %d)',N)); for ii = 1:N %get noisemask if ii==1 || ~strcmp(DRsylls(ii-1).file, DRsylls(ii).file) [filePath fileStem] = fileparts(DRsylls(ii).file); nMFile = [filePath filesep 'noiseMask-' fileStem '.mat']; if exist(nMFile, 'file') fprintf('Loading noise mask from %s...\n',nMFile); noiseMask = []; load(nMFile); end end cl = getClipAndProcess([],DRsylls(ii), params, 'noroll','doFilterNoise',true,'noiseFilter', noiseMask); tmpSpec = getMTSpectrumStats(cl, params.fine); for jj = 1:numel(fieldsToKeep) spectra(ii).(fieldsToKeep{jj}) = tmpSpec.(fieldsToKeep{jj}); end if ~featuresCached featureTable{ii} = extractFeatures(tmpSpec); end progressbar(ii/N); end end if ~featuresCached featureTable = [featureTable{:}]; save(['tmpFeatures-' timeFlag],'DRsylls','spectra','featureTable'); end % convert features from struct array to 2D array fn = fieldnames(featureTable); featureTable = cellfun(@(x) [featureTable.(x)]', fn', 'UniformOutput',false); featureTable = [featureTable{:}]; %% calculate local distances, TIME WARPED version, on MFCC tic innerIdx = 0; progressbar('Saves','Time Warped Distance Calcs'); for ii = 1:N-1 iLen = DRsylls(ii).stop - DRsylls(ii).start; for jj = ii+1:N jLen = DRsylls(jj).stop - DRsylls(jj).start; innerIdx = innerIdx + 1; % distance, normalized by the average length distMatrices.warpedLocal(innerIdx) = ... timeWarpedDistanceMFCC(spectra(ii), spectra(jj), params) / ... ((iLen + jLen) / 2); progressbar([],innerIdx/nchoosek(N,2)); if rem(innerIdx, floor(sqrt(nchoosek(N,2)))) == 0 save(['tmpDists-' timeFlag],'DRsylls','distMatrices'); progressbar(floor(innerIdx/floor(sqrt(nchoosek(N,2)))) / ... floor(nchoosek(N,2)/floor(sqrt(nchoosek(N,2))))) end end end save(['tmpDists-' timeFlag],'DRsylls','distMatrices'); progressbar(1); tt=toc; fprintf('Time warping took %0.2f s...\n', tt); %save([dataPath 'localSimTW-' birdID '.mat'],'clustSylls','twDistM'); %% step 5: measure global distances within pairs of syllables %seldFeaturesTable = allFeaturesTable; %clustSylls = allDRsylls(trainIdxs); %featureTable = allFeaturesTable(trainIdxs,:); % start with unnormalized table of features % step 1: normalize to z-scores fprintf('Calculating global dissimilarity scores...\n'); zNormedFeatures = zscore(featureTable); distMatrices.global = pdist(zNormedFeatures); save(['tmpDists-' timeFlag],'DRsylls','distMatrices'); %% get non-parametric (probability-rank) ordering of similarity scores fprintf('Calculating empirical scores...\n'); scoreTypes = fieldnames(distMatrices); for ii = 1:numel(scoreTypes) fld = scoreTypes{ii}; arr = distMatrices.(fld); [sArr,rord] = sort(arr); empMatrices.(fld)(rord) = [1:numel(arr)] / numel(arr); xx = linspace(0,1,nEmpD); if nEmpD == numel(arr) yy = sArr; else yy = interp1(linspace(0,1,numel(arr)), sArr, xx); end % prepare for interp1 by removing redundant entries redun = [diff(yy)==0 false]; if any(redun) xx = xx(~redun); % might be better to take a mean of the p-values instead of the max (as this implies) yy = yy(~redun); end empDistrs.(fld) = zeros(2,numel(xx)); empDistrs.(fld)(1,:) = xx; empDistrs.(fld)(2,:) = yy; save(['tmpEmp-' timeFlag],'DRsylls','empMatrices', 'empDistrs'); end %% construct co-similarity as fusion of local and global p-values fprintf('Calculating co-dissimilarity (correlation of dissimilarities, which is a similarity score)...\n'); fusedPVals = sqrt(empMatrices.warpedLocal .* empMatrices.global); distMatrices.cosim = pdist(squareform(fusedPVals), 'correlation'); % do the clustering - the easiest part nClusters = 4:10; pairLinks = linkage(distMatrices.cosim,'complete'); clustIdxs = cluster(pairLinks,'maxclust',nClusters); % undo sorting step clustIdxs(sortedIdx,:) = clustIdxs; scoreTypes = fieldnames(distMatrices); for ii = 1:numel(scoreTypes) distMatrices.(scoreTypes{ii}) = squareform(unsort2D(squareform(distMatrices.(scoreTypes{ii})), sortedIdx)); if isfield(empMatrices, scoreTypes{ii}) empMatrices.(scoreTypes{ii}) = squareform(unsort2D(squareform( empMatrices.(scoreTypes{ii})), sortedIdx)); end end end function mat = unsort2D(mat, sI) [coordsi, coordsj] = meshgrid(sI,sI); mat(sub2ind(size(mat),coordsi, coordsj)) = mat; end
github
BottjerLab/Acoustic_Similarity-master
getClipAndProcess.m
.m
Acoustic_Similarity-master/code/audioProc/getClipAndProcess.m
4,796
utf_8
30480d5c09cbb7de571c3d0a447cf8f6
function [clip, fs] = getClipAndProcess(songStruct, region, params, varargin) % GETCLIPANDPROCESS add pre/post roll, bandpass, and filter noise % % function clip = getClipAndProcess(songStruct, region, params) returns the % clean clip belonging to a specific region, as preprocessed by the % default params. % % revision note: an empty songStruct first argument can be given if the % region structure has a 'file' field which will access partial read data if nargin < 3 params = defaultParams; end params = processArgs(params, varargin{:}); region = addPrePost(region, params); % either filter noise or get raw values [clip, fs] = getClip(region, songStruct); params.fs = fs; minFiltLength = (params.noiseReduce.windowSize * 2 - ... params.noiseReduce.nOverlap) / 1000 + params.nps.attack; % minimum length in seconds if params.doFilterNoise && length(clip) / fs > minFiltLength if isempty(songStruct) && isempty(params.noiseFilter) && isfield(region,'file'); [filedir filestem] = fileparts(region.file); % TODO: check here manifest = struct('name','noiseMask','originalFile',[filedir filesep 'noiseMask-' filestem '.mat']); params.noiseFilter = loadFromManifest(manifest,'noiseMask'); end if isempty(params.noiseFilter) warning('getClipAndProcess:noNoiseFilter','Cannot find noise filter, skipping filtering for clip...'); else clip = noiseGate(clip, params.noiseFilter); end end % band pass the result clip = highPassSample(clip, params); clip = lowPassSample(clip, params); function reconstructClip = noiseGate(clip, noiseProfile) %NOISEGATE Extracts a noise filtered version of a clip % clip = noiseGate(songStruct, region, noiseProfile) returns a clip which % has been cleaned of its noise, following certain parameters % The spectral noise filter is equivalent to a bank of narrow band-passed % limiters for each frequency band. This has the general advantage of % precisely defining syllable boundaries in noisier recording conditions. % % noiseProfile is the 1D reduced FFT of noise given by noiseAnalysis.m params.noiseReduce.fs = fs; spec = getMTSpectrumStats(clip, params.noiseReduce); nps = params.nps; % define regions where gating is required -todo, apply hysteresis gain = ones(size(spec.spectrum)) * nps.reduction; for ifreq = 1:numel(spec.freqs) gain(ifreq,spec.psd(ifreq,:) >= noiseProfile(ifreq)) = 0.0; end % smooth in frequency space if nps.freqSmooth > 0.0 dF = spec.freqs(2) - spec.freqs(1); fWindowSize = nps.freqSmooth * 8/dF; % 4 half widths in either direction fWindow = (-fWindowSize / 2 : fWindowSize / 2) * dF; fWindow = exp(- (fWindow / nps.freqSmooth).^2); fWindow = fWindow ./ sum(fWindow) ; % normalize gain = conv2(fWindow,[1],gain,'same'); end % apply attack, hold, release dT = spec.times(2) - spec.times(1); attackRate = -nps.reduction * dT / nps.attack; releaseRate = -nps.reduction * dT / nps.release; holdSamples = floor(nps.hold / dT); for ifreq = 1:numel(spec.freqs) holdClock = 0; for iTp = 1:numel(spec.times)-1 dG = gain(ifreq, iTp+1) - gain(ifreq, iTp); if dG > attackRate % attack is on gain(ifreq, iTp+1) = gain(ifreq, iTp) + attackRate; elseif gain(ifreq,iTp + 1)== 0.0 % gate is open, hold is ready holdClock = holdSamples; elseif holdClock > 0 % hold is being used up gain(ifreq,iTp+1) = 0.0; holdClock = holdClock - 1; elseif dG < -releaseRate gain(ifreq, iTp+1) = gain(ifreq, iTp) - releaseRate; end end end % reduce volume in those bands adjustedSpec = spec.spectrum .* ... (10.^(gain / 10)); % the inverse spectrogram does not always reproduce the exact volume, but % this is pretty close to about +/- %1 scaleFac = 2.195; % empirically found by running spectrogram and inverse winSS = floor(params.noiseReduce.windowSize * params.noiseReduce.fs/1000); overlapSS = floor(params.noiseReduce.nOverlap * params.noiseReduce.fs/1000); reconstructClip = invspecgram(adjustedSpec, params.noiseReduce.NfreqBands, ... params.noiseReduce.fs, winSS, overlapSS); reconstructClip = reconstructClip / scaleFac; % debug function to plot either the spectrogram or the shape of the % spectral noise filter function hndl = plotGram(mat) mat = mat + eps; hndl = surf(spec.times, spec.freqs, 10*log10(abs(mat)),'EdgeColor','none'); view(0,90); xlim([min(spec.times) max(spec.times)]); xlabel('Time (s)'); ylim([min(spec.freqs) max(spec.freqs)]); ylabel('Frequency (Hz)'); colorbar; title(sprintf('max=%0.3f,min=%0.3f',10*log10(abs(max(mat(:)))),... 10*log10(abs(min(mat(:)))))); end end end
github
BottjerLab/Acoustic_Similarity-master
checkForNoise.m
.m
Acoustic_Similarity-master/code/workflow/checkForNoise.m
620
utf_8
e971738b1c5c8e7b18833aea214510e8
for ii = 1:numel(qqq) [newFeats,newSylls]=getFeatures(Lb277_3_27_4_Ch1,qqq(ii),noiseProfile,... 'plot',false,'verbose',true,'playsample',false); if ~isempty(newFeats) noisy = testIsNoise(forest, newFeats(1)); end end function isNoise = testIsNoise(Forest, featureStruct) %% compile feature matrix fields = fieldnames(featureStruct); nF = numel(fields); % number of features nE = numel(marks); % number of examples featVecs = zeros(nF, nE); % columns-major for ii = 1:nF featVecs(ii,:) = [features.(fields{ii})]; end isNoise = Classify(Forest.Learners, Forest.Weights, featVecs) > 0; end
github
BottjerLab/Acoustic_Similarity-master
loadSessionDataFiles.m
.m
Acoustic_Similarity-master/code/workflow/loadSessionDataFiles.m
3,278
utf_8
552b52726f88b0358eba63af39b6071c
%startup a current session function loadSessionDataFiles(session) dataDir = 'data\'; %session = 'Lb277_3_27'; birdID = strtok(session, '_'); dataSubdir = [dataDir dataSubdir filesep]; % look at what files are there dir([dataSubdir '*' session '*.mat']); fil=[dataSubdir session '_voice.mat']; if exist(fil,'file'), load(fil), else fprintf('%s not found...\n', fil); end fil = [dataSubdir 'markedSongs-' session '_voice.mat'] ; if exist(fil,'file'), load(fil), else fprintf('%s not found...\n', fil); end fil = [dataSubdir 'spikeRates-' session '_ch13-16_times.mat']; if exist(fil,'file'), load(fil), else fprintf('%s not found...\n', fil); end fil = [dataSubdir 'noiseMask-' session '_voice.mat']; if exist(fil,'file'), load(fil), else fprintf('%s not found...\n', fil); end fil = [dataSubdir 'tutorSimilarity-' session '_voice.mat']; if exist(fil,'file'), load(fil), else fprintf('%s not found...\n', fil); end % rename the songStruct (it's the biggest one) with a little dirty eval vars = whos; [~,bigVarIdx] = max([vars.bytes]); bigVarName = vars(bigVarIdx).name; eval(sprintf('songStruct = %s; clear %s', bigVarName, bigVarName)); %% (5) LOAD the SPIKE-SORTED-FILE and calculate firing rate during syllables %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% All processing up to this point has been solely on the song file %%%% To continue you should have: %%%% (a) some measure of distance between syllables and different tutor %%%% syllables (which we call stdDist), %%%% (b) definitions of the tutor syllables (tutorSylls), and %%%% (c) juvenileSylls with defined boundaries %%%% AND types that correspond to the tutor syllables' types %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this is where we LOAD the SPIKE-SORTED-FILE [matFile, matSpikePath] = uigetfile('*.mat','Please choose the SPIKING Spike2 file','data'); spikes = loadSpikeData([matSpikePath matFile]); % calculate spike data w.r.t segmented regions syllLengths = [juvenileSylls.stop] - [juvenileSylls.start]; for ii = 1:numel(spikes) [spikeCounts{ii}, spikeInternalTimes{ii}] = countSpikes(juvenileSylls, spikes{ii},'onset'); spikeRates{ii} = spikeCounts{ii} ./ syllLengths; end totalSpikeRates = sum(vertcat(spikeRates{:})); %spikeTimes = sort(vertcat(spikes{:})); %% (5.x) option: load ANOTHER spike file (make sure (5) is run first) syllLengths = [juvenileSylls.stop] - [juvenileSylls.start]; while(strcmp(questdlg('Load another spike file?', 'Load more spikes', 'OK','No', 'No'), 'OK')) [matFile, matpath] = uigetfile('*.mat','Please choose the SPIKING Spike2 file','data'); spikeData = load([matpath matFile]); clusterFields = fieldnames(spikeData); % append to spikes cell array and recount newSpikes = loadSpikeData([matpath matFile]); spikes = [spikes newSpikes]; for ii = 1:numel(newSpikes) [spikeCounts{end+1}, spikeInternalTimes{end+1}] = countSpikes(juvenileSylls, newSpikes{ii},'onset'); spikeRates{end+1} = spikeCounts{end} ./ syllLengths; end clear spikeData clusterFields end if exist('spikeRates'), totalSpikeRates = sum(vertcat(spikeRates{:})); end; %[spikeCounts, spikeInternalTimes] = countSpikes(juvenileSylls, spikeTimes,'onset');
github
BottjerLab/Acoustic_Similarity-master
examineClusterQuality.m
.m
Acoustic_Similarity-master/code/workflow/examineClusterQuality.m
6,435
utf_8
79b765aad674ddcef9542920f09210d6
%function examineClusterFull(birdID, sessFilter) function clustQuality = examineClusterQuality(birdID, ages) % calculate the objective cluster quality for the given ages of a bird % TODO: test rewrite - make objective cluster score % get the files clusterDir = [pwd filesep 'data' filesep 'cluster-' birdID filesep]; dataDir = [pwd filesep 'data' filesep birdID filesep]; clustQuality = cell(1,numel(ages)); for ii = 1:numel(ages) thisAge = ages(ii); [fil, filExist] = getLatestFile([clusterDir 'altClustDataAge-' ... num2str(thisAge) '*.mat']); if ~filExist error('examineClusterFull:missingDistances',... 'Missing distances file for bird %s, age %d', birdID, thisAge); end load(fil, 'distMats'); labelsFil = sprintf('%sacceptedLabels-%s-age%d.mat', dataDir, birdID, thisAge); if ~exist(labelsFil,'file') error('examineClusterFull:missingClusters',... 'Missing clusterfile for bird %s, age %d', birdID, thisAge); end syllLabels = loadAcceptedLabels(birdID, thisAge); % no labels means no quality if all(isnan(syllLabels)) clustQuality{ii} = []; continue; end % assign the types num2cell(syllLabels); [thisAgeSylls.type] = ans{:}; %#ok<NOANS> [~,clustQuality{ii}] = clusterQuality(distMats.cosim, syllLabels); end %{ % cross tabulate / tree out types fprintf('Cross-tabulation of syllables...\n'); nClusterings = size(syllLabels,2); nMaxClust = max(syllLabels(:,end)); splitNodes = zeros(1,nClusterings); parentRef = NaN(nMaxClust, nClusterings); for jj = 1:nClusterings-1 ct = crosstab(syllLabels(:,jj), syllLabels(:,jj+1)); splitNodes(jj) = find(sum(ct > 0, 2)==2,1); for kk = 1:size(ct,2) parentRef(kk,jj+1) = find(ct(:, kk) > 0, 1); end end nSylls = sum(isThisAge); mConform = zeros(nSylls, nClusterings); vConform = zeros(nSylls, nClusterings); clustQuality = NaN(nMaxClust, nClusterings); clustMConform = NaN(nMaxClust, nClusterings); clustVConform = NaN(nMaxClust, nClusterings); for jj = 1:nClusterings thisIdxs = syllLabels(:,jj); [mConform(:,jj), vConform] = conformity(distMats.cosim, thisIdxs); nClusters = max(thisIdxs); [~,clustQuality(1:nClusters, jj)] = clusterQuality(distMats.cosim, thisIdxs); for kk = 1:nClusters clustMConform(kk,jj) = mean(mConform(thisIdxs == kk)); clustVConform(kk,jj) = mean(vConform(thisIdxs == kk)); end end parentRef clustQuality clustMConform clustVConform %{ figureDir = [pwd filesep 'figures' filesep 'cluster-' birdID filesep clustSession{ii} filesep]; mkdir([pwd filesep 'figures' filesep 'cluster-' birdID filesep], clustSession{ii}); nClusts = max([thisAgeSylls.type]); for jj = 1:nClusts trainClust = thisAgeSylls([thisAgeSylls.type]==jj); if ~isempty(trainClust), figure hf = mosaicDRSpec(trainClust, [], 'dgram.minContrast', 1e-10, 'maxMosaicLength', 5.5, 'noroll'); set(hf,'Name', sprintf('Trained cluster %d, age %d, bird %s', jj, currAge, birdID)); saveCurrFigure(sprintf('%s%s_a%d_c%d-train.jpg', figureDir, birdID, currAge, jj)); close(hf); end end %} end %} %{ % get all cluster files that match the pattern for files = dir([clusterDir sessFilter]); files = {files.name}'; fPats = {'altClustDataAge-'}; isAssigned = strncmp(fPats{1}, files, length(fPats{1})); clustSession = strrep(strrep(files(isAssigned), fPats{1}, ''),'.mat',''); fprintf('Loading library for bird %s...\n',birdID); load([dataDir 'allSpecs-' birdID]) for ii = 1:numel(clustSession) if ~exist([clusterDir fPats{1} clustSession{ii} '.mat'], 'file') %&& ... %exist([clusterDir fPats{2} clustSession{ii}],'file')) continue; end fprintf('Loading session %s...\n', clustSession{ii}); clusterIdxs = []; load([clusterDir fPats{1} clustSession{ii}]); %load([clusterDir fPats{2} clustSession{ii}]); currAge = str2double(clustSession{ii}(1:2)); isThisAge = [DRsylls.age]==currAge; thisAgeSylls = DRsylls(isThisAge); % assign the types num2cell(clusterIdxs(:,end)); [thisAgeSylls.type] = ans{:}; %#ok<NOANS> % cross tabulate / tree out types fprintf('Cross-tabulation of syllables...\n'); nClusterings = size(clusterIdxs,2); nMaxClust = max(clusterIdxs(:,end)); splitNodes = zeros(1,nClusterings); parentRef = NaN(nMaxClust, nClusterings); for jj = 1:nClusterings-1 ct = crosstab(clusterIdxs(:,jj), clusterIdxs(:,jj+1)); splitNodes(jj) = find(sum(ct > 0, 2)==2,1); for kk = 1:size(ct,2) parentRef(kk,jj+1) = find(ct(:, kk) > 0, 1); end end nSylls = sum(isThisAge); mConform = zeros(nSylls, nClusterings); vConform = zeros(nSylls, nClusterings); clustQuality = NaN(nMaxClust, nClusterings); clustMConform = NaN(nMaxClust, nClusterings); clustVConform = NaN(nMaxClust, nClusterings); for jj = 1:nClusterings thisIdxs = clusterIdxs(:,jj); [mConform(:,jj), vConform] = conformity(distMats.cosim, thisIdxs); nClusters = max(thisIdxs); [~,clustQuality(1:nClusters, jj)] = clusterQuality(distMats.cosim, thisIdxs); for kk = 1:nClusters clustMConform(kk,jj) = mean(mConform(thisIdxs == kk)); clustVConform(kk,jj) = mean(vConform(thisIdxs == kk)); end end parentRef clustQuality clustMConform clustVConform figureDir = [pwd filesep 'figures' filesep 'cluster-' birdID filesep clustSession{ii} filesep]; mkdir([pwd filesep 'figures' filesep 'cluster-' birdID filesep], clustSession{ii}); nClusts = max([thisAgeSylls.type]); for jj = 1:nClusts trainClust = thisAgeSylls([thisAgeSylls.type]==jj); if ~isempty(trainClust), figure hf = mosaicDRSpec(trainClust, [], 'dgram.minContrast', 1e-10, 'maxMosaicLength', 5.5, 'noroll'); set(hf,'Name', sprintf('Trained cluster %d, age %d, bird %s', jj, currAge, birdID)); saveCurrFigure(sprintf('%s%s_a%d_c%d-train.jpg', figureDir, birdID, currAge, jj)); close(hf); end end end %}
github
BottjerLab/Acoustic_Similarity-master
reportOnData.m
.m
Acoustic_Similarity-master/code/workflow/reportOnData.m
8,565
utf_8
0855589187bfce7342e1e3c70b7de51b
function database = reportOnData(birdIDs, sessions, params, varargin) % reportOnData looks in the data folder and sees what is generated for what % folder % if birdIDs are provided, only looks at those birdIDs % if sessions are provided, only looks at those sessions % note: to clear old contents files, run clearSummaries.m dataDir = [pwd filesep 'data']; relDataDir = 'data'; % find all the bird IDs from directory if nargin < 1 || isempty(birdIDs) files = dir(dataDir); birdIDs = {files([files.isdir]).name}; isID = ~cellfun('isempty',regexp(birdIDs, '^[A-Z][a-z]?\d{1,3}')); %could make tighter by using cap birdIDs = birdIDs(isID); end if nargin < 2, sessions = ''; end if nargin < 3 || isempty(params), params = defaultParams; end if nargin > 3, params = processArgs(params,varargin{:}); end if ~iscell(birdIDs) birdIDs = {birdIDs}; end summaryFields = {'sessionID','manifest','spikeFiles'}; database = cell(1,numel(birdIDs)); for ii = 1:numel(birdIDs) % for each bird thisID = birdIDs{ii}; thisBirdPath = [dataDir filesep thisID]; relBirdPath = [relDataDir filesep thisID]; matFiles = dir([thisBirdPath filesep '*.mat']); matFiles = {matFiles.name}; % %%%%%%%% look for spike-sorted neuron files: % subdirectories in the bird directory % should contain NEURONS ONLY subDirs = dir(thisBirdPath); subDirs = {subDirs([subDirs.isdir]).name}; subDirs(1:2)=[]; % get rid of the first two . / .. directories % get all the neurons in the bird directory subdirectories birdNeuronFiles = ''; for jj = 1:numel(subDirs) % get all related files in this subdir % these are the neuron files thisSubDir = [thisBirdPath filesep subDirs{jj}]; relSubDir = [relBirdPath filesep subDirs{jj}]; possSpikeFiles = dir([thisSubDir filesep thisID '*times.mat']); if isempty(possSpikeFiles), continue; end birdNeuronFiles = [birdNeuronFiles strcat([relSubDir filesep], {possSpikeFiles.name})]; if params.rejectSpikeFiles filesToReject = ~cellfun('isempty', strfind(birdNeuronFiles,'REJECTME')); birdNeuronFiles = birdNeuronFiles(~filesToReject); end end isNFClaimed = false(1,numel(birdNeuronFiles)); % look for spike6 session files: they have the ID at the front isAudioFile = strncmp(matFiles, thisID, numel(thisID)); audioFiles = matFiles(isAudioFile); % get rid of the mat suffixes audioFiles = strrep(audioFiles, '.mat',''); if ~isempty(sessions) audioFiles = intersect(audioFiles, sessions); end sessionRecords = initEvents(numel(audioFiles),summaryFields); for jj = 1:numel(audioFiles) % for each session thisSession = audioFiles{jj}; thisSpikeStem = strtok(thisSession, '.'); isRelatedFile = ~cellfun('isempty',strfind(matFiles,thisSession)); relatedFiles = matFiles(isRelatedFile); % includes the original spikeFile % summary file -> not in the data directory, % but its parent directory summaryDir = [dataDir filesep '..' filesep 'summaries']; if ~exist(summaryDir, 'dir'), mkdir(summaryDir); end summaryFile = [summaryDir filesep ... 'contents-' thisSession '.mat']; % get a manifest of all the files % first, check to see if the contents are updated freshContents = false; if exist(summaryFile,'file') freshContents = true; contentUpdate = getModifiedStamp(summaryFile); for kk = 1:numel(relatedFiles) if(getModifiedStamp([thisBirdPath filesep relatedFiles{kk}]) > contentUpdate) freshContents = false; break; end end if ~isempty(birdNeuronFiles) % are we related to this particular session? isRelatedNeuronFile = ~cellfun('isempty',strfind(birdNeuronFiles,thisSpikeStem)); relatedNeuronFiles = birdNeuronFiles(isRelatedNeuronFile); for kk = 1:numel(relatedNeuronFiles) if(getModifiedStamp(relatedNeuronFiles{kk}) > contentUpdate) freshContents = false; break; end end end end % if the summary file is fresher than its related data files if freshContents % read off the manifest from the previous file, converting the one-field % structure to a struct. tmp = load(summaryFile); flds = fieldnames(tmp); sessionRecords(jj) = tmp.(flds{1}); if ~isempty(birdNeuronFiles) isNFClaimed = isNFClaimed | cellfun(... @(x) any(strcmpi(x,sessionRecords(jj).spikeFiles)), birdNeuronFiles); end else [~,idxShortest] = min(cellfun('length',relatedFiles)); [~,contents.sessionID,~] = fileparts(relatedFiles{idxShortest}); relatedFiles = strcat([relBirdPath filesep], relatedFiles); contents.manifest = getManifest(relatedFiles); contents.spikeFiles = []; % find the neuron files that are linked with the session if ~isempty(birdNeuronFiles) isRelatedNeuronFile = ~cellfun('isempty',strfind(birdNeuronFiles,thisSpikeStem)); isNFClaimed = isNFClaimed | isRelatedNeuronFile; contents.spikeFiles = birdNeuronFiles(isRelatedNeuronFile); end save(summaryFile,'contents'); sessionRecords(jj) = contents; end spikeData = loadSpikeData(sessionRecords(jj).spikeFiles); nNeurons = numel(spikeData); if params.verbose && ~params.quiet fprintf('%s/%s with %d recorded variables, %d neurons...\n', thisID, thisSession, numel(sessionRecords(jj).manifest), nNeurons); for kk = 1:numel(sessionRecords(jj).manifest) fprintf('\t%s --> %s\n', sessionRecords(jj).manifest(kk).originalFile, ... sessionRecords(jj).manifest(kk).name); end end end unclaimedSessionRecords = initEvents(0,summaryFields); if any(~isNFClaimed) && isempty(sessions) unclaimedNeuronFiles = birdNeuronFiles(~isNFClaimed); % get the session IDs from the neuron files sessionID = cell(1,numel(unclaimedNeuronFiles)); for jj = 1:numel(unclaimedNeuronFiles) [~, birdFile] = fileparts(unclaimedNeuronFiles{jj}); sessionID{jj} = birdFile(1:strfind(birdFile, '_ch')-1); end [uniqIDs,~,crossIdxs] = unique(sessionID); unclaimedSessionRecords = initEvents(numel(uniqIDs),summaryFields); for jj = 1:numel(uniqIDs) unclaimedSessionRecords(jj).sessionID = sessionID{jj}; iNeuronFiles = unclaimedNeuronFiles(crossIdxs==jj); if params.verbose && ~params.quiet fprintf('UNPROCESSED: %s - %d attached neurons...\n', uniqIDs{jj}, ... numel(loadSpikeData(iNeuronFiles))); end % let's create an entry for these files now unclaimedSessionRecords(jj).manifest=[]; unclaimedSessionRecords(jj).spikeFiles = iNeuronFiles; end end database{ii} = [sessionRecords unclaimedSessionRecords]; if params.rejectNoNeuronSessions sessionsWithNoNeurons = arrayfun(@(x) isempty(x.spikeFiles), database{ii}); database{ii}(sessionsWithNoNeurons) = []; end end if numel(database) == 1 database = database{1}; end function manifest = getManifest(files) manifest = initEvents(0, {'name','originalFile'}); for iFile = 1:numel(files) thisFile = files{iFile}; % this who step is slow, so we presave manifests vars = who('-file', thisFile); fileVars = struct('name',vars); % make the path relative [fileVars.originalFile] = deal(thisFile); % we don't know how many variables each file has, hence no % preallocation manifest = [manifest; fileVars]; end function timestamp = getModifiedStamp(filename) if ~iscell(filename) timestamp = getfield(dir(filename),'datenum'); else timestamp = cellfun(@(x) getfield(dir(x),'datenum'), filename); end
github
BottjerLab/Acoustic_Similarity-master
examineClusterFull.m
.m
Acoustic_Similarity-master/code/workflow/examineClusterFull.m
6,296
utf_8
de956fe651ecf344838022d04dae40fb
%function examineClusterFull(birdID, sessFilter) function clustQuality = examineClusterFull(birdID, ages) % get the objective cluster quality for the given ages of a bird % TODO: test rewrite - make objective cluster score % get the files clusterDir = [pwd filesep 'data' filesep 'cluster-' birdID filesep]; dataDir = [pwd filesep 'data' filesep birdID filesep]; clustQuality = cell(1,numel(ages)); for ii = 1:numel(ages) thisAge = ages(ii); [fil, filExist] = getLatestFile([clusterDir 'altClustDataAge-' ... num2str(thisAge) '*.mat']); if ~filExist error('examineClusterFull:missingDistances',... 'Missing distances file for bird %s, age %d', birdID, thisAge); end load(fil, 'distMats'); labelsFil = sprintf('%sacceptedLabels-%s-age%d.mat', dataDir, birdID, thisAge); if ~exist(labelsFil,2) error('examineClusterFull:missingClusters',... 'Missing clusterfile for bird %s, age %d', birdID, thisAge); end syllLabels = loadAcceptedLabels(birdID, thisAge); % assign the types num2cell(syllLabels); [thisAgeSylls.type] = ans{:}; %#ok<NOANS> [~,clustQuality{ii}] = clusterQuality(distMats.cosim, syllLabels); end %{ % cross tabulate / tree out types fprintf('Cross-tabulation of syllables...\n'); nClusterings = size(syllLabels,2); nMaxClust = max(syllLabels(:,end)); splitNodes = zeros(1,nClusterings); parentRef = NaN(nMaxClust, nClusterings); for jj = 1:nClusterings-1 ct = crosstab(syllLabels(:,jj), syllLabels(:,jj+1)); splitNodes(jj) = find(sum(ct > 0, 2)==2,1); for kk = 1:size(ct,2) parentRef(kk,jj+1) = find(ct(:, kk) > 0, 1); end end nSylls = sum(isThisAge); mConform = zeros(nSylls, nClusterings); vConform = zeros(nSylls, nClusterings); clustQuality = NaN(nMaxClust, nClusterings); clustMConform = NaN(nMaxClust, nClusterings); clustVConform = NaN(nMaxClust, nClusterings); for jj = 1:nClusterings thisIdxs = syllLabels(:,jj); [mConform(:,jj), vConform] = conformity(distMats.cosim, thisIdxs); nClusters = max(thisIdxs); [~,clustQuality(1:nClusters, jj)] = clusterQuality(distMats.cosim, thisIdxs); for kk = 1:nClusters clustMConform(kk,jj) = mean(mConform(thisIdxs == kk)); clustVConform(kk,jj) = mean(vConform(thisIdxs == kk)); end end parentRef clustQuality clustMConform clustVConform %{ figureDir = [pwd filesep 'figures' filesep 'cluster-' birdID filesep clustSession{ii} filesep]; mkdir([pwd filesep 'figures' filesep 'cluster-' birdID filesep], clustSession{ii}); nClusts = max([thisAgeSylls.type]); for jj = 1:nClusts trainClust = thisAgeSylls([thisAgeSylls.type]==jj); if ~isempty(trainClust), figure hf = mosaicDRSpec(trainClust, [], 'dgram.minContrast', 1e-10, 'maxMosaicLength', 5.5, 'noroll'); set(hf,'Name', sprintf('Trained cluster %d, age %d, bird %s', jj, currAge, birdID)); saveCurrFigure(sprintf('%s%s_a%d_c%d-train.jpg', figureDir, birdID, currAge, jj)); close(hf); end end %} end %{ % get all cluster files that match the pattern for files = dir([clusterDir sessFilter]); files = {files.name}'; fPats = {'altClustDataAge-'}; isAssigned = strncmp(fPats{1}, files, length(fPats{1})); clustSession = strrep(strrep(files(isAssigned), fPats{1}, ''),'.mat',''); fprintf('Loading library for bird %s...\n',birdID); load([dataDir 'allSpecs-' birdID]) for ii = 1:numel(clustSession) if ~exist([clusterDir fPats{1} clustSession{ii} '.mat'], 'file') %&& ... %exist([clusterDir fPats{2} clustSession{ii}],'file')) continue; end fprintf('Loading session %s...\n', clustSession{ii}); clusterIdxs = []; load([clusterDir fPats{1} clustSession{ii}]); %load([clusterDir fPats{2} clustSession{ii}]); currAge = str2double(clustSession{ii}(1:2)); isThisAge = [DRsylls.age]==currAge; thisAgeSylls = DRsylls(isThisAge); % assign the types num2cell(clusterIdxs(:,end)); [thisAgeSylls.type] = ans{:}; %#ok<NOANS> % cross tabulate / tree out types fprintf('Cross-tabulation of syllables...\n'); nClusterings = size(clusterIdxs,2); nMaxClust = max(clusterIdxs(:,end)); splitNodes = zeros(1,nClusterings); parentRef = NaN(nMaxClust, nClusterings); for jj = 1:nClusterings-1 ct = crosstab(clusterIdxs(:,jj), clusterIdxs(:,jj+1)); splitNodes(jj) = find(sum(ct > 0, 2)==2,1); for kk = 1:size(ct,2) parentRef(kk,jj+1) = find(ct(:, kk) > 0, 1); end end nSylls = sum(isThisAge); mConform = zeros(nSylls, nClusterings); vConform = zeros(nSylls, nClusterings); clustQuality = NaN(nMaxClust, nClusterings); clustMConform = NaN(nMaxClust, nClusterings); clustVConform = NaN(nMaxClust, nClusterings); for jj = 1:nClusterings thisIdxs = clusterIdxs(:,jj); [mConform(:,jj), vConform] = conformity(distMats.cosim, thisIdxs); nClusters = max(thisIdxs); [~,clustQuality(1:nClusters, jj)] = clusterQuality(distMats.cosim, thisIdxs); for kk = 1:nClusters clustMConform(kk,jj) = mean(mConform(thisIdxs == kk)); clustVConform(kk,jj) = mean(vConform(thisIdxs == kk)); end end parentRef clustQuality clustMConform clustVConform figureDir = [pwd filesep 'figures' filesep 'cluster-' birdID filesep clustSession{ii} filesep]; mkdir([pwd filesep 'figures' filesep 'cluster-' birdID filesep], clustSession{ii}); nClusts = max([thisAgeSylls.type]); for jj = 1:nClusts trainClust = thisAgeSylls([thisAgeSylls.type]==jj); if ~isempty(trainClust), figure hf = mosaicDRSpec(trainClust, [], 'dgram.minContrast', 1e-10, 'maxMosaicLength', 5.5, 'noroll'); set(hf,'Name', sprintf('Trained cluster %d, age %d, bird %s', jj, currAge, birdID)); saveCurrFigure(sprintf('%s%s_a%d_c%d-train.jpg', figureDir, birdID, currAge, jj)); close(hf); end end end %}
github
BottjerLab/Acoustic_Similarity-master
getSpectrumStats.m
.m
Acoustic_Similarity-master/code/obsoleted/getSpectrumStats.m
3,226
utf_8
9acb25dde98de1dc0bc1056aa718a6c2
function spectrumData = getSpectrumStats(sample, params) % acquire spectrogram - TODO: use multitaper % https://github.com/dmeliza/libtfr winSS = floor(params.windowSize * params.fs/1000); overlapSS = floor(params.nOverlap * params.fs/1000); if ~isfield(params,'freqBands') [spectrumData.spectrum, spectrumData.freqs, spectrumData.times, spectrumData.psd] = ... spectrogram(sample, winSS, overlapSS, params.NfreqBands, params.fs); else [spectrumData.spectrum, spectrumData.freqs, spectrumData.times, spectrumData.psd] = ... spectrogram(sample, winSS, overlapSS, params.freqBands, params.fs); end % get center frequency - simply weighted average by spectrogram spectrumData.centerFreq = getCentroidFreq(spectrumData); % get total power spectrumData.totalPower = getTotalPower(spectrumData); % get wiener entropy: high = noise, low = pure tone, mid = stack/chirp ramp spectrumData.wienerEntropy = getEntropy(spectrumData); % get derivative spectrogram %spectrumData.deriv = getSpectralDerivative(spectrumData, params); [spectrumData.deriv spectrumData.mTD, spectrumData.mFD, spectrumData.FM] ... = getSpectralDerivative(spectrumData); % get pitch goodness [spectrumData.pitchGoodness, spectrumData.harmonicPitch] = ... getHarmonicPitch(spectrumData, params); end function power = getTotalPower(spectrum) dFreq = spectrum.freqs(2) - spectrum.freqs(1); power = sqrt(dot(spectrum.psd,spectrum.psd)) * dFreq; % amp factor end function centerfreq = getCentroidFreq(spectrum) centerfreq = spectrum.freqs' * spectrum.psd ./ sum(spectrum.psd); end function entropy = getEntropy(spectrum) % Wiener entropy, defined as the log ratio of GM to AM of the power % pure white noise means that Wiener entropy should be 0, and pure tone % should have -inf Wiener entropy AMpsd = mean(spectrum.psd,1); logGMpsd = mean(log(spectrum.psd),1); entropy = logGMpsd - log(AMpsd); end % get mag gradient of spectral derivative, as well as frequency Modulation function [deriv, mTD, mFD, freqMod] = getSpectralDerivative(spectrum) % and maximum derivatives in time and space dt = spectrum.times(2) - spectrum.times(1); df = spectrum.freqs(2) - spectrum.freqs(1); freqDeriv = conv2([1 0 -1], [1], spectrum.psd, 'same') / df; timeDeriv = conv2([1], [1 0 -1], spectrum.psd, 'same') / dt; deriv = sqrt(timeDeriv.*timeDeriv + ... freqDeriv .* freqDeriv) .* sign(freqDeriv); mTD = max(abs(timeDeriv),[],1); mFD = max(abs(freqDeriv),[],1); %[foo,imax] = max(abs(deriv), [], 1); % this definition doesn't seem to be that sensitive freqMod = atan2(max(abs(freqDeriv),[],1),max(abs(timeDeriv / 1000),[],1)) * 180 / pi; %{ tPart = sin(freqMod); fPart = cos(freqMod); deriv = timeDeriv .* (ones(size(spectrum.freqs)) * tPart) + ... freqDeriv .* (ones(size(spectrum.freqs)) * fPart) ./ spectrum.psd; %} end function [goodness, pitch] = getHarmonicPitch(spectrum, params) dcepstrum = fft(spectrum.deriv,[],1); dcepstrum = dcepstrum(1:ceil(end/2),:); % remove the non-symmetric part out % pitch goodness is unscaled, calculated from deriv-cepstrum as in SAP % 2011 % harmonic pitch is estimated as well - doesn't seem to work too well [goodness, pitch] = max(abs(dcepstrum),[],1); pitch = params.fs./pitch; end
github
BottjerLab/Acoustic_Similarity-master
editEventsNoLabelOLD.m
.m
Acoustic_Similarity-master/code/obsoleted/editEventsNoLabelOLD.m
10,197
utf_8
99d7c2aaf98a6ba4f6f61bea18bafa43
afunction evsNew = editEvents(evs) % Prereqs: active figure/axes that are appropriate to have marks % evs is properly sorted % NB: for resizing to work properly, the axes property 'Units' should be % normalized % housekeeping, removing warning RGBWarnID = 'MATLAB:hg:patch:RGBColorDataNotSupported'; warnState = warning('query',RGBWarnID); warning('off',RGBWarnID'); if isempty(evs), evs = initEvents; fs = 44100; % FIXME: a pure guess warning('editEvents:InputUninitialized','Events uninitialized, sampling rate may be incorrect...'); else fs = evs(1).idxStart/evs(1).start; end greycol = [0.75 0.75 0.75]; % inform user of termination behavior oldTitle = get(get(gca,'Title'),'String'); newTitle = 'Click outside figure to exit and save'; title(newTitle); % create patch handle hp = plotAreaMarks(evs,greycol); % prepare handle for axes hax = gca; set(gcf,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); set(gcf,'WindowButtonUpFcn',{@buttonUpFcn, [hax hp]}); set(gcf,'WindowButtonDownFcn',{@buttonDownFcn, [hax hp]}); disp('Click outside to finish'); % exit is triggered when mouseUp occurs outside the axis window waitfor(gcf,'WindowButtonMotionFcn',''); % clean up - restore any changed properties title(oldTitle); warning(warnState.state,RGBWarnID); % read the events back from the edited patch handle xdat = get(hp,'XData'); evsNew = initEvents(size(xdat,2)); if isempty(xdat), return; end; % return an empty event structure if no marks starts = num2cell(xdat(2,:)); idxStarts = num2cell(floor(xdat(2,:) * fs)); stops = num2cell(xdat(3,:)); idxStops = num2cell( ceil(xdat(3,:) * fs)); [evsNew.start] = starts{:}; [evsNew.stop] = stops{:}; [evsNew.idxStart] = idxStarts{:}; [evsNew.idxStop] = idxStops{:}; [evsNew.type] = deal(NaN); % get rid of the old patch delete(hp); end %%%%%%%% begin callbacks %%%%%%%%%%%%% function mouseOverFcn(gcbo, eventdata, handles) % some default colors greyCol = [0.75 0.75 0.75]; hiCol = [0.5 0.5 0.5]; lineCol = [0.8 0 0]; % unpack handles hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currPt = currPt(1,1:2); nFaces = size(get(hp,'XData'),2); vertexColors = greyCol(ones(4 * nFaces,1),:); [patchHover, lineHover] = clickStatus(currPt, handles); if ~isempty(patchHover) % highlight that patch vertexColors(patchHover * 4 - 3,:) = hiCol; if ~isempty(lineHover) vertexColors(patchHover * 4 + [-2,0],:) = lineCol(ones(2,1),:); end end set(hp,'FaceVertexCData',vertexColors); end function buttonUpFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); % get point relative to window to determine if click lies outside currPt = get(gcbo,'CurrentPoint'); currPt(1,1:2); oldUnits = get(gca,'Units'); set(gca,'Units','pixels'); axisWindow = get(hax,'Position'); set(gca,'Units',oldUnits); % exiting function - did we click outside the figure and not as part of a drag? if ~inRect(axisWindow, currPt) && isempty(get(hp,'UserData')); % clearing the callbacks is the signal for the program to exit set(gcbo,'WindowButtonMotionFcn',''); set(gcbo,'WindowButtonUpFcn',''); set(gcbo,'WindowButtonDownFcn',''); elseif ~isempty(get(hp,'UserData')) % finished editing drag % clean up intervals %(1) negative intervals - delete %(2) overlapping intervals - merge resolveOverlaps(hp); set(hp,'UserData',''); set(gcbo,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); disp('Letting go'); else disp('Still holding on...'); end end function buttonDownFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currPt = currPt(1,1:2); [patchClicked, lineClicked, hitWindow] = clickStatus(currPt, handles); if ~hitWindow, return; end; if isempty(patchClicked) % nothing, or create new event? % create new event currXData = get(hp, 'XData'); currYData = get(hp, 'YData'); currVertexColors = get(hp, 'FaceVertexCData'); % find where to insert new event insertPt = find(currPt(1) <= [currXData(1,:) Inf], 1); currXData = [currXData(:,1:insertPt-1) currPt(1)*ones(4,1) currXData(:,insertPt:end)]; currYData = currYData(:,[1 1:end]); %all columns are the same currVertexColors = currVertexColors([ones(1,4) 1:end], :);% we need four more rows, but the colors are all the same disp('Creating patch'); set(hp,'XData',currXData,'YData',currYData,'FaceVertexCData',currVertexColors); % handle dragging dragData = struct('lineHeld', [], ... 'startPt', currPt, ... 'patchHeld', insertPt, ... 'justCreated', true, ... 'origBounds', []); set(hp,'UserData',dragData); set(gcf,'WindowButtonMotionFcn',{@draggingFcn, [hax hp]}); else xBounds = get(hp,'XData'); dragData = struct('lineHeld', lineClicked, ... 'startPt', currPt, ... 'patchHeld', patchClicked,... 'justCreated', false,... 'origBounds', xBounds(:,patchClicked)); set(hp,'UserData',dragData); set(gcf,'WindowButtonMotionFcn',{@draggingFcn, [hax hp]}); end end function draggingFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currXData = get(hp,'XData'); userData = get(hp, 'UserData'); %nFaces = size(currXData,2); if isempty(userData.patchHeld) error('editEvents:PatchNotClicked','Patch not Clicked, drag callback should not be set'); end if userData.justCreated % if we just created an event, detect the drag motion if currPt(1) ~= userData.startPt(1) userData.justCreated = false; userData.lineHeld = 1 + (currPt(1) > userData.startPt(1)); end set(hp,'UserData',userData); end if ~isempty(userData.lineHeld) % moving one edge of the eventdata rIdxs = 2 * userData.lineHeld + [-1 0]; currXData(rIdxs,userData.patchHeld) = currPt(1); set(hp,'XData',currXData); % detect collisions immediately and quit drag if detectCollision(hp,userData.patchHeld,userData.lineHeld), set(gcbo,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); resolveOverlaps(hp); end else % moving whole event currXData(:,userData.patchHeld) = userData.origBounds + currPt(1) - userData.startPt(1); set(hp,'XData',currXData); end end %%%%%%%% end callbacks %%%%%%%%%%%%% function resolveOverlaps(patchHandle) % cleaning up intervals, %keeping colors the same greyCol = [0.75 0.75 0.75]; currXData = get(patchHandle,'XData'); currYData = get(patchHandle,'YData'); %currColData = get(patchHandle,'FaceVertexCData'); if isempty(currXData), return; end; % nothing to resolve borders = currXData(2:3,:); % remove any negative-length intervals isNonPosLength = (borders(1,:) >= borders(2,:)); borders(:,isNonPosLength) = []; % merge overlapping regions % since the number of regions is probably small (<10), we'll do this in a % naive way (better is with interval trees) ii = 1; nFaces = size(borders,2); while ii <= nFaces && nFaces > 1 toMerge = find(borders(1,ii) >= borders(1,:) & borders(1,ii) <= borders(2,:) | ... borders(2,ii) >= borders(1,:) & borders(2,ii) <= borders(2,:)); if numel(toMerge) > 1 disp('Merging...') borders(1,ii) = min(borders(1,toMerge)); borders(2,ii) = max(borders(2,toMerge)); toDelete = toMerge(toMerge ~= ii); borders(:,toDelete) = []; nFaces = size(borders,2); else ii = ii + 1; end end currXData = borders([1 1 2 2],:); currYData = currYData(:,ones(1,nFaces)); % just copy the first row currColData = greyCol(ones(4*nFaces,1),:); % just copy the first color set(patchHandle,'XData',currXData,'YData',currYData,'FaceVertexCData',currColData); end function didCollide = detectCollision(patchHandle,activePatch, boundarySide) currXData = get(patchHandle,'XData'); if isempty(currXData), return; end; % nothing to collide borders = currXData(2:3,:); nFaces = size(borders,2); adjBorder = NaN; if activePatch > 1 && boundarySide == 1 adjBorder = borders(2,activePatch - 1); elseif activePatch < nFaces && boundarySide == 2 adjBorder = borders(1,activePatch + 1); end didCollide = (borders(1,activePatch) >= borders(2,activePatch)) || ... borders(boundarySide,activePatch) <= adjBorder && boundarySide == 1 || ... borders(boundarySide,activePatch) >= adjBorder && boundarySide == 2; end function foo = inRect(win, pt) foo = win(1) <= pt(1) && pt(1) < win(1) + win(3) && ... win(2) <= pt(2) && pt(2) < win(2) + win(4); end function [patchSeld, lineSeld, hitWindow] = clickStatus(currPt, handles) % returns empties on default patchSeld = []; lineSeld = []; hax = handles(1); hp = handles(2); win([1 3]) = get(hax,'XLim'); win(3) = win(3) - win(1); win([2 4]) = get(hax,'YLim'); win(4) = win(4) - win(2); hitWindow = inRect(win, currPt); if ~hitWindow, return, end; % how 'fat' should our edge be for us to highlight/grab it? edgeFuzzFrac = 0.0035; edgeFuzz = diff(get(hax,'XLim')) * edgeFuzzFrac; yy = get(hax,'YLim'); if currPt(2) > yy(2) || currPt(2) < yy(1), return; end; xBounds = get(hp,'XData'); if isempty(xBounds), return; end; % nothing to click xBounds = xBounds(2:3,:); patchSeld = ... find(xBounds(1,:) - edgeFuzz <= currPt(1) & ... xBounds(2,:) + edgeFuzz >= currPt(1)); if any(abs(xBounds(1,:) - currPt(1)) <= edgeFuzz), lineSeld = 1; elseif any(abs(xBounds(2,:) - currPt(1)) <= edgeFuzz), lineSeld = 2; end end
github
BottjerLab/Acoustic_Similarity-master
editEventsOLD.m
.m
Acoustic_Similarity-master/code/obsoleted/editEventsOLD.m
10,556
utf_8
06bb207d15179346d7118826aa157710
function evsNew = editEvents(evs,fs) % Prereqs: active figure/axes that are appropriate to have marks % evs is properly sorted % NB: for resizing to work properly, the axes property 'Units' should be % normalized % housekeeping, removing warning RGBWarnID = 'MATLAB:hg:patch:RGBColorDataNotSupported'; warnState = warning('query',RGBWarnID); warning('off',RGBWarnID'); if isempty(evs), evs = initEvents; if nargin < 2 fs = 44100; % FIXME: a pure guess warning('editEvents:InputUninitialized','Events uninitialized, sampling rate may be incorrect...'); end else if nargin < 2 fs = evs(1).idxStart/evs(1).start; end end greycol = [0.75 0.75 0.75]; % inform user of termination behavior oldTitle = get(get(gca,'Title'),'String'); newTitle = 'Click outside figure to exit and save'; title(newTitle); % create patch handle if isempty(evs) % create a fake event and then delete it later hp = plotAreaMarks(initEvent,greycol); else hp = plotAreaMarks(evs,greycol); end % prepare handle for axes hax = gca; set(gcf,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); set(gcf,'WindowButtonUpFcn',{@buttonUpFcn, [hax hp]}); set(gcf,'WindowButtonDownFcn',{@buttonDownFcn, [hax hp]}); disp('Click outside to finish'); % exit is triggered when mouseUp occurs outside the axis window waitfor(gcf,'WindowButtonMotionFcn',''); % clean up - restore any changed properties title(oldTitle); warning(warnState.state,RGBWarnID); % read the events back from the edited patch handle xdat = get(hp,'XData'); evsNew = initEvents(size(xdat,2)); if isempty(xdat), return; end; % return an empty event structure if no marks starts = num2cell(xdat(2,:)); idxStarts = num2cell(floor(xdat(2,:) * fs)); stops = num2cell(xdat(3,:)); idxStops = num2cell( ceil(xdat(3,:) * fs)); [evsNew.start] = starts{:}; [evsNew.stop] = stops{:}; [evsNew.idxStart] = idxStarts{:}; [evsNew.idxStop] = idxStops{:}; [evsNew.type] = deal(NaN); % get rid of the old patch delete(hp); % if we had an empty event structure to begin with, remove the placeholder % first structure if isempty(evs) evsNew(1) = []; end end %%%%%%%% begin callbacks %%%%%%%%%%%%% function mouseOverFcn(gcbo, eventdata, handles) % some default colors greyCol = [0.75 0.75 0.75]; hiCol = [0.5 0.5 0.5]; lineCol = [0.8 0 0]; % unpack handles hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currPt = currPt(1,1:2); nFaces = size(get(hp,'XData'),2); vertexColors = greyCol(ones(4 * nFaces,1),:); [patchHover, lineHover] = clickStatus(currPt, handles); if ~isempty(patchHover) % highlight that patch vertexColors(patchHover * 4 - 3,:) = hiCol; % what if numel(patchHover) > 1 if ~isempty(lineHover) vertexColors(patchHover * 4 + [-2,0],:) = lineCol(ones(2,1),:); end end set(hp,'FaceVertexCData',vertexColors); end function buttonUpFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); % get point relative to window to determine if click lies outside currPt = get(gcbo,'CurrentPoint'); currPt(1,1:2); oldUnits = get(gca,'Units'); set(gca,'Units','pixels'); axisWindow = get(hax,'Position'); set(gca,'Units',oldUnits); % exiting function - did we click outside the figure and not as part of a drag? if ~inRect(axisWindow, currPt) && isempty(get(hp,'UserData')); % clearing the callbacks is the signal for the program to exit set(gcbo,'WindowButtonMotionFcn',''); set(gcbo,'WindowButtonUpFcn',''); set(gcbo,'WindowButtonDownFcn',''); elseif ~isempty(get(hp,'UserData')) % finished editing drag % clean up intervals %(1) negative intervals - delete %(2) overlapping intervals - merge resolveOverlaps(hp); set(hp,'UserData',''); set(gcbo,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); disp('Letting go'); else disp('Still holding on...'); end end function buttonDownFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currPt = currPt(1,1:2); [patchClicked, lineClicked, hitWindow] = clickStatus(currPt, handles); if ~hitWindow, return; end; if isempty(patchClicked) % nothing, or create new event? % create new event currXData = get(hp, 'XData'); currYData = get(hp, 'YData'); currVertexColors = get(hp, 'FaceVertexCData'); % find where to insert new event insertPt = find(currPt(1) <= [currXData(1,:) Inf], 1); currXData = [currXData(:,1:insertPt-1) currPt(1)*ones(4,1) currXData(:,insertPt:end)]; currYData = currYData(:,[1 1:end]); %all columns are the same currVertexColors = currVertexColors([ones(1,4) 1:end], :);% we need four more rows, but the colors are all the same disp('Creating patch'); set(hp,'XData',currXData,'YData',currYData,'FaceVertexCData',currVertexColors); % handle dragging dragData = struct('lineHeld', [], ... 'startPt', currPt, ... 'patchHeld', insertPt, ... 'justCreated', true, ... 'origBounds', []); set(hp,'UserData',dragData); set(gcf,'WindowButtonMotionFcn',{@draggingFcn, [hax hp]}); else xBounds = get(hp,'XData'); dragData = struct('lineHeld', lineClicked, ... 'startPt', currPt, ... 'patchHeld', patchClicked,... 'justCreated', false,... 'origBounds', xBounds(:,patchClicked)); set(hp,'UserData',dragData); set(gcf,'WindowButtonMotionFcn',{@draggingFcn, [hax hp]}); end end function draggingFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currXData = get(hp,'XData'); userData = get(hp, 'UserData'); %nFaces = size(currXData,2); if isempty(userData.patchHeld) error('editEvents:PatchNotClicked','Patch not Clicked, drag callback should not be set'); end if userData.justCreated % if we just created an event, detect the drag motion if currPt(1) ~= userData.startPt(1) userData.justCreated = false; userData.lineHeld = 1 + (currPt(1) > userData.startPt(1)); end set(hp,'UserData',userData); end if ~isempty(userData.lineHeld) % moving one edge of the eventdata rIdxs = 2 * userData.lineHeld + [-1 0]; currXData(rIdxs,userData.patchHeld) = currPt(1); set(hp,'XData',currXData); % detect collisions immediately and quit drag if detectCollision(hp,userData.patchHeld,userData.lineHeld), set(gcbo,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); resolveOverlaps(hp); end else % moving whole event currXData(:,userData.patchHeld) = userData.origBounds + currPt(1) - userData.startPt(1); set(hp,'XData',currXData); end end %%%%%%%% end callbacks %%%%%%%%%%%%% function resolveOverlaps(patchHandle) % cleaning up intervals, %keeping colors the same greyCol = [0.75 0.75 0.75]; currXData = get(patchHandle,'XData'); currYData = get(patchHandle,'YData'); %currColData = get(patchHandle,'FaceVertexCData'); if isempty(currXData), return; end; % nothing to resolve borders = currXData(2:3,:); % remove any negative-length intervals isNonPosLength = (borders(1,:) >= borders(2,:)); borders(:,isNonPosLength) = []; % merge overlapping regions % since the number of regions is probably small (<10), we'll do this in a % naive way (better is with interval trees) ii = 1; nFaces = size(borders,2); while ii <= nFaces && nFaces > 1 toMerge = find(borders(1,ii) >= borders(1,:) & borders(1,ii) <= borders(2,:) | ... borders(2,ii) >= borders(1,:) & borders(2,ii) <= borders(2,:)); if numel(toMerge) > 1 disp('Merging...') borders(1,ii) = min(borders(1,toMerge)); borders(2,ii) = max(borders(2,toMerge)); toDelete = toMerge(toMerge ~= ii); borders(:,toDelete) = []; nFaces = size(borders,2); else ii = ii + 1; end end currXData = borders([1 1 2 2],:); currYData = currYData(:,ones(1,nFaces)); % just copy the first row currColData = greyCol(ones(4*nFaces,1),:); % just copy the first color set(patchHandle,'XData',currXData,'YData',currYData,'FaceVertexCData',currColData); end function didCollide = detectCollision(patchHandle,activePatch, boundarySide) currXData = get(patchHandle,'XData'); if isempty(currXData), return; end; % nothing to collide borders = currXData(2:3,:); nFaces = size(borders,2); adjBorder = NaN; if activePatch > 1 && boundarySide == 1 adjBorder = borders(2,activePatch - 1); elseif activePatch < nFaces && boundarySide == 2 adjBorder = borders(1,activePatch + 1); end didCollide = (borders(1,activePatch) >= borders(2,activePatch)) || ... borders(boundarySide,activePatch) <= adjBorder && boundarySide == 1 || ... borders(boundarySide,activePatch) >= adjBorder && boundarySide == 2; end function foo = inRect(win, pt) foo = win(1) <= pt(1) && pt(1) < win(1) + win(3) && ... win(2) <= pt(2) && pt(2) < win(2) + win(4); end function [patchSeld, lineSeld, hitWindow] = clickStatus(currPt, handles) % returns empties on default patchSeld = []; lineSeld = []; hax = handles(1); hp = handles(2); win([1 3]) = get(hax,'XLim'); win(3) = win(3) - win(1); win([2 4]) = get(hax,'YLim'); win(4) = win(4) - win(2); hitWindow = inRect(win, currPt); if ~hitWindow, return, end; % how 'fat' should our edge be for us to highlight/grab it? edgeFuzzFrac = 0.0035; edgeFuzz = diff(get(hax,'XLim')) * edgeFuzzFrac; yy = get(hax,'YLim'); if currPt(2) > yy(2) || currPt(2) < yy(1), return; end; xBounds = get(hp,'XData'); if isempty(xBounds), return; end; % nothing to click xBounds = xBounds(2:3,:); patchSeld = ... find(xBounds(1,:) - edgeFuzz <= currPt(1) & ... xBounds(2,:) + edgeFuzz >= currPt(1),1); if any(abs(xBounds(1,:) - currPt(1)) <= edgeFuzz), lineSeld = 1; elseif any(abs(xBounds(2,:) - currPt(1)) <= edgeFuzz), lineSeld = 2; end end
github
BottjerLab/Acoustic_Similarity-master
constructBaselineJenny.m
.m
Acoustic_Similarity-master/code/obsoleted/constructBaselineJenny.m
3,951
utf_8
105d1cfdf33ca3dbb3d59d1efadcff2b
%removing baseline periods that overlap with events---Jenny function baselineEvents = constructBaselineJenny(events, keyName, startOffsets, stopOffsets, params) % does automatic exclusion % startOffsets is 2 x 1 vector in seconds, and is SIGNED (to go backwards % in time, go negative) % stopOffsets is similar % if we only want one of st artOfsets/stopOffsets, blank the other ([]) fs = params.fs; % allow overlap? %allowSelfOverlap = false; %allowOtherOverlap = true; % dodgy: default behavior for keyName isKeyEvent = true(numel(events),1); if ~isempty(keyName) isKeyEvent = strcmp(keyName, {events.type}); end keyStarts = [events(isKeyEvent).start]; keyStops = [events(isKeyEvent).stop]; nKey = sum(isKeyEvent); otherEvents = events(~isKeyEvent); isUsablePreEvent = false(nKey,1); isUsablePostEvent = false(nKey,1); for j = 1:length(events) isUsablePreEvent = isUsablePreEvent | (keyStarts + startOffsets(2) < end for i = 1:length(keyStarts); %go through each event of this type for j = 1:length(events); %look for overlap with any event preEventsToUse = []; if (keyStarts(i) + startOffsets(2)) < events(j).start &... (keyStarts(i)+ startOffsets(2)) > events(j).stop; %keep track of the baseline periods that do not overlap preEventsToUse(end+1) = i; end postEventsToUse = []; if (keyStops(i)+ stopOffsets(2)) < events(j).start &... (keyStops(i)+ stopOffsets(2)) > events(j).stop; postEventsToUse(end+1) = i; end end %save events for which baseline is usable correctedOwnStarts = preEventsToUse(keyStarts); correctedOwnStops = postEventsToUse(keyStops); baselinePreEvents = initEvents(0); if ~isempty(startOffsets) baselinePreEvents = eventFromTimes(... correctedOwnStarts + startOffsets(1), ... correctedOwnStarts + startOffsets(2), fs); end baselinePostEvents = initEvents(0); if ~isempty(stopOffsets) baselinePostEvents = eventFromTimes(... correctedOwnStops + stopOffsets(1), ... correctedOwnStops + stopOffsets(2), fs); end end %% Option 1:"timing", removing early %{ for i = 1:length(ownStarts); %go through each event of this type for j = 1:length(events.type); %look for overlap with any event k = 1; if (ownStarts(i) + startOffsets(2)) < events(j).start &... (ownStarts(i)+ startOffsets(2)) > events(j).stop; %keep track of the baseline periods that do not overlap preEventsToUse(k) = i; k = k + 1; end k = 1; if (ownStops(i)+ stopOffsets(2)) < events(j).start &... (ownStops(i)+ stopOffsets(2)) > events(j).stop; postEventsToUse(k) = i; k = k + 1; end end %save events for which baseline is usable correctedOwnStarts = preEventsToUse(ownStarts); correctedOwnStops = postEventsToUse(ownStops); baselinePreEvents = initEvents(0); if ~isempty(startOffsets) baselinePreEvents = eventFromTimes(... correctedOwnStarts + startOffsets(1), ... correctedOwnStarts + startOffsets(2), fs); end baselinePostEvents = initEvents(0); if ~isempty(stopOffsets) baselinePostEvents = eventFromTimes(... correctedOwnStops + stopOffsets(1), ... correctedOwnStops + stopOffsets(2), fs); end end %} %would need to run findUnion for only those baselines that have both %pre and post? %%Option 2: "length", removing later %let everything go as usual through findUniqueAreas, then remove... % pre-periods that are shorter in time than % abs(startOffsets(1)) - abs(startOffsets(2))... % or post-periods that are shorter than stopOffsets(2) - stopOffsets(1); %Are the lengths of baselines preserved in findUniqueAreas?
github
BottjerLab/Acoustic_Similarity-master
findSilence.m
.m
Acoustic_Similarity-master/code/segmentation/findSilence.m
4,173
utf_8
65b47ba2d9790e7aba6aa48812df90f6
function [silentRegions, soundRegions, spectrum] = findSilence(songStruct, region, params, varargin) % yet another segmentation method for detecting silence... % slower than stepSpectrogram but tends to be more accurate % not as accurate/slow as segmentSyllables, especially in finding boundaries % (can be tuned in the future) % in general tends to have false negatives in finding silence % (due to long smoothing) % (which is to say, marks silence as sound) % but has good false positive rate (doesn't mark sound as silence) % i.e. is more robust to find silence (properly filtered) if nargin < 3 params = defaultParams; end params = processArgs(params, varargin{:}); fs = 1/songStruct.interval; params.fs = fs; params.(params.editSpecType).fs = fs; % get waveform and spectrum data clip = getClipAndProcess(songStruct, region, params); spectrum = getMTSpectrumStats(clip, params.(params.editSpecType)); % find amplitude modulation in different power bands % modifiable parameters nPowerBands = 7; scale = 5:8:61; masterThresh = params.syllable.minPower; nScales = numel(scale); powerBandBorders = logspace(log10(params.highPassFq), log10(params.lowPassFq), ... nPowerBands + 1); thresholds = ones(nPowerBands) * masterThresh; powerPerBand = zeros(nPowerBands, numel(spectrum.times), nScales); aboveT = zeros(nPowerBands, numel(spectrum.times), nScales); cols = jet(nPowerBands); for ii = 1:nPowerBands % powerBand = band pass filtering % todo: replace with MFCC power bands if necessary includedBands = (powerBandBorders(ii) <= spectrum.freqs & spectrum.freqs < powerBandBorders(ii+1)); for jj = 1:nScales % scale = amount of smoothing that the signal undergoes (similar to % a low pass filter with large sidelobes) % note: these low passes don't do very much smoothedBandSignal = smoothSignal(sum(spectrum.psd(includedBands, :)),scale(jj)); powerPerBand(ii,:,jj) = smoothedBandSignal; aboveT(ii,:,jj) = (smoothedBandSignal > thresholds(ii)); if params.plot subplot(311); plot(spectrum.times, smoothedBandSignal - thresholds(ii), '-', 'Color', cols(ii, :)); hold on; end end end % vote is sum over all scales votePercent = sum(sum(aboveT,3),1) / (nScales * nPowerBands); % what fraction of votes are needed voteThresh = 1/(sqrt(nScales * nPowerBands)); if params.plot %&& params.verbose hold off; xlabel('time'); ylabel('power in band'); xlim([0 max(spectrum.times)]); subplot(312); plot(spectrum.times, votePercent, 'r-', ... spectrum.times, voteThresh * ones(size(spectrum.times)), 'k-'); xlabel('time (s)'); ylabel('vote %'); xlim([0 max(spectrum.times)]); subplot(313); plot((1:numel(spectrum.waveform)) / fs, spectrum.waveform, 'b-'); xlim([0 numel(spectrum.waveform) / fs]) end % detect silence based on the times that bands are above above threshold diffAT = diff(votePercent > voteThresh); ducksThresh = find(diffAT == -1); jumpsThresh = find(diffAT == 1); [soundOnsets soundOffsets] = regBounds(ducksThresh, jumpsThresh, ... numel(spectrum.times)); [silOffsets silOnsets] = regBounds(jumpsThresh, ducksThresh, ... numel(spectrum.times)); fSO = spectrum.times(1); % first sample offset soundRegions = eventFromTimes(spectrum.times(soundOnsets)' - fSO, ... spectrum.times(soundOffsets)', fs); silentRegions = eventFromTimes(spectrum.times(silOnsets)' - fSO, ... spectrum.times(silOffsets)', fs); % adjust the timestamps before we leave soundRegions = adjustTimeStamps(soundRegions, region.start, fs); silentRegions = adjustTimeStamps(silentRegions, region.start, fs); function [putStarts, putEnds] = regBounds(putStarts, putEnds, endNum) if numel(putStarts) == 0 && numel(putEnds) == 0, return; end % boundary conditions - will fix later if numel(putStarts) == numel(putEnds) + 1 putEnds = [1 putEnds]; elseif numel(putEnds) > numel(putStarts), putStarts = [putStarts endNum]; elseif numel(putEnds) == numel(putStarts) && ... putEnds(1) > putStarts(1) putEnds = [1 putEnds]; putStarts = [putStarts endNum]; end
github
BottjerLab/Acoustic_Similarity-master
plotNeuronCorrDataPairs.m
.m
Acoustic_Similarity-master/code/plotting/plotNeuronCorrDataPairs.m
27,362
utf_8
1bbbea4ea958b442a35dcf226fae963e
function plotNeuronCorrData(allNeuronCorrData, params, varargin) if nargin < 2 || isempty(params) params = defaultParams; end params = processArgs(params, varargin{:}); % plot difference between firing rates for near tutor/far from tutor % and also p-values for correlations between neurons and firing rates % this data is compiled in correlateDistanceToFiring if nargin < 1 || isempty(allNeuronCorrData) load('data/allNeuronCorrelations.mat'); end %% here we load the cluster quality % get birds and ages first sessionIDs = {allNeuronCorrData.sessionID}; birdIDs = strtok(sessionIDs, '_'); [uSessions, ~, rIdxSession] = unique(sessionIDs); % index through ages can go back to sessions uAges = getAgeOfSession(uSessions); sessionAges = zeros(size(sessionIDs)); for ii = 1:numel(uAges) sessionAges(rIdxSession == ii) = uAges(ii); end [sessionQ , allSubj] = getClusterQuality(birdIDs, sessionAges, [allNeuronCorrData.syllID]); [sessionObjQ, allObj ] = getClusterQuality(birdIDs, sessionAges, [allNeuronCorrData.syllID], true); foo = num2cell(sessionQ ); [allNeuronCorrData.clusterQ ] = foo{:}; foo = num2cell(sessionObjQ); [allNeuronCorrData.clusterObjQ] = foo{:}; foo = allSubj'; allSubj = [allSubj(:)]; foo = allObj' ; allObj = [allObj(:) ]; missingData = isnan(allSubj) | isnan(allObj); qualityFit = polyfit(allSubj(~missingData), allObj(~missingData), 1); plot(1:5, polyval(qualityFit,1:5),'r-'); hold on; %boxplot(sessionObjQ', sessionQ', 'notch', 'on'); plot(allSubj, allObj, 'k.'); [rQualCorr, pQualCorr] = corrcoef(allSubj(~missingData), allObj(~missingData)); legend(sprintf('r^2 = %0.3f, p = %0.3g', rQualCorr(2,1), pQualCorr(2,1))); xlim([0.5 5.5]) xlabel('Subjective Cluster Quality'); ylabel('Davies-Bouldin Index'); title('Subjective vs. objective cluster quality correlations'); if params.saveplot saveCurrFigure('figures\A_keeper\objSubjClusterQuality.jpg'); end %% flags isCore = [allNeuronCorrData.isCore]; isMUA = [allNeuronCorrData.isMUA]; isPlastic = [allNeuronCorrData.isPlastic]; isSignificant = [allNeuronCorrData.sigResponse]; nSylls = [allNeuronCorrData.nSylls]; %isSignificant = true(1,numel(allNeuronCorrData)); isExcited = [allNeuronCorrData.isExcited]; %% isSubjGood = [allNeuronCorrData.clusterQ] < 1.5; % < 2.5 isObjGood = [allNeuronCorrData.clusterObjQ] < 0.8; % < 1 %% % criteria for cluster inclusion % must have at least three syllables per quartile isPresel = ~isMUA & nSylls >= 40 & isObjGood; %JMA %isPresel = ~isMUA & isObjGood; %~isMUA & isObjGood %%isPresel = isSignificant; % for mostresponsive neurons in todo0410.m %isPresel = nSylls >= 12; % subplot rows / columns nR = 3; nC = 2; % measures distanceTypes = {'tutor', 'intra', 'inter', 'consensus', 'central','humanMatch'}'; distanceDescriptions = {'closest tutor', 'cluster center', 'normed center', ... 'closest tutor to cluster consensus', 'closest tutor to cluster center', 'expert-designated tutor'}; dFieldsRS = [strcat(distanceTypes, '_nearMeanRS') strcat(distanceTypes, '_farMeanRS')]; dFieldsSEM = [strcat(distanceTypes, '_nearMeanSEM') strcat(distanceTypes, '_farMeanSEM')]; eiTitle = {'Significantly inhibited single unit-syllable pairs', ... 'Significantly excited single unit-syllable pairs', ... 'All significant single unit-syllable pairs'}; xlabels = strcat({'RS for near - far to '}, distanceDescriptions); filsuff = {'inh','exc','all'}; %% %{ for hh = 1:3 % inhibited, excited, all for ii = 1:numel(distanceTypes) % six of them figure; diffTutorMeanRS = [allNeuronCorrData.(dFieldsRS{ii,1})] - [allNeuronCorrData.(dFieldsRS{ii,2})]; nearMeanRS = [allNeuronCorrData.(dFieldsRS{ii,1})]; farMeanRS = [allNeuronCorrData.(dFieldsRS{ii,2})]; nearMeanSEM = [allNeuronCorrData.(dFieldsRS{ii,1})]; farMeanSEM = [allNeuronCorrData.(dFieldsRS{ii,2})]; if hh < 3 selHereCore = isPresel & isExcited == hh-1 & isCore; selHereShell = isPresel & isExcited == hh-1 & ~isCore; coreDiffRS = diffTutorMeanRS(selHereCore); shellDiffRS = diffTutorMeanRS(selHereShell); coreSubDiffRS = diffTutorMeanRS(selHereCore & ~isPlastic); shellSubDiffRS = diffTutorMeanRS(selHereShell & ~isPlastic); corePlastDiffRS = diffTutorMeanRS(selHereCore & isPlastic); shellPlastDiffRS = diffTutorMeanRS(selHereShell & isPlastic); else coreDiffRS = diffTutorMeanRS(isPresel & isCore); shellDiffRS = diffTutorMeanRS(isPresel & ~isCore); coreSubDiffRS = diffTutorMeanRS(isPresel & isCore & ~isPlastic); shellSubDiffRS = diffTutorMeanRS(isPresel & ~isCore & ~isPlastic); corePlastDiffRS = diffTutorMeanRS(isPresel & isCore & isPlastic); shellPlastDiffRS = diffTutorMeanRS(isPresel & ~isCore & isPlastic); end pc = signrank( coreDiffRS); ps = signrank(shellDiffRS); pMannU = ranksum(coreDiffRS(~isnan(coreDiffRS)), shellDiffRS(~isnan(shellDiffRS))); fprintf(['%s-%s:\n\tsign-rank test p-value for core: %0.3f' ... ' \n\tsign-rank test p-value for shell: %0.3f',... ' \n\tMann-Whitney U test p-value for core v shell: %0.3f\n'],... eiTitle{hh},xlabels{ii},pc,ps,pMannU); % clunky way just to get the top histogram value RSdiffBins = -10:0.2:10; plotInterlaceBars(coreDiffRS, shellDiffRS, RSdiffBins); ytop = ylim * [0 1]'; % todo: plot significance on graph hold on; plotSEMBar( coreDiffRS, ytop , [0.5 0.5 0.5]); plotSEMBar( coreSubDiffRS, ytop+1, [0.5 0.5 0.5]); plotSEMBar( corePlastDiffRS, ytop+2, [0.5 0.5 0.5]); plotSEMBar( shellDiffRS, ytop+3, [ 1 0 0]); plotSEMBar( shellSubDiffRS, ytop+4, [ 1 0 0]); plotSEMBar(shellPlastDiffRS, ytop+5, [ 1 0 0]); plot([0 0], ylim, 'k--'); hold off; % redo y axis labels yt = get(gca,'YTick'); yt = [yt(yt < ytop) ytop:ytop+5]; ytl = cellfun(@(x) sprintf('%d',x),num2cell(yt),'UniformOutput',false); ytl(end-5:end) = {'Core','Core/Subsong','Core/Plastic','Shell','Shell/Subsong','Shell/Plastic'}; set(gca,'YTick',yt,'YTickLabel',ytl); % figure formatting xlabel(xlabels{ii}); ylabel('Count'); xlim([min(RSdiffBins) max(RSdiffBins)]); set(gca,'Box','off'); set(gca, 'FontSize', 14); set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); title(eiTitle{hh}); set(gcf,'Color',[1 1 1]); if params.saveplot saveCurrFigure(sprintf('figures/distanceCorrelations/RSdiffs-SUA-%s-%s.jpg', distanceTypes{ii}, filsuff{hh})); end end end %} %% JMA added this section to compare neurons with compiled cluster data for aa = 1: length(allNeuronCorrData) allNeuronCorrData(aa).intra_DistanceAll = allNeuronCorrData(aa).intra_DistanceAll';%these were in columns allNeuronCorrData(aa).inter_DistanceAll = allNeuronCorrData(aa).inter_DistanceAll'; allNeuronCorrData(aa).burstFraction = allNeuronCorrData(aa).burstFraction'; allNeuronCorrData(aa).quality = allNeuronCorrData(aa).clusterObjQ; end ccc = allNeuronCorrData(1);%trying to get unique syllable iterations to compare similarity to tutor with song stage goodness-of-fit coefficient for aaa = 2: length(allNeuronCorrData) ddd = strcmp(allNeuronCorrData(aaa).sessionID,{ccc.sessionID}); if ~any(ddd) ccc = [ccc;allNeuronCorrData(aaa)];%I know, I know, I can't pre-allocate else eee = ccc(ddd); bbb = ~ismember(allNeuronCorrData(aaa).syllID,[eee.syllID]); if bbb ccc = [ccc;allNeuronCorrData(aaa)]; end end end load('goodnessOfFitCo.mat') for aa = 1: length(ccc) tt = zeros(ccc(aa).nSylls,1);%needed to get syllable type for every syllable tt(:,1) = deal(ccc(aa).syllID); ccc(aa).syllID = tt'; for bb = 1: length(goodness.fit) sess(bb) = strcmp(ccc(aa).sessionID,goodness.sessionID(bb)); end gof = cell2mat(goodness.fit(sess)); ttt = zeros(ccc(aa).nSylls,1); ttt(:,1) = deal(gof); ccc(aa).indGoF = ttt'; end usablePairs = allNeuronCorrData(isPresel); % usableClusterSessions = {usablePairs.sessionID}; % [uUCSessions, ~, ~] = unique(usableClusterSessions); % corrByNeuron = struct([]); % for mm = 1: length(uUCSessions) % isCurrentSession = strcmp(uUCSessions(mm),{usablePairs.sessionID}); % currentSessionPairs = usablePairs(isCurrentSession); % % [neuronsHere, ~, ~] = unique([currentSessionPairs.unitNum]); % % for nn = 1: length(neuronsHere) % % isCurrentNeuron = [currentSessionPairs.unitNum] == neuronsHere(nn); % % currentNeuronPairs = currentSessionPairs(isCurrentNeuron); % % compiledNeuron.isCore = currentNeuronPairs(1).isCore; % % compiledNeuron.isMUA = currentNeuronPairs(1).isMUA; % % compiledNeuron.isPlastic = currentNeuronPairs(1).isPlastic; % % compiledNeuron.sessionID = currentNeuronPairs(1).sessionID; % % compiledNeuron.unitNum = currentNeuronPairs(1).unitNum; % % compiledNeuron.nSylls = sum([currentNeuronPairs.nSylls]); % % compiledNeuron.sigSyll = sum([currentNeuronPairs.sigResponse]); % % compiledNeuron.RSAll = horzcat([currentNeuronPairs.RSAll]); % % compiledNeuron.FRSyll = horzcat([currentNeuronPairs.FRSyll]); % % compiledNeuron.FRBase = horzcat([currentNeuronPairs.FRBase]); % % compiledNeuron.burstFraction = horzcat([currentNeuronPairs.burstFraction]); % % compiledNeuron.tutor_DistanceAll = horzcat([currentNeuronPairs.tutor_DistanceAll]); % % compiledNeuron.consensus_DistanceAll = horzcat([currentNeuronPairs.consensus_DistanceAll]); % % compiledNeuron.central_DistanceAll = horzcat([currentNeuronPairs.central_DistanceAll]); % % compiledNeuron.intra_DistanceAll = horzcat([currentNeuronPairs.intra_DistanceAll]); % % compiledNeuron.inter_DistanceAll = horzcat([currentNeuronPairs.inter_DistanceAll]); % % compiledNeuron.quality = horzcat([currentNeuronPairs.clusterObjQ]); % % compiledNeuron.syllID = horzcat([currentNeuronPairs.syllID]); % % numClassSyll = length(unique(compiledNeuron.syllID)); % % compiledNeuron.classSyll = deal(numClassSyll); % corrByNeuron = [corrByNeuron; compiledNeuron]; % % end % end % isenoughSyll = [corrByNeuron.nSylls] > 39; %want at least 10 syllables in each quartile % usableNeuron = [corrByNeuron.sigSyll] > 0 & isenoughSyll; %neuron has to respond to at least one syllable cluster (but maybe shouldn't do this) % usableNeuron = isenoughSyll; % corrByNeuron = corrByNeuron(usableNeuron); corrByNeuron = usablePairs; %correlation of distance to response strength for bb = 1: length(corrByNeuron) yDist = corrByNeuron(bb).tutor_DistanceAll'; %can try other distances xRS = corrByNeuron(bb).RSAll'; %response strength, does it make sense to use firing rate? [linfit, ~,~,~, fitStats] = regress(yDist, [ones(numel(xRS),1) xRS]); %checked with corrcoef and gives same p value %if params.plot % figure % plot(xRS, yDist, 'k.', 'HandleVisibility', 'off'); % hold on; % plot(xRS, linfit(1) + xRS * linfit(2), '--','Color',[1 0 0]); % legend(sprintf('r^2 = %0.3g, F = %0.3g, p = %0.3g\n',... % fitStats(1), fitStats(2),fitStats(3))); % xlabel('Response Strength'); ylabel('Matched distance'); %end corrByNeuron(bb).linfit = linfit; corrByNeuron(bb).fitStats = fitStats; end isCore2 = [corrByNeuron.isCore]; CorrPRS = zeros(length(corrByNeuron),1); for cc = 1: length(corrByNeuron) CorrPRS(cc) = corrByNeuron(cc).fitStats(3); end isCorrel = CorrPRS < 0.05; cSC = isCore2 & isCorrel'; cSS = ~isCore2 & isCorrel'; fprintf('Number neurons with significant correlation of RS in core %s out of %s core neurons \n', num2str(sum(cSC)), num2str(sum(isCore2))) fprintf('Number neurons with significant correlation of RS in shell %s out of %s shell neurons \n', num2str(sum(cSS)), num2str(sum(~isCore2))) %correlation of distance to burst fraction for bb = 1: length(corrByNeuron) yDist = corrByNeuron(bb).tutor_DistanceAll'; xRS = corrByNeuron(bb).burstFraction'; [linfit, ~,~,~, fitStats] = regress(yDist, [ones(numel(xRS),1) xRS]); %checked with corrcoef and gives same p value corrByNeuron(bb).linfitBF = linfit; corrByNeuron(bb).fitStatsBF = fitStats; end isCore2 = [corrByNeuron.isCore]; CorrP = zeros(length(corrByNeuron),1); for cc = 1: length(corrByNeuron) CorrP(cc) = corrByNeuron(cc).fitStatsBF(3); end isCorrel = CorrP < 0.05; cSC = isCore2 & isCorrel'; cSS = ~isCore2 & isCorrel'; fprintf('Number neurons with significant correlation of BF in core %s out of %s core neurons \n', num2str(sum(cSC)), num2str(sum(isCore2))) fprintf('Number neurons with significant correlation of BF in shell %s out of %s shell neurons \n', num2str(sum(cSS)), num2str(sum(~isCore2))) %compare population response, standardized response to top and bottom 50% %similarity to tutor song for dd = 1: length(corrByNeuron) dists = corrByNeuron(dd).tutor_DistanceAll; %tutor_DistanceAll iqDists = prctile(dists, 50); near_medianFR = corrByNeuron(dd).FRSyll(dists < iqDists); nMedian = numel(near_medianFR); far_medianFR = corrByNeuron(dd).FRSyll(dists > iqDists); fMedian = numel( far_medianFR); near_medianFRBase = corrByNeuron(dd).FRBase(dists < iqDists); far_medianFRBase = corrByNeuron(dd).FRBase(dists > iqDists); near_medianBF = corrByNeuron(dd).burstFraction(dists < iqDists); far_medianBF = corrByNeuron(dd).burstFraction(dists > iqDists); near_medianDist = corrByNeuron(dd).tutor_DistanceAll(dists < iqDists); far_medianDist = corrByNeuron(dd).tutor_DistanceAll(dists > iqDists); allDist = corrByNeuron(dd).tutor_DistanceAll; % near_quartileQual = corrByNeuron(dd).quality(dists < iqDists(1)); % far_quartileQual = corrByNeuron(dd).quality(dists > iqDists(2)); % near_quartileType = corrByNeuron(dd).syllID(dists < iqDists(1)); % far_quartileType = corrByNeuron(dd).syllID(dists > iqDists(2)); farMedian = nanmean(far_medianDist); nearMedian = nanmean(near_medianDist); meanDist = nanmean(allDist); % farQual = nanmean(far_quartileQual); % nearQual = nanmean(near_quartileQual); % farTypes = length(unique(far_quartileType)); % nearTypes = length(unique(near_quartileType)); nq_meanFR = nanmean(near_medianFR); nq_varFR = nanvar(near_medianFR); fq_meanFR = nanmean( far_medianFR); fq_varFR = nanvar( far_medianFR); nq_meanBF = nanmean(near_medianBF); fq_meanBF = nanmean(far_medianBF); nq_CV = nanstd(near_medianFR)/nq_meanFR; fq_CV = nanstd(far_medianFR)/fq_meanFR; nq_meanFRBase = nanmean(near_medianFRBase); nq_varFRBase = nanvar(near_medianFRBase); fq_meanFRBase = nanmean( far_medianFRBase); fq_varFRBase = nanvar( far_medianFRBase); [~, pVal, ~, tValStruct] = ttest2(near_medianFR- near_medianFRBase, far_medianFR- far_medianFRBase); tVal = tValStruct.tstat; fcovar = nancov(far_medianFR,far_medianFRBase);if numel(fcovar) > 1, fcovar = fcovar(2,1); end; ncovar = nancov(near_medianFR,near_medianFRBase);if numel(ncovar) > 1, ncovar = ncovar(2,1); end; farZDenom = sqrt(fq_varFR + fq_varFRBase - 2*fcovar); nearZDenom = sqrt(nq_varFR + nq_varFRBase - 2*ncovar); farZ = ((fq_meanFR - fq_meanFRBase)* sqrt(fMedian))/farZDenom; nearZ = ((nq_meanFR - nq_meanFRBase)* sqrt(nMedian))/nearZDenom; corrByNeuron(dd).medianPValue = pVal; corrByNeuron(dd).farZ = farZ; corrByNeuron(dd).nearZ = nearZ; corrByNeuron(dd).farCV = fq_CV; corrByNeuron(dd).nearCV = nq_CV; corrByNeuron(dd).nearBF = nq_meanBF; corrByNeuron(dd).farBF = fq_meanBF; corrByNeuron(dd).farQuart = farMedian; corrByNeuron(dd).nearQuart = nearMedian; corrByNeuron(dd).meanDist = meanDist; corrByNeuron(dd).farRS = (fq_meanFR - fq_meanFRBase); corrByNeuron(dd).nearRS = (nq_meanFR - nq_meanFRBase); % corrByNeuron(dd).farQual = farQual; % corrByNeuron(dd).nearQual = nearQual; % corrByNeuron(dd).farTypes = farTypes; % corrByNeuron(dd).nearTypes = nearTypes; % corrByNeuron(dd).farTypeID = {unique(far_quartileType)}; % corrByNeuron(dd).nearTypeID = {unique(near_quartileType)}; end isQS = [corrByNeuron.medianPValue] < 0.05; SQC = isCore2 & isQS; SQS = ~isCore2 & isQS; fprintf('Number neurons with significant difference in RS to near vs far in core %s out of %s core neurons \n', num2str(sum(SQC)), num2str(sum(isCore2))) fprintf('Number neurons with significant difference in RS to near vs far in shell %s out of %s shell neurons \n', num2str(sum(SQS)), num2str(sum(~isCore2))) meanFarZC = nanmean([corrByNeuron(isCore2).farZ]); meanFarZS = nanmean([corrByNeuron(~isCore2).farZ]); SEMFarC = nanstd([corrByNeuron(isCore2).farZ])/sqrt(length(corrByNeuron(isCore2))); SEMFarS = nanstd([corrByNeuron(~isCore2).farZ])/sqrt(length(corrByNeuron(~isCore2))); meanNearZC = nanmean([corrByNeuron(isCore2).nearZ]); meanNearZS = nanmean([corrByNeuron(~isCore2).nearZ]); SEMNearC = nanstd([corrByNeuron(isCore2).nearZ])/sqrt(length(corrByNeuron(isCore2))); SEMFarS = nanstd([corrByNeuron(~isCore2).nearZ])/sqrt(length(corrByNeuron(~isCore2))); % normalized RS values--not using this part dNormedRSFields = strcat(distanceTypes, '_dRSnorm'); for hh = 1:3 % inhibited, excited, all for ii = 1:numel(distanceTypes) % six of them figure; dRSNormed = [allNeuronCorrData.(dNormedRSFields{ii})]; if hh < 3 coreDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & isCore); shellDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & ~isCore); coreSubDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & isCore & ~isPlastic); shellSubDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & ~isCore & ~isPlastic); corePlastDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & isCore & isPlastic); shellPlastDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & ~isCore & isPlastic); else coreDiffRSNorm = dRSNormed(isPresel & isCore); shellDiffRSNorm = dRSNormed(isPresel & ~isCore); coreSubDiffRSNorm = dRSNormed(isPresel & isCore & ~isPlastic); shellSubDiffRSNorm = dRSNormed(isPresel & ~isCore & ~isPlastic); corePlastDiffRSNorm = dRSNormed(isPresel & isCore & isPlastic); shellPlastDiffRSNorm = dRSNormed(isPresel & ~isCore & isPlastic); end fprintf('%s-normed %s: ', eiTitle{hh},xlabels{ii}); if ~(all(isnan( coreSubDiffRSNorm)) || ... all(isnan( corePlastDiffRSNorm)) || ... all(isnan( shellSubDiffRSNorm)) || ... all(isnan(shellPlastDiffRSNorm))) % significance tests: two-way anova, permuted % this function is not consistent with matlab's anovan, so it % won't be used until we can see why the inconsistency's there %[stats, df, pvals] = statcond(... % {noNaN( coreSubDiffRSNorm), noNaN( corePlastDiffRSNorm); ... % noNaN(shellSubDiffRSNorm), noNaN(shellPlastDiffRSNorm)}, ... %'mode','param'); % test against anova xx = [coreSubDiffRSNorm corePlastDiffRSNorm shellSubDiffRSNorm shellPlastDiffRSNorm]'; grps = [zeros(size(coreSubDiffRSNorm)) zeros(size(corePlastDiffRSNorm)) ... ones(size(shellSubDiffRSNorm)) ones(size(shellPlastDiffRSNorm)); ... zeros(size(coreSubDiffRSNorm)) ones(size(corePlastDiffRSNorm)) ... zeros(size(shellSubDiffRSNorm)) ones(size(shellPlastDiffRSNorm))]'; if isreal(xx) %JMA added [pAnova, tAnova] = anovan(xx,grps,'model','interaction','display', 'off'); fprintf(['\n\tANOVA (fixed model), 2-way: effect of core/shell, p = %0.2f, '... 'effect of subsong/plastic, p = %0.2f, interaction, p = %0.2f'], ... pAnova(1), pAnova(2), pAnova(3)) else fprintf('Skipping two-way permutation ANOVA'); end end % significance tests: post-hoc, core vs shell if ~isempty(coreDiffRSNorm) && ~isempty(shellDiffRSNorm) pc = signrank( coreDiffRSNorm); ps = signrank(shellDiffRSNorm); pMannU = ranksum(coreDiffRSNorm(~isnan(coreDiffRSNorm)), shellDiffRSNorm(~isnan(shellDiffRSNorm))); % no subsong/plastic significance tests fprintf(['\n\tsign-rank test p-value for core: %0.3f' ... '\n\tsign-rank test p-value for shell: %0.3f',... '\n\tMann-Whitney U test p-value for core v shell: %0.3f\n'],... pc,ps,pMannU); end % set bins for histogram RSdiffBins = -10:0.5:10; plotInterlaceBars(coreDiffRSNorm, shellDiffRSNorm, RSdiffBins); ytop = ylim * [0 1]'; % todo: plot significance on graph hold on; plotSEMBar( coreDiffRSNorm, ytop , [0.5 0.5 0.5]); plotSEMBar( shellDiffRSNorm, ytop+1, [ 1 0 0]); plotSEMBar( coreSubDiffRSNorm, ytop+2, [0.5 0.5 0.5]); plotSEMBar( shellSubDiffRSNorm, ytop+3, [ 1 0 0]); plotSEMBar( corePlastDiffRSNorm, ytop+4, [0.5 0.5 0.5]); plotSEMBar(shellPlastDiffRSNorm, ytop+5, [ 1 0 0]); plot([0 0], ylim, 'k--'); hold off; % redo y axis labels yt = get(gca,'YTick'); yt = [yt(yt < ytop) ytop:ytop+5]; ytl = cellfun(@(x) sprintf('%d',x),num2cell(yt),'UniformOutput',false); ytl(end-5:end) = {'Core','Shell','Core/Subsong','Shell/Subsong','Core/Plastic','Shell/Plastic'}; set(gca,'YTick',yt,'YTickLabel',ytl); % figure formatting xlabel(['normalized ' xlabels{ii}]); ylabel('Count'); legend(sprintf('CORE: n = %d', numel( coreDiffRSNorm(~isnan( coreDiffRSNorm)))),... sprintf('SHELL: n = %d', numel(shellDiffRSNorm(~isnan(shellDiffRSNorm))))); xlim([min(RSdiffBins) max(RSdiffBins)]); set(gca,'Box','off'); set(gca, 'FontSize', 14); set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); title(sprintf('%s, core/shell diff p = %0.2g, core from zero p = %0.2g, shell from zero p = %0.2g', eiTitle{hh}, pMannU, pc, ps)); set(gcf,'Color',[1 1 1]); %mean(coreDiffRSNorm) %mean(shellDiffRSNorm) %pause; if params.saveplot imFile = sprintf('figures/paper/distanceCorrelations-subjectiveScoreFilter/normedRSdiffs-SUA-%s-%s.pdf', distanceTypes{ii}, filsuff{hh}); fprintf('Writing image to %s', imFile); scrsz = get(0,'ScreenSize'); set(gcf, 'Position', [1 1 scrsz(3) scrsz(4)]); export_fig(imFile); % saveCurrFigure(sprintf('figures/A_keeper/mostResponsive/normedRSdiffs-SUA-%s-%s.jpg', distanceTypes{ii}, filsuff{hh})); end end end %{ fprintf('\n\np-values of FR correlation to distance types'); pFields = strcat(distanceTypes, 'Distance_p'); R2Fields = strcat(distanceTypes, 'DistanceR2'); xlabels = strcat({'Linear trend p-values of FR to '}, distanceDescriptions); for hh = 1:3 % inhibited, excited, all figure; for ii = 1:numel(distanceTypes) subplot(nR,nC,ii) corrPVals = [allNeuronCorrData.(pFields{ii})]; corrR2Vals = [allNeuronCorrData.(R2Fields{ii})]; if hh < 3 coreCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore); shellCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore); % get % variance explained [ coreR2M, coreR2SEM] = meanSEM(corrR2Vals(isPresel & isExcited == hh-1 & isCore)); [shellR2M, shellR2SEM] = meanSEM(corrR2Vals(isPresel & isExcited == hh-1 & ~isCore)); %coreSubCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore & ~isPlastic); %shellSubCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore & ~isPlastic); %corePlastCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore & isPlastic); %shellPlastCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore & isPlastic); else coreCPVs = corrPVals(isPresel & isCore); shellCPVs = corrPVals(isPresel & ~isCore); [ coreR2M, coreR2SEM] = meanSEM(corrR2Vals(isPresel & isCore)); [shellR2M, shellR2SEM] = meanSEM(corrR2Vals(isPresel & ~isCore)); %coreSubCPVs = corrPVals(isPresel & isCore & ~isPlastic); %shellSubCPVs = corrPVals(isPresel & ~isCore & ~isPlastic); %corePlastCPVs = corrPVals(isPresel & isCore & isPlastic); %shellPlastCPVs = corrPVals(isPresel & ~isCore & isPlastic); end % test the difference between core and shell pMannU = ranksum(coreCPVs(~isnan(coreCPVs)), shellCPVs(~isnan(shellCPVs))); fprintf('%s - %s: Mann-Whitney U p-value for core v shell: %0.3f\n',... eiTitle{hh}, xlabels{ii},pMannU); fprintf(['\tCore variance explained: %0.2f +/- %0.2f, '... 'shell variance explained: %0.2f +/- %0.2f\n'], ... coreR2M, coreR2SEM, shellR2M, shellR2SEM); pBins = logspace(-3,0,30); plotInterlaceBars(coreCPVs, shellCPVs, pBins); legend(sprintf('CORE: n = %d', numel( coreCPVs(~isnan( coreCPVs)))),... sprintf('SHELL: n = %d', numel(shellCPVs(~isnan(shellCPVs))))); xlabel(xlabels{ii}); ylabel('Count'); xlim([0 1]) % figure formatting set(gca, 'XTick', [0.05 0.1 0.2 0.4 0.6 0.8]); set(gca, 'Box', 'off'); set(gca, 'FontSize', 12); % xticklabel_rotate([],45); % this messes up the figure subplots set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); % todo: plot the significance markers ytop = ylim * [0 1]'; ylim([0 ytop+2]); hold on; plotSEMBar( coreCPVs, ytop-0.2, [0.5 0.5 0.5]); plotSEMBar(shellCPVs, ytop-0.1, [1 0 0]); hold off; end subplot(nR,nC,1); title(eiTitle{hh}); set(gcf,'Color',[1 1 1]); if params.saveplot saveCurrFigure(sprintf('figures/distanceCorrelations/neuronDistanceCorr-SUA-%s.jpg', filsuff{hh})); end end %} end function [m, v] = meanSEM(set1) m = nanmean(set1); if numel(set1) >= 2 v = nanstd(set1 )/sqrt(numel(set1)-1); else v = 0; end end % plot the error bars w/ SEM on top function plotSEMBar(set, y, col) [m,v] = meanSEM(set); plotHorzErrorBar(m,y,v,col); end function x = noNaN(x) x(isnan(x)) = []; end
github
BottjerLab/Acoustic_Similarity-master
plotNeuronCorrDataVert.m
.m
Acoustic_Similarity-master/code/plotting/plotNeuronCorrDataVert.m
9,117
utf_8
36d30b062aeb58c51826251d08b27b1b
function plotNeuronCorrDataVert(params, varargin) if nargin < 1 || isempty(params) params = defaultParams; end params = processArgs(params, varargin{:}); % plot excited difference between firing rates for near tutor/far from tutor % and also p-values for correlations between neurons and firing rates allNeuronCorrData = []; load('data/allNeuronCorrelations.mat'); %% flags isCore = [allNeuronCorrData.isCore]; isMUA = [allNeuronCorrData.isMUA]; isPlastic = [allNeuronCorrData.isPlastic]; isSignificant = [allNeuronCorrData.sigResponse]; isExcited = [allNeuronCorrData.isExcited]; isPresel = isSignificant & ~isMUA; RSdiffBins = -10:0.2:10; % subplot rows / columns nR = 3; nC = 2; % measures distanceTypes = {'tutor', 'intra', 'inter', 'consensus', 'central','humanMatch'}'; distanceDescriptions = {'closest tutor', 'cluster center', 'normed center', ... 'closest tutor to cluster consensus', 'closest tutor to cluster center', 'expert-designated tutor'}; dFields = [strcat(distanceTypes, '_nearMeanRS') strcat(distanceTypes, '_farMeanRS')]; eiTitle = {'Significantly inhibited single unit-syllable pairs', ... 'Significantly excited single unit-syllable pairs', ... 'All significant single unit-syllable pairs'}; xlabels = strcat({'RS for near - far to '}, distanceDescriptions); filsuff = {'inh','exc','all'}; %% ycommlims = [-10 10]; for hh = 1:3 % inhibited, excited, all for ii = 1:numel(distanceTypes) % six of them diffTutorMeanRS = [allNeuronCorrData.(dFields{ii,1})] - [allNeuronCorrData.(dFields{ii,2})]; if hh < 3 coreDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & isCore); shellDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & ~isCore); coreSubDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & isCore & ~isPlastic); shellSubDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & ~isCore & ~isPlastic); corePlastDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & isCore & isPlastic); shellPlastDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & ~isCore & isPlastic); else coreDiffRS = diffTutorMeanRS(isPresel & isCore); shellDiffRS = diffTutorMeanRS(isPresel & ~isCore); coreSubDiffRS = diffTutorMeanRS(isPresel & isCore & ~isPlastic); shellSubDiffRS = diffTutorMeanRS(isPresel & ~isCore & ~isPlastic); corePlastDiffRS = diffTutorMeanRS(isPresel & isCore & isPlastic); shellPlastDiffRS = diffTutorMeanRS(isPresel & ~isCore & isPlastic); end pc = signrank( coreDiffRS); ps = signrank(shellDiffRS); pMannU = ranksum(coreDiffRS(~isnan(coreDiffRS)), shellDiffRS(~isnan(shellDiffRS))); fprintf(['%s-%s:\n\tsign-rank test p-value for core: %0.3f' ... ' \n\tsign-rank test p-value for shell: %0.3f',... ' \n\tMann-Whitney U test p-value for core v shell: %0.3f\n'],... eiTitle{hh},xlabels{ii},pc,ps,pMannU); figure % plot the core/shell contrast for single units for this % RS contrast subplot(1,2,1); plotInterlaceBarsVert(coreDiffRS, shellDiffRS, RSdiffBins, pMannU < 0.05); legend(sprintf('CORE: n = %d', numel( coreDiffRS(~isnan( coreDiffRS)))),... sprintf('SHELL: n = %d', numel(shellDiffRS(~isnan(shellDiffRS))))) xlabel('Count'); ylabel(xlabels{ii}); ylim(ycommlims); set(gca,'Box','off'); set(gca, 'FontSize', 14); set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); title(eiTitle{hh}); set(gcf,'Color',[1 1 1]); subplot(1,2,2) % plot the core/core subsong/core plastic// % shell/shell subsong/shell plastic individual bars [ coreMean, coreVar] = meanVar( coreDiffRS); [ coreSubMean, coreSubVar] = meanVar( coreSubDiffRS); [ corePlastMean, corePlastVar] = meanVar(corePlastDiffRS); [ shellMean, shellVar] = meanVar( shellDiffRS); [ shellSubMean, shellSubVar] = meanVar( shellSubDiffRS); [shellPlastMean, shellPlastVar] = meanVar(shellPlastDiffRS); xlim([0.5 6.5]) hold on; plotHorzErrorBarVert(1, coreMean, coreVar, [0.5 0.5 0.5]); plotHorzErrorBarVert(2, coreSubMean, coreSubVar, [0.5 0.5 0.5]); plotHorzErrorBarVert(3, corePlastMean, corePlastVar, [0.5 0.5 0.5]); plotHorzErrorBarVert(4, shellMean, shellVar, [0.5 0.5 0.5]); plotHorzErrorBarVert(5, shellSubMean, shellSubVar, [0.5 0.5 0.5]); plotHorzErrorBarVert(6, shellPlastMean, shellPlastVar, [0.5 0.5 0.5]); ylim(ycommlims); set(gca,'Box','off', 'XTick', 1:6,... 'XTickLabel',{'Core', 'Core/Subsong','Core/Plastic',... 'Shell','Shell/Subsong','Shell/Plastic'}); xticklabel_rotate([],45, [], 'FontSize', 14); hold on; keyboard end if params.saveplot saveCurrFigure(sprintf('figures/distanceCorrelations/RSdiffs-SUA-%s.jpg', filsuff{hh})); end end %{ pFields = strcat(distanceTypes, 'Distance_p'); xlabels = strcat({'Linear trend p-values of FR to '}, distanceDescriptions); for hh = 1:3 % inhibited, excited, all figure(hh+3); for ii = 1:numel(distanceTypes) subplot(nR,nC,ii) corrPVals = [allNeuronCorrData.(pFields{ii})]; if hh < 3 coreCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore); shellCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore); else coreCPVs = corrPVals(isPresel & isCore); shellCPVs = corrPVals(isPresel & ~isCore); end pMannU = ranksum(coreCPVs(~isnan(coreCPVs)), shellCPVs(~isnan(shellCPVs))); fprintf('%s - %s: Mann-Whitney U p-value for core v shell: %0.3f\n',... eiTitle{hh}, xlabels{ii},pMannU); pBins = logspace(-3,0,30); plotInterlaceBarsVert(coreCPVs, shellCPVs, pBins, pMannU < 0.05); legend(sprintf('CORE: n = %d', numel( coreCPVs(~isnan( coreCPVs)))),... sprintf('SHELL: n = %d', numel(shellCPVs(~isnan(shellCPVs))))); xlabel(xlabels{ii}); ylabel('Count'); xlim([0 1]) set(gca, 'XTick', [0.01 0.05 0.1 0.2 0.4 0.6 0.8]); set(gca, 'Box', 'off'); set(gca, 'FontSize', 14); set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); end subplot(nR,nC,1); title(eiTitle{hh}); set(gcf,'Color',[1 1 1]); if params.saveplot saveCurrFigure(sprintf('figures/distanceCorrelations/neuronDistanceCorr-SUA-%s.jpg', filsuff{hh})); end end %} end function [m, v] = meanVar(set1) m = nanmean(set1); v = nanstd(set1 )/sqrt(numel(set1)-1); end function plotInterlaceBarsVert(setCore, setShell, bins, sigLevel) % core plotted in gray, shell plotted in red % run mann-whitney u test [p,h] = ranksum(setCore, setShell); binTol = 1e-5; hCore = histc(setCore , bins); hShell = histc(setShell, bins); [m1 sem1] = meanVar(setCore ); [m2 sem2] = meanVar(setShell); if all(diff(bins) - (bins(2) - bins(1)) < binTol) bw = bins(2) - bins(1); barh(bins, hCore, 0.5, 'FaceColor', [0.5 0.5 0.5]); hold on; barh(bins+bw/2, hShell, 0.5, 'r'); else bw = diff(bins); bw = [bins(1)/2 bw bw(end)]; % make visible legend groups ghCore = hggroup; ghShell = hggroup; set(get(get(ghCore , 'Annotation'),'LegendInformation'), 'IconDisplayStyle','on'); set(get(get(ghShell, 'Annotation'),'LegendInformation'), 'IconDisplayStyle','on'); for ii = 1:numel(bins) % draw histogram bin by bin % core bin yd = bins(ii) - bw(ii)/2; yu = bins(ii); xl = 0; xr = hCore(ii); patch([xl xr; xr xr; xl xl], [yd yd; yd yu; yu yu], [0.5 0.5 0.5],... 'EdgeColor','none', 'Parent', ghCore); hold on; % shell bins yd = bins(ii); yu = bins(ii) + bw(ii+1)/2; xl = 0; xr = hShell(ii); patch([xl xr; xr xr; xl xl], [yd yd; yd yu; yu yu], [1 0 0],... 'EdgeColor','none', 'Parent', ghShell); end end xlims = xlim; right = xlims(2) + 2; xlim([0 right]); plotHorzErrorBarVert(right - 0.8, m1, sem1, [0.5 0.5 0.5]); hold on; plotHorzErrorBarVert(right - 1.2, m2, sem2, [1 0 0]); if sigLevel > 0 plot(right-1.0, mean([m1 m2]), 'k*','MarkerSize',6); end hold off; end function plotHorzErrorBarVert(x, y, yerr, col) xw = 0.02*diff(xlim); % the connecting line, and the bottom and top end lines xx = [x x NaN x-xw x+xw NaN x-xw x+xw ]; yy = [y-yerr y+yerr NaN y-yerr y-yerr NaN y+yerr y+yerr]; plot(xx,yy, '-','Color', col, 'LineWidth', 1.5); end
github
BottjerLab/Acoustic_Similarity-master
plotPSTHOld.m
.m
Acoustic_Similarity-master/code/plotting/plotPSTHOld.m
9,698
utf_8
5ec4c7c774dbbb5c775903bcb0904f2d
function eventSpikeTimes = plotPSTHOld(events, spikeTimes, subEvents, labelsOfInterest, prePostParams) % function plotPSTH(events, spikeTimes) plot time-warped rasters/PSTH % TODO: revise/refactor this - too specific % % This function plots the raster and PSTH for each event. Spike times % should be input uncorrected, that is, raw times with respect to the same % timeframe as that of the events. % % plotPSTH(events, spikeTimes, subEvents) plots the subEvents as gray % areas. Tip: Use events as an expanded version of subEvents to plot a PSTH % with baseline. % % plotPSTH(events, spikeTimes, subEvents, labelsOfInterest) plots a separate % raster/PSTH with time warping for each event of type label of interest. Times are % warped so that events of each label are warped. % % labelsOfInterest is a cell array of strings for the syllables that should % be aligned. everything will be time warped to those syllables. (These % should be inorder) % % spikeTimes is expected to be a column vector of spike times. % % if warping is requested (by adding labels) if nargin < 3 subEvents = initEvents; end if nargin < 4 labelsOfInterest = {}; elseif ~iscell(labelsOfInterest) labelsOfInterest = {labelsOfInterest}; end % find which subevents belong to which events % note: if the events and subevents are in one to one correspondence, (i.e. % one is the pre/post rolled version of another, then the parentage is % probably just one-to-one if numel(events) == numel(subEvents) parentage = 1:numel(subEvents); for ii = 1:numel(subEvents) eventsInContext(ii) = adjustTimeStamps(subEvents(ii), ... -events(ii).start); end else if nargin < 5 [parentage, eventsInContext] = findParent(events,subEvents); else %nargin == 5 parentage = findParent(events,subEvents); events = addPrePost(events, prePostParams); % take out orphan events :[ subEvents(isnan(parentage)) = []; parentage(isnan(parentage)) = []; for ii = 1:numel(subEvents) eventsInContext(ii) = adjustTimeStamps(subEvents(ii), ... -events(parentage(ii)).start); end end end % take out orphan events :[ subEvents(isnan(parentage)) = []; eventsInContext(isnan(parentage)) = []; parentage(isnan(parentage)) = []; % equalize outside events so that spikes are evenly counted maxEvLength = max([events.stop] - [events.start]); % now extend/alter the events so that they all have the same postroll / % preroll % if ~isempty(events) % num2cell(maxEvLength + [events.start]); [events.stop] = ans{:}; % [events.length] = deal(maxEvLength); % end [counts, eventSpikeTimes] = countSpikes(events, spikeTimes,'onset'); syllableLabels = {subEvents.type}; syllableLengths = [subEvents.stop] - [subEvents.start]; [uLabels, foo, rLabelIdx] = unique(syllableLabels); nAlign = numel(labelsOfInterest); rAlignIdx = NaN(size(rLabelIdx)); % should we warp? (according to whether or not user gave syllables list) doWarping = (nargin >= 4); if doWarping % set index of event types according to the align list for ii = 1:nAlign labelsIndex = find(strcmp(uLabels,labelsOfInterest{ii})); if ~isempty(labelsIndex) rAlignIdx(rLabelIdx == labelsIndex) = ii; end end % get the average onset and length of each syllable avgEnds = zeros(1,nAlign); avgStarts = zeros(1,nAlign); for ii = 1:nAlign % get average length isThisLabel = (rAlignIdx == ii); avgEnds(ii) = mean([eventsInContext(isThisLabel).stop]); avgStarts(ii) = mean([eventsInContext(isThisLabel).start]); end % repair cases where average events overlap for some strange reason % (needs to be more reasonable) if any(avgEnds(1:end-1) > avgStarts(2:end)) warning('distorted average event profile, repairing...'); defaultGap = 0.005; overlaps = find(avgEnds(1:end-1) > avgStarts(2:end)); for ll = 1:numel(overlaps) gapJump = avgEnds(ll) - avgStarts(ll+1) + defaultGap; avgEnds((ll+1):end) = avgEnds((ll+1):end) + gapJump; avgStarts((ll+1):end) = avgStarts((ll+1):end) + gapJump; end end avgLengths = avgEnds - avgStarts; warpedEventsInContext = eventsInContext; for ii = 1:numel(events) isChild = (parentage == ii); childEvs = eventsInContext(isChild); controlPoints = NaN(2*nAlign, 2); % first column is sample, second is standard; controlSet = false(1,2*nAlign); for jj = 1:nAlign % NB: in case of multiply labeled syllables, just pick the first % one for alignment purposes matchAlign = find(strcmp({childEvs.type},labelsOfInterest{jj}),1); if ~isempty(matchAlign) controlPoints(2*jj-1:2*jj,:) = ... [childEvs(matchAlign).start avgStarts(jj); ... childEvs(matchAlign).stop avgStarts(jj) + avgLengths(jj)]; controlSet(2*jj-1) = true; controlSet(2*jj) = true; end end controlPoints(~controlSet,:) = []; % get rid of nan points % now use control points to linearly interpolate times adjEventSpikeTimes{ii} = interpLinearPoints(eventSpikeTimes{ii},... controlPoints(:,2), controlPoints(:,1)); % for plotting purposes: warp event boundaries themselves warpedStarts = interpLinearPoints([childEvs.start],... controlPoints(:,2), controlPoints(:,1)); warpedStops = interpLinearPoints([childEvs.stop],... controlPoints(:,2), controlPoints(:,1)); foo = num2cell(warpedStarts); [warpedEventsInContext(isChild).start] = foo{:}; foo = num2cell(warpedStops); [warpedEventsInContext(isChild).stop] = foo{:}; end end % prepare the bins - all important binning parameter binSize = 1e-3; % in seconds % concatenate the context spiketimes if doWarping eventSpikeTimes = adjEventSpikeTimes; end % these values are needed by both plotting subroutines xcoords = vertcat(eventSpikeTimes{:}); maxTime = max(max(xcoords), maxEvLength); % plot raster subplot(3,1,1:2) plotRasterInner; title(sprintf('Raster for song')); % plot average PSTH subplot(3,1,3) title(sprintf('PSTH')); plotPeriHist % for title positioning subplot(3,1,1:2) %%%%%%%%%%%%%%%%%%%%%%%% plotting functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plotRasterInner plotColors = true; % this code tells us how to sort out the y-coordinates so that % each 'spike' lands on the correct row ycoords = []; for ii = 1:numel(counts) ycoords = [ycoords; ii * ones(counts(ii), 1)]; end % actually plot the spikes plot(xcoords, ycoords, 'ks','MarkerSize',2,'MarkerFaceColor','k'); xlim([0 maxTime]); ylim([0.5 numel(events) + 0.5]) % optional: plot gray/colored subEvent backgrounds behind for kk = 1:numel(events) %isKthChild = (parentage == kk); % subEvs = eventsInContext(isKthChild); % plot all gray/colored isKthChild = isWithinEvent(subEvents, events(kk)); subEvs = adjustTimeStamps(subEvents(isKthChild), -events(kk).start); if doWarping subEvs = warpedEventsInContext(isKthChild); end % assign the new colors only to the labels that correspond to alignment ones if plotColors typeColors = autumn(nAlign); % color assignment for each label evTypes = rAlignIdx(isKthChild); markColors = 0.5*ones(numel(subEvs),3); markColors(~isnan(evTypes),:) = typeColors(evTypes(~isnan(evTypes)),:); else markColors = [0.5 0.5 0.5]; end plotAreaMarks(subEvs, markColors, false, [-0.5 0.5] + kk); end end function plotPeriHist % counts per bin spikesPerBin = histc(xcoords, 0:binSize:maxTime); spikeRate = spikesPerBin / (binSize * numel(events)); % smooth bins with gaussian curve: tt = 0:binSize:maxTime; smoothedSpikeCount = zeros(size(tt)); smoothWidth = 4e-3; for ii = 1:numel(tt) smoothedSpikeCount(ii) = 1/sqrt(2*pi) * sum(exp(-((xcoords-tt(ii))/smoothWidth).^2)); end smoothedRate = smoothedSpikeCount / (binSize * numel(events)); % plot the raw PSTH %bar(0:binSize:maxTime, spikeRate, 'histc'); %hold on % plot the smoothed stuff plot(tt,smoothedRate, 'r-'); xlim([0 maxTime]); xlabel('Time(s)'); ylabel('Mean firing rate (Hz)'); %hold off; end end function yy = interpLinearPoints(xx,y1,x1) % interpolate linearly between each pair of points & interpolate, without % warping before and after the control points assert(numel(x1) == numel(y1)) if numel(x1) == 0, yy = xx; return; end; [x1, idxs] = sort(x1); y1 = y1(idxs); intervalPtr = 1; yy = zeros(size(xx)); for kk = 1:numel(xx) intervalPtr = find(xx(kk) <= x1,1); if isempty(intervalPtr) yy(kk) = xx(kk) - x1(end) + y1(end); % no warping after last control point elseif intervalPtr == 1 yy(kk) = xx(kk) - x1(1) + y1(1); % no warping before first control point else yy(kk) = interp1(x1(intervalPtr-1:intervalPtr),... y1(intervalPtr-1:intervalPtr),xx(kk)); end end end
github
BottjerLab/Acoustic_Similarity-master
plotAllFigures.m
.m
Acoustic_Similarity-master/code/plotting/plotAllFigures.m
13,002
utf_8
f8ebba7b55bed1fb7bd5eaa079f21fb7
function [hax, optGraphs, hfig] = plotAllFigures(spec, regions, params, varargin) % PLOTALLFIGURES main plotting function % plotAllFigures(spec) plots the waveform in parallel with audio features % handling bad arguments % (1) empty spectrogram if isempty(spec) hax = 0; optGraphs = params.optGraphs; hfig = 0; return; end % returns axis handles if nargin < 2, regions = []; end; if nargin < 3 || isempty(params), params = defaultParams; end; % plot only the graphs that you want and that have information provided by % the spectrum data structure params = processArgs(params, varargin{:}); optGraphs = params.optGraphs; optGraphs = optGraphs(isfield(spec, optGraphs) | strcmp('spectrogram',optGraphs) | ... strcmp('fracDiffPower',optGraphs)); % find the number of plots nPlots = numel(optGraphs); hax = zeros(1,nPlots); % labels for events structure toggleLabels = true; cP = 0; for ii = 1:nPlots % plot in next window cP = cP + 1; hax(ii) = subplot(nPlots,1,cP); switch(optGraphs{ii}) case 'spectrogram' plotSpectrogram(spec); % if isfield(spec,'fundamentalFreq') % hold on; plotPitch('fundamentalFreq','r-'); hold off; % end; % if isfield(spec,'centerFreq') % hold on; plotPitch('centerFreq','y-'); hold off; % end; for ii = 1:numel(regions), regionsMark(ii).start = regions(ii).start * numel(spec.times) / max(spec.times); regionsMark(ii).stop = regions(ii).stop * numel(spec.times) / max(spec.times); end %plotMarks(regions); case 'deriv' % if any(strcmp(optGraphs,'spectrogram')) % freezeColors(hh); %seems not to work in 2011b =/ % end % todo: it would be a very nice detail to change contrast based % on the scroll wheel, but that would mean carrying large data % amounts in the userData memory plotDerivGram(spec,params); %{ if isfield(spec,'fundamentalFreq') hold on; plotPitch('fundamentalFreq','r-.', 'LineWidth',0.5); hold off; end; if isfield(spec,'centerFreq') hold on; plotPitch('centerFreq','y-.', 'LineWidth',0.5); hold off; end; %} switch params.showDgramRegionStyle case 'lines' % non-fancy non-interactive method plotMarks(regions); plotLabels; case 'fancy' % fancy interactive method, slows down interface some and set(gcf,'Renderer','OpenGL'); plotAreaMarks(regions, [0 0.8 0.8 0.15]); % requires openGL plotLabels; % note: have to use opengl software to render, which is % slower end case 'totalPower' plotRMS; plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'fracDiffPower' plotFracDiffPower; plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'wienerEntropy' plotEntropy; plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'FM' plotFM; plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'AM' plotAM; plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'rawAM' plotRawAM; plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'pitchGoodness' plotPitchGoodness; plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'aperiodicity' hold off; plotFracPeriodicPower; plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'waveform' if ~isfield(params,'fs') error('plotAllFigures:undefined','sampling rate not defined, pass parameters'); end; hline = plotWaveform(spec.waveform,params.fs); % magic user interface happens here set(hline,'UserData',params.fs); % give playback clue xlim([min(spec.times) max(spec.times)]); hp = plotAreaMarks(regions,[],params.showLabels && toggleLabels); % magic playback UI control happens here set(gcf,'WindowButtonDownFcn',{@buttonDownFcn, [hax(ii) hp]}); toggleLabels = false; case 'centerFreq' hold off; plotPitch('centerFreq'); plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'fundamentalFreq' hold off; plotPitch('fundamentalFreq'); title('Fundamental frequency'); plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'mTD' hold off; plotPartialDerivs; plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; case 'mfcc' hold off; plotMFCC; %plotAreaMarks(regions,[],params.showLabels && toggleLabels); toggleLabels = false; otherwise error('plotAllFigures:UnspecifiedPlotting','Don''t know how to plot %s', optGraphs{ii}); end end subplot(nPlots,1,1); % for correct title positioning % allow for linked scanning/zooming on segments set(gcf,'UserData', struct('hlink', linkprop(hax, 'XLim'))); %drawnow hfig = gcf; % individual plotting for different acoustic features function plotRMS % technical note: % openGL rendering does not support log scaling, which causes % problems with highlighting % plot unsmoothed power semilogy(spec.times, spec.totalPower, 'm-'); % plot first derivative smoothedPower = smoothSignal(spec.totalPower,17); dt = spec.times(2) - spec.times(1); dPdT = [diff(smoothedPower) / dt eps]; posTimes = spec.times; posTimes(dPdT<=0) = NaN; negTimes = spec.times; negTimes(dPdT>=0) = NaN; % plot negative and positive as diff signs hold on; semilogy(posTimes, dPdT,'g-') semilogy(negTimes, -dPdT,'r-') hold off; % set plotting window set(gca, 'YLimMode', 'manual') minPower = min(spec.totalPower); ylim([minPower/2,1e-1]) set(gca,'YTick',10.^(ceil(log10(minPower)):-1)); xlim([min(spec.times) max(spec.times)]); ylabel('log RMS Power') title('Total Power (Volume)') end function plotFracDiffPower % plot first derivative smoothedPower = smoothSignal(spec.totalPower,17); dt = spec.times(2) - spec.times(1); dPdT = [diff(smoothedPower) / dt eps]; dfPdT = dPdT./spec.totalPower; posTimes = spec.times; posTimes(dPdT<=0) = NaN; negTimes = spec.times; negTimes(dPdT>=0) = NaN; semilogy(posTimes, dfPdT,'g-', negTimes, -dfPdT,'r-') hold off; % set plotting window set(gca, 'YLimMode', 'manual') xlim([min(spec.times) max(spec.times)]); %minPower = min(spec.totalPower); ylim([min(abs(dfPdT))/3,max(abs(dfPdT)) * 3]) %set(gca,'YTick',10.^(ceil(log10(minPower)):-1)); end function plotEntropy plot(spec.times, spec.wienerEntropy, 'r-'); xlim([min(spec.times) max(spec.times)]); ylabel('Entropy') title('Wiener entropy (high = noise, low = tone, mid = stack)') end function plotFM %semilogy(spec.times, spec.mTD, 'r-',spec.times, spec.mFD,'b-'); plot(spec.times, spec.FM, 'r-'); xlim([min(spec.times) max(spec.times)]); %ylim([0 90]); ylabel('FM (deg)') title('Frequency modulation') end function plotAM plot(spec.times, spec.AM, 'r-'); xlim([min(spec.times) max(spec.times)]); %ylim([0 90]); ylabel('AM (1/ms)') title('Amplitude modulation') end function plotRawAM % plot first derivative posTimes = spec.times; posTimes(spec.rawAM<=0) = NaN; negTimes = spec.times; negTimes(spec.rawAM>=0) = NaN; % plot negative and positive as diff signs semilogy(posTimes, spec.rawAM,'g-') hold on; semilogy(negTimes, -spec.rawAM,'r-') hold off; xlim([min(spec.times) max(spec.times)]); ylabel('raw AM (dB/ms)') ylim([1e-5 1]); title('Unnormalized amplitude modulation') end function plotPitchGoodness semilogy(spec.times, spec.pitchGoodness, 'r-'); % plot(spec.times, log10(spec.pitchGoodness), 'r-'); xlim([min(spec.times) max(spec.times)]); ylabel('log Cepstral strength'); title('Goodness of pitch'); end function plotPitch(field, colStyle, varargin) if nargin < 2, colStyle = 'r-'; end; if nargin < 1, field = 'fundamentalFreq'; end; plot(spec.times, spec.(field), colStyle,varargin{:}); xlim([min(spec.times) max(spec.times)]); ylim([min(spec.freqs) max(spec.freqs)]); ylabel('freq (Hz)'); % title(field); end function plotFracPeriodicPower plot(spec.times, spec.aperiodicity, 'r-'); xlim([min(spec.times) max(spec.times)]); ylim([0 1]); ylabel('aper pow frac'); title('Fraction of Periodic power') end function plotPartialDerivs semilogy(spec.times, spec.mTD, 'r-', spec.times, spec.mFD, 'g-'); %plot(spec.times, log10(spec.mTD), 'r-', ... % spec.times, log10(spec.mFD), 'g-'); xlim([min(spec.times) max(spec.times)]); ylabel('partial deriv amp (dB/msec)'); end function plotMFCC nColors=256; % the first row of the MFCC is the volume nBands = size(spec.mfcc, 1) - 1; hs = imagesc([min(spec.times) max(spec.times)],... [2 nBands],... spec.mfcc(2:end,:)); xlabel('Time (s)'); ylabel('mel-freq cepstral coeff'); set(gca,'YDir','normal'); colormap(gray(nColors)); end function plotLabels for kk = 1:numel(regions) if ~isempty(regions(kk).type) xpos = (regions(kk).start + regions(kk).stop)/2; createTextLabel(xpos, regions(kk).type); end end end end function buttonDownFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currPt = currPt(1,1:2); [patchClicked, lineClicked, hitWindow] = clickStatus(currPt, handles); if ~hitWindow, return; end; % if we are NOT double clicked, get out if ~strcmp(get(gcbo,'SelectionType'),'open'), return; end; % we are double clicked: play a sound % get the clip data hline = findobj(hax,'Type','line'); hline = hline(end); % it should be the one furthest back xWave = get(hline,'XData'); yWave = get(hline,'YData'); fs = get(hline,'UserData'); if isempty(patchClicked) % what should we do if a patch is not clicked? % play the whole clip playSound(yWave, fs, true); else % get the borders currXData = get(hp, 'XData'); patchBorders = currXData(2:3,patchClicked); % cut the clip at the right points clipStart = find(xWave >= patchBorders(1),1); clipEnd = find(xWave >= patchBorders(2),1); clip = yWave(clipStart:clipEnd); % play the sound clip, while blocking playSound(clip, fs, true); end end function [patchSeld, lineSeld, hitWindow] = clickStatus(currPt, handles) % returns empties on default patchSeld = []; lineSeld = []; hax = handles(1); hp = handles(2); win([1 3]) = get(hax,'XLim'); win(3) = win(3) - win(1); win([2 4]) = get(hax,'YLim'); win(4) = win(4) - win(2); hitWindow = inRect(win, currPt); if ~hitWindow, return, end; yy = get(hax,'YLim'); if currPt(2) > yy(2) || currPt(2) < yy(1), return; end; xBounds = get(hp,'XData'); if isempty(xBounds), return; end; % nothing to click xBounds = xBounds(2:3,:); patchSeld = find(xBounds(1,:) <= currPt(1) & xBounds(2,:) >= currPt(1)); if numel(patchSeld) > 1 % find the one which is closer distsToCursor = min(xBounds(1,patchSeld) - currPt(1)); [~,closest] = min(distsToCursor); patchSeld = patchSeld(closest); end end function foo = inRect(win, pt) foo = win(1) <= pt(1) && pt(1) < win(1) + win(3) && ... win(2) <= pt(2) && pt(2) < win(2) + win(4); end
github
BottjerLab/Acoustic_Similarity-master
plotWaveform.m
.m
Acoustic_Similarity-master/code/plotting/plotWaveform.m
2,453
utf_8
d3bade9bec54e936a5bd0b02de9ae59a
function hline = plotWaveform(clip, fs) %PLOTWAVEFORM plots waveform in the window, with downsampling if necessary len = length(clip); xx = 1:len; % Plots downsampled data. This has much faster response time. This is % based on dsplot by Jiro Doke in file exchange. % Find outliers filterWidth = min([50, ceil(length(xx)/10)]); % max window size of 50 a = clip - ... filter(ones(filterWidth,1)/filterWidth, 1, clip); this.iOutliers = ... find(abs(a - repmat(mean(a), size(a, 1), 1)) > ... repmat(4 * std(a), size(a, 1), 1)); range = floor([0 len]); % Despite the spirit of this script (which is to keep memory down for % large (1M #) arrays, % We keep a large number of points in order to make the playback simpler - % since the data needs to be stored anyway for playback in some % applications (editEventLabels), we might as well keep them all. % TODO: make this an option in the future numPoints = 1e6; if length(xx) > numPoints idx = round(linspace(xx(1), xx(end), numPoints))'; idxi = unique([idx; this.iOutliers]); hline = plot(idxi/fs,clip(idxi)); else hline = plot(xx/fs,clip(xx)); end %%% maxNTicks = 25; interval = max(0.05,numel(clip)/fs/maxNTicks); interval = round(interval * 100)/100; % fix to two decimal points set(gca,'XTick',0:interval:numel(clip)/fs); xlim([0 len]/fs); ylim([-1 1]); end % Plots downsampled data. This has much faster response time. This is % based on dsplot by Jiro Doke in file exchange. % TODO Add data cursor callbacks function dsplot(clip) len = length(clip); x = 1:len; % Find outliers filterWidth = min([50, ceil(length(x)/10)]); % max window size of 50 a = clip - ... filter(ones(filterWidth,1)/filterWidth, 1, clip); [this.iOutliers, this.jOutliers] = ... find(abs(a - repmat(mean(a), size(a, 1), 1)) > ... repmat(4 * std(a), size(a, 1), 1)); range = floor([0 len]); numPoints = 50000; %len = length(this.ChannelHandles); x = (1:size(clip, 1))'; id = find(x >= range(1) & x <= range(2)); if length(id) > numPoints/len idx = round(linspace(id(1), id(end), round(numPoints/len)))'; ol = this.iOutliers > id(1) & this.iOutliers < id(end); for i=1:len idxi = unique([idx; this.iOutliers(ol & this.jOutliers == i)]); set(this.ChannelHandles(i), 'XData', idxi/fs, ... 'YData', clip(idxi)); end else for i=1:len set(this.ChannelHandles(i), 'XData', id/fs, ... 'YData', clip(id)); end end end
github
BottjerLab/Acoustic_Similarity-master
plotEvent.m
.m
Acoustic_Similarity-master/code/plotting/plotEvent.m
971
utf_8
5fe64e798dff955eb8852350c57d55ca
function plotEvent(songStruct, ev, regions) cl = getClip(ev, songStruct); plot( (1:numel(cl)) * songStruct.interval, cl); plotMarks(0.95) function plotMarks(yc) hold on; if ~isempty(regions) plot([regions.start],yc, 'cv',... 'MarkerFaceColor','c', 'MarkerSize', 5); plot([regions.stop],yc, 'mv',... 'MarkerFaceColor','m', 'MarkerSize', 5); for jj = 1:numel(regions) ymins = ylim; if strcmp(get(gca,'YScale'),'log') semilogy(repmat([regions.start],2,1), [ymins(1) yc],'c-'); semilogy(repmat([regions.stop],2,1), [ymins(1) yc],'m-'); else plot(repmat([regions.start],2,1), [ymins(1) yc],'c-'); plot(repmat([regions.stop],2,1), [ymins(1) yc],'m-'); end end end hold off; end end
github
BottjerLab/Acoustic_Similarity-master
plotFRERA.m
.m
Acoustic_Similarity-master/code/plotting/plotFRERA.m
2,754
utf_8
a0fba374e90a98c7ad40a0648beddb91
function plotFRERA(subset1, subset2, field, bins) % plots a firing rate comparison if ~isempty(subset1) set1Hist = sum(horzcat(subset1.(field)),2)/length(subset1); set1HistSem = std(horzcat(subset1.(field)),[],2)/sqrt(length(subset1)); plotLineTransparentSEM(bins(1:end-3), set1Hist, set1HistSem, [0.5 0.5 0.5]);%removing bins because removed last three points in eraFind hold on; end if ~isempty(subset2) set2Hist = sum(horzcat(subset2.(field)),2)/length(subset2); set2HistSem = std(horzcat(subset2.(field)),[],2)/sqrt(length(subset2)); plotLineTransparentSEM(bins(1:end-3), set2Hist, set2HistSem, [1 0.2 0.2]); %removing bins because removed last three points in eraFind end if ~isempty(subset1) hold off; end % let's look for significance N1 = length(subset1); N2 = length(subset2); t_stat = tinv(0.975, N1-1); %0.05 two-tailed critical value if any((set1Hist - set1HistSem * t_stat) > 0) sig_set1IdxPos = find((set1Hist - set1HistSem * t_stat) > 0); sig_set1xxPos = insertNonConsecNans(bins(sig_set1IdxPos), sig_set1IdxPos); hold on; ybar = ylim * [0.08 0.92]'; % 92% of the way to the top plot(sig_set1xxPos, ybar * ones(1,numel(sig_set1xxPos)), '-', 'LineWidth', 2, 'Color', [0.5 0.5 0.5]); end if any((set1Hist + set1HistSem * t_stat) < 0) sig_set1IdxNeg = find((set1Hist + set1HistSem * t_stat) < 0); sig_set1xxNeg = insertNonConsecNans(bins(sig_set1IdxNeg), sig_set1IdxNeg); hold on; ybar = ylim * [0.92 0.08]'; % 92% of the way to the bottom plot(sig_set1xxNeg, ybar * ones(1,numel(sig_set1xxNeg)), '-', 'LineWidth', 2, 'Color', [0.5 0.5 0.5]); end t_stat = tinv(0.975, N2-1); %0.05 two-tailed critical value if any((set2Hist - set2HistSem * t_stat) > 0) sig_set2IdxPos = find((set2Hist - set2HistSem * t_stat) > 0); sig_set2xxPos = insertNonConsecNans(bins(sig_set2IdxPos), sig_set2IdxPos); hold on; ybar = ylim * [0.12 0.88]'; % 88% of the way to the top plot(sig_set2xxPos, ybar * ones(1,numel(sig_set2xxPos)), 'r-', 'LineWidth', 2); end if any((set2Hist + set2HistSem * t_stat) < 0) sig_set2IdxNeg = find((set2Hist + set2HistSem * t_stat) < 0); sig_set2xxNeg = insertNonConsecNans(bins(sig_set2IdxNeg), sig_set2IdxNeg); hold on; ybar = ylim * [0.88 0.12]'; % 88% of the way to the bottom plot(sig_set2xxNeg, ybar * ones(1,numel(sig_set2xxNeg)), 'r-', 'LineWidth', 2); end end function ret = insertNonConsecNans(lookupvec, idxvec) nonConsec = find(diff(idxvec)>1); ret = lookupvec; for jj = 1:numel(nonConsec) ret = [ret(1:nonConsec(jj)); NaN; ... ret(nonConsec(jj)+1:end)]; nonConsec = nonConsec+1; end xlim([-150 150]); end
github
BottjerLab/Acoustic_Similarity-master
plotDerivGram.m
.m
Acoustic_Similarity-master/code/plotting/plotDerivGram.m
1,212
utf_8
55be1f678d3bab14683fd36a1e2f021c
function hs = plotDerivGram(spec, params, varargin) if nargin < 2 || isempty(params) params = defaultParams; end params = processArgs(params, varargin{:}); % arrange into log space deps = params.dgram.minContrast; lDeriv = spec.deriv; lDeriv(abs(spec.deriv) < deps) = 0; lDeriv(spec.deriv > deps) = -log(lDeriv(spec.deriv > deps)/deps); lDeriv(spec.deriv < -deps) = log(-lDeriv(spec.deriv < -deps)/deps); % convert to direct color mapping, for efficiency's sake nColors = 256; lmin = min(lDeriv(:)); lmax = max(lDeriv(:)); %lDerivMap = flipud(uint8(fix((lDeriv - lmin)/(lmax-lmin) * nColors) + 1)); hs = imagesc([min(spec.times) max(spec.times)],... [min(spec.freqs) max(spec.freqs)],... lDeriv); colormap(gray(nColors)); % flip the y-axis set(gca,'YDir','normal'); % a much slower way to do it, but imagesc may not be supported in all matlab % versions %hs = surf(spec.times, spec.freqs, lDerivMap,'EdgeColor','none',... % 'CDataMapping','direct','facecolor','texturemap');%,... % 'xlimmode','manual','ylimmode','manual','zlimmode','manual',... % 'climmode','manual','alimmode','manual'); %view(0,90) end function ans = roundN(val,N) round(val / N) * N; end
github
BottjerLab/Acoustic_Similarity-master
plotNeuronCorrData.m
.m
Acoustic_Similarity-master/code/plotting/plotNeuronCorrData.m
29,105
utf_8
b64a370a4d3b4143c844755b92c7984d
function plotNeuronCorrData(allNeuronCorrData, params, varargin) if nargin < 2 || isempty(params) params = defaultParams; end params = processArgs(params, varargin{:}); % plot difference between firing rates for near tutor/far from tutor % and also p-values for correlations between neurons and firing rates % this data is compiled in correlateDistanceToFiring, but JMA edited so % that main neural analysis is done here and ignores neural analysis stuff % done in correlateDistanceToFiring if nargin < 1 || isempty(allNeuronCorrData) load('data/allNeuronCorrelations.mat'); end %% here we load the cluster quality % get birds and ages first sessionIDs = {allNeuronCorrData.sessionID}; birdIDs = strtok(sessionIDs, '_'); [uSessions, ~, rIdxSession] = unique(sessionIDs); % index through ages can go back to sessions uAges = getAgeOfSession(uSessions); sessionAges = zeros(size(sessionIDs)); for ii = 1:numel(uAges) sessionAges(rIdxSession == ii) = uAges(ii); end [sessionQ , allSubj] = getClusterQuality(birdIDs, sessionAges, [allNeuronCorrData.syllID]); [sessionObjQ, allObj ] = getClusterQuality(birdIDs, sessionAges, [allNeuronCorrData.syllID], true); foo = num2cell(sessionQ ); [allNeuronCorrData.clusterQ ] = foo{:}; foo = num2cell(sessionObjQ); [allNeuronCorrData.clusterObjQ] = foo{:}; foo = allSubj'; allSubj = [allSubj(:)]; foo = allObj' ; allObj = [allObj(:) ]; missingData = isnan(allSubj) | isnan(allObj); qualityFit = polyfit(allSubj(~missingData), allObj(~missingData), 1); plot(1:5, polyval(qualityFit,1:5),'r-'); hold on; %boxplot(sessionObjQ', sessionQ', 'notch', 'on'); plot(allSubj, allObj, 'k.'); [rQualCorr, pQualCorr] = corrcoef(allSubj(~missingData), allObj(~missingData)); legend(sprintf('r^2 = %0.3f, p = %0.3g', rQualCorr(2,1), pQualCorr(2,1))); xlim([0.5 5.5]) xlabel('Subjective Cluster Quality'); ylabel('Davies-Bouldin Index'); title('Subjective vs. objective cluster quality correlations'); if params.saveplot saveCurrFigure('figures\A_keeper\objSubjClusterQuality.jpg'); end %% flags isCore = [allNeuronCorrData.isCore]; isMUA = [allNeuronCorrData.isMUA]; isPlastic = [allNeuronCorrData.isPlastic]; isSignificant = [allNeuronCorrData.sigResponse]; nSylls = [allNeuronCorrData.nSylls]; %isSignificant = true(1,numel(allNeuronCorrData)); isExcited = [allNeuronCorrData.isExcited]; %% isSubjGood = [allNeuronCorrData.clusterQ] < 1.5; % < 2.5 isObjGood = [allNeuronCorrData.clusterObjQ] < 0.8; % < 1 %% % criteria for cluster inclusion % isPresel = isSignificant & ~isMUA & nSylls >= 12 & isSubjGood; %JMA changed this because don't need a certain #/cluster rather certain # overall all clusters for neurons correlation (as opposed to neuron/syllable pair) isPresel = ~isMUA & isObjGood; %~isMUA & isObjGood %%isPresel = isSignificant; % for mostresponsive neurons in todo0410.m %isPresel = nSylls >= 12; % subplot rows / columns nR = 3; nC = 2; % measures distanceTypes = {'tutor', 'intra', 'inter', 'consensus', 'central','humanMatch'}'; distanceDescriptions = {'closest tutor', 'cluster center', 'normed center', ... 'closest tutor to cluster consensus', 'closest tutor to cluster center', 'expert-designated tutor'}; dFieldsRS = [strcat(distanceTypes, '_nearMeanRS') strcat(distanceTypes, '_farMeanRS')]; dFieldsSEM = [strcat(distanceTypes, '_nearMeanSEM') strcat(distanceTypes, '_farMeanSEM')]; eiTitle = {'Significantly inhibited single unit-syllable pairs', ... 'Significantly excited single unit-syllable pairs', ... 'All significant single unit-syllable pairs'}; xlabels = strcat({'RS for near - far to '}, distanceDescriptions); filsuff = {'inh','exc','all'}; %% %{ for hh = 1:3 % inhibited, excited, all for ii = 1:numel(distanceTypes) % six of them figure; diffTutorMeanRS = [allNeuronCorrData.(dFieldsRS{ii,1})] - [allNeuronCorrData.(dFieldsRS{ii,2})]; nearMeanRS = [allNeuronCorrData.(dFieldsRS{ii,1})]; farMeanRS = [allNeuronCorrData.(dFieldsRS{ii,2})]; nearMeanSEM = [allNeuronCorrData.(dFieldsRS{ii,1})]; farMeanSEM = [allNeuronCorrData.(dFieldsRS{ii,2})]; if hh < 3 selHereCore = isPresel & isExcited == hh-1 & isCore; selHereShell = isPresel & isExcited == hh-1 & ~isCore; coreDiffRS = diffTutorMeanRS(selHereCore); shellDiffRS = diffTutorMeanRS(selHereShell); coreSubDiffRS = diffTutorMeanRS(selHereCore & ~isPlastic); shellSubDiffRS = diffTutorMeanRS(selHereShell & ~isPlastic); corePlastDiffRS = diffTutorMeanRS(selHereCore & isPlastic); shellPlastDiffRS = diffTutorMeanRS(selHereShell & isPlastic); else coreDiffRS = diffTutorMeanRS(isPresel & isCore); shellDiffRS = diffTutorMeanRS(isPresel & ~isCore); coreSubDiffRS = diffTutorMeanRS(isPresel & isCore & ~isPlastic); shellSubDiffRS = diffTutorMeanRS(isPresel & ~isCore & ~isPlastic); corePlastDiffRS = diffTutorMeanRS(isPresel & isCore & isPlastic); shellPlastDiffRS = diffTutorMeanRS(isPresel & ~isCore & isPlastic); end pc = signrank( coreDiffRS); ps = signrank(shellDiffRS); pMannU = ranksum(coreDiffRS(~isnan(coreDiffRS)), shellDiffRS(~isnan(shellDiffRS))); fprintf(['%s-%s:\n\tsign-rank test p-value for core: %0.3f' ... ' \n\tsign-rank test p-value for shell: %0.3f',... ' \n\tMann-Whitney U test p-value for core v shell: %0.3f\n'],... eiTitle{hh},xlabels{ii},pc,ps,pMannU); % clunky way just to get the top histogram value RSdiffBins = -10:0.2:10; plotInterlaceBars(coreDiffRS, shellDiffRS, RSdiffBins); ytop = ylim * [0 1]'; % todo: plot significance on graph hold on; plotSEMBar( coreDiffRS, ytop , [0.5 0.5 0.5]); plotSEMBar( coreSubDiffRS, ytop+1, [0.5 0.5 0.5]); plotSEMBar( corePlastDiffRS, ytop+2, [0.5 0.5 0.5]); plotSEMBar( shellDiffRS, ytop+3, [ 1 0 0]); plotSEMBar( shellSubDiffRS, ytop+4, [ 1 0 0]); plotSEMBar(shellPlastDiffRS, ytop+5, [ 1 0 0]); plot([0 0], ylim, 'k--'); hold off; % redo y axis labels yt = get(gca,'YTick'); yt = [yt(yt < ytop) ytop:ytop+5]; ytl = cellfun(@(x) sprintf('%d',x),num2cell(yt),'UniformOutput',false); ytl(end-5:end) = {'Core','Core/Subsong','Core/Plastic','Shell','Shell/Subsong','Shell/Plastic'}; set(gca,'YTick',yt,'YTickLabel',ytl); % figure formatting xlabel(xlabels{ii}); ylabel('Count'); xlim([min(RSdiffBins) max(RSdiffBins)]); set(gca,'Box','off'); set(gca, 'FontSize', 14); set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); title(eiTitle{hh}); set(gcf,'Color',[1 1 1]); if params.saveplot saveCurrFigure(sprintf('figures/distanceCorrelations/RSdiffs-SUA-%s-%s.jpg', distanceTypes{ii}, filsuff{hh})); end end end %} %% JMA added this section to compare neurons with compiled cluster data for aa = 1: length(allNeuronCorrData) allNeuronCorrData(aa).intra_DistanceAll = allNeuronCorrData(aa).intra_DistanceAll';%these were in columns allNeuronCorrData(aa).inter_DistanceAll = allNeuronCorrData(aa).inter_DistanceAll'; allNeuronCorrData(aa).burstFraction = allNeuronCorrData(aa).burstFraction'; qq = zeros(allNeuronCorrData(aa).nSylls,1);%needed to do this to get cluster quality and syllable type for every syllable tt = zeros(allNeuronCorrData(aa).nSylls,1); qq(:,1) = deal(allNeuronCorrData(aa).clusterObjQ); tt(:,1) = deal(allNeuronCorrData(aa).syllID); allNeuronCorrData(aa).clusterObjQ = qq'; allNeuronCorrData(aa).syllID = tt'; end usablePairs = allNeuronCorrData(isPresel); usableClusterSessions = {usablePairs.sessionID}; [uUCSessions, ~, ~] = unique(usableClusterSessions); corrByNeuron = struct([]); for mm = 1: length(uUCSessions) isCurrentSession = strcmp(uUCSessions(mm),{usablePairs.sessionID}); currentSessionPairs = usablePairs(isCurrentSession); [neuronsHere, ~, ~] = unique([currentSessionPairs.unitNum]); for nn = 1: length(neuronsHere) isCurrentNeuron = [currentSessionPairs.unitNum] == neuronsHere(nn); currentNeuronPairs = currentSessionPairs(isCurrentNeuron); compiledNeuron.isCore = currentNeuronPairs(1).isCore; compiledNeuron.isMUA = currentNeuronPairs(1).isMUA; compiledNeuron.isPlastic = currentNeuronPairs(1).isPlastic; compiledNeuron.sessionID = currentNeuronPairs(1).sessionID; compiledNeuron.unitNum = currentNeuronPairs(1).unitNum; compiledNeuron.nSylls = sum([currentNeuronPairs.nSylls]); compiledNeuron.sigSyll = sum([currentNeuronPairs.sigResponse]); compiledNeuron.RSAll = horzcat([currentNeuronPairs.RSAll]); compiledNeuron.FRSyll = horzcat([currentNeuronPairs.FRSyll]); compiledNeuron.FRBase = horzcat([currentNeuronPairs.FRBase]); compiledNeuron.burstFraction = horzcat([currentNeuronPairs.burstFraction]); compiledNeuron.tutor_DistanceAll = horzcat([currentNeuronPairs.tutor_DistanceAll]); compiledNeuron.consensus_DistanceAll = horzcat([currentNeuronPairs.consensus_DistanceAll]); compiledNeuron.central_DistanceAll = horzcat([currentNeuronPairs.central_DistanceAll]); compiledNeuron.intra_DistanceAll = horzcat([currentNeuronPairs.intra_DistanceAll]); compiledNeuron.inter_DistanceAll = horzcat([currentNeuronPairs.inter_DistanceAll]); compiledNeuron.quality = horzcat([currentNeuronPairs.clusterObjQ]); compiledNeuron.syllID = horzcat([currentNeuronPairs.syllID]); numClassSyll = length(unique(compiledNeuron.syllID)); compiledNeuron.classSyll = deal(numClassSyll); corrByNeuron = [corrByNeuron; compiledNeuron]; end end isenoughSyll = [corrByNeuron.nSylls] > 39; %want at least 10 syllables in each quartile % usableNeuron = [corrByNeuron.sigSyll] > 0 & isenoughSyll; %neuron has to respond to at least one syllable cluster (but maybe shouldn't do this) usableNeuron = isenoughSyll; corrByNeuron = corrByNeuron(usableNeuron); %correlation of distance to response strength for bb = 1: length(corrByNeuron) yDist = corrByNeuron(bb).tutor_DistanceAll'; %can try other distances xRS = corrByNeuron(bb).RSAll'; [linfit, ~,~,~, fitStats] = regress(yDist, [ones(numel(xRS),1) xRS]); %checked with corrcoef and gives same p value CC = corrcoef(yDist,xRS); %JMA added to get direction of correlation %if params.plot % figure % plot(xRS, yDist, 'k.', 'HandleVisibility', 'off'); % hold on; % plot(xRS, linfit(1) + xRS * linfit(2), '--','Color',[1 0 0]); % legend(sprintf('r^2 = %0.3g, F = %0.3g, p = %0.3g\n',... % fitStats(1), fitStats(2),fitStats(3))); % xlabel('Response Strength'); ylabel('Matched distance'); %end corrByNeuron(bb).linfit = linfit; corrByNeuron(bb).fitStats = fitStats; corrByNeuron(bb).CorrCoef = CC; %JMA added end isCore2 = [corrByNeuron.isCore]; CorrPRS = zeros(length(corrByNeuron),1); for cc = 1: length(corrByNeuron) CorrPRS(cc) = corrByNeuron(cc).fitStats(3); end isCorrel = CorrPRS < 0.05; cSC = isCore2 & isCorrel'; cSS = ~isCore2 & isCorrel'; fprintf('Number neurons with significant correlation of RS in core %s out of %s core neurons \n', num2str(sum(cSC)), num2str(sum(isCore2))) fprintf('Number neurons with significant correlation of RS in shell %s out of %s shell neurons \n', num2str(sum(cSS)), num2str(sum(~isCore2))) %correlation of distance to burst fraction; need to work out bugs if want %to use this burst fraction analysis because just giving NaNs % for bb = 1: length(corrByNeuron) % yDist = corrByNeuron(bb).tutor_DistanceAll'; % xRS = corrByNeuron(bb).burstFraction'; % [linfit, ~,~,~, fitStats] = regress(yDist, [ones(numel(xRS),1) xRS]); % corrByNeuron(bb).linfitBF = linfit; % corrByNeuron(bb).fitStatsBF = fitStats; % end % isCore2 = [corrByNeuron.isCore]; % CorrP = zeros(length(corrByNeuron),1); % for cc = 1: length(corrByNeuron) % CorrP(cc) = corrByNeuron(cc).fitStatsBF(3); % end % isCorrel = CorrP < 0.05; % cSC = isCore2 & isCorrel'; % cSS = ~isCore2 & isCorrel'; % fprintf('Number neurons with significant correlation of BF in core %s out of %s core neurons \n', num2str(sum(cSC)), num2str(sum(isCore2))) % fprintf('Number neurons with significant correlation of BF in shell %s out of %s shell neurons \n', num2str(sum(cSS)), num2str(sum(~isCore2))) %compare population response, standardized response to top and bottom 25% %or 50% %similarity to tutor song for dd = 1: length(corrByNeuron) dists = corrByNeuron(dd).tutor_DistanceAll; %tutor_DistanceAll syllCV = nanstd(corrByNeuron(dd).FRSyll)/nanmean(corrByNeuron(dd).FRSyll); iqDists = prctile(dists, 50); %iqDists = prctile(dists, [25 75]); %quartiles near_quartileFR = corrByNeuron(dd).FRSyll(dists < iqDists); nQuartile = numel(near_quartileFR); %changing it to median instead of quartiles but not changing all the variable names JMA far_quartileFR = corrByNeuron(dd).FRSyll(dists > iqDists); fQuartile = numel( far_quartileFR); % near_quartileFR = corrByNeuron(dd).FRSyll(dists < iqDists(1)); nQuartile = numel(near_quartileFR); %changing it to median instead of quartiles but not changing all the variable names JMA % far_quartileFR = corrByNeuron(dd).FRSyll(dists > iqDists(2)); fQuartile = numel( far_quartileFR); % near_quartileFRBase = corrByNeuron(dd).FRBase(dists < iqDists(1)); % far_quartileFRBase = corrByNeuron(dd).FRBase(dists > iqDists(2)); % near_quartileBF = corrByNeuron(dd).burstFraction(dists < iqDists(1)); % far_quartileBF = corrByNeuron(dd).burstFraction(dists > iqDists(2)); % near_quartileDist = corrByNeuron(dd).tutor_DistanceAll(dists < iqDists(1)); % far_quartileDist = corrByNeuron(dd).tutor_DistanceAll(dists > iqDists(2)); % near_quartileQual = corrByNeuron(dd).quality(dists < iqDists(1)); % far_quartileQual = corrByNeuron(dd).quality(dists > iqDists(2)); % near_quartileType = corrByNeuron(dd).syllID(dists < iqDists(1)); % far_quartileType = corrByNeuron(dd).syllID(dists > iqDists(2)); near_quartileFRBase = corrByNeuron(dd).FRBase(dists < iqDists); far_quartileFRBase = corrByNeuron(dd).FRBase(dists > iqDists); near_quartileBF = corrByNeuron(dd).burstFraction(dists < iqDists); far_quartileBF = corrByNeuron(dd).burstFraction(dists > iqDists); near_quartileDist = corrByNeuron(dd).tutor_DistanceAll(dists < iqDists); far_quartileDist = corrByNeuron(dd).tutor_DistanceAll(dists > iqDists); near_quartileQual = corrByNeuron(dd).quality(dists < iqDists); far_quartileQual = corrByNeuron(dd).quality(dists > iqDists); near_quartileType = corrByNeuron(dd).syllID(dists < iqDists); far_quartileType = corrByNeuron(dd).syllID(dists > iqDists); farQuart = nanmean(far_quartileDist); nearQuart = nanmean(near_quartileDist); farQual = nanmean(far_quartileQual); nearQual = nanmean(near_quartileQual); farTypes = length(unique(far_quartileType)); nearTypes = length(unique(near_quartileType)); nq_meanFR = nanmean(near_quartileFR); nq_varFR = nanvar(near_quartileFR); fq_meanFR = nanmean( far_quartileFR); fq_varFR = nanvar( far_quartileFR); nq_meanBF = nanmean(near_quartileBF); fq_meanBF = nanmean(far_quartileBF); nq_CV = nanstd(near_quartileFR)/nq_meanFR; fq_CV = nanstd(far_quartileFR)/fq_meanFR; nq_meanFRBase = nanmean(near_quartileFRBase); nq_varFRBase = nanvar(near_quartileFRBase); fq_meanFRBase = nanmean( far_quartileFRBase); fq_varFRBase = nanvar( far_quartileFRBase); [~, pVal, ~, tValStruct] = ttest2(near_quartileFR- near_quartileFRBase, far_quartileFR- far_quartileFRBase); tVal = tValStruct.tstat; fcovar = nancov(far_quartileFR,far_quartileFRBase);if numel(fcovar) > 1, fcovar = fcovar(2,1); end; ncovar = nancov(near_quartileFR,near_quartileFRBase);if numel(ncovar) > 1, ncovar = ncovar(2,1); end; aCovar = nancov(corrByNeuron(dd).FRSyll,corrByNeuron(dd).FRBase);if numel(aCovar) > 1, aCovar = aCovar(2,1); end; farZDenom = sqrt(fq_varFR + fq_varFRBase - 2*fcovar); nearZDenom = sqrt(nq_varFR + nq_varFRBase - 2*ncovar); farZ = ((fq_meanFR - fq_meanFRBase)* sqrt(fQuartile))/farZDenom; nearZ = ((nq_meanFR - nq_meanFRBase)* sqrt(nQuartile))/nearZDenom; allZDenom = sqrt(nanvar(corrByNeuron(dd).FRSyll) + nanvar(corrByNeuron(dd).FRBase) - 2*aCovar); allZ = ((nanmean(corrByNeuron(dd).FRSyll) - nanmean(corrByNeuron(dd).FRBase)) *sqrt(corrByNeuron(dd).nSylls))/allZDenom; corrByNeuron(dd).quartilePValue = pVal; corrByNeuron(dd).farZ = farZ; corrByNeuron(dd).nearZ = nearZ; corrByNeuron(dd).farCV = fq_CV; corrByNeuron(dd).nearCV = nq_CV; corrByNeuron(dd).nearBF = nq_meanBF; corrByNeuron(dd).farBF = fq_meanBF; corrByNeuron(dd).farQuart = farQuart; corrByNeuron(dd).nearQuart = nearQuart; corrByNeuron(dd).farQual = farQual; corrByNeuron(dd).nearQual = nearQual; corrByNeuron(dd).farTypes = farTypes; corrByNeuron(dd).nearTypes = nearTypes; corrByNeuron(dd).farTypeID = {unique(far_quartileType)}; corrByNeuron(dd).nearTypeID = {unique(near_quartileType)}; corrByNeuron(dd).modeFarTypeID = mode(far_quartileType); corrByNeuron(dd).modeNearTypeID = mode(near_quartileType); corrByNeuron(dd).syllCV = syllCV; corrByNeuron(dd).allZ = allZ; corrByNeuron(dd).BLFR = nanmean(corrByNeuron(dd).FRBase); corrByNeuron(dd).FR = nanmean(corrByNeuron(dd).FRSyll); corrByNeuron(dd).meanDist = mean(dists); corrByNeuron(dd).farRS = (fq_meanFR - fq_meanFRBase); corrByNeuron(dd).nearRS = (nq_meanFR - nq_meanFRBase); end isQS = [corrByNeuron.quartilePValue] < 0.05; SQC = isCore2 & isQS; SQS = ~isCore2 & isQS; fprintf('Number neurons with significant difference in RS to near vs far in core %s out of %s core neurons \n', num2str(sum(SQC)), num2str(sum(isCore2))) fprintf('Number neurons with significant difference in RS to near vs far in shell %s out of %s shell neurons \n', num2str(sum(SQS)), num2str(sum(~isCore2))) meanFarZC = nanmean([corrByNeuron(isCore2).farZ]); meanFarZS = nanmean([corrByNeuron(~isCore2).farZ]); SEMFarC = nanstd([corrByNeuron(isCore2).farZ])/sqrt(length(corrByNeuron(isCore2))); SEMFarS = nanstd([corrByNeuron(~isCore2).farZ])/sqrt(length(corrByNeuron(~isCore2))); meanNearZC = nanmean([corrByNeuron(isCore2).nearZ]); meanNearZS = nanmean([corrByNeuron(~isCore2).nearZ]); SEMNearC = nanstd([corrByNeuron(isCore2).nearZ])/sqrt(length(corrByNeuron(isCore2))); SEMFarS = nanstd([corrByNeuron(~isCore2).nearZ])/sqrt(length(corrByNeuron(~isCore2))); % % normalized RS values--JMA not using anything from this point on % dNormedRSFields = strcat(distanceTypes, '_dRSnorm'); % for hh = 1:3 % inhibited, excited, all % for ii = 1:numel(distanceTypes) % six of them % figure; % dRSNormed = [allNeuronCorrData.(dNormedRSFields{ii})]; % if hh < 3 % coreDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & isCore); % shellDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & ~isCore); % % coreSubDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & isCore & ~isPlastic); % shellSubDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & ~isCore & ~isPlastic); % % corePlastDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & isCore & isPlastic); % shellPlastDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & ~isCore & isPlastic); % else % coreDiffRSNorm = dRSNormed(isPresel & isCore); % shellDiffRSNorm = dRSNormed(isPresel & ~isCore); % % coreSubDiffRSNorm = dRSNormed(isPresel & isCore & ~isPlastic); % shellSubDiffRSNorm = dRSNormed(isPresel & ~isCore & ~isPlastic); % % corePlastDiffRSNorm = dRSNormed(isPresel & isCore & isPlastic); % shellPlastDiffRSNorm = dRSNormed(isPresel & ~isCore & isPlastic); % end % fprintf('%s-normed %s: ', eiTitle{hh},xlabels{ii}); % if ~(all(isnan( coreSubDiffRSNorm)) || ... % all(isnan( corePlastDiffRSNorm)) || ... % all(isnan( shellSubDiffRSNorm)) || ... % all(isnan(shellPlastDiffRSNorm))) % % % significance tests: two-way anova, permuted % % this function is not consistent with matlab's anovan, so it % % won't be used until we can see why the inconsistency's there % %[stats, df, pvals] = statcond(... % % {noNaN( coreSubDiffRSNorm), noNaN( corePlastDiffRSNorm); ... % % noNaN(shellSubDiffRSNorm), noNaN(shellPlastDiffRSNorm)}, ... % %'mode','param'); % % test against anova % % xx = [coreSubDiffRSNorm corePlastDiffRSNorm shellSubDiffRSNorm shellPlastDiffRSNorm]'; % grps = [zeros(size(coreSubDiffRSNorm)) zeros(size(corePlastDiffRSNorm)) ... % ones(size(shellSubDiffRSNorm)) ones(size(shellPlastDiffRSNorm)); ... % zeros(size(coreSubDiffRSNorm)) ones(size(corePlastDiffRSNorm)) ... % zeros(size(shellSubDiffRSNorm)) ones(size(shellPlastDiffRSNorm))]'; % if isreal(xx) %JMA added % [pAnova, tAnova] = anovan(xx,grps,'model','interaction','display', 'off'); % fprintf(['\n\tANOVA (fixed model), 2-way: effect of core/shell, p = %0.2f, '... % 'effect of subsong/plastic, p = %0.2f, interaction, p = %0.2f'], ... % pAnova(1), pAnova(2), pAnova(3)) % else % fprintf('Skipping two-way permutation ANOVA'); % end % end % % significance tests: post-hoc, core vs shell % if ~isempty(coreDiffRSNorm) && ~isempty(shellDiffRSNorm) % pc = signrank( coreDiffRSNorm); % ps = signrank(shellDiffRSNorm); % pMannU = ranksum(coreDiffRSNorm(~isnan(coreDiffRSNorm)), shellDiffRSNorm(~isnan(shellDiffRSNorm))); % % no subsong/plastic significance tests % % fprintf(['\n\tsign-rank test p-value for core: %0.3f' ... % '\n\tsign-rank test p-value for shell: %0.3f',... % '\n\tMann-Whitney U test p-value for core v shell: %0.3f\n'],... % pc,ps,pMannU); % end % % % set bins for histogram % RSdiffBins = -10:0.5:10; % plotInterlaceBars(coreDiffRSNorm, shellDiffRSNorm, RSdiffBins); % ytop = ylim * [0 1]'; % % % todo: plot significance on graph % hold on; % plotSEMBar( coreDiffRSNorm, ytop , [0.5 0.5 0.5]); % plotSEMBar( shellDiffRSNorm, ytop+1, [ 1 0 0]); % plotSEMBar( coreSubDiffRSNorm, ytop+2, [0.5 0.5 0.5]); % plotSEMBar( shellSubDiffRSNorm, ytop+3, [ 1 0 0]); % plotSEMBar( corePlastDiffRSNorm, ytop+4, [0.5 0.5 0.5]); % plotSEMBar(shellPlastDiffRSNorm, ytop+5, [ 1 0 0]); % plot([0 0], ylim, 'k--'); % hold off; % % redo y axis labels % yt = get(gca,'YTick'); % yt = [yt(yt < ytop) ytop:ytop+5]; % ytl = cellfun(@(x) sprintf('%d',x),num2cell(yt),'UniformOutput',false); % ytl(end-5:end) = {'Core','Shell','Core/Subsong','Shell/Subsong','Core/Plastic','Shell/Plastic'}; % set(gca,'YTick',yt,'YTickLabel',ytl); % % % figure formatting % xlabel(['normalized ' xlabels{ii}]); % ylabel('Count'); % legend(sprintf('CORE: n = %d', numel( coreDiffRSNorm(~isnan( coreDiffRSNorm)))),... % sprintf('SHELL: n = %d', numel(shellDiffRSNorm(~isnan(shellDiffRSNorm))))); % xlim([min(RSdiffBins) max(RSdiffBins)]); % set(gca,'Box','off'); % set(gca, 'FontSize', 14); % set(get(gca,'XLabel'),'FontSize', 14); % set(get(gca,'YLabel'),'FontSize', 14); % set(get(gca,'Title' ),'FontSize', 14); % title(sprintf('%s, core/shell diff p = %0.2g, core from zero p = %0.2g, shell from zero p = %0.2g', eiTitle{hh}, pMannU, pc, ps)); % set(gcf,'Color',[1 1 1]); % % %mean(coreDiffRSNorm) % %mean(shellDiffRSNorm) % %pause; % if params.saveplot % imFile = sprintf('figures/paper/distanceCorrelations-subjectiveScoreFilter/normedRSdiffs-SUA-%s-%s.pdf', distanceTypes{ii}, filsuff{hh}); % fprintf('Writing image to %s', imFile); % scrsz = get(0,'ScreenSize'); % set(gcf, 'Position', [1 1 scrsz(3) scrsz(4)]); % % export_fig(imFile); % % % saveCurrFigure(sprintf('figures/A_keeper/mostResponsive/normedRSdiffs-SUA-%s-%s.jpg', distanceTypes{ii}, filsuff{hh})); % end % end % end %{ fprintf('\n\np-values of FR correlation to distance types'); pFields = strcat(distanceTypes, 'Distance_p'); R2Fields = strcat(distanceTypes, 'DistanceR2'); xlabels = strcat({'Linear trend p-values of FR to '}, distanceDescriptions); for hh = 1:3 % inhibited, excited, all figure; for ii = 1:numel(distanceTypes) subplot(nR,nC,ii) corrPVals = [allNeuronCorrData.(pFields{ii})]; corrR2Vals = [allNeuronCorrData.(R2Fields{ii})]; if hh < 3 coreCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore); shellCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore); % get % variance explained [ coreR2M, coreR2SEM] = meanSEM(corrR2Vals(isPresel & isExcited == hh-1 & isCore)); [shellR2M, shellR2SEM] = meanSEM(corrR2Vals(isPresel & isExcited == hh-1 & ~isCore)); %coreSubCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore & ~isPlastic); %shellSubCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore & ~isPlastic); %corePlastCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore & isPlastic); %shellPlastCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore & isPlastic); else coreCPVs = corrPVals(isPresel & isCore); shellCPVs = corrPVals(isPresel & ~isCore); [ coreR2M, coreR2SEM] = meanSEM(corrR2Vals(isPresel & isCore)); [shellR2M, shellR2SEM] = meanSEM(corrR2Vals(isPresel & ~isCore)); %coreSubCPVs = corrPVals(isPresel & isCore & ~isPlastic); %shellSubCPVs = corrPVals(isPresel & ~isCore & ~isPlastic); %corePlastCPVs = corrPVals(isPresel & isCore & isPlastic); %shellPlastCPVs = corrPVals(isPresel & ~isCore & isPlastic); end % test the difference between core and shell pMannU = ranksum(coreCPVs(~isnan(coreCPVs)), shellCPVs(~isnan(shellCPVs))); fprintf('%s - %s: Mann-Whitney U p-value for core v shell: %0.3f\n',... eiTitle{hh}, xlabels{ii},pMannU); fprintf(['\tCore variance explained: %0.2f +/- %0.2f, '... 'shell variance explained: %0.2f +/- %0.2f\n'], ... coreR2M, coreR2SEM, shellR2M, shellR2SEM); pBins = logspace(-3,0,30); plotInterlaceBars(coreCPVs, shellCPVs, pBins); legend(sprintf('CORE: n = %d', numel( coreCPVs(~isnan( coreCPVs)))),... sprintf('SHELL: n = %d', numel(shellCPVs(~isnan(shellCPVs))))); xlabel(xlabels{ii}); ylabel('Count'); xlim([0 1]) % figure formatting set(gca, 'XTick', [0.05 0.1 0.2 0.4 0.6 0.8]); set(gca, 'Box', 'off'); set(gca, 'FontSize', 12); % xticklabel_rotate([],45); % this messes up the figure subplots set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); % todo: plot the significance markers ytop = ylim * [0 1]'; ylim([0 ytop+2]); hold on; plotSEMBar( coreCPVs, ytop-0.2, [0.5 0.5 0.5]); plotSEMBar(shellCPVs, ytop-0.1, [1 0 0]); hold off; end subplot(nR,nC,1); title(eiTitle{hh}); set(gcf,'Color',[1 1 1]); if params.saveplot saveCurrFigure(sprintf('figures/distanceCorrelations/neuronDistanceCorr-SUA-%s.jpg', filsuff{hh})); end end %} end function [m, v] = meanSEM(set1) m = nanmean(set1); if numel(set1) >= 2 v = nanstd(set1 )/sqrt(numel(set1)-1); else v = 0; end end % plot the error bars w/ SEM on top function plotSEMBar(set, y, col) [m,v] = meanSEM(set); plotHorzErrorBar(m,y,v,col); end function x = noNaN(x) x(isnan(x)) = []; end
github
BottjerLab/Acoustic_Similarity-master
plotAlignedPSTH.m
.m
Acoustic_Similarity-master/code/plotting/plotAlignedPSTH.m
5,624
utf_8
ab6ae9432ab85c399e8892991cf10680
function eventSpikeTimes = plotAlignedPSTH(events, spikeTimes, subEvents, labelsOfInterest) % function plotAlignedPSTH(events, spikeTimes) plot time-warped rasters/PSTH % % % spikeTimes is expected to be a raw array of spike times if nargin < 3 subEvents = initEvents(1); end if nargin < 4 labelsOfInterest = {}; elseif ~iscell(labelsOfInterest) labelsOfInterest = {labelsOfInterest}; end [counts, eventSpikeTimes] = countSpikes(events, spikeTimes,'onset'); syllableLabels = {subEvents.type}; syllableLengths = [subEvents.stop] - [subEvents.start]; [uLabels, foo, rLabelIdx] = unique(syllableLabels); [parentage, eventsInContext] = findParent(events,subEvents); nAlign = numel(labelsOfInterest); rAlignIdx = NaN(size(rLabelIdx)); doWarping = (nargin == 4); if doWarping % set index of event types according to the align list for ii = 1:nAlign labelsIndex = find(strcmp(uLabels,labelsOfInterest{ii})); if ~isempty(labelsIndex) rAlignIdx(rLabelIdx == labelsIndex) = ii; end end % get the average onset and length of each syllable avgLengths = zeros(1,nAlign); for ii = 1:nAlign % get average length isThisLabel = (rAlignIdx == ii); avgLengths(ii) = mean(syllableLengths(isThisLabel)); avgStarts(ii) = mean([eventsInContext(isThisLabel).start]); end warpedEventsInContext = eventsInContext; for ii = 1:numel(events) isChild = (parentage == ii); childEvs = eventsInContext(isChild); controlPoints = NaN(2*nAlign, 2); % first column is sample, second is standard; controlSet = false(1,2*nAlign); for jj = 1:nAlign % in case of multiply labeled syllables, just pick the first % one for alignment purposes matchAlign = find(strcmp({childEvs.type},labelsOfInterest{jj}),1); if ~isempty(matchAlign) controlPoints(2*jj-1:2*jj,:) = ... [childEvs(matchAlign).start avgStarts(jj); ... childEvs(matchAlign).stop avgStarts(jj) + avgLengths(jj)]; controlSet(2*jj-1) = true; controlSet(2*jj) = true; end end controlPoints(~controlSet,:) = []; % get rid of nan points % now use control points to linearly interpolate times adjEventSpikeTimes{ii} = interpLinearPoints(eventSpikeTimes{ii},... controlPoints(:,2), controlPoints(:,1)); % for plotting purposes: warp event boundaries themselves warpedStarts = interpLinearPoints([childEvs.start],... controlPoints(:,2), controlPoints(:,1)); warpedStops = interpLinearPoints([childEvs.stop],... controlPoints(:,2), controlPoints(:,1)); foo = num2cell(warpedStarts); [warpedEventsInContext(isChild).start] = foo{:}; foo = num2cell(warpedStops); [warpedEventsInContext(isChild).stop] = foo{:}; end end % prepare the bins - all important binning parameter binSize = 1e-3; % in seconds % concatenate the spiketimes if doWarping eventSpikeTimes = adjEventSpikeTimes; end xcoords = vertcat(eventSpikeTimes{:}); maxTime = max(xcoords); % plot raster subplot(3,1,1:2) plotRaster; title(sprintf('Raster for song')); % plot average PSTH subplot(3,1,3) title(sprintf('PSTH')); plotPeriHist function plotRaster % option plotColors = true; % this code tells us how to sort out the y-coordinates so that % each 'spike' lands on the correct row stepsUp = zeros(size(xcoords)); stepsUp(cumsum(counts(1:end-1))+1) = 1; stepsUp(1) = 1; ycoords = cumsum(stepsUp); % actually plot the spikes plot(xcoords, ycoords, 'ks','MarkerSize',2,'MarkerFaceColor','k'); xlim([0 maxTime]); ylim([0.5 numel(events) + 0.5]) % optional: plot marks behind for kk = 1:numel(events) isKthChild = (parentage == kk); subEvs = eventsInContext(isKthChild); if doWarping subEvs = warpedEventsInContext(isKthChild); end % assign the new colors only to the labels that correspond to alignment ones if plotColors typeColors = autumn(nAlign); % color assignment for each label evTypes = rAlignIdx(isKthChild); markColors = 0.5*ones(numel(subEvs),3); markColors(~isnan(evTypes),:) = typeColors(evTypes(~isnan(evTypes)),:); else markColors = [0.5 0.5 0.5]; end plotAreaMarks(subEvs, markColors, false, [-0.5 0.5] + kk); end end function plotPeriHist histBar = histc(xcoords, 0:binSize:maxTime); bar(0:binSize:maxTime, histBar, 'histc'); xlim([0 maxTime]); end end function yy = interpLinearPoints(xx,y1,x1) % interpolate linearly between each pair of points & interpolate assert(numel(x1) == numel(y1)) if numel(x1) == 0, yy = xx; return; end; [x1, idxs] = sort(x1); y1 = y1(idxs); intervalPtr = 1; yy = zeros(size(xx)); for kk = 1:numel(xx) intervalPtr = find(xx(kk) <= x1,1); if isempty(intervalPtr) yy(kk) = xx(kk) - x1(end) + y1(end); % no warping after last control point elseif intervalPtr == 1 yy(kk) = xx(kk) - x1(1) + y1(1); % no warping before first control point else yy(kk) = interp1(x1(intervalPtr-1:intervalPtr),... y1(intervalPtr-1:intervalPtr),xx(kk)); end end end
github
BottjerLab/Acoustic_Similarity-master
plotNeuronCorrDataNoCluster.m
.m
Acoustic_Similarity-master/code/plotting/plotNeuronCorrDataNoCluster.m
27,240
utf_8
854abe747d607ccc45ebd0bfeea55088
function plotNeuronCorrDataNoCluster(allNeuronCorrData, params, varargin) if nargin < 2 || isempty(params) params = defaultParams; end params = processArgs(params, varargin{:}); % plot difference between firing rates for near tutor/far from tutor % and also p-values for correlations between neurons and firing rates %This will be without regard classified syllables (i,e. all syllables will %be included) % this data is compiled in correlateDistanceToFiring if nargin < 1 || isempty(allNeuronCorrData) load('data/allNeuronCorrelations.mat'); end %% here we load the cluster quality % get birds and ages first sessionIDs = {allNeuronCorrData.sessionID}; birdIDs = strtok(sessionIDs, '_'); [uSessions, ~, rIdxSession] = unique(sessionIDs); % index through ages can go back to sessions uAges = getAgeOfSession(uSessions); sessionAges = zeros(size(sessionIDs)); for ii = 1:numel(uAges) sessionAges(rIdxSession == ii) = uAges(ii); end [sessionQ , allSubj] = getClusterQuality(birdIDs, sessionAges, [allNeuronCorrData.syllID]); [sessionObjQ, allObj ] = getClusterQuality(birdIDs, sessionAges, [allNeuronCorrData.syllID], true); foo = num2cell(sessionQ ); [allNeuronCorrData.clusterQ ] = foo{:}; foo = num2cell(sessionObjQ); [allNeuronCorrData.clusterObjQ] = foo{:}; foo = allSubj'; allSubj = [allSubj(:)]; foo = allObj' ; allObj = [allObj(:) ]; missingData = isnan(allSubj) | isnan(allObj); qualityFit = polyfit(allSubj(~missingData), allObj(~missingData), 1); plot(1:5, polyval(qualityFit,1:5),'r-'); hold on; %boxplot(sessionObjQ', sessionQ', 'notch', 'on'); plot(allSubj, allObj, 'k.'); [rQualCorr, pQualCorr] = corrcoef(allSubj(~missingData), allObj(~missingData)); legend(sprintf('r^2 = %0.3f, p = %0.3g', rQualCorr(2,1), pQualCorr(2,1))); xlim([0.5 5.5]) xlabel('Subjective Cluster Quality'); ylabel('Davies-Bouldin Index'); title('Subjective vs. objective cluster quality correlations'); if params.saveplot saveCurrFigure('figures\A_keeper\objSubjClusterQuality.jpg'); end %% flags isCore = [allNeuronCorrData.isCore]; isMUA = [allNeuronCorrData.isMUA]; isPlastic = [allNeuronCorrData.isPlastic]; isSignificant = [allNeuronCorrData.sigResponse]; nSylls = [allNeuronCorrData.nSylls]; %isSignificant = true(1,numel(allNeuronCorrData)); isExcited = [allNeuronCorrData.isExcited]; %% isSubjGood = [allNeuronCorrData.clusterQ] < 1.5; % < 2.5 isObjGood = [allNeuronCorrData.clusterObjQ] < 0.8; % < 1 %% % criteria for cluster inclusion % must have at least three syllables per quartile % isPresel = isSignificant & ~isMUA & nSylls >= 12 & isSubjGood; %JMA changed this because don't need a certain #/cluster rather certain # overall all clusters for neurons correlation (as opposed to neuron/syllable pair) isPresel = ~isMUA; %~isMUA & isObjGood %%isPresel = isSignificant; % for mostresponsive neurons in todo0410.m %isPresel = nSylls >= 12; % subplot rows / columns nR = 3; nC = 2; % measures distanceTypes = {'tutor', 'intra', 'inter', 'consensus', 'central','humanMatch'}'; distanceDescriptions = {'closest tutor', 'cluster center', 'normed center', ... 'closest tutor to cluster consensus', 'closest tutor to cluster center', 'expert-designated tutor'}; dFieldsRS = [strcat(distanceTypes, '_nearMeanRS') strcat(distanceTypes, '_farMeanRS')]; dFieldsSEM = [strcat(distanceTypes, '_nearMeanSEM') strcat(distanceTypes, '_farMeanSEM')]; eiTitle = {'Significantly inhibited single unit-syllable pairs', ... 'Significantly excited single unit-syllable pairs', ... 'All significant single unit-syllable pairs'}; xlabels = strcat({'RS for near - far to '}, distanceDescriptions); filsuff = {'inh','exc','all'}; %% %{ for hh = 1:3 % inhibited, excited, all for ii = 1:numel(distanceTypes) % six of them figure; diffTutorMeanRS = [allNeuronCorrData.(dFieldsRS{ii,1})] - [allNeuronCorrData.(dFieldsRS{ii,2})]; nearMeanRS = [allNeuronCorrData.(dFieldsRS{ii,1})]; farMeanRS = [allNeuronCorrData.(dFieldsRS{ii,2})]; nearMeanSEM = [allNeuronCorrData.(dFieldsRS{ii,1})]; farMeanSEM = [allNeuronCorrData.(dFieldsRS{ii,2})]; if hh < 3 selHereCore = isPresel & isExcited == hh-1 & isCore; selHereShell = isPresel & isExcited == hh-1 & ~isCore; coreDiffRS = diffTutorMeanRS(selHereCore); shellDiffRS = diffTutorMeanRS(selHereShell); coreSubDiffRS = diffTutorMeanRS(selHereCore & ~isPlastic); shellSubDiffRS = diffTutorMeanRS(selHereShell & ~isPlastic); corePlastDiffRS = diffTutorMeanRS(selHereCore & isPlastic); shellPlastDiffRS = diffTutorMeanRS(selHereShell & isPlastic); else coreDiffRS = diffTutorMeanRS(isPresel & isCore); shellDiffRS = diffTutorMeanRS(isPresel & ~isCore); coreSubDiffRS = diffTutorMeanRS(isPresel & isCore & ~isPlastic); shellSubDiffRS = diffTutorMeanRS(isPresel & ~isCore & ~isPlastic); corePlastDiffRS = diffTutorMeanRS(isPresel & isCore & isPlastic); shellPlastDiffRS = diffTutorMeanRS(isPresel & ~isCore & isPlastic); end pc = signrank( coreDiffRS); ps = signrank(shellDiffRS); pMannU = ranksum(coreDiffRS(~isnan(coreDiffRS)), shellDiffRS(~isnan(shellDiffRS))); fprintf(['%s-%s:\n\tsign-rank test p-value for core: %0.3f' ... ' \n\tsign-rank test p-value for shell: %0.3f',... ' \n\tMann-Whitney U test p-value for core v shell: %0.3f\n'],... eiTitle{hh},xlabels{ii},pc,ps,pMannU); % clunky way just to get the top histogram value RSdiffBins = -10:0.2:10; plotInterlaceBars(coreDiffRS, shellDiffRS, RSdiffBins); ytop = ylim * [0 1]'; % todo: plot significance on graph hold on; plotSEMBar( coreDiffRS, ytop , [0.5 0.5 0.5]); plotSEMBar( coreSubDiffRS, ytop+1, [0.5 0.5 0.5]); plotSEMBar( corePlastDiffRS, ytop+2, [0.5 0.5 0.5]); plotSEMBar( shellDiffRS, ytop+3, [ 1 0 0]); plotSEMBar( shellSubDiffRS, ytop+4, [ 1 0 0]); plotSEMBar(shellPlastDiffRS, ytop+5, [ 1 0 0]); plot([0 0], ylim, 'k--'); hold off; % redo y axis labels yt = get(gca,'YTick'); yt = [yt(yt < ytop) ytop:ytop+5]; ytl = cellfun(@(x) sprintf('%d',x),num2cell(yt),'UniformOutput',false); ytl(end-5:end) = {'Core','Core/Subsong','Core/Plastic','Shell','Shell/Subsong','Shell/Plastic'}; set(gca,'YTick',yt,'YTickLabel',ytl); % figure formatting xlabel(xlabels{ii}); ylabel('Count'); xlim([min(RSdiffBins) max(RSdiffBins)]); set(gca,'Box','off'); set(gca, 'FontSize', 14); set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); title(eiTitle{hh}); set(gcf,'Color',[1 1 1]); if params.saveplot saveCurrFigure(sprintf('figures/distanceCorrelations/RSdiffs-SUA-%s-%s.jpg', distanceTypes{ii}, filsuff{hh})); end end end %} %% JMA added this section to compare neurons with compiled cluster data for aa = 1: length(allNeuronCorrData) allNeuronCorrData(aa).intra_DistanceAll = allNeuronCorrData(aa).intra_DistanceAll';%these were in columns allNeuronCorrData(aa).inter_DistanceAll = allNeuronCorrData(aa).inter_DistanceAll'; allNeuronCorrData(aa).burstFraction = allNeuronCorrData(aa).burstFraction'; qq = zeros(allNeuronCorrData(aa).nSylls,1);%needed to do this to get cluster quality and syllable type for every syllable tt = zeros(allNeuronCorrData(aa).nSylls,1); qq(:,1) = deal(allNeuronCorrData(aa).clusterObjQ); tt(:,1) = deal(allNeuronCorrData(aa).syllID); allNeuronCorrData(aa).clusterObjQ = qq'; allNeuronCorrData(aa).syllID = tt'; end usablePairs = allNeuronCorrData(isPresel); usableClusterSessions = {usablePairs.sessionID}; [uUCSessions, ~, ~] = unique(usableClusterSessions); corrByNeuron = struct([]); for mm = 1: length(uUCSessions) isCurrentSession = strcmp(uUCSessions(mm),{usablePairs.sessionID}); currentSessionPairs = usablePairs(isCurrentSession); [neuronsHere, ~, ~] = unique([currentSessionPairs.unitNum]); for nn = 1: length(neuronsHere) isCurrentNeuron = [currentSessionPairs.unitNum] == neuronsHere(nn); currentNeuronPairs = currentSessionPairs(isCurrentNeuron); compiledNeuron.isCore = currentNeuronPairs(1).isCore; compiledNeuron.isMUA = currentNeuronPairs(1).isMUA; compiledNeuron.isPlastic = currentNeuronPairs(1).isPlastic; compiledNeuron.sessionID = currentNeuronPairs(1).sessionID; compiledNeuron.unitNum = currentNeuronPairs(1).unitNum; compiledNeuron.nSylls = sum([currentNeuronPairs.nSylls]); compiledNeuron.sigSyll = sum([currentNeuronPairs.sigResponse]); compiledNeuron.RSAll = horzcat([currentNeuronPairs.RSAll]); compiledNeuron.FRSyll = horzcat([currentNeuronPairs.FRSyll]); compiledNeuron.FRBase = horzcat([currentNeuronPairs.FRBase]); compiledNeuron.burstFraction = horzcat([currentNeuronPairs.burstFraction]); compiledNeuron.tutor_DistanceAll = horzcat([currentNeuronPairs.tutor_DistanceAll]); compiledNeuron.consensus_DistanceAll = horzcat([currentNeuronPairs.consensus_DistanceAll]); compiledNeuron.central_DistanceAll = horzcat([currentNeuronPairs.central_DistanceAll]); compiledNeuron.intra_DistanceAll = horzcat([currentNeuronPairs.intra_DistanceAll]); compiledNeuron.inter_DistanceAll = horzcat([currentNeuronPairs.inter_DistanceAll]); compiledNeuron.quality = horzcat([currentNeuronPairs.clusterObjQ]); compiledNeuron.syllID = horzcat([currentNeuronPairs.syllID]); numClassSyll = length(unique(compiledNeuron.syllID)); compiledNeuron.classSyll = deal(numClassSyll); corrByNeuron = [corrByNeuron; compiledNeuron]; end end isenoughSyll = [corrByNeuron.nSylls] > 39; %want at least 10 syllables in each quartile % usableNeuron = [corrByNeuron.sigSyll] > 0 & isenoughSyll; %neuron has to respond to at least one syllable cluster (but maybe shouldn't do this) usableNeuron = isenoughSyll; corrByNeuron = corrByNeuron(usableNeuron); %correlation of distance to response strength for bb = 1: length(corrByNeuron) yDist = corrByNeuron(bb).tutor_DistanceAll'; %can try other distances xRS = corrByNeuron(bb).RSAll'; %response strength, does it make sense to use firing rate? [linfit, ~,~,~, fitStats] = regress(yDist, [ones(numel(xRS),1) xRS]); %checked with corrcoef and gives same p value %if params.plot % figure % plot(xRS, yDist, 'k.', 'HandleVisibility', 'off'); % hold on; % plot(xRS, linfit(1) + xRS * linfit(2), '--','Color',[1 0 0]); % legend(sprintf('r^2 = %0.3g, F = %0.3g, p = %0.3g\n',... % fitStats(1), fitStats(2),fitStats(3))); % xlabel('Response Strength'); ylabel('Matched distance'); %end corrByNeuron(bb).linfit = linfit; corrByNeuron(bb).fitStats = fitStats; end isCore2 = [corrByNeuron.isCore]; CorrPRS = zeros(length(corrByNeuron),1); for cc = 1: length(corrByNeuron) CorrPRS(cc) = corrByNeuron(cc).fitStats(3); end isCorrel = CorrPRS < 0.05; cSC = isCore2 & isCorrel'; cSS = ~isCore2 & isCorrel'; fprintf('Number neurons with significant correlation of RS in core %s out of %s core neurons \n', num2str(sum(cSC)), num2str(sum(isCore2))) fprintf('Number neurons with significant correlation of RS in shell %s out of %s shell neurons \n', num2str(sum(cSS)), num2str(sum(~isCore2))) %correlation of distance to burst fraction for bb = 1: length(corrByNeuron) yDist = corrByNeuron(bb).tutor_DistanceAll'; xRS = corrByNeuron(bb).burstFraction'; [linfit, ~,~,~, fitStats] = regress(yDist, [ones(numel(xRS),1) xRS]); %checked with corrcoef and gives same p value corrByNeuron(bb).linfitBF = linfit; corrByNeuron(bb).fitStatsBF = fitStats; end isCore2 = [corrByNeuron.isCore]; CorrP = zeros(length(corrByNeuron),1); for cc = 1: length(corrByNeuron) CorrP(cc) = corrByNeuron(cc).fitStatsBF(3); end isCorrel = CorrP < 0.05; cSC = isCore2 & isCorrel'; cSS = ~isCore2 & isCorrel'; fprintf('Number neurons with significant correlation of BF in core %s out of %s core neurons \n', num2str(sum(cSC)), num2str(sum(isCore2))) fprintf('Number neurons with significant correlation of BF in shell %s out of %s shell neurons \n', num2str(sum(cSS)), num2str(sum(~isCore2))) %compare population response, standardized response to top and bottom 25% %similarity to tutor song for dd = 1: length(corrByNeuron) dists = corrByNeuron(dd).tutor_DistanceAll; %tutor_DistanceAll syllCV = nanstd(corrByNeuron(dd).FRSyll)/nanmean(corrByNeuron(dd).FRSyll); iqDists = prctile(dists, [25 75]); near_quartileFR = corrByNeuron(dd).FRSyll(dists < iqDists(1)); nQuartile = numel(near_quartileFR); far_quartileFR = corrByNeuron(dd).FRSyll(dists > iqDists(2)); fQuartile = numel( far_quartileFR); near_quartileFRBase = corrByNeuron(dd).FRBase(dists < iqDists(1)); far_quartileFRBase = corrByNeuron(dd).FRBase(dists > iqDists(2)); near_quartileBF = corrByNeuron(dd).burstFraction(dists < iqDists(1)); far_quartileBF = corrByNeuron(dd).burstFraction(dists > iqDists(2)); near_quartileDist = corrByNeuron(dd).tutor_DistanceAll(dists < iqDists(1)); far_quartileDist = corrByNeuron(dd).tutor_DistanceAll(dists > iqDists(2)); near_quartileQual = corrByNeuron(dd).quality(dists < iqDists(1)); far_quartileQual = corrByNeuron(dd).quality(dists > iqDists(2)); near_quartileType = corrByNeuron(dd).syllID(dists < iqDists(1)); far_quartileType = corrByNeuron(dd).syllID(dists > iqDists(2)); farQuart = nanmean(far_quartileDist); nearQuart = nanmean(near_quartileDist); farQual = nanmean(far_quartileQual); nearQual = nanmean(near_quartileQual); farTypes = length(unique(far_quartileType)); nearTypes = length(unique(near_quartileType)); nq_meanFR = nanmean(near_quartileFR); nq_varFR = nanvar(near_quartileFR); fq_meanFR = nanmean( far_quartileFR); fq_varFR = nanvar( far_quartileFR); nq_meanBF = nanmean(near_quartileBF); fq_meanBF = nanmean(far_quartileBF); nq_CV = nanstd(near_quartileFR)/nq_meanFR; fq_CV = nanstd(far_quartileFR)/fq_meanFR; nq_meanFRBase = nanmean(near_quartileFRBase); nq_varFRBase = nanvar(near_quartileFRBase); fq_meanFRBase = nanmean( far_quartileFRBase); fq_varFRBase = nanvar( far_quartileFRBase); [~, pVal, ~, tValStruct] = ttest2(near_quartileFR- near_quartileFRBase, far_quartileFR- far_quartileFRBase); tVal = tValStruct.tstat; fcovar = nancov(far_quartileFR,far_quartileFRBase);if numel(fcovar) > 1, fcovar = fcovar(2,1); end; ncovar = nancov(near_quartileFR,near_quartileFRBase);if numel(ncovar) > 1, ncovar = ncovar(2,1); end; aCovar = nancov(corrByNeuron(dd).FRSyll,corrByNeuron(dd).FRBase);if numel(aCovar) > 1, aCovar = aCovar(2,1); end; farZDenom = sqrt(fq_varFR + fq_varFRBase - 2*fcovar); nearZDenom = sqrt(nq_varFR + nq_varFRBase - 2*ncovar); farZ = ((fq_meanFR - fq_meanFRBase)* sqrt(fQuartile))/farZDenom; nearZ = ((nq_meanFR - nq_meanFRBase)* sqrt(nQuartile))/nearZDenom; allZDenom = sqrt(nanvar(corrByNeuron(dd).FRSyll) + nanvar(corrByNeuron(dd).FRBase) - 2*aCovar); allZ = ((nanmean(corrByNeuron(dd).FRSyll) - nanmean(corrByNeuron(dd).FRBase)) *sqrt(corrByNeuron(dd).nSylls))/allZDenom; corrByNeuron(dd).quartilePValue = pVal; corrByNeuron(dd).farZ = farZ; corrByNeuron(dd).nearZ = nearZ; corrByNeuron(dd).farCV = fq_CV; corrByNeuron(dd).nearCV = nq_CV; corrByNeuron(dd).nearBF = nq_meanBF; corrByNeuron(dd).farBF = fq_meanBF; corrByNeuron(dd).farQuart = farQuart; corrByNeuron(dd).nearQuart = nearQuart; corrByNeuron(dd).farQual = farQual; corrByNeuron(dd).nearQual = nearQual; corrByNeuron(dd).farTypes = farTypes; corrByNeuron(dd).nearTypes = nearTypes; corrByNeuron(dd).farTypeID = {unique(far_quartileType)}; corrByNeuron(dd).nearTypeID = {unique(near_quartileType)}; corrByNeuron(dd).syllCV = syllCV; corrByNeuron(dd).allZ = allZ; corrByNeuron(dd).BLFR = nanmean(corrByNeuron(dd).FRBase); corrByNeuron(dd).FR = nanmean(corrByNeuron(dd).FRSyll); end isQS = [corrByNeuron.quartilePValue] < 0.05; SQC = isCore2 & isQS; SQS = ~isCore2 & isQS; fprintf('Number neurons with significant difference in RS to near vs far in core %s out of %s core neurons \n', num2str(sum(SQC)), num2str(sum(isCore2))) fprintf('Number neurons with significant difference in RS to near vs far in shell %s out of %s shell neurons \n', num2str(sum(SQS)), num2str(sum(~isCore2))) meanFarZC = nanmean([corrByNeuron(isCore2).farZ]); meanFarZS = nanmean([corrByNeuron(~isCore2).farZ]); SEMFarC = nanstd([corrByNeuron(isCore2).farZ])/sqrt(length(corrByNeuron(isCore2))); SEMFarS = nanstd([corrByNeuron(~isCore2).farZ])/sqrt(length(corrByNeuron(~isCore2))); meanNearZC = nanmean([corrByNeuron(isCore2).nearZ]); meanNearZS = nanmean([corrByNeuron(~isCore2).nearZ]); SEMNearC = nanstd([corrByNeuron(isCore2).nearZ])/sqrt(length(corrByNeuron(isCore2))); SEMFarS = nanstd([corrByNeuron(~isCore2).nearZ])/sqrt(length(corrByNeuron(~isCore2))); % normalized RS values--not using this part dNormedRSFields = strcat(distanceTypes, '_dRSnorm'); for hh = 1:3 % inhibited, excited, all for ii = 1:numel(distanceTypes) % six of them figure; dRSNormed = [allNeuronCorrData.(dNormedRSFields{ii})]; if hh < 3 coreDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & isCore); shellDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & ~isCore); coreSubDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & isCore & ~isPlastic); shellSubDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & ~isCore & ~isPlastic); corePlastDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & isCore & isPlastic); shellPlastDiffRSNorm = dRSNormed(isPresel & isExcited == hh-1 & ~isCore & isPlastic); else coreDiffRSNorm = dRSNormed(isPresel & isCore); shellDiffRSNorm = dRSNormed(isPresel & ~isCore); coreSubDiffRSNorm = dRSNormed(isPresel & isCore & ~isPlastic); shellSubDiffRSNorm = dRSNormed(isPresel & ~isCore & ~isPlastic); corePlastDiffRSNorm = dRSNormed(isPresel & isCore & isPlastic); shellPlastDiffRSNorm = dRSNormed(isPresel & ~isCore & isPlastic); end fprintf('%s-normed %s: ', eiTitle{hh},xlabels{ii}); if ~(all(isnan( coreSubDiffRSNorm)) || ... all(isnan( corePlastDiffRSNorm)) || ... all(isnan( shellSubDiffRSNorm)) || ... all(isnan(shellPlastDiffRSNorm))) % significance tests: two-way anova, permuted % this function is not consistent with matlab's anovan, so it % won't be used until we can see why the inconsistency's there %[stats, df, pvals] = statcond(... % {noNaN( coreSubDiffRSNorm), noNaN( corePlastDiffRSNorm); ... % noNaN(shellSubDiffRSNorm), noNaN(shellPlastDiffRSNorm)}, ... %'mode','param'); % test against anova xx = [coreSubDiffRSNorm corePlastDiffRSNorm shellSubDiffRSNorm shellPlastDiffRSNorm]'; grps = [zeros(size(coreSubDiffRSNorm)) zeros(size(corePlastDiffRSNorm)) ... ones(size(shellSubDiffRSNorm)) ones(size(shellPlastDiffRSNorm)); ... zeros(size(coreSubDiffRSNorm)) ones(size(corePlastDiffRSNorm)) ... zeros(size(shellSubDiffRSNorm)) ones(size(shellPlastDiffRSNorm))]'; if isreal(xx) %JMA added [pAnova, tAnova] = anovan(xx,grps,'model','interaction','display', 'off'); fprintf(['\n\tANOVA (fixed model), 2-way: effect of core/shell, p = %0.2f, '... 'effect of subsong/plastic, p = %0.2f, interaction, p = %0.2f'], ... pAnova(1), pAnova(2), pAnova(3)) else fprintf('Skipping two-way permutation ANOVA'); end end % significance tests: post-hoc, core vs shell if ~isempty(coreDiffRSNorm) && ~isempty(shellDiffRSNorm) pc = signrank( coreDiffRSNorm); ps = signrank(shellDiffRSNorm); pMannU = ranksum(coreDiffRSNorm(~isnan(coreDiffRSNorm)), shellDiffRSNorm(~isnan(shellDiffRSNorm))); % no subsong/plastic significance tests fprintf(['\n\tsign-rank test p-value for core: %0.3f' ... '\n\tsign-rank test p-value for shell: %0.3f',... '\n\tMann-Whitney U test p-value for core v shell: %0.3f\n'],... pc,ps,pMannU); end % set bins for histogram RSdiffBins = -10:0.5:10; plotInterlaceBars(coreDiffRSNorm, shellDiffRSNorm, RSdiffBins); ytop = ylim * [0 1]'; % todo: plot significance on graph hold on; plotSEMBar( coreDiffRSNorm, ytop , [0.5 0.5 0.5]); plotSEMBar( shellDiffRSNorm, ytop+1, [ 1 0 0]); plotSEMBar( coreSubDiffRSNorm, ytop+2, [0.5 0.5 0.5]); plotSEMBar( shellSubDiffRSNorm, ytop+3, [ 1 0 0]); plotSEMBar( corePlastDiffRSNorm, ytop+4, [0.5 0.5 0.5]); plotSEMBar(shellPlastDiffRSNorm, ytop+5, [ 1 0 0]); plot([0 0], ylim, 'k--'); hold off; % redo y axis labels yt = get(gca,'YTick'); yt = [yt(yt < ytop) ytop:ytop+5]; ytl = cellfun(@(x) sprintf('%d',x),num2cell(yt),'UniformOutput',false); ytl(end-5:end) = {'Core','Shell','Core/Subsong','Shell/Subsong','Core/Plastic','Shell/Plastic'}; set(gca,'YTick',yt,'YTickLabel',ytl); % figure formatting xlabel(['normalized ' xlabels{ii}]); ylabel('Count'); legend(sprintf('CORE: n = %d', numel( coreDiffRSNorm(~isnan( coreDiffRSNorm)))),... sprintf('SHELL: n = %d', numel(shellDiffRSNorm(~isnan(shellDiffRSNorm))))); xlim([min(RSdiffBins) max(RSdiffBins)]); set(gca,'Box','off'); set(gca, 'FontSize', 14); set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); title(sprintf('%s, core/shell diff p = %0.2g, core from zero p = %0.2g, shell from zero p = %0.2g', eiTitle{hh}, pMannU, pc, ps)); set(gcf,'Color',[1 1 1]); %mean(coreDiffRSNorm) %mean(shellDiffRSNorm) %pause; if params.saveplot imFile = sprintf('figures/paper/distanceCorrelations-subjectiveScoreFilter/normedRSdiffs-SUA-%s-%s.pdf', distanceTypes{ii}, filsuff{hh}); fprintf('Writing image to %s', imFile); scrsz = get(0,'ScreenSize'); set(gcf, 'Position', [1 1 scrsz(3) scrsz(4)]); export_fig(imFile); % saveCurrFigure(sprintf('figures/A_keeper/mostResponsive/normedRSdiffs-SUA-%s-%s.jpg', distanceTypes{ii}, filsuff{hh})); end end end %{ fprintf('\n\np-values of FR correlation to distance types'); pFields = strcat(distanceTypes, 'Distance_p'); R2Fields = strcat(distanceTypes, 'DistanceR2'); xlabels = strcat({'Linear trend p-values of FR to '}, distanceDescriptions); for hh = 1:3 % inhibited, excited, all figure; for ii = 1:numel(distanceTypes) subplot(nR,nC,ii) corrPVals = [allNeuronCorrData.(pFields{ii})]; corrR2Vals = [allNeuronCorrData.(R2Fields{ii})]; if hh < 3 coreCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore); shellCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore); % get % variance explained [ coreR2M, coreR2SEM] = meanSEM(corrR2Vals(isPresel & isExcited == hh-1 & isCore)); [shellR2M, shellR2SEM] = meanSEM(corrR2Vals(isPresel & isExcited == hh-1 & ~isCore)); %coreSubCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore & ~isPlastic); %shellSubCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore & ~isPlastic); %corePlastCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore & isPlastic); %shellPlastCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore & isPlastic); else coreCPVs = corrPVals(isPresel & isCore); shellCPVs = corrPVals(isPresel & ~isCore); [ coreR2M, coreR2SEM] = meanSEM(corrR2Vals(isPresel & isCore)); [shellR2M, shellR2SEM] = meanSEM(corrR2Vals(isPresel & ~isCore)); %coreSubCPVs = corrPVals(isPresel & isCore & ~isPlastic); %shellSubCPVs = corrPVals(isPresel & ~isCore & ~isPlastic); %corePlastCPVs = corrPVals(isPresel & isCore & isPlastic); %shellPlastCPVs = corrPVals(isPresel & ~isCore & isPlastic); end % test the difference between core and shell pMannU = ranksum(coreCPVs(~isnan(coreCPVs)), shellCPVs(~isnan(shellCPVs))); fprintf('%s - %s: Mann-Whitney U p-value for core v shell: %0.3f\n',... eiTitle{hh}, xlabels{ii},pMannU); fprintf(['\tCore variance explained: %0.2f +/- %0.2f, '... 'shell variance explained: %0.2f +/- %0.2f\n'], ... coreR2M, coreR2SEM, shellR2M, shellR2SEM); pBins = logspace(-3,0,30); plotInterlaceBars(coreCPVs, shellCPVs, pBins); legend(sprintf('CORE: n = %d', numel( coreCPVs(~isnan( coreCPVs)))),... sprintf('SHELL: n = %d', numel(shellCPVs(~isnan(shellCPVs))))); xlabel(xlabels{ii}); ylabel('Count'); xlim([0 1]) % figure formatting set(gca, 'XTick', [0.05 0.1 0.2 0.4 0.6 0.8]); set(gca, 'Box', 'off'); set(gca, 'FontSize', 12); % xticklabel_rotate([],45); % this messes up the figure subplots set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); % todo: plot the significance markers ytop = ylim * [0 1]'; ylim([0 ytop+2]); hold on; plotSEMBar( coreCPVs, ytop-0.2, [0.5 0.5 0.5]); plotSEMBar(shellCPVs, ytop-0.1, [1 0 0]); hold off; end subplot(nR,nC,1); title(eiTitle{hh}); set(gcf,'Color',[1 1 1]); if params.saveplot saveCurrFigure(sprintf('figures/distanceCorrelations/neuronDistanceCorr-SUA-%s.jpg', filsuff{hh})); end end %} end function [m, v] = meanSEM(set1) m = nanmean(set1); if numel(set1) >= 2 v = nanstd(set1 )/sqrt(numel(set1)-1); else v = 0; end end % plot the error bars w/ SEM on top function plotSEMBar(set, y, col) [m,v] = meanSEM(set); plotHorzErrorBar(m,y,v,col); end function x = noNaN(x) x(isnan(x)) = []; end
github
BottjerLab/Acoustic_Similarity-master
mosaicDRSpec.m
.m
Acoustic_Similarity-master/code/plotting/mosaicDRSpec.m
3,635
utf_8
35303eb898e6dba8e08964640e85f3e2
function [hf, hims] = mosaicDRSpec(DRevents, params, varargin) hf = []; if isempty(DRevents) warning('mosaicDRspec:noClips', 'No clips input or maxLength is smaller than clip'); return; end if nargin < 2 || isempty(params) params = defaultParams; end params = processArgs(params,varargin{:}); % make sure we only have the clips we want clLens = [DRevents.stop]-[DRevents.start]; cumLens = cumsum(clLens); if ~isinf(params.maxMosaicLength) && cumLens(end) > params.maxMosaicLength cutoff = find(cumLens < params.maxMosaicLength, 1, 'last'); cumLens = cumLens(1:cutoff); clLens = clLens(1:cutoff); DRevents = DRevents(1:cutoff); end % extend by any roll DRevents = addPrePost(DRevents, params); % make one long clip... nEv = numel(DRevents); cl = cell(1, nEv); fs = zeros(1,nEv); %params = processArgs(params, 'noroll'); % strict boundaries for ii = 1:nEv [cl{ii}, fs(ii)] = getClipAndProcess([],DRevents(ii), params, 'noroll'); % TEMP: readjust lengths (bugfix until we can fix noiseGate chopping % problem) clLens(ii) = numel(cl{ii}) / fs(ii); end cumLens = cumsum(clLens); if isempty(fs) warning('mosaicDRspec:noClips', 'No clips input or maxLength is smaller than clip'); return end if ~all(fs==fs(1)) error('mosaicDRSpec:variableSampling', ... 'Different sampling frequencies in each clip...'); end fs = fs(1); %% maxClipLen = params.mosaicRowLength; %seconds nLowPlots = floor(cumLens(end)/maxClipLen); concatCl = cell(1,nLowPlots); idxRange = 1:find(cumLens < maxClipLen, 1,'last'); params.fine.fs=fs; refRanges = cell(1,nLowPlots); ii = 1; while ~isempty(idxRange) && (idxRange(end) <= nEv || isempty(concatCl)) % concatenate clip concatCl{ii} = vertcat(cl{idxRange}); refRanges{ii} = idxRange; idxRange = (idxRange(end)+1):find(cumLens < maxClipLen + cumLens(idxRange(end)), 1, 'last'); ii = ii+1; end % for display purposes - 1/3 rows is the most proportional for spectrogram % display nPlots = max(3,numel(concatCl)); %maxClipLen = max(cellfun(@numel, concatCl)); for ii = 1:min(nPlots, numel(concatCl)); % calculate and plot spectrogram - todo: more space, less ticks... %subplot(nPlots,1,ii); % handle all plots to scale - 3rd entry has normalized unit of length hh(ii) = subplot('Position',[0 (nPlots-ii)/nPlots (length(concatCl{ii})/fs)/maxClipLen 1/nPlots]); spectrum = getMTSpectrumStats(concatCl{ii}, params.fine); hims(ii) = plotDerivGram(spectrum,params); % plot vertical separators yy = ylim; xpts = cumsum(clLens(refRanges{ii})); xpts(end) = []; % don't need the last one b/c it's already at the boundary hold on; for jj = 1:numel(xpts) plot(xpts(jj) * [1 1], yy,'w-','LineWidth',2); end % plot a small time scale bar if ii == 1 xx = xlim; xSB = xx * [0.95 0.05]'; fracBar = 0.04; xSBEnd = xx * [(0.95 - fracBar) (0.05 + fracBar)]'; ySB = yy * [0.15 0.85]'; textH = yy * [0.24 0.76]'; SBlen = roundn(maxClipLen * 1000 * fracBar, 10); % 1/25th of the bar in milliseconds, 10 ms length intervals; plot([xSB, xSBEnd], [ySB, ySB], 'g-', 'LineWidth', 2); text(xSB, textH, sprintf('%d ms', SBlen),'FontWeight','bold',... 'HorizontalAlignment','left','VerticalAlignment','bottom'); hold off; end % remove axes set(gca,'YTickLabel',[],'YTick',[]); set(gca,'XTickLabel',[],'XTick',[]); end % reset for title placement axes(hh(1)) hf = gcf; end function x = roundn(x,y) % round to the nearest y x = round(x/y)*y; end
github
BottjerLab/Acoustic_Similarity-master
editEventsLabel.m
.m
Acoustic_Similarity-master/code/plotting/editEventsLabel.m
19,214
utf_8
243ddcd2f4ac2fdfade6c2cc2032a578
function evsNew = editEventsLabel(evs,fs,doLabel) % EDITEVENTSLABEL(EVS) % This function allows the user to edit event boundaries and labels. % % The function plots a set of gray patches over each event in the active % figure. Usually a waveform or some other line plot pertaining to % the signal should be behind it. % The user can left-click and drag on events to adjust either the onset, % offset, or both. The user can also right-click on events to relabel % them. Clicking and dragging on a space without an event will create % a new event, while dragging the boundaries of an event past each other % results in deletion. % % For the purpose of this % % Known issues: % 1) Cursor may jump to the wrong side if patches are too close together % 2) Can be slow if surface data is being displayed in same figure % 3) If slow and you try to type a label too soon, focus moves to command window % 4) Events cnnot be added when no events exist? % Prereqs: active figure/axes that are appropriate to have marks % evs is properly sorted % TODO: link callbacks so that drags can be performed everywhere % figure out a way to draw patches smartly over the spectrograms % NB: for resizing to work properly, the axes property 'Units' should be % normalized % housekeeping, removing warning RGBWarnID = 'MATLAB:hg:patch:RGBColorDataNotSupported'; warnState = warning('query',RGBWarnID); warning('off',RGBWarnID'); if nargin < 3 doLabel = false; end % setting some defaults for sampling rate if isempty(evs), evs = initEvents; if nargin < 2 fs = 44100; % FIXME: a pure guess warning('editEvents:InputUninitialized','Events uninitialized, sampling rate may be incorrect...'); end else if nargin < 2 fs = evs(1).idxStart/evs(1).start; end end greycol = [0.75 0.75 0.75]; % inform user of termination behavior oldTitle = get(get(gca,'Title'),'String'); newTitle = [oldTitle ' - Double click outside figure to exit and save, double click to play sound']; if doLabel, newTitle = [newTitle ', right click to relabel']; end; title(newTitle); % hide any other patch handles that are being used here otherPatchesOnAxis = findobj('Type','patch','Parent',gca); set(otherPatchesOnAxis,'visible','off'); % create patch handle if isempty(evs) % create a fake event and then delete it later hp = plotAreaMarks(initEvents(1),greycol); else hp = plotAreaMarks(evs,greycol); end % prepare handle for axes hax = gca; % give the label information to the patch handles set(hp,'UserData',struct('labels', [evs.type])); % transform labels into text objects if doLabel drawLabelsInit(hp); end % some notes on action: % when in drag mode, data gets added to the patch's userData field % when changing labels, the data gets changed in the patch's userData.labels field set(gcf,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); set(gcf,'WindowButtonUpFcn',{@buttonUpFcn, [hax hp]}); set(gcf,'WindowButtonDownFcn',{@buttonDownFcn, [hax hp]}); % exit is triggered when mouseUp occurs outside the axis window disp('Click outside to finish...'); waitfor(gcf,'WindowButtonMotionFcn',''); disp('Wrapping up...'); % clean up - restore any changed properties title([oldTitle ' - Finishing']); warning(warnState.state,RGBWarnID); % read the events back from the edited patch handle xdat = get(hp,'XData'); evsNew = initEvents(size(xdat,2)); if isempty(xdat), return; end; % return an empty event structure if no marks starts = num2cell(xdat(2,:)); idxStarts = num2cell(floor(xdat(2,:) * fs)); stops = num2cell(xdat(3,:)); idxStops = num2cell( ceil(xdat(3,:) * fs)); [evsNew.start] = starts{:}; [evsNew.stop] = stops{:}; [evsNew.idxStart] = idxStarts{:}; [evsNew.idxStop] = idxStops{:}; [evsNew.type] = deal(NaN); if doLabel % retrieve the labels labelHandles = getfield(get(hp,'UserData'),'labels'); textLabels = get(labelHandles,'String'); if ~iscell(textLabels), textLabels = {textLabels}; end; [evsNew.type] = textLabels{:}; % get rid of the old text labels delete(labelHandles); set(otherPatchesOnAxis,'XData',get(hp,'XData'),'visible','on'); end % get rid of the old patch delete(hp); % if we had an empty event structure to begin with, remove the placeholder % first structure if isempty(evs) evsNew(1) = []; end title(oldTitle); %%%%%%%% begin callbacks %%%%%%%%%%%%% function mouseOverFcn(gcbo, eventdata, handles) % some default colors greyCol = [0.75 0.75 0.75]; hiCol = [0.5 0.5 0.5]; lineCol = [0.8 0 0]; % unpack handles hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currPt = currPt(1,1:2); nFaces = size(get(hp,'XData'),2); vertexColors = greyCol(ones(4 * nFaces,1),:); [patchHover, lineHover] = clickStatus(currPt, handles); if ~isempty(patchHover) % highlight that patch vertexColors(patchHover * 4 - 3,:) = hiCol; if ~isempty(lineHover) %vertexColors(patchHover * 4 + [-2,0],:) = lineCol(ones(2,1),:); currXData = get(hp,'XData'); cursor(currXData(1+lineHover,patchHover),'on'); else cursor(0,'off'); end else cursor(0,'off'); end set(hp,'FaceVertexCData',vertexColors); end function cursor(xpos, status) lineHandle = findobj('Tag','cursor'); if isempty(lineHandle) line([xpos xpos], ylim,'Color',lineCol,'Tag','cursor','LineWidth',1.5); elseif strcmp(status, 'off') && strcmp(get(lineHandle,'visible'), 'on') set(lineHandle,'visible','off'); elseif strcmp(status, 'on') set(lineHandle,'XData',[xpos xpos],'visible',status); end end function buttonUpFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); % get point relative to window to determine if click lies outside currPt = get(gcbo,'CurrentPoint'); currPt(1,1:2); oldUnits = get(gca,'Units'); set(gca,'Units','pixels'); axisWindow = get(hax,'Position'); set(gca,'Units',oldUnits); % return cursor to original look setptr(gcf,'arrow'); % exiting function - did we double-click outside the figure and % not as part of a drag? if ~inRect(axisWindow, currPt) && ~isfield(get(hp,'UserData'),'lineHeld') && ... strcmp(get(gcbo,'SelectionType'),'open') % clearing the callbacks is the signal for the program to exit set(gcbo,'WindowButtonMotionFcn',''); set(gcbo,'WindowButtonUpFcn',''); set(gcbo,'WindowButtonDownFcn',''); elseif isfield(get(hp,'UserData'),'patchHeld') % finished clicking on an event % remove the data not pertaining to labels userData = get(hp,'UserData'); set(hp,'UserData',struct('labels',userData.labels,'lastClicked',userData.patchHeld)); %(1) negative intervals - delete %(2) overlapping intervals - merge resolveOverlaps(hp); set(gcbo,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); else % clear last Clicked field userData = get(hp,'UserData'); set(hp,'UserData',struct('labels',userData.labels)); % leave only the labels end % links patches from other plots - a bit hacky, assumes all plots % hold same patch pattern % note that a naive linkprop doesn't work because we need the size of % yData/colorData to vary dynamically % TODO: dynamically activate/deactivate linkprop otherPatches = findobj(gcbo, 'Type', 'patch'); for ii = 1:numel(otherPatches) otherYData = get(otherPatches(ii),'YData'); otherYData = otherYData(:,ones(1,size(get(hp,'YData'),2))); set(otherPatches(ii),'XData',get(hp,'XData'),... 'YData',otherYData,... 'FaceVertexCData',get(hp,'FaceVertexCData')); end % refresh labels if doLabel repositionLabels(hp); end end function buttonDownFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currPt = currPt(1,1:2); [patchClicked, lineClicked, hitWindow] = clickStatus(currPt, handles); if ~hitWindow, return; end; if doLabel && strcmp(get(gcbo,'SelectionType'),'alt') % if a right click, rename if ~isempty(patchClicked) textHandles = getfield(get(hp,'UserData'),'labels'); set(textHandles(patchClicked),'Editing','on'); end elseif strcmp(get(gcbo,'SelectionType'),'extend') % middle click disp('Debug Mode:'); keyboard; % profile viewer; % profile on; % pause; elseif strcmp(get(gcbo,'SelectionType'),'open') % double click detection? play a sound % let people know we're working while we load the clip % set(gcf,'Pointer','watch'); % disp('Clock on'); % % get the clip data hline = findobj(hax,'Type','line'); hline = hline(end); % it should be the one furthest back xWave = get(hline,'XData'); yWave = get(hline,'YData'); if isempty(patchClicked) % what should we do if a patch is not clicked? % play the whole clip playSound(yWave, fs, true); else % get the borders currXData = get(hp, 'XData'); patchBorders = currXData(2:3,patchClicked); % cut the clip at the right points clipStart = find(xWave >= patchBorders(1),1); clipEnd = find(xWave >= patchBorders(2),1); clip = yWave(clipStart:clipEnd); % play the sound clip, while blocking playSound(clip, fs, true); end % ok, waiting's up % disp('Clock off'); % set(gcf,'Pointer', 'arrow'); elseif isempty(patchClicked) % clicked on an empty space % create new event currXData = get(hp, 'XData'); currYData = get(hp, 'YData'); currVertexColors = get(hp, 'FaceVertexCData'); userData = get(hp,'UserData'); % find where to insert new event if ~all(isnan(currXData)) insertPt = find(currPt(1) <= [currXData(1,:) Inf], 1); currXData = [currXData(:,1:insertPt-1) currPt(1)*ones(4,1) currXData(:,insertPt:end)]; currYData = currYData(:,[1 1:end]); %all columns are the same currVertexColors = currVertexColors([ones(1,4) 1:end], :);% we need four more rows, but the colors are all the same if doLabel newTextHandle = createTextLabel(currPt(1), ' '); userData.labels = [userData.labels(:,1:insertPt-1) newTextHandle userData.labels(:,insertPt:end)]; end else % currXData is filled with a NaN box so that insertPt is not % consistent with adding into an empty array insertPt = 1; currXData = currPt(1) * ones(4,1); currYData = [ylim fliplr(ylim)]'; if doLabel newTextHandle = createTextLabel(currPt(1), ' '); userData.labels=newTextHandle; end end set(hp,'XData',currXData,'YData',currYData,'FaceVertexCData',currVertexColors); % handle dragging dragData = struct('lineHeld', [], ... 'startPt', currPt, ... 'patchHeld', insertPt, ... 'justCreated', true, ... 'origBounds', currPt(1)*ones(4,1), ... 'labels', userData.labels); % dragging data gets added to the patch userData set(hp,'UserData',dragData); set(gcf,'WindowButtonMotionFcn',{@draggingFcn, [hax hp]}); % set the cursor look setptr(gcf, 'fullcrosshair'); else % we clicked on a patch xBounds = get(hp,'XData'); userData = get(hp,'UserData'); dragData = struct('lineHeld', lineClicked, ... 'startPt', currPt, ... 'patchHeld', patchClicked,... 'justCreated', false,... 'origBounds', xBounds(:,patchClicked),... 'labels', userData.labels); set(hp,'UserData',dragData); set(gcf,'WindowButtonMotionFcn',{@draggingFcn, [hax hp]}); % set cursor look if ~isempty(lineClicked) setptr(gcf,'fullcrosshair'); else setptr(gcf,'hand'); end end end function draggingFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currXData = get(hp,'XData'); userData = get(hp, 'UserData'); %nFaces = size(currXData,2); if ~isfield(userData,'patchHeld') || isempty(userData.patchHeld) error('editEvents:PatchNotClicked','Patch not Clicked, drag callback should not be set'); end if userData.justCreated % if we just created an event, detect the drag motion if currPt(1) ~= userData.startPt(1) userData.justCreated = false; userData.lineHeld = 1 + (currPt(1) > userData.startPt(1)); end end if ~isempty(userData.lineHeld) % moving one edge of the eventdata rIdxs = 2 * userData.lineHeld + [-1 0]; currXData(rIdxs,userData.patchHeld) = currPt(1); set(hp,'XData',currXData); cursor(currPt(1),'on'); % detect collisions immediately and quit drag if detectCollision(hp,userData.patchHeld,userData.lineHeld), set(gcbo,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); resolveOverlaps(hp); cursor(0,'off'); end else % moving whole event currXData(:,userData.patchHeld) = userData.origBounds + currPt(1) - userData.startPt(1); set(hp,'XData',currXData); end if doLabel repositionLabels(hp); end end %%%%%%%% end callbacks %%%%%%%%%%%%% function didCollide = detectCollision(patchHandle,activePatch, boundarySide) currXData = get(patchHandle,'XData'); if isempty(currXData), return; end; % nothing to collide borders = currXData(2:3,:); nFaces = size(borders,2); adjBorder = NaN; if activePatch > 1 && boundarySide == 1 adjBorder = borders(2,activePatch - 1); elseif activePatch < nFaces && boundarySide == 2 adjBorder = borders(1,activePatch + 1); end didCollide = (borders(1,activePatch) >= borders(2,activePatch)) || ... borders(boundarySide,activePatch) <= adjBorder && boundarySide == 1 || ... borders(boundarySide,activePatch) >= adjBorder && boundarySide == 2; end function repositionLabels(hp) userData = get(hp,'UserData'); currXData = get(hp,'XData'); nFaces = size(currXData,2); for ii = 1:nFaces labelPos = get(userData.labels(ii),'Position'); labelPos(1) = mean(currXData(:,ii)); set(userData.labels(ii),'Position', labelPos); end end function resolveOverlaps(patchHandle) % cleans up intervals %keeping colors the same greyCol = [0.75 0.75 0.75]; currXData = get(patchHandle,'XData'); currYData = get(patchHandle,'YData'); %currColData = get(patchHandle,'FaceVertexCData'); if isempty(currXData), return; end; % nothing to resolve borders = currXData(2:3,:); userData = get(patchHandle,'UserData'); % remove any negative-length intervals isNonPosLength = (borders(1,:) >= borders(2,:)); borders(:,isNonPosLength) = []; % remove their label if doLabel delete(userData.labels(isNonPosLength)); userData.labels(isNonPosLength) = []; end % merge overlapping regions % since the number of regions is probably small (<10), we'll do this in a % naive way (better is with interval trees) ii = 1; nFaces = size(borders,2); while ii <= nFaces && nFaces > 1 toMerge = find(borders(1,ii) >= borders(1,:) & borders(1,ii) <= borders(2,:) | ... borders(2,ii) >= borders(1,:) & borders(2,ii) <= borders(2,:)); if numel(toMerge) > 1 borders(1,ii) = min(borders(1,toMerge)); borders(2,ii) = max(borders(2,toMerge)); toDelete = toMerge(toMerge ~= ii); % remove patch information borders(:,toDelete) = []; % remove labels if doLabel delete(userData.labels(toDelete)); userData.labels(toDelete) = []; end % get resized # of patches nFaces = size(borders,2); else ii = ii + 1; end end if ~isempty(borders) currXData = borders([1 1 2 2],:); currYData = currYData(:,ones(1,nFaces)); % just copy the first row currColData = greyCol(ones(4*nFaces,1),:); % just copy the first color else currXData = NaN(4,1); currColData = greyCol(ones(4,1),:); currYData = NaN(4,1); end set(patchHandle,'XData',currXData,'YData',currYData,'FaceVertexCData',currColData,'UserData',userData); end function foo = inRect(win, pt) foo = win(1) <= pt(1) && pt(1) < win(1) + win(3) && ... win(2) <= pt(2) && pt(2) < win(2) + win(4); end function [patchSeld, lineSeld, hitWindow] = clickStatus(currPt, handles) % returns empties on default patchSeld = []; lineSeld = []; hax = handles(1); hp = handles(2); win([1 3]) = get(hax,'XLim'); win(3) = win(3) - win(1); win([2 4]) = get(hax,'YLim'); win(4) = win(4) - win(2); hitWindow = inRect(win, currPt); if ~hitWindow, return, end; % how 'fat' should our edge be for us to highlight/grab it? edgeFuzzFrac = 3e-3; edgeFuzz = diff(get(hax,'XLim')) * edgeFuzzFrac; yy = get(hax,'YLim'); if currPt(2) > yy(2) || currPt(2) < yy(1), return; end; xBounds = get(hp,'XData'); if isempty(xBounds), return; end; % nothing to click xBounds = xBounds(2:3,:); patchSeld = ... find(xBounds(1,:) - edgeFuzz <= currPt(1) & ... xBounds(2,:) + edgeFuzz >= currPt(1)); if numel(patchSeld) > 1 % find the one which is closer distsToCursor = min(xBounds(1,patchSeld) - currPt(1)); [~,closest] = min(distsToCursor); patchSeld = patchSeld(closest); end if ~isempty(patchSeld) if abs(xBounds(1,patchSeld) - currPt(1)) <= edgeFuzz, lineSeld = 1; elseif abs(xBounds(2,patchSeld) - currPt(1)) <= edgeFuzz, lineSeld = 2; end end end function drawLabelsInit(patchHandle) %prereq: userdata is already set with labels %converts labels to a set of txthandles currXData = get(patchHandle,'XData'); borders = currXData(2:3,:); nFaces = size(borders,2); userData = get(patchHandle,'UserData'); isString = ischar(userData.labels); txthandles = zeros(1,nFaces); for ii = 1:nFaces % convert to string if necessary thisLabel = userData.labels(ii); if ~isString, thisLabel = num2str(thisLabel); end txthandles(ii) = createTextLabel(mean(borders(:,ii)),thisLabel); end % labels is cell userData.labels = txthandles; set(patchHandle,'UserData',userData); end end
github
BottjerLab/Acoustic_Similarity-master
plotNeuronCorrDataBoxPlot.m
.m
Acoustic_Similarity-master/code/plotting/plotNeuronCorrDataBoxPlot.m
10,340
utf_8
ac60482f5dcd5bdd9734c2fa9c47fa86
function plotNeuronCorrData(params, varargin) if nargin < 1 || isempty(params) params = defaultParams; end params = processArgs(params, varargin{:}); % plot excited difference between firing rates for near tutor/far from tutor % and also p-values for correlations between neurons and firing rates allNeuronCorrData = []; load('data/allNeuronCorrelations.mat'); %% flags isCore = [allNeuronCorrData.isCore]; isMUA = [allNeuronCorrData.isMUA]; isPlastic = [allNeuronCorrData.isPlastic]; isSignificant = [allNeuronCorrData.sigResponse]; %isSignificant = true(1,numel(allNeuronCorrData)); isExcited = [allNeuronCorrData.isExcited]; isPresel = isSignificant & ~isMUA; RSdiffBins = -10:0.2:10; % subplot rows / columns nR = 3; nC = 2; % measures distanceTypes = {'tutor', 'intra', 'inter', 'consensus', 'central','humanMatch'}'; distanceDescriptions = {'closest tutor', 'cluster center', 'normed center', ... 'closest tutor to cluster consensus', 'closest tutor to cluster center', 'expert-designated tutor'}; dFields = [strcat(distanceTypes, '_nearMeanRS') strcat(distanceTypes, '_farMeanRS')]; eiTitle = {'Significantly inhibited single unit-syllable pairs', ... 'Significantly excited single unit-syllable pairs', ... 'All significant single unit-syllable pairs'}; xlabels = strcat({'RS for near - far to '}, distanceDescriptions); filsuff = {'inh','exc','all'}; %% for hh = 1:3 % inhibited, excited, all for ii = 1:numel(distanceTypes) % six of them figure; diffTutorMeanRS = [allNeuronCorrData.(dFields{ii,1})] - [allNeuronCorrData.(dFields{ii,2})]; if hh < 3 coreDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & isCore); shellDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & ~isCore); coreSubDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & isCore & ~isPlastic); shellSubDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & ~isCore & ~isPlastic); corePlastDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & isCore & isPlastic); shellPlastDiffRS = diffTutorMeanRS(isPresel & isExcited == hh-1 & ~isCore & isPlastic); else coreDiffRS = diffTutorMeanRS(isPresel & isCore); shellDiffRS = diffTutorMeanRS(isPresel & ~isCore); coreSubDiffRS = diffTutorMeanRS(isPresel & isCore & ~isPlastic); shellSubDiffRS = diffTutorMeanRS(isPresel & ~isCore & ~isPlastic); corePlastDiffRS = diffTutorMeanRS(isPresel & isCore & isPlastic); shellPlastDiffRS = diffTutorMeanRS(isPresel & ~isCore & isPlastic); end pc = signrank( coreDiffRS); ps = signrank(shellDiffRS); pMannU = ranksum(coreDiffRS(~isnan(coreDiffRS)), shellDiffRS(~isnan(shellDiffRS))); fprintf(['%s-%s:\n\tsign-rank test p-value for core: %0.3f' ... ' \n\tsign-rank test p-value for shell: %0.3f',... ' \n\tMann-Whitney U test p-value for core v shell: %0.3f\n'],... eiTitle{hh},xlabels{ii},pc,ps,pMannU); % clunky way just to get the top histogram value plotInterlaceBars(coreDiffRS, shellDiffRS, RSdiffBins, pMannU < 0.05); ytop = ylim * [0 1]'; % plot boxplots above - b/c of boxplot behavior, this eliminates % the histograms grps = [ones(size(coreDiffRS)) 2*ones(size(coreSubDiffRS)) 3*ones(size(corePlastDiffRS)) ,... 4*ones(size(shellDiffRS)), 5*ones(size(shellSubDiffRS)) 6*ones(size(shellPlastDiffRS))]; dats = [coreDiffRS coreSubDiffRS corePlastDiffRS shellDiffRS shellSubDiffRS shellPlastDiffRS]; boxplot(gca, dats, grps, 'orientation', 'horizontal', 'notch','on','positions', ytop:ytop+5, ... 'colors', [0.5 * ones(3); [1 1 1]' * [1 0 0]]); % plot histograms underneath again hold on; plotInterlaceBars(coreDiffRS, shellDiffRS, RSdiffBins, pMannU < 0.05); ylim([0 ytop+6]); plot([0 0], ylim,'k--','HandleVisibility','off'); legend(sprintf('CORE: n = %d', numel( coreDiffRS(~isnan( coreDiffRS)))),... sprintf('SHELL: n = %d', numel(shellDiffRS(~isnan(shellDiffRS))))) %{ plotSEMBar( coreDiffRS, ytop , [0.5 0.5 0.5]); plotSEMBar( coreSubDiffRS, ytop+1, [0.5 0.5 0.5]); plotSEMBar( corePlastDiffRS, ytop+2, [0.5 0.5 0.5]); plotSEMBar( shellDiffRS, ytop+3, [ 1 0 0]); plotSEMBar( shellSubDiffRS, ytop+4, [ 1 0 0]); plotSEMBar(shellPlastDiffRS, ytop+5, [ 1 0 0]); %} % redo y axis labels yt = get(gca,'YTick'); yt = [yt(yt < ytop) ytop:ytop+5]; ytl = cellfun(@(x) sprintf('%d',x),num2cell(yt),'UniformOutput',false); ytl(end-5:end) = {'Core','Core/Subsong','Core/Plastic','Shell','Shell/Subsong','Shell/Plastic'}; set(gca,'YTick',yt,'YTickLabel',ytl); % figure formatting xlabel(xlabels{ii}); ylabel('Count'); xlim([-10 10]); set(gca,'Box','off'); set(gca, 'FontSize', 14); set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); title(eiTitle{hh}); set(gcf,'Color',[1 1 1]); hold off; if params.saveplot saveCurrFigure(sprintf('figures/distanceCorrelations/RSdiffs-SUA-box-%s-%s.jpg', distanceTypes{ii}, filsuff{hh})); end end end pFields = strcat(distanceTypes, 'Distance_p'); xlabels = strcat({'Linear trend p-values of FR to '}, distanceDescriptions); for hh = 1:3 % inhibited, excited, all figure; for ii = 1:numel(distanceTypes) subplot(nR,nC,ii) corrPVals = [allNeuronCorrData.(pFields{ii})]; if hh < 3 coreCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore); shellCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore); %coreSubCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore & ~isPlastic); %shellSubCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore & ~isPlastic); %corePlastCPVs = corrPVals(isPresel & isExcited == hh-1 & isCore & isPlastic); %shellPlastCPVs = corrPVals(isPresel & isExcited == hh-1 & ~isCore & isPlastic); else coreCPVs = corrPVals(isPresel & isCore); shellCPVs = corrPVals(isPresel & ~isCore); %coreSubCPVs = corrPVals(isPresel & isCore & ~isPlastic); %shellSubCPVs = corrPVals(isPresel & ~isCore & ~isPlastic); %corePlastCPVs = corrPVals(isPresel & isCore & isPlastic); %shellPlastCPVs = corrPVals(isPresel & ~isCore & isPlastic); end pMannU = ranksum(coreCPVs(~isnan(coreCPVs)), shellCPVs(~isnan(shellCPVs))); fprintf('%s - %s: Mann-Whitney U p-value for core v shell: %0.3f\n',... eiTitle{hh}, xlabels{ii},pMannU); pBins = logspace(-3,0,30); plotInterlaceBars(coreCPVs, shellCPVs, pBins, pMannU < 0.05); legend(sprintf('CORE: n = %d', numel( coreCPVs(~isnan( coreCPVs)))),... sprintf('SHELL: n = %d', numel(shellCPVs(~isnan(shellCPVs))))); xlabel(xlabels{ii}); ylabel('Count'); xlim([0 1]) set(gca, 'XTick', [0.01 0.05 0.1 0.2 0.4 0.6 0.8]); set(gca, 'Box', 'off'); set(gca, 'FontSize', 11); set(get(gca,'XLabel'),'FontSize', 14); set(get(gca,'YLabel'),'FontSize', 14); set(get(gca,'Title' ),'FontSize', 14); ytop = ylim * [0 1]'; ylim([0 ytop+2]); plotSEMBar( coreCPVs, ytop, [0.5 0.5 0.5]); plotSEMBar(shellCPVs, ytop, [1 0 0]); end subplot(nR,nC,1); title(eiTitle{hh}); set(gcf,'Color',[1 1 1]); if params.saveplot saveCurrFigure(sprintf('figures/distanceCorrelations/neuronDistanceCorr-SUA-%s.jpg', filsuff{hh})); end end end function plotInterlaceBars(setCore, setShell, bins, sigLevel) % core plotted in gray, shell plotted in red % run mann-whitney u test [p,h] = ranksum(setCore, setShell); binTol = 1e-5; hCore = histc(setCore , bins); hShell = histc(setShell, bins); %[m1 sem1] = meanSEM( setCore); %[m2 sem2] = meanSEM(setShell); holdState = ishold; if all(diff(bins) - (bins(2) - bins(1)) < binTol) bw = bins(2) - bins(1); bar(bins, hCore, 0.5, 'FaceColor', [0.5 0.5 0.5]); hold on; bar(bins+bw/2, hShell, 0.5, 'r'); else bw = diff(bins); bw = [bins(1)/2 bw bw(end)]; % make visible legend groups ghCore = hggroup; ghShell = hggroup; set(get(get(ghCore , 'Annotation'),'LegendInformation'), 'IconDisplayStyle','on'); set(get(get(ghShell, 'Annotation'),'LegendInformation'), 'IconDisplayStyle','on'); for ii = 1:numel(bins) % draw histogram bin by bin % core bin xl = bins(ii) - bw(ii)/2; xr = bins(ii); yd = 0; yu = hCore(ii); patch([xl xl; xl xr; xr xr], [yd yu; yu yu; yd yd], [0.5 0.5 0.5],... 'EdgeColor','none', 'Parent', ghCore); hold on; % shell bins xl = bins(ii); xr = bins(ii) + bw(ii+1)/2; yd = 0; yu = hShell(ii); patch([xl xl; xl xr; xr xr], [yd yu; yu yu; yd yd], [1 0 0],... 'EdgeColor','none', 'Parent', ghShell); end end % plot the error bars w/ SEM on top %{ ylims = ylim; top = ylims(2) + 2; ylim([0 top]); plotHorzErrorBar(m1, top - 0.8, sem1, [0.5 0.5 0.5]); plotHorzErrorBar(m2, top - 1.2, sem2, [1 0 0]); if sigLevel > 0 plot(mean([m1 m2]), top-1, 'k*','MarkerSize',8); end %} if ~ishold hold off end end function [m, v] = meanSEM(set1) m = nanmean(set1); v = nanstd(set1 )/sqrt(numel(set1)-1); end function plotSEMBar(set, y, col) [m,v] = meanSEM(set); plotHorzErrorBar(m,y,v,col); end function plotHorzErrorBar(x, y, xwidth, col) yh = 0.02*diff(ylim); xx = [x-xwidth x+xwidth NaN x-xwidth x-xwidth NaN x+xwidth x+xwidth]; yy = [y y NaN y-yh y+yh NaN y-yh y+yh]; plot(xx,yy, '-','Color', col, 'LineWidth', 1.5); %hold on; %plot(x,y,'.','MarkerSize', 16, 'Color', col); end
github
BottjerLab/Acoustic_Similarity-master
ksfitstat.m
.m
Acoustic_Similarity-master/code/metaAnalysis/ksfitstat.m
793
utf_8
9bea8df82fcafc068593eb078693ff26
% fit syllable distributions % based on veit/aronov/fee papers on breaths/etc function [kstat, nIncluded, tPrime] = ksfitstat(X, fitRange) % default? fitRange = [0.02 0.5]; % seconds %warning('off', 'stats:lillietest:OutOfRangePLow'); MLEfunc = @(t, sampMean) t + fitRange(1) - sampMean - ... (diff(fitRange) * exp(-(diff(fitRange)/t))) / (1 - exp(-(diff(fitRange)/t))); isWithin = X > fitRange(1) & X < fitRange(2); sample = X(isWithin); nIncluded = sum(isWithin); tBounds = [0 10*diff(fitRange)]; % seconds tPrime = fzero(@(x) MLEfunc(x, mean(sample)), tBounds); % the sufficient statistic if versionNumber > 8 [~,p,kstat] = lillietest(sample, 0.05, 'exp', 'MCTol', 1e-6); else [~,p,kstat] = lillietest(sample, 0.05, 'exp', 1e-3); end kstat = kstat * sqrt(numel(sample)); end
github
BottjerLab/Acoustic_Similarity-master
fitExponentialDuration.m
.m
Acoustic_Similarity-master/code/metaAnalysis/fitExponentialDuration.m
5,287
utf_8
3f37d7c17678f5d070489b56561fb55b
%% This script examines the syllable durations over sessions function [kstatValues, ages] = fitExponentialDuration(birdID) %birdID = 'Gy242'; report = reportOnData(birdID,'',[],'verbose',false); % only look for sessions with approved syllables nSessions = numel(report); hasData = false(1,nSessions); for ii = 1:nSessions hasData(ii) = any(findInManifest(report(ii).manifest, {'approvedSyllables'})); %,'bosSyllables','manualSyllables','syllables'})); end report = report(hasData); nSessions = numel(report); %% bookkeeping dateStr = cell(size(report)); for ii = 1:nSessions % get the date for each session sess = report(ii).sessionID; delimIdx = strfind(sess, '_'); dateStr{ii} = sess((delimIdx(1)+1):(delimIdx(3) - 1)); end % organize data - not every session has a date (in the excel file), % but every session has a recording date embedded in the name possAges = getAgeOfSession({report.sessionID}); [uDate, ~, dateIdx] = unique(dateStr); nAges = numel(uDate); % syllable Records sR = initEmptyStructArray({'sessions', 'age', 'kstat', 'nIncluded', 'tPrime', 'adjKS', 'adjIncl'}, nAges); for ii = 1:nAges foo = possAges(dateIdx == ii); foo(isnan(foo)) = []; if isempty(foo), error('sylDurationByBird:noAgeForSession', 'Age not found...'); end; sR(ii).age = foo(1); end %% gather syllable length empirical distributions fprintf('Session %s, %d sessions with data...\n', birdID, nSessions) syllLensPerDate = cell(1,nAges); for ii = 1:nSessions sylls = loadFromManifest(report(ii).manifest, 'approvedSyllables'); syllLengths = [sylls.stop]-[sylls.start]; syllLensPerDate{dateIdx(ii)} = [syllLensPerDate{dateIdx(ii)} syllLengths]; sR(dateIdx(ii)).sessions = [sR(dateIdx(ii)).sessions report(ii).sessionID]; end %% plotting, not always necessary %{ nR = floor(sqrt(nSessions)); nC = ceil(nSessions / nR); figure(1) for ii = 1:nSessions subplot(nR, nC, ii); syllLengths = plotDurationDistr(sylls); title(report(ii).sessionID,'interpreter', 'none'); xlim([0 0.5]) end %} %% do subsong/plastic song analysis with correction for sample size (exponential, maybe MOG/log-normals) % distribution is roughly exponential from 25-400 ms expRegion = [0.025 0.4]; % seconds %progressbar(sprintf('%s: Ages', birdID), 'Trials'); for ii = 1:nAges syllLens = syllLensPerDate{ii}; nPop = numel(syllLens); [sR(ii).kstat, sR(ii).nIncluded, sR(ii).tPrime] ... = ksfitstat(syllLens, expRegion); %{ sampleNumbers = 100 * 2.^(0:10); nTrials = 20; ksTrial = zeros(nTrials, numel(sampleNumbers)); tTrial = zeros(nTrials, numel(sampleNumbers)); for jj = 1:nTrials for kk = 1:numel(sampleNumbers) oversamp = randi(nPop,1,sampleNumbers(kk)); bootstrapSample = syllLens(oversamp); [ksTrial(jj,kk), ~, tTrial(jj,kk)] = ... ksfitstat(bootstrapSample, expRegion); end progressbar([],jj/nTrials); end fitParams = polyfit(log(sampleNumbers), log(mean(ksTrial)),1); surrogate = 0; sR(ii).adjKS = exp(fitParams(2)); %exp(polyval(fitParams, log(surrogate))); sR(ii).adjIncl = surrogate; %keyboard progressbar(ii/nAges,[]); %} end %% % take out day 48 %{ if strcmp(birdID,'Y231') ageToEliminate = find(birdAge == 48); uDate(ageToEliminate) = []; syllLensPerDate(ageToEliminate) = []; nInInterval(ageToEliminate) = []; tPrime(ageToEliminate) = []; kstat(ageToEliminate) = []; birdAge(ageToEliminate) = []; end %} %% plotting %{ % histogram binning for display purposes binWidth = 0.003; syllBins = 0:binWidth:0.65; % prep axes hax = zeros(1,nAges); nR = nAges; nC = 1; for ii = 1:nAges hax(ii) = subplot(nR,nC,ii); hold off; % make axis wider pos = get(gca,'Position'); set(gca, 'Position', [0.1 pos(2) 0.8 pos(4)]); % x-coordinates binCenters = syllBins + binWidth/2; % histogram syllDatePDF = hist(syllLensPerDate{ii},syllBins); bar(binCenters, syllDatePDF, 1, 'FaceColor', [0 0 0]) hold on; % trend line distrFunc = @(x,t) 1/t * (exp(-expRegion(1)/t) - exp(-expRegion(2)/t)).^(-1) * exp(-x/t); plot(binCenters, sR(ii).nIncluded * binWidth * distrFunc(binCenters, sR(ii).tPrime), 'r-',... 'LineWidth',2); % axis labels fontN = 'Arial'; if ii == numel(uDate) xlabel('syllable length (ms)','FontName', fontN, 'FontSize',14); end ylabel({'syllable count',sprintf('age %d dph', sR(ii).age)},'FontName', fontN, 'FontSize',14); xlim([0 0.4]); % text labels text(0.32, ylim * [0.4 0.6]', ... sprintf('Score = %0.2f, (# = %d)\nAdj score = %0.2f, (# = %d)', ... sR(ii).kstat, sR(ii).nIncluded, sR(ii).adjKS, sR(ii).adjIncl),... 'HorizontalAlignment', 'right', 'VerticalAlignment','middle',... 'FontName', fontN, 'FontSize',14); % appearance tweaks set(gca,'TickLength',[0 0], 'FontName', fontN, 'FontSize',14, ... 'Box', 'off'); end %subplot(hax(2)); ylim([0 150]); %? set(gcf,'Color', [1 1 1]); subplot(hax(1)); %} %% kstatValues = [sR.kstat]; ages = [sR.age]; %%+ %saveCurrFigure([pwd filesep 'figures' filesep 'dailySyllDur-' birdID '.pdf']);
github
BottjerLab/Acoustic_Similarity-master
oversampleTest.m
.m
Acoustic_Similarity-master/code/metaAnalysis/oversampleTest.m
2,319
utf_8
86835abc58823a3ff01a7c733f84fe07
%% This script examines the syllable durations over sessions function [ksamples, sampNumbers] = oversampleTest(birdID, selAge) %birdID = 'Gy242'; report = reportOnData(birdID,'',[],'verbose',false); % only look for sessions with approved syllables nSessions = numel(report); hasData = false(1,nSessions); for ii = 1:nSessions hasData(ii) = any(findInManifest(report(ii).manifest, {'approvedSyllables'})); %,'bosSyllables','manualSyllables','syllables'})); end report = report(hasData); nSessions = numel(report); %% bookkeeping dateStr = cell(size(report)); for ii = 1:nSessions % get the date for each session sess = report(ii).sessionID; delimIdx = strfind(sess, '_'); dateStr{ii} = sess((delimIdx(1)+1):(delimIdx(3) - 1)); end % organize data - not every session has a date (in the excel file), % but every session has a recording date embedded in the name possAges = getAgeOfSession({report.sessionID}); [uDate, ~, dateIdx] = unique(dateStr); nAges = numel(uDate); % syllable Records sR = initEmptyStructArray({'sessions', 'age', 'kstat', 'nIncluded', 'tPrime'}, nAges); for ii = 1:nAges foo = possAges(dateIdx == ii); foo(isnan(foo)) = []; if isempty(foo), error('sylDurationByBird:noAgeForSession', 'Age not found...'); end; sR(ii).age = foo(1); end %% gather syllable length empirical distributions fprintf('Session %s, %d sessions with data...\n', birdID, nSessions) syllLensPerDate = cell(1,nAges); for ii = 1:nSessions sylls = loadFromManifest(report(ii).manifest, 'approvedSyllables'); syllLengths = [sylls.stop]-[sylls.start]; syllLensPerDate{dateIdx(ii)} = [syllLensPerDate{dateIdx(ii)} syllLengths]; sR(dateIdx(ii)).sessions = [sR(dateIdx(ii)).sessions report(ii).sessionID]; end %% select only the age we want syllLensPerDate = syllLensPerDate{[sR.age] == selAge}; sR([sR.age] ~= selAge) = []; nAges = 1; %% oversampling mini-experiment expRegion = [0.025 0.4]; % seconds sampNumbers = 100 * 2.^(0:15); trials = 50; ksamples = zeros(numel(sampNumbers), trials); nPop = numel(syllLensPerDate); progressbar(0) for jj = 1:trials for ii = 1:numel(sampNumbers) oversamp = randi(nPop,1,sampNumbers(ii)); boots = syllLensPerDate(oversamp); ksamples(ii,jj) = ksfitstat(boots, expRegion); end progressbar(jj/trials) end
github
BottjerLab/Acoustic_Similarity-master
fitBimodalDuration.m
.m
Acoustic_Similarity-master/code/metaAnalysis/fitBimodalDuration.m
3,365
utf_8
663c9211895a201f0fdc7878d1b6db72
%% This script examines the syllable durations over sessions function [peakSize, ages, fitQ] = fitBimodalDuration(birdID) %birdID = 'Gy242'; report = reportOnData(birdID,'',[],'verbose',false); % only look for sessions with approved syllables nSessions = numel(report); hasData = false(1,nSessions); for ii = 1:nSessions hasData(ii) = any(findInManifest(report(ii).manifest, {'approvedSyllables'})); %,'bosSyllables','manualSyllables','syllables'})); end report = report(hasData); nSessions = numel(report); %% bookkeeping dateStr = cell(size(report)); for ii = 1:nSessions % get the date for each session sess = report(ii).sessionID; delimIdx = strfind(sess, '_'); dateStr{ii} = sess((delimIdx(1)+1):(delimIdx(3) - 1)); end % organize data - not every session has a date (in the excel file), % but every session has a recording date embedded in the name possAges = getAgeOfSession({report.sessionID}); [uDate, ~, dateIdx] = unique(dateStr); nAges = numel(uDate); % syllable Records sR = initEmptyStructArray({'sessions', 'age', 'peakheight', 'peakfit'}, nAges); for ii = 1:nAges foo = possAges(dateIdx == ii); foo(isnan(foo)) = []; if isempty(foo), error('sylDurationByBird:noAgeForSession', 'Age not found...'); end; sR(ii).age = foo(1); end %% gather syllable length empirical distributions fprintf('Session %s, %d sessions with data...\n', birdID, nSessions) syllLensPerDate = cell(1,nAges); for ii = 1:nSessions sylls = loadFromManifest(report(ii).manifest, 'approvedSyllables'); syllLengths = [sylls.stop]-[sylls.start]; syllLensPerDate{dateIdx(ii)} = [syllLensPerDate{dateIdx(ii)} syllLengths]; sR(dateIdx(ii)).sessions = [sR(dateIdx(ii)).sessions report(ii).sessionID]; end tau = zeros(1,nAges); for ii = 1:nAges syllLens = syllLensPerDate{ii}; binWidth = 0.003; % in seconds syllBins = 0:binWidth:0.65; % get the fit from 200-400 milliseconds lensDistr = hist(syllLens, syllBins) / numel(syllLens) / binWidth; [tau(ii), nFit] = fitExpOnInterval(syllLens, [0.2 0.4]); expFit = exp(-syllBins/tau(ii)) / tau(ii); % fit a gaussian to the residual residDistr = lensDistr - expFit; zeroedDistr = residDistr; zeroedDistr(zeroedDistr<0) = 0; [cfun, opts] = fit(syllBins', zeroedDistr', 'gauss1'); sR(ii).peakheight = cfun.a1; sR(ii).peakfit = opts.rsquare; subplot(nAges, 3, 1 + 3*(ii-1)); plot(syllBins, lensDistr, 'k-', syllBins, expFit, 'r-'); ylabel('Prob. density (s^{-1})'); title(sprintf('%s, age %d (fit on %d)', birdID, sR(ii).age, nFit)); if ii == nAges, xlabel('Syllable duration (ms)'); end set(gca,'Box', 'off'); ylim([0 15]) xlim([0 0.5]); subplot(nAges, 3, 2 + 3*(ii-1)); semilogy(syllBins, lensDistr, 'k-', syllBins, expFit, 'r-'); set(gca,'Box', 'off'); xlim([0 0.5]); set(gca,'YTick',[0.01 0.1 1 10]); ylim([0.01 15]); subplot(nAges, 3, 3*ii) plot(syllBins, lensDistr, 'k-', syllBins, expFit'+cfun(syllBins), 'b-'); title(sprintf('Peak = %0.2f, fit = %0.2f', sR(ii).peakheight, sR(ii).peakfit)); if ii == nAges, xlabel('Syllable duration (ms)'); end set(gca,'Box', 'off'); ylim([0 15]) xlim([0 0.5]); % try to fit end set(gcf,'Color', [1 1 1]); peakSize = [sR.peakheight]; ages = [sR.age]; fitQ = [sR.peakfit];
github
BottjerLab/Acoustic_Similarity-master
nm_inputdlg.m
.m
Acoustic_Similarity-master/code/interactive/nm_inputdlg.m
12,683
utf_8
0479860aeaed1cdb423e50e732f1bb77
function Answer=nm_inputdlg(Prompt, Title, NumLines, DefAns, Resize) %INPUTDLG Input dialog box. % ANSWER = INPUTDLG(PROMPT) creates a modal dialog box that returns user % input for multiple prompts in the cell array ANSWER. PROMPT is a cell % array containing the PROMPT strings. % % INPUTDLG uses UIWAIT to suspend execution until the user responds. % % ANSWER = INPUTDLG(PROMPT,NAME) specifies the title for the dialog. % % ANSWER = INPUTDLG(PROMPT,NAME,NUMLINES) specifies the number of lines for % each answer in NUMLINES. NUMLINES may be a constant value or a column % vector having one element per PROMPT that specifies how many lines per % input field. NUMLINES may also be a matrix where the first column % specifies how many rows for the input field and the second column % specifies how many columns wide the input field should be. % % ANSWER = INPUTDLG(PROMPT,NAME,NUMLINES,DEFAULTANSWER) specifies the % default answer to display for each PROMPT. DEFAULTANSWER must contain % the same number of elements as PROMPT and must be a cell array of % strings. % % ANSWER = INPUTDLG(PROMPT,NAME,NUMLINES,DEFAULTANSWER,OPTIONS) specifies % additional options. If OPTIONS is the string 'on', the dialog is made % resizable. If OPTIONS is a structure, the fields Resize, WindowStyle, and % Interpreter are recognized. Resize can be either 'on' or % 'off'. WindowStyle can be either 'normal' or 'modal'. Interpreter can be % either 'none' or 'tex'. If Interpreter is 'tex', the prompt strings are % rendered using LaTeX. % % Examples: % % prompt={'Enter the matrix size for x^2:','Enter the colormap name:'}; % name='Input for Peaks function'; % numlines=1; % defaultanswer={'20','hsv'}; % % answer=inputdlg(prompt,name,numlines,defaultanswer); % % options.Resize='on'; % options.WindowStyle='normal'; % options.Interpreter='tex'; % % answer=inputdlg(prompt,name,numlines,defaultanswer,options); % % See also DIALOG, ERRORDLG, HELPDLG, LISTDLG, MSGBOX, % QUESTDLG, TEXTWRAP, UIWAIT, WARNDLG . % Copyright 1994-2010 The MathWorks, Inc. % $Revision: 1.58.4.21 $ %%%%%%%%%%%%%%%%%%%% %%% Nargin Check %%% %%%%%%%%%%%%%%%%%%%% error(nargchk(0,5,nargin)); error(nargoutchk(0,1,nargout)); %%%%%%%%%%%%%%%%%%%%%%%%% %%% Handle Input Args %%% %%%%%%%%%%%%%%%%%%%%%%%%% if nargin<1 Prompt=getString(message('MATLAB:uistring:popupdialogs:InputDlgInput')); end if ~iscell(Prompt) Prompt={Prompt}; end NumQuest=numel(Prompt); if nargin<2, Title=' '; end if nargin<3 NumLines=1; end if nargin<4 DefAns=cell(NumQuest,1); for lp=1:NumQuest DefAns{lp}=''; end end if nargin<5 Resize = 'off'; end WindowStyle='normal'; Interpreter='none'; Options = struct([]); %#ok if nargin==5 && isstruct(Resize) Options = Resize; Resize = 'off'; if isfield(Options,'Resize'), Resize=Options.Resize; end if isfield(Options,'WindowStyle'), WindowStyle=Options.WindowStyle; end if isfield(Options,'Interpreter'), Interpreter=Options.Interpreter; end end [rw,cl]=size(NumLines); OneVect = ones(NumQuest,1); if (rw == 1 & cl == 2) %#ok Handle [] NumLines=NumLines(OneVect,:); elseif (rw == 1 & cl == 1) %#ok NumLines=NumLines(OneVect); elseif (rw == 1 & cl == NumQuest) %#ok NumLines = NumLines'; elseif (rw ~= NumQuest | cl > 2) %#ok error(message('MATLAB:inputdlg:IncorrectSize')) end if ~iscell(DefAns), error(message('MATLAB:inputdlg:InvalidDefaultAnswer')); end %%%%%%%%%%%%%%%%%%%%%%% %%% Create InputFig %%% %%%%%%%%%%%%%%%%%%%%%%% FigWidth=175; FigHeight=100; FigPos(3:4)=[FigWidth FigHeight]; %#ok FigColor=get(0,'DefaultUicontrolBackgroundColor'); InputFig=dialog( ... 'Visible' ,'off' , ... 'KeyPressFcn' ,@doFigureKeyPress, ... 'Name' ,Title , ... 'Pointer' ,'arrow' , ... 'Units' ,'pixels' , ... 'UserData' ,'Cancel' , ... 'Tag' ,Title , ... 'HandleVisibility' ,'callback' , ... 'Color' ,FigColor , ... 'NextPlot' ,'new' , ... 'WindowStyle' ,WindowStyle, ... 'Resize' ,Resize ... ); %%%%%%%%%%%%%%%%%%%%% %%% Set Positions %%% %%%%%%%%%%%%%%%%%%%%% DefOffset = 5; DefBtnWidth = 53; DefBtnHeight = 23; TextInfo.Units = 'pixels' ; TextInfo.FontSize = get(0,'FactoryUicontrolFontSize'); TextInfo.FontWeight = get(InputFig,'DefaultTextFontWeight'); TextInfo.HorizontalAlignment= 'left' ; TextInfo.HandleVisibility = 'callback' ; StInfo=TextInfo; StInfo.Style = 'text' ; StInfo.BackgroundColor = FigColor; EdInfo=StInfo; EdInfo.FontWeight = get(InputFig,'DefaultUicontrolFontWeight'); EdInfo.Style = 'edit'; EdInfo.BackgroundColor = 'white'; BtnInfo=StInfo; BtnInfo.FontWeight = get(InputFig,'DefaultUicontrolFontWeight'); BtnInfo.Style = 'pushbutton'; BtnInfo.HorizontalAlignment = 'center'; % Add VerticalAlignment here as it is not applicable to the above. TextInfo.VerticalAlignment = 'bottom'; TextInfo.Color = get(0,'FactoryUicontrolForegroundColor'); % adjust button height and width btnMargin=1.4; ExtControl=uicontrol(InputFig ,BtnInfo , ... 'String' ,getString(message('MATLAB:uistring:popupdialogs:Cancel')) , ... 'Visible' ,'off' ... ); % BtnYOffset = DefOffset; BtnExtent = get(ExtControl,'Extent'); BtnWidth = max(DefBtnWidth,BtnExtent(3)+8); BtnHeight = max(DefBtnHeight,BtnExtent(4)*btnMargin); delete(ExtControl); % Determine # of lines for all Prompts TxtWidth=FigWidth-2*DefOffset; ExtControl=uicontrol(InputFig ,StInfo , ... 'String' ,'' , ... 'Position' ,[ DefOffset DefOffset 0.96*TxtWidth BtnHeight ] , ... 'Visible' ,'off' ... ); WrapQuest=cell(NumQuest,1); QuestPos=zeros(NumQuest,4); for ExtLp=1:NumQuest if size(NumLines,2)==2 [WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ... textwrap(ExtControl,Prompt(ExtLp),NumLines(ExtLp,2)); else [WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ... textwrap(ExtControl,Prompt(ExtLp),80); end end % for ExtLp delete(ExtControl); QuestWidth =QuestPos(:,3); QuestHeight=QuestPos(:,4); if ismac % Change Edit box height to avoid clipping on mac. editBoxHeightScalingFactor = 1.4; else editBoxHeightScalingFactor = 1; end TxtHeight=QuestHeight(1)/size(WrapQuest{1,1},1) * editBoxHeightScalingFactor; EditHeight=TxtHeight*NumLines(:,1); EditHeight(NumLines(:,1)==1)=EditHeight(NumLines(:,1)==1)+4; FigHeight=(NumQuest+2)*DefOffset + ... BtnHeight+sum(EditHeight) + ... sum(QuestHeight); TxtXOffset=DefOffset; QuestYOffset=zeros(NumQuest,1); EditYOffset=zeros(NumQuest,1); QuestYOffset(1)=FigHeight-DefOffset-QuestHeight(1); EditYOffset(1)=QuestYOffset(1)-EditHeight(1); for YOffLp=2:NumQuest, QuestYOffset(YOffLp)=EditYOffset(YOffLp-1)-QuestHeight(YOffLp)-DefOffset; EditYOffset(YOffLp)=QuestYOffset(YOffLp)-EditHeight(YOffLp); end % for YOffLp QuestHandle=[]; EditHandle=[]; AxesHandle=axes('Parent',InputFig,'Position',[0 0 1 1],'Visible','off'); inputWidthSpecified = false; for lp=1:NumQuest, if ~ischar(DefAns{lp}), delete(InputFig); error(message('MATLAB:inputdlg:InvalidInput')); end EditHandle(lp)=uicontrol(InputFig , ... EdInfo , ... 'Max' ,NumLines(lp,1) , ... 'Position' ,[ TxtXOffset EditYOffset(lp) TxtWidth EditHeight(lp)], ... 'String' ,DefAns{lp} , ... 'Tag' ,'Edit' ... ); QuestHandle(lp)=text('Parent' ,AxesHandle, ... TextInfo , ... 'Position' ,[ TxtXOffset QuestYOffset(lp)], ... 'String' ,WrapQuest{lp} , ... 'Interpreter',Interpreter , ... 'Tag' ,'Quest' ... ); MinWidth = max(QuestWidth(:)); if (size(NumLines,2) == 2) % input field width has been specified. inputWidthSpecified = true; EditWidth = setcolumnwidth(EditHandle(lp), NumLines(lp,1), NumLines(lp,2)); MinWidth = max(MinWidth, EditWidth); end FigWidth=max(FigWidth, MinWidth+2*DefOffset); end % for lp % fig width may have changed, update the edit fields if they dont have user specified widths. if ~inputWidthSpecified TxtWidth=FigWidth-2*DefOffset; for lp=1:NumQuest set(EditHandle(lp), 'Position', [TxtXOffset EditYOffset(lp) TxtWidth EditHeight(lp)]); end end FigPos=get(InputFig,'Position'); FigWidth=max(FigWidth,2*(BtnWidth+DefOffset)+DefOffset); FigPos(1)=0; FigPos(2)=0; FigPos(3)=FigWidth; FigPos(4)=FigHeight; set(InputFig,'Position',getnicedialoglocation(FigPos,get(InputFig,'Units'))); OKHandle=uicontrol(InputFig , ... BtnInfo , ... 'Position' ,[ FigWidth-2*BtnWidth-2*DefOffset DefOffset BtnWidth BtnHeight ] , ... 'KeyPressFcn',@doControlKeyPress , ... 'String' ,getString(message('MATLAB:uistring:popupdialogs:OK')) , ... 'Callback' ,@doCallback , ... 'Tag' ,'OK' , ... 'UserData' ,'OK' ... ); setdefaultbutton(InputFig, OKHandle); CancelHandle=uicontrol(InputFig , ... BtnInfo , ... 'Position' ,[ FigWidth-BtnWidth-DefOffset DefOffset BtnWidth BtnHeight ] , ... 'KeyPressFcn',@doControlKeyPress , ... 'String' ,getString(message('MATLAB:uistring:popupdialogs:Cancel')) , ... 'Callback' ,@doCallback , ... 'Tag' ,'Cancel' , ... 'UserData' ,'Cancel' ... ); %#ok handles = guihandles(InputFig); handles.MinFigWidth = FigWidth; handles.FigHeight = FigHeight; handles.TextMargin = 2*DefOffset; guidata(InputFig,handles); set(InputFig,'ResizeFcn', {@doResize, inputWidthSpecified}); % make sure we are on screen movegui(InputFig) % if there is a figure out there and it's modal, we need to be modal too if ~isempty(gcbf) && strcmp(get(gcbf,'WindowStyle'),'modal') set(InputFig,'WindowStyle','modal'); end set(InputFig,'Visible','on'); drawnow; if ~isempty(EditHandle) uicontrol(EditHandle(1)); end if ishghandle(InputFig) % Go into uiwait if the figure handle is still valid. % This is mostly the case during regular use. uiwait(InputFig); end % Check handle validity again since we may be out of uiwait because the % figure was deleted. if ishghandle(InputFig) Answer={}; if strcmp(get(InputFig,'UserData'),'OK'), Answer=cell(NumQuest,1); for lp=1:NumQuest, Answer(lp)=get(EditHandle(lp),{'String'}); end end delete(InputFig); else Answer={}; end function doFigureKeyPress(obj, evd) %#ok switch(evd.Key) case {'return','space'} set(gcbf,'UserData','OK'); uiresume(gcbf); case {'escape'} delete(gcbf); end function doControlKeyPress(obj, evd) %#ok switch(evd.Key) case {'return'} if ~strcmp(get(obj,'UserData'),'Cancel') set(gcbf,'UserData','OK'); uiresume(gcbf); else delete(gcbf) end case 'escape' delete(gcbf) end function doCallback(obj, evd) %#ok if ~strcmp(get(obj,'UserData'),'Cancel') set(gcbf,'UserData','OK'); uiresume(gcbf); else delete(gcbf) end function doResize(FigHandle, evd, multicolumn) %#ok % TBD: Check difference in behavior w/ R13. May need to implement % additional resize behavior/clean up. Data=guidata(FigHandle); resetPos = false; FigPos = get(FigHandle,'Position'); FigWidth = FigPos(3); FigHeight = FigPos(4); if FigWidth < Data.MinFigWidth FigWidth = Data.MinFigWidth; FigPos(3) = Data.MinFigWidth; resetPos = true; end % make sure edit fields use all available space if % number of columns is not specified in dialog creation. if ~multicolumn for lp = 1:length(Data.Edit) EditPos = get(Data.Edit(lp),'Position'); EditPos(3) = FigWidth - Data.TextMargin; set(Data.Edit(lp),'Position',EditPos); end end if FigHeight ~= Data.FigHeight FigPos(4) = Data.FigHeight; resetPos = true; end if resetPos set(FigHandle,'Position',FigPos); end % set pixel width given the number of columns function EditWidth = setcolumnwidth(object, rows, cols) % Save current Units and String. old_units = get(object, 'Units'); old_string = get(object, 'String'); old_position = get(object, 'Position'); set(object, 'Units', 'pixels') set(object, 'String', char(ones(1,cols)*'x')); new_extent = get(object,'Extent'); if (rows > 1) % For multiple rows, allow space for the scrollbar new_extent = new_extent + 19; % Width of the scrollbar end new_position = old_position; new_position(3) = new_extent(3) + 1; set(object, 'Position', new_position); % reset string and units set(object, 'String', old_string, 'Units', old_units); EditWidth = new_extent(3);
github
BottjerLab/Acoustic_Similarity-master
nm_listdlg.m
.m
Acoustic_Similarity-master/code/interactive/nm_listdlg.m
8,294
utf_8
54b220d4944ea9e2e83a641976b6b6f7
function [selection,value] = nm_listdlg(varargin) %LISTDLG List selection dialog box. % [SELECTION,OK] = LISTDLG('ListString',S) creates a modal dialog box % which allows you to select a string or multiple strings from a list. % SELECTION is a vector of indices of the selected strings (length 1 in % the single selection mode). This will be [] when OK is 0. OK is 1 if % you push the OK button, or 0 if you push the Cancel button or close the % figure. % % Double-clicking on an item or pressing <CR> when multiple items are % selected has the same effect as clicking the OK button. Pressing <CR> % is the same as clicking the OK button. Pressing <ESC> is the same as % clicking the Cancel button. % % Inputs are in parameter,value pairs: % % Parameter Description % 'ListString' cell array of strings for the list box. % 'SelectionMode' string; can be 'single' or 'multiple'; defaults to % 'multiple'. % 'ListSize' [width height] of listbox in pixels; defaults % to [160 300]. % 'InitialValue' vector of indices of which items of the list box % are initially selected; defaults to the first item. % 'Name' String for the figure's title; defaults to ''. % 'PromptString' string matrix or cell array of strings which appears % as text above the list box; defaults to {}. % 'OKString' string for the OK button; defaults to 'OK'. % 'CancelString' string for the Cancel button; defaults to 'Cancel'. % % A 'Select all' button is provided in the multiple selection case. % % Example: % d = dir; % str = {d.name}; % [s,v] = listdlg('PromptString','Select a file:',... % 'SelectionMode','single',... % 'ListString',str) % % See also DIALOG, ERRORDLG, HELPDLG, INPUTDLG, % MSGBOX, QUESTDLG, WARNDLG. % Copyright 1984-2010 The MathWorks, Inc. % $Revision: 1.20.4.14 $ $Date: 2011/09/08 23:36:08 $ % 'uh' uicontrol button height, in pixels; default = 22. % 'fus' frame/uicontrol spacing, in pixels; default = 8. % 'ffs' frame/figure spacing, in pixels; default = 8. % simple test: % % d = dir; [s,v] = listdlg('PromptString','Select a file:','ListString',{d.name}); % % Generate a warning in -nodisplay and -noFigureWindows mode. warnfiguredialog('nm_listdlg'); error(nargchk(1,inf,nargin)) figname = ''; smode = 2; % (multiple) promptstring = {}; liststring = []; listsize = [160 300]; initialvalue = []; okstring = getString(message('MATLAB:uistring:popupdialogs:OK')); cancelstring = getString(message('MATLAB:uistring:popupdialogs:Cancel')); fus = 8; ffs = 8; uh = 22; if mod(length(varargin),2) ~= 0 % input args have not com in pairs, woe is me error(message('MATLAB:listdlg:InvalidArgument')) end for i=1:2:length(varargin) switch lower(varargin{i}) case 'name' figname = varargin{i+1}; case 'promptstring' promptstring = varargin{i+1}; case 'selectionmode' switch lower(varargin{i+1}) case 'single' smode = 1; case 'multiple' smode = 2; end case 'listsize' listsize = varargin{i+1}; case 'liststring' liststring = varargin{i+1}; case 'initialvalue' initialvalue = varargin{i+1}; case 'uh' uh = varargin{i+1}; case 'fus' fus = varargin{i+1}; case 'ffs' ffs = varargin{i+1}; case 'okstring' okstring = varargin{i+1}; case 'cancelstring' cancelstring = varargin{i+1}; otherwise error(message('MATLAB:listdlg:UnknownParameter', varargin{ i })) end end if ischar(promptstring) promptstring = cellstr(promptstring); end if isempty(initialvalue) initialvalue = 1; end if isempty(liststring) error(message('MATLAB:listdlg:NeedParameter')) end ex = get(0,'DefaultUicontrolFontSize')*1.7; % height extent per line of uicontrol text (approx) fp = get(0,'DefaultFigurePosition'); w = 2*(fus+ffs)+listsize(1); h = 2*ffs+6*fus+ex*length(promptstring)+listsize(2)+uh+(smode==2)*(fus+uh); fp = [fp(1) fp(2)+fp(4)-h w h]; % keep upper left corner fixed fig_props = { ... 'name' figname ... 'color' get(0,'DefaultUicontrolBackgroundColor') ... 'resize' 'off' ... 'numbertitle' 'off' ... 'menubar' 'none' ... 'windowstyle' 'normal' ... 'visible' 'off' ... 'createfcn' '' ... 'position' fp ... 'closerequestfcn' 'delete(gcbf)', ... 'nextplot' 'new'... }; liststring=cellstr(liststring); fig = figure(fig_props{:}); if length(promptstring)>0 prompt_text = uicontrol('Style','text','String',promptstring,... 'HorizontalAlignment','left',... 'Position',[ffs+fus fp(4)-(ffs+fus+ex*length(promptstring)) ... listsize(1) ex*length(promptstring)]); %#ok end btn_wid = (fp(3)-2*(ffs+fus)-fus)/2; listbox = uicontrol('Style','listbox',... 'Position',[ffs+fus ffs+uh+4*fus+(smode==2)*(fus+uh) listsize],... 'String',liststring,... 'BackgroundColor','w',... 'Max',smode,... 'Tag','listbox',... 'Value',initialvalue, ... 'Callback', {@doListboxClick}); ok_btn = uicontrol('Style','pushbutton',... 'String',okstring,... 'Position',[ffs+fus ffs+fus btn_wid uh],... 'Tag','ok_btn',... 'Callback',{@doOK,listbox}); cancel_btn = uicontrol('Style','pushbutton',... 'String',cancelstring,... 'Position',[ffs+2*fus+btn_wid ffs+fus btn_wid uh],... 'Tag','cancel_btn',... 'Callback',{@doCancel,listbox}); if smode == 2 selectall_btn = uicontrol('Style','pushbutton',... 'String',getString(message('MATLAB:uistring:popupdialogs:SelectAll')),... 'Position',[ffs+fus 4*fus+ffs+uh listsize(1) uh],... 'Tag','selectall_btn',... 'Callback',{@doSelectAll, listbox}); if length(initialvalue) == length(liststring) set(selectall_btn,'Enable','off') end set(listbox,'Callback',{@doListboxClick, selectall_btn}) end set([fig, ok_btn, cancel_btn, listbox], 'KeyPressFcn', {@doKeypress, listbox}); set(fig,'Position',getnicedialoglocation(fp, get(fig,'Units'))); % Make ok_btn the default button. setdefaultbutton(fig, ok_btn); % make sure we are on screen movegui(fig) set(fig, 'Visible','on'); drawnow; try % Give default focus to the listbox *after* the figure is made visible uicontrol(listbox); uiwait(fig); catch if ishghandle(fig) delete(fig) end end if isappdata(0,'ListDialogAppData__') ad = getappdata(0,'ListDialogAppData__'); selection = ad.selection; value = ad.value; rmappdata(0,'ListDialogAppData__') else % figure was deleted selection = []; value = 0; end %% figure, OK and Cancel KeyPressFcn function doKeypress(src, evd, listbox) %#ok switch evd.Key case 'escape' doCancel([],[],listbox); end %% OK callback function doOK(ok_btn, evd, listbox) %#ok if (~isappdata(0, 'ListDialogAppData__')) ad.value = 1; ad.selection = get(listbox,'Value'); setappdata(0,'ListDialogAppData__',ad); delete(gcbf); end %% Cancel callback function doCancel(cancel_btn, evd, listbox) %#ok ad.value = 0; ad.selection = []; setappdata(0,'ListDialogAppData__',ad) delete(gcbf); %% SelectAll callback function doSelectAll(selectall_btn, evd, listbox) %#ok set(selectall_btn,'Enable','off') set(listbox,'Value',1:length(get(listbox,'String'))); %% Listbox callback function doListboxClick(listbox, evd, selectall_btn) %#ok % if this is a doubleclick, doOK if strcmp(get(gcbf,'SelectionType'),'open') doOK([],[],listbox); elseif nargin == 3 if length(get(listbox,'String'))==length(get(listbox,'Value')) set(selectall_btn,'Enable','off') else set(selectall_btn,'Enable','on') end end
github
BottjerLab/Acoustic_Similarity-master
editEventsLabel.m
.m
Acoustic_Similarity-master/code/interactive/editEventsLabel.m
21,267
utf_8
2b2164914a00e4013ae1608717b153fb
function evsNew = editEventsLabel(evs,fs,doLabel) % EDITEVENTSLABEL(EVS) % This function allows the user to edit event boundaries and labels. % % The function plots a set of gray patches over each event in the active % figure. Usually a waveform or some other line plot pertaining to % the signal should be behind it. % The user can left-click and drag on events to adjust either the onset, % offset, or both. The user can also right-click on events to relabel % them. Clicking and dragging on a space without an event will create % a new event, while dragging the boundaries of an event past each other % results in deletion. % % For the purpose of this % % Known issues: % 1) Can be slow if surface data is being displayed in same figure or if % transparency is being used % 1b) If slow and you try to type a label too soon, focus moves to command window % 2) Will cause harmless error is patch handle is not ready in time for % mouse % % Prereqs: active figure/axes that are appropriate to have marks from the % labels applied % evs should be properly sorted % TODO: link callbacks so that drags can be performed everywhere % figure out a way to draw patches smartly over the spectrograms % NB: for resizing to work properly, the axes property 'Units' should be % normalized evsNew = initEvents(0); clearCallbacks(gcf); % housekeeping, removing warning RGBWarnID = 'MATLAB:hg:patch:RGBColorDataNotSupported'; warnState = warning('query',RGBWarnID); warning('off',RGBWarnID'); if nargin < 3 doLabel = false; end % setting some defaults for sampling rate if isempty(evs), evs = initEvents; if nargin < 2 fs = 44100; % FIXME: a pure guess warning('editEvents:InputUninitialized','Events uninitialized, sampling rate may be incorrect...'); end else if nargin < 2 fs = evs(1).idxStart/evs(1).start; end end greycol = [0.75 0.75 0.75]; % inform user of termination behavior oldTitle = get(get(gca,'Title'),'String'); newTitle = [oldTitle ' - Double click outside figure to exit and save, double click to play sound']; if doLabel, newTitle = [newTitle ', right click to relabel']; end; title(newTitle); % hide any other patch handles that are being used here otherPatchesOnAxis = findobj('Type','patch','Parent',gca); set(otherPatchesOnAxis,'visible','off'); % create patch handle if isempty(evs) % create a fake event and then delete it later fakeEvent = eventFromTimes(NaN,NaN, 1); hp = plotAreaMarks(fakeEvent,greycol); else hp = plotAreaMarks(evs,greycol); end % prepare handle for axes hax = gca; % give the label information to the patch handles labelsCell = {evs.type}; labelsCell = {labelsCell}; set(hp,'UserData',struct('labels', labelsCell)); % transform labels into text objects if doLabel drawLabelsInit(hp); end % some notes on action: % when in drag mode, data gets added to the patch's userData field % when changing labels, the data gets changed in the patch's userData.labels field set(gcf,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); set(gcf,'WindowButtonUpFcn',{@buttonUpFcn, [hax hp]}); set(gcf,'WindowButtonDownFcn',{@buttonDownFcn, [hax hp]}); % the end of the function is called on cleanup, that is, when the figure is % closed set(gcf,'DeleteFcn',{@cleanup, [hax hp]}); % exit is triggered when mouseUp occurs outside the axis window disp('Click outside to finish...'); waitfor(gcf,'WindowButtonMotionFcn',''); % NB: the termination of this routine, where evsNew is defined is in cleanup %%%%%%%% begin callbacks %%%%%%%%%%%%% function mouseOverFcn(gcbo, eventdata, handles) % some default colors greyCol = [0.75 0.75 0.75]; hiCol = [0.5 0.5 0.5]; lineCol = [0.8 0 0]; % unpack handles hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currPt = currPt(1,1:2); nFaces = size(get(hp,'XData'),2); vertexColors = greyCol(ones(4 * nFaces,1),:); [patchHover, lineHover] = clickStatus(currPt, handles); if ~isempty(patchHover) % highlight that patch vertexColors(patchHover * 4 - 3,:) = hiCol; if ~isempty(lineHover) %vertexColors(patchHover * 4 + [-2,0],:) = lineCol(ones(2,1),:); currXData = get(hp,'XData'); cursor(currXData(1+lineHover,patchHover),'on'); else cursor(0,'off'); end else cursor(0,'off'); end set(hp,'FaceVertexCData',vertexColors); end function cursor(xpos, status) lineCol = [0.8 0 0]; lineHandle = findobj('Tag','cursor'); if isempty(lineHandle) line([xpos xpos], ylim,'Color',lineCol,'Tag','cursor','LineWidth',1.5); elseif strcmp(status, 'off') && strcmp(get(lineHandle,'visible'), 'on') set(lineHandle,'visible','off'); elseif strcmp(status, 'on') set(lineHandle,'XData',[xpos xpos],'visible',status); end end function buttonUpFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); % get point relative to window to determine if click lies outside currPt = get(gcbo,'CurrentPoint'); currPt(1,1:2); oldUnits = get(gca,'Units'); set(gca,'Units','pixels'); axisWindow = get(hax,'Position'); set(gca,'Units',oldUnits); % return cursor to original look setptr(gcf,'arrow'); % exiting function - did we double-click outside the figure and % not as part of a drag? if ~inRect(axisWindow, currPt) && ~isfield(get(hp,'UserData'),'lineHeld') && ... strcmp(get(gcbo,'SelectionType'),'open') cleanup(gcbo); return; elseif isfield(get(hp,'UserData'),'patchHeld') % finished clicking on an event % remove the data not pertaining to labels userData = get(hp,'UserData'); set(hp,'UserData',struct('labels',userData.labels,'lastClicked',userData.patchHeld)); %(1) negative intervals - delete %(2) overlapping intervals - merge resolveOverlaps(hp); set(gcbo,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); else % clear last Clicked field userData = get(hp,'UserData'); set(hp,'UserData',struct('labels',userData.labels)); % leave only the labels end % links patches from other plots - a bit hacky, assumes all plots % hold same patch pattern % note that a naive linkprop doesn't work because we need the size of % yData/colorData to vary dynamically % TODO: dynamically activate/deactivate linkprop otherPatches = findobj(gcbo, 'Type', 'patch'); for ii = 1:numel(otherPatches) otherYData = get(otherPatches(ii),'YData'); otherYData = otherYData(:,ones(1,size(get(hp,'YData'),2))); set(otherPatches(ii),'XData',get(hp,'XData'),... 'YData',otherYData,... 'FaceVertexCData',get(hp,'FaceVertexCData')); end % refresh labels if doLabel repositionLabels(hp); end end function buttonDownFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currPt = currPt(1,1:2); [patchClicked, lineClicked, hitWindow] = clickStatus(currPt, handles); if ~hitWindow, return; end; if doLabel && strcmp(get(gcbo,'SelectionType'),'alt') % if a right click, rename if ~isempty(patchClicked) textHandles = getfield(get(hp,'UserData'),'labels'); %oldLabel = get(textHandles(patchClicked),'Text'); % erase old label set(textHandles(patchClicked),'String',''); set(textHandles(patchClicked),'Editing','on'); end elseif strcmp(get(gcbo,'SelectionType'),'extend') % middle click disp('Debug Mode (access variables through get(hp,''UserData'', \n and type ''dbcont'' to exit.'); % todo: allow different debug modes? keyboard; % profile viewer; % profile on; % pause; elseif strcmp(get(gcbo,'SelectionType'),'open') % double click detection? play a sound % let people know we're working while we load the clip % set(gcf,'Pointer','watch'); % disp('Clock on'); % % get the clip data hline = findobj(hax,'Type','line'); hline = hline(end); % it should be the one furthest back xWave = get(hline,'XData'); yWave = get(hline,'YData'); if isempty(patchClicked) % what should we do if a patch is not clicked? % play the whole clip playSound(yWave, fs, true); else % get the borders currXData = get(hp, 'XData'); patchBorders = currXData(2:3,patchClicked); % cut the clip at the right points clipStart = find(xWave >= patchBorders(1),1); clipEnd = find(xWave >= patchBorders(2),1); clip = yWave(clipStart:clipEnd); % play the sound clip, while blocking playSound(clip, fs, true); end % ok, waiting's up % disp('Clock off'); % set(gcf,'Pointer', 'arrow'); elseif isempty(patchClicked) % clicked on an empty space % create new event currXData = get(hp, 'XData'); currYData = get(hp, 'YData'); currVertexColors = get(hp, 'FaceVertexCData'); userData = get(hp,'UserData'); % find where to insert new event if ~all(isnan(currXData)) insertPt = find(currPt(1) <= [currXData(1,:) Inf], 1); currXData = [currXData(:,1:insertPt-1) currPt(1)*ones(4,1) currXData(:,insertPt:end)]; currYData = currYData(:,[1 1:end]); %all columns are the same currVertexColors = currVertexColors([ones(1,4) 1:end], :);% we need four more rows, but the colors are all the same if doLabel newTextHandle = createTextLabel(currPt(1), ' '); % move to front ch = get(hax,'Children'); ch = [newTextHandle; ch(ch~=newTextHandle)]; set(hax,'Children', ch); userData.labels = [userData.labels(:,1:insertPt-1) newTextHandle userData.labels(:,insertPt:end)]; end else % currXData is filled with a NaN box so that insertPt is not % consistent with adding into an empty array insertPt = 1; currXData = currPt(1) * ones(4,1); currYData = [ylim fliplr(ylim)]'; if doLabel newTextHandle = createTextLabel(currPt(1), ' '); % move to front ch = get(hax,'Children'); ch = [newTextHandle; ch(ch~=newTextHandle)]; set(hax,'Children', ch); userData.labels=newTextHandle; end end set(hp,'XData',currXData,'YData',currYData,'FaceVertexCData',currVertexColors); % handle dragging dragData = struct('lineHeld', [], ... 'startPt', currPt, ... 'patchHeld', insertPt, ... 'justCreated', true, ... 'origBounds', currPt(1)*ones(4,1), ... 'labels', userData.labels); % dragging data gets added to the patch userData set(hp,'UserData',dragData); set(gcf,'WindowButtonMotionFcn',{@draggingFcn, [hax hp]}); % set the cursor look setptr(gcf, 'fullcrosshair'); else % we clicked on a patch xBounds = get(hp,'XData'); userData = get(hp,'UserData'); dragData = struct('lineHeld', lineClicked, ... 'startPt', currPt, ... 'patchHeld', patchClicked,... 'justCreated', false,... 'origBounds', xBounds(:,patchClicked),... 'labels', userData.labels); set(hp,'UserData',dragData); set(gcf,'WindowButtonMotionFcn',{@draggingFcn, [hax hp]}); % set cursor look if ~isempty(lineClicked) setptr(gcf,'fullcrosshair'); else setptr(gcf,'hand'); end end end function draggingFcn(gcbo, eventdata, handles) hax = handles(1); hp = handles(2); currPt = get(hax,'CurrentPoint'); currXData = get(hp,'XData'); userData = get(hp, 'UserData'); %nFaces = size(currXData,2); if ~isfield(userData,'patchHeld') || isempty(userData.patchHeld) error('editEvents:PatchNotClicked','Patch not Clicked, drag callback should not be set'); end if userData.justCreated % if we just created an event, detect the drag motion if currPt(1) ~= userData.startPt(1) userData.justCreated = false; userData.lineHeld = 1 + (currPt(1) > userData.startPt(1)); end end if ~isempty(userData.lineHeld) % moving one edge of the eventdata rIdxs = 2 * userData.lineHeld + [-1 0]; currXData(rIdxs,userData.patchHeld) = currPt(1); set(hp,'XData',currXData); cursor(currPt(1),'on'); % detect collisions immediately and quit drag if detectCollision(hp,userData.patchHeld,userData.lineHeld), set(gcbo,'WindowButtonMotionFcn',{@mouseOverFcn, [hax hp]}); resolveOverlaps(hp); cursor(0,'off'); end else % moving whole event currXData(:,userData.patchHeld) = userData.origBounds + currPt(1) - userData.startPt(1); set(hp,'XData',currXData); end if doLabel repositionLabels(hp); end end %%%%%%%% end callbacks %%%%%%%%%%%%% function didCollide = detectCollision(patchHandle,activePatch, boundarySide) currXData = get(patchHandle,'XData'); if isempty(currXData), return; end; % nothing to collide borders = currXData(2:3,:); nFaces = size(borders,2); adjBorder = NaN; if activePatch > 1 && boundarySide == 1 adjBorder = borders(2,activePatch - 1); elseif activePatch < nFaces && boundarySide == 2 adjBorder = borders(1,activePatch + 1); end didCollide = (borders(1,activePatch) >= borders(2,activePatch)) || ... borders(boundarySide,activePatch) <= adjBorder && boundarySide == 1 || ... borders(boundarySide,activePatch) >= adjBorder && boundarySide == 2; end function repositionLabels(hp) userData = get(hp,'UserData'); currXData = get(hp,'XData'); nFaces = size(currXData,2); % all NaNs is the placeholder for no regions if all(isnan(currXData)), nFaces = 0; end; for ii = 1:nFaces labelPos = get(userData.labels(ii),'Position'); labelPos(1) = mean(currXData(:,ii)); set(userData.labels(ii),'Position', labelPos); end end function resolveOverlaps(patchHandle) % cleans up intervals %keeping colors the same greyCol = [0.75 0.75 0.75]; currXData = get(patchHandle,'XData'); currYData = get(patchHandle,'YData'); %currColData = get(patchHandle,'FaceVertexCData'); if isempty(currXData), return; end; % nothing to resolve borders = currXData(2:3,:); userData = get(patchHandle,'UserData'); % remove any negative-length intervals isNonPosLength = (borders(1,:) >= borders(2,:)); borders(:,isNonPosLength) = []; % remove their label if doLabel delete(userData.labels(isNonPosLength)); userData.labels(isNonPosLength) = []; end % merge overlapping regions % since the number of regions is probably small (<10), we'll do this in a % naive way (better is with interval trees) ii = 1; nFaces = size(borders,2); while ii <= nFaces && nFaces > 1 toMerge = find(borders(1,ii) >= borders(1,:) & borders(1,ii) <= borders(2,:) | ... borders(2,ii) >= borders(1,:) & borders(2,ii) <= borders(2,:)); if numel(toMerge) > 1 borders(1,ii) = min(borders(1,toMerge)); borders(2,ii) = max(borders(2,toMerge)); toDelete = toMerge(toMerge ~= ii); % remove patch information borders(:,toDelete) = []; % remove labels if doLabel delete(userData.labels(toDelete)); userData.labels(toDelete) = []; end % get resized # of patches nFaces = size(borders,2); else ii = ii + 1; end end if ~isempty(borders) currXData = borders([1 1 2 2],:); currYData = currYData(:,ones(1,nFaces)); % just copy the first row currColData = greyCol(ones(4*nFaces,1),:); % just copy the first color else currXData = NaN(4,1); currColData = greyCol(ones(4,1),:); currYData = NaN(4,1); end set(patchHandle,'XData',currXData,'YData',currYData,'FaceVertexCData',currColData,'UserData',userData); end function foo = inRect(win, pt) foo = win(1) <= pt(1) && pt(1) < win(1) + win(3) && ... win(2) <= pt(2) && pt(2) < win(2) + win(4); end function [patchSeld, lineSeld, hitWindow] = clickStatus(currPt, handles) % returns empties on default patchSeld = []; lineSeld = []; hax = handles(1); hp = handles(2); win([1 3]) = get(hax,'XLim'); win(3) = win(3) - win(1); win([2 4]) = get(hax,'YLim'); win(4) = win(4) - win(2); hitWindow = inRect(win, currPt); if ~hitWindow, return, end; % how 'fat' should our edge be for us to highlight/grab it? edgeFuzzFrac = 4.3e-3; edgeFuzz = diff(get(hax,'XLim')) * edgeFuzzFrac; yy = get(hax,'YLim'); if currPt(2) > yy(2) || currPt(2) < yy(1), return; end; xBounds = get(hp,'XData'); if isempty(xBounds), return; end; % nothing to click xBounds = xBounds(2:3,:); patchSeld = ... find(xBounds(1,:) - edgeFuzz <= currPt(1) & ... xBounds(2,:) + edgeFuzz >= currPt(1)); if numel(patchSeld) > 1 % find the one which is closer distsToCursor = min(xBounds(1,patchSeld) - currPt(1)); [~,closest] = min(distsToCursor); patchSeld = patchSeld(closest); end if ~isempty(patchSeld) if abs(xBounds(1,patchSeld) - currPt(1)) <= edgeFuzz, lineSeld = 1; elseif abs(xBounds(2,patchSeld) - currPt(1)) <= edgeFuzz, lineSeld = 2; end end end function drawLabelsInit(patchHandle) %prereq: userdata is already set with labels %converts labels to a set of txthandles currXData = get(patchHandle,'XData'); borders = currXData(2:3,:); nFaces = size(borders,2); userData = get(patchHandle,'UserData'); txthandles = zeros(nFaces,1); chold = get(hax,'Children'); if numel(userData.labels) == 0, return, end; for ii = 1:nFaces thisLabel = userData.labels{ii}; % convert to string if necessary if ~(ischar(thisLabel) || iscellstr(thisLabel) || isempty(thisLabel)) && isnumeric(thisLabel) thisLabel = num2str(thisLabel); elseif isempty(thisLabel) thisLabel = ''; end txthandles(ii) = createTextLabel(mean(borders(:,ii)),thisLabel); end % move to front - for some reason this doesn't work with openGL ch = [txthandles; chold]; set(hax,'Children', ch); % labels is cell userData.labels = txthandles'; set(patchHandle,'UserData',userData); end function clearCallbacks(gcbo) set(gcbo,'WindowButtonMotionFcn',''); % triggers the end of waitfor set(gcbo,'WindowButtonUpFcn',''); set(gcbo,'WindowButtonDownFcn',''); set(gcbo,'DeleteFcn',''); end function cleanup(gcbo, eventdata, handles) % clearing the callbacks is the signal for the program to exit % this also triggers the end of the function in normal operation, % but cleanup is allowed to finish clearCallbacks(gcbo); disp('Wrapping up...'); % clean up - restore any changed properties title([oldTitle ' - Finishing']); warning(warnState.state,RGBWarnID); % read the events back from the edited patch handle xdat = []; if ishandle(hp) xdat = get(hp,'XData'); % get rid of any NaN columns that were placeholders xdat(:,all(isnan(xdat))) = []; % allocate the correct number of events % evsNew = initEvents(size(xdat,2)); end if isempty(xdat), return; end; % return an empty event structure if no marks evsNew = eventFromTimes(xdat(2,:), xdat(3,:),fs); %{ starts = num2cell(xdat(2,:)); idxStarts = num2cell(floor(xdat(2,:) * fs)); stops = num2cell(xdat(3,:)); idxStops = num2cell(floor(xdat(3,:) * fs)); [evsNew.start] = starts{:}; [evsNew.stop] = stops{:}; [evsNew.idxStart] = idxStarts{:}; [evsNew.idxStop] = idxStops{:}; [evsNew.type] = deal(NaN); %} if doLabel % retrieve the labels labelHandles = getfield(get(hp,'UserData'),'labels'); textLabels = get(labelHandles,'String'); if ~iscell(textLabels), textLabels = {textLabels}; end; [evsNew.type] = textLabels{:}; % get rid of the editing text labels delete(labelHandles); set(otherPatchesOnAxis,'XData',get(hp,'XData'),'visible','on'); end % get rid of the editing patch delete(hp); title(oldTitle); end end
github
BottjerLab/Acoustic_Similarity-master
uigetfile_deprecated.m
.m
Acoustic_Similarity-master/code/interactive/private/uigetfile_deprecated.m
39,745
utf_8
4a87e0c1ae0cc528d4f96bb00362a730
function [filename, pathname, filterindex] = uigetfile_deprecated(varargin) % Copyright 1984-2012 The MathWorks, Inc. % $Revision: 1.1.6.11 $ $Date: 2012/07/05 16:48:22 $ % Built-in function. %%%%%%%%%%%%%%%% % Error messages %%%%%%%%%%%%%%%% badLocMessage = 'The Location parameter value must be a 2 element vector.' ; badMultiMessage = 'The MultiSelect parameter value must be a string specifying on/off.' ; %badFirstMessage = 'Ill formed first argument to uigetfile' ; badArgsMessage = 'Unrecognized input arguments.' ; bad2ndArgMessage = 'Expecting a string as 2nd arg' ; bad3rdArgMessage = 'Expecting a string as 3rd arg' ; badFilterMessage = 'FILTERSPEC argument must be a string or an M by 1 or M by 2 cell array.' ; badNumArgsMessage = 'Too many input arguments.' ; badLastArgsMessage = 'MultiSelect and Location args must be the last args' ; badMultiPosMessage = '''MultiSelect'' , ''on/off'' can only be followed by Location args' ; badLocationPosMessage = '''Location'' , [ x y ] can only be followed by MultiSelect args' ; caErr1Message = 'Illegal filespec'; caErr2Message = 'Illegal filespec - can have at most two cols'; caErr3Message = 'Illegal file extension - ''' ; maxArgs = 7 ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check the number of args - must be <= maxArgs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% numArgs = nargin ; if( numArgs > maxArgs ) error( badNumArgsMessage ) end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Restrict new version to the mac % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If we are on the mac, default to using non-native % dialog. If the root property UseNativeSystemDialogs % is false, use the non-native version instead. useNative = true; %#ok<NASGU> % If we are on the Mac & swing is available, set useNative to false, % i.e., we are going to use Java dialogs not native dialogs. % Comment the following line to disable java dialogs on Mac. useNative = ~( ismac && usejava('awt') ) ; % If the root appdata is set and swing is available, % honor that overriding all other prefs. %if isequal(-1, getappdata(0,'UseNativeSystemDialogs')) && isempty( javachk('swing') ) % useNative = false ; %end if useNative try if nargin == 0 [filename, pathname, filterindex] = native_uigetfile ; else [filename, pathname, filterindex] = native_uigetfile( varargin{:} ) ; end catch ex rethrow(ex) end return end % end useNative %%%%%%%%%%%%%%%%% % General globals %%%%%%%%%%%%%%%%% %multiPosition = '' ; locationPosition = '' ; %fileSeparator = filesep ; %pathSeparator = pathsep ; remainderArgs = '' ; newFilter = '' ; locationPosition = '' ; % position of 'Location' arg multiSelectPosition = '' ; % position of 'MultiSelect' arg theError = '' ; userTitle = '' ; extError = 'mExtError' ; % returned from dFilter if there is an error %selectionFilter = '' ; % File Filter used by the user in the dialog %%%%%%% % Flags %%%%%%% filespecError = false ; cellArrayOk = false ; locationError = false ; multiSelectOn = false ; multiSelectError = false ; %argUsedAsFileName = false ; multiSelectFound = false ; locationFound = false ; %%%%%%%%%%%%%%%%%%%%% % Filter descriptions %%%%%%%%%%%%%%%%%%%%% allMDesc = 'All MATLAB Files' ; mDesc = 'MATLAB code (*.m)' ; figDesc = 'Figures (*.fig)' ; matDesc = 'MAT-files (*.mat)' ; simDesc = 'Simulink Models (*.mdl, *.slx)' ; staDesc = 'Stateflow Files (*.cdr)' ; wksDesc = 'Code generation files (*.rtw,*.tmf,*.tlc,*.c,*.h)' ; rptDesc = 'Report Generator Files (*.rpt)' ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Extension "specs" for our default filters % These strings are used by filters to match file extensions % NOTE that they do NOT contian a '.' character %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% mSpec = 'm' ; figSpec = 'fig' ; matSpec = 'mat' ; simSpec = 'mdl' ; sim2Spec = 'slx'; staSpec = 'cdr' ; rtwSpec = 'rtw' ; tmfSpec = 'tmf' ; tlcSpec = 'tlc' ; rptSpec = 'rpt' ; cSpec = 'c' ; hSpec = 'h' ; %%%%%%%%%%%%%%%%% % Default filters %%%%%%%%%%%%%%%%% % A filter for all Matlab files allMatlabFilter = '' ; % A filter for .m files mFilter = '' ; % A filter for .fig files figFilter = '' ; % A filter for .mat files matFilter = '' ; % A filter for Simulink files - .mdl simFilter = '' ; % A filter for Stateflow files - .cdr staFilter = '' ; % A filter for Code generation files - .rtw, .tmf, .tlc, .c, .h wksFilter = '' ; % A filter for Report Generator files - .rpt rptFilter = '' ; % A filter for all files - *.* allFilter = '' ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The dialog that holds our file chooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % jp = handle(javax.swing.JPanel) ; jp = awtcreate('com.mathworks.mwswing.MJPanel', ... 'Ljava.awt.LayoutManager;', ... java.awt.BorderLayout); % Title is set later d = mydialog( ... 'Visible','off', ... 'DockControls','off', ... 'Color',get(0,'DefaultUicontrolBackgroundColor'), ... 'Windowstyle','modal', ... 'Resize','on' ... ); % Create a JPanel and put it into the dialog - this is for resizing [panel, container] = javacomponent( jp,[10 10 20 20],d); % Create a JFileChooser sys = char( computer ) ; jfc = awtcreate('com.mathworks.hg.util.dFileChooser'); awtinvoke( jfc , 'init(ZLjava/lang/String;)' , false , java.lang.String(sys) ) ; %jfc.init( false , sys ) ; % We're going to use our own "all" file filter awtinvoke( jfc , 'setAcceptAllFileFilterUsed(Z)' , false ) ; %jfc.setAcceptAllFileFilterUsed( false ) ; % Set the chooser's current directory awtinvoke( jfc , 'setCurrentDirectory(Ljava/io/File;)' , java.io.File(pwd) ) ; %jfc.setCurrentDirectory( java.io.File(pwd) ) ; % Make sure multi select is initially disabled awtinvoke( jfc , 'setMultiSelectionEnabled(Z)' , false ) ; %jfc.setMultiSelectionEnabled( false ) ; awtinvoke( java(panel), 'add(Ljava.awt.Component;)', jfc ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Eliminate "built-in" args such as 'multiselect', 'location' and % their values. As a side effect, create the array remainderArgs. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% eliminateBuiltIns() ; % Exit if there was an error with MultiSelect or Location numArgs = nargin ; if( multiSelectError || locationError ) error( theError ) ; end % Check to see that there are no extra args. % 'MultiSelect', 'location' and their values % must be the last args. if( multiSelectFound && ~locationFound ) if( ~( multiSelectPosition == ( numArgs - 1 ) ) ) error( badMultiPosMessage ) ; end % end if( ~( multiSelectPosition ... end % end if( multiSelectFound ) if( locationFound && ~multiSelectFound ) if( ~( locationPosition == ( numArgs - 1 ) ) ) error( badLocationPosMessage ) ; end % end if( ~( locationPosition ... end % end if( locationFound ) if( multiSelectFound && locationFound ) if( ( ~( ( numArgs - 1 ) == multiSelectPosition ) && ~( ( numArgs - 3 ) == multiSelectPosition ) ) || ... ( ~( ( numArgs - 1 ) == locationPosition ) && ~( ( numArgs - 3 ) == locationPosition ) ) ) error( badLastArgsMessage ) ; end end % end if( multiSelectFound & locationFound ) % Set the chooser to multi select if required % if( multiSelectFound ) % warning('MATLAB:UIGETFILE:MultiSelectIg','MultiSelect is being ignored temporally.'); % end if( locationFound ) warning(message('MATLAB:UIGETFILE:LocationIgnore')); end if( multiSelectOn ) awtinvoke( jfc , 'setMultiSelectionEnabled(Z)' , true ) ; % jfc.setMultiSelectionEnabled( true ) ; end % Reset the content of varargin & numArgs varargin = remainderArgs ; numArgs = numel( remainderArgs ) ; % At this point we can have at most 3 remaining args if( numArgs > 3 ) error( badArgsMessage ) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of no args. In this case % we load and use the default filters. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 0 == numArgs ) buildDefaultFilters() ; % Load our filters into the JFileChooser loadDefaultFilters( jfc , 1 ) ; % Set our "allMatlabFilter" to be the active filter awtinvoke( jfc , 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allMatlabFilter ) ; %jfc.setFileFilter( allMatlabFilter ) ; end % end if( 0 == numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of exactly one remaining arg. % The argument must be a string or a cell array. % % If it's a cell array we try to use it as a filespec. % % If it's a string, there are 2 options: % % If it's a legit description of a file ext, we use it % to create a filter and a description. We then add % that filter and the "all" filter to the file chooser. % Example - '*.txt' or '.txt' % % FOR COMPATIBILITY, % if it's not an ext we understand, we use it as a % "selected file name." We then set up the file chooser % to use our default filters including the "all" filter. % Example - 'x' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 1 == numArgs ) spec = varargin{ 1 } ; if ~( ischar( spec ) ) && ~( iscellstr( spec ) ) error( badFilterMessage ) end % OK - the type is correct %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case where the arg is a string %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isempty(spec) || ( ischar( spec ) && isvector( spec ) ) if( ~( 1 == size( spec , 1 ) ) ) spec = spec' ; end handleStringFilespec( jfc , spec , 1 ) ; if( filespecError ) error( theError ) ; end end % end if( ischar( spec ) ) ... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case where the arg is a cell array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( iscellstr( spec ) ) cellArrayOk = false ; handleCellArrayFilespec( spec , jfc ) ; if ~cellArrayOk error( theError ) ; end end % if( iscellstr( spec ) ) end % end if( 1 == numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of two remaining args. % % If arg 1 is a good filespec, use it % and interpret the 2nd arg as a title. % % FOR COMPATIBILITY, % if arg1 is a string but not a legit % filespec, we use it as a file name % and interpret the 2nd arg as a title. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 2 == numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Error check the types of the args. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The 2nd arg must be a string arg2 = varargin{ 2 } ; if ~isempty(arg2) && ~( ischar( arg2 ) && isvector( arg2 ) ) % Not a string error( bad2ndArgMessage ) end % Transpose if necessary if( ~( 1 == size( arg2 , 1 ) ) ) arg2 = arg2' ; end % Use arg2 as title userTitle = char(arg2); % Check out the first arg spec = varargin{ 1 } ; if ~( ischar( spec ) ) && ~( iscellstr( spec ) ) error( badFilterMessage ) end % OK - the types are correct %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case where the 1st arg is a string %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isempty(spec) || ( ischar( spec ) && isvector( spec ) ) if( ~( 1 == size( spec , 1 ) ) ) spec = spec' ; end handleStringFilespec( jfc, spec, '1' ); if( filespecError ) error( theError ) ; end else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case where first arg is a cell array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% handleCellArrayFilespec( spec , jfc ) ; if( ~cellArrayOk ) error( theError ) ; end end %if( ischar( spec ) & isvector( spec ) ) end % if( 2 == numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of three remaining arguments. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 3 == numArgs ) % The 2nd and 3rd args must be strings arg2 = varargin{ 2 } ; if ~isempty(arg2) && ~( ischar( arg2 ) && isvector( arg2 ) ) % Not a string error( bad2ndArgMessage ) end if( ~( 1 == size( arg2 , 1 ) ) ) arg2 = arg2' ; end % Use arg2 as title userTitle = char(arg2); arg3 = varargin{ 3 } ; if ~isempty(arg3) && ~( ischar( arg3 ) && isvector( arg3 ) ) % Not a string error( bad3rdArgMessage ) end if( ~( 1 == size( arg3 , 1 ) ) ) arg3 = arg3' ; end % Use arg3 as file after handling arg1 % Check out the first arg spec = varargin{ 1 } ; % The first arg must be a string or cell array if ~( ischar( spec ) ) && ~( iscellstr( spec ) ) error( badFilterMessage ) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case where the 1st arg is a string %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isempty(spec) || ( ischar( spec ) && isvector( spec ) ) if( ~( 1 == size( spec , 1 ) ) ) spec = spec' ; end handleStringFilespec( jfc , spec , '1' ) ; if( filespecError ) error( theError ) ; end else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle case where 1st arg is a cell array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% handleCellArrayFilespec( spec , jfc ) ; if( ~cellArrayOk ) error( theError ) ; end end % if( ischar( spec ) & isvector( spec ) ) % Use arg3 as file after handling arg1 awtinvoke( jfc , 'setSelectedFile(Ljava/io/File;)' , java.io.File( arg3 ) ) ; end % if( 3 == numargs ) % Set the title of the dialog if( ~( strcmp( char(userTitle) , '' ) ) ) set( d , 'Name' , userTitle ) else set( d , 'Name' , char( jfc.getDefaultGetfileTitle() ) ) end set(container,'Units','normalized','Position',[0 0 1 1]); jfcHandle = handle(jfc , 'callbackproperties' ); % these will get set by the callback filename = 0 ; pathname = 0 ; filterindex = 0 ; set(jfcHandle,'PropertyChangeCallback', {@callbackHandler, d , multiSelectOn , sys }) figure(d) refresh(d) awtinvoke( jfc , 'listen()' ) ; %jfc.listen() ; waitfor(d); % Retrieve the data stored by the callback if isappdata( 0 , 'uigetfileData' ) uigetfileData = getappdata( 0 , 'uigetfileData' ) ; filename = uigetfileData.filename ; pathname = uigetfileData.pathname ; filterindex = uigetfileData.filterindex ; rmappdata( 0 , 'uigetfileData' ) ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Build all the default filters. Each filter handles % one or more extension. Each filter also has a % description string which appears in the file selection % dialog. Each filter can also be assigned a string "id." % Filters are Java objects. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buildDefaultFilters() allMatlabFilter = com.mathworks.hg.util.dFilter ; allMatlabFilter.setDescription( allMDesc ) ; allMatlabFilter.addExtension( mSpec ) ; allMatlabFilter.addExtension( figSpec ) ; allMatlabFilter.addExtension( matSpec ) ; % Filter for files mFilter = com.mathworks.hg.util.dFilter ; mFilter.setDescription( mDesc ) ; mFilter.addExtension( mSpec ) ; % Filter for .fig files figFilter = com.mathworks.hg.util.dFilter ; figFilter.setDescription( figDesc ) ; figFilter.addExtension( figSpec ) ; % Filter for MAT-files matFilter = com.mathworks.hg.util.dFilter ; matFilter.setDescription( matDesc ) ; matFilter.addExtension( matSpec ) ; % Filter for Simulink Models simFilter = com.mathworks.hg.util.dFilter ; simFilter.setDescription( simDesc ) ; simFilter.addExtension( simSpec ) ; simFilter.addExtension( sim2Spec ) ; % Filter for Stateflow files staFilter = com.mathworks.hg.util.dFilter ; staFilter.setDescription( staDesc ) ; staFilter.addExtension( staSpec ) ; % Filter for Code generation files wksFilter = com.mathworks.hg.util.dFilter ; wksFilter.setDescription( wksDesc ) ; wksFilter.addExtension( rtwSpec ) ; wksFilter.addExtension( tmfSpec ) ; wksFilter.addExtension( tlcSpec ) ; wksFilter.addExtension( cSpec ) ; wksFilter.addExtension( hSpec ) ; % Filter for Report Generator files rptFilter = com.mathworks.hg.util.dFilter ; rptFilter.setDescription( rptDesc ) ; rptFilter.addExtension( rptSpec ) ; % Filter for "All Files" allFilter = com.mathworks.hg.util.AllFileFilter ; end % end buildDefaultFilters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Load all the default filters into the jFileChooser. % Give each filter an id starting at "startId." We'll % later use the id to determine which filter was active % when the user made the selection. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function loadDefaultFilters( chooser , startId ) j = startId ; allMatlabFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allMatlabFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , allMatlabFilter ) ; % chooser.addFileFilter( allMatlabFilter ) ; % chooser.noteFilter( allMatlabFilter ) ; j = j + 1 ; mFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , mFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , mFilter ) ; % chooser.addFileFilter( mFilter ) ; % chooser.noteFilter( mFilter ) ; j = j + 1 ; figFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , figFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , figFilter ) ; % chooser.addFileFilter( figFilter ) ; % chooser.noteFilter( figFilter ) ; j = j + 1 ; matFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , matFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , matFilter ) ; % chooser.addFileFilter( matFilter ) ; % chooser.noteFilter( matFilter ) ; j = j + 1 ; simFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , simFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , simFilter ) ; % chooser.addFileFilter( simFilter ) ; % chooser.noteFilter( simFilter ) ; j = j + 1 ; staFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , staFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , staFilter ) ; % chooser.addFileFilter( staFilter ) ; % chooser.noteFilter( staFilter ) ; j = j + 1 ; wksFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , wksFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , wksFilter ) ; % chooser.addFileFilter( wksFilter ) ; % chooser.noteFilter( wksFilter ) ; j = j + 1 ; rptFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , rptFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , rptFilter ) ; % chooser.addFileFilter( rptFilter ) ; % chooser.noteFilter( rptFilter ) ; j = j + 1 ; allFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , allFilter ) ; % chooser.addFileFilter( allFilter ) % chooser.noteFilter( allFilter ) ; % We shouldn't need the pause or the following drawnow - % But it doesn't work without them pause(.5) ; awtinvoke( chooser, 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allMatlabFilter ) ; drawnow() ; end % end loadDefaultFilters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Build a new filter containing an extension and a description %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buildFilter( desc , ext ) newFilter = com.mathworks.hg.util.dFilter ; newFilter.setDescription( desc ) ; newFilter.addExtension( ext ) ; end % buildFilter %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Add a filter to the indicated JFileChooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function addFilterToChooser( chooser , filter ) awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , filter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , filter ) ; % chooser.addFileFilter( filter ) ; % chooser.noteFilter( filter ) ; end % end addFilterToChooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Set the indicated filter's identifier (must be a string) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function setFilterIdentifier( filter , id ) filter.setIdentifier( id ) ; end % setFilterIdentifier %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Build a filter that "accepts" all files %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buildAllFilter() allFilter = com.mathworks.hg.util.AllFileFilter ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This handles the case where the filespec is a string %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handleStringFilespec( chooser , str , id ) %argUsedAsFileName = false ; useDefaultFilter = false; if( isempty( str ) ) % If the filter string is empty use defaults. useDefaultFilter = true; else filterspec = str ; %extStr = '' ; extStr = char(com.mathworks.hg.util.dFilter.returnExtensionString( str )) ; if( strcmpi( extStr , extError ) ) % This isn't a "legal" extension we know about. % Treat it as the name of a file or a path with filter % for COMPATIBILITY with the current release. So, it can be: % 'filename.m' % 'H:\filename.m' or '/home/user/filename.m' % 'H:\*.m' or '/home/user/*.m' % Do a fileparts to analyze the string. This returns us the % path, file and ext. [p, n, e] = fileparts(str); filename = ''; if ~isempty(p) filename = [p, filesep]; end if isempty(strfind(n, '*')) % There is no wildcard in the file name filename = [filename, n, e]; end % Set the file % test = java.io.File( str ) ; % if( test.isFile() ) awtinvoke( chooser , 'setSelectedFile(Ljava/io/File;)' , java.io.File( filename ) ) ; if isempty(e) % If no file extension was specified to be used as a % filter, use defaults useDefaultFilter = true; else % extStr is the extension w/o the '.' extStr = e(2:end); % filterspec is *.<ext> filterspec = ['*', e]; end end end if (useDefaultFilter) buildDefaultFilters() ; loadDefaultFilters( chooser , id ) ; awtinvoke( chooser , 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allMatlabFilter ) ; %argUsedAsFileName = true ; % else % theError = caErr1Message ; % filespecError = true ; % return ; % end else % Build a new filter. % Load the new filter and % load the "all" filter if necessary newFilter = [] ; if ( strcmp( char( spec ) , '*.*' ) ) buildAllFilter() ; setFilterIdentifier( allFilter , '1' ) ; addFilterToChooser( chooser , allFilter ) ; else buildFilter( filterspec, extStr ) ; setFilterIdentifier( newFilter , '1' ) ; addFilterToChooser( chooser , newFilter ) ; buildAllFilter() ; setFilterIdentifier( allFilter , '2' ) ; addFilterToChooser( chooser , allFilter ) ; end % don't know why the pause and drawnow are needed % but things don't work properly if they are not there pause(.5) ; % If necessary, set the active filter to the new filter if ~isempty( newFilter ) awtinvoke( chooser , 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , newFilter ) ; end drawnow() ; end % end if/else end % end handleStringFilespec %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This handles the case where the filespec is a cell array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handleCellArrayFilespec( theCellArray , chooser ) cellArrayOk = false ; t = '' ; rows = '' ; cols = '' ; try t = size( theCellArray ) ; rows = t(1) ; cols = t(2) ; catch ex theError = caErr1Message; return end if( 2 < cols ) theError = caErr2Message ; return end % The first col is supposed to hold an extension array extArray = '' ; descrArray = '' ; %ext = '' ; for i = 1:rows ext = theCellArray{ i , 1 } ; % Format the extension for our filter s = com.mathworks.hg.util.dFilter.returnExtensionString( char(ext) ) ; s = char( s ) ; if~( strcmpi( s , extError ) ) extArray{i} = s ; else theError = strcat( caErr3Message , ext , '''' ) ; cellArrayOk = false ; return end end % end for % If there are two cols, the 2nd col is % supposed to be descriptions for 1st col if( 2 == cols ) for i = 1 : rows descrArray{ i } = theCellArray{ i , 2 } ; end % end for i = 1 : rows end % end if( 2 == cols ) % Create the filters for file selection ii = 0 ; firstFilter = ''; %theFilter = ''; allFound = false; for i = 1:rows if( strcmp( char( extArray{i} ) , '*.*' )) % This corresponds to the All Files filter. % buildAllFilter() ; theFilter = com.mathworks.hg.util.AllFileFilter ; theFilter.setIdentifier( int2str( i ) ) ; addFilterToChooser(chooser, theFilter); % awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allFilter ) ; % awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , allFilter ) ; allFound = true ; else theFilter = com.mathworks.hg.util.dFilter ; theFilter.addExtension( extArray{i} ) ; theFilter.setIdentifier( int2str(i) ) ; if( 2 == cols ) theFilter.setDescription( descrArray{i} ) ; else theFilter.setDescription( theCellArray{i,1} ) ; end % end if( 2 == cols ) % Add the filter addFilterToChooser(chooser, theFilter); % awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , usrFilter ) ; % awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , usrFilter ) ; ii = i ; end % if( strcmp( char( extArray{i} ) , '*.*' )) % Set a current filter if( 1 == i ) firstFilter = theFilter ; end % end if( 1 == i ) end % end for i = 1:rows % Add in the "all" filter if( ~allFound ) % buildAllFilter() ; theFilter = com.mathworks.hg.util.AllFileFilter ; theFilter.setIdentifier( int2str( ii+1 ) ) ; addFilterToChooser(chooser, theFilter); % awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allFilter ) ; % awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , allFilter ) ; end % Set the user's first filter as the active filter % Shouldn't need the pause and drawnow, but things % don't work without them. pause(.5) ; awtinvoke( chooser , 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , firstFilter ) ; drawnow() ; cellArrayOk = true ; end % end handleCellArrayFilespec %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Scan the input arguments for 'MultiSelect' and 'Location'. % If either is present, check that the next arg has an % appropriate value. If not, set an appropriate error flag. % % Also, store all the other arguments in the array "remainderArgs". %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function eliminateBuiltIns() args = varargin ; numberOfArgs = numel( args ) ; remainderArgIndex = 1 ; i = 1 ; while( i <= numberOfArgs ) theArg = args{i} ; % Add to remainder args if its not a string if( ~( ischar( theArg ) ) || ~( isvector( theArg ) ) ) remainderArgs{ remainderArgIndex } = theArg ; %#ok<AGROW> remainderArgIndex = remainderArgIndex + 1 ; i = i + 1 ; %end % end if( ~( ischar( theArg ) ) | ~( isvector( theArg ) ) ) if( i > numberOfArgs ) return end continue end % end if( ~( ischar( theArg ) ) | ~( isvector( theArg ) ) ) % Transpose if necessary if( ~( 1 == size( theArg , 1 ) ) ) theArg = theArg' ; end % Check to see if we have an interesting string lowArg = lower( theArg ) ; if( ~strcmp( 'multiselect' , lowArg ) && ~strcmp( 'location' , lowArg ) ) remainderArgs{ remainderArgIndex } = theArg ; %#ok<AGROW> remainderArgIndex = remainderArgIndex + 1 ; i = i + 1 ; continue ; end % end if( ~strcmp( 'multiselect' , lowArg ) ... % Check the next arg - we have found 'multiselect' or 'location' i = i + 1 ; if( i > numberOfArgs ) % oops - missing arg switch( lowArg ) case 'multiselect' theError = badMultiMessage ; multiSelectError = true ; return case 'location' theError = badLocMessage ; locationError = true ; return end % end switch return end % end if( i > numberOfArgs ) nextArg = args{ i } ; switch( lowArg ) case 'multiselect' % nextArg must be 'on' or 'off' if( ~( ischar( nextArg ) ) || ~( isvector( nextArg ) ) ) theError = badMultiMessage ; multiSelectError = true ; return end if( ~( 1 == size( nextArg , 1 ) ) ) nextArg = nextArg' ; end if( ~( strcmpi( 'on',nextArg ) ) && ~( strcmpi( 'off' , nextArg) ) ) theError = badMultiMessage ; multiSelectError = true ; return end multiSelectFound = true ; multiSelectPosition = i - 1 ; if( strcmpi( 'on' , nextArg ) ) multiSelectOn = true ; end i = i + 1 ; if( i > numberOfArgs ) return end case 'location' % nextArg must be a numeric vector if( ~( isvector( nextArg ) ) || ... ~( isnumeric( nextArg ) ) ) theError = badLocMessage ; locationError = true ; return end % Transpose if necessary if( ~( 1 == size( nextArg , 1 ) ) ) nextArg = nextArg' ; end % Check size if( ~( 1 == size( nextArg , 1 ) ) || ... ~( 2 == size( nextArg , 2 ) ) ) theError = badLocMessage ; locationError = true ; return end % Record the fact that we've found 'location' locationFound = true ; locationPosition = i - 1 ; % skip to the next arg i = i + 1 ; if( i > numberOfArgs ) return end end % end switch end % end while end % eliminateBuiltIns function out = mydialog(varargin) out = []; try out = dialog(varargin{:}) ; catch ex rethrow(ex) end end % end myDialog end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the callback from the JFileChooser. If the user % selected "Open", return the name of the selected file, % the full pathname and the index of the current filter. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function callbackHandler(obj, evd, d , multiSelectOn , sys ) fileSeparator = filesep ; %pathSeparator = pathsep ; jfc = obj; cmd = char(evd.getPropertyName()) ; switch(cmd) case 'mathworksHgCancel' if ishandle(d) close(d) end case 'mathworksHgOk' selectionFilter = jfc.getFileFilter() ; if( ~multiSelectOn ) [pathname, fn, ext ] = fileparts(char(jfc.getSelectedFile.toString)); filename = [fn ext]; pathname = strcat( pathname , fileSeparator ) ; else % Multi Select is On fileObjArray = jfc.getSelectedFiles ; fileNames = jfc.getSelectedFileNames() ; rows = size( fileNames , 1 ) ; cols = size( fileNames , 2 ) ; %#ok<NASGU> x = '' ;%( 1 , rows ) ; j = 1 ; for i = 1 : rows %x{ 1 , i } = char( fileNames( i , 1 ) ) ;xxxxxx if( ~( strncmp( 'MAC' , sys, 3 ) ) ) x{ 1 , i } = char( fileNames( i , 1 ) ) ; else name = char( fileNames( i , 1 ) ) ; if( selectionFilter.accept( java.io.File( name ) ) ) x{ 1 , j } = name ; j = j + 1 ; end end end % end for i = 1 : rows filename = x ; fileObj = fileObjArray(1) ; [pathname, fn, ext ] = fileparts(char(fileObj.getAbsolutePath())); %#ok<NASGU,NASGU> pathname = strcat( pathname , fileSeparator ) ; end % end if( ~multiSelectOn ) uigetfileData.filename = filename ; uigetfileData.pathname = pathname ; uigetfileData.filterindex = str2double( selectionFilter.getIdentifier() ) ; setappdata( 0 , 'uigetfileData' , uigetfileData ) ; close(d); end % end switch end % end callbackHandler
github
BottjerLab/Acoustic_Similarity-master
removeJavaCallbacks.m
.m
Acoustic_Similarity-master/code/interactive/private/removeJavaCallbacks.m
1,211
utf_8
9275dd0972c0c82aabff1abd170e22f5
% Copyright 2011 The MathWorks, Inc. % This function is for internal use and will change in a future release %----------------------------------------------------- % We are giving ourselves a hook to run resource cleanup functions % like freeing up callbacks. This is important for uitree because % the expand and selectionchange callbacks need to be freed when % the figure is destroyed. See G769077 for more information. %----------------------------------------------------- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Empties all callbacks on the given java UDD handle %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function removeJavaCallbacks(jh) c = classhandle(jh); if (~isJavaHandleWithCallbacks(c)) return; end E = c.Events; for k = 1:length(E) set(jh, [E(k).Name 'Callback'] , []); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Helper that determines if a given class handle % is a java handle with callbacks or not %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function withCbks = isJavaHandleWithCallbacks(metacls) assert(isa(metacls,'schema.class')); pkgName = metacls.Package.Name; withCbks = strcmp(pkgName,'javahandle_withcallbacks'); end
github
BottjerLab/Acoustic_Similarity-master
uisetcolor_helper.m
.m
Acoustic_Similarity-master/code/interactive/private/uisetcolor_helper.m
2,450
utf_8
3198fc328516b1eb1e94d7d5383ec49f
function selectedColor = uisetcolor_helper(varargin) % Copyright 2007-2010 The MathWorks, Inc. % $Revision: 1.1.6.9 $ $Date: 2011/09/23 19:13:38 $ [rgbColorVector,title,fhandle] = parseArgs(varargin{:}); ccDialog = matlab.ui.internal.dialog.ColorChooser; ccDialog.Title = title; if ~isempty(rgbColorVector) ccDialog.InitialColor = rgbColorVector; end selectedColor = showDialog(ccDialog); if (~isempty(rgbColorVector) && ~(size(selectedColor,2)==3)) selectedColor = rgbColorVector; end if ~isempty(fhandle) try set(fhandle,'Color',selectedColor); catch try set(fhandle,'ForegroundColor',selectedColor); catch try set(fhandle,'BackgroundColor',selectedColor); catch end end end end % Done. MCOS Object ccDialog cleans up and its java peer at the end of its % scope(AbstractDialog has a destructor that every subclass % inherits) function [rgbColorVector,title,handle] = parseArgs(varargin) handle = []; rgbColorVector = []; title = getString(message('MATLAB:uistring:uisetcolor:TitleColor')); if nargin>2 error(message('MATLAB:uisetcolor:TooManyInputs')) ; end if (nargin==2) if ~ischar(varargin{2}) error(message('MATLAB:uisetcolor:InvalidSecondParameter')); end title = varargin{2}; end if (nargin>=1) if (isscalar(varargin{1}) && ishghandle(varargin{1})) handle = varargin{1}; rgbColorVector = getrgbColorVectorFromHandle(handle); elseif (~ischar(varargin{1}) && isnumeric(varargin{1})) rgbColorVector = varargin{1}; elseif ischar(varargin{1}) if (nargin > 1) error(message('MATLAB:uisetcolor:InvalidParameterList')); end title = varargin{1}; else error(message('MATLAB:uisetcolor:InvalidFirstParameter')); end end %Given the dialog, user chooses to select or not select function rgbColorVector = showDialog(ccDialog) ccDialog.show; rgbColorVector = ccDialog.SelectedColor; if isempty(rgbColorVector) rgbColorVector = 0; end %Helper functions to extract color(rgbColorVector) from the given handle function rgbValue = getrgbColorVectorFromHandle(fhandle) rgbValue = [0 0 0]; try rgbValue = get(fhandle,'Color'); catch try rgbValue = get(fhandle,'ForegroundColor'); catch try rgbValue = get(fhandle,'BackgroundColor'); catch end end end
github
BottjerLab/Acoustic_Similarity-master
javaaddlistener.m
.m
Acoustic_Similarity-master/code/interactive/private/javaaddlistener.m
1,648
utf_8
b588fa2b4b900654813b0c5e822813c7
function hdl=javaaddlistener(jobj, eventName, response) % ADDLISTENER Add a listener to a Java object. % % L=ADDLISTENER(JObject, EventName, Callback) % Adds a listener to the specified Java object for the given % event name. The listener will stop firing when the return % value L goes out of scope. % % ADDLISTENER(JObject) % Lists all the available event names. % % Examples: % % jf = javaObjectEDT('javax.swing.JFrame'); % addlistener(jf) % list all events % % % Basic string eval callback: % addlistener(jf,'WindowClosing','disp closing') % % % Function handle callback % addlistener(jf,'WindowClosing',@(o,e) disp(e)) % Copyright 2003-2010 The MathWorks, Inc. % make sure we have a Java objects if ~isjava(jobj) error(message('MATLAB:addlistener:InvalidNonJavaObject')) end if nargin == 1 if nargout error(message('MATLAB:addlistener:InvalidNumberOfInputArguments')) end % just display the possible events hSrc = handle(jobj,'callbackproperties'); allfields = sortrows(fields(set(hSrc))); for i = 1:length(allfields) fn = allfields{i}; if ~isempty(strfind(fn,'Callback')) fn = strrep(fn,'Callback',''); disp(fn) end end return; end hdl = handle.listener(handle(jobj), eventName, ... @(o,e) cbBridge(o,e,response)); set(hdl,'RecursionLimit',255); % Allow nested callbacks g681014 end function cbBridge(o,e,response) hgfeval(response, java(o), e.JavaEvent) end % LocalWords: JObject jf invalidinput callbackproperties
github
BottjerLab/Acoustic_Similarity-master
uitable_deprecated.m
.m
Acoustic_Similarity-master/code/interactive/private/uitable_deprecated.m
7,741
utf_8
d10f44f75391f13c0bddf79d7d3ee0a3
function [table, container] = uitable_deprecated(varargin) % This function is undocumented and has been replaced % See also UITABLE % Copyright 2002-2012 The MathWorks, Inc. % $Revision: 1.1.6.9 $ $Date: 2012/07/05 16:48:24 $ % Warn that this old code path is no longer supported. warn = warning('query', 'MATLAB:uitable:DeprecatedFunction'); if isequal(warn.state, 'on') warning(message('MATLAB:uitable:DeprecatedFunction')); end % Setup and P-V parsing % Change to if ~(usejavacomponent) when we find the appropriate error % message. error(javachk('awt')); error(nargoutchk(0,2,nargout)); parent = []; numargs = nargin; % The rest of this code to be moved to private\uitable_deprecated.m. datastatus=false; columnstatus=false; rownum = 1; colnum = 1; % Default to a 1x1 table. position = [20 20 200 200]; combo_box_found = false; check_box_found = false; import com.mathworks.hg.peer.UitablePeer; if (numargs > 0 && isscalar(varargin{1}) && ... ishghandle(varargin{1}, 'figure')) parent = varargin{1}; varargin = varargin(2:end); numargs = numargs - 1; end if (numargs > 0 && isscalar(varargin{1}) && ishandle(varargin{1})) if ~isa(varargin{1}, 'javax.swing.table.DefaultTableModel') error('MATLAB:uitable:UnrecognizedParameter', ['Unrecognized parameter: ', varargin{1}]); end data_model = varargin{1}; varargin = varargin(2:end); numargs = numargs - 1; elseif ((numargs > 1) && isscalar(varargin{1}) && isscalar(varargin{2})) if(isnumeric(varargin{1}) && isnumeric(varargin{2})) rownum = varargin{1}; colnum = varargin{2}; varargin = varargin(3:end); numargs = numargs-2; else error(message('MATLAB:uitable:InputMustBeScalar')) end elseif ((numargs > 1) && isequal(size(varargin{2},1), 1) && iscell(varargin{2})) if (size(varargin{1},2) == size(varargin{2},2)) if (isnumeric(varargin{1})) varargin{1} = num2cell(varargin{1}); end else error(message('MATLAB:uitable:MustMatchInfo')); end data = varargin{1}; datastatus = true; coln = varargin{1+1}; columnstatus = true; varargin = varargin(3:end); numargs = numargs-2; end for i = 1:2:numargs-1 if (~ischar(varargin{i})) error('MATLAB:uitable:UnrecognizedParameter', ['Unrecognized parameter: ', varargin{i}]); end switch lower(varargin{i}) case 'data' if (isnumeric(varargin{i+1})) varargin{i+1} = num2cell(varargin{i+1}); end data = varargin{i+1}; datastatus = true; case 'columnnames' if(iscell(varargin{i+1})) coln = varargin{i+1}; columnstatus = true; else error(message('MATLAB:uitable:InvalidCellArray')) end case 'numrows' if (isnumeric(varargin{i+1})) rownum = varargin{i+1}; else error(message('MATLAB:uitable:NumrowsMustBeScalar')) end case 'numcolumns' if (isnumeric(varargin{i+1})) colnum = varargin{i+1}; else error(message('MATLAB:uitable:NumcolumnsMustBeScalar')) end case 'gridcolor' if (ischar(varargin{i+1})) gridcolor = varargin{i+1}; else if (isnumeric(varargin{i+1}) && (numel(varargin{i+1}) == 3)) gridcolor = varargin{i+1}; else error(message('MATLAB:uitable:InvalidString')) end end case 'rowheight' if (isnumeric(varargin{i+1})) rowheight = varargin{i+1}; else error(message('MATLAB:uitable:RowheightMustBeScalar')) end case 'parent' if ishandle(varargin{i+1}) parent = varargin{i+1}; else error(message('MATLAB:uitable:InvalidParent')) end case 'position' if (isnumeric(varargin{i+1})) position = varargin{i+1}; else error(message('MATLAB:uitable:InvalidPosition')) end case 'columnwidth' if (isnumeric(varargin{i+1})) columnwidth = varargin{i+1}; else error(message('MATLAB:uitable:ColumnwidthMustBeScalar')) end otherwise error('MATLAB:uitable:UnrecognizedParameter', ['Unrecognized parameter: ', varargin{i}]); end end % ---combo/check box detection--- % if (datastatus) if (iscell(data)) rownum = size(data,1); colnum = size(data,2); combo_count =0; check_count = 0; combo_box_data = num2cell(zeros(1, colnum)); combo_box_column = zeros(1, colnum); check_box_column = zeros(1, colnum); for j = 1:rownum for k = 1:colnum if (iscell(data{j,k})) combo_box_found = true; combo_count = combo_count + 1; combo_box_data{combo_count} = data{j,k}; combo_box_column(combo_count ) = k; dc = data{j,k}; data{j,k} = dc{1}; else if(islogical(data{j,k})) check_box_found = true; check_count = check_count + 1; check_box_column(check_count) = k; end end end end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%% % Check the validity of the parent and/or create a figure. if isempty(parent) parent = gcf; % Get the current figure. Create one if not available end if ( columnstatus && datastatus ) if(size(data,2) ~= size(coln,2)) error(message('MATLAB:uitable:NeedSameNumberColumns')); end elseif ( ~columnstatus && datastatus ) for i=1:size(data,2) coln{i} = num2str(i); end columnstatus = true; elseif ( columnstatus && ~datastatus) error(message('MATLAB:uitable:NoDataProvided')); end if (~exist('data_model', 'var')) data_model = javax.swing.table.DefaultTableModel; end if exist('rownum', 'var') data_model.setRowCount(rownum); end if exist('colnum', 'var') data_model.setColumnCount(colnum); end table_h= UitablePeer(data_model); % We should have valid data and column names here. if (datastatus), table_h.setData(data); end; if (columnstatus), table_h.setColumnNames(coln); end; if (combo_box_found), for i=1:combo_count table_h.setComboBoxEditor(combo_box_data(i), combo_box_column(i)); end end if (check_box_found), for i = 1: check_count table_h.setCheckBoxEditor(check_box_column(i)); end end [table, container] = javacomponentfigurechild_helper(table_h, position, parent); % Have to do a drawnow here to make the properties stick. Try to restrict % the drawnow call to only when it is absolutely required. flushed = false; if exist('gridcolor', 'var') pause(.1); drawnow; flushed = true; table_h.setGridColor(gridcolor); end if exist('rowheight', 'var') if (~flushed) drawnow; end table_h.setRowHeight(rowheight); end if exist('columnwidth', 'var') table_h.setColumnWidth(columnwidth); end; % Add a predestroy listener so we can call cleanup on the table. temp = handle.listener(table, 'ObjectBeingDestroyed', @componentDelete); save__listener__(table,temp); function componentDelete(src, evd) %#ok % Clean up the table here so it disengages all its internal listeners. src.cleanup;
github
BottjerLab/Acoustic_Similarity-master
uitree_deprecated.m
.m
Acoustic_Similarity-master/code/interactive/private/uitree_deprecated.m
7,914
utf_8
6958f7f99706f031c84da06056614a35
function [tree, container] = uitree_deprecated(varargin) % This function is undocumented and will change in a future release % Copyright 2003-2012 The MathWorks, Inc. % Release: R14. This feature will not work in previous versions of MATLAB. % Warn that this old code path is no longer supported. warn = warning('query', 'MATLAB:uitree:DeprecatedFunction'); if isequal(warn.state, 'on') warning(message('MATLAB:uitree:DeprecatedFunction')); end %% Setup and P-V parsing. error(javachk('jvm')); error(nargoutchk(0, 2, nargout)); fig = []; numargs = nargin; if (nargin > 0 && isscalar(varargin{1}) && ishandle(varargin{1})) if ~ishghandle(handle(varargin{1}), 'figure') error(message('MATLAB:uitree:InvalidFigureHandle')); end fig = varargin{1}; varargin = varargin(2:end); numargs = numargs - 1; end % RootFound = false; root = []; expfcn = []; selfcn = []; pos = []; % parent = []; if (numargs == 1) error(message('MATLAB:uitree:InvalidNumInputs')); end for i = 1:2:numargs-1 if ~ischar(varargin{i}) error(message('MATLAB:uitree:UnrecognizedParameter')); end switch lower(varargin{i}) case 'root' root = varargin{i+1}; case 'expandfcn' expfcn = varargin{i+1}; case 'selectionchangefcn' selfcn = varargin{i+1}; case 'parent' if ishandle(varargin{i+1}) f = varargin{i+1}; if ishghandle(handle(f), 'figure') fig = f; end end case 'position' p = varargin{i+1}; if isnumeric(p) && (length(p) == 4) pos = p; end otherwise error('MATLAB:uitree:UnknownParameter', ['Unrecognized parameter: ', varargin{i}]); end end if isempty(expfcn) [root, expfcn] = processNode(root); else root = processNode(root); end % This should not be tagged for EDT invocation. This is a FigureChild. % Its public methods expect main thread invocation which subsequently post % stuff to EDT. tree_h = com.mathworks.hg.peer.UITreePeer; tree_h.setRoot(root); if isempty(fig) fig = gcf; end if isempty(pos) figpos = get(fig, 'Position'); pos = [0 0 min(figpos(3), 200) figpos(4)]; end [tree, container] = javacomponentfigurechild_helper(tree_h,pos, fig); if ~isempty(expfcn) set(tree, 'NodeExpandedCallback', {@nodeExpanded, tree, expfcn}); end if ~isempty(selfcn) set(tree, 'NodeSelectedCallback', {@nodeSelected, tree, selfcn}); end end %% ----------------------------------------------------- function nodeExpanded(src, evd, tree, expfcn) %#ok % tree = handle(src); % evdsrc = evd.getSource; evdnode = evd.getCurrentNode; % indices = []; if ~tree.isLoaded(evdnode) value = evdnode.getValue; % <call a user function(value) which returns uitreenodes>; cbk = expfcn; if iscell(cbk) childnodes = feval(cbk{1}, tree, value, cbk{2:end}); else childnodes = feval(cbk, tree, value); end if (length(childnodes) == 1) % Then we dont have an array of nodes. Create an array. chnodes = childnodes; childnodes = javaArray('com.mathworks.hg.peer.UITreeNode', 1); childnodes(1) = java(chnodes); end tree.add(evdnode, childnodes); tree.setLoaded(evdnode, true); end end %% ----------------------------------------------------- function nodeSelected(src, evd, tree, selfcn) %#ok cbk = selfcn; hgfeval(cbk, tree, evd); end %% ----------------------------------------------------- function [node, expfcn] = processNode(root) expfcn = []; if isempty(root) || isa(root, 'com.mathworks.hg.peer.UITreeNode') || ... isa(root, 'javahandle.com.mathworks.hg.peer.UITreeNode') node = root; elseif ishghandle(root) % Try to process as an HG object. try %In the HG tree rendering, the java side is intelligent enough to %pick an icon based on the class of the object that we are sending %in. It is absolutely essential that we send in the handle to java %because the icon picking is based on the bean adapter's display %name. node = uitreenode_deprecated(handle(root), get(root, 'Type'), ... [], isempty(get(0, 'Children'))); catch ex %#ok mlint node = []; end expfcn = @hgBrowser; elseif ismodel(root) % Try to process as an open Simulink system % TODO if there is an open simulink system and a directory on the path with % the same name, the system will hide the directory. Perhaps we should % warn about this. try h = handle(get_param(root,'Handle')); % TODO we pass root to the tree as a string, % it would be better if we could just pass the % handle up node = uitreenode_deprecated(root, get(h, 'Name'), ... [], isempty(h.getHierarchicalChildren)); catch ex %#ok mlint node = []; end expfcn = @mdlBrowser; elseif ischar(root) % Try to process this as a directory structure. try iconpath = [matlabroot, '/toolbox/matlab/icons/foldericon.gif']; node = uitreenode_deprecated(root, root, iconpath, ~isdir(root)); catch ex %#ok mlint node = []; end expfcn = @dirBrowser; else node = []; end end %% ----------------------------------------------------- function nodes = hgBrowser(tree, value) %#ok try count = 0; parent = handle(value); ch = parent.children; for i=1:length(ch) count = count+1; nodes(count) = uitreenode_deprecated(handle(ch(i)), get(ch(i), 'Type'), [], ... isempty(get(ch(i), 'Children'))); end catch error(message('MATLAB:uitree:UnknownNodeType')); end if (count == 0) nodes = []; end end %% ----------------------------------------------------- function nodes = mdlBrowser(tree, value) %#ok try count = 0; parent = handle(get_param(value,'Handle')); ch = parent.getHierarchicalChildren; for i=1:length(ch) if isempty(findstr(class(ch(i)),'SubSystem')) % not a subsystem else % is a subsystem count = count+1; descr = get(ch(i),'Name'); isleaf = true; cch = ch(i).getHierarchicalChildren; if ~isempty(cch) for j = 1:length(cch) if ~isempty(findstr(class(cch(j)),'SubSystem')) isleaf = false; break; end end end nodes(count) = uitreenode_deprecated([value '/' descr], descr, [], ... isleaf); end end catch error(message('MATLAB:uitree:UnknownNodeType')); end if (count == 0) nodes = []; end end %% ----------------------------------------------------- function nodes = dirBrowser(tree, value) %#ok try count = 0; ch = dir(value); for i=1:length(ch) if (any(strcmp(ch(i).name, {'.', '..', ''})) == 0) count = count + 1; if ch(i).isdir iconpath = [matlabroot, '/toolbox/matlab/icons/foldericon.gif']; else iconpath = [matlabroot, '/toolbox/matlab/icons/pageicon.gif']; end nodes(count) = uitreenode_deprecated([value, ch(i).name, filesep], ... ch(i).name, iconpath, ~ch(i).isdir); end end catch error(message('MATLAB:uitree:UnknownNodeType')); end if (count == 0) nodes = []; end end %% ----------------------------------------------------- function yesno = ismodel(input) yesno = false; try if is_simulink_loaded get_param(input,'handle'); yesno = true; end end end
github
BottjerLab/Acoustic_Similarity-master
uisetcolor_deprecated.m
.m
Acoustic_Similarity-master/code/interactive/private/uisetcolor_deprecated.m
14,563
utf_8
b29ebe5b5c83b36a119bca02eb0be77f
function [selectedColor] = uisetcolor_deprecated(varargin) % Copyright 1984-2010 The MathWorks, Inc. % $Revision: 1.1.6.9 $ $Date: 2011/03/09 07:07:39 $ %%%%%%%%%%%%%%%% % Error messages %%%%%%%%%%%%%%%% %bad1ArgMessage = 'First of two args cannot be a string' ; bad2ArgMessage = 'Second argument (dialog title) must be a string.' ; badTitleMessage = 'title must be the last parameter passed to uisetcolor.' ; badNumArgMessage = 'Too many input arguments.' ; badRgbAryMessage = 'Color value contains NaN, or element out of range 0.0 <= value <= 1.0.' ; badObjTypMessage = 'Color selection is not supported for light objects.' ; badPropertyMessage = 'Color selection is only supported for objects with Color or ForeGroundColor properties.' ; badColorValMessage = 'Color value must be a 3 element numeric vector.' ; badColorSelMessage1 = 'Color selection is not supported for' ; badColorSelMessage2 = ' objects, but only for objects with Color or ForeGroundColor properties.' ; maxArgs = 2 ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check the number of args - must be <= maxArgs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% numArgs = nargin ; if( numArgs > maxArgs ) error( badNumArgMessage ) end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Restrict new version to the mac % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If we are on the mac, default to using non-native % dialog. If the root property UseNativeSystemDialogs % is false, use the non-native version instead. useNative = true; %#ok<NASGU> % If we are on the Mac & swing is available, set useNative to false, % i.e., we are going to use Java dialogs not native dialogs. % Comment the following line to disable java dialogs on Mac. useNative = ~( ismac && usejava('awt') ) ; % If the root appdata is set and swing is available, % honor that overriding all other prefs. % if isequal(0, getappdata(0,'UseNativeSystemDialogs')) && usejava('awt') % useNative = false ; % end if useNative try if nargin == 0 [selectedColor] = native_uisetcolor ; else [selectedColor] = native_uisetcolor( varargin{:} ) ; end catch ex rethrow(ex) end return end % end useNative %%%%%%%%%%%%%%%%% % General globals %%%%%%%%%%%%%%%%% %dcc = '' ; % dColorChooser - our Java ColorChooser rgbArray = '' ; %sz = '' ; objectType = '' ; %propertyName = '' ; firstArg = '' ; propUsed = '' ; userTitle = '' ; sys = char( computer ) ; % String the type of computer - PCWIN, MAC, ...ui %%%%%%% % Flags %%%%%%% typeFound = false ; rgbHandedIn = false ; objectHandedIn = false ; arg1IsBad = false ; arg1IsRGB = false ; arg1IsChar = false ; arg1IsHgHandle = false ; %rgbError = false ; %%%%%%%%%%%%%%%%%%%%%% % Default color values %%%%%%%%%%%%%%%%%%%%%% red = 1.0 ; green = 1.0 ; blue = 1.0 ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Check the first arg if there is one %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 1 <= numArgs ) firstArg = varargin{1} ; getArg1Type() ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Bail out if the first arg is not the correct type %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( arg1IsBad ) if( ishandle( firstArg ) ) try objectType = get( firstArg , 'Type' ) ; typeFound = true ; catch end end % end if( ishandle( firstArg ) ) if( ~typeFound ) error( badPropertyMessage ) ; else objectType = strcat( ' ' , objectType ) ; error( strcat( badColorSelMessage1 , objectType , badColorSelMessage2 ) ) ; end return ; % end if( arg1IsBad ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Check to see that we really do have an RGB arg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif( arg1IsRGB ) % Check for 3 vals if ~( 3 == length( firstArg ) ) error( badColorValMessage ) ; end rgbArray = firstArg; % Check that vals are in range rgbError = checkRGB() ; if( rgbError ) error( badRgbAryMessage ) end % Overwrite the default rgb values red = rgbArray( 1 , 1 ) ; green = rgbArray( 1 , 2 ) ; blue = rgbArray( 1 , 3 ) ; rgbHandedIn = true ; % end if( arg1IsRGB ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Make sure that if first arg is a string, then it's the only arg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif( arg1IsChar ) if~( 1 == numArgs ) error( badTitleMessage ) end % We'll use the string as a title userTitle = firstArg ; %end if( arg1IsChar ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Make sure the object is not of type 'light' (cpmpat) % and that it has the Color or ForegroundColor property %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else if( arg1IsHgHandle ) objectType = get( firstArg , 'Type' ) ; % The current uisetcolor does not support "light" objects %if( strcmp( 'light' , lower( objectType ) ) ) if (strcmpi('light',objectType)) error( badObjTypMessage ) end hasColorProperty = false ; hasForegroundProperty = false ; % Make sure the object has either the % Color or ForegroundColor property. propFound = false ; try rgbArray = get( firstArg , 'Color' ) ; hasColorProperty = true ; propUsed = 'Color' ; propFound = true ; catch end if( ~propFound ) try rgbArray = get( firstArg , 'ForegroundColor' ) ; hasForegroundProperty = true ; propUsed = 'ForegroundColor' ; catch end end % end if( ~propFound ) if( ~hasColorProperty && ~hasForegroundProperty ) error( badPropertyMessage ) end % Overwrite the default rgb values red = rgbArray( 1 , 1 ) ; green = rgbArray( 1 , 2 ) ; blue = rgbArray( 1 , 3 ) ; objectHandedIn = true ; end % end if( arg1IsHgHandle ) end % end of if/elseif end % end if( 1 <= numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If there are two args, the second must be a character string %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 2 == numArgs ) arg2 = varargin{ 2 } ; if( ~( ischar( arg2 ) ) ) error( bad2ArgMessage ) end if( ~( 1 == size( arg2 , 1 ) ) ) arg2 = arg2'; if( ~( ischar( arg2 ) ) ) error( bad2ArgMessage ) end end % end if( ~( 1 == size( arg2 , 1 ) ) ) userTitle = arg2 ; end % end if( 2 == numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Create a dialog to hold our ColorChooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % jp = handle(javax.swing.JPanel) ; jp = awtcreate('com.mathworks.mwswing.MJPanel', ... 'Ljava.awt.LayoutManager;', ... java.awt.BorderLayout); % Dialog title is set later d = mydialog( ... 'Visible','off', ... 'Color',get(0,'DefaultUicontrolBackgroundColor'), ... 'Windowstyle','modal', ... 'Resize','on' ) ; % Create an MJPanel and put it into the dialog - this is for resizing [panel, container] = javacomponent(handle(jp),[10 10 20 20],d); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Create a chooser with the appropriate initial setting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( objectHandedIn ) % Some object was handed in. Find its Color-related properties. s = set( firstArg ) ; flds = fields( s ) ; propArray = '' ; j = 1 ; % Create an array of "Color-related" properties for this figure for i = 1 : length( flds ) if ~( isempty( findstr( flds{i} , 'Color' ) ) ) propArray{ 1 , j } = flds{i} ; j = j + 1 ; end % end if end % end for jcc = handle(com.mathworks.hg.util.dColorChooser( java.awt.Color( red , green , blue ) , propArray , propUsed , sys )); % Make the dialog large enough % to show the Color-related properties combo box set( d , 'Position' , [232 246 145 270] ) ; else % No object was handed in. % No combo box - figure can be smaller set( d , 'Position' , [232 246 145 230] ) ; jcc = handle(com.mathworks.hg.util.dColorChooser( java.awt.Color( red , green , blue ) , [] , [] , sys )); end % end if( objectHandedIn ) % Use supplied title if one was given else use default if ~( strcmp( '' , userTitle ) ) set( d , 'Name' , userTitle ) ; else set( d , 'Name' , char( jcc.getDefaultTitle() ) ) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Add the panel holding the actual chooser to the panel in the dialog %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% dcc = jcc.getContentPanel() ; awtinvoke(java(panel), 'add(Ljava.awt.Component;)', dcc); set(container,'Units','normalized','Position',[0 0 1 1]); %%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%% % Set up callbacks %%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%% % jbOK = javax.swing.JButton() ; jbOK = handle( jcc.getOkButton(), 'callbackproperties') ; set(jbOK ,'ActionPerformedCallback', {@callbackHandler , firstArg , d , jcc , objectHandedIn , rgbHandedIn , rgbArray}) % jbCancel = javax.swing.JButton() ; jbCancel = handle(jcc.getCancelButton(), 'callbackproperties') ; set(jbCancel,'ActionPerformedCallback', {@callbackHandler , firstArg , d , jcc , objectHandedIn , rgbHandedIn , rgbArray}) %%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%% % Display everything %%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%% figure(d) refresh(d) % Set the default return value to 0 selectedColor = 0 ; % If RGB or object handle is passed in, set default return value to the % specified color. This is used if an error occurs or the user hits % Cancel. if( rgbHandedIn || objectHandedIn ) % changed 12-30-04 Dave Oppenheim selectedColor = rgbArray ; % See comment at line 283 end waitfor(d); if isappdata( 0 , 'uisetcolorData' ) selectedColor = getappdata( 0 , 'uisetcolorData' ) ; rmappdata( 0 , 'uisetcolorData' ) ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Discover the type of the first arg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function getArg1Type() if( ishghandle( firstArg ) & ( 1 == length( firstArg ) ) ) arg1IsHgHandle = true ; elseif ( ischar( firstArg ) ) arg1IsChar = true ; elseif( isnumeric( firstArg ) && isvector( firstArg ) ) arg1IsRGB = true ; else arg1IsBad = true ; end end % end getArg1Type() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Check the values in an array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rgbErr = checkRGB() rgbErr = false; % Transpose if necessary ( maybe user handed in 3 by 1 array ) if( ~( 1 == size( rgbArray , 1) ) ) rgbArray = rgbArray' ; end % Validate size and component values OF rgbArray if( ~( 1 == size( rgbArray , 1 ) ) | ~( 3 == size( rgbArray , 2 ) ) | ... ( 1.0 < rgbArray(1) ) | ( rgbArray(1) < 0.0 ) | ... ( 1.0 < rgbArray(2) ) | ( rgbArray(2) < 0.0 ) | ... ( 1.0 < rgbArray(3) ) | ( rgbArray(3) < 0.0 ) ) rgbErr = true ; end end % end function checkRGB() function out = mydialog(varargin) out = []; try out = dialog(varargin{:}) ; catch ex rethrow(ex) end end % end myDialog end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The callback function for the chooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function callbackHandler( obj , evd , firstArg , d , jcc , objectHandedIn , rgbHandedIn , rgbArg ) cmd = char(evd.getActionCommand()); switch(cmd) case 'dColorChooserOK' red = jcc.getColor.getRed/255 ; green = jcc.getColor.getGreen/255 ; blue = jcc.getColor.getBlue/255 ; % If an object was handed in (via its handle), % set the appropriate color-related property % to the value selected by the user. if( objectHandedIn ) propertyName = char(jcc.getProperty()) ; z = [ red green blue ] ; if ~( strcmp( propertyName , 'None' ) ) set( firstArg , propertyName ,z ) ; end end % end if( objectHandedIn ) % Set the return value selectedColor = [ red green blue ] ; setappdata( 0 , 'uisetcolorData' , selectedColor ) ; % Cleanup jcc.cleanup(); if ishandle(d) close(d) end case 'dColorChooserCancel' % If user hits Cancel, we use the default values that are set up % accordingly. % Cleanup jcc.cleanup(); if ishandle(d) close(d) end otherwise error(message('MATLAB:uisetcolor_deprecated:UnimplementedOption', cmd)) end end % end callbackHandler
github
BottjerLab/Acoustic_Similarity-master
javacomponentundoc_helper.m
.m
Acoustic_Similarity-master/code/interactive/private/javacomponentundoc_helper.m
20,472
utf_8
1d9e111d2f81fc5e516d0bfa653fae2f
function [hcomponent, hcontainer] = javacomponentundoc_helper(varargin) % Copyright 2010-2012 The MathWorks, Inc. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Old javacomponent implementation. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if (nargin>=1) component = varargin{1}; end if (nargin>=2) position = varargin{2}; end if (nargin>=3) parent = varargin{3}; end if (nargin==4) callback = varargin{4}; end if (usejavacomponent == 0) error(message('MATLAB:javacomponent:FeatureNotSupported')); end if ~isempty(nargchk(1,4,nargin)) %#ok error('MATLAB:javacomponent',getString(message('MATLAB:javacomponent:IncorrectUsage'))); end if nargin < 4 callback = ''; else if ~iscell(callback) error('MATLAB:javacomponent',getString(message('MATLAB:javacomponent:IncorrectUsage'))); end end if nargin < 3 parent = gcf; end if nargin < 2 position = [20 20 60 20]; end parentIsFigure = false; hParent = handle(parent); % g500548 - changed to use ishghandle. if ( ishghandle(hParent, 'figure') || ... ishghandle(hParent, 'uicontainer') || ... ishghandle(hParent, 'uiflowcontainer') || ... ishghandle(hParent, 'uigridcontainer')) parentIsFigure = true; peer = getJavaFrame(ancestor(parent,'figure')); elseif ishghandle(hParent, 'uitoolbar') peer = get(parent,'JavaContainer'); if isempty(peer) drawnow; peer = get(parent,'JavaContainer'); end elseif (ishghandle(hParent, 'uisplittool') || ... ishghandle(hParent, 'uitogglesplittool')) parPeer = get(get(hParent,'Parent'),'JavaContainer'); if isempty(parPeer) drawnow; end peer = get(parent,'JavaContainer'); else error(message('MATLAB:javacomponent:InvalidParentHandle', getString(message('MATLAB:javacomponent:IncorrectUsage')))) end if isempty(peer) error(message('MATLAB:javacomponent:JavaFigsNotEnabled')) end hUicontainer = []; hgp = []; returnContainer = true; if ischar(component) % create from class name component = javaObjectEDT(component); elseif iscell(component) % create from class name and input args component = javaObjectEDT(component{:}); elseif ~isa(component,'com.mathworks.hg.peer.FigureChild') % tag existing object for auto-delegation - unless it is a FigureChild javaObjectEDT(component); end % Promote the component to a handle object first. It seems once a java % object is cast to a handle, you cannot get another handle with % 'callbackproperties'. if ~isjava(component) component = java(component); end hcomponent = handle(component,'callbackProperties'); if nargin == 1 hgp = handle(peer.addchild(component)); % parent must be a figure, we default to gcf upstairs createPanel; hgp.setUIContainer(double(hUicontainer)); else if parentIsFigure if isnumeric(position) if isempty(position) position = [20 20 60 20]; end % numeric position is not set here, rely on the uicontainer % listeners below. hgp = handle(peer.addchild(component)); createPanel; hgp.setUIContainer(double(hUicontainer)); elseif ... isequal(char(position),char(java.awt.BorderLayout.NORTH)) || ... isequal(char(position),char(java.awt.BorderLayout.SOUTH)) || ... isequal(char(position),char(java.awt.BorderLayout.EAST)) || ... isequal(char(position),char(java.awt.BorderLayout.WEST)) || ... isequal(char(position),char('Overlay')) hgp = handle(peer.addchild(component, position)); returnContainer = false; else error(message('MATLAB:javacomponent:InvalidPosition', getString(message('MATLAB:javacomponent:IncorrectUsage')))) end else % Adding component to the toolbar. % component position is ignored peer.add(component); hUicontainer = parent; % toolbar. handles = getappdata(hUicontainer, 'childhandles'); handles = [handles, hcomponent]; setappdata(hUicontainer, 'childhandles', handles); end % make sure the component is on the screen so the % caller can interact with it right now. % drawnow; end if returnContainer configureComponent(); end % If asked for callbacks, add them now. if ~isempty(callback) % The hg panel is the best place to store the listeners so they get % cleaned up asap. We can't do that if the parent is a uitoolbar so we % just put them on the toolbar itself. lsnrParent = hgp; if isempty(lsnrParent) lsnrParent = hParent; end if mod(length(callback),2) error('MATLAB:javacomponent',usage); end for i = 1:2:length(callback) lsnrs = getappdata(lsnrParent,'JavaComponentListeners'); l = javalistener(component, callback{i}, callback{i+1}); setappdata(lsnrParent,'JavaComponentListeners',[l lsnrs]); end end if returnContainer hcontainer = hUicontainer; else hcontainer = []; end function createPanel % add delete listener hUicontainer = hgjavacomponent('Parent',parent,'Units', 'Pixels','Serializable','off'); set(hUicontainer, 'UserData', char(component.getClass.getName)); % For findobj queries. if isa(java(hgp), 'com.mathworks.hg.peer.FigureChild') set(hUicontainer, 'FigureChild', hgp); end if isa(java(hcomponent), 'javax.swing.JComponent') % force component to be opaque if it's a JComponent. This prevents % lightweight component from showing the figure background (which % may never get a paint event) hcomponent.setOpaque(true); end set(hUicontainer, 'JavaPeer', hcomponent); if returnContainer % add move/resize listener to the hgjavacomponent addlistener(hUicontainer, 'PixelBounds', 'PostSet', @handleResize); % add visible listener addlistener(hUicontainer, 'Visible', 'PostSet', @handleVisible); %Parent was set before we get here. Hence we need to explicitly %walk up and attach listeners. For subsequent parent changes, %the parent property postset listener callback will take care of setting %up the hierarchy listeners to listen for position and visible changes createHierarchyListeners(hUicontainer, @handleVisible); % add parent listener addlistener(hUicontainer, 'Parent', 'PreSet', @handlePreParent); % add parent listener addlistener(hUicontainer, 'Parent', 'PostSet', @(o,e) handlePostParent(o,e,@handleVisible)); % force though 1st resize event set(hUicontainer,'Position', position); else % For the BorderLayout components, we don't really want the % hUicontainer to show. But, it provides a nice place for cleanup. set(hUicontainer,'Visible', 'off', 'HandleVisibility', 'off'); % Set position out of the figure to work around a current bug % due to which invisible uicontainers show up when renderer is % OpenGL (G. set(hUicontainer, 'Position', [1 1 0.01 0.01]); end if isa(component,'com.mathworks.hg.peer.FigureChild') component.setUIContainer(double(hUicontainer)); end %Handles move or resize of the hgjavacomponent. function handleResize(obj, evd) %#ok - mlint %Deal with early warnings [lastWarnMsg, lastWarnId] = lastwarn; oldPBWarning = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:PixelBounds'); pb = get(hUicontainer,'PixelBounds'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HACK FOR HMI - When X-location is negative, we are % messing up the width of the component because we are % going from pixel bounds (xmin,ymin,xmax,ymax) to actual % bounds on the screen (width and height calculated). There is % a floor/ceil issue with the X-min not quite adjusted by % the X-max so as to keep the width correct. I am forcing it % here. An ideal fix would have been in the pixelbounds % calculation but it seems like too much work in HG1 and hence % I am using a narrow scoped fix for now - 815546 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% jcPos = getpixelposition(hUicontainer,true); if (jcPos(1) < 0) pb(3) = pb(1) + jcPos(3); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% hgp.setPixelBounds(pb); warning(oldPBWarning.state, 'MATLAB:HandleGraphics:ObsoletedProperty:PixelBounds'); % restore the last warning thrown lastwarn(lastWarnMsg, lastWarnId); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % g482174 - Bandage solution to support hierarchy visibility changes % We will look for any invisible parent container to see if we can % show the javacomponent or not. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handleVisible(obj, evd) %#ok - mlint source = evd.AffectedObject; if ishghandle(source,'hgjavacomponent') hgp.setVisible(strcmp(get(source,'Visible'),'on')); else if (strcmp(get(source,'Visible'),'off')) setInternalVisible(hUicontainer, component, false); else setInternalVisible(hUicontainer, component, isVisibleInCurrentLineage(hUicontainer)); end end drawnow update; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % isVisibleInCurrentLineage - returns whether the javacomponent can % be visible or not in its current hierarchy. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function visible = isVisibleInCurrentLineage(hUicontainer) stParent = get(hUicontainer,'Parent'); hgjcompVisible = strcmp(get(hUicontainer,'Visible'),'on'); visible = hgjcompVisible && strcmp(get(stParent,'Visible'),'on'); while (~ishghandle(stParent,'root') && visible) stParent = get(stParent,'Parent'); visible = visible && strcmp(get(stParent,'Visible'),'on'); end end function handlePreParent(obj, evd) %#ok - mlint oldfig = ancestor(hUicontainer, 'figure'); removecomponent = true; % NewValue field is absent in MCOS and hence we need to do the % following safely. if ~isempty(findprop(evd,'NewValue')) newfig = ancestor(evd.NewValue, 'figure'); removecomponent = ~isempty(newfig) && ~isequal(oldfig, newfig); end %We are losing on this optimization(event may not have NewValue). We always %remove and add upon reparenting. We do not have the context of %the new parent in the preset to do a compare to see if we are %being parented to the same parent again. We hope that this is %not done often. if (removecomponent) peer = getJavaFrame(oldfig); peer.remove(component); end end function handlePostParent(obj, evd, visibleCbk) %#ok - mlint createHierarchyListeners(hUicontainer, visibleCbk); oldfig = ancestor(parent, 'figure'); newfig = ancestor(evd.AffectedObject,'figure'); addcomponent = true; %Before, we could decide if we want to re-add the %javacomponent. Now we have to always add. if ~isempty(findprop(evd,'NewValue')) newfig = ancestor(evd.NewValue, 'figure'); addcomponent = ~isempty(newfig) && ~isequal(oldfig, newfig); end if addcomponent peer = getJavaFrame(newfig); hgp= handle(peer.addchild(component)); %When we reparent ourself (javacomponent), the truth about %whether we are visible or not needs to be queried from %the proxy and its current lineage. Change visibility %without changing state on the hUicontainer setInternalVisible(hUicontainer, component, isVisibleInCurrentLineage(hUicontainer)); if isa(java(hgp), 'com.mathworks.hg.peer.FigureChild') % used by the uicontainer C-code setappdata(hUicontainer, 'FigureChild', java(hgp)); end parent = newfig; end handleResize([],[]); end end function configureComponent set(hUicontainer,'DeleteFcn', {@containerDelete, hcomponent}); % addlistener(java(hcomponent), 'ObjectBeingDestroyed', @(o,e)componentDelete(o,e,hUicontainer, parentIsFigure)); temp = handle.listener(hcomponent, 'ObjectBeingDestroyed', @(o,e)componentDelete(o,e,hUicontainer, parentIsFigure)); save__listener__(hcomponent,temp); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % g637916 - Visibility of the hgjavacomponent is posing issues due to the % fact that the state is being used to control visibility and hence when % the parent's are turned visible off, we need an alternate api to make it % go away from the screen. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function setInternalVisible(hUicontainer, component ,vis) cleaner = warnSuppressAndSetInternalVisible(hUicontainer, component ,vis); delete(cleaner); end function cleaner = warnSuppressAndSetInternalVisible(hUicontainer, component ,vis) [ state.lastWarnMsg, state.lastWarnId ] = lastwarn; state.usagewarning = warning('off','MATLAB:hg:javacomponent'); cleaner = onCleanup(@() warnRestore(state)); setVisibility(handle(hUicontainer),vis); if (isa(component,'com.mathworks.hg.peer.FigureChild')) component = component.getFigureComponent; end setVisible(component, vis); end function warnRestore(state) lastwarn(state.lastWarnMsg, state.lastWarnId); warning(state.usagewarning); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function containerDelete(obj, evd, hc) %#ok - mlint obj = handle(obj); if ishghandle(handle(obj), 'uitoolbar') || ... ishghandle(handle(obj),'uisplittool') || ... ishghandle(handle(obj),'uitogglesplittool'); childHandles = getappdata(obj, 'childhandles'); delete(childHandles(ishandle(childHandles))); else if ishandle(hc) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % We are giving ourselves a hook to run resource cleanup functions % like freeing up callbacks. This is important for uitree because % the expand and selectionchange callbacks need to be freed when % the figure is destroyed. See G769077 for more information. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% removeJavaCallbacks(hc); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% delete(hc); end end end function componentDelete(obj, evd, hUicontainer, parentIsFigure) %#ok - mlint if (parentIsFigure) % This java component is always deleted before hUicontainer. It is % ensured by calling component deletion in function containerDelete. % hUicontainer becomes invalid when delete(hUicontainer) below is run. parent = ancestor(hUicontainer,'figure'); peer = getJavaFrame(parent); if any(ishandle(obj)) removeobj = java(obj); if ~isempty(get(hUicontainer,'FigureChild')) removeobj = get(hUicontainer,'FigureChild'); end peer.remove(removeobj); end % delete container if it exists if any(ishghandle(hUicontainer)) delete(hUicontainer); end else parent = hUicontainer; % toolbar or split tool if ~ishandle(parent) || ~ishandle(obj) % The toolbar parent or the component has been deleted. Bail out. % Toolbar clears all javacomponents after itself. return; end % For uisplittool and uitogglesplittool objects % The parent may have done this deletion for us % already. hPar = get(parent,'Parent'); if ishghandle(handle(hPar),'uitoolbar') parPeer = get(hPar,'JavaContainer'); if isempty(parPeer) return; end end peer = get(parent, 'JavaContainer'); if ~isempty(peer) peer.remove(java(obj)); end end end function hdl=javalistener(jobj, eventName, response) try jobj = java(jobj); catch ex %#ok end % make sure we have a Java objects if ~ishandle(jobj) || ~isjava(jobj) error(message('MATLAB:javacomponent:invalidinput')) end hSrc = handle(jobj,'callbackproperties'); allfields = sortrows(fields(set(hSrc))); alltypes = cell(length(allfields),1); j = 1; for i = 1:length(allfields) fn = allfields{i}; if ~isempty(strfind(fn,'Callback')) fn = strrep(fn,'Callback',''); alltypes{j} = fn; j = j + 1; end end alltypes = alltypes(~cellfun('isempty',alltypes)); if nargin == 1 % show or return the possible events if nargout hdl = alltypes; else disp(alltypes) end return; end % validate event name valid = any(cellfun(@(x) isequal(x,eventName), alltypes)); if ~valid error(message('MATLAB:javacomponent:invalidevent', class( jobj ), char( cellfun( @(x) sprintf( '\t%s', x ), alltypes, 'UniformOutput', false ) )')) end hdl = handle.listener(handle(jobj), eventName, ... @(o,e) cbBridge(o,e,response)); function cbBridge(o,e,response) hgfeval(response, java(o), e.JavaEvent) end end function createHierarchyListeners(hUicontainer, visCbk) deleteExistingHierarchyListeners(hUicontainer, []); hUicontainer = handle(hUicontainer); parent = get(hUicontainer,'Parent'); % Walk up instance hierarchy and put a listener on all the % containers. We don't need a listener on the figure. while ~ishghandle(parent,'root') %Set up all the visible listeners createVisibleListener(parent, hUicontainer, visCbk); %Keep walking up parent = get(parent,'Parent'); end % When the hgjavacomponent goes away, clean all listeners addlistener(hUicontainer, 'ObjectBeingDestroyed', @(o,e) deleteExistingHierarchyListeners(o,e)); end function deleteExistingHierarchyListeners(src,~) hUicontainer = handle(src); %Delete all the visibility listeners if isListenerData(hUicontainer, 'VisiblilityListeners') appdata = getListenerData(hUicontainer, 'VisiblilityListeners'); cellfun(@(x) delete(x), appdata, 'UniformOutput',false); setListenerData(hUicontainer, 'VisiblilityListeners',{}); end end function createVisibleListener(object, hUicontainer, visCbk) %Attach visibility listeners visContainerListnr = addlistener(object, 'Visible','PostSet', visCbk); if (~isListenerData(hUicontainer, 'VisiblilityListeners')) setListenerData(hUicontainer, 'VisiblilityListeners',{}); end visibilityAppdata = getListenerData(hUicontainer, 'VisiblilityListeners'); visibilityAppdata{end+1} = visContainerListnr; setListenerData(hUicontainer, 'VisiblilityListeners', visibilityAppdata); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function javaFrame = getJavaFrame(f) % store the last warning thrown [ lastWarnMsg, lastWarnId ] = lastwarn; % disable the warning when using the 'JavaFrame' property % this is a temporary solution oldJFWarning = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); javaFrame = get(f,'JavaFrame'); warning(oldJFWarning.state, 'MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); % restore the last warning thrown lastwarn(lastWarnMsg, lastWarnId); end
github
BottjerLab/Acoustic_Similarity-master
uigetdir_deprecated.m
.m
Acoustic_Similarity-master/code/interactive/private/uigetdir_deprecated.m
10,331
utf_8
a785775f5575f2c0d602724694ad0687
function [directoryname] = uigetdir_deprecated(varargin) % $Revision: 1.1.6.7 $ $Date: 2010/07/02 16:17:19 $ % Copyright 2006-2010 The MathWorks, Inc. %UIGETDIR Standard open directory dialog box % DIRECTORYNAME = UIGETDIR(STARTPATH, TITLE) % displays a dialog box for the user to browse through the directory % structure and select a directory, and returns the directory name % as a string. A successful return occurs if the directory exists. % % The STARTPATH parameter determines the initial display of directories % and files in the dialog box. % % When STARTPATH is empty the dialog box opens in the current directory. % % When STARTPATH is a string representing a valid directory path, the % dialog box opens in the specified directory. % % When STARTPATH is not a valid directory path, the dialog box opens % in the base directory. % % Windows: % Base directory is the Windows Desktop directory. % % UNIX: % Base directory is the directory from which MATLAB is started. % The dialog box displays all filetypes by default. The type % of files that are displayed can be changed by changing the filter % string in the Selected Directory field of the dialog box. If the % user selects a file instead of a directory, then the directory % containing the file is returned. % % Parameter TITLE is a string containing a title for the dialog box. % When TITLE is empty, a default title is assigned to the dialog box. % % Windows: % The TITLE string replaces the default caption inside the % dialog box for specifying instructions to the user. % % UNIX: % The TITLE string replaces the default title of the dialog box. % % When no input parameters are specified, the dialog box opens in the % current directory with the default dialog title. % % The output parameter DIRECTORYNAME is a string containing the % directory selected in the dialog box. If the user presses the Cancel % button it is set to 0. % % Examples: % % directoryname = uigetdir; % % Windows: % directoryname = uigetdir('D:\APPLICATIONS\MATLAB'); % directoryname = uigetdir('D:\APPLICATIONS\MATLAB', 'Pick a Directory'); % % UNIX: % directoryname = uigetdir('/home/matlab/work'); % directoryname = uigetdir('/home/matlab/work', 'Pick a Directory'); % % See also UIGETFILE, UIPUTFILE. % Copyright 1984-2009 The MathWorks, Inc. % $Revision: 1.1.6.7 $ $Date: 2010/07/02 16:17:19 $ % Built-in function. %%%%%%%%%%%%%%%% % Error messages %%%%%%%%%%%%%%%% badNumArgsMessage = 'Too many input arguments.' ; badTitleMessage = 'TITLE argument must be a string.' ; badStartPathMessage = 'STARTPATH argument must be a string.'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check the number of args - must be 0 , 1 , or 2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% maxArgs = 2 ; numArgs = nargin ; if( numArgs > maxArgs ) error( badNumArgsMessage ) return end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Restrict new version to the mac % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If we are on the mac, default to using non-native % dialog. If the root property UseNativeSystemDialogs % is false, use the non-native version instead. useNative = true; %#ok % If we are on the Mac & swing is available, set useNative to false, % i.e., we are going to use Java dialogs not native dialogs. % Comment the following line to disable java dialogs on Mac. useNative = ~( ismac && usejava('awt') ) ; % If the root appdata is set and swing is available, % honor that overriding all other prefs. %if isequal(0, getappdata(0,'UseNativeSystemDialogs')) && isempty( javachk('swing') ) % useNative = false ; %end if useNative try if nargin == 0 [directoryname] = native_uigetdir ; else [directoryname] = native_uigetdir( varargin{:} ) ; end catch ex rethrow(ex) end return end % end useNative %%%%%%%%%%%%%%%%% % General globals %%%%%%%%%%%%%%%%% dirName = '' ; userTitle = '' ; % fileSeparator = filesep ; % pathSeparator = pathsep ; directoryname = '' ; %#ok %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of exactly one argument. % The argument must be a string specifying a directory. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 1 <= numArgs ) dirName = varargin{ 1 } ; % First arg must be a string if ~( ischar( dirName ) ) || ~( isvector( dirName ) ) error( badStartPathMessage ) ; end if~( 1 == size( dirName , 1 ) ) dirName = dirName' ; end % If the string is not a directory name, % dirName to the "base" directory. On % Windows, it's the Windows Desktop dir. % On UNIX systems, it's the MATLAB dir. if ~( isdir( dirName ) ) if ispc dirName = char( com.mathworks.hg.util.dFileChooser.getUserHome() ) ; dirName = strcat( dirName , '\Desktop' ) ; else dirname = char( matlabroot ) ; %#ok end end end % end if( 1 <= numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of two args. % The second arg must be a title string. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 2 == numArgs ) % The 2nd arg must be a string title = varargin{ 2 } ; if~( ischar( title ) && isvector( title ) ) % Not a string error( badTitleMessage ) ; end % Transpose if necessary if( ~( 1 == size( title , 1 ) ) ) title = title' ; end userTitle = title ; end % if( 2 == numArgs ) directoryname = 0 ; %#ok %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Build the dialog that holds our file chooser and add the chooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % jp = handle(javax.swing.JPanel) ; jp = awtcreate('com.mathworks.mwswing.MJPanel', ... 'Ljava.awt.LayoutManager;', ... java.awt.BorderLayout); % Title is set later d = mydialog( ... 'Visible','off', ... 'DockControls','off', ... 'Color',get(0,'DefaultUicontrolBackgroundColor'), ... 'Windowstyle','modal', ... 'Resize','on' ... ); % Create a JPanel and put it into the dialog - this is for resizing [panel, container] = javacomponent(jp,[10 10 20 20],d); % Create a JFileChooser - 'false' means do not show as 'Save' dialog sys = char( computer ) ; stringSys = java.lang.String( sys ) ; jfc = awtcreate('com.mathworks.hg.util.dFileChooser'); % Set the dialog's title if ~( strcmp( userTitle , char('') ) ) set( d , 'Name' , userTitle ) ; else set( d , 'Name' , char( jfc.getDefaultGetdirTitle() ) ) end awtinvoke( jfc , 'init(ZLjava/lang/String;)' , false , stringSys ) ; %jfc.init( false , sys ) ; awtinvoke( jfc , 'setFileSelectionMode(I)' , javax.swing.JFileChooser.DIRECTORIES_ONLY) ; %jfc.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY) ; % file = java.io.File(dirName) ; if ~( strcmp( dirName , char('') ) ) awtinvoke( jfc , 'setCurrentDirectory(Ljava/io/File;)' , java.io.File(dirName) ) ; %jfc.setCurrentDirectory( java.io.File(dirName) ) ; end awtinvoke( java(panel), 'add(Ljava.awt.Component;)', jfc ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of no args. In this case % open in the user's current working dir. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 0 == numArgs ) % Set the chooser's current directory if ispc awtinvoke( jfc , 'setCurrentDirectory(Ljava/io/File;)' , java.io.File(pwd) ) ; % jfc.setCurrentDirectory( java.io.File(pwd) ) ; else awtinvoke( jfc , 'setCurrentDirectory(Ljava/io/File;)' , java.io.File(matlabroot) ) ; %jfc.setCurrentDirectory( java.io.File(matlabroot) ) ; end % end if( 0 == numArgs ) end % end if( 0 == numArgs ) set(container,'Units','normalized','Position',[0 0 1 1]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Set up a callback to this MATLAB file and show the dialog %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% jfcHandle = handle(jfc , 'callbackproperties' ); set(jfcHandle,'PropertyChangeCallback',{ @callbackHandler , d }) figure(d) refresh(d) awtinvoke( jfc , 'listen()' ) ; waitfor(d); directoryname = 0 ; % Get the data stored by the callback if( isappdata( 0 , 'uigetdirData' ) ) directoryname = getappdata( 0 , 'uigetdirData' ) ; rmappdata( 0 , 'uigetdirData' ) ; end function out = mydialog(varargin) out = []; try out = dialog(varargin{:}) ; catch ex rethrow(ex) end end % end myDialog end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the callback from the JFileChooser. If the user % selected "Open", return the name of the selected file, % the full pathname and the index of the current filter. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function callbackHandler(obj , evd , d ) jfc = obj ; directoryname = '' ; %#ok cmd = char(evd.getPropertyName()); switch(cmd) %case 'CancelSelection' case 'mathworksHgCancel' if ishandle(d) directoryname = 0 ; setappdata( 0 , 'uigetdirData' , directoryname ) ; close(d) ; end case 'mathworksHgOk' directoryname = char(jfc.getSelectedFile.toString) ; setappdata( 0 , 'uigetdirData' , directoryname ) ; close(d) ; end % end switch end % end callbackHandler
github
BottjerLab/Acoustic_Similarity-master
uisetfont_helper.m
.m
Acoustic_Similarity-master/code/interactive/private/uisetfont_helper.m
2,310
utf_8
6541f09d1a3b5296c8b737665e6b6beb
function fontstruct = uisetfont_helper(varargin) % Copyright 2007-2008 The MathWorks, Inc. % $Revision: 1.1.8.10 $ $Date: 2011/09/08 23:36:53 $ [fontstruct,title,fhandle] = parseArgs(varargin{:}); fcDialog = matlab.ui.internal.dialog.FontChooser; fcDialog.Title = title; if ~isempty(fontstruct) fcDialog.InitialFont = fontstruct; end fontstruct = showDialog(fcDialog); if ~isempty(fhandle) setPointFontOnHandle(fhandle,fontstruct); end % Done. MCOS Object fcDialog cleans up and its java peer at the end of its % scope(AbstractDialog has a destructor that every subclass % inherits) function [fontstruct,title,handle] = parseArgs(varargin) handle = []; fontstruct = []; title = getString(message('MATLAB:uistring:uisetfont:TitleFont')); if nargin>2 error(message('MATLAB:uisetfont:TooManyInputs')) ; end if (nargin==2) if ~ischar(varargin{2}) error(message('MATLAB:uisetfont:InvalidTitleType')); end title = varargin{2}; end if (nargin>=1) if ishghandle(varargin{1}) handle = varargin{1}; fontstruct = getPointFontFromHandle(handle); elseif isstruct(varargin{1}) fontstruct = varargin{1}; elseif ischar(varargin{1}) if (nargin > 1) error(message('MATLAB:uisetfont:InvalidParameterList')); end title = varargin{1}; else error(message('MATLAB:uisetfont:InvalidFirstParameter')); end end %Given the dialog, user chooses to select or not select function fontstruct = showDialog(fcDialog) fcDialog.show; fontstruct = fcDialog.SelectedFont; if isempty(fontstruct) fontstruct = 0; end %Helper functions to convert font sizes based on the font units of the %handle object function setPointFontOnHandle(fhandle,fontstruct) tempunits = get(fhandle,'FontUnits'); try set(fhandle,fontstruct); catch ex %#ok<NASGU> end set(fhandle,'FontUnits',tempunits); function fs = getPointFontFromHandle(fhandle) tempunits = get(fhandle,'FontUnits'); set(fhandle, 'FontUnits', 'points'); fs = []; try fs.FontName = get(fhandle, 'FontName'); fs.FontWeight = get(fhandle, 'FontWeight'); fs.FontAngle = get(fhandle, 'FontAngle'); fs.FontUnits = get(fhandle, 'FontUnits'); fs.FontSize = get(fhandle, 'FontSize'); catch ex %#ok<NASGU> end set(fhandle, 'FontUnits', tempunits);
github
BottjerLab/Acoustic_Similarity-master
uisetfont_deprecated.m
.m
Acoustic_Similarity-master/code/interactive/private/uisetfont_deprecated.m
15,770
utf_8
beff9a38d9734c348ddc6ef7fc211731
function [fontStruct] = uisetfont_deprecated(varargin) % Copyright 1984-2010 The MathWorks, Inc. % $Revision: 1.1.8.6 $ $Date: 2010/07/02 16:17:24 $ %%%%%%%%%%%%%%%% % Error Messages %%%%%%%%%%%%%%%% badNumArgsMessage = 'Too many input arguments.' ; badObjTypeMessage1 = 'Font selection is not supported for '; badObjTypeMessage2 = ' objects, but only for axes, text, and uicontrols.' ; % badHandleMessage = 'Invalid object handle.'; badTitleLocMessage = 'title must be the last parameter passed to uisetfont.' ; badParamMessage = 'Invalid first parameter - please check usage' ; % badTitleMessage = 'Second argument (dialog title) must be a string.' ; badFontsizeMessage = 'Font size must be an integer.'; %#ok badFontSize = false; maxArgs = 2 ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Check the number of args - must <= maxArgs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% numArgs = nargin ; if( numArgs > maxArgs ) error('MATLAB:uisetfont:TooManyInputs', badNumArgsMessage ) ; end % end if( numArgs > maxArgs ) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Restrict new version to the mac % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If we are on the mac, default to using non-native % dialog. If the root property UseNativeSystemDialogs % is false, use the non-native version instead. useNative = true; %#ok<NASGU> % If we are on the Mac & swing is available, set useNative to false, % i.e., we are going to use Java dialogs not native dialogs. % Comment the following line to disable java dialogs on Mac. useNative = ~( isequal( 'MAC' , computer ) && usejava('awt') ) ; % % If the root appdata is set and swing is available, % % honor that overriding all other prefs. % if isequal(0, getappdata(0,'UseNativeSystemDialogs')) && usejava('awt') % useNative = false ; % end if useNative try if nargin == 0 [fontStruct] = native_uisetfont ; else [fontStruct] = native_uisetfont( varargin{:} ) ; end catch ex rethrow(ex) end return end % end useNative %%%%%%%%%%%%%%%%% % General Globals %%%%%%%%%%%%%%%%% arg1 = '' ; arg2 = '' ; %#ok jfc = '' ; arg1Type = '' ; suppliedType = '' ; suppliedFieldNames = '' ; title = '' ; numberAppropriateFields = 0 ; badType = 'badType'; structType = 'struct' ; objectType = 'object' ; % stringType = 'string' ; allowedObjectTypes = { 'axes' ; 'text' ; 'uicontrol' } ; structFields = { 'FontName' ;... 'FontUnits' ; ... 'FontSize' ; ... 'FontWeight' ; ... 'FontAngle' } ; %%%%%%% % Flags %%%%%%% arg1OK = false ; % titleFound = false ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Default font values - used when there are 0 args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fontStruct.FontName = 'Arial' ; fontStruct.FontUnits = 'points' ; fontStruct.FontSize = 10 ; fontStruct.FontWeight = 'normal' ; fontStruct.FontAngle = 'normal' ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The dialog that will hold our chooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% d = '' ; %#ok %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of exactly one arg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( numArgs == 1 ) arg1 = varargin{1} ; % Check out arg1 - it should be a struct having some specific % fields or a handle to an object of type text , uicontrol or axes. % FOR COMPATIBILITY, % It might also be a string we are going to use as a title. if( ischar( arg1 ) && isvector( arg1 ) ) % Save dialog title if( 1 == size( arg1 , 1 ) ) title = char( arg1 ) ; else title = char( arg1' ) ; end % Handle the case where arg1 is a struct or handle here elseif isstruct(arg1) || (isscalar(arg1) && ishandle(arg1)) % Process arg1 - return if there's an error checkArg1() ; % Return if there's an error with an object (illegal type) % No errors are returned if a struct has been handed in if( ~arg1OK || ( strcmp( suppliedType , badType ) ) ) if (badFontSize) error('MATLAB:uisetfont:InvalidParameter', badFontsizeMessage); else if ~( strcmp( suppliedType , char('') ) ) error('MATLAB:uisetfont:InvalidObjectType', [ badObjTypeMessage1 suppliedType badObjTypeMessage2 ] ) ; else error('MATLAB:uisetfont:InvalidParameter', badParamMessage ); end end end % if( ~arg1OK & ( strcmp( arg1Type , objectType ) ) ) % Handle error of param type here else error( badParamMessage ) ; end % end if/elseif/else end % if( numArgs == 1 ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of exactly two args %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( numArgs == 2 ) arg1 = varargin{1} ; arg2 = varargin{2} ; if ~( isstruct( arg1 ) || ishandle( arg1 ) ) error('MATLAB:uisetfont:InvalidParameter', badParamMessage ) ; end % The only "legit" combination here is to have % the first arg be a struct or a handle and to % have the second arg be a string (title). if( ~( ischar( arg2 ) && isvector( arg2 ) ) ) error('MATLAB:uisetfont:TitleMustBeLastInput', badTitleLocMessage ) ; end % end if ... checkArg1() ; % Return if arg1 is a handle to a type we don't support if( ~arg1OK || ( strcmp( arg1Type , objectType ) ) ) if ~( strcmp( suppliedType , char('') ) ) error('MATLAB:uisetfont:InvalidObjectType', [ badObjTypeMessage1 suppliedType badObjTypeMessage2 ] ) ; else if (badFontSize) error('MATLAB:uisetfont:InvalidParameter', badFontsizeMessage); else error('MATLAB:uisetfont:InvalidParameter', badParamMessage ) end end end % if( ~arg1OK & ( strcmp( arg1Type , objectType ) ) ) % Set op the title for in the dialog if( 1 == size( arg2 , 1 ) ) title = char( arg2 ) ; else title = char( arg2' ) ; end end % end if( numArgs == 2 ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % OK - set up and display the dialog. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Dialog title is set later d = mydialog( ... 'Visible','off', ... 'DockControls','off', ... 'Color',get(0,'DefaultUicontrolBackgroundColor'), ... 'Windowstyle','modal', ... 'Resize','on' ... ); set( d , 'Position' , [232 246 345 390] ) ; % Create a chooser (JPanel) and put it into the dialog - this is for resizing sys = char( computer ) ; lf = listfonts; fonts = javaArray('java.lang.String', length(lf)); for i=1:length(lf) %#ok<FXUP> fonts(i) = java.lang.String(lf{i}); end jfc = awtcreate('com.mathworks.hg.util.FontChooser', ... '[Ljava/lang/String;Ljava/lang/String;', ... fonts , sys ); [jfc,container] = javacomponent( jfc,[10 10 20 20],d ); % Use supplied title if one was given else use default if ~( strcmp( '' , title ) ) set( d , 'Name' , title ) ; else set( d , 'Name' , char( jfc.getDefaultTitle() ) ) end % Initialize the font chooser using the fontStruct struct initFontChooser() ; awtinvoke( java(jfc), 'setUpAttributes()'); awtinvoke( java(jfc), 'updatePreviewFont()'); % Add some control buttons jbSet = handle( awtcreate('com.mathworks.mwswing.MJButton', 'Ljava/lang/String;', 'OK'), ... 'callbackproperties' ) ; jbCancel = handle( awtcreate('com.mathworks.mwswing.MJButton', 'Ljava/lang/String;', 'Cancel'), ... 'callbackproperties' ) ; buttonPanel = handle( awtcreate('com.mathworks.mwswing.MJPanel') ) ; awtinvoke(java(buttonPanel), 'add(Ljava.awt.Component;)', java(jbSet)) ; awtinvoke(java(buttonPanel), 'add(Ljava.awt.Component;)', java(jbCancel)) ; awtinvoke( java(jfc), 'add(Ljava.awt.Component;Ljava.lang.Object;)',... java(buttonPanel), java.awt.BorderLayout.SOUTH ) ; set(container,'Units','normalized','Position',[0 0 1 1]); set(jbSet,'ActionPerformedCallback', {@callbackHandler, jfc , d , arg1}) set(jbCancel,'ActionPerformedCallback', {@callbackHandler, jfc , d , arg1}) % Go fontStruct = 0 ; figure(d) refresh(d) waitfor(d); if isappdata( 0 , 'uisetfontData' ) fontStruct = getappdata( 0 , 'uisetfontData' ) ; rmappdata( 0 , 'uisetfontData' ) ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Error check the first arg. As a side effect, if % arg1 is a struct, return the set of field names % matching the "font-related set" ( 'FontName', 'FontSize', ... ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function checkArg1() % Cover the case where arg1 is a handle if( isscalar(arg1) && ishandle( arg1 ) ) suppliedType = '' ; try %arg1Type = objectType ; suppliedType = get( arg1 , 'Type' ) ; catch arg1OK = false ; suppliedType = badType ; return ; end % Check type of supplied obj against allowed obj types (axes,text,...) len = size( allowedObjectTypes , 1 ) ; for i = 1 : len %#ok<FXUP> if( strcmp( allowedObjectTypes( i , 1 ) , suppliedType ) ) arg1OK = true ; return ; end % end if( strcmp( allowedObjectTypes( i , 1 ) , arg1 ) ) end % end for i = 1 : len % Bad object type arg1OK = false ; return ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % End processing for handle % Do the case where arg1 is a struct %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif( isstruct( arg1 ) ) arg1Type = structType ; % Check the structure to see if has font-related fields len = size( structFields , 1 ); numberAppropriateFields = 0 ; for j = 1 : len % Get next font-related field name fieldName = char( structFields( j , 1 ) ) ; % If arg1 has a field of this name, store the field name if ( isfield( arg1 , fieldName ) ) if (strcmp(fieldName, 'FontSize')) fieldVal = arg1.(fieldName); % FontSize should be a number. if ~isnumeric(fieldVal) badFontSize = true; arg1OK = false; break; end end arg1OK = true ; numberAppropriateFields = numberAppropriateFields + 1 ; suppliedFieldNames{ 1 , numberAppropriateFields } = char( fieldName ) ; %#ok<AGROW> end % end if j = 1 : size( structFields , 1 ) end % end for else arg1OK = false ; end % end if/else end % end function checkArg1() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Initialize the FontChooser with values given by the user or defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function initFontChooser() % If arg1 is a handle to an object, get the font values of the object if( ishandle( arg1 ) ) %%%%%%%%%%%%%%%%%%%%??????? should be char( get( arg1 , 'FontName' ) %%%%%%%%%%%%%%%%%%%%)??????????????????????????????????????????????? fontStruct.FontName = get( arg1 , 'FontName' ) ; fontStruct.FontUnits = get( arg1 , 'FontUnits' ) ; fontStruct.FontSize = get( arg1 , 'FontSize' ) ; fontStruct.FontWeight = get( arg1 , 'FontWeight' ) ; fontStruct.FontAngle = get( arg1 , 'FontAngle' ) ; end % end if( ishandle( arg1 ) ) % If arg1 is a struct, use it's font-related field values if( isstruct( arg1 ) ) if( numberAppropriateFields > 0 ) % Get vals and set fields of the fontStruct structure for i = 1 : numberAppropriateFields %#ok<FXUP> fieldName = char( suppliedFieldNames( 1 , i )) ; val = arg1.(fieldName); fontStruct.(fieldName) = val ; end % for i = 1 : numberAppropriateFields end % if( numberAppropriateFields > 0 ) end % if( isStruct( arg1 ) ) %disp( fontStruct ) ; % Now actually set the selections in the FileChooser awtinvoke(java(jfc), 'selectFontName(Ljava/lang/String;)', fontStruct.('FontName')) ; awtinvoke(java(jfc), 'selectFontSize(I)', fontStruct.('FontSize' )) ; % fontAngle = '' ; % fontWeight = '' ; fw = fontStruct.('FontWeight') ; fontStyle = 'Regular' ; fa = fontStruct.('FontAngle'); if( strcmpi( fw , 'bold' ) ) if( strcmpi( fa , 'italic' ) ) fontStyle = 'Bold Italic'; else fontStyle = 'Bold'; end else if( strcmpi( fa , 'italic' ) ) fontStyle = 'Italic'; end end % end if( strcmp( fw , 'bold' ) awtinvoke(java(jfc), 'selectFontStyle(Ljava/lang/String;)', char(fontStyle) ) ; jfc.addSampleTextActionListeners(); awtinvoke( java(jfc), 'setUpAttributes()'); awtinvoke( java(jfc), 'updatePreviewFont()'); end % end function initFontChooser function out = mydialog(varargin) out = []; try out = dialog(varargin{:}) ; catch ex rethrow(ex) end end % end myDialog end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The callback from the chooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function callbackHandler( obj , evd , jfc , d , arg1 ) %#ok cmd = char(evd.getActionCommand()); switch(cmd) case 'Cancel' if ishandle(d) close(d) end case 'OK' % Set up the output variable fontStruct.FontName = char( jfc.getFontName() ) ; fontStruct.FontSize = jfc.getFontSize() ; fontStruct.FontWeight = char( jfc.getFontWeight() ) ; fontStruct.FontAngle = char( jfc.getFontAngle() ) ; setappdata( 0 , 'uisetfontData' , fontStruct ) ; % If necessary, set the input obj's properties if( isscalar(arg1) && ishandle( arg1 ) ) set( arg1 , 'FontName' , char( jfc.getFontName() ) ) ; set( arg1 , 'FontSize' , jfc.getFontSize() ) ; set( arg1 , 'FontWeight' , char( jfc.getFontWeight() ) ) ; set( arg1 , 'FontAngle' , char( jfc.getFontAngle() ) ) ; end % end if( ishandle( arg1 ) ) if ishandle(d) close(d) end otherwise disp([cmd ' Unimplemented']) end % end switch end % end callbackHandler
github
BottjerLab/Acoustic_Similarity-master
uiputfile_deprecated.m
.m
Acoustic_Similarity-master/code/interactive/private/uiputfile_deprecated.m
41,884
utf_8
c7e9f70a660e10105e4c07ebca2d2900
function [filename, pathname, filterindex] = uiputfile_deprecated(varargin) % $Revision: 1.1.6.11 $ $Date: 2011/09/23 19:13:36 $ % Copyright 2006-2011 The MathWorks, Inc. %UIPUTFILE Standard save file dialog box. % [FILENAME, PATHNAME, FILTERINDEX] = UIPUTFILE(FILTERSPEC, TITLE) % displays a dialog box for the user to fill in and returns the % filename and path strings and the index of the selected filter. % A successful return occurs if a valid filename is specified. If a % exisiting filename is specified or selected, a warning message is % displayed. The user may select Yes to use the filename or No to % return to the dialog to select another filename. % % The FILTERSPEC parameter determines the initial display of files in % the dialog box. For example '*.m' lists all MATLAB code files. If % FILTERSPEC is a cell array, the first column is used as the list of % extensions, and the second column is used as the list of descriptions. % % When FILTERSPEC is a string or a cell array, "All files" is appended % to the list. % % When FILTERSPEC is empty the default list of file types is used. % % When FILTERSPEC is a filename, it is used as the default filename and % the file's extension is used as the default filter. % % Parameter TITLE is a string containing the title of the dialog % box. % % The output variable FILENAME is a string containing the name of the file % selected in the dialog box. If the user presses Cancel, it is set to 0. % % The output variable PATH is a string containing the name of the path % selected in the dialog box. If the user presses Cancel, it is set to 0. % % The output variable FILTERINDEX returns the index of the filter selected % in the dialog box. The indexing starts at 1. If the user presses Cancel, % it is set to 0. % % [FILENAME, PATHNAME, FILTERINDEX] = UIPUTFILE(FILTERSPEC, TITLE, FILE) % FILE is a string containing the name to use as the default selection. % % [FILENAME, PATHNAME] = UIPUTFILE(..., 'Location', [X Y]) % places the dialog box at screen position [X,Y] in pixel units. % This option is supported on UNIX platforms only. % % [FILENAME, PATHNAME] = UIPUTFILE(..., X, Y) % places the dialog box at screen position [X,Y] in pixel units. % This option is supported on UNIX platforms only. % THIS SYNTAX IS OBSOLETE AND WILL BE REMOVED. PLEASE USE THE FOLLOWING % SYNTAX INSTEAD: % [FILENAME, PATHNAME] = UIPUTFILE(..., 'Location', [X Y]) % % % Examples: % % [filename, pathname] = uiputfile('matlab.mat', 'Save Workspace as'); % % [filename, pathname] = uiputfile('*.mat', 'Save Workspace as'); % % [filename, pathname, filterindex] = uiputfile( ... % {'*.m;*.fig;*.mat;*.mdl', 'All MATLAB Files (*.m, *.fig, *.mat, *.mdl)'; % '*.m', 'MATLAB Code (*.m)'; ... % '*.fig','Figures (*.fig)'; ... % '*.mat','MAT-files (*.mat)'; ... % '*.mdl','Models (*.mdl)'; ... % '*.*', 'All Files (*.*)'}, ... % 'Save as'); % % [filename, pathname, filterindex] = uiputfile( ... % {'*.mat','MAT-files (*.mat)'; ... % '*.mdl','Models (*.mdl)'; ... % '*.*', 'All Files (*.*)'}, ... % 'Save as', 'Untitled.mat'); % % Note, multiple extensions with no descriptions must be separated by semi- % colons. % % [filename, pathname] = uiputfile( ... % {'*.m';'*.mdl';'*.mat';'*.*'}, ... % 'Save as'); % % Associate multiple extensions with one description like this: % % [filename, pathname] = uiputfile( ... % {'*.m;*.fig;*.mat;*.mdl', 'All MATLAB Files (*.m, *.fig, *.mat, *.mdl)'; ... % '*.*', 'All Files (*.*)'}, ... % 'Save as'); % % This code checks if the user pressed cancel on the dialog. % % [filename, pathname] = uiputfile('*.m', 'Pick a MATLAB code file'); % if isequal(filename,0) || isequal(pathname,0) % disp('User pressed cancel') % else % disp(['User selected ', fullfile(pathname, filename)]) % end % % % See also UIGETDIR, UIGETFILE. % Copyright 1984-2005 The MathWorks, Inc. % $Revision: 1.1.6.11 $ $Date: 2011/09/23 19:13:36 $ % Built-in function. %%%%%%%%%%%%%%%% % Error messages %%%%%%%%%%%%%%%% badLocMessage = 'The Location parameter value must be a 2 element vector.' ; % badMultiMessage = 'The MultiSelect parameter value must be a string specifying on/off.' ; % badFirstMessage = 'Ill formed first argument to uigetfile' ; badArgsMessage = 'Unrecognized input arguments.' ; bad2ndArgMessage = 'Expecting a string as 2nd arg' ; bad3rdArgMessage = 'Expecting a string as 3rd arg' ; badFilterMessage = 'FILTERSPEC argument must be a string or an M by 1 or M by 2 cell array.' ; badNumArgsMessage = 'Too many input arguments.' ; badLastArgsMessage = 'MultiSelect and Location args must be the last args' ; badMultiPosMessage = '''MultiSelect'' , ''on/off'' can only be followed by Location args' ; badLocationPosMessage = '''Location'' , [ x y ] can only be followed by MultiSelect args' ; caErr1Message = 'Illegal filespec'; caErr2Message = 'Illegal filespec - can have at most two cols'; caErr3Message = 'Illegal file extension - ''' ; maxArgs = 5 ; numArgs = nargin ; %#ok %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check the number of args - must be <= maxArgs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% numArgs = nargin ; if( numArgs > maxArgs ) error( badNumArgsMessage ) ; end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Restrict new version to the mac % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If we are on the mac, default to using non-native % dialog. If the root property UseNativeSystemDialogs % is false, use the non-native version instead. useNative = true; %#ok % If we are on the Mac & swing is available, set useNative to false, % i.e., we are going to use Java dialogs not native dialogs. % Comment the following line to disable java dialogs on Mac. useNative = ~( ismac && usejava('awt') ) ; % If the root appdata is set and swing is available, % honor that overriding all other prefs. %if isequal(0, getappdata(0,'UseNativeSystemDialogs')) && isempty( javachk('swing') ) % useNative = false ; %end if useNative try if nargin == 0 [filename, pathname, filterindex] = native_uiputfile ; else [filename, pathname, filterindex] = native_uiputfile( varargin{:} ) ; end catch ex rethrow(ex) end return end % end useNative %%%%%%%%%%%%%%%%% % General globals %%%%%%%%%%%%%%%%% selectedName = '' ; % multiPosition = '' ; locationPosition = '' ; fileSeparator = filesep ; %#ok %pathSeparator = pathsep ; remainderArgs = '' ; newFilter = '' ; locationPosition = '' ; % position of 'Location' arg multiSelectPosition = '' ; % position of 'MultiSelect' arg extError = 'mExtError' ; theError = '' ; %%%%%%% % Flags %%%%%%% filespecError = false ; allFound = false ; cellArrayOk = false ; locationError = false ; multiSelectOn = false ; multiSelectError = false ; %argUsedAsFileName = false ; multiSelectFound = false ; locationFound = false ; %%%%%%%%%%%%%%%%%%%%% % Filter descriptions %%%%%%%%%%%%%%%%%%%%% allMDesc = 'All MATLAB Files' ; mDesc = 'MATLAB Code (*.m)' ; figDesc = 'Figures (*.fig)' ; matDesc = 'MAT-files (*.mat)' ; simDesc = 'Simulink Models (*.mdl,*.slx)' ; staDesc = 'Stateflow Files (*.cdr)' ; wksDesc = 'Code generation files (*.rtw,*.tmf,*.tlc,*.c,*.h)' ; rptDesc = 'Report Generator Files (*.rpt)' ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Extension "specs" for our default filters % These strings are used by filters to match file extensions % NOTE that they do NOT contian a '.' character %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% mSpec = 'm' ; figSpec = 'fig' ; matSpec = 'mat' ; simSpec = 'mdl' ; sim2Spec = 'slx'; staSpec = 'cdr' ; rtwSpec = 'rtw' ; tmfSpec = 'tmf' ; tlcSpec = 'tlc' ; rptSpec = 'rpt' ; cSpec = 'c' ; hSpec = 'h' ; % allSpec = 'all' ; %%%%%%%%%%%%%%%%% % Default filters %%%%%%%%%%%%%%%%% % A filter for all Matlab files allMatlabFilter = '' ; % A filter for .m files mFilter = '' ; % A filter for .fig files figFilter = '' ; % A filter for .mat files matFilter = '' ; % A filter for Simulink files - .mdl simFilter = '' ; % A filter for Stateflow files - .cdr staFilter = '' ; % A filter for Code generation files - .rtw, .tmf, .tlc, .c, .h wksFilter = '' ; % A filter for Report Generator files - .rpt rptFilter = '' ; % A filter for all files - *.* allFilter = '' ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The dialog that holds our file chooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % jp = handle(javax.swing.JPanel) ; jp = awtcreate('com.mathworks.mwswing.MJPanel', ... 'Ljava.awt.LayoutManager;', ... java.awt.BorderLayout); d = mydialog( ... 'Visible','off', ... 'DockControls','off', ... 'Color',get(0,'DefaultUicontrolBackgroundColor'), ... 'Windowstyle','modal', ... 'Resize','on' ... ); % Create a JPanel and put it into the dialog - this is for resizing [panel, container] = javacomponent(jp,[10 10 20 20],d); % Create a JFileChooser sys = char( computer ) ; jfc = awtcreate('com.mathworks.hg.util.dFileChooser'); set( d , 'Name' , char( jfc.getDefaultPutfileTitle() ) ) awtinvoke( jfc , 'init(ZLjava.lang/String;)' , true , java.lang.String(sys) ) ; %jfc.init( true , sys ) ; % We're going to use our own "all" file filter awtinvoke( jfc , 'setAcceptAllFileFilterUsed(Z)' , false ) ; %jfc.setAcceptAllFileFilterUsed( false ) ; % Set the chooser's current directory awtinvoke( jfc , 'setCurrentDirectory(Ljava/io/File;)' , java.io.File(pwd) ) ; %jfc.setCurrentDirectory( java.io.File(pwd) ) ; % Make sure multi select is initially disabled awtinvoke( jfc , 'setMultiSelectionEnabled(Z)' , false ) ; awtinvoke( jfc , 'setDialogType(I)' , javax.swing.JFileChooser.SAVE_DIALOG ) ; awtinvoke( java(panel), 'add(Ljava.awt.Component;)', jfc ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Eliminate "built-in" args such as 'multiselect', 'location' and % their values. As a side effect, create the array remainderArgs. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% eliminateBuiltIns() ; % Exit if there was an error with MultiSelect or Location if( multiSelectError || locationError ) error( theError ) ; end if( locationFound ) warning(message('MATLAB:UIPUTFILE:LocationIgnore')); end % Check to see that there are no extra args. % 'MultiSelect', 'location' and their values % must be the last args. if( multiSelectFound && ~locationFound ) if( ~( multiSelectPosition == ( numArgs - 1 ) ) ) error( badMultiPosMessage ) ; end % end if( ~( multiSelectPosition ... end % end if( multiSelectFound ) if( locationFound && ~multiSelectFound ) if( ~( locationPosition == ( numArgs - 1 ) ) ) error( badLocationPosMessage ) ; end % end if( ~( locationPosition ... end % end if( locationFound ) if( multiSelectFound && locationFound ) if( ( ~( ( numArgs - 1 ) == multiSelectPosition ) && ~( ( numArgs - 3 ) == multiSelectPosition ) ) || ... ( ~( ( numArgs - 1 ) == locationPosition ) && ~( ( numArgs - 3 ) == locationPosition ) ) ) error( badLastArgsMessage ) ; end end % end if( multiSelectFound & locationFound ) % Set the chooser to multi select if required if( multiSelectOn ) awtinvoke( jfc , 'setMultiSelectionEnabled(Z)' , true ) ; % jfc.setMultiSelectionEnabled( true ) ; end % Reset the content of varargin & numArgs varargin = remainderArgs ; numArgs = numel( remainderArgs ) ; % At this point we can have at most 3 remaining args if( numArgs > 3 ) error( badArgsMessage ) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of no args. In this case % we load and use the default filters. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 0 == numArgs ) buildDefaultFilters() ; % Load our filters into the JFileChooser loadDefaultFilters( jfc , 1 ) ; % Set our "allMatlabFilter" to be the active filter awtinvoke( jfc , 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allMatlabFilter ) ; end % end if( 0 == numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of exactly one remaining arg. % The argument must be a string or a cell array. % % If it's a cell array we try to use it as a filespec. % % If it's a string, there are 2 options: % % If it's a legit description of a file ext, we use it % to create a filter and a description. We then add % that filter and the "all" filter to the file chooser. % Example - '*.txt' or '.txt' % % FOR COMPATIBILITY, % if it's not an ext we understand, we use it as a % "selected file name." We then set up the file chooser % to use our default filters including the "all" filter. % Example - 'x' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 1 == numArgs ) spec = varargin{ 1 } ; if ~( ischar( spec ) ) && ~( iscellstr( spec ) ) error( badFilterMessage ); end % OK - the type is correct %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case where the arg is a string %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( ischar( spec ) && isvector( spec ) ) if( ~( 1 == size( spec , 1 ) ) ) spec = spec' ; end handleStringFilespec( jfc , spec , 1 ) ; if( filespecError ) error( theError ) ; end end % end if( ischar( spec ) ) ... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case where the arg is a cell array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( iscellstr( spec ) ) cellArrayOk = false ; handleCellArrayFilespec( spec , jfc ) ; if ~cellArrayOk error( theError ) ; end end % if( iscellstr( spec ) ) end % end if( 1 == numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of two remaining args. % % If arg 1 is a good filespec, use it % and interpret the 2nd arg as a title. % % FOR COMPATIBILITY, % if arg1 is a string but not a legit % filespec, we use it as a file name % and interpret the 2nd arg as a title. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 2 == numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Error check the types of the args. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % The 2nd arg must be a string arg2 = varargin{ 2 } ; if~( ischar( arg2 ) && isvector( arg2 ) ) % Not a string error( bad2ndArgMessage ) ; end % Transpose if necessary if( ~( 1 == size( arg2 , 1 ) ) ) arg2 = arg2' ; end % Check out the first arg spec = varargin{ 1 } ; if ~( ischar( spec ) ) && ~( iscellstr( spec ) ) error( badFilterMessage ); end % OK - the types are correct %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case where the 1st arg is a string %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( ischar( spec ) && isvector( spec ) ) if( ~( 1 == size( spec , 1 ) ) ) spec = spec' ; end % See if the 1st arg is a legit extension extStr = char(com.mathworks.hg.util.dFilter.returnExtensionString( spec )) ; if( strcmpi( extStr , extError ) ) % The 1st arg is a NOT legit extension. % Use first arg as file name and 2nd arg as title set( d , 'Name' , arg2 ) ; awtinvoke( jfc , 'setSelectedFile(Ljava/io/File;)' , java.io.File( spec ) ) ; %jfc.setSelectedFile( java.io.File( spec ) ) ; % Load and use the default filters buildDefaultFilters() ; loadDefaultFilters( jfc , 1 ) ; else % The 1st arg IS a legit extension. % Use arg2 as a title string. handleStringFilespec( jfc , spec , '1' ); if( filespecError ) error( theError ) ; end set( d , 'Name' , arg2 ) ; end % if( ' ' == extStr ) else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case where first arg is a cell array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% handleCellArrayFilespec( spec , jfc ) ; if( ~cellArrayOk ) error( theError ) ; end set( d , 'Name' , arg2 ) ; end %if( ischar( spec ) & isvector( spec ) ) end % if( 2 == numArgs ) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case of three remaining arguments. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( 3 == numArgs ) % The 2nd and 3rd args must be strings arg2 = varargin{ 2 } ; if~( ischar( arg2 ) && isvector( arg2 ) ) % Not a string error( bad2ndArgMessage ) end if( ~( 1 == size( arg2 , 1 ) ) ) arg2 = arg2' ; end arg3 = varargin{ 3 } ; if~( ischar( arg3 ) && isvector( arg3 ) ) % Not a string error( bad3rdArgMessage ) end if( ~( 1 == size( arg3 , 1 ) ) ) arg3 = arg3' ; end % Use arg2 as title and arg3 as file set( d , 'Name' , arg2 ) ; awtinvoke( jfc , 'setSelectedFile(Ljava.io.File;)' , java.io.File( char(arg3) ) ) ; % jfc.setSelectedFile( java.io.File( char(arg3) ) ) ; selectedName = char( arg3 ) ; spec = varargin{ 1 } ; % The first arg must be a string or cell array if ~( ischar( spec ) ) && ~( iscellstr( spec ) ) error( badFilterMessage ); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the case where the 1st arg is a string %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if( ischar( spec ) && isvector( spec ) ) if( ~( 1 == size( spec , 1 ) ) ) spec = spec' ; end % See if the 1st arg is a legit extension extStr = com.mathworks.hg.util.dFilter.returnExtensionString( spec ) ; if( strcmpi( extStr , extError ) ) % The 1st arg is a NOT legit extension. % Ignore it FOR COMPATIBILITY WITH EXISTING RELEASE. buildDefaultFilters() ; loadDefaultFilters( jfc , 1 ) ; else % The 1st arg IS legit extension. handleStringFilespec( jfc , spec , '1' ) ; if( filespecError ) error( theError ) ; end end % if( ' ' == extStr ) else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle case where 1st arg is a cell array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% handleCellArrayFilespec( spec , jfc ) ; if( ~cellArrayOk ) error( theError ) ; end end % if( ischar( spec ) & isvector( spec ) ) end % if( 3 == numargs ) if( ~strcmp( selectedName , char('') ) ) awtinvoke( jfc , 'noteName(Ljava/lang/String;)' , java.lang.String( selectedName ) ) ; end set(container,'Units','normalized','Position',[0 0 1 1]); jfcHandle = handle(jfc , 'callbackproperties' ); set(jfcHandle,'PropertyChangeCallback', { @callbackHandler , d } ); figure(d) refresh(d) % these will get set by data from the callback filename = 0 ; pathname = 0 ; filterindex = 0 ; awtinvoke( jfc , 'listen()' ) ; waitfor(d); % Retrieve the data stored by the callback if isappdata( 0 , 'uiputfileData' ) uiputfileData = getappdata( 0 , 'uiputfileData' ) ; filename = uiputfileData.filename ; pathname = uiputfileData.pathname ; filterindex = uiputfileData.filterindex ; rmappdata( 0 , 'uiputfileData' ) ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Build all the default filters. Each filter handles % one or more extension. Each filter also has a % description string which appears in the file selection % dialog. Each filter can also be assigned a string "id." % Filters are Java objects. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buildDefaultFilters() allMatlabFilter = com.mathworks.hg.util.dFilter ; allMatlabFilter.setDescription( allMDesc ) ; allMatlabFilter.addExtension( mSpec ) ; allMatlabFilter.addExtension( figSpec ) ; allMatlabFilter.addExtension( matSpec ) ; % Filter for files mFilter = com.mathworks.hg.util.dFilter ; mFilter.setDescription( mDesc ) ; mFilter.addExtension( mSpec ) ; % Filter for .fig files figFilter = com.mathworks.hg.util.dFilter ; figFilter.setDescription( figDesc ) ; figFilter.addExtension( figSpec ) ; % Filter for MAT-files matFilter = com.mathworks.hg.util.dFilter ; matFilter.setDescription( matDesc ) ; matFilter.addExtension( matSpec ) ; % Filter for Simulink Models simFilter = com.mathworks.hg.util.dFilter ; simFilter.setDescription( simDesc ) ; simFilter.addExtension( simSpec ) ; simFilter.addExtension( sim2Spec ) ; % Filter for Stateflow files staFilter = com.mathworks.hg.util.dFilter ; staFilter.setDescription( staDesc ) ; staFilter.addExtension( staSpec ) ; % Filter for Real-Time Workshop files wksFilter = com.mathworks.hg.util.dFilter ; wksFilter.setDescription( wksDesc ) ; wksFilter.addExtension( rtwSpec ) ; wksFilter.addExtension( tmfSpec ) ; wksFilter.addExtension( tlcSpec ) ; wksFilter.addExtension( cSpec ) ; wksFilter.addExtension( hSpec ) ; % Filter for Report Generator files rptFilter = com.mathworks.hg.util.dFilter ; rptFilter.setDescription( rptDesc ) ; rptFilter.addExtension( rptSpec ) ; % Filter for "All Files" allFilter = com.mathworks.hg.util.AllFileFilter ; end % end buildDefaultFilters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Load all the default filters into the jFileChooser. % Give each filter an id starting at "startId." We'll % later use the id to determine which filter was active % when the user made the selection. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function loadDefaultFilters( chooser , startId ) j = startId ; allMatlabFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax.swing.filechooser.FileFilter;)' , allMatlabFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax.swing.filechooser.FileFilter;)' , allMatlabFilter ) ; % chooser.addFileFilter( allMatlabFilter ) ; % chooser.noteFilter( allMatlabFilter ) ; j = j + 1 ; mFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax.swing.filechooser.FileFilter;)' , mFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax.swing.filechooser.FileFilter;)' , mFilter ) ; % chooser.addFileFilter( mFilter ) ; % chooser.noteFilter( mFilter ) ; j = j + 1 ; figFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax.swing.filechooser.FileFilter;)' , figFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax.swing.filechooser.FileFilter;)' , figFilter ) ; % chooser.addFileFilter( figFilter ) ; % chooser.noteFilter( figFilter ) ; j = j + 1 ; matFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax.swing.filechooser.FileFilter;)' , matFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax.swing.filechooser.FileFilter;)' , matFilter ) ; % chooser.addFileFilter( matFilter ) ; % chooser.noteFilter( matFilter ) ; j = j + 1 ; simFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax.swing.filechooser.FileFilter;)' , simFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax.swing.filechooser.FileFilter;)' , simFilter ) ; % chooser.addFileFilter( simFilter ) ; % chooser.noteFilter( simFilter ) ; j = j + 1 ; staFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax.swing.filechooser.FileFilter;)' , staFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax.swing.filechooser.FileFilter;)' , staFilter ) ; % chooser.addFileFilter( staFilter ) ; % chooser.noteFilter( staFilter ) ; j = j + 1 ; wksFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax.swing.filechooser.FileFilter;)' , wksFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax.swing.filechooser.FileFilter;)' , wksFilter ) ; % chooser.addFileFilter( wksFilter ) ; % chooser.noteFilter( wksFilter ) ; j = j + 1 ; rptFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax.swing.filechooser.FileFilter;)' , rptFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax.swing.filechooser.FileFilter;)' , rptFilter ) ; % chooser.addFileFilter( rptFilter ) ; % chooser.noteFilter( rptFilter ) ; j = j + 1 ; allFilter.setIdentifier( int2str( j ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax.swing.filechooser.FileFilter;)' , allFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax.swing.filechooser.FileFilter;)' , allFilter ) ; % chooser.addFileFilter( allFilter ) % chooser.noteFilter( allFilter ) ; % We shouldn't need the pause or the following drawnow - % But it doesn't work without them pause(.5) ; awtinvoke( chooser, 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allMatlabFilter ) ; drawnow() ; end % end loadDefaultFilters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Build a new filter containing an extension and a description %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buildFilter( desc , ext ) newFilter = com.mathworks.hg.util.dFilter ; newFilter.setDescription( desc ) ; newFilter.addExtension( ext ) ; end % buildFilter %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Add a filter to the indicated JFileChooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function addFilterToChooser( chooser , filter ) awtinvoke( chooser , 'addFileFilter(Ljavax.swing.filechooser.FileFilter;)' , filter ) ; awtinvoke( chooser , 'noteFilter(Ljavax.swing.filechooser.FileFilter;)' , filter ) ; % chooser.addFileFilter( filter ) ; % chooser.noteFilter( filter ) ; end % end addFilterToChooser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Set the indicated filter's identifier (must be a string) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function setFilterIdentifier( filter , id ) filter.setIdentifier( id ) ; end % setFilterIdentifier %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Build a filter that "accepts" all files %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buildAllFilter() allFilter = com.mathworks.hg.util.AllFileFilter ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This handles the case where the filespec is a string %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handleStringFilespec( chooser , str , id ) %argUsedAsFileName = false ; extStr = char(com.mathworks.hg.util.dFilter.returnExtensionString( str )) ; if( strcmpi( extStr , extError ) ) % This isn't a "legal" extension we know about. % Treat it as the name of a file for COMPATIBILITY % with the current release. % test = java.io.File( str ) ; %if( test.isFile() ) awtinvoke( chooser , 'setSelectedFile(Ljava/io/File;)' , java.io.File( str ) ) ; %chooser.setSelectedFile( java.io.File( str ) ) ; buildDefaultFilters() ; loadDefaultFilters( chooser , id ) ; awtinvoke( chooser , 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allMatlabFilter ) ; %chooser.setFileFilter( allMatlabFilter ) ; %argUsedAsFileName = true ; % else % theError = caErr1Message ; % filespecError = true ; % return ; % end else % Build a new filter. % Load the new filter and the "all" filter buildFilter( spec , extStr ) ; setFilterIdentifier( newFilter , '1' ) ; addFilterToChooser( chooser , newFilter ) ; if ~( strcmp( char( spec ) , '*.*' ) ) buildAllFilter() ; setFilterIdentifier( allFilter , '2' ) ; addFilterToChooser( chooser , allFilter ) ; end % We shouldn't need the pause or the following drawnow - % But it doesn't work without them pause(.5) ; awtinvoke( chooser , 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , newFilter ) ; %chooser.setFileFilter( newFilter ) ; drawnow() ; end % end if/else end % end handleStringFilespec %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This handles the case where the filespec is a cell array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handleCellArrayFilespec( theCellArray , chooser ) cellArrayOk = false ; t = '' ; rows = '' ; cols = '' ; firstFilter = '' ; try t = size( theCellArray ) ; rows = t(1) ; cols = t(2) ; catch theError = caErr1Message ; end if( 2 < cols ) theError = caErr2Message ; end % The first col is supposed to hold an extension array extArray = '' ; descrArray = '' ; ext = '' ; %#ok for i = 1:rows ext = theCellArray{ i , 1 } ; % Format the extension for our filter s = com.mathworks.hg.util.dFilter.returnExtensionString( char(ext) ) ; s = char( s ) ; if~( strcmpi( s , extError ) ) extArray{i} = s ; else theError = strcat( caErr3Message , ext , '''' ) ; cellArrayOk = false ; end end % end for % If there are two cols, the 2nd col is % supposed to be descriptions for 1st col if( 2 == cols ) for i = 1 : rows descrArray{ i } = theCellArray{ i , 2 } ; end % end for i = 1 : rows end % end if( 2 == cols ) % Create the filters for file selection ii = 0 ; for i = 1:rows %disp( extArray{i} ) if( strcmp( char( extArray{i} ) , '*.*' )) buildAllFilter() ; allFilter.setIdentifier( int2str( i ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , allFilter ) ; % chooser.addFileFilter( allFilter ) ; % chooser.noteFilter( allFilter ) ; allFound = true ; end if ~( strcmp( char( extArray{i} ) , '*.*' ) ) usrFilter = com.mathworks.hg.util.dFilter ; usrFilter.addExtension( extArray{i} ) ; usrFilter.setIdentifier( int2str(i) ) ; if( 2 == cols ) usrFilter.setDescription( descrArray{i} ) ; else usrFilter.setDescription( theCellArray{i,1} ) ; end % end if( 2 == cols ) % Add the filter awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , usrFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , usrFilter ) ; % chooser.addFileFilter( usrFilter ) ; % chooser.noteFilter( usrFilter ) ; % Set a current filter if( 1 == i ) firstFilter = usrFilter ; %awtinvoke( chooser , 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , usrFilter ) ; %chooser.setFileFilter( usrFilter ) ; end % end if( 1 == i ) ii = i ; end % end if ~( strcmp( char( extArray{i} ) , '*.*' ) ) end % end for i = 1:rows % Add in the "all" filter if( ~allFound ) buildAllFilter() ; allFilter.setIdentifier( int2str( ii+1 ) ) ; awtinvoke( chooser , 'addFileFilter(Ljavax/swing/filechooser/FileFilter;)' , allFilter ) ; awtinvoke( chooser , 'noteFilter(Ljavax/swing/filechooser/FileFilter;)' , allFilter ) ; % chooser.addFileFilter( allFilter ) ; % chooser.noteFilter( allFilter ) ; end % Set the user's first filter as the active filter % Shouldn't need the pause and drawnow, but things % don't work without them. pause(.5) ; awtinvoke( chooser , 'setFileFilter(Ljavax/swing/filechooser/FileFilter;)' , firstFilter ) ; drawnow() ; cellArrayOk = true ; end % end handleCellArrayFilespec %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Scan the input arguments for 'Location'. % If either is present, check that the next arg has an % appropriate value. If not, set an appropriate error flag. % % Also, store all the other arguments in the array "remaining args". %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function eliminateBuiltIns() args = varargin ; numberOfArgs = numel( args ) ; remainderArgIndex = 1 ; i = 1 ; while( i <= numberOfArgs ) theArg = args{i} ; % Add to remainder args if its not a string if( ~( ischar( theArg ) ) || ~( isvector( theArg ) ) ) remainderArgs{ remainderArgIndex } = theArg ; %#ok<AGROW> remainderArgIndex = remainderArgIndex + 1 ; i = i + 1 ; %end % end if( ~( ischar( theArg ) ) | ~( isvector( theArg ) ) ) if( i > numberOfArgs ) return end continue end % end if( ~( ischar( theArg ) ) | ~( isvector( theArg ) ) ) % Transpose if necessary if( ~( 1 == size( theArg , 1 ) ) ) theArg = theArg' ; end % Check to see if we have an interesting string lowArg = lower( theArg ) ; %if( ~strcmp( 'multiselect' , lowArg ) & ~strcmp( 'location' , lowArg ) ) if( ~strcmp( 'location' , lowArg ) ) remainderArgs{ remainderArgIndex } = theArg ; %#ok<AGROW> remainderArgIndex = remainderArgIndex + 1 ; i = i + 1 ; continue ; end % end if( ~strcmp( 'multiselect' , lowArg ) ... % Check the next arg - we have found x'location' i = i + 1 ; if( i > numberOfArgs ) % oops - missing arg switch( lowArg ) % case 'multiselect' % theError = badMultiMessage ; % multiSelectError = true ; % return case 'location' theError = badLocMessage ; locationError = true ; return end % end switch return end % end if( i > numberOfArgs ) nextArg = args{ i } ; switch( lowArg ) case 'location' % nextArg must be a numeric vector if( ~( isvector( nextArg ) ) || ... ~( isnumeric( nextArg ) ) ) theError = badLocMessage ; locationError = true ; return end % Transpose if necessary if( ~( 1 == size( nextArg , 1 ) ) ) nextArg = nextArg' ; end % Check size if( ~( 1 == size( nextArg , 1 ) ) || ... ~( 2 == size( nextArg , 2 ) ) ) theError = badLocMessage ; locationError = true ; return end % Record the fact that we've found 'location' locationFound = true ; locationPosition = i - 1 ; % skip to the next arg i = i + 1 ; if( i > numberOfArgs ) return end end % end switch end % end while end % eliminateBuiltIns function out = mydialog(varargin) out = []; try out = dialog(varargin{:}) ; catch ex rethrow(ex) end end % end myDialog end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Handle the callback from the JFileChooser. If the user % selected "Open", return the name of the selected file, % the full pathname and the index of the current filter. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function callbackHandler( obj, evd , d ) fileSeparator = filesep ; jfc = obj ; cmd = char(evd.getPropertyName()); switch(cmd) case 'mathworksHgCancel' if ishandle(d) close(d) end case 'mathworksHgOk' [pathname, fn, ext ] = fileparts(char(jfc.getSelectedFile.toString)); if (isempty(ext)) % If the file name did not have any extension specified, try to % guess from the filter selection (only if its not a compound % filter). filt_desc = char(jfc.getFileFilter().getDescription()); if (length(strfind(filt_desc, '.')) == 1) ext = strtrim(filt_desc(strfind(filt_desc, '.') : ... strfind(filt_desc, ')')-1)); end end uiputfileData.filename = [fn ext]; % concatenate filename and ext. uiputfileData.pathname = strcat( pathname , fileSeparator ) ; % add trailing sep uiputfileData.filterindex = str2double( jfc.getFileFilter().getIdentifier() ) ; setappdata( 0 , 'uiputfileData' , uiputfileData ) ; close(d); end % end switch end % callbackHandler
github
BottjerLab/Acoustic_Similarity-master
prefutils.m
.m
Acoustic_Similarity-master/code/interactive/private/prefutils.m
3,035
utf_8
77563c8b2ed8cde2667908a0fdf1a29e
function varargout = prefutils(varargin) % PREFUTILS Utilities used by set/get/is/add/rmpref % $Revision: 1.7.4.3 $ $Date: 2011/03/09 07:07:28 $ % Copyright 1984-2005 The MathWorks, Inc. % Switchyard: call the subfunction named by the first input % argument, passing it the remaning input arguments, and returning % any return arguments from it. [varargout{1:nargout}] = feval(varargin{:}); function prefName = truncToMaxLength(prefName) % This is necessary because SETFIELD/GETFIELD/ISFIELD/RMFIELD do % not operate the same as dotref and dotassign when it comes to % variable names longer than 'namelengthmax'. Dotref/dotassign % do an implicit truncation, so both operations appear to work % fine with longer names, even though they're really paying % attention only to the first 31 characters. But the *field % functions don't do the truncation, so GETFIELD and ISFIELD % and RMFIELD report errors when you pass them a longer name that % you've just used with SETFIELD. So the suite of pref functions % are using truncToMaxLength until that bug is fixed - when it is, % just remove this. prefName = prefName(1:min(end, namelengthmax)); function prefFile = getPrefFile % return name of preferences file, create pref dir if it does not exist prefFile = [prefdir(1) filesep 'matlabprefs.mat']; function Preferences = loadPrefs % return ALL preferences in the file. Return empty matrix if file % doesn't exist, or it is empty. prefFile = getPrefFile; Preferences = []; if exist(prefFile) fileContents = load(prefFile); if isfield(fileContents, 'Preferences') Preferences = fileContents.Preferences; end end function savePrefs(Preferences) prefFile = getPrefFile; save(prefFile, 'Preferences'); function [val, existed_out] = getFieldOptional(s, f) fMax = truncToMaxLength(f); existed = isfield(s, fMax); if existed == 1 val = s.(fMax); else val = []; end if nargout == 2 existed_out = existed; end function val = getFieldRequired(s, f, e) [val, existed] = getFieldOptional(s, f); if ~existed error(e); end function [p_out, v_out] = checkAndConvertToCellVector(pref, value) % Pref must be a string or cell array of strings. % return it as a cell vector. % Value (if passed in) must be the same length as Pref. % return it as a cell vector (only convert it to cell if we % converted Pref to cell) if ischar(pref) p_out = {pref}; elseif iscell(pref) p_out = {pref{:}}; for i = 1:length(p_out) if ~ischar(p_out{i}) error(message('MATLAB:prefutils:InvalidCellArray')); end end else error(message('MATLAB:prefutils:InvalidPREFinput')); end if nargin == 2 if ischar(pref) v_out = {value}; elseif iscell(value) v_out = {value{:}}; else error(message('MATLAB:prefutils:InvalidValueType')); end if length(v_out) ~= length(p_out) error(message('MATLAB:prefutils:InvalidValueType')); end end function checkGroup(group) % Error out if group is not a string: if ~ischar(group) error(message('MATLAB:prefutils:InvalidGroupInput')); end
github
BottjerLab/Acoustic_Similarity-master
chkmem.m
.m
Acoustic_Similarity-master/code/fileExchange/chkmem.m
8,064
utf_8
cdbeeb4199d2ee2ca04d008c7a5de7be
function chkmem % CHKMEM % This utility measures the size of the largest contiguous block of virtual % memory available to MATLAB, then recommends solutions to increase its % size should it be smaller than typical. This is only for the diagnosis of % memory fragmentation problems just after MATLAB startup. % % The recommended solutions can help to reduce the occurence of "Out of Memory" % errors. See MEMORY function in MATLAB 7.6 and later. % % Example: % chkmem % MATLAB Memory Fragmentation Detection Utility % --------------------------------------------- % Measurement of largest block size: % Largest free block is 1157MB, which is close to typical (1200MB) but less than % best case (1500MB), therefore, its size **CAN BE INCREASED** and may reduce the % occurrence of "Out of Memory" errors if you are experiencing them. % % Possible software modules fragmenting MATLAB's memory space: % c:\winnt\system32\uxtheme.dll % % Recommendations to increase size of largest block: % * The location of uxtheme.dll may be causing problems. Consider solution 1-1HE4G5, % which rebases a group of Windows DLLs. This has some known side effects which you % should consider. If you choose to make the changes, restart MATLAB and run % this utility again. % * If the list of software modules above includes DLLs located in the MATLAB % installation directory, check your startup.m or matlabrc.m files to see if % they are running code that is not essential. % * If the list of software modules above includes DLLs from applications other than % Windows or MATLAB, consider uninstalling the application if it is not essential, % then restart MATLAB and run this utility again. A tool such as Process Explorer % can help identify the source and manufacturer of DLLs MATLAB is using. You could % also contact the software manufacturer to ask if the DLL can be safely rebased. % % 3GB switch status: % The MATLAB process limit has been detected as is 3071MB, therefore the 3GB switch % in your system's boot.ini is SET. % % Copyright 2007-2009 The MathWorks, Inc %% Test platform if ~strcmp(computer,'PCWIN') % Check for 32-bit Windows error('This utility is supported on 32-bit Windows only.'); else fprintf('\n'); fprintf('MATLAB Memory Fragmentation Detection Utility\n'); fprintf('---------------------------------------------\n'); str = evalc('feature(''dumpmem'')'); newlines = regexp(str,'\n'); memmap=cell(size(newlines,2)-2,4); % Preallocate %% Extract info about s/w modules for i=4:size(newlines,2)-5 memmap{i-3,1}=deblank(str(newlines(i-1)+1:newlines(i)-36)); memmap{i-3,2}=hex2dec(str(newlines(i)-35:newlines(i)-28)); memmap{i-3,3}=hex2dec(str(newlines(i)-23:newlines(i)-16)); memmap{i-3,4}=hex2dec(str(newlines(i)-11:newlines(i)-4)); end %% Analyze Largest Block fprintf('Measurement of largest block size:\n') free=cell2mat(memmap(:,4)); [largest index]=max(free); fprintf(' Largest free block is %dMB, ',floor(largest/2^20)); if largest >= 1.4e9 fprintf('which is close to best case (1500MB), therefore\n cannot be improved.\n'); else if largest >= 1.2e9 fprintf('which is close to typical (1200MB) but less than\n'); fprintf(' best case (1500MB), therefore its size **CAN BE INCREASED** and may reduce the\n'); fprintf(' occurrence of "Out of Memory" errors if you are experiencing them.\n'); else fprintf('which is less than typical (1100MB) and much less than\n'); fprintf(' best case (1500MB), therefore its size **CAN BE INCREASED** and may reduce the\n'); fprintf(' occurrence of "Out of Memory" errors if you are experiencing them.\n'); end %% Cause of fragmentation modules=memmap([index-1:index+1],1); found=~strcmp(modules,' <anonymous>'); fprintf('\nPossible software modules fragmenting MATLAB''s memory space:\n'); foundOnes=modules(found); for i=1:length(foundOnes) disp(foundOnes{i}); end if isempty(foundOnes) fprintf(' No software modules found. It is likely that chkmem is not being run\n') fprintf(' immediately after startup. Restart MATLAB and run it again.\n'); else %% Fragmentation Solutions fprintf('\nRecommendations to increase size of largest block:\n'); if ~isempty(cell2mat(strfind(modules,'uxtheme.dll'))) fprintf('* The location of uxtheme.dll may be causing problems. Consider solution <a href="http://www.mathworks.com/support/solutions/data/1-1HE4G5.html?solution=1-1HE4G5">1-1HE4G5</a>,\n'); fprintf(' which rebases a group of Windows DLLs. This has some known side effects which you\n'); fprintf(' should consider. If you choose to make the changes, restart MATLAB and run\n'); fprintf(' this utility again.\n'); end if ~isempty(cell2mat(strfind(modules,'NETAPI32.dll'))) fprintf('* The location of NETAPI32.dll may be causing problems. Consider solution <a href="http://www.mathworks.com/support/solutions/data/1-1HE4G5.html?solution=1-1HE4G5">1-1HE4G5</a>,\n'); fprintf(' which rebases a group of windows DLLs. This has some known side effects which you\n'); fprintf(' should consider. If you choose to make the changes, restart MATLAB and run\n'); fprintf(' this utility again.\n'); end if ~isempty(cell2mat(strfind(modules,'wr_nspr4'))); fprintf('* The location of wr_nspr4.dll may be causing problems, consider <a href="http://www.mathworks.com/support/bugreports/details.html?rp=334120">Bug Report 334120</a>.\n'); end fprintf('* If the list of software modules above includes DLLs located in the MATLAB\n'); fprintf(' installation directory, check your startup.m or matlabrc.m files to see if\n'); fprintf(' they are running code that is not essential.\n'); fprintf('* If the list of software modules above includes DLLs from applications other than\n'); fprintf(' Windows or MATLAB, consider uninstalling the application if it is not essential,\n'); fprintf(' then restart MATLAB and run this utility again. A tool such as <a href="http://www.microsoft.com/technet/sysinternals/utilities/ProcessExplorer.mspx">Process Explorer</a>\n'); fprintf(' can help identify the source and manufacturer of DLLs MATLAB is using. You could\n'); fprintf(' also contact the software manufacturer to ask if the DLL can be safely rebased.\n'); end end end %% 3GB Switch setting information virtual=virtinfo; fprintf('\n3GB switch status:\n') if virtual ==2047 fprintf(' The MATLAB process limit has been detected as %dMB, therefore the 3GB switch\n',virtual); fprintf(' in your system''s boot.ini file is NOT SET. If you add this switch you can gain\n'); fprintf(' an additional 1GB of memory space for MATLAB. See this <a href="http://www.microsoft.com/whdc/system/platform/server/PAE/PAEmem.mspx">Microsoft Web Page</a>\n'); fprintf(' describing the /3GB switch (or <a href="http://www.google.com/search?hl=en&q=3gb&btnG=Google+Search">search Google</a>).\n'); else fprintf(' The MATLAB process limit has been detected as is %dMB, therefore the 3GB switch\n in your system''s boot.ini is SET.\n',virtual); end function virtualTotal = virtinfo % Calculates total memory for MATLAB process str = evalc('feature memstats'); ind = findstr(str,'MB'); LEN = 20; % Virtual Memory (Address Space): % In Use: 536 MB (21851000) % Free: 1511 MB (5e78f000) % Total: 2047 MB (7ffe0000) retval = str((ind(9)-2):-1:ind(9)-LEN); virtualTotal = str2double(fliplr(retval));
github
BottjerLab/Acoustic_Similarity-master
xlswrite1.m
.m
Acoustic_Similarity-master/code/fileExchange/xlswrite1.m
10,438
utf_8
ef574cfee4f63e3d03d942a2194061cc
function xlswrite1(file,data,sheet,range) Excel=evalin('base','Excel'); % Set default values. Sheet1 = 1; if nargin < 3 sheet = Sheet1; range = ''; elseif nargin < 4 range = ''; end if nargout > 0 success = true; message = struct('message',{''},'identifier',{''}); end % Handle input. try % handle requested Excel workbook filename. if ~isempty(file) if ~ischar(file) error('MATLAB:xlswrite:InputClass','Filename must be a string'); end % check for wildcards in filename if any(findstr('*', file)) error('MATLAB:xlswrite:FileName', 'Filename must not contain *'); end [Directory,file,ext]=fileparts(file); if isempty(ext) % add default Excel extension; ext = '.xls'; end file = abspath(fullfile(Directory,[file ext])); [a1 a2 a3] = fileattrib(file); if a1 && ~(a2.UserWrite == 1) error('MATLAB:xlswrite:FileReadOnly', 'File can not be read only.'); end else % get workbook filename. error('MATLAB:xlswrite:EmptyFileName','Filename is empty.'); end % Check for empty input data if isempty(data) error('MATLAB:xlswrite:EmptyInput','Input array is empty.'); end % Check for N-D array input data if ndims(data)>2 error('MATLAB:xlswrite:InputDimension',... 'Dimension of input array cannot be higher than two.'); end % Check class of input data if ~(iscell(data) || isnumeric(data) || ischar(data)) && ~islogical(data) error('MATLAB:xlswrite:InputClass',... 'Input data must be a numeric, cell, or logical array.'); end % convert input to cell array of data. if iscell(data) A=data; else A=num2cell(data); end if nargin > 2 % Verify class of sheet parameter. if ~(ischar(sheet) || (isnumeric(sheet) && sheet > 0)) error('MATLAB:xlswrite:InputClass',... 'Sheet argument must a string or a whole number greater than 0.'); end if isempty(sheet) sheet = Sheet1; end % parse REGION into sheet and range. % Parse sheet and range strings. if ischar(sheet) && ~isempty(strfind(sheet,':')) range = sheet; % only range was specified. sheet = Sheet1;% Use default sheet. elseif ~ischar(range) error('MATLAB:xlswrite:InputClass',... 'Range argument must a string of Excel A1 notation.'); end end catch if ~isempty(nargchk(2,4,nargin)) error('MATLAB:xlswrite:InputArguments',nargchk(2,4,nargin)); elseif nargout == 0 rethrow(lasterror); % Display last error. else success = false; message = lasterror; % Return last error. end return; end %------------------------------------------------------------------------------ try % Construct range string if isempty(strfind(range,':')) % Range was partly specified or not at all. Calculate range. [m,n] = size(A); range = calcrange(range,m,n); end catch if nargout == 0 rethrow(lasterror); % Display last error. else success = false; message = lasterror; % Return last error. end return; end %------------------------------------------------------------------------------ try if ~exist(file,'file') % Create new workbook. %This is in place because in the presence of a Google Desktop %Search installation, calling Add, and then SaveAs after adding data, %to create a new Excel file, will leave an Excel process hanging. %This workaround prevents it from happening, by creating a blank file, %and saving it. It can then be opened with Open. ExcelWorkbook = Excel.workbooks.Add; ExcelWorkbook.SaveAs(file,1); ExcelWorkbook.Close(false); end %Open file %ExcelWorkbook = Excel.workbooks.Open(file); try % select region. % Activate indicated worksheet. message = activate_sheet(Excel,sheet); % Select range in worksheet. Select(Range(Excel,sprintf('%s',range))); catch % Throw data range error. error('MATLAB:xlswrite:SelectDataRange',lasterr); end % Export data to selected region. set(Excel.selection,'Value',A); %ExcelWorkbook.Save %ExcelWorkbook.Close(false) % Close Excel workbook. %Excel.Quit; catch try %ExcelWorkbook.Close(false); % Close Excel workbook. end %Excel.Quit; %delete(Excel); % Terminate Excel server. if nargout == 0 rethrow(lasterror); % Display last error. else success = false; message = lasterror; % Return last error. end end %-------------------------------------------------------------------------- function message = activate_sheet(Excel,Sheet) % Activate specified worksheet in workbook. % Initialise worksheet object WorkSheets = Excel.sheets; message = struct('message',{''},'identifier',{''}); % Get name of specified worksheet from workbook try TargetSheet = get(WorkSheets,'item',Sheet); catch % Worksheet does not exist. Add worksheet. TargetSheet = addsheet(WorkSheets,Sheet); warning('MATLAB:xlswrite:AddSheet','Added specified worksheet.'); if nargout > 0 [message.message,message.identifier] = lastwarn; end end % activate worksheet Activate(TargetSheet); %------------------------------------------------------------------------------ function newsheet = addsheet(WorkSheets,Sheet) % Add new worksheet, Sheet into worsheet collection, WorkSheets. if isnumeric(Sheet) % iteratively add worksheet by index until number of sheets == Sheet. while WorkSheets.Count < Sheet % find last sheet in worksheet collection lastsheet = WorkSheets.Item(WorkSheets.Count); newsheet = WorkSheets.Add([],lastsheet); end else % add worksheet by name. % find last sheet in worksheet collection lastsheet = WorkSheets.Item(WorkSheets.Count); newsheet = WorkSheets.Add([],lastsheet); end % If Sheet is a string, rename new sheet to this string. if ischar(Sheet) set(newsheet,'Name',Sheet); end %------------------------------------------------------------------------------ function [absolutepath]=abspath(partialpath) % parse partial path into path parts [pathname filename ext] = fileparts(partialpath); % no path qualification is present in partial path; assume parent is pwd, except % when path string starts with '~' or is identical to '~'. if isempty(pathname) && isempty(strmatch('~',partialpath)) Directory = pwd; elseif isempty(regexp(partialpath,'(.:|\\\\)')) && ... isempty(strmatch('/',partialpath)) && ... isempty(strmatch('~',partialpath)); % path did not start with any of drive name, UNC path or '~'. Directory = [pwd,filesep,pathname]; else % path content present in partial path; assume relative to current directory, % or absolute. Directory = pathname; end % construct absulute filename absolutepath = fullfile(Directory,[filename,ext]); %------------------------------------------------------------------------------ function range = calcrange(range,m,n) % Calculate full target range, in Excel A1 notation, to include array of size % m x n range = upper(range); cols = isletter(range); rows = ~cols; % Construct first row. if ~any(rows) firstrow = 1; % Default row. else firstrow = str2double(range(rows)); % from range input. end % Construct first column. if ~any(cols) firstcol = 'A'; % Default column. else firstcol = range(cols); % from range input. end try lastrow = num2str(firstrow+m-1); % Construct last row as a string. firstrow = num2str(firstrow); % Convert first row to string image. lastcol = dec2base27(base27dec(firstcol)+n-1); % Construct last column. range = [firstcol firstrow ':' lastcol lastrow]; % Final range string. catch error('MATLAB:xlswrite:CalculateRange',... 'Data range must be between A1 and IV65536.'); end %------------------------------------------------------------------------------ function s = dec2base27(d) % DEC2BASE27(D) returns the representation of D as a string in base 27, % expressed as 'A'..'Z', 'AA','AB'...'AZ', until 'IV'. Note, there is no zero % digit, so strictly we have hybrid base26, base27 number system. D must be a % negative integer bigger than 0 and smaller than 2^52, which is the maximum % number of columns in an Excel worksheet. % % Examples % dec2base(1) returns 'A' % dec2base(26) returns 'Z' % dec2base(27) returns 'AA' %----------------------------------------------------------------------------- b = 26; symbols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; d = d(:); if d ~= floor(d) | any(d < 0) | any(d > 1/eps) error('MATLAB:xlswrite:Dec2BaseInput',... 'D must be an integer, 0 <= D <= 2^52.'); end % find the number of columns in new base n = max(1,round(log2(max(d)+1)/log2(b))); while any(b.^n <= d) n = n + 1; end % set b^0 column s(:,n) = rem(d,b); while n > 1 && any(d) if s(:,n) == 0 s(:,n) = b; end if d > b % after the carry-over to the b^(n+1) column if s(:,n) == b % for the b^n digit at b, set b^(n+1) digit to b s(:,n-1) = floor(d/b)-1; else % set the b^(n+1) digit to the new value after the last carry-over. s(:,n-1) = rem(floor(d/b),b); end else s(:,n-1) = []; % remove b^(n+1) digit. end n = n - 1; end s = symbols(s); %------------------------------------------------------------------------------ function d = base27dec(s) % BASE27DEC(S) returns the decimal of string S which represents a number in % base 27, expressed as 'A'..'Z', 'AA','AB'...'AZ', until 'IV'. Note, there is % no zero so strictly we have hybrid base26, base27 number system. % % Examples % base27dec('A') returns 1 % base27dec('Z') returns 26 % base27dec('IV') returns 256 %----------------------------------------------------------------------------- d = 0; b = 26; n = numel(s); for i = n:-1:1 d = d+(s(i)-'A'+1)*(b.^(n-i)); end %-------------------------------------------------------------------------------
github
BottjerLab/Acoustic_Similarity-master
pdftops.m
.m
Acoustic_Similarity-master/code/fileExchange/export_fig/pdftops.m
2,962
utf_8
fc695d9dae7025244e0f02be5116be46
function varargout = pdftops(cmd) %PDFTOPS Calls a local pdftops executable with the input command % % Example: % [status result] = pdftops(cmd) % % Attempts to locate a pdftops executable, finally asking the user to % specify the directory pdftops was installed into. The resulting path is % stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have pdftops (from the Xpdf package) % installed on your system. You can download this from: % http://www.foolabs.com/xpdf % % IN: % cmd - Command string to be passed into pdftops. % % OUT: % status - 0 iff command ran without problem. % result - Output from pdftops. % Copyright: Oliver Woodford, 2009-2010 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path % under linux. % Call pdftops [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd)); return function path_ = xpdf_path % Return a valid path % Start with the currently set path path_ = user_string('pdftops'); % Check the path works if check_xpdf_path(path_) return end % Check whether the binary is on the path if ispc bin = 'pdftops.exe'; else bin = 'pdftops'; end if check_store_xpdf_path(bin) path_ = bin; return end % Search the obvious places if ispc path_ = 'C:\Program Files\xpdf\pdftops.exe'; else path_ = '/usr/local/bin/pdftops'; end if check_store_xpdf_path(path_) return end % Ask the user to enter the path while 1 if strncmp(computer,'MAC',3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.')) end base = uigetdir('/', 'Pdftops not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) path_ = [base bin_dir{a} bin]; if exist(path_, 'file') == 2 break; end end if check_store_xpdf_path(path_) return end end error('pdftops executable not found.'); function good = check_store_xpdf_path(path_) % Check the path is valid good = check_xpdf_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('pdftops', path_) warning('Path to pdftops executable could not be saved. Enter it manually in pdftops.txt.'); return end return function good = check_xpdf_path(path_) % Check the path is valid [good message] = system(sprintf('"%s" -h', path_)); % system returns good = 1 even when the command runs % Look for something distinct in the help text good = ~isempty(strfind(message, 'PostScript')); return
github
BottjerLab/Acoustic_Similarity-master
isolate_axes.m
.m
Acoustic_Similarity-master/code/fileExchange/export_fig/isolate_axes.m
3,447
utf_8
c6ed56010868279f32b86dfa9815d524
%ISOLATE_AXES Isolate the specified axes in a figure on their own % % Examples: % fh = isolate_axes(ah) % fh = isolate_axes(ah, vis) % % This function will create a new figure containing the axes/uipanels % specified, and also their associated legends and colorbars. The objects % specified must all be in the same figure, but they will generally only be % a subset of the objects in the figure. % % IN: % ah - An array of axes and uipanel handles, which must come from the % same figure. % vis - A boolean indicating whether the new figure should be visible. % Default: false. % % OUT: % fh - The handle of the created figure. % Copyright (C) Oliver Woodford 2011-2012 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs % 16/3/2012 Moved copyfig to its own function. Thanks to Bob Fratantonio % for pointing out that the function is also used in export_fig.m. % 12/12/12 - Add support for isolating uipanels. Thanks to michael for % suggesting it. % 08/10/13 - Bug fix to allchildren suggested by Will Grant (many thanks!). function fh = isolate_axes(ah, vis) % Make sure we have an array of handles if ~all(ishandle(ah)) error('ah must be an array of handles'); end % Check that the handles are all for axes or uipanels, and are all in the same figure fh = ancestor(ah(1), 'figure'); nAx = numel(ah); for a = 1:nAx if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'}) error('All handles must be axes or uipanel handles.'); end if ~isequal(ancestor(ah(a), 'figure'), fh) error('Axes must all come from the same figure.'); end end % Tag the objects so we can find them in the copy old_tag = get(ah, 'Tag'); if nAx == 1 old_tag = {old_tag}; end set(ah, 'Tag', 'ObjectToCopy'); % Create a new figure exactly the same as the old one fh = copyfig(fh); %copyobj(fh, 0); if nargin < 2 || ~vis set(fh, 'Visible', 'off'); end % Reset the object tags for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Find the objects to save ah = findall(fh, 'Tag', 'ObjectToCopy'); if numel(ah) ~= nAx close(fh); error('Incorrect number of objects found.'); end % Set the axes tags to what they should be for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Keep any legends and colorbars which overlap the subplots lh = findall(fh, 'Type', 'axes', '-and', {'Tag', 'legend', '-or', 'Tag', 'Colorbar'}); nLeg = numel(lh); if nLeg > 0 ax_pos = get(ah, 'OuterPosition'); if nAx > 1 ax_pos = cell2mat(ax_pos(:)); end ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2); leg_pos = get(lh, 'OuterPosition'); if nLeg > 1; leg_pos = cell2mat(leg_pos); end leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2); for a = 1:nAx % Overlap test ah = [ah; lh(leg_pos(:,1) < ax_pos(a,3) & leg_pos(:,2) < ax_pos(a,4) &... leg_pos(:,3) > ax_pos(a,1) & leg_pos(:,4) > ax_pos(a,2))]; end end % Get all the objects in the figure axs = findall(fh); % Delete everything except for the input objects and associated items delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)]))); return function ah = allchildren(ah) ah = findall(ah); if iscell(ah) ah = cell2mat(ah); end ah = ah(:); return function ph = allancestors(ah) ph = []; for a = 1:numel(ah) h = get(ah(a), 'parent'); while h ~= 0 ph = [ph; h]; h = get(h, 'parent'); end end return
github
BottjerLab/Acoustic_Similarity-master
pdf2eps.m
.m
Acoustic_Similarity-master/code/fileExchange/export_fig/pdf2eps.m
1,473
utf_8
cb8bb442a3d65a64025c32693704d89e
%PDF2EPS Convert a pdf file to eps format using pdftops % % Examples: % pdf2eps source dest % % This function converts a pdf file to eps format. % % This function requires that you have pdftops, from the Xpdf suite of % functions, installed on your system. This can be downloaded from: % http://www.foolabs.com/xpdf % %IN: % source - filename of the source pdf file to convert. The filename is % assumed to already have the extension ".pdf". % dest - filename of the destination eps file. The filename is assumed to % already have the extension ".eps". % Copyright (C) Oliver Woodford 2009-2010 % Thanks to Aldebaro Klautau for reporting a bug when saving to % non-existant directories. function pdf2eps(source, dest) % Construct the options string for pdftops options = ['-q -paper match -eps -level2 "' source '" "' dest '"']; % Convert to eps using pdftops [status message] = pdftops(options); % Check for error if status % Report error if isempty(message) error('Unable to generate eps. Check destination directory is writable.'); else error(message); end end % Fix the DSC error created by pdftops fid = fopen(dest, 'r+'); if fid == -1 % Cannot open the file return end fgetl(fid); % Get the first line str = fgetl(fid); % Get the second line if strcmp(str(1:min(13, end)), '% Produced by') fseek(fid, -numel(str)-1, 'cof'); fwrite(fid, '%'); % Turn ' ' into '%' end fclose(fid); return
github
BottjerLab/Acoustic_Similarity-master
print2array.m
.m
Acoustic_Similarity-master/code/fileExchange/export_fig/print2array.m
6,276
utf_8
259fd52e4431efae4d76ca22d1d8dac8
%PRINT2ARRAY Exports a figure to an image array % % Examples: % A = print2array % A = print2array(figure_handle) % A = print2array(figure_handle, resolution) % A = print2array(figure_handle, resolution, renderer) % [A bcol] = print2array(...) % % This function outputs a bitmap image of the given figure, at the desired % resolution. % % If renderer is '-painters' then ghostcript needs to be installed. This % can be downloaded from: http://www.ghostscript.com % % IN: % figure_handle - The handle of the figure to be exported. Default: gcf. % resolution - Resolution of the output, as a factor of screen % resolution. Default: 1. % renderer - string containing the renderer paramater to be passed to % print. Default: '-opengl'. % % OUT: % A - MxNx3 uint8 image of the figure. % bcol - 1x3 uint8 vector of the background color % Copyright (C) Oliver Woodford 2008-2012 % 05/09/11: Set EraseModes to normal when using opengl or zbuffer % renderers. Thanks to Pawel Kocieniewski for reporting the % issue. % 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting % the issue. % 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure % size and erasemode settings. Makes it a bit slower, but more % reliable. Thanks to Phil Trinh and Meelis Lootus for reporting % the issues. % 09/12/11: Pass font path to ghostscript. % 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to % Ken Campbell for reporting it. % 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting % it. % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for % reporting the issue. function [A, bcol] = print2array(fig, res, renderer) % Generate default input arguments, if needed if nargin < 2 res = 1; if nargin < 1 fig = gcf; end end % Warn if output is large old_mode = get(fig, 'Units'); set(fig, 'Units', 'pixels'); px = get(fig, 'Position'); set(fig, 'Units', old_mode); npx = prod(px(3:4)*res)/1e6; if npx > 30 % 30M pixels or larger! warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx); end % Retrieve the background colour bcol = get(fig, 'Color'); % Set the resolution parameter res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))]; % Generate temporary file name tmp_nam = [tempname '.tif']; if nargin > 2 && strcmp(renderer, '-painters') % Print to eps file tmp_eps = [tempname '.eps']; print2eps(tmp_eps, fig, renderer, '-loose'); try % Initialize the command to export to tiff using ghostscript cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc']; % Set the font path fp = font_path(); if ~isempty(fp) cmd_str = [cmd_str ' -sFONTPATH="' fp '"']; end % Add the filenames cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"']; % Execute the ghostscript command ghostscript(cmd_str); catch me % Delete the intermediate file delete(tmp_eps); rethrow(me); end % Delete the intermediate file delete(tmp_eps); % Read in the generated bitmap A = imread(tmp_nam); % Delete the temporary bitmap file delete(tmp_nam); % Set border pixels to the correct colour if isequal(bcol, 'none') bcol = []; elseif isequal(bcol, [1 1 1]) bcol = uint8([255 255 255]); else for l = 1:size(A, 2) if ~all(reshape(A(:,l,:) == 255, [], 1)) break; end end for r = size(A, 2):-1:l if ~all(reshape(A(:,r,:) == 255, [], 1)) break; end end for t = 1:size(A, 1) if ~all(reshape(A(t,:,:) == 255, [], 1)) break; end end for b = size(A, 1):-1:t if ~all(reshape(A(b,:,:) == 255, [], 1)) break; end end bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1)); for c = 1:size(A, 3) A(:,[1:l-1, r+1:end],c) = bcol(c); A([1:t-1, b+1:end],:,c) = bcol(c); end end else if nargin < 3 renderer = '-opengl'; end err = false; % Set paper size old_pos_mode = get(fig, 'PaperPositionMode'); old_orientation = get(fig, 'PaperOrientation'); set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait'); try % Print to tiff file print(fig, renderer, res_str, '-dtiff', tmp_nam); % Read in the printed file A = imread(tmp_nam); % Delete the temporary file delete(tmp_nam); catch ex err = true; end % Reset paper size set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation); % Throw any error that occurred if err rethrow(ex); end % Set the background color if isequal(bcol, 'none') bcol = []; else bcol = bcol * 255; if isequal(bcol, round(bcol)) bcol = uint8(bcol); else bcol = squeeze(A(1,1,:)); end end end % Check the output size is correct if isequal(res, round(res)) px = [px([4 3])*res 3]; if ~isequal(size(A), px) % Correct the output size A = A(1:min(end,px(1)),1:min(end,px(2)),:); end end return % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); return
github
BottjerLab/Acoustic_Similarity-master
eps2pdf.m
.m
Acoustic_Similarity-master/code/fileExchange/export_fig/eps2pdf.m
5,017
utf_8
bc81caea32035f06d8cb08ea1ccdc81f
%EPS2PDF Convert an eps file to pdf format using ghostscript % % Examples: % eps2pdf source dest % eps2pdf(source, dest, crop) % eps2pdf(source, dest, crop, append) % eps2pdf(source, dest, crop, append, gray) % eps2pdf(source, dest, crop, append, gray, quality) % % This function converts an eps file to pdf format. The output can be % optionally cropped and also converted to grayscale. If the output pdf % file already exists then the eps file can optionally be appended as a new % page on the end of the eps file. The level of bitmap compression can also % optionally be set. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % %IN: % source - filename of the source eps file to convert. The filename is % assumed to already have the extension ".eps". % dest - filename of the destination pdf file. The filename is assumed to % already have the extension ".pdf". % crop - boolean indicating whether to crop the borders off the pdf. % Default: true. % append - boolean indicating whether the eps should be appended to the % end of the pdf as a new page (if the pdf exists already). % Default: false. % gray - boolean indicating whether the output pdf should be grayscale or % not. Default: false. % quality - scalar indicating the level of image bitmap quality to % output. A larger value gives a higher quality. quality > 100 % gives lossless output. Default: ghostscript prepress default. % Copyright (C) Oliver Woodford 2009-2011 % Suggestion of appending pdf files provided by Matt C at: % http://www.mathworks.com/matlabcentral/fileexchange/23629 % Thank you to Fabio Viola for pointing out compression artifacts, leading % to the quality setting. % Thank you to Scott for pointing out the subsampling of very small images, % which was fixed for lossless compression settings. % 9/12/2011 Pass font path to ghostscript. function eps2pdf(source, dest, crop, append, gray, quality) % Intialise the options string for ghostscript options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"']; % Set crop option if nargin < 3 || crop options = [options ' -dEPSCrop']; end % Set the font path fp = font_path(); if ~isempty(fp) options = [options ' -sFONTPATH="' fp '"']; end % Set the grayscale option if nargin > 4 && gray options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray']; end % Set the bitmap quality if nargin > 5 && ~isempty(quality) options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false']; if quality > 100 options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"']; else options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode']; v = 1 + (quality < 80); quality = 1 - quality / 100; s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v); options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s); end end % Check if the output file exists if nargin > 3 && append && exist(dest, 'file') == 2 % File exists - append current figure to the end tmp_nam = tempname; % Copy the file copyfile(dest, tmp_nam); % Add the output file names options = [options ' -f "' tmp_nam '" "' source '"']; try % Convert to pdf using ghostscript [status message] = ghostscript(options); catch % Delete the intermediate file delete(tmp_nam); rethrow(lasterror); end % Delete the intermediate file delete(tmp_nam); else % File doesn't exist or should be over-written % Add the output file names options = [options ' -f "' source '"']; % Convert to pdf using ghostscript [status message] = ghostscript(options); end % Check for error if status % Report error if isempty(message) error('Unable to generate pdf. Check destination directory is writable.'); else error(message); end end return % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); return
github
BottjerLab/Acoustic_Similarity-master
copyfig.m
.m
Acoustic_Similarity-master/code/fileExchange/export_fig/copyfig.m
814
utf_8
1844a9d51dbe52ce3927c9eac5ee672e
%COPYFIG Create a copy of a figure, without changing the figure % % Examples: % fh_new = copyfig(fh_old) % % This function will create a copy of a figure, but not change the figure, % as copyobj sometimes does, e.g. by changing legends. % % IN: % fh_old - The handle of the figure to be copied. Default: gcf. % % OUT: % fh_new - The handle of the created figure. % Copyright (C) Oliver Woodford 2012 function fh = copyfig(fh) % Set the default if nargin == 0 fh = gcf; end % Is there a legend? if isempty(findobj(fh, 'Type', 'axes', 'Tag', 'legend')) % Safe to copy using copyobj fh = copyobj(fh, 0); else % copyobj will change the figure, so save and then load it instead tmp_nam = [tempname '.fig']; hgsave(fh, tmp_nam); fh = hgload(tmp_nam); delete(tmp_nam); end return
github
BottjerLab/Acoustic_Similarity-master
user_string.m
.m
Acoustic_Similarity-master/code/fileExchange/export_fig/user_string.m
2,462
utf_8
dd1a7fa5b4f2be6320fc2538737a2f3e
%USER_STRING Get/set a user specific string % % Examples: % string = user_string(string_name) % saved = user_string(string_name, new_string) % % Function to get and set a string in a system or user specific file. This % enables, for example, system specific paths to binaries to be saved. % % IN: % string_name - String containing the name of the string required. The % string is extracted from a file called (string_name).txt, % stored in the same directory as user_string.m. % new_string - The new string to be saved under the name given by % string_name. % % OUT: % string - The currently saved string. Default: ''. % saved - Boolean indicating whether the save was succesful % Copyright (C) Oliver Woodford 2011-2013 % This method of saving paths avoids changing .m files which might be in a % version control system. Instead it saves the user dependent paths in % separate files with a .txt extension, which need not be checked in to % the version control system. Thank you to Jonas Dorn for suggesting this % approach. % 10/01/2013 - Access files in text, not binary mode, as latter can cause % errors. Thanks to Christian for pointing this out. function string = user_string(string_name, string) if ~ischar(string_name) error('string_name must be a string.'); end % Create the full filename string_name = fullfile(fileparts(mfilename('fullpath')), '.ignore', [string_name '.txt']); if nargin > 1 % Set string if ~ischar(string) error('new_string must be a string.'); end % Make sure the save directory exists dname = fileparts(string_name); if ~exist(dname, 'dir') % Create the directory try if ~mkdir(dname) string = false; return end catch string = false; return end % Make it hidden try fileattrib(dname, '+h'); catch end end % Write the file fid = fopen(string_name, 'wt'); if fid == -1 string = false; return end try fprintf(fid, '%s', string); catch fclose(fid); string = false; return end fclose(fid); string = true; else % Get string fid = fopen(string_name, 'rt'); if fid == -1 string = ''; return end string = fgetl(fid); fclose(fid); end return
github
BottjerLab/Acoustic_Similarity-master
export_fig.m
.m
Acoustic_Similarity-master/code/fileExchange/export_fig/export_fig.m
29,671
utf_8
c5d72abc2018b55d22123e68214518e4
%EXPORT_FIG Exports figures suitable for publication % NB: patch objects have to be independently exported - in the future, % write a function that programatically extracts them % Examples: % im = export_fig % [im alpha] = export_fig % export_fig filename % export_fig filename -format1 -format2 % export_fig ... -nocrop % export_fig ... -transparent % export_fig ... -native % export_fig ... -m<val> % export_fig ... -r<val> % export_fig ... -a<val> % export_fig ... -q<val> % export_fig ... -<renderer> % export_fig ... -<colorspace> % export_fig ... -append % export_fig ... -bookmark % export_fig(..., handle) % % This function saves a figure or single axes to one or more vector and/or % bitmap file formats, and/or outputs a rasterized version to the % workspace, with the following properties: % - Figure/axes reproduced as it appears on screen % - Cropped borders (optional) % - Embedded fonts (vector formats) % - Improved line and grid line styles % - Anti-aliased graphics (bitmap formats) % - Render images at native resolution (optional for bitmap formats) % - Transparent background supported (pdf, eps, png) % - Semi-transparent patch objects supported (png only) % - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff) % - Variable image compression, including lossless (pdf, eps, jpg) % - Optionally append to file (pdf, tiff) % - Vector formats: pdf, eps % - Bitmap formats: png, tiff, jpg, bmp, export to workspace % % This function is especially suited to exporting figures for use in % publications and presentations, because of the high quality and % portability of media produced. % % Note that the background color and figure dimensions are reproduced % (the latter approximately, and ignoring cropping & magnification) in the % output file. For transparent background (and semi-transparent patch % objects), use the -transparent option or set the figure 'Color' property % to 'none'. To make axes transparent set the axes 'Color' property to % 'none'. Pdf, eps and png are the only file formats to support a % transparent background, whilst the png format alone supports transparency % of patch objects. % % The choice of renderer (opengl, zbuffer or painters) has a large impact % on the quality of output. Whilst the default value (opengl for bitmaps, % painters for vector formats) generally gives good results, if you aren't % satisfied then try another renderer. Notes: 1) For vector formats (eps, % pdf), only painters generates vector graphics. 2) For bitmaps, only % opengl can render transparent patch objects correctly. 3) For bitmaps, % only painters will correctly scale line dash and dot lengths when % magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when % using painters. % % When exporting to vector format (pdf & eps) and bitmap format using the % painters renderer, this function requires that ghostscript is installed % on your system. You can download this from: % http://www.ghostscript.com % When exporting to eps it additionally requires pdftops, from the Xpdf % suite of functions. You can download this from: % http://www.foolabs.com/xpdf % %IN: % filename - string containing the name (optionally including full or % relative path) of the file the figure is to be saved as. If % a path is not specified, the figure is saved in the current % directory. If no name and no output arguments are specified, % the default name, 'export_fig_out', is used. If neither a % file extension nor a format are specified, a ".png" is added % and the figure saved in that format. % -format1, -format2, etc. - strings containing the extensions of the % file formats the figure is to be saved as. % Valid options are: '-pdf', '-eps', '-png', % '-tif', '-jpg' and '-bmp'. All combinations % of formats are valid. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -transparent - option indicating that the figure background is to be % made transparent (png, pdf and eps output only). % -m<val> - option where val indicates the factor to magnify the % on-screen figure pixel dimensions by when generating bitmap % outputs. Default: '-m1'. % -r<val> - option val indicates the resolution (in pixels per inch) to % export bitmap and vector outputs at, keeping the dimensions % of the on-screen figure. Default: '-r864' (for vector output % only). Note that the -m option overides the -r option for % bitmap outputs only. % -native - option indicating that the output resolution (when outputting % a bitmap format) should be such that the vertical resolution % of the first suitable image found in the figure is at the % native resolution of that image. To specify a particular % image to use, give it the tag 'export_fig_native'. Notes: % This overrides any value set with the -m and -r options. It % also assumes that the image is displayed front-to-parallel % with the screen. The output resolution is approximate and % should not be relied upon. Anti-aliasing can have adverse % effects on image quality (disable with the -a1 option). % -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to % use for bitmap outputs. '-a1' means no anti- % aliasing; '-a4' is the maximum amount (default). % -<renderer> - option to force a particular renderer (painters, opengl % or zbuffer) to be used over the default: opengl for % bitmaps; painters for vector formats. % -<colorspace> - option indicating which colorspace color figures should % be saved in: RGB (default), CMYK or gray. CMYK is only % supported in pdf, eps and tiff output. % -q<val> - option to vary bitmap image quality (in pdf, eps and jpg % files only). Larger val, in the range 0-100, gives higher % quality/lower compression. val > 100 gives lossless % compression. Default: '-q95' for jpg, ghostscript prepress % default for pdf & eps. Note: lossless compression can % sometimes give a smaller file size than the default lossy % compression, depending on the type of images. % -append - option indicating that if the file (pdfs only) already % exists, the figure is to be appended as a new page, instead % of being overwritten (default). % -bookmark - option to indicate that a bookmark with the name of the % figure is to be created in the output file (pdf only). % handle - The handle of the figure, axes or uipanels (can be an array of % handles, but the objects must be in the same figure) to be % saved. Default: gcf. % %OUT: % im - MxNxC uint8 image array of the figure. % alpha - MxN single array of alphamatte values in range [0,1], for the % case when the background is transparent. % % Some helpful examples and tips can be found at: % http://sites.google.com/site/oliverwoodford/software/export_fig % % See also PRINT, SAVEAS. % Copyright (C) Oliver Woodford 2008-2012 % The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG % (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782). % The idea for using pdftops came from the MATLAB newsgroup (id: 168171). % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928). % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id: % 20979). % The idea of appending figures in pdfs came from Matt C in comments on the % FEX (id: 23629) % Thanks to Roland Martin for pointing out the colour MATLAB % bug/feature with colorbar axes and transparent backgrounds. % Thanks also to Andrew Matthews for describing a bug to do with the figure % size changing in -nodisplay mode. I couldn't reproduce it, but included a % fix anyway. % Thanks to Tammy Threadgill for reporting a bug where an axes is not % isolated from gui objects. % 23/02/12: Ensure that axes limits don't change during printing % 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for % reporting it). % 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling % bookmarking of figures in pdf files. % 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep % tick marks fixed. % 12/12/12: Add support for isolating uipanels. Thanks to michael for % suggesting it. % 25/09/13: Add support for changing resolution in vector formats. Thanks % to Jan Jaap Meijer for suggesting it. function [im, alpha] = export_fig(varargin) % Make sure the figure is rendered correctly _now_ so that properties like % axes limits are up-to-date. drawnow; % Parse the input arguments [fig, options] = parse_args(nargout, varargin{:}); % Isolate the subplot, if it is one cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'})); if cls % Given handles of one or more axes, so isolate them from the rest fig = isolate_axes(fig); else % Check we have a figure if ~isequal(get(fig, 'Type'), 'figure'); error('Handle must be that of a figure, axes or uipanel'); end % Get the old InvertHardcopy mode old_mode = get(fig, 'InvertHardcopy'); end % Hack the font units where necessary (due to a font rendering bug in % print?). This may not work perfectly in all cases. Also it can change the % figure layout if reverted, so use a copy. magnify = options.magnify * options.aa_factor; if isbitmap(options) && magnify ~= 1 fontu = findobj(fig, 'FontUnits', 'normalized'); if ~isempty(fontu) % Some normalized font units found if ~cls fig = copyfig(fig); set(fig, 'Visible', 'off'); fontu = findobj(fig, 'FontUnits', 'normalized'); cls = true; end set(fontu, 'FontUnits', 'points'); end end % MATLAB "feature": axes limits and tick marks can change when printing Hlims = findall(fig, 'Type', 'axes'); if ~cls % Record the old axes limit and tick modes Xlims = make_cell(get(Hlims, 'XLimMode')); Ylims = make_cell(get(Hlims, 'YLimMode')); Zlims = make_cell(get(Hlims, 'ZLimMode')); Xtick = make_cell(get(Hlims, 'XTickMode')); Ytick = make_cell(get(Hlims, 'YTickMode')); Ztick = make_cell(get(Hlims, 'ZTickMode')); end % Set all axes limit and tick modes to manual, so the limits and ticks can't change set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual'); % Set to print exactly what is there set(fig, 'InvertHardcopy', 'off'); % Set the renderer switch options.renderer case 1 renderer = '-opengl'; case 2 renderer = '-zbuffer'; case 3 renderer = '-painters'; otherwise renderer = '-opengl'; % Default for bitmaps end % Do the bitmap formats first if isbitmap(options) % Get the background colour if options.transparent && (options.png || options.alpha) % Get out an alpha channel % MATLAB "feature": black colorbar axes can change to white and vice versa! hCB = findobj(fig, 'Type', 'axes', 'Tag', 'Colorbar'); if isempty(hCB) yCol = []; xCol = []; else yCol = get(hCB, 'YColor'); xCol = get(hCB, 'XColor'); if iscell(yCol) yCol = cell2mat(yCol); xCol = cell2mat(xCol); end yCol = sum(yCol, 2); xCol = sum(xCol, 2); end % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); % Set the background colour to black, and set size in case it was % changed internally tcol = get(fig, 'Color'); set(fig, 'Color', 'k', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==0), 'YColor', [0 0 0]); set(hCB(xCol==0), 'XColor', [0 0 0]); % Print large version to array B = print2array(fig, magnify, renderer); % Downscale the image B = downsize(single(B), options.aa_factor); % Set background to white (and set size) set(fig, 'Color', 'w', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==3), 'YColor', [1 1 1]); set(hCB(xCol==3), 'XColor', [1 1 1]); % Print large version to array A = print2array(fig, magnify, renderer); % Downscale the image A = downsize(single(A), options.aa_factor); % Set the background colour (and size) back to normal set(fig, 'Color', tcol, 'Position', pos); % Compute the alpha map alpha = round(sum(B - A, 3)) / (255 * 3) + 1; A = alpha; A(A==0) = 1; A = B ./ A(:,:,[1 1 1]); clear B % Convert to greyscale if options.colourspace == 2 A = rgb2grey(A); end A = uint8(A); % Crop the background if options.crop [alpha, v] = crop_background(alpha, 0); A = A(v(1):v(2),v(3):v(4),:); end if options.png % Compute the resolution res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; % Save the png imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); % Clear the png bit options.png = false; end % Return only one channel for greyscale if isbitmap(options) A = check_greyscale(A); end if options.alpha % Store the image im = A; % Clear the alpha bit options.alpha = false; end % Get the non-alpha image if isbitmap(options) alph = alpha(:,:,ones(1, size(A, 3))); A = uint8(single(A) .* alph + 255 * (1 - alph)); clear alph end if options.im % Store the new image im = A; end else % Print large version to array if options.transparent % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); tcol = get(fig, 'Color'); set(fig, 'Color', 'w', 'Position', pos); A = print2array(fig, magnify, renderer); set(fig, 'Color', tcol, 'Position', pos); tcol = 255; else [A, tcol] = print2array(fig, magnify, renderer); end % Crop the background if options.crop A = crop_background(A, tcol); end % Downscale the image A = downsize(A, options.aa_factor); if options.colourspace == 2 % Convert to greyscale A = rgb2grey(A); else % Return only one channel for greyscale A = check_greyscale(A); end % Outputs if options.im im = A; end if options.alpha im = A; alpha = zeros(size(A, 1), size(A, 2), 'single'); end end % Save the images if options.png res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); end if options.bmp imwrite(A, [options.name '.bmp']); end % Save jpeg with given quality if options.jpg quality = options.quality; if isempty(quality) quality = 95; end if quality > 100 imwrite(A, [options.name '.jpg'], 'Mode', 'lossless'); else imwrite(A, [options.name '.jpg'], 'Quality', quality); end end % Save tif images in cmyk if wanted (and possible) if options.tif if options.colourspace == 1 && size(A, 3) == 3 A = double(255 - A); K = min(A, [], 3); K_ = 255 ./ max(255 - K, 1); C = (A(:,:,1) - K) .* K_; M = (A(:,:,2) - K) .* K_; Y = (A(:,:,3) - K) .* K_; A = uint8(cat(3, C, M, Y, K)); clear C M Y K K_ end append_mode = {'overwrite', 'append'}; imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1}); end end % Now do the vector formats if isvector(options) % Set the default renderer to painters if ~options.renderer renderer = '-painters'; end % Generate some filenames tmp_nam = [tempname '.eps']; if options.pdf pdf_nam = [options.name '.pdf']; else pdf_nam = [tempname '.pdf']; end % Generate the options for print p2eArgs = {renderer, sprintf('-r%d', options.resolution)}; if options.colourspace == 1 p2eArgs = [p2eArgs {'-cmyk'}]; end if ~options.crop p2eArgs = [p2eArgs {'-loose'}]; end try % Generate an eps print2eps(tmp_nam, fig, p2eArgs{:}); % Remove the background, if desired if options.transparent && ~isequal(get(fig, 'Color'), 'none') eps_remove_background(tmp_nam); end % Add a bookmark to the PDF if desired if options.bookmark fig_nam = get(fig, 'Name'); if isempty(fig_nam) warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.'); end add_bookmark(tmp_nam, fig_nam); end % Generate a pdf eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality); catch ex % Delete the eps delete(tmp_nam); rethrow(ex); end % Delete the eps delete(tmp_nam); if options.eps try % Generate an eps from the pdf pdf2eps(pdf_nam, [options.name '.eps']); catch ex if ~options.pdf % Delete the pdf delete(pdf_nam); end rethrow(ex); end if ~options.pdf % Delete the pdf delete(pdf_nam); end end end if cls % Close the created figure close(fig); else % Reset the hardcopy mode set(fig, 'InvertHardcopy', old_mode); % Reset the axes limit and tick modes for a = 1:numel(Hlims) set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a}); end end return function [fig, options] = parse_args(nout, varargin) % Parse the input arguments % Set the defaults fig = get(0, 'CurrentFigure'); options = struct('name', 'export_fig_out', ... 'crop', true, ... 'transparent', false, ... 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters 'pdf', false, ... 'eps', false, ... 'png', false, ... 'tif', false, ... 'jpg', false, ... 'bmp', false, ... 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray 'append', false, ... 'im', nout == 1, ... 'alpha', nout == 2, ... 'aa_factor', 3, ... 'magnify', [], ... 'resolution', [], ... 'bookmark', false, ... 'quality', []); native = false; % Set resolution to native of an image % Go through the other arguments for a = 1:nargin-1 if all(ishandle(varargin{a})) fig = varargin{a}; elseif ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' switch lower(varargin{a}(2:end)) case 'nocrop' options.crop = false; case {'trans', 'transparent'} options.transparent = true; case 'opengl' options.renderer = 1; case 'zbuffer' options.renderer = 2; case 'painters' options.renderer = 3; case 'pdf' options.pdf = true; case 'eps' options.eps = true; case 'png' options.png = true; case {'tif', 'tiff'} options.tif = true; case {'jpg', 'jpeg'} options.jpg = true; case 'bmp' options.bmp = true; case 'rgb' options.colourspace = 0; case 'cmyk' options.colourspace = 1; case {'gray', 'grey'} options.colourspace = 2; case {'a1', 'a2', 'a3', 'a4'} options.aa_factor = str2double(varargin{a}(3)); case 'append' options.append = true; case 'bookmark' options.bookmark = true; case 'native' native = true; otherwise val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q))(\d*\.)?\d+(e-?\d+)?', 'match')); if ~isscalar(val) error('option %s not recognised', varargin{a}); end switch lower(varargin{a}(2)) case 'm' options.magnify = val; case 'r' options.resolution = val; case 'q' options.quality = max(val, 0); end end else [p, options.name, ext] = fileparts(varargin{a}); if ~isempty(p) options.name = [p filesep options.name]; end switch lower(ext) case {'.tif', '.tiff'} options.tif = true; case {'.jpg', '.jpeg'} options.jpg = true; case '.png' options.png = true; case '.bmp' options.bmp = true; case '.eps' options.eps = true; case '.pdf' options.pdf = true; otherwise options.name = varargin{a}; end end end end % Compute the magnification and resolution if isempty(options.magnify) if isempty(options.resolution) options.magnify = 1; options.resolution = 864; else options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch'); end elseif isempty(options.resolution) options.resolution = 864; end % Check we have a figure handle if isempty(fig) error('No figure found'); end % Set the default format if ~isvector(options) && ~isbitmap(options) options.png = true; end % Check whether transparent background is wanted (old way) if isequal(get(ancestor(fig, 'figure'), 'Color'), 'none') options.transparent = true; end % If requested, set the resolution to the native vertical resolution of the % first suitable image found if native && isbitmap(options) % Find a suitable image list = findobj(fig, 'Type', 'image', 'Tag', 'export_fig_native'); if isempty(list) list = findobj(fig, 'Type', 'image', 'Visible', 'on'); end for hIm = list(:)' % Check height is >= 2 height = size(get(hIm, 'CData'), 1); if height < 2 continue end % Account for the image filling only part of the axes, or vice % versa yl = get(hIm, 'YData'); if isscalar(yl) yl = [yl(1)-0.5 yl(1)+height+0.5]; else if ~diff(yl) continue end yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1)); end hAx = get(hIm, 'Parent'); yl2 = get(hAx, 'YLim'); % Find the pixel height of the axes oldUnits = get(hAx, 'Units'); set(hAx, 'Units', 'pixels'); pos = get(hAx, 'Position'); set(hAx, 'Units', oldUnits); if ~pos(4) continue end % Found a suitable image % Account for stretch-to-fill being disabled pbar = get(hAx, 'PlotBoxAspectRatio'); pos = min(pos(4), pbar(2)*pos(3)/pbar(1)); % Set the magnification to give native resolution options.magnify = (height * diff(yl2)) / (pos * diff(yl)); break end end return function A = downsize(A, factor) % Downsample an image if factor == 1 % Nothing to do return end try % Faster, but requires image processing toolbox A = imresize(A, 1/factor, 'bilinear'); catch % No image processing toolbox - resize manually % Lowpass filter - use Gaussian as is separable, so faster % Compute the 1d Gaussian filter filt = (-factor-1:factor+1) / (factor * 0.6); filt = exp(-filt .* filt); % Normalize the filter filt = single(filt / sum(filt)); % Filter the image padding = floor(numel(filt) / 2); for a = 1:size(A, 3) A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid'); end % Subsample A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:); end return function A = rgb2grey(A) A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); return function A = check_greyscale(A) % Check if the image is greyscale if size(A, 3) == 3 && ... all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ... all(reshape(A(:,:,2) == A(:,:,3), [], 1)) A = A(:,:,1); % Save only one channel for 8-bit output end return function [A, v] = crop_background(A, bcol) % Map the foreground pixels [h, w, c] = size(A); if isscalar(bcol) && c > 1 bcol = bcol(ones(1, c)); end bail = false; for l = 1:w for a = 1:c if ~all(A(:,l,a) == bcol(a)) bail = true; break; end end if bail break; end end bail = false; for r = w:-1:l for a = 1:c if ~all(A(:,r,a) == bcol(a)) bail = true; break; end end if bail break; end end bail = false; for t = 1:h for a = 1:c if ~all(A(t,:,a) == bcol(a)) bail = true; break; end end if bail break; end end bail = false; for b = h:-1:t for a = 1:c if ~all(A(b,:,a) == bcol(a)) bail = true; break; end end if bail break; end end % Crop the background, leaving one boundary pixel to avoid bleeding on % resize v = [max(t-1, 1) min(b+1, h) max(l-1, 1) min(r+1, w)]; A = A(v(1):v(2),v(3):v(4),:); return function eps_remove_background(fname) % Remove the background of an eps file % Open the file fh = fopen(fname, 'r+'); if fh == -1 error('Not able to open file %s.', fname); end % Read the file line by line while true % Get the next line l = fgets(fh); if isequal(l, -1) break; % Quit, no rectangle found end % Check if the line contains the background rectangle if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +rf *[\n\r]+', 'start'), 1) % Set the line to whitespace and quit l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' '; fseek(fh, -numel(l), 0); fprintf(fh, l); break; end end % Close the file fclose(fh); return function b = isvector(options) b = options.pdf || options.eps; return function b = isbitmap(options) b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha; return % Helper function function A = make_cell(A) if ~iscell(A) A = {A}; end return function add_bookmark(fname, bookmark_text) % Adds a bookmark to the temporary EPS file after %%EndPageSetup % Read in the file fh = fopen(fname, 'r'); if fh == -1 error('File %s not found.', fname); end try fstrm = fread(fh, '*char')'; catch ex fclose(fh); rethrow(ex); end fclose(fh); % Include standard pdfmark prolog to maximize compatibility fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse')); % Add page bookmark fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text)); % Write out the updated file fh = fopen(fname, 'w'); if fh == -1 error('Unable to open %s for writing.', fname); end try fwrite(fh, fstrm, 'char*1'); catch ex fclose(fh); rethrow(ex); end fclose(fh); return
github
BottjerLab/Acoustic_Similarity-master
ghostscript.m
.m
Acoustic_Similarity-master/code/fileExchange/export_fig/ghostscript.m
4,505
utf_8
18a672bb6982a1fbc6b21b3ab52b0fc9
%GHOSTSCRIPT Calls a local GhostScript executable with the input command % % Example: % [status result] = ghostscript(cmd) % % Attempts to locate a ghostscript executable, finally asking the user to % specify the directory ghostcript was installed into. The resulting path % is stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have Ghostscript installed on your % system. You can download this from: http://www.ghostscript.com % % IN: % cmd - Command string to be passed into ghostscript. % % OUT: % status - 0 iff command ran without problem. % result - Output from ghostscript. % Copyright: Oliver Woodford, 2009-2013 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Nathan Childress for the fix to the default location on 64-bit % Windows systems. % 27/4/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and % Shaun Kline for pointing out the issue % 4/5/11 - Thanks to David Chorlian for pointing out an alternative % location for gs on linux. % 12/12/12 - Add extra executable name on Windows. Thanks to Ratish % Punnoose for highlighting the issue. % 28/6/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick % Steinbring for proposing the fix. function varargout = ghostscript(cmd) % Initialize any required system calls before calling ghostscript shell_cmd = ''; if isunix shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07 end % Call ghostscript [varargout{1:nargout}] = system(sprintf('%s"%s" %s', shell_cmd, gs_path, cmd)); return function path_ = gs_path % Return a valid path % Start with the currently set path path_ = user_string('ghostscript'); % Check the path works if check_gs_path(path_) return end % Check whether the binary is on the path if ispc bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'}; else bin = {'gs'}; end for a = 1:numel(bin) path_ = bin{a}; if check_store_gs_path(path_) return end end % Search the obvious places if ispc default_location = 'C:\Program Files\gs\'; dir_list = dir(default_location); if isempty(dir_list) default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems dir_list = dir(default_location); end executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'}; ver_num = 0; % If there are multiple versions, use the newest for a = 1:numel(dir_list) ver_num2 = sscanf(dir_list(a).name, 'gs%g'); if ~isempty(ver_num2) && ver_num2 > ver_num for b = 1:numel(executable) path2 = [default_location dir_list(a).name executable{b}]; if exist(path2, 'file') == 2 path_ = path2; ver_num = ver_num2; end end end end if check_store_gs_path(path_) return end else bin = {'/usr/bin/gs', '/usr/local/bin/gs'}; for a = 1:numel(bin) path_ = bin{a}; if check_store_gs_path(path_) return end end end % Ask the user to enter the path while 1 if strncmp(computer, 'MAC', 3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Ghostscript not found. Please locate the program.')) end base = uigetdir('/', 'Ghostcript not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) for b = 1:numel(bin) path_ = [base bin_dir{a} bin{b}]; if exist(path_, 'file') == 2 if check_store_gs_path(path_) return end end end end end error('Ghostscript not found. Have you installed it from www.ghostscript.com?'); function good = check_store_gs_path(path_) % Check the path is valid good = check_gs_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('ghostscript', path_) warning('Path to ghostscript installation could not be saved. Enter it manually in ghostscript.txt.'); return end return function good = check_gs_path(path_) % Check the path is valid [good, message] = system(sprintf('"%s" -h', path_)); good = good == 0; return
github
BottjerLab/Acoustic_Similarity-master
freezeColors.m
.m
Acoustic_Similarity-master/code/fileExchange/freezeColors/freezeColors.m
9,815
utf_8
2068d7a4f7a74d251e2519c4c5c1c171
function freezeColors(varargin) % freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3) % % Problem: There is only one colormap per figure. This function provides % an easy solution when plots using different colomaps are desired % in the same figure. % % freezeColors freezes the colors of graphics objects in the current axis so % that subsequent changes to the colormap (or caxis) will not change the % colors of these objects. freezeColors works on any graphics object % with CData in indexed-color mode: surfaces, images, scattergroups, % bargroups, patches, etc. It works by converting CData to true-color rgb % based on the colormap active at the time freezeColors is called. % % The original indexed color data is saved, and can be restored using % unfreezeColors, making the plot once again subject to the colormap and % caxis. % % % Usage: % freezeColors applies to all objects in current axis (gca), % freezeColors(axh) same, but works on axis axh. % % Example: % subplot(2,1,1); imagesc(X); colormap hot; freezeColors % subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc... % % Note: colorbars must also be frozen. Due to Matlab 'improvements' this can % no longer be done with freezeColors. Instead, please % use the function CBFREEZE by Carlos Adrian Vargas Aguilera % that can be downloaded from the MATLAB File Exchange % (http://www.mathworks.com/matlabcentral/fileexchange/24371) % % h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar) % % For additional examples, see test/test_main.m % % Side effect on render mode: freezeColors does not work with the painters % renderer, because Matlab doesn't support rgb color data in % painters mode. If the current renderer is painters, freezeColors % changes it to zbuffer. This may have unexpected effects on other aspects % of your plots. % % See also unfreezeColors, freezeColors_pub.html, cbfreeze. % % % John Iversen ([email protected]) 3/23/05 % % Changes: % JRI ([email protected]) 4/19/06 Correctly handles scaled integer cdata % JRI 9/1/06 should now handle all objects with cdata: images, surfaces, % scatterplots. (v 2.1) % JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded) % JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3) % JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it. % JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf) % JRI 4/7/10 Change documentation for colorbars % Hidden option for NaN colors: % Missing data are often represented by NaN in the indexed color % data, which renders transparently. This transparency will be preserved % when freezing colors. If instead you wish such gaps to be filled with % a real color, add 'nancolor',[r g b] to the end of the arguments. E.g. % freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]), % where [r g b] is a color vector. This works on images & pcolor, but not on % surfaces. % Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes % attributed in the code. % Free for all uses, but please retain the following: % Original Author: % John Iversen, 2005-10 % [email protected] appdatacode = 'JRI__freezeColorsData'; [h, nancolor] = checkArgs(varargin); %gather all children with scaled or indexed CData cdatah = getCDataHandles(h); %current colormap cmap = colormap; nColors = size(cmap,1); cax = caxis; % convert object color indexes into colormap to true-color data using % current colormap for hh = cdatah', g = get(hh); %preserve parent axis clim parentAx = getParentAxes(hh); originalClim = get(parentAx, 'clim'); % Note: Special handling of patches: For some reason, setting % cdata on patches created by bar() yields an error, % so instead we'll set facevertexcdata instead for patches. if ~strcmp(g.Type,'patch'), cdata = g.CData; else cdata = g.FaceVertexCData; end %get cdata mapping (most objects (except scattergroup) have it) if isfield(g,'CDataMapping'), scalemode = g.CDataMapping; else scalemode = 'scaled'; end %save original indexed data for use with unfreezeColors siz = size(cdata); setappdata(hh, appdatacode, {cdata scalemode}); %convert cdata to indexes into colormap if strcmp(scalemode,'scaled'), %4/19/06 JRI, Accommodate scaled display of integer cdata: % in MATLAB, uint * double = uint, so must coerce cdata to double % Thanks to O Yamashita for pointing this need out idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors); else %direct mapping idx = cdata; %10/8/09 in case direct data is non-int (e.g. image;freezeColors) % (Floor mimics how matlab converts data into colormap index.) % Thanks to D Armyr for the catch idx = floor(idx); end %clamp to [1, nColors] idx(idx<1) = 1; idx(idx>nColors) = nColors; %handle nans in idx nanmask = isnan(idx); idx(nanmask)=1; %temporarily replace w/ a valid colormap index %make true-color data--using current colormap realcolor = zeros(siz); for i = 1:3, c = cmap(idx,i); c = reshape(c,siz); c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified) realcolor(:,:,i) = c; end %apply new true-color color data %true-color is not supported in painters renderer, so switch out of that if strcmp(get(gcf,'renderer'), 'painters'), set(gcf,'renderer','zbuffer'); end %replace original CData with true-color data if ~strcmp(g.Type,'patch'), set(hh,'CData',realcolor); else set(hh,'faceVertexCData',permute(realcolor,[1 3 2])) end %restore clim (so colorbar will show correct limits) if ~isempty(parentAx), set(parentAx,'clim',originalClim) end end %loop on indexed-color objects % ============================================================================ % % Local functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% getCDataHandles -- get handles of all descendents with indexed CData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hout = getCDataHandles(h) % getCDataHandles Find all objects with indexed CData %recursively descend object tree, finding objects with indexed CData % An exception: don't include children of objects that themselves have CData: % for example, scattergroups are non-standard hggroups, with CData. Changing % such a group's CData automatically changes the CData of its children, % (as well as the children's handles), so there's no need to act on them. error(nargchk(1,1,nargin,'struct')) hout = []; if isempty(h),return;end ch = get(h,'children'); for hh = ch' g = get(hh); if isfield(g,'CData'), %does object have CData? %is it indexed/scaled? if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1, hout = [hout; hh]; %#ok<AGROW> %yes, add to list end else %no CData, see if object has any interesting children hout = [hout; getCDataHandles(hh)]; %#ok<AGROW> end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% getParentAxes -- return handle of axes object to which a given object belongs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hAx = getParentAxes(h) % getParentAxes Return enclosing axes of a given object (could be self) error(nargchk(1,1,nargin,'struct')) %object itself may be an axis if strcmp(get(h,'type'),'axes'), hAx = h; return end parent = get(h,'parent'); if (strcmp(get(parent,'type'), 'axes')), hAx = parent; else hAx = getParentAxes(parent); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% checkArgs -- Validate input arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [h, nancolor] = checkArgs(args) % checkArgs Validate input arguments to freezeColors nargs = length(args); error(nargchk(0,3,nargs,'struct')) %grab handle from first argument if we have an odd number of arguments if mod(nargs,2), h = args{1}; if ~ishandle(h), error('JRI:freezeColors:checkArgs:invalidHandle',... 'The first argument must be a valid graphics handle (to an axis)') end % 4/2010 check if object to be frozen is a colorbar if strcmp(get(h,'Tag'),'Colorbar'), if ~exist('cbfreeze.m'), warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',... ['You seem to be attempting to freeze a colorbar. This no longer'... 'works. Please read the help for freezeColors for the solution.']) else cbfreeze(h); return end end args{1} = []; nargs = nargs-1; else h = gca; end %set nancolor if that option was specified nancolor = [nan nan nan]; if nargs == 2, if strcmpi(args{end-1},'nancolor'), nancolor = args{end}; if ~all(size(nancolor)==[1 3]), error('JRI:freezeColors:checkArgs:badColorArgument',... 'nancolor must be [r g b] vector'); end nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0; else error('JRI:freezeColors:checkArgs:unrecognizedOption',... 'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1}) end end
github
BottjerLab/Acoustic_Similarity-master
ModestAdaBoost.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/ModestAdaBoost.m
3,156
utf_8
c030e77a7bae187a1e6fd5ec623874eb
% The algorithms developed and implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % ModestAdaBoost Implements boosting process based on "Modest AdaBoost" % algorithm %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % [Learners, Weights, final_hyp] = ModestAdaBoost(WeakLrn, Data, Labels, % Max_Iter, OldW, OldLrn, final_hyp) % --------------------------------------------------------------------------------- % Arguments: % WeakLrn - weak learner % Data - training data. Should be DxN matrix, where D is the % dimensionality of data, and N is the number of % training samples. % Labels - training labels. Should be 1xN matrix, where N is % the number of training samples. % Max_Iter - number of iterations % OldW - weights of already built commitee (used for training % of already built commitee) % OldLrn - learnenrs of already built commitee (used for training % of already built commitee) % final_hyp - output for training data of already built commitee % (used to speed up training of already built commitee) % Return: % Learners - cell array of constructed learners % Weights - weights of learners % final_hyp - output for training data function [Learners, Weights, final_hyp] = ModestAdaBoost(WeakLrn, Data, Labels, Max_Iter, OldW, OldLrn, final_hyp) global ME_min; if( nargin < 7) alpha = 1; end if( nargin == 4) Learners = {}; Weights = []; distr = ones(1, size(Data,2)) / size(Data,2); final_hyp = zeros(1, size(Data,2)); elseif( nargin > 5) Learners = OldLrn; Weights = OldW; if(nargin < 7) final_hyp = Classify(Learners, Weights, Data); end distr = exp(- (Labels .* final_hyp)); distr = distr / sum(distr); else error('Fuck'); end L = length(Learners); for It = 1 : Max_Iter %chose best learner nodes = train(WeakLrn, Data, Labels, distr); % calc error rev_distr = ((1 ./ distr)) / sum ((1 ./ distr)); for i = 1:length(nodes) curr_tr = nodes{i}; step_out = calc_output(curr_tr, Data); s1 = sum( (Labels == 1) .* (step_out) .* distr); s2 = sum( (Labels == -1) .* (step_out) .* distr); s1_rev = sum( (Labels == 1) .* (step_out) .* rev_distr); s2_rev = sum( (Labels == -1) .* (step_out) .* rev_distr); Alpha = s1 * (1 - s1_rev) - s2 * (1 - s2_rev); if(sign(Alpha) ~= sign(s1 - s2) || (s1 + s2) == 0) continue; end Weights(end+1) = Alpha; Learners{end+1} = curr_tr; final_hyp = final_hyp + step_out .* Alpha; end distr = exp(- 1 * (Labels .* final_hyp)); Z = sum(distr); distr = distr / Z; end
github
BottjerLab/Acoustic_Similarity-master
RealAdaBoost.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/RealAdaBoost.m
2,840
utf_8
2666cf47840c3fe72ded547d5b355335
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % RealAdaBoost Implements boosting process based on "Real AdaBoost" % algorithm %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % [Learners, Weights, final_hyp] = RealAdaBoost(WeakLrn, Data, Labels, % Max_Iter, OldW, OldLrn, final_hyp) % --------------------------------------------------------------------------------- % Arguments: % WeakLrn - weak learner % Data - training data. Should be DxN matrix, where D is the % dimensionality of data, and N is the number of % training samples. % Labels - training labels. Should be 1xN matrix, where N is % the number of training samples. % Max_Iter - number of iterations % OldW - weights of already built commitee (used for training % of already built commitee) % OldLrn - learnenrs of already built commitee (used for training % of already built commitee) % final_hyp - output for training data of already built commitee % (used to speed up training of already built commitee) % Return: % Learners - cell array of constructed learners % Weights - weights of learners % final_hyp - output for training data function [Learners, Weights, final_hyp] = RealAdaBoost(WeakLrn, Data, Labels, Max_Iter, OldW, OldLrn, final_hyp) if( nargin == 4) Learners = {}; Weights = []; distr = ones(1, size(Data,2)) / size(Data,2); final_hyp = zeros(1, size(Data,2)); elseif( nargin > 5) Learners = OldLrn; Weights = OldW; if(nargin < 7) final_hyp = Classify(Learners, Weights, Data); end distr = exp(- (Labels .* final_hyp)); distr = distr / sum(distr); else error('Function takes eather 4 or 6 arguments'); end for It = 1 : Max_Iter %chose best learner nodes = train(WeakLrn, Data, Labels, distr); for i = 1:length(nodes) curr_tr = nodes{i}; step_out = calc_output(curr_tr, Data); s1 = sum( (Labels == 1) .* (step_out) .* distr); s2 = sum( (Labels == -1) .* (step_out) .* distr); if(s1 == 0 && s2 == 0) continue; end Alpha = 0.5*log((s1 + eps) / (s2+eps)); Weights(end+1) = Alpha; Learners{end+1} = curr_tr; final_hyp = final_hyp + step_out .* Alpha; end distr = exp(- 1 * (Labels .* final_hyp)); Z = sum(distr); distr = distr / Z; end
github
BottjerLab/Acoustic_Similarity-master
GentleAdaBoost.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/GentleAdaBoost.m
2,913
utf_8
f5ca8646cb65ff5571b95135827f14b3
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % GentleAdaBoost Implements boosting process based on "Gentle AdaBoost" % algorithm %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % [Learners, Weights, final_hyp] = GentleAdaBoost(WeakLrn, Data, Labels, % Max_Iter, OldW, OldLrn, final_hyp) % --------------------------------------------------------------------------------- % Arguments: % WeakLrn - weak learner % Data - training data. Should be DxN matrix, where D is the % dimensionality of data, and N is the number of % training samples. % Labels - training labels. Should be 1xN matrix, where N is % the number of training samples. % Max_Iter - number of iterations % OldW - weights of already built commitee (used for training % of already built commitee) % OldLrn - learnenrs of already built commitee (used for training % of already built commitee) % final_hyp - output for training data of already built commitee % (used to speed up training of already built commitee) % Return: % Learners - cell array of constructed learners % Weights - weights of learners % final_hyp - output for training data function [Learners, Weights, final_hyp] = GentleAdaBoost(WeakLrn, Data, Labels, Max_Iter, OldW, OldLrn, final_hyp) global GE_min; if( nargin == 4) Learners = {}; Weights = []; distr = ones(1, size(Data,2)) / size(Data,2); final_hyp = zeros(1, size(Data,2)); elseif( nargin > 5) Learners = OldLrn; Weights = OldW; if(nargin < 7) final_hyp = Classify(Learners, Weights, Data); end distr = exp(- (Labels .* final_hyp)); distr = distr / sum(distr); else error('Function takes eather 4 or 6 arguments'); end for It = 1 : Max_Iter fprintf('.'); if mod(It,50) == 0, fprintf('\n'),end; %chose best learner nodes = train(WeakLrn, Data, Labels, distr); for i = 1:length(nodes) curr_tr = nodes{i}; step_out = calc_output(curr_tr, Data); s1 = sum( (Labels == 1) .* (step_out) .* distr); s2 = sum( (Labels == -1) .* (step_out) .* distr); if(s1 == 0 && s2 == 0) continue; end Alpha = (s1 - s2) / (s1 + s2); Weights(end+1) = Alpha; Learners{end+1} = curr_tr; final_hyp = final_hyp + step_out .* Alpha; end distr = exp(- 1 * (Labels .* final_hyp)); Z = sum(distr); distr = distr / Z; end
github
BottjerLab/Acoustic_Similarity-master
Classify.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/Classify.m
1,238
utf_8
ceb50fd41859da083c242df1896f71d9
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % Classify Implements classification data samples by already built % boosted commitee %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % Result = Classify(Learners, Weights, Data) % --------------------------------------------------------------------------------- % Arguments: % Learners - cell array of weak learners % Weights - vector of learners weights % Data - Data to be classified. Should be DxN matrix, % where D is the dimensionality of data, and N % is the number of data samples. % Return: % Result - vector of real valued commitee outputs for Data. function Result = Classify(Learners, Weights, Data) Result = zeros(1, size(Data, 2)); for i = 1 : length(Weights) lrn_out = calc_output(Learners{i}, Data); Result = Result + lrn_out * Weights(i); end
github
BottjerLab/Acoustic_Similarity-master
TranslateToC.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/TranslateToC.m
1,339
utf_8
92e85b9a48079bf98fdb8f3d00a7fecf
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % TranslateToC Implements procedure of saving trained classifier to file, % that can be further used in C++ programm %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % code = TranslateToC (Learners, Weights, fid) % --------------------------------------------------------------------------------- % Arguments: % Learners - learners of commitee % Weights - weights of commitee % fid - opened file id (use fopen to make one) % Return: % code - equals 1 if everything was alright function code = TranslateToC (Learners, Weights, fid) Weights = Weights ./ (sum(abs(Weights))); fprintf(fid, ' %d\r\n ', length(Weights)); for i = 1 : length(Weights) Curr_Result = get_dim_and_tr(Learners{i}); fprintf(fid, ' %f ', Weights(i)); fprintf(fid, ' %d ', length(Curr_Result) / 3); for j = 1 : length(Curr_Result) fprintf(fid, ' %f ', Curr_Result(j)); end fprintf(fid, '\r\n'); end code = 1;
github
BottjerLab/Acoustic_Similarity-master
get_threshold_and_dim.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@stump_w/get_threshold_and_dim.m
427
utf_8
786dd5f266e245d713c0e55ea0fd3878
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. function [thr, dim] = get_threshold_and_dim(stump) thr = stump.threshold; dim = stump.t_dim;
github
BottjerLab/Acoustic_Similarity-master
stump_w.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@stump_w/stump_w.m
512
utf_8
12cee278ab5b85d39a91ec8a6e578e65
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. function stump = stump_w stump.threshold = 0; stump.signum = 1; stump.t_dim = 1; stump=class(stump, 'stump_w') ; %tr=class(tr, 'threshold_w', learner(idim, odim), learner_w) ;
github
BottjerLab/Acoustic_Similarity-master
calc_output.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@stump_w/calc_output.m
500
utf_8
1f8a7dbbe5dca5881c29affef02ecdd9
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. function y = calc_output(stump, XData) y = (XData(stump.t_dim, :) <= stump.threshold) * (stump.signum) + (XData(stump.t_dim, :) > stump.threshold) * (-stump.signum);
github
BottjerLab/Acoustic_Similarity-master
do_learn_nu.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@stump_w/do_learn_nu.m
2,648
utf_8
a07989e9cb721ab7c2cad9e2629dac17
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. function stump = do_learn_nu(stump, dataset, labels, weights) %dataset=data_w(dataset) ; %stump = set_distr(stump, get_sampl_weights(dataset)) ; Distr = weights; %[trainpat, traintarg] = get_train( dataset); trainpat = dataset; traintarg = labels; tr_size = size(trainpat, 2); T_MIN = zeros(3,size(trainpat,1)); for d = 1 : size(trainpat,1); [DS, IX] = sort(trainpat(d,:)); TS = traintarg(IX); DiS = Distr(IX); lDS = length(DS); vPos = 0 * TS; vNeg = vPos; i = 1; j = 1; while i <= lDS k = 0; while i + k <= lDS && DS(i) == DS(i+k) if(TS(i+k) > 0) vPos(j) = vPos(j) + DiS(i+k); else vNeg(j) = vNeg(j) + DiS(i+k); end k = k + 1; end i = i + k; j = j + 1; end vNeg = vNeg(1:j-1); vPos = vPos(1:j-1); Error = zeros(1, j - 1); InvError = Error; IPos = vPos; INeg = vNeg; for i = 2 : length(IPos) IPos(i) = IPos(i-1) + vPos(i); INeg(i) = INeg(i-1) + vNeg(i); end Ntot = INeg(end); Ptot = IPos(end); for i = 1 : j - 1 Error(i) = IPos(i) + Ntot - INeg(i); InvError(i) = INeg(i) + Ptot - IPos(i); end idx_of_err_min = find(Error == min(Error)); if(length(idx_of_err_min) < 1) idx_of_err_min = 1; end if(length(idx_of_err_min) <1) idx_of_err_min = idx_of_err_min; end idx_of_err_min = idx_of_err_min(1); idx_of_inv_err_min = find(InvError == min(InvError)); if(length(idx_of_inv_err_min) < 1) idx_of_inv_err_min = 1; end idx_of_inv_err_min = idx_of_inv_err_min(1); if(Error(idx_of_err_min) < InvError(idx_of_inv_err_min)) T_MIN(1,d) = Error(idx_of_err_min); T_MIN(2,d) = idx_of_err_min; T_MIN(3,d) = -1; else T_MIN(1,d) = InvError(idx_of_inv_err_min); T_MIN(2,d) = idx_of_inv_err_min; T_MIN(3,d) = 1; end end best_dim = find(T_MIN(1,:) == min(T_MIN(1,:))); stump.t_dim = best_dim(1); TDS = sort(trainpat(stump.t_dim,:)); lDS = length(TDS); DS = TDS * 0; i = 1; j = 1; while i <= lDS k = 0; while i + k <= lDS && TDS(i) == TDS(i+k) DS(j) = TDS(i); k = k + 1; end i = i + k; j = j + 1; end DS = DS(1:j-1); stump.threshold = (DS(T_MIN(2,stump.t_dim)) + DS(min(T_MIN(2,stump.t_dim) + 1, length(DS)))) / 2; stump.signum = T_MIN(3,stump.t_dim);
github
BottjerLab/Acoustic_Similarity-master
get_dim_and_tr.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@tree_node_w/get_dim_and_tr.m
1,905
utf_8
128d5e5a782cf045502564dba3c897eb
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % get_dim_and_tr is the function, that returns dimension and threshold of % tree node %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % output = get_dim_and_tr(tree_node, output) % --------------------------------------------------------------------------------- % Arguments: % tree_node - a node of classification tree % output - vector of dimensions and thresholds. Result fo % current node would be concatinated to it % Return: % output - a vector of thresholds and dimensions. It has the % following format: % [dimension threshold left/right ...] % left/right is [-1, +1] number, wich signifies if % current threshold is eather left or right function output = get_dim_and_tr(tree_node, output) if(nargin < 2) output = []; end if(length(tree_node.parent) > 0) output = get_dim_and_tr(tree_node.parent, output); end output(end+1) = tree_node.dim; if( length(tree_node.right_constrain) > 0) output(end+1) = tree_node.right_constrain; output(end+1) = -1; elseif( length(tree_node.left_constrain) > 0) output(end+1) = tree_node.left_constrain; output(end+1) = +1; end % function [dim, tr, signum] = get_dim_and_tr(tree_node) % % dim = tree_node.dim; % % % % if( length(tree_node.right_constrain) > 0) % tr = tree_node.right_constrain; % signum = -1; % end % if( length(tree_node.left_constrain) > 0) % tr = tree_node.left_constrain; % signum = +1; % end
github
BottjerLab/Acoustic_Similarity-master
calc_output.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@tree_node_w/calc_output.m
1,236
utf_8
87fb96d3f77a0ac11a5430a6a3883aa6
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % calc_output Implements classification of input by a classification tree node %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % y = calc_output(tree_node, XData) % --------------------------------------------------------------------------------- % Arguments: % tree_node - classification tree node % XData - data, that will be classified % Return: % y - +1, if XData belongs to tree node, -1 otherwise (y is a vector) function y = calc_output(tree_node, XData) y = XData(tree_node.dim, :) * 0 + 1; for i = 1 : length(tree_node.parent) y = y .* calc_output(tree_node.parent, XData); end if( length(tree_node.right_constrain) > 0) y = y .* ((XData(tree_node.dim, :) < tree_node.right_constrain)); end if( length(tree_node.left_constrain) > 0) y = y .* ((XData(tree_node.dim, :) > tree_node.left_constrain)); end
github
BottjerLab/Acoustic_Similarity-master
do_learn_nu.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@tree_node_w/do_learn_nu.m
4,266
utf_8
5be6c419f73699a7df841d2736111631
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % do_learn_nu Implements splitting of tree node %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % [tree_node_left, tree_node_right, split_error] = % do_learn_nu(tree_node, dataset, labels, weights, papa) % --------------------------------------------------------------------------------- % Arguments: % tree_node - object of tree_node_w class % dataset - training data % labels - training labels % weights - weights of training data % papa - parent node (the one being split) % Return: % tree_node_left - left node (result of splitting) % tree_node_right - right node (result of splitting) % split_error - error of splitting function [tree_node_left, tree_node_right, split_error] = do_learn_nu(tree_node, dataset, labels, weights, papa) tree_node_left = tree_node; tree_node_right = tree_node; if(nargin > 4) tree_node_left.parent = papa; tree_node_right.parent = papa; end % [i,t] = weakLearner(weights,dataset', labels'); % % tree_node_left.right_constrain = t; % tree_node_right.left_constrain = t; % % tree_node_left.dim = i; % tree_node_right.dim = i; % % return; %dataset=data_w(dataset) ; %stump = set_distr(stump, get_sampl_weights(dataset)) ; Distr = weights; %[trainpat, traintarg] = get_train( dataset); trainpat = dataset; traintarg = labels; tr_size = size(trainpat, 2); T_MIN = zeros(3,size(trainpat,1)); d_min = 1; d_max = size(trainpat,1); for d = d_min : d_max; [DS, IX] = sort(trainpat(d,:)); TS = traintarg(IX); DiS = Distr(IX); lDS = length(DS); vPos = 0 * TS; vNeg = vPos; i = 1; j = 1; while i <= lDS k = 0; while i + k <= lDS && DS(i) == DS(i+k) if(TS(i+k) > 0) vPos(j) = vPos(j) + DiS(i+k); else vNeg(j) = vNeg(j) + DiS(i+k); end k = k + 1; end i = i + k; j = j + 1; end vNeg = vNeg(1:j-1); vPos = vPos(1:j-1); Error = zeros(1, j - 1); InvError = Error; IPos = vPos; INeg = vNeg; for i = 2 : length(IPos) IPos(i) = IPos(i-1) + vPos(i); INeg(i) = INeg(i-1) + vNeg(i); end Ntot = INeg(end); Ptot = IPos(end); for i = 1 : j - 1 Error(i) = IPos(i) + Ntot - INeg(i); InvError(i) = INeg(i) + Ptot - IPos(i); end idx_of_err_min = find(Error == min(Error)); if(length(idx_of_err_min) < 1) idx_of_err_min = 1; end if(length(idx_of_err_min) <1) idx_of_err_min = idx_of_err_min; end idx_of_err_min = idx_of_err_min(1); idx_of_inv_err_min = find(InvError == min(InvError)); if(length(idx_of_inv_err_min) < 1) idx_of_inv_err_min = 1; end idx_of_inv_err_min = idx_of_inv_err_min(1); if(Error(idx_of_err_min) < InvError(idx_of_inv_err_min)) T_MIN(1,d) = Error(idx_of_err_min); T_MIN(2,d) = idx_of_err_min; T_MIN(3,d) = -1; else T_MIN(1,d) = InvError(idx_of_inv_err_min); T_MIN(2,d) = idx_of_inv_err_min; T_MIN(3,d) = 1; end end dim = []; best_dim = find(T_MIN(1,:) == min(T_MIN(1,:))); dim = best_dim(1); tree_node_left.dim = dim; tree_node_right.dim = dim; TDS = sort(trainpat(dim,:)); lDS = length(TDS); DS = TDS * 0; i = 1; j = 1; while i <= lDS k = 0; while i + k <= lDS && TDS(i) == TDS(i+k) DS(j) = TDS(i); k = k + 1; end i = i + k; j = j + 1; end DS = DS(1:j-1); split = (DS(T_MIN(2,dim)) + DS(min(T_MIN(2,dim) + 1, length(DS)))) / 2; split_error = T_MIN(1,dim); tree_node_left.right_constrain = split; tree_node_right.left_constrain = split; function [i,t] = weakLearner(distribution,train,label) %disp('run weakLearner'); for tt = unique(train)%1:(16*256-1) error(tt)=(label .* distribution) * ((train(:,floor(tt/16)+1)>=16*(mod(tt,16)+1))); end [val,tt]=max(abs(error-0.5)); i=floor(tt/16)+1; t=16*(mod(tt,16)+1); return;
github
BottjerLab/Acoustic_Similarity-master
train.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@tree_node_w/train.m
3,474
utf_8
4612a951935a7047eb5e580691cb7d0b
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % train Implements training of a classification tree %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % nodes = train(node, dataset, labels, weights) % --------------------------------------------------------------------------------- % Arguments: % node - object of tree_node_w class (initialized properly) % dataset - training data % labels - training labels % weights - weights of training data % Return: % nodes - tree is represented as a cell array of its nodes function nodes = train(node, dataset, labels, weights) max_split = node.max_split; [left right spit_error] = do_learn_nu(node, dataset, labels, weights); nodes = {left, right}; left_pos = sum((calc_output(left , dataset) == labels) .* weights); left_neg = sum((calc_output(left , dataset) == -labels) .* weights); right_pos = sum((calc_output(right, dataset) == labels) .* weights); right_neg = sum((calc_output(right, dataset) == -labels) .* weights); errors = [min(left_pos, left_neg), min(right_pos, right_neg)]; if(right_pos == 0 && right_neg == 0) return; end if(left_pos == 0 && left_neg == 0) return; end [errors, IDX] = sort(errors); errors = flipdim(errors,2); IDX = flipdim(IDX,2); nodes = nodes(IDX); splits = []; split_errors = []; deltas = []; for i = 2 : max_split for j = 1 : length(errors) if(length(deltas) >= j) continue; end max_node = nodes{j}; max_node_out = calc_output(max_node, dataset); mask = find(max_node_out == 1); [left right spit_error] = do_learn_nu(node, dataset(:,mask), labels(mask), weights(mask), max_node); left_pos = sum((calc_output(left , dataset) == labels) .* weights); left_neg = sum((calc_output(left , dataset) == -labels) .* weights); right_pos = sum((calc_output(right, dataset) == labels) .* weights); right_neg = sum((calc_output(right, dataset) == -labels) .* weights); splits{end+1} = left; splits{end+1} = right; if( (right_pos + right_neg) == 0 || (left_pos + left_neg) == 0) deltas(end+1) = 0; else deltas(end+1) = errors(j) - spit_error; end split_errors(end+1) = min(left_pos, left_neg); split_errors(end+1) = min(right_pos, right_neg); end if(max(deltas) == 0) return; end best_split = find(deltas == max(deltas)); best_split = best_split(1); cut_vec = [1 : (best_split-1) (best_split + 1) : length(errors)]; nodes = nodes(cut_vec); errors = errors(cut_vec); deltas = deltas(cut_vec); nodes{end+1} = splits{2 * best_split - 1}; nodes{end+1} = splits{2 * best_split}; errors(end+1) = split_errors(2 * best_split - 1); errors(end+1) = split_errors(2 * best_split); cut_vec = [1 : 2 * (best_split-1) 2 * (best_split)+1 : length(split_errors)]; split_errors = split_errors(cut_vec); splits = splits(cut_vec); end
github
BottjerLab/Acoustic_Similarity-master
crossvalidation.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@crossvalidation/crossvalidation.m
967
utf_8
5885782c13c91dcbd80398a1bc3bc552
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % crossvalidation Implements the constructor for crossvalidation class %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % this = crossvalidation(folds) % --------------------------------------------------------------------------------- % Arguments: % folds - number of cross-validation folds % Return: % this - object of crossvalidation class function this = crossvalidation(folds) if( folds == 1) error('folds should be >= 2'); end this.folds = folds; this.CrossDataSets = cell(folds, 1); this.CrossLabelsSets = cell(folds, 1); this=class(this, 'crossvalidation') ;
github
BottjerLab/Acoustic_Similarity-master
CatFold.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@crossvalidation/CatFold.m
1,132
utf_8
14bc637af960adb6280c6916fb2cb3fd
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % CatFold cancatinates cross-validation fold N to passed Data and Labels %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % [Data, Labels] = CatFold(this, Data, Labels, N) % --------------------------------------------------------------------------------- % Arguments: % this - crossvalidation object % Data - Data matrix % Labels - Labels matrix % N - number of fold % Return: % Data - Data with fold N concatinated % Labels - Labels with fold N concatinated function [Data, Labels] = CatFold(this, Data, Labels, N) if(N > this.folds) error('N > total folds'); end Data = cat(2, Data, this.CrossDataSets{N}{1,1}); Labels = cat(2, Labels, this.CrossLabelsSets{N}{1,1});
github
BottjerLab/Acoustic_Similarity-master
Initialize.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@crossvalidation/Initialize.m
2,347
utf_8
b3501dc177ff753b917d1f464e85f1e2
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % Initialize initializes crossvalidation object with data %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % this = Initialize(this, Data, Labels) % --------------------------------------------------------------------------------- % Arguments: % this - crossvalidation object % Data - Should be DxN matrix, where D is the % dimensionality of data, and N is the number of % samples. % Labels - Should be 1xN matrix, where N is % the number of samples. % Return: % this - crossvalidation object, initialized with data and % labels function this = Initialize(this, Data, Labels) if( size(Labels,1) ~= 1 || length(size(Labels)) ~= 2) error('Labels should be a (1,N) matrix.'); end if( size(Labels,2) ~= size(Data,2)) error('Data should be (M,N) matrix and Labels (1,N)'); end for i = 1 : length(Data) fold_i = floor(rand * (this.folds - eps) + 1); % fold_i = mod(i,this.folds) + 1; if( i > this.folds ) this.CrossDataSets{fold_i} = {cat(2, Data(:, i), this.CrossDataSets{fold_i}{1,1})}; this.CrossLabelsSets{fold_i} = {cat(2, Labels(:, i), this.CrossLabelsSets{fold_i}{1,1})}; else this.CrossDataSets{i} = {cat(2, Data(:, i), this.CrossDataSets{i})}; this.CrossLabelsSets{i} = {cat(2, Labels(:, i), this.CrossLabelsSets{i})}; end % if( i > this.folds ) % this.CrossDataSets{mod(i,this.folds) + 1} = {cat(2, Data(:, i), this.CrossDataSets{mod(i,this.folds) + 1}{1,1})}; % this.CrossLabelsSets{mod(i,this.folds) + 1} = {cat(2, Labels(:, i), this.CrossLabelsSets{mod(i,this.folds) + 1}{1,1})}; % else % this.CrossDataSets{mod(i,this.folds) + 1} = {cat(2, Data(:, i), this.CrossDataSets{mod(i,this.folds) + 1})}; % this.CrossLabelsSets{mod(i,this.folds) + 1} = {cat(2, Labels(:, i), this.CrossLabelsSets{mod(i,this.folds) + 1})}; % end end
github
BottjerLab/Acoustic_Similarity-master
GetFold.m
.m
Acoustic_Similarity-master/code/fileExchange/boosting/@crossvalidation/GetFold.m
976
utf_8
a33135611bfd93f1eca9ba3999e2d7b0
% The algorithms implemented by Alexander Vezhnevets aka Vezhnick % <a>href="mailto:[email protected]">[email protected]</a> % % Copyright (C) 2005, Vezhnevets Alexander % [email protected] % % This file is part of GML Matlab Toolbox % For conditions of distribution and use, see the accompanying License.txt file. % % GetFold returns Nth fold %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % % [Data, Labels] = GetFold(this, N) % --------------------------------------------------------------------------------- % Arguments: % this - crossvalidation object % N - number of fold % Return: % Data - fold N data % Labels - fold N labels function [Data, Labels] = GetFold(this, N) Data = []; Labels = []; if(N > this.folds) error('N > total folds'); end Data = cat(2, Data, this.CrossDataSets{N}{1,1}); Labels = cat(2, Labels, this.CrossLabelsSets{N}{1,1});
github
BottjerLab/Acoustic_Similarity-master
progressbar.m
.m
Acoustic_Similarity-master/code/fileExchange/progressbar/progressbar.m
11,767
utf_8
06705e480618e134da62478338e8251c
function progressbar(varargin) % Description: % progressbar() provides an indication of the progress of some task using % graphics and text. Calling progressbar repeatedly will update the figure and % automatically estimate the amount of time remaining. % This implementation of progressbar is intended to be extremely simple to use % while providing a high quality user experience. % % Features: % - Can add progressbar to existing m-files with a single line of code. % - Supports multiple bars in one figure to show progress of nested loops. % - Optional labels on bars. % - Figure closes automatically when task is complete. % - Only one figure can exist so old figures don't clutter the desktop. % - Remaining time estimate is accurate even if the figure gets closed. % - Minimal execution time. Won't slow down code. % - Randomized color. When a programmer gets bored... % % Example Function Calls For Single Bar Usage: % progressbar % Initialize/reset % progressbar(0) % Initialize/reset % progressbar('Label') % Initialize/reset and label the bar % progressbar(0.5) % Update % progressbar(1) % Close % % Example Function Calls For Multi Bar Usage: % progressbar(0, 0) % Initialize/reset two bars % progressbar('A', '') % Initialize/reset two bars with one label % progressbar('', 'B') % Initialize/reset two bars with one label % progressbar('A', 'B') % Initialize/reset two bars with two labels % progressbar(0.3) % Update 1st bar % progressbar(0.3, []) % Update 1st bar % progressbar([], 0.3) % Update 2nd bar % progressbar(0.7, 0.9) % Update both bars % progressbar(1) % Close % progressbar(1, []) % Close % progressbar(1, 0.4) % Close % % Notes: % For best results, call progressbar with all zero (or all string) inputs % before any processing. This sets the proper starting time reference to % calculate time remaining. % Bar color is choosen randomly when the figure is created or reset. Clicking % the bar will cause a random color change. % % Demos: % % Single bar % m = 500; % progressbar % Init single bar % for i = 1:m % pause(0.01) % Do something important % progressbar(i/m) % Update progress bar % end % % % Simple multi bar (update one bar at a time) % m = 4; % n = 3; % p = 100; % progressbar(0,0,0) % Init 3 bars % for i = 1:m % progressbar([],0) % Reset 2nd bar % for j = 1:n % progressbar([],[],0) % Reset 3rd bar % for k = 1:p % pause(0.01) % Do something important % progressbar([],[],k/p) % Update 3rd bar % end % progressbar([],j/n) % Update 2nd bar % end % progressbar(i/m) % Update 1st bar % end % % % Fancy multi bar (use labels and update all bars at once) % m = 4; % n = 3; % p = 100; % progressbar('Monte Carlo Trials','Simulation','Component') % Init 3 bars % for i = 1:m % for j = 1:n % for k = 1:p % pause(0.01) % Do something important % % Update all bars % frac3 = k/p; % frac2 = ((j-1) + frac3) / n; % frac1 = ((i-1) + frac2) / m; % progressbar(frac1, frac2, frac3) % end % end % end % % Author: % Steve Hoelzer % % Revisions: % 2002-Feb-27 Created function % 2002-Mar-19 Updated title text order % 2002-Apr-11 Use floor instead of round for percentdone % 2002-Jun-06 Updated for speed using patch (Thanks to waitbar.m) % 2002-Jun-19 Choose random patch color when a new figure is created % 2002-Jun-24 Click on bar or axes to choose new random color % 2002-Jun-27 Calc time left, reset progress bar when fractiondone == 0 % 2002-Jun-28 Remove extraText var, add position var % 2002-Jul-18 fractiondone input is optional % 2002-Jul-19 Allow position to specify screen coordinates % 2002-Jul-22 Clear vars used in color change callback routine % 2002-Jul-29 Position input is always specified in pixels % 2002-Sep-09 Change order of title bar text % 2003-Jun-13 Change 'min' to 'm' because of built in function 'min' % 2003-Sep-08 Use callback for changing color instead of string % 2003-Sep-10 Use persistent vars for speed, modify titlebarstr % 2003-Sep-25 Correct titlebarstr for 0% case % 2003-Nov-25 Clear all persistent vars when percentdone = 100 % 2004-Jan-22 Cleaner reset process, don't create figure if percentdone = 100 % 2004-Jan-27 Handle incorrect position input % 2004-Feb-16 Minimum time interval between updates % 2004-Apr-01 Cleaner process of enforcing minimum time interval % 2004-Oct-08 Seperate function for timeleftstr, expand to include days % 2004-Oct-20 Efficient if-else structure for sec2timestr % 2006-Sep-11 Width is a multiple of height (don't stretch on widescreens) % 2010-Sep-21 Major overhaul to support multiple bars and add labels % persistent progfig progdata lastupdate % Get inputs if nargin > 0 input = varargin; ninput = nargin; else % If no inputs, init with a single bar input = {0}; ninput = 1; end % If task completed, close figure and clear vars, then exit if input{1} == 1 if ishandle(progfig) delete(progfig) % Close progress bar end clear progfig progdata lastupdate % Clear persistent vars drawnow return end % Init reset flag resetflag = false; % Set reset flag if first input is a string if ischar(input{1}) resetflag = true; end % Set reset flag if all inputs are zero if input{1} == 0 % If the quick check above passes, need to check all inputs if all([input{:}] == 0) && (length([input{:}]) == ninput) resetflag = true; end end % Set reset flag if more inputs than bars if ninput > length(progdata) resetflag = true; end % If reset needed, close figure and forget old data if resetflag if ishandle(progfig) delete(progfig) % Close progress bar end progfig = []; progdata = []; % Forget obsolete data end % Create new progress bar if needed if ishandle(progfig) else % This strange if-else works when progfig is empty (~ishandle() does not) % Define figure size and axes padding for the single bar case height = 0.03; width = height * 8; hpad = 0.02; vpad = 0.25; % Figure out how many bars to draw nbars = max(ninput, length(progdata)); % Adjust figure size and axes padding for number of bars heightfactor = (1 - vpad) * nbars + vpad; height = height * heightfactor; vpad = vpad / heightfactor; % Initialize progress bar figure left = (1 - width) / 2; bottom = (1 - height) / 2; progfig = figure(... 'Units', 'normalized',... 'Position', [left bottom width height],... 'NumberTitle', 'off',... 'Resize', 'off',... 'MenuBar', 'none' ); % Initialize axes, patch, and text for each bar left = hpad; width = 1 - 2*hpad; vpadtotal = vpad * (nbars + 1); height = (1 - vpadtotal) / nbars; for ndx = 1:nbars % Create axes, patch, and text bottom = vpad + (vpad + height) * (nbars - ndx); progdata(ndx).progaxes = axes( ... 'Position', [left bottom width height], ... 'XLim', [0 1], ... 'YLim', [0 1], ... 'Box', 'on', ... 'ytick', [], ... 'xtick', [] ); progdata(ndx).progpatch = patch( ... 'XData', [0 0 0 0], ... 'YData', [0 0 1 1] ); progdata(ndx).progtext = text(0.99, 0.5, '', ... 'HorizontalAlignment', 'Right', ... 'FontUnits', 'Normalized', ... 'FontSize', 0.7 ); progdata(ndx).proglabel = text(0.01, 0.5, '', ... 'HorizontalAlignment', 'Left', ... 'FontUnits', 'Normalized', ... 'FontSize', 0.7 ); if ischar(input{ndx}) set(progdata(ndx).proglabel, 'String', input{ndx}) input{ndx} = 0; end % Set callbacks to change color on mouse click set(progdata(ndx).progaxes, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).progpatch, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).progtext, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).proglabel, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) % Pick a random color for this patch changecolor([], [], progdata(ndx).progpatch) % Set starting time reference if ~isfield(progdata(ndx), 'starttime') || isempty(progdata(ndx).starttime) progdata(ndx).starttime = clock; end end % Set time of last update to ensure a redraw lastupdate = clock - 1; end % Process inputs and update state of progdata for ndx = 1:ninput if ~isempty(input{ndx}) progdata(ndx).fractiondone = input{ndx}; progdata(ndx).clock = clock; end end % Enforce a minimum time interval between graphics updates myclock = clock; if abs(myclock(6) - lastupdate(6)) < 0.01 % Could use etime() but this is faster return end % Update progress patch for ndx = 1:length(progdata) set(progdata(ndx).progpatch, 'XData', ... [0, progdata(ndx).fractiondone, progdata(ndx).fractiondone, 0]) end % Update progress text if there is more than one bar if length(progdata) > 1 for ndx = 1:length(progdata) set(progdata(ndx).progtext, 'String', ... sprintf('%1d%%', floor(100*progdata(ndx).fractiondone))) end end % Update progress figure title bar if progdata(1).fractiondone > 0 runtime = etime(progdata(1).clock, progdata(1).starttime); timeleft = runtime / progdata(1).fractiondone - runtime; timeleftstr = sec2timestr(timeleft); titlebarstr = sprintf('%2d%% %s remaining', ... floor(100*progdata(1).fractiondone), timeleftstr); else titlebarstr = ' 0%'; end set(progfig, 'Name', titlebarstr) % Force redraw to show changes drawnow % Record time of this update lastupdate = clock; % ------------------------------------------------------------------------------ function changecolor(h, e, progpatch) %#ok<INUSL> % Change the color of the progress bar patch % Prevent color from being too dark or too light colormin = 1.5; colormax = 2.8; thiscolor = rand(1, 3); while (sum(thiscolor) < colormin) || (sum(thiscolor) > colormax) thiscolor = rand(1, 3); end set(progpatch, 'FaceColor', thiscolor) % ------------------------------------------------------------------------------ function timestr = sec2timestr(sec) % Convert a time measurement from seconds into a human readable string. % Convert seconds to other units w = floor(sec/604800); % Weeks sec = sec - w*604800; d = floor(sec/86400); % Days sec = sec - d*86400; h = floor(sec/3600); % Hours sec = sec - h*3600; m = floor(sec/60); % Minutes sec = sec - m*60; s = floor(sec); % Seconds % Create time string if w > 0 if w > 9 timestr = sprintf('%d week', w); else timestr = sprintf('%d week, %d day', w, d); end elseif d > 0 if d > 9 timestr = sprintf('%d day', d); else timestr = sprintf('%d day, %d hr', d, h); end elseif h > 0 if h > 9 timestr = sprintf('%d hr', h); else timestr = sprintf('%d hr, %d min', h, m); end elseif m > 0 if m > 9 timestr = sprintf('%d min', m); else timestr = sprintf('%d min, %d sec', m, s); end else timestr = sprintf('%d sec', s); end
github
BottjerLab/Acoustic_Similarity-master
yin2.m
.m
Acoustic_Similarity-master/code/fileExchange/yin/junk/yin2.m
2,235
utf_8
b91a6e57061458dd6bd01fc6a7162a27
function r=yin2(p,fileinfo) % YIN2 - fundamental frequency estimator % new version (feb 2003) % % % process signal a chunk at a time idx=0; totalhops=round(fileinfo.nsamples / p.hop); r1=nan*zeros(1,totalhops);r2=nan*zeros(1,totalhops); r3=nan*zeros(1,totalhops);r4=nan*zeros(1,totalhops); idx2=0+round(p.wsize/2/p.hop); while (1) xx=sf_wave(fileinfo, [idx+1, idx+p.bufsize], []); xx=xx(:,1); % first channel if multichannel [prd,ap0,ap,pwr]=yin_helper(xx,p); n=size(prd ,2); if (~n) break; end; idx=idx+n*p.hop; r1(idx2+1:idx2+n)= prd; r2(idx2+1:idx2+n)= ap0; r3(idx2+1:idx2+n)= ap; r4(idx2+1:idx2+n)= pwr; idx2=idx2+n; end size(r1) r.r1=r1; % period estimate r.r2=r2; % gross aperiodicity measure r.r3=r3; % fine aperiodicity measure r.r4=r4; % power sf_cleanup(fileinfo); % end of program % Estimate F0 of a chunk of signal function [prd,ap0,ap,pwr]=yin_helper(x,p,dd) [m,n]=size(x); smooth=ceil(p.sr/p.lpf); x=rsmooth(x,smooth); % light low-pass smoothing x=x(smooth+1:end); maxlag = ceil(p.sr/p.minf0); minlag = floor(p.sr/p.maxf0); hops=floor((m-maxlag-p.wsize)/p.hop); prd=zeros(1,hops); ap0=zeros(1,hops); ap=zeros(1,hops); pwr=zeros(1,hops); if hops<1; return; end % difference function matrix dd=zeros(ceil((m-maxlag-2)/p.hop),maxlag+2); % +2 to improve interp near maxlag lags=[zeros(1,maxlag+2); 1:maxlag+2]; rdiff_inplace(x,x,dd,lags,p.hop); rsum_inplace(dd,round(p.wsize/p.hop)); dd=dd'; % parabolic interpolation near min, then cumulative mean normalization [dd,ddx]=minparabolic(dd); cumnorm_inplace(dd); for j=0:hops-1 idx=j*p.hop; d=dd(:,j+1); dx=ddx(:,j+1); % estimate period pd=dftoperiod(d,[minlag,maxlag],p.thresh*2); % gross aperiodicity is value of cumnormed df at minimum: ap0(j+1)=d(pd)/2; % fine tune period based on parabolic interpolation pd=pd+dx(pd+1)+1; % power estimates k=(1:ceil(pd))'; x1=x(k+idx); x2=k+idx+pd-1; interp_inplace(x,x2); x3=x2-x1; x4=x2+x1; x1=x1.^2; rsum_inplace(x1,pd); x3=x3.^2; rsum_inplace(x3,pd); x4=x4.^2; rsum_inplace(x4,pd); x1=x1(1)/pd; x2=x2(1)/pd; x3=x3(1)/pd; x4=x4(1)/pd; % total power pwr(j+1)=x1; % fine aperiodicity ap(j+1)=(eps+x3)/(eps+(x3+x4)); % accurate, only for valid min prd(j+1)=pd; end
github
BottjerLab/Acoustic_Similarity-master
yink.m
.m
Acoustic_Similarity-master/code/fileExchange/yin/private/yink.m
3,440
utf_8
77a95ea21aeeda525ec337a2f6545d95
function r=yink(p,fileinfo) % YINK - fundamental frequency estimator % new version (feb 2003) % % %global jj; %jj=0; % process signal a chunk at a time idx=p.range(1)-1; totalhops=round((p.range(2)-p.range(1)+1) / p.hop); r1=nan*zeros(1,totalhops);r2=nan*zeros(1,totalhops); r3=nan*zeros(1,totalhops);r4=nan*zeros(1,totalhops); idx2=0+round(p.wsize/2/p.hop); while (1) start = idx+1; stop = idx+p.bufsize; stop=min(stop, p.range(2)); xx=sf_wave(fileinfo, [start, stop], []); % if size(xx,1) == 1; xx=xx'; end xx=xx(:,1); % first channel if multichannel [prd,ap0,ap,pwr]=yin_helper(xx,p); n=size(prd ,2); if (~n) break; end; idx=idx+n*p.hop; r1(idx2+1:idx2+n)= prd; r2(idx2+1:idx2+n)= ap0; r3(idx2+1:idx2+n)= ap; r4(idx2+1:idx2+n)= pwr; idx2=idx2+n; end r.r1=r1; % period estimate r.r2=r2; % gross aperiodicity measure r.r3=r3; % fine aperiodicity measure r.r4=r4; % power sf_cleanup(fileinfo); % end of program % Estimate F0 of a chunk of signal function [prd,ap0,ap,pwr]=yin_helper(x,p,dd) smooth=ceil(p.sr/p.lpf); x=rsmooth(x,smooth); % light low-pass smoothing x=x(smooth:end-smooth+1); [m,n]=size(x); maxlag = ceil(p.sr/p.minf0); minlag = floor(p.sr/p.maxf0); mxlg = maxlag+2; % +2 to improve interp near maxlag hops=floor((m-mxlg-p.wsize)/p.hop); prd=zeros(1,hops); ap0=zeros(1,hops); ap=zeros(1,hops); pwr=zeros(1,hops); if hops<1; return; end % difference function matrix dd=zeros(floor((m-mxlg-p.hop)/p.hop),mxlg); if p.shift == 0 % windows shift both ways lags1=round(mxlg/2) + round((0:mxlg-1)/2); lags2=round(mxlg/2) - round((1:mxlg)/2); lags=[lags1; lags2]; elseif p.shift == 1 % one window fixed, other shifts right lags=[zeros(1,mxlg); 1:mxlg]; elseif p.shift == -1 % one window fixed, other shifts right lags=[mxlg-1:-1:0; mxlg*ones(1,mxlg)]; else error (['unexpected shift flag: ', num2str(p.shift)]); end rdiff_inplace(x,x,dd,lags,p.hop); rsum_inplace(dd,min(round(p.wsize/p.hop),size(dd,1))); dd=dd'; [dd,ddx]=minparabolic(dd); % parabolic interpolation near min cumnorm_inplace(dd);; % cumulative mean-normalize % first period estimate %global jj; for j=1:hops d=dd(:,j); if p.relflag pd=dftoperiod2(d,[minlag,maxlag],p.thresh); else pd=dftoperiod(d,[minlag,maxlag],p.thresh); end ap0(j)=d(pd+1); prd(j)=pd; end % replace each estimate by best estimate in range range = 2*round(maxlag/p.hop); if hops>1; prd=prd(mininrange(ap0,range*ones(1,hops))); end %prd=prd(mininrange(ap0,prd)); % refine estimate by constraining search to vicinity of best local estimate margin1=0.6; margin2=1.8; for j=1:hops d=dd(:,j); dx=ddx(:,j); pd=prd(j); lo=floor(pd*margin1); lo=max(minlag,lo); hi=ceil(pd*margin2); hi=min(maxlag,hi); pd=dftoperiod(d,[lo,hi],0); ap0(j)=d(pd+1); pd=pd+dx(pd+1)+1; % fine tune based on parabolic interpolation prd(j)=pd; % power estimates idx=(j-1)*p.hop; k=(1:ceil(pd))'; x1=x(k+idx); x2=k+idx+pd-1; interp_inplace(x,x2); x3=x2-x1; x4=x2+x1; x1=x1.^2; rsum_inplace(x1,pd); x3=x3.^2; rsum_inplace(x3,pd); x4=x4.^2; rsum_inplace(x4,pd); x1=x1(1)/pd; x2=x2(1)/pd; x3=x3(1)/pd; x4=x4(1)/pd; % total power pwr(j)=x1; % fine aperiodicity ap(j)=(eps+x3)/(eps+(x3+x4)); % accurate, only for valid min %ap(j) %plot(min(1, d)); pause prd(j)=pd; end %cumulative mean-normalize function y=cumnorm(x) [m,n]=size(x); y = cumsum(x); y = (y)./ (eps+repmat((1:m)',1,n)); % cumulative mean y = (eps+x) ./ (eps+y);
github
BottjerLab/Acoustic_Similarity-master
anova2rm_cell.m
.m
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/anova2rm_cell.m
6,774
utf_8
37ad08d0dfb97a5ae59971a6becc90b7
% anova2rm_cell() - compute F-values in cell array using repeated measure % ANOVA. % % Usage: % >> [FC FR FI dfc dfr dfi] = anova2rm_cell( data ); % % Inputs: % data = data consisting of PAIRED arrays to be compared. The last % dimension of the data array is used to compute ANOVA. % Outputs: % FC - F-value for columns. % FR - F-value for rows. % FI - F-value for interaction. % dfc - degree of freedom for columns. % dfr - degree of freedom for rows. % dfi - degree of freedom for interaction. % % Note: this function is inspired from rm_anova available at % http://www.mathworks.se/matlabcentral/fileexchange/6874-two-way-rep % eated-measures-anova % It allows for fast computation of about 20 thousands ANOVA per % second. It is different from anova2_cell which mimics the ANOVA % fonction from the Matlab statistical toolbox. This function % computes true repeated measure ANOVA. % % Example: % a = { rand(1,10) rand(1,10) rand(1,10); rand(1,10) rand(1,10) rand(1,10) } % [FC FR FI dfc dfr dfi] = anova2rm_cell(a) % signifC = 1-fcdf(FC, dfc(1), dfc(2)) % signifR = 1-fcdf(FR, dfr(1), dfr(2)) % signifI = 1-fcdf(FI, dfi(1), dfi(2)) % % % for comparison % z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2; % rm_anova2( [ a{1,1}';a{1,2}';a{1,3}';a{2,1}';a{2,2}';a{2,3}' ], ... % repmat([1:10]', [6 1]), [o;o;o;z;z;z], [z;o;t;z;o;t], {'a','b'}) % % c = { rand(200,400,10) rand(200,400,10); ... % rand(200,400,10) rand(200,400,10)}; % [FC FR FI dfc dfr dfi] = anova2rm_cell(c) % computes 200x400 ANOVAs % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2010 % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [fA fB fAB dfApair dfBpair dfABpair] = anova2rm_cell(data) % compute all means and all std % ----------------------------- a = size(data,1); b = size(data,2); nd = myndims( data{1} ); n = size( data{1} ,nd); % only for paired stats % --------------------- if nd == 1 AB = zeros(a,b,'single'); AS = zeros(a,n,'single'); BS = zeros(b,n,'single'); sq = single(0); for ind1 = 1:a for ind2 = 1:b AB(ind1,ind2) = sum(data{ind1,ind2}); AS(ind1,:) = AS(ind1,:) + data{ind1,ind2}'; BS(ind2,:) = BS(ind2,:) + data{ind1,ind2}'; sq = sq + sum(data{ind1,ind2}.^2); end; end; dimA = 2; dimB = 1; elseif nd == 2 AB = zeros(size(data{1},1),a,b,'single'); AS = zeros(size(data{1},1),a,n,'single'); BS = zeros(size(data{1},1),b,n,'single'); sq = zeros(size(data{1},1),1,'single'); for ind1 = 1:a for ind2 = 1:b AB(:,ind1,ind2) = sum(data{ind1,ind2},nd); AS(:,ind1,:) = AS(:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),1,n); BS(:,ind2,:) = BS(:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),1,n); sq = sq + sum(data{ind1,ind2}.^2,nd); end; end; dimA = 3; dimB = 2; elseif nd == 3 AB = zeros(size(data{1},1),size(data{1},2),a,b,'single'); AS = zeros(size(data{1},1),size(data{1},2),a,n,'single'); BS = zeros(size(data{1},1),size(data{1},2),b,n,'single'); sq = zeros(size(data{1},1),size(data{1},2),'single'); for ind1 = 1:a for ind2 = 1:b AB(:,:,ind1,ind2) = sum(data{ind1,ind2},nd); AS(:,:,ind1,:) = AS(:,:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),1,n); BS(:,:,ind2,:) = BS(:,:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),1,n); sq = sq + sum(data{ind1,ind2}.^2,nd); end; end; dimA = 4; dimB = 3; elseif nd == 4 AB = zeros(size(data{1},1),size(data{1},2),size(data{1},3),a,b,'single'); AS = zeros(size(data{1},1),size(data{1},2),size(data{1},3),a,n,'single'); BS = zeros(size(data{1},1),size(data{1},2),size(data{1},3),b,n,'single'); sq = zeros(size(data{1},1),size(data{1},2),size(data{1},3),'single'); for ind1 = 1:a for ind2 = 1:b AB(:,:,:,ind1,ind2) = sum(data{ind1,ind2},nd); AS(:,:,:,ind1,:) = AS(:,:,:,ind1,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),size(data{1},3),1,n); BS(:,:,:,ind2,:) = BS(:,:,:,ind2,:) + reshape(data{ind1,ind2},size(data{1},1),size(data{1},2),size(data{1},3),1,n); sq = sq + sum(data{ind1,ind2}.^2,nd); end; end; dimA = 5; dimB = 4; end; A = sum(AB,dimA); % sum across columns, so result is ax1 column vector B = sum(AB,dimB); % sum across rows, so result is 1xb row vector S = sum(AS,dimB); % sum across columns, so result is 1xs row vector T = sum(sum(A,dimB),dimA); % could sum either A or B or S, choice is arbitrary % degrees of freedom dfA = a-1; dfB = b-1; dfAB = (a-1)*(b-1); dfS = n-1; dfAS = (a-1)*(n-1); dfBS = (b-1)*(n-1); dfABS = (a-1)*(b-1)*(n-1); % bracket terms (expected value) expA = sum(A.^2,dimB)./(b*n); expB = sum(B.^2,dimA)./(a*n); expAB = sum(sum(AB.^2,dimA),dimB)./n; expS = sum(S.^2,dimA)./(a*b); expAS = sum(sum(AS.^2,dimB),dimA)./b; expBS = sum(sum(BS.^2,dimB),dimA)./a; expY = sq; %sum(Y.^2); expT = T.^2 / (a*b*n); % sums of squares ssA = expA - expT; ssB = expB - expT; ssAB = expAB - expA - expB + expT; ssS = expS - expT; ssAS = expAS - expA - expS + expT; ssBS = expBS - expB - expS + expT; ssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT; ssTot = expY - expT; % mean squares msA = ssA / dfA; msB = ssB / dfB; msAB = ssAB / dfAB; msS = ssS / dfS; msAS = ssAS / dfAS; msBS = ssBS / dfBS; msABS = ssABS / dfABS; % f statistic fA = msA ./ msAS; fB = msB ./ msBS; fAB = msAB ./ msABS; dfApair = [dfA dfAS]; dfBpair = [dfB dfBS]; dfABpair = [dfAB dfABS]; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;
github
BottjerLab/Acoustic_Similarity-master
statcond.m
.m
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/statcond.m
22,523
utf_8
4da6856416931e3152c3292a592259a0
% statcond() - compare two or more data conditions statistically using % standard parametric or nonparametric permutation-based ANOVA % (1-way or 2-way) or t-test methods. Parametric testing uses % fcdf() from the Matlab Statistical Toolbox. Use of up to % 4-D data matrices speeds processing. % Usage: % >> [stats, df, pvals, surrog] = statcond( data, 'key','val'... ); % Inputs: % data = one-or two-dimensional cell array of data matrices. % For nonparametric, permutation-based testing, the % last dimension of the data arrays (which may be of up to % 4 dimensions) is permuted across conditions, either in % a 'paired' fashion (not changing the, e.g., subject or % trial order in the last dimension) or in an umpaired % fashion (not respecting this order). If the number of % elements in the last dimension is not the same across % conditions, the 'paired' option is turned 'off'. Note: % All other dimensions MUST be constant across conditions. % For example, consider a (1,3) cell array of matrices % of size (100,20,x) each holding a (100,20) time/frequency % transform from each of x subjects. Only the last dimension % (here x, the number of subjects) may differ across the % three conditions. % The test used depends on the size of the data array input. % When the data cell array has 2 columns and the data are % paired, a paired t-test is performed; when the data are % unpaired, an unpaired t-test is performed. If 'data' % has only one row (paired or unpaired) and more than 2 % columns, a one-way ANOVA is performed. If the data cell % array contains several rows and columns, and the data is % paired, a two-way repeated measure ANOVA is performed. % NOTE THAT IF THE DATA is unpaired, EEGLAB will use a % balanced 1 or 2 way ANOVA and parametric results might not % be meaningful (bootstrap and permutation should be fine). % % Optional inputs: % 'paired' = ['on'|'off'] pair the data array {default: 'on' unless % the last dimension of data array is of different lengths}. % 'mode' = ['perm'|'bootstrap'|'param'] mode for computing the p-values: % 'param' = parametric testing (standard ANOVA or t-test); % 'perm' = non-parametric testing using surrogate data % 'bootstrap' = non-parametric bootstrap % made by permuting the input data {default: 'param'} % 'naccu' = [integer] Number of surrogate data copies to use in 'perm' % or 'bootstrap' mode estimation (see above) {default: 200}. % 'verbose' = ['on'|'off'] print info on the command line {default: 'on'}. % 'variance' = ['homegenous'|'inhomogenous'] this option is exclusively % for parametric statistics using unpaired t-test. It allows % to compute a more accurate value for the degree of freedom % using the formula for inhomogenous variance (see % ttest2_cell function). Default is 'homegenous'. % % Outputs: % stats = F- or T-value array of the same size as input data without % the last dimension. A T value is returned only when the data % includes exactly two conditions. % df = degrees of freedom, a (2,1) vector, when F-values are returned % pvals = array of p-values. Same size as input data without the last % data dimension. All returned p-values are two-tailed. % surrog = surrogate data array (same size as input data with the last % dimension filled with a number ('naccu') of surrogate data sets. % % Important note: When a two-way ANOVA is performed, outputs are cell arrays % with three elements: output(1) = column effects; % output(2) = row effects; output(3) = interactions % between rows and columns. % Examples: % >> a = { rand(1,10) rand(1,10)+0.5 }; % pseudo 'paired' data vectors % [t df pvals] = statcond(a); % perform paired t-test % pvals = % 5.2807e-04 % standard t-test probability value % % Note: for different rand() outputs, results will differ. % % [t df pvals surog] = statcond(a, 'mode', 'perm', 'naccu', 2000); % pvals = % 0.0065 % nonparametric t-test using 2000 permuted data sets % % a = { rand(2,11) rand(2,10) rand(2,12)+0.5 }; % pseudo 'unpaired' % [F df pvals] = statcond(a); % perform an unpaired ANOVA % pvals = % 0.00025 % p-values for difference between columns % 0.00002 % for each data row % % a = { rand(3,4,10) rand(3,4,10) rand(3,4,10); ... % rand(3,4,10) rand(3,4,10) rand(3,4,10)+0.5 }; % % pseudo (2,3)-condition data array, each entry containing % % ten (3,4) data matrices % [F df pvals] = statcond(a); % perform a paired 2-way ANOVA % % Output: % pvals{1} % a (3,4) matrix of p-values; effects across columns % pvals{2} % a (3,4) matrix of p-values; effects across rows % pvals{3} % a (3,4) matrix of p-values; interaction effects % % across rows and columns % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005- % With rhanks to Robert Oostenveld for fruitful discussions % and advice on this function. % % See also: anova1_cell(), anova2_cell(), anova2rm_cell, fcdf() % perform a paired t-test % ----------------------- % a = { rand(2,10) rand(2,10) }; % [t df pval] = statcond(a); pval % [h p t stat] = ttest( a{1}(1,:), a{2}(1,:)); p % [h p t stat] = ttest( a{1}(2,:), a{2}(2,:)); p % % compare significance levels % -------------------------- % a = { rand(1,10) rand(1,10) }; % [F df pval] = statcond(a, 'mode', 'perm', 'naccu', 200); pval % [h p t stat] = ttest( a{1}(1,:), a{2}(1,:)); p % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [ ori_vals, df, pvals, surrogval ] = statcond( data, varargin ); if nargin < 1 help statcond; return; end; try, warning('off', 'MATLAB:divideByZero'); catch, end; if exist('finputcheck') g = finputcheck( varargin, { 'naccu' 'integer' [1 Inf] 200; 'mode' 'string' { 'param' 'perm' 'bootstrap' } 'param'; 'paired' 'string' { 'on' 'off' } 'on'; 'arraycomp' 'string' { 'on' 'off' } 'on'; 'variance' 'string' { 'homogenous' 'inhomogenous' } 'homogenous'; 'returnresamplingarray' 'string' { 'on' 'off' } 'off'; 'verbose' 'string' { 'on' 'off' } 'on' }, 'statcond'); if isstr(g), error(g); end; else g = struct(varargin{:}); if ~isfield(g, 'naccu'), g.naccu = 200; end; if ~isfield(g, 'mode'), g.mode = 'param'; end; if ~isfield(g, 'paired'), g.paired = 'on'; end; if ~isfield(g, 'arraycomp'), g.arraycomp = 'on'; end; if ~isfield(g, 'verbose'), g.verbose = 'on'; end; if ~isfield(g, 'variance'), g.variance = 'homogenous'; end; if ~isfield(g, 'returnresamplingarray'), g.returnresamplingarray = 'off'; end; end; if strcmpi(g.verbose, 'on'), verb = 1; else verb = 0; end; if strcmp(g.mode, 'param' ) & exist('fcdf') ~= 2 myfprintf(verb,['statcond(): parametric testing requires fcdf() \n' ... ' from the Matlab StatsticaL Toolbox.\n' ... ' Running nonparametric permutation tests\n.']); g.mode = 'perm'; end if size(data,2) == 1, data = transpose(data); end; % cell array transpose tmpsize = size(data{1}); if ~strcmpi(g.mode, 'param') surrogval = zeros([ tmpsize(1:end-1) g.naccu ], 'single'); else surrogval = []; end; % bootstrap flag % -------------- if strcmpi(g.mode, 'bootstrap'), bootflag = 1; else bootflag = 0; end; % concatenate all data arrays % --------------------------- [ datavals datalen datadims ] = concatdata( data ); % test if data can be paired % -------------------------- if length(unique(cellfun('size', data, ndims(data{1}) ))) > 1 g.paired = 'off'; end; if strcmpi(g.paired, 'on') pairflag = 1; else pairflag = 0; end; % return resampling array % ----------------------- if strcmpi(g.returnresamplingarray, 'on') if strcmpi(g.arraycomp, 'on') ori_vals = supersurrogate( datavals, datalen, datadims, bootflag, pairflag, g.naccu); else ori_vals = surrogate( datavals, datalen, datadims, bootflag, pairflag); end; return; end; % text output % ----------- myfprintf(verb,'%d x %d, ', size(data,1), size(data,2)); if strcmpi(g.paired, 'on') myfprintf(verb,'paired data, '); else myfprintf(verb,'unpaired data, '); end; if size(data,1) == 1 && size(data,2) == 2 myfprintf(verb,'computing T values\n'); else myfprintf(verb,'computing F values\n'); end; if size(data,1) > 1 if strcmpi(g.paired, 'on') myfprintf(verb,'Using 2-way repeated measure ANOVA\n'); else myfprintf(verb,'Using balanced 2-way ANOVA (not suitable for parametric testing, only bootstrap)\n'); end; elseif size(data,2) > 2 if strcmpi(g.paired, 'on') myfprintf(verb,'Using 1-way repeated measure ANOVA\n'); else myfprintf(verb,'Using balanced 1-way ANOVA (equivalent to Matlab anova1)\n'); end; else if strcmpi(g.paired, 'on') myfprintf(verb,'Using paired t-test\n'); else myfprintf(verb,'Using unpaired t-test\n'); end; end; if ~strcmpi(g.mode, 'param') if bootflag, myfprintf(verb,'Bootstraps (of %d):', g.naccu); else myfprintf(verb,'Permutations (of %d):', g.naccu); end; end; if size(data,1) == 1, % only one row if size(data,2) == 2 % paired t-test (very fast) % ------------- tail = 'both'; [ori_vals df] = ttest_cell_select(data, g.paired, g.variance); if strcmpi(g.mode, 'param') pvals = 2*tcdf(-abs(ori_vals), df); pvals = reshape(pvals, size(pvals)); return; else if strcmpi(g.arraycomp, 'on') try myfprintf(verb,'...'); res = supersurrogate( datavals, datalen, datadims, bootflag, pairflag, g.naccu); surrogval = ttest_cell_select( res, g.paired, g.variance); catch, lasterr myfprintf(verb,'\nSuperfast array computation failed because of memory limitation, reverting to standard computation'); g.arraycomp = 'off'; end; end; if strcmpi(g.arraycomp, 'off') for index = 1:g.naccu res = surrogate( datavals, datalen, datadims, bootflag, pairflag); if mod(index, 10) == 0, myfprintf(verb,'%d ', index); end; if mod(index, 100) == 0, myfprintf(verb,'\n'); end; switch myndims(res{1}) case 1 , surrogval(index) = ttest_cell_select(res, g.paired, g.variance); case 2 , surrogval(:,index) = ttest_cell_select(res, g.paired, g.variance); otherwise, surrogval(:,:,index) = ttest_cell_select(res, g.paired, g.variance); end; end; end; end; else % one-way ANOVA (paired) this is equivalent to unpaired t-test % ------------- tail = 'one'; [ori_vals df] = anova1_cell_select( data, g.paired ); if strcmpi(g.mode, 'param') pvals = 1-fcdf(ori_vals, df(1), df(2)); return; else if strcmpi(g.arraycomp, 'on') try myfprintf(verb,'...'); res = supersurrogate( datavals, datalen, datadims, bootflag, pairflag, g.naccu); surrogval = anova1_cell( res ); catch, myfprintf(verb,'\nSuperfast array computation failed because of memory limitation, reverting to standard computing'); g.arraycomp = 'off'; end; end; if strcmpi(g.arraycomp, 'off') for index = 1:g.naccu if mod(index, 10) == 0, myfprintf(verb,'%d ', index); end; if mod(index, 100) == 0, myfprintf(verb,'\n'); end; res = surrogate( datavals, datalen, datadims, bootflag, pairflag); switch myndims(data{1}) case 1 , surrogval(index) = anova1_cell_select( res, g.paired ); case 2 , surrogval(:,index) = anova1_cell_select( res, g.paired ); otherwise, surrogval(:,:,index) = anova1_cell_select( res, g.paired ); end; end; end; end; end; else % two-way ANOVA (paired or unpaired) % ---------------------------------- tail = 'one'; [ ori_vals{1} ori_vals{2} ori_vals{3} df{1} df{2} df{3} ] = anova2_cell_select( data, g.paired ); if strcmpi(g.mode, 'param') pvals{1} = 1-fcdf(ori_vals{1}, df{1}(1), df{1}(2)); pvals{2} = 1-fcdf(ori_vals{2}, df{2}(1), df{2}(2)); pvals{3} = 1-fcdf(ori_vals{3}, df{3}(1), df{3}(2)); return; else surrogval = { surrogval surrogval surrogval }; dataori = data; if strcmpi(g.arraycomp, 'on') try myfprintf(verb,'...'); res = supersurrogate( datavals, datalen, datadims, bootflag, pairflag, g.naccu); [ surrogval{1} surrogval{2} surrogval{3} ] = anova2_cell_select( res, g.paired ); catch, myfprintf(verb,'\nSuperfast array computation failed because of memory limitation, reverting to standard computing'); g.arraycomp = 'off'; end; end; if strcmpi(g.arraycomp, 'off') for index = 1:g.naccu if mod(index, 10) == 0, myfprintf(verb,'%d ', index); end; if mod(index, 100) == 0, myfprintf(verb,'\n'); end; res = surrogate( datavals, datalen, datadims, bootflag, pairflag); switch myndims(data{1}) case 1 , [ surrogval{1}(index) surrogval{2}(index) surrogval{3}(index) ] = anova2_cell_select( res, g.paired ); case 2 , [ surrogval{1}(:,index) surrogval{2}(:,index) surrogval{3}(:,index) ] = anova2_cell_select( res, g.paired ); otherwise, [ surrogval{1}(:,:,index) surrogval{2}(:,:,index) surrogval{3}(:,:,index) ] = anova2_cell_select( res, g.paired ); end; end; end; end; end; myfprintf(verb,'\n'); % compute p-values % ---------------- if iscell( surrogval ) pvals{1} = compute_pvals(surrogval{1}, ori_vals{1}, tail); pvals{2} = compute_pvals(surrogval{2}, ori_vals{2}, tail); pvals{3} = compute_pvals(surrogval{3}, ori_vals{3}, tail); else pvals = compute_pvals(surrogval, ori_vals, tail); end; try, warning('on', 'MATLAB:divideByZero'); catch, end; % compute p-values % ---------------- function pvals = compute_pvals(surrog, oridat, tail) surrog = sort(surrog, myndims(surrog)); % sort last dimension if myndims(surrog) == 1 surrog(end+1) = oridat; elseif myndims(surrog) == 2 surrog(:,end+1) = oridat; elseif myndims(surrog) == 3 surrog(:,:,end+1) = oridat; elseif myndims(surrog) == 4 surrog(:,:,:,end+1) = oridat; else surrog(:,:,:,:,end+1) = oridat; end; [tmp idx] = sort( surrog, myndims(surrog) ); [tmp mx] = max( idx,[], myndims(surrog)); len = size(surrog, myndims(surrog) ); pvals = 1-(mx-0.5)/len; if strcmpi(tail, 'both') pvals = min(pvals, 1-pvals); pvals = 2*pvals; end; function res = supersurrogate(dat, lens, dims, bootstrapflag, pairedflag, naccu); % for increased speed only shuffle half the indices % recompute indices in set and target cell indices % ------------------------------------------------ ncond = length(lens)-1; nsubj = lens(2); if bootstrapflag if pairedflag indswap = mod( repmat([1:lens(end)],[naccu 1]) + ceil(rand(naccu,lens(end))*length(lens))*lens(2)-1, lens(end) )+1; else indswap = ceil(rand(naccu,lens(end))*lens(end)); end; else if pairedflag [tmp idx] = sort(rand(naccu,nsubj,ncond),3); indswap = ((idx)-1)*nsubj + repmat( repmat([1:nsubj], [naccu 1 1]),[1 1 ncond]); indswap = reshape(indswap, [naccu lens(end)]); else [tmp indswap] = sort(rand(naccu, lens(end)),2); end; end; for i = 1:length(lens)-1 switch myndims(dat) case 1, res{i} = reshape(dat(indswap(:,lens(i)+1:lens(i+1))), naccu, lens(i+1)-lens(i)); case 2, res{i} = reshape(dat(:,indswap(:,lens(i)+1:lens(i+1))), size(dat,1), naccu, lens(i+1)-lens(i)); case 3, res{i} = reshape(dat(:,:,indswap(:,lens(i)+1:lens(i+1))), size(dat,1), size(dat,2), naccu, lens(i+1)-lens(i)); case 4, res{i} = reshape(dat(:,:,:,indswap(:,lens(i)+1:lens(i+1))), size(dat,1), size(dat,2), size(dat,3), naccu, lens(i+1)-lens(i)); case 5, res{i} = reshape(dat(:,:,:,:,indswap(:,lens(i)+1:lens(i+1))), size(dat,1), size(dat,2), size(dat,3), size(dat,4), naccu, lens(i+1)-lens(i)); end; end; res = reshape(res, dims); function res = surrogate(dataconcat, lens, dims, bootstrapflag, pairedflag); % for increased speed only shuffle half the indices % recompute indices in set and target cell indices % ------------------------------------------------ if bootstrapflag if pairedflag indswap = mod( [1:lens(end)]+ ceil(rand(1,lens(end))*length(lens))*lens(2)-1, lens(end) )+1; else indswap = ceil(rand(1,lens(end))*lens(end)); end; else if pairedflag indswap = [1:lens(end)]; indswap = reshape(indswap, [lens(2) length(lens)-1]); for i = 1:size(indswap,1) % shuffle each row [tmp idx] = sort(rand(1,size(indswap,2))); indswap(i,:) = indswap(i,idx); end; indswap = reshape(indswap, [1 lens(2)*(length(lens)-1)]); else oriindices = [1:lens(end)]; % just shuffle indices [tmp idx] = sort(rand(1,length(oriindices))); indswap = oriindices(idx); end; end; res = {}; for i = 1:length(lens)-1 switch myndims(dataconcat) case 1, res{i} = dataconcat(indswap(lens(i)+1:lens(i+1))); case 2, res{i} = dataconcat(:,indswap(lens(i)+1:lens(i+1))); case 3, res{i} = dataconcat(:,:,indswap(lens(i)+1:lens(i+1))); case 4, res{i} = dataconcat(:,:,:,indswap(lens(i)+1:lens(i+1))); case 4, res{i} = dataconcat(:,:,:,:,indswap(lens(i)+1:lens(i+1))); end; end; res = reshape(res, dims); % compute ANOVA 2-way % ------------------- function [f1 f2 f3 df1 df2 df3] = anova2_cell_select( res, paired); if strcmpi(paired,'on') [f1 f2 f3 df1 df2 df3] = anova2rm_cell( res ); else [f1 f2 f3 df1 df2 df3] = anova2_cell( res ); end; % compute ANOVA 1-way % ------------------- function [f df] = anova1_cell_select( res, paired); if strcmpi(paired,'on') [f df] = anova1rm_cell( res ); else [f df] = anova1_cell( res ); end; % compute t-test % ------------------- function [t df] = ttest_cell_select( res, paired, homogenous); if strcmpi(paired,'on') [t df] = ttest_cell( res{1}, res{2}); else [t df] = ttest2_cell( res{1}, res{2}, homogenous); end; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end; function myfprintf(verb, varargin) if verb fprintf(varargin{:}); end;
github
BottjerLab/Acoustic_Similarity-master
anova1rm_cell.m
.m
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/anova1rm_cell.m
4,008
utf_8
6d041396c55955b021a3bd629387ab33
% anova1rm_cell() - compute F-values in cell array using repeated measure % ANOVA. % % Usage: % >> [FC dfc] = anova2rm_cell( data ); % % Inputs: % data = data consisting of PAIRED arrays to be compared. The last % dimension of the data array is used to compute ANOVA. % Outputs: % FC - F-value for columns % dfc - degree of freedom for columns % % Note: this function is inspired from rm_anova available at % http://www.mathworks.se/matlabcentral/fileexchange/6874-two-way-rep % eated-measures-anova % % Example: % a = { rand(1,10) rand(1,10) rand(1,10) } % [FC dfc] = anova1rm_cell(a) % signifC = 1-fcdf(FC, dfc(1), dfc(2)) % % % for comparison % [F1 F2 FI df1 df2 dfi] = anova1rm_cell(a); % F2 % % c = { rand(200,400,10) rand(200,400,10) }; % [FC dfc] = anova2rm_cell(c) % computes 200x400 ANOVAs % % Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2010 % Copyright (C) Arnaud Delorme % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [fA dfApair] = anova1rm_cell(data) % compute all means and all std % ----------------------------- a = length(data); nd = myndims( data{1} ); n = size( data{1} ,nd); % only for paired stats % --------------------- if nd == 1 AS = zeros(a,n,'single'); sq = single(0); for ind1 = 1:a AS(ind1,:) = AS(ind1,:) + data{ind1}'; sq = sq + sum(data{ind1}.^2); end; dimA = 2; dimB = 1; elseif nd == 2 AS = zeros(size(data{1},1),a,n,'single'); sq = zeros(size(data{1},1),1,'single'); for ind1 = 1:a AS(:,ind1,:) = AS(:,ind1,:) + reshape(data{ind1},size(data{1},1),1,n); sq = sq + sum(data{ind1}.^2,nd); end; dimA = 3; dimB = 2; elseif nd == 3 AS = zeros(size(data{1},1),size(data{1},2),a,n,'single'); sq = zeros(size(data{1},1),size(data{1},2),'single'); for ind1 = 1:a AS(:,:,ind1,:) = AS(:,:,ind1,:) + reshape(data{ind1},size(data{1},1),size(data{1},2),1,n); sq = sq + sum(data{ind1}.^2,nd); end; dimA = 4; dimB = 3; elseif nd == 4 AS = zeros(size(data{1},1),size(data{1},2),size(data{1},3),a,n,'single'); sq = zeros(size(data{1},1),size(data{1},2),size(data{1},3),'single'); for ind1 = 1:a AS(:,:,:,ind1,:) = AS(:,:,:,ind1,:) + reshape(data{ind1},size(data{1},1),size(data{1},2),size(data{1},3),1,n); sq = sq + sum(data{ind1}.^2,nd); end; dimA = 5; dimB = 4; end; A = sum(AS,dimA); % sum across columns, so result is 1xs row vector S = sum(AS,dimB); % sum across columns, so result is 1xs row vector T = sum(sum(S,dimB),dimA); % could sum either A or B or S, choice is arbitrary % degrees of freedom dfA = a-1; dfAS = (a-1)*(n-1); % bracket terms (expected value) expA = sum(A.^2,dimB)./n; expS = sum(S.^2,dimA)./a; expAS = sum(sum(AS.^2,dimB),dimA); expT = T.^2 / (a*n); % sums of squares ssA = expA - expT; ssAS = expAS - expA - expS + expT; % mean squares msA = ssA / dfA; msAS = ssAS / dfAS; % f statistic fA = msA ./ msAS; dfApair = [dfA dfAS]; function val = myndims(a) if ndims(a) > 2 val = ndims(a); else if size(a,1) == 1, val = 2; elseif size(a,2) == 1, val = 1; else val = 2; end; end;