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
|
GYZHikari/Semantic-Cosegmentation-master
|
getargs.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/getargs.m
| 3,455 |
utf_8
|
de2bab917fa6b9ba3099f1c6b6d68cf0
|
% Utility to process parameter name/value pairs.
%
% DEPRECATED -- ONLY USED BY KMEANS2? SHOULD BE REMOVED.
% USE GETPARAMDEFAULTS INSTEAD.
%
% Based on code fromt Matlab Statistics Toolobox's "private/statgetargs.m"
%
% [EMSG,A,B,...]=GETARGS(PNAMES,DFLTS,'NAME1',VAL1,'NAME2',VAL2,...)
% accepts a cell array PNAMES of valid parameter names, a cell array DFLTS
% of default values for the parameters named in PNAMES, and additional
% parameter name/value pairs. Returns parameter values A,B,... in the same
% order as the names in PNAMES. Outputs corresponding to entries in PNAMES
% that are not specified in the name/value pairs are set to the
% corresponding value from DFLTS. If nargout is equal to length(PNAMES)+1,
% then unrecognized name/value pairs are an error. If nargout is equal to
% length(PNAMES)+2, then all unrecognized name/value pairs are returned in
% a single cell array following any other outputs.
%
% EMSG is empty if the arguments are valid, or the text of an error message
% if an error occurs. GETARGS does not actually throw any errors, but
% rather returns an error message so that the caller may throw the error.
% Outputs will be partially processed after an error occurs.
%
% USAGE
% [emsg,varargout]=getargs(pnames,dflts,varargin)
%
% INPUTS
% pnames - cell of valid parameter names
% dflts - cell of default parameter values
% varargin - list of proposed name / value pairs
%
% OUTPUTS
% emsg - error msg - '' if no error
% varargout - list of assigned name / value pairs
%
% EXAMPLE
% pnames = {'color' 'linestyle', 'linewidth'}; dflts = { 'r','_','1'};
% v = {'linew' 2 'nonesuch' [1 2 3] 'linestyle' ':'};
% [emsg,color,linestyle,linewidth,unrec] = getargs(pnames,dflts,v{:}) % ok
% [emsg,color,linestyle,linewidth] = getargs(pnames,dflts,v{:}) % err
%
% See also GETPARAMDEFAULTS
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [emsg,varargout]=getargs(pnames,dflts,varargin)
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n It will be ' ...
'removed in the next version of the toolbox.'],upper(mfilename));
% We always create (nparams+1) outputs:
% one for emsg
% nparams varargs for values corresponding to names in pnames
% If they ask for one more (nargout == nparams+2), it's for unrecognized
% names/values
emsg = '';
nparams = length(pnames);
varargout = dflts;
unrecog = {};
nargs = length(varargin);
% Must have name/value pairs
if mod(nargs,2)~=0
emsg = sprintf('Wrong number of arguments.');
else
% Process name/value pairs
for j=1:2:nargs
pname = varargin{j};
if ~ischar(pname)
emsg = sprintf('Parameter name must be text.');
break;
end
i = strmatch(lower(pname),lower(pnames));
if isempty(i)
% if they've asked to get back unrecognized names/values, add this
% one to the list
if nargout > nparams+1
unrecog((end+1):(end+2)) = {varargin{j} varargin{j+1}};
% otherwise, it's an error
else
emsg = sprintf('Invalid parameter name: %s.',pname);
break;
end
elseif length(i)>1
emsg = sprintf('Ambiguous parameter name: %s.',pname);
break;
else
varargout{i} = varargin{j+1};
end
end
end
varargout{nparams+1} = unrecog;
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
normxcorrn_fg.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/normxcorrn_fg.m
| 2,699 |
utf_8
|
e65c38d97efb3a624e0fa94a97f75eb6
|
% Normalized n-dimensional cross-correlation with a mask.
%
% Similar to normxcorrn, except takes an additional argument that specifies
% a figure ground mask for the T. That is T_fg must be of the same
% dimensions as T, with each entry being 0 or 1, where zero specifies
% regions to ignore (the ground) and 1 specifies interesting regions (the
% figure). Essentially T_fg specifies regions in T that are interesting
% and should be taken into account when doing normalized cross correlation.
% This allows for templates of arbitrary shape, and not just squares.
%
% Note: this function is approximately 3 times slower then normxcorr2
% because it cannot use the trick of precomputing sums.
%
% USAGE
% C = normxcorrn_fg( T, T_fg, A, [shape] )
%
% INPUTS
% T - template to correlate to each window in A
% T_fg - figure/ground mask for the template
% A - matrix to correlate T to
% shape - ['full'] 'valid', 'full', or 'same', see convn_fast help
%
% OUTPUTS
% C - correlation matrix
%
% EXAMPLE
% A=rand(50); B=rand(11); Bfg=ones(11);
% C1=normxcorrn_fg(B,Bfg,A); C2=normxcorr2(B,A);
% figure(1); im(C1); figure(2); im(C2);
% figure(3); im(abs(C1-C2));
%
% See also NORMXCORRN
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function C = normxcorrn_fg( T, T_fg, A, shape )
if( nargin <4 || isempty(shape)); shape='full'; end;
if( ndims(T)~=ndims(A) || ndims(T)~=ndims(T_fg) )
error('TEMPALTE, T_fg, and A must have same number of dimensions'); end;
if( any(size(T)~=size(T_fg)))
error('TEMPALTE and T_fg must have same dimensions'); end;
if( ~all(T_fg==0 | T_fg==1))
error('T_fg may have only entries either 0 or 1'); end;
nkeep = sum(T_fg(:));
if( nkeep==0); error('T_fg must have some nonzero values'); end;
% center T on 0 and normalize magnitued to 1, excluding ground
% T= (T-T_av) / ||(T-T_av)||
T(T_fg==0)=0;
T = T - sum(T(:)) / nkeep;
T(T_fg==0)=0;
T = T / norm( T(:) );
% flip for convn_fast purposes
for d=1:ndims(T); T = flipdim(T,d); end;
for d=1:ndims(T_fg); T_fg = flipdim(T_fg,d); end;
% get average over each window over A
A_av = convn_fast( A, T_fg/nkeep, shape );
% get magnitude over each window over A "mag(WA-WAav)"
% We can rewrite the above as "sqrt(SUM(WAi^2)-n*WAav^2)". so:
A_mag = convn_fast( A.*A, T_fg, shape ) - nkeep * A_av .* A_av;
A_mag = sqrt(A_mag); A_mag(A_mag<.000001)=1; %removes divide by 0 error
% finally get C. in each image window, we will now do:
% "dot(T,(WA-WAav)) / mag(WA-WAav)"
C = convn_fast(A,T,shape) - A_av*sum(T(:));
C = C ./ A_mag;
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
makemovie.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/makemovie.m
| 1,266 |
utf_8
|
9a03d9a5227c4eaa86520f206ce283e7
|
% [3D] Used to convert a stack of T images into a movie.
%
% To display same data statically use montage.
%
% USAGE
% M = makemovies( IS )
%
% INPUTS
% IS - MxNxT or MxNx1xT or MxNx3xT array of movies.
%
% OUTPUTS
% M - resulting movie
%
% EXAMPLE
% load( 'images.mat' );
% M = makemovie( videos(:,:,:,1) );
% movie( M );
%
% See also MONTAGE2, MAKEMOVIES, PLAYMOVIE, CELL2ARRAY, FEVALARRAYS,
% IMMOVIE, MOVIE2AVI
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function M = makemovie( IS )
% get images format (if image stack is MxNxT convert to MxNx1xT)
if (ndims(IS)==3); IS = permute(IS, [1,2,4,3] ); end
siz = size(IS); nch = siz(3); nd = ndims(IS);
if ( nd~=4 ); error('unsupported dimension of IS'); end
if( nch~=1 && nch~=3 ); error('illegal image stack format'); end;
% normalize for maximum contrast
if( isa(IS,'double') ); IS = IS - min(IS(:)); IS = IS / max(IS(:)); end
% make movie
for i=1:siz(4)
Ii=IS(:,:,:,i);
if( nch==1 ); [Ii,Mi] = gray2ind( Ii ); else Mi=[]; end
if i==1
M=repmat(im2frame( Ii, Mi ),[1,siz(4)]);
else
M(i) = im2frame( Ii, Mi );
end
end
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
localsum_block.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/localsum_block.m
| 815 |
utf_8
|
1216b03a3bd44ff1fc3256de16a2f1c6
|
% Calculates the sum in non-overlapping blocks of I of size dims.
%
% Similar to localsum except gets sum in non-overlapping windows.
% Equivalent to doing localsum, and then subsampling (except more
% efficient).
%
% USAGE
% I = localsum_block( I, dims )
%
% INPUTS
% I - matrix to compute sum over
% dims - size of volume to compute sum over
%
% OUTPUTS
% I - resulting array
%
% EXAMPLE
% load trees; I=ind2gray(X,map);
% I2 = localsum_block( I, 11 );
% figure(1); im(I); figure(2); im(I2);
%
% See also LOCALSUM
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function I = localsum_block( I, dims )
I = nlfiltblock_sep( I, dims, @rnlfiltblock_sum );
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
imrotate2.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/imrotate2.m
| 1,326 |
utf_8
|
bb2ff6c3138ce5f53154d58d7ebc4f31
|
% Custom version of imrotate that demonstrates use of apply_homography.
%
% Works exactly the same as imrotate. For usage see imrotate.
%
% USAGE
% IR = imrotate2( I, angle, [method], [bbox] )
%
% INPUTS
% I - 2D image [converted to double]
% angle - angle to rotate in degrees
% method - ['linear'] 'nearest', 'linear', 'spline', 'cubic'
% bbox - ['loose'] 'loose' or 'crop'
%
% OUTPUTS
% IR - rotated image
%
% EXAMPLE
% load trees;
% tic; X1 = imrotate( X, 55, 'bicubic' ); toc,
% tic; X2 = imrotate2( X, 55, 'bicubic' ); toc
% clf; subplot(2,2,1); im(X); subplot(2,2,2); im(X1-X2);
% subplot(2,2,3); im(X1); subplot(2,2,4); im(X2);
%
% See also IMROTATE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = imrotate2( I, angle, method, bbox )
if( ~isa( I, 'double' ) ); I = double(I); end
if( nargin<3 || isempty(method)); method='linear'; end
if( nargin<4 || isempty(bbox) ); bbox='loose'; end
if( strcmp(method,'bilinear') || strcmp(method,'lin')); method='linear';end
% convert arguments for apply_homography
angle_rads = angle /180 * pi;
R = rotationMatrix( angle_rads );
H = [R [0;0]; 0 0 1];
IR = apply_homography( I, H, method, bbox );
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
imSubsResize.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/imSubsResize.m
| 1,338 |
utf_8
|
cd7dedf790c015adfb1f2d620e9ed82f
|
% Resizes subs by resizVals.
%
% Resizes subs in subs/vals image representation by resizVals.
%
% This essentially replaces each sub by sub.*resizVals. The only subtlety
% is that in images the leftmost sub value is .5, so for example when
% resizing by a factor of 2, the first pixel is replaced by 2 pixels and so
% location 1 in the original image goes to location 1.5 in the second
% image, NOT 2. It may be necessary to round the values afterward.
%
% USAGE
% subs = imSubsResize( subs, resizVals, [zeroPnt] )
%
% INPUTS
% subs - subscripts of point locations (n x d)
% resizVals - k element vector of shrinking factors
% zeroPnt - [.5] See comment above.
%
% OUTPUTS
% subs - transformed subscripts of point locations (n x d)
%
% EXAMPLE
% subs = imSubsResize( [1 1; 2 2], [2 2] )
%
%
% See also IMSUBSTOARRAY
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function subs = imSubsResize( subs, resizVals, zeroPnt )
if( nargin<3 || isempty(zeroPnt) ); zeroPnt=.5; end
[n d] = size(subs);
[resizVals,er] = checkNumArgs( resizVals, [1 d], -1, 2 ); error(er);
% transform subs
resizVals = repmat( resizVals, [n, 1] );
subs = (subs - zeroPnt) .* resizVals + zeroPnt;
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
imtranslate.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/imtranslate.m
| 1,183 |
utf_8
|
054727fb31c105414b655c0f938b6ced
|
% Translate an image to subpixel accuracy.
%
% Note that for subplixel accuracy cannot use nearest neighbor interp.
%
% USAGE
% IR = imtranslate( I, dx, dy, [method], [bbox] )
%
% INPUTS
% I - 2D image [converted to double]
% dx - x translation (right)
% dy - y translation (up)
% method - ['linear'] 'nearest', 'linear', 'spline', 'cubic'
% bbox - ['loose'] 'loose' or 'crop'
%
% OUTPUTS
% IR - translated image
%
% EXAMPLE
% load trees;
% XT = imtranslate(X,0,1.5,'bicubic','crop');
% figure(1); im(X,[0 255]); figure(2); im(XT,[0 255]);
%
% See also IMROTATE2
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = imtranslate( I, dx, dy, method, bbox )
if( ~isa( I, 'double' ) ); I = double(I); end
if( nargin<4 || isempty(method)); method='linear'; end
if( nargin<5 || isempty(bbox) ); bbox='loose'; end
if( strcmp(method,'bilinear') || strcmp(method,'lin')); method='linear';end
% convert arguments for apply_homography
H = [eye(2) [dy; dx]; 0 0 1];
IR = apply_homography( I, H, method, bbox );
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
randperm2.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/randperm2.m
| 1,398 |
utf_8
|
5007722f3d5f5ba7c0f83f32ef8a3a2c
|
% Returns a random permutation of integers.
%
% randperm2(n) is a random permutation of the integers from 1 to n. For
% example, randperm2(6) might be [2 4 5 6 1 3]. randperm2(n,k) is only
% returns the first k elements of the permuation, so for example
% randperm2(6) might be [2 4]. This is a faster version of randperm.m if
% only need first k<<n elements of the random permutation. Also uses less
% random bits (only k). Note that this is an implementation O(k), versus
% the matlab implementation which is O(nlogn), however, in practice it is
% often slower for k=n because it uses a loop.
%
% USAGE
% p = randperm2( n, k )
%
% INPUTS
% n - permute 1:n
% k - keep only first k outputs
%
% OUTPUTS
% p - k length vector of permutations
%
% EXAMPLE
% randperm2(10,5)
%
% See also RANDPERM
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function p = randperm2( n, k )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n RANDSAMPLE is its '...
'recommended replacement.'],upper(mfilename));
p = randsample( n, k );
%if (nargin<2); k=n; else k = min(k,n); end
% p = 1:n;
% for i=1:k
% r = i + floor( (n-i+1)*rand );
% t = p(r); p(r) = p(i); p(i) = t;
% end
% p = p(1:k);
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
apply_homography.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/apply_homography.m
| 3,582 |
utf_8
|
9c3ed72d35b1145f41114e6e6135b44f
|
% Applies the homography defined by H on the image I.
%
% Takes the center of the image as the origin, not the top left corner.
% Also, the coordinate system is row/ column format, so H must be also.
%
% The bounding box of the image is set by the BBOX argument, a string that
% can be 'loose' (default) or 'crop'. When BBOX is 'loose', IR includes the
% whole transformed image, which generally is larger than I. When BBOX is
% 'crop' IR is cropped to include only the central portion of the
% transformed image and is the same size as I. Preserves I's type.
%
% USAGE
% IR = apply_homography( I, H, [method], [bbox], [show] )
%
% INPUTS
% I - input black and white image (2D double or unint8 array)
% H - 3x3 nonsingular homography matrix
% method - ['linear'] for interp2 'nearest','linear','spline','cubic'
% bbox - ['loose'] see above for meaning of bbox 'loose','crop')
% show - [0] figure to use for optional display
%
% OUTPUTS
% IR - result of applying H to I.
%
% EXAMPLE
% load trees; I=X;
% R = rotationMatrix( pi/4 ); T = [1; 3]; H = [R T; 0 0 1];
% IR = apply_homography( I, H, [], 'crop', 1 );
%
% See also TEXTURE_MAP, IMROTATE2
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = apply_homography( I, H, method, bbox, show )
if( ndims(I)~=2 ); error('I must a MxN array'); end;
if(any(size(H)~=[3 3])); error('H must be 3 by 3'); end;
if(rank(H)~=3); error('H must be full rank.'); end;
if( nargin<3 || isempty(method)); method='linear'; end;
if( nargin<4 || isempty(bbox)); bbox='loose'; end;
if( nargin<5 || isempty(show)); show=0; end;
classname = class( I );
if(~strcmp(classname,'double')); I = double(I); end
I = padarray(I,[3,3],eps,'both');
siz = size(I);
% set origin to be center of image
rstart = (-siz(1)+1)/2; rend = (siz(1)-1)/2;
cstart = (-siz(2)+1)/2; cend = (siz(2)-1)/2;
% If 'bbox' then get bounds of resulting image. To do this project the
% original points accoring to the homography and see the bounds. Note
% that since a homography maps a quadrilateral to a quadrilateral only
% need to look at where the bounds of the quadrilateral are mapped to.
% If 'same' then simply use the original image bounds.
if (strcmp(bbox,'loose'))
pr = H * [rstart rend rstart rend; cstart cstart cend cend; 1 1 1 1];
row_dest = pr(1,:) ./ pr(3,:); col_dest = pr(2,:) ./ pr(3,:);
minr = floor(min(row_dest(:))); maxr = ceil(max(row_dest(:)));
minc = floor(min(col_dest(:))); maxc = ceil(max(col_dest(:)));
elseif (strcmp(bbox,'crop'))
minr = rstart; maxr = rend;
minc = cstart; maxc = cend;
else
error('illegal value for bbox');
end;
mrows = maxr-minr+1;
ncols = maxc-minc+1;
% apply inverse homography on meshgrid in destination image
[col_dest_grid,row_dest_grid] = meshgrid( minc:maxc, minr:maxr );
pr = inv(H) * [row_dest_grid(:)'; col_dest_grid(:)'; ones(1,mrows*ncols)];
row_sample_locs = pr(1,:) ./ pr(3,:) + (siz(1)+1)/2;
row_sample_locs = reshape(row_sample_locs,mrows,ncols);
col_sample_locs = pr(2,:) ./ pr(3,:) + (siz(2)+1)/2;
col_sample_locs = reshape(col_sample_locs,mrows,ncols);
% now texture map results
IR = interp2( I, col_sample_locs, row_sample_locs, method );
IR(isnan(IR)) = 0;
IR = arraycrop2dims( IR, size(IR)-6 ); %undo extra padding
if(~strcmp(classname,'double')); IR=feval(classname,IR ); end
% optionally show
if ( show)
I = arraycrop2dims( I, size(IR)-2 );
figure(show); clf; im(I);
figure(show+1); clf; im(IR);
end
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
pca_apply.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/pca_apply.m
| 2,427 |
utf_8
|
0831befb6057f8502bc492227455019a
|
% Companion function to pca.
%
% Use pca to retrieve the principal components U and the mean mu from a
% set fo vectors X1 via [U,mu,vars] = pca(X1). Then given a new
% vector x, use y = pca_apply( x, U, mu, vars, k ) to get the first k
% coefficients of x in the space spanned by the columns of U. See pca for
% general information.
%
% This may prove useful:
% siz = size(X); k = 100;
% Uim = reshape( U(:,1:k), [ siz(1:end-1) k ] );
%
% USAGE
% [ Yk, Xhat, avsq, avsqOrig ] = pca_apply( X, U, mu, vars, k )
%
% INPUTS
% X - array for which to get PCA coefficients
% U - [returned by pca] -- see pca
% mu - [returned by pca] -- see pca
% vars - [returned by pca] -- see pca
% k - number of principal coordinates to approximate X with
%
% OUTPUTS
% Yk - first k coordinates of X in column space of U
% Xhat - approximation of X corresponding to Yk
% avsq - measure of squared error normalized to fall between [0,1]
%
% EXAMPLE
%
% See also PCA, PCA_VISUALIZE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [Yk,Xhat,avsq,avsqOrig] = pca_apply(X,U,mu,vars,k) %#ok<INUSL>
siz = size(X); nd = ndims(X); [N,r] = size(U);
if(N==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
inds = {':'}; inds = inds(:,ones(1,nd-1));
d= prod(siz(1:end-1));
% some error checking
if(d~=N); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if( k>r )
warning(['Only ' int2str(r) '<k comp. available.']); %#ok<WNTAG>
k=r;
end
% subtract mean, then flatten X
Xorig = X;
murep = mu( inds{:}, ones(1,siz(end)));
X = X - murep;
X = reshape(X, d, [] );
% Find Yk, the first k coefficients of X in the new basis
k = min( r, k );
Uk = U(:,1:k);
Yk = Uk' * X;
% calculate Xhat - the approx of X using the first k princ components
if( nargout>1 )
Xhat = Uk * Yk;
Xhat = reshape( Xhat, siz );
Xhat = Xhat + murep;
end
% caclulate average value of (Xhat-Xorig).^2 compared to average value
% of X.^2, where X is Xorig without the mean. This is equivalent to
% what fraction of the variance is captured by Xhat.
if( nargout>2 )
avsq = Xhat - Xorig;
avsq = dot(avsq(:),avsq(:));
avsqOrig = dot(X(:),X(:));
if (nargout==3)
avsq = avsq / avsqOrig;
end
end
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
mode2.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/deprecated/mode2.m
| 731 |
utf_8
|
5c9321ef4b610b4f4a2d43902a68838e
|
% Returns the mode of a vector.
%
% Was mode not part of Matlab before?
%
% USAGE
% y = mode2( x )
%
% INPUTS
% x - vector of integers
%
% OUTPUTS
% y - mode
%
% EXAMPLE
% x = randint2( 1, 10, [1 3] )
% mode(x), mode2( x )
%
% See also MODE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function y = mode2( x )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n MODE is its '...
'recommended replacement.'],upper(mfilename));
y = mode( x );
% [b,i,j] = unique(x);
% [ mval, ind ] = max(hist(j,length(b)));
% y = b(ind);
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
savefig.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/external/other/savefig.m
| 13,459 |
utf_8
|
2b8463f9b01ceb743e440d8fb5755829
|
function savefig(fname, varargin)
% Usage: savefig(filename, fighdl, options)
%
% Saves a pdf, eps, png, jpeg, and/or tiff of the contents of the fighandle's (or current) figure.
% It saves an eps of the figure and the uses Ghostscript to convert to the other formats.
% The result is a cropped, clean picture. There are options for using rgb or cmyk colours,
% or grayscale. You can also choose the resolution.
%
% The advantage of savefig is that there is very little empty space around the figure in the
% resulting files, you can export to more than one format at once, and Ghostscript generates
% trouble-free files.
%
% If you find any errors, please let me know! (peder at axensten dot se)
%
% filename: File name without suffix.
%
% fighdl: (default: gcf) Integer handle to figure.
%
% options: (default: '-r300', '-lossless', '-rgb') You can define your own
% defaults in a global variable savefig_defaults, if you want to, i.e.
% savefig_defaults= {'-r200','-gray'};.
% 'eps': Output in Encapsulated Post Script (no preview yet).
% 'pdf': Output in (Adobe) Portable Document Format.
% 'png': Output in Portable Network Graphics.
% 'jpeg': Output in Joint Photographic Experts Group format.
% 'tiff': Output in Tagged Image File Format (no compression: huge files!).
% '-rgb': Output in rgb colours.
% '-cmyk': Output in cmyk colours (not yet 'png' or 'jpeg' -- '-rgb' is used).
% '-gray': Output in grayscale (not yet 'eps' -- '-rgb' is used).
% '-fonts': Include fonts in eps or pdf. Includes only the subset needed.
% '-lossless': Use lossless compression, works on most formats. same as '-c0', below.
% '-c<float>': Set compression for non-indexed bitmaps in PDFs -
% 0: lossless; 0.1: high quality; 0.5: medium; 1: high compression.
% '-r<integer>': Set resolution.
% '-crop': Removes points and line segments outside the viewing area -- permanently.
% Only use this on figures where many points and/or line segments are outside
% the area zoomed in to. This option will result in smaller vector files (has no
% effect on pixel files).
% '-dbg': Displays gs command line(s).
%
% EXAMPLE:
% savefig('nicefig', 'pdf', 'jpeg', '-cmyk', '-c0.1', '-r250');
% Saves the current figure to nicefig.pdf and nicefig.png, both in cmyk and at 250 dpi,
% with high quality lossy compression.
%
% REQUIREMENT: Ghostscript. Version 8.57 works, probably older versions too, but '-dEPSCrop'
% must be supported. I think version 7.32 or newer is ok.
%
% HISTORY:
% Version 1.0, 2006-04-20.
% Version 1.1, 2006-04-27:
% - No 'epstopdf' stuff anymore! Using '-dEPSCrop' option in gs instead!
% Version 1.2, 2006-05-02:
% - Added a '-dbg' option (see options, above).
% - Now looks for a global variable 'savefig_defaults' (see options, above).
% - More detailed Ghostscript options (user will not really notice).
% - Warns when there is no device for a file-type/color-model combination.
% Version 1.3, 2006-06-06:
% - Added a check to see if there actually is a figure handle.
% - Now works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
% - Now compatible with Ghostscript 8.54, released 2006-06-01.
% Version 1.4, 2006-07-20:
% - Added an option '-soft' that enables anti-aliasing on pixel graphics (on by default).
% - Added an option '-hard' that don't do anti-aliasing on pixel graphics.
% Version 1.5, 2006-07-27:
% - Fixed a bug when calling with a figure handle argument.
% Version 1.6, 2006-07-28:
% - Added a crop option, see above.
% Version 1.7, 2007-03-31:
% - Fixed bug: calling print with invalid renderer value '-none'.
% - Removed GhostScript argument '-dUseCIEColor' as it sometimes discoloured things.
% Version 1.8, 2008-01-03:
% - Added MacIntel: 'MACI'.
% - Added 64bit PC (I think, can't test it myself).
% - Added option '-nointerpolate' (use it to prevent blurring of pixelated).
% - Removed '-hard' and '-soft'. Use '-nointerpolate' for '-hard', default for '-soft'.
% - Fixed the gs 8.57 warning on UseCIEColor (it's now set).
% - Added '-gray' for pdf, but gs 8.56 or newer is needed.
% - Added '-gray' and '-cmyk' for eps, but you a fairly recent gs might be needed.
% Version 1.9, 2008-07-27:
% - Added lossless compression, see option '-lossless', above. Works on most formats.
% - Added lossy compression, see options '-c<float>...', above. Works on 'pdf'.
% Thanks to Olly Woodford for idea and implementation!
% - Removed option '-nointerpolate' -- now savefig never interpolates.
% - Fixed a few small bugs and removed some mlint comments.
% Version 2.0, 2008-11-07:
% - Added the possibility to include fonts into eps or pdf.
%
% TO DO: (Need Ghostscript support for these, so don't expect anything soon...)
% - svg output.
% - '-cmyk' for 'jpeg' and 'png'.
% - Preview in 'eps'.
% - Embedded vector fonts, not bitmap, in 'eps'.
%
% Copyright (C) Peder Axensten (peder at axensten dot se), 2006.
% KEYWORDS: eps, pdf, jpg, jpeg, png, tiff, eps2pdf, epstopdf, ghostscript
%
% INSPIRATION: eps2pdf (5782), eps2xxx (6858)
%
% REQUIREMENTS: Works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
op_dbg= false; % Default value.
% Compression
compr= [' -dUseFlateCompression=true -dLZWEncodePages=true -dCompatibilityLevel=1.6' ...
' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false ' ...
' -dColorImageFilter=%s -dGrayImageFilter=%s']; % Compression.
lossless= sprintf (compr, '/FlateEncode', '/FlateEncode');
lossy= sprintf (compr, '/DCTEncode', '/DCTEncode' );
lossy= [lossy ' -c ".setpdfwrite << /ColorImageDict << /QFactor %g ' ...
'/Blend 1 /HSample [%s] /VSample [%s] >> >> setdistillerparams"'];
% Create gs command.
cmdEnd= ' -sDEVICE=%s -sOutputFile="%s"'; % Essential.
epsCmd= '';
epsCmd= [epsCmd ' -dSubsetFonts=true -dNOPLATFONTS']; % Future support?
epsCmd= [epsCmd ' -dUseCIEColor=true -dColorConversionStrategy=/UseDeviceIndependentColor'];
epsCmd= [epsCmd ' -dProcessColorModel=/%s']; % Color conversion.
pdfCmd= [epsCmd ' -dAntiAliasColorImages=false' cmdEnd];
epsCmd= [epsCmd cmdEnd];
% Get file name.
if((nargin < 1) || isempty(fname) || ~ischar(fname)) % Check file name.
error('No file name specified.');
end
[pathstr, namestr] = fileparts(fname);
if(isempty(pathstr)), fname= fullfile(cd, namestr); end
% Get handle.
fighdl= get(0, 'CurrentFigure'); % See gcf. % Get figure handle.
if((nargin >= 2) && (numel(varargin{1}) == 1) && isnumeric(varargin{1}))
fighdl= varargin{1};
varargin= {varargin{2:end}};
end
if(isempty(fighdl)), error('There is no figure to save!?'); end
set(fighdl, 'Units', 'centimeters') % Set paper stuff.
sz= get(fighdl, 'Position');
sz(1:2)= 0;
set(fighdl, 'PaperUnits', 'centimeters', 'PaperSize', sz(3:4), 'PaperPosition', sz);
% Set up the various devices.
% Those commented out are not yet supported by gs (nor by savefig).
% pdf-cmyk works due to the Matlab '-cmyk' export being carried over from eps to pdf.
device.eps.rgb= sprintf(epsCmd, 'DeviceRGB', 'epswrite', [fname '.eps']);
device.jpeg.rgb= sprintf(cmdEnd, 'jpeg', [fname '.jpeg']);
% device.jpeg.cmyk= sprintf(cmdEnd, 'jpegcmyk', [fname '.jpeg']);
device.jpeg.gray= sprintf(cmdEnd, 'jpeggray', [fname '.jpeg']);
device.pdf.rgb= sprintf(pdfCmd, 'DeviceRGB', 'pdfwrite', [fname '.pdf']);
device.pdf.cmyk= sprintf(pdfCmd, 'DeviceCMYK', 'pdfwrite', [fname '.pdf']);
device.pdf.gray= sprintf(pdfCmd, 'DeviceGray', 'pdfwrite', [fname '.pdf']);
device.png.rgb= sprintf(cmdEnd, 'png16m', [fname '.png']);
% device.png.cmyk= sprintf(cmdEnd, 'png???', [fname '.png']);
device.png.gray= sprintf(cmdEnd, 'pnggray', [fname '.png']);
device.tiff.rgb= sprintf(cmdEnd, 'tiff24nc', [fname '.tiff']);
device.tiff.cmyk= sprintf(cmdEnd, 'tiff32nc', [fname '.tiff']);
device.tiff.gray= sprintf(cmdEnd, 'tiffgray', [fname '.tiff']);
% Get options.
global savefig_defaults; % Add global defaults.
if( iscellstr(savefig_defaults)), varargin= {savefig_defaults{:}, varargin{:}};
elseif(ischar(savefig_defaults)), varargin= {savefig_defaults, varargin{:}};
end
varargin= {'-r300', '-lossless', '-rgb', varargin{:}}; % Add defaults.
res= '';
types= {};
fonts= 'false';
crop= false;
for n= 1:length(varargin) % Read options.
if(ischar(varargin{n}))
switch(lower(varargin{n}))
case {'eps','jpeg','pdf','png','tiff'}, types{end+1}= lower(varargin{n});
case '-rgb', color= 'rgb'; deps= {'-depsc2'};
case '-cmyk', color= 'cmyk'; deps= {'-depsc2', '-cmyk'};
case '-gray', color= 'gray'; deps= {'-deps2'};
case '-fonts', fonts= 'true';
case '-lossless', comp= 0;
case '-crop', crop= true;
case '-dbg', op_dbg= true;
otherwise
if(regexp(varargin{n}, '^\-r[0-9]+$')), res= varargin{n};
elseif(regexp(varargin{n}, '^\-c[0-9.]+$')), comp= str2double(varargin{n}(3:end));
else warning('pax:savefig:inputError', 'Unknown option in argument: ''%s''.', varargin{n});
end
end
else
warning('pax:savefig:inputError', 'Wrong type of argument: ''%s''.', class(varargin{n}));
end
end
types= unique(types);
if(isempty(types)), error('No output format given.'); end
if (comp == 0) % Lossless compression
gsCompr= lossless;
elseif (comp <= 0.1) % High quality lossy
gsCompr= sprintf(lossy, comp, '1 1 1 1', '1 1 1 1');
else % Normal lossy
gsCompr= sprintf(lossy, comp, '2 1 1 2', '2 1 1 2');
end
% Generate the gs command.
switch(computer) % Get gs command.
case {'MAC','MACI'}, gs= '/usr/local/bin/gs';
case {'PCWIN'}, gs= 'gswin32c.exe';
case {'PCWIN64'}, gs= 'gswin64c.exe';
otherwise, gs= 'gs';
end
gs= [gs ' -q -dNOPAUSE -dBATCH -dEPSCrop']; % Essential.
gs= [gs ' -dPDFSETTINGS=/prepress -dEmbedAllFonts=' fonts]; % Must be first?
gs= [gs ' -dUseFlateCompression=true']; % Useful stuff.
gs= [gs ' -dAutoRotatePages=/None']; % Probably good.
gs= [gs ' -dHaveTrueTypes']; % Probably good.
gs= [gs ' ' res]; % Add resolution to cmd.
if(crop && ismember(types, {'eps', 'pdf'})) % Crop the figure.
fighdl= do_crop(fighdl);
end
% Output eps from Matlab.
renderer= ['-' lower(get(fighdl, 'Renderer'))]; % Use same as in figure.
if(strcmpi(renderer, '-none')), renderer= '-painters'; end % We need a valid renderer.
deps = [deps '-loose']; % added by PPD seems to help w cropping in matlab 2014b :(
print(fighdl, deps{:}, '-noui', renderer, res, [fname '-temp']); % Output the eps.
% Convert to other formats.
for n= 1:length(types) % Output them.
if(isfield(device.(types{n}), color))
cmd= device.(types{n}).(color); % Colour model exists.
else
cmd= device.(types{n}).rgb; % Use alternative.
if(~strcmp(types{n}, 'eps')) % It works anyways for eps (VERY SHAKY!).
warning('pax:savefig:deviceError', ...
'No device for %s using %s. Using rgb instead.', types{n}, color);
end
end
cmp= lossless;
if (strcmp(types{n}, 'pdf')), cmp= gsCompr; end % Lossy compr only for pdf.
if (strcmp(types{n}, 'eps')), cmp= ''; end % eps can't use lossless.
cmd= sprintf('%s %s %s -f "%s-temp.eps"', gs, cmd, cmp, fname);% Add up.
status= system(cmd); % Run Ghostscript.
if (op_dbg || status), display (cmd), end
end
delete([fname '-temp.eps']); % Clean up.
end
function fig= do_crop(fig)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Remove line segments that are outside the view.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
haxes= findobj(fig, 'Type', 'axes', '-and', 'Tag', '');
for n=1:length(haxes)
xl= get(haxes(n), 'XLim');
yl= get(haxes(n), 'YLim');
lines= findobj(haxes(n), 'Type', 'line');
for m=1:length(lines)
x= get(lines(m), 'XData');
y= get(lines(m), 'YData');
inx= (xl(1) <= x) & (x <= xl(2)); % Within the x borders.
iny= (yl(1) <= y) & (y <= yl(2)); % Within the y borders.
keep= inx & iny; % Within the box.
if(~strcmp(get(lines(m), 'LineStyle'), 'none'))
crossx= ((x(1:end-1) < xl(1)) & (xl(1) < x(2:end))) ... % Crossing border x1.
| ((x(1:end-1) < xl(2)) & (xl(2) < x(2:end))) ... % Crossing border x2.
| ((x(1:end-1) > xl(1)) & (xl(1) > x(2:end))) ... % Crossing border x1.
| ((x(1:end-1) > xl(2)) & (xl(2) > x(2:end))); % Crossing border x2.
crossy= ((y(1:end-1) < yl(1)) & (yl(1) < y(2:end))) ... % Crossing border y1.
| ((y(1:end-1) < yl(2)) & (yl(2) < y(2:end))) ... % Crossing border y2.
| ((y(1:end-1) > yl(1)) & (yl(1) > y(2:end))) ... % Crossing border y1.
| ((y(1:end-1) > yl(2)) & (yl(2) > y(2:end))); % Crossing border y2.
crossp= [( (crossx & iny(1:end-1) & iny(2:end)) ... % Crossing a x border within y limits.
| (crossy & inx(1:end-1) & inx(2:end)) ... % Crossing a y border within x limits.
| crossx & crossy ... % Crossing a x and a y border (corner).
), false ...
];
crossp(2:end)= crossp(2:end) | crossp(1:end-1); % Add line segment's secont end point.
keep= keep | crossp;
end
set(lines(m), 'XData', x(keep))
set(lines(m), 'YData', y(keep))
end
end
end
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
dirSynch.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/matlab/dirSynch.m
| 4,570 |
utf_8
|
d288299d31d15f1804183206d0aa0227
|
function dirSynch( root1, root2, showOnly, flag, ignDate )
% Synchronize two directory trees (or show differences between them).
%
% If a file or directory 'name' is found in both tree1 and tree2:
% 1) if 'name' is a file in both the pair is considered the same if they
% have identical size and identical datestamp (or if ignDate=1).
% 2) if 'name' is a directory in both the dirs are searched recursively.
% 3) if 'name' is a dir in root1 and a file in root2 (or vice-versa)
% synchronization cannot proceed (an error is thrown).
% If 'name' is found only in root1 or root2 it's a difference between them.
%
% The parameter flag controls how synchronization occurs:
% flag==0: neither tree1 nor tree2 has preference (newer file is kept)
% flag==1: tree2 is altered to reflect tree1 (tree1 is unchanged)
% flag==2: tree1 is altered to reflect tree2 (tree2 is unchanged)
% Run with showOnly=1 and different values of flag to see its effect.
%
% By default showOnly==1. If showOnly, displays a list of actions that need
% to be performed in order to synchronize the two directory trees, but does
% not actually perform the actions. It is highly recommended to run
% dirSynch first with showOnly=1 before running it with showOnly=0.
%
% USAGE
% dirSynch( root1, root2, [showOnly], [flag], [ignDate] )
%
% INPUTS
% root1 - root directory of tree1
% root2 - root directory of tree2
% showOnly - [1] show but do NOT perform actions
% flag - [0] 0: synchronize; 1: set root2=root1; 2: set root1==root2
% ignDate - [0] if true considers two files same even if have diff dates
%
% OUTPUTS
% dirSynch( 'c:\toolbox', 'c:\toolbox-old', 1 )
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 2.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if(nargin<3 || isempty(showOnly)), showOnly=1; end;
if(nargin<4 || isempty(flag)), flag=0; end;
if(nargin<5 || isempty(ignDate)), ignDate=0; end;
% get differences between root1/root2 and loop over them
D = dirDiff( root1, root2, ignDate );
roots={root1,root2}; ticId = ticStatus;
for i=1:length(D)
% get action
if( flag==1 )
if( D(i).in1 ), act=1; src1=1; else act=0; src1=2; end
elseif( flag==2 )
if( D(i).in2 ), act=1; src1=2; else act=0; src1=1; end
else
act=1;
if(D(i).in1 && D(i).in2)
if( D(i).new1 ), src1=1; else src1=2; end
else
if( D(i).in1 ), src1=1; else src1=2; end
end
end
src2=mod(src1,2)+1;
% perform action
if( act==1 )
if( showOnly )
disp(['COPY ' int2str(src1) '->' int2str(src2) ': ' D(i).name]);
else
copyfile( [roots{src1} D(i).name], [roots{src2} D(i).name], 'f' );
end;
else
if( showOnly )
disp(['DEL in ' int2str(src1) ': ' D(i).name]);
else
fName = [roots{src1} D(i).name];
if(D(i).isdir), rmdir(fName,'s'); else delete(fName); end
end
end
if(~showOnly), tocStatus( ticId, i/length(D) ); end;
end
end
function D = dirDiff( root1, root2, ignDate )
% get differences from root1 to root2
D1 = dirDiff1( root1, root2, ignDate, '/' );
% get differences from root2 to root1
D2 = dirDiff1( root2, root1, ignDate, '/' );
% remove duplicates (arbitrarily from D2)
D2=D2(~([D2.in1] & [D2.in2]));
% swap 1 and 2 in D2
for i=1:length(D2),
D2(i).in1=0; D2(i).in2=1; D2(i).new1=~D2(i).new1;
end
% merge
D = [D1 D2];
end
function D = dirDiff1( root1, root2, ignDate, subdir )
if(root1(end)~='/'), root1(end+1)='/'; end
if(root2(end)~='/'), root2(end+1)='/'; end
if(subdir(end)~='/'), subdir(end+1)='/'; end
fs1=dir([root1 subdir]); fs2=dir([root2 subdir]);
D=struct('name',0,'isdir',0,'in1',0,'in2',0,'new1',0);
D=repmat(D,[1 length(fs1)]); n=0; names2={fs2.name}; Dsub=[];
for i1=1:length( fs1 )
name=fs1(i1).name; isdir=fs1(i1).isdir;
if( any(strcmp(name,{'.','..'})) ), continue; end;
i2 = find(strcmp(name,names2));
if(~isempty(i2) && isdir)
% cannot handle this condition
if(~fs2(i2).isdir), disp([root1 subdir name]); assert(false); end;
% recurse and record possible differences
Dsub=[Dsub dirDiff1(root1,root2,ignDate,[subdir name])]; %#ok<AGROW>
elseif( ~isempty(i2) && fs1(i1).bytes==fs2(i2).bytes && ...
(ignDate || fs1(i1).datenum==fs2(i2).datenum))
% nothing to do - files are same
continue;
else
% record differences
n=n+1;
D(n).name=[subdir name]; D(n).isdir=isdir;
D(n).in1=1; D(n).in2=~isempty(i2);
D(n).new1 = ~D(n).in2 || (fs1(i1).datenum>fs2(i2).datenum);
end
end
D = [D(1:n) Dsub];
end
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
plotRoc.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/matlab/plotRoc.m
| 5,212 |
utf_8
|
008f9c63073c6400c4960e9e213c47e5
|
function [h,miss,stds] = plotRoc( D, varargin )
% Function for display of rocs (receiver operator characteristic curves).
%
% Display roc curves. Consistent usage ensures uniform look for rocs. The
% input D should have n rows, each of which is of the form:
% D = [falsePosRate truePosRate]
% D is generated, for example, by scanning a detection threshold over n
% values from 0 (so first entry is [1 1]) to 1 (so last entry is [0 0]).
% Alternatively D can be a cell vector of rocs, in which case an average
% ROC will be shown with error bars. Plots missRate (which is just 1 minus
% the truePosRate) on the y-axis versus the falsePosRate on the x-axis.
%
% USAGE
% [h,miss,stds] = plotRoc( D, prm )
%
% INPUTS
% D - [nx2] n data points along roc [falsePosRate truePosRate]
% typically ranges from [1 1] to [0 0] (or may be reversed)
% prm - [] param struct
% .color - ['g'] color for curve
% .lineSt - ['-'] linestyle (see LineSpec)
% .lineWd - [4] curve width
% .logx - [0] use logarithmic scale for x-axis
% .logy - [0] use logarithmic scale for y-axis
% .marker - [''] marker type (see LineSpec)
% .mrkrSiz - [12] marker size
% .nMarker - [5] number of markers (regularly spaced) to display
% .lims - [0 1 0 1] axes limits
% .smooth - [0] if T compute lower envelop of roc to smooth staircase
% .fpTarget - [] return miss rates at given fp values (and draw lines)
% .xLbl - ['false positive rate'] label for x-axis
% .yLbl - ['miss rate'] label for y-axis
%
% OUTPUTS
% h - plot handle for use in legend only
% miss - average miss rates at fpTarget reference values
% stds - standard deviation of miss rates at fpTarget reference values
%
% EXAMPLE
% k=2; x=0:.0001:1; data1 = [1-x; (1-x.^k).^(1/k)]';
% k=3; x=0:.0001:1; data2 = [1-x; (1-x.^k).^(1/k)]';
% hs(1)=plotRoc(data1,struct('color','g','marker','s'));
% hs(2)=plotRoc(data2,struct('color','b','lineSt','--'));
% legend( hs, {'roc1','roc2'} ); xlabel('fp'); ylabel('fn');
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.02
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get params
[color,lineSt,lineWd,logx,logy,marker,mrkrSiz,nMarker,lims,smooth, ...
fpTarget,xLbl,yLbl] = getPrmDflt( varargin, {'color' 'g' 'lineSt' '-' ...
'lineWd' 4 'logx' 0 'logy' 0 'marker' '' 'mrkrSiz' 12 'nMarker' 5 ...
'lims' [] 'smooth' 0 'fpTarget' [] 'xLbl' 'false positive rate' ...
'yLbl' 'miss rate' } );
if( isempty(lims) ); lims=[logx*1e-5 1 logy*1e-5 1]; end
% ensure descending fp rate, change to miss rate, optionally 'nicefy' roc
if(~iscell(D)), D={D}; end; nD=length(D);
for j=1:nD, assert(size(D{j},2)==2); end
for j=1:nD, if(D{j}(1,2)<D{j}(end,2)), D{j}=flipud(D{j}); end; end
for j=1:nD, D{j}(:,2)=1-D{j}(:,2); assert(all(D{j}(:,2)>=0)); end
if(smooth), for j=1:nD, D{j}=smoothRoc(D{j}); end; end
% plot: (1) h for legend only, (2) markers, (3) error bars, (4) roc curves
hold on; axis(lims); xlabel(xLbl); ylabel(yLbl);
prmMrkr = {'MarkerSize',mrkrSiz,'MarkerFaceColor',color};
prmClr={'Color',color}; prmPlot = [prmClr,{'LineWidth',lineWd}];
h = plot( 2, 0, [lineSt marker], prmMrkr{:}, prmPlot{:} ); %(1)
DQ = quantizeRocs( D, nMarker, logx, lims ); DQm=mean(DQ,3);
if(~isempty(marker))
plot(DQm(:,1),DQm(:,2),marker,prmClr{:},prmMrkr{:} ); end %(2)
if(nD>1), DQs=std(DQ,0,3);
errorbar(DQm(:,1),DQm(:,2),DQs(:,2),'.',prmClr{:}); end %(3)
if(nD==1), DQ=D{1}; else DQ=quantizeRocs(D,100,logx,lims); end
DQm = mean(DQ,3); plot( DQm(:,1), DQm(:,2), lineSt, prmPlot{:} ); %(4)
% plot line at given fp rate
m=length(fpTarget); miss=zeros(1,m); stds=miss;
if( m>0 )
assert( min(DQm(:,1))<=min(fpTarget) ); DQs=std(DQ,0,3);
for i=1:m, j=find(DQm(:,1)<=fpTarget(i)); j=j(1);
miss(i)=DQm(j,2); stds(i)=DQs(j,2); end
fp=min(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]);
fp=max(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]);
end
% set log axes
if( logx==1 )
ticks=10.^(-8:8);
set(gca,'XScale','log','XTick',ticks);
end
if( logy==1 )
ticks=[.001 .002 .005 .01 .02 .05 .1 .2 .5 1];
set(gca,'YScale','log','YTick',ticks);
end
if( logx==1 || logy==1 ), grid on;
set(gca,'XMinorGrid','off','XMinorTic','off');
set(gca,'YMinorGrid','off','YMinorTic','off');
end
end
function DQ = quantizeRocs( Ds, nPnts, logx, lims )
% estimate miss rate at each target fp rate
nD=length(Ds); DQ=zeros(nPnts,2,nD);
if(logx==1), fps=logspace(log10(lims(1)),log10(lims(2)),nPnts);
else fps=linspace(lims(1),lims(2),nPnts); end; fps=flipud(fps');
for j=1:nD, D=[Ds{j}; 0 1]; k=1; fp=D(k,1);
for i=1:nPnts
while( k<size(D,1) && fp>=fps(i) ), k=k+1; fp=D(k,1); end
k0=max(k-1,1); fp0=D(k0,1); assert(fp0>=fp);
if(fp0==fp), r=.5; else r=(fps(i)-fp)/(fp0-fp); end
DQ(i,1,j)=fps(i); DQ(i,2,j)=r*D(k0,2)+(1-r)*D(k,2);
end
end
end
function D1 = smoothRoc( D )
D1 = zeros(size(D));
n = size(D,1); cnt=0;
for i=1:n
isAnkle = (i==1) || (i==n);
if( ~isAnkle )
dP=D1(cnt,:); dC=D(i,:); dN=D(i+1,:);
isAnkle = (dC(1)~=dP(1)) && (dC(2)~=dN(2));
end
if(isAnkle); cnt=cnt+1; D1(cnt,:)=D(i,:); end
end
D1=D1(1:cnt,:);
end
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
simpleCache.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/matlab/simpleCache.m
| 4,098 |
utf_8
|
92df86b0b7e919c9a26388e598e4d370
|
function varargout = simpleCache( op, cache, varargin )
% A simple cache that can be used to store results of computations.
%
% Can save and retrieve arbitrary values using a vector (includnig char
% vectors) as a key. Especially useful if a function must perform heavy
% computation but is often called with the same inputs (for which it will
% give the same outputs). Note that the current implementation does a
% linear search for the key (a more refined implementation would use a hash
% table), so it is not meant for large scale usage.
%
% To use inside a function, make the cache persistent:
% persistent cache; if( isempty(cache) ) cache=simpleCache('init'); end;
% The following line, when placed inside a function, means the cache will
% stay in memory until the matlab environment changes. For an example
% usage see maskGaussians.
%
% USAGE - 'init': initialize a cache object
% cache = simpleCache('init');
%
% USAGE - 'put': put something in cache. key must be a numeric vector
% cache = simpleCache( 'put', cache, key, val );
%
% USAGE - 'get': retrieve from cache. found==1 if obj was found
% [found,val] = simpleCache( 'get', cache, key );
%
% USAGE - 'remove': free key
% [cache,found] = simpleCache( 'remove', cache, key );
%
% INPUTS
% op - 'init', 'put', 'get', 'remove'
% cache - the cache object being operated on
% varargin - see USAGE above
%
% OUTPUTS
% varargout - see USAGE above
%
% EXAMPLE
% cache = simpleCache('init');
% hellokey=rand(1,3); worldkey=rand(1,11);
% cache = simpleCache( 'put', cache, hellokey, 'hello' );
% cache = simpleCache( 'put', cache, worldkey, 'world' );
% [f,v]=simpleCache( 'get', cache, hellokey ); disp(v);
% [f,v]=simpleCache( 'get', cache, worldkey ); disp(v);
%
% See also PERSISTENT, MASKGAUSSIANS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
switch op
case 'init' % init a cache
cacheSiz = 8;
cache.freeinds = 1:cacheSiz;
cache.keyns = -ones(1,cacheSiz);
cache.keys = cell(1,cacheSiz);
cache.vals = cell(1,cacheSiz);
varargout = {cache};
case 'put' % a put operation
key=varargin{1}; val=varargin{2};
cache = cacheput( cache, key, val );
varargout = {cache};
case 'get' % a get operation
key=varargin{1};
[ind,val] = cacheget( cache, key );
found = ind>0;
varargout = {found,val};
case 'remove' % a remove operation
key=varargin{1};
[cache,found] = cacheremove( cache, key );
varargout = {cache,found};
otherwise
error('Unknown cache operation: %s',op);
end
end
function cache = cachegrow( cache )
% double cache size
cacheSiz = length( cache.keyns );
if( cacheSiz>64 ) % warn if getting big
warning(['doubling cache size to: ' int2str2(cacheSiz*2)]);%#ok<WNTAG>
end
cache.freeinds = [cache.freeinds (cacheSiz+1):(2*cacheSiz)];
cache.keyns = [cache.keyns -ones(1,cacheSiz)];
cache.keys = [cache.keys cell(1,cacheSiz)];
cache.vals = [cache.vals cell(1,cacheSiz)];
end
function cache = cacheput( cache, key, val )
% put something into the cache
% get location to place
ind = cacheget( cache, key ); % see if already in cache
if( ind==-1 )
if( isempty( cache.freeinds ) )
cache = cachegrow( cache ); %grow cache
end
ind = cache.freeinds(1); % get new cache loc
cache.freeinds = cache.freeinds(2:end);
end
% now simply place in ind
cache.keyns(ind) = length(key);
cache.keys{ind} = key;
cache.vals{ind} = val;
end
function [ind,val] = cacheget( cache, key )
% get cache element, or fail
cacheSiz = length( cache.keyns );
keyn = length( key );
for i=1:cacheSiz
if(keyn==cache.keyns(i) && all(key==cache.keys{i}))
val = cache.vals{i}; ind = i; return; end
end
ind=-1; val=-1;
end
function [cache,found] = cacheremove( cache, key )
% get cache element, or fail
ind = cacheget( cache, key );
found = ind>0;
if( found )
cache.freeinds = [ind cache.freeinds];
cache.keyns(ind) = -1;
cache.keys{ind} = [];
cache.vals{ind} = [];
end
end
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
tpsInterpolate.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_toolbox/matlab/tpsInterpolate.m
| 1,646 |
utf_8
|
d3bd3a26d048f32cfdc17884ccae6d8c
|
function [xsR,ysR] = tpsInterpolate( warp, xs, ys, show )
% Apply warp (obtained by tpsGetWarp) to a set of new points.
%
% USAGE
% [xsR,ysR] = tpsInterpolate( warp, xs, ys, [show] )
%
% INPUTS
% warp - [see tpsGetWarp] bookstein warping parameters
% xs, ys - points to apply warp to
% show - [1] will display results in figure(show)
%
% OUTPUTS
% xsR, ysR - result of warp applied to xs, ys
%
% EXAMPLE
%
% See also TPSGETWARP
%
% 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<4 || isempty(show)); show = 1; end
wx = warp.wx; affinex = warp.affinex;
wy = warp.wy; affiney = warp.affiney;
xsS = warp.xsS; ysS = warp.ysS;
xsD = warp.xsD; ysD = warp.ysD;
% interpolate points (xs,ys)
xsR = f( wx, affinex, xsS, ysS, xs(:)', ys(:)' );
ysR = f( wy, affiney, xsS, ysS, xs(:)', ys(:)' );
% optionally show points (xsR, ysR)
if( show )
figure(show);
subplot(2,1,1); plot( xs, ys, '.', 'color', [0 0 1] );
hold('on'); plot( xsS, ysS, '+' ); hold('off');
subplot(2,1,2); plot( xsR, ysR, '.' );
hold('on'); plot( xsD, ysD, '+' ); hold('off');
end
function zs = f( w, aff, xsS, ysS, xs, ys )
% find f(x,y) for xs and ys given W and original points
n = size(w,1); ns = size(xs,2);
delXs = xs'*ones(1,n) - ones(ns,1)*xsS;
delYs = ys'*ones(1,n) - ones(ns,1)*ysS;
distSq = (delXs .* delXs + delYs .* delYs);
distSq = distSq + eye(size(distSq)) + eps;
U = distSq .* log( distSq ); U( isnan(U) )=0;
zs = aff(1)*ones(ns,1)+aff(2)*xs'+aff(3)*ys';
zs = zs + sum((U.*(ones(ns,1)*w')),2);
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
checkNumArgs.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_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
|
GYZHikari/Semantic-Cosegmentation-master
|
fevalDistr.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_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
|
GYZHikari/Semantic-Cosegmentation-master
|
medfilt1m.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_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
|
GYZHikari/Semantic-Cosegmentation-master
|
FbMake.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/pdollar_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
|
GYZHikari/Semantic-Cosegmentation-master
|
computeColor.m
|
.m
|
Semantic-Cosegmentation-master/code/Util/Optical Flow/computeColor.m
| 3,142 |
utf_8
|
a36a650437bc93d4d8ffe079fe712901
|
function img = computeColor(u,v)
% computeColor color codes flow field U, V
% According to the c++ source code of Daniel Scharstein
% Contact: [email protected]
% Author: Deqing Sun, Department of Computer Science, Brown University
% Contact: [email protected]
% $Date: 2007-10-31 21:20:30 (Wed, 31 Oct 2006) $
% Copyright 2007, Deqing Sun.
%
% All Rights Reserved
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for any purpose other than its incorporation into a
% commercial product is hereby granted without fee, provided that the
% above copyright notice appear in all copies and that both that
% copyright notice and this permission notice appear in supporting
% documentation, and that the name of the author and Brown University not be used in
% advertising or publicity pertaining to distribution of the software
% without specific, written prior permission.
%
% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
% INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY
% PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR OR BROWN UNIVERSITY BE LIABLE FOR
% ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
nanIdx = isnan(u) | isnan(v);
u(nanIdx) = 0;
v(nanIdx) = 0;
colorwheel = makeColorwheel();
ncols = size(colorwheel, 1);
rad = sqrt(u.^2+v.^2);
a = atan2(-v, -u)/pi;
fk = (a+1) /2 * (ncols-1) + 1; % -1~1 maped to 1~ncols
k0 = floor(fk); % 1, 2, ..., ncols
k1 = k0+1;
k1(k1==ncols+1) = 1;
f = fk - k0;
for i = 1:size(colorwheel,2)
tmp = colorwheel(:,i);
col0 = tmp(k0)/255;
col1 = tmp(k1)/255;
col = (1-f).*col0 + f.*col1;
idx = rad <= 1;
col(idx) = 1-rad(idx).*(1-col(idx)); % increase saturation with radius
col(~idx) = col(~idx)*0.75; % out of range
img(:,:, i) = uint8(floor(255*col.*(1-nanIdx)));
end;
%%
function colorwheel = makeColorwheel()
% color encoding scheme
% adapted from the color circle idea described at
% http://members.shaw.ca/quadibloc/other/colint.htm
RY = 15;
YG = 6;
GC = 4;
CB = 11;
BM = 13;
MR = 6;
ncols = RY + YG + GC + CB + BM + MR;
colorwheel = zeros(ncols, 3); % r g b
col = 0;
%RY
colorwheel(1:RY, 1) = 255;
colorwheel(1:RY, 2) = floor(255*(0:RY-1)/RY)';
col = col+RY;
%YG
colorwheel(col+(1:YG), 1) = 255 - floor(255*(0:YG-1)/YG)';
colorwheel(col+(1:YG), 2) = 255;
col = col+YG;
%GC
colorwheel(col+(1:GC), 2) = 255;
colorwheel(col+(1:GC), 3) = floor(255*(0:GC-1)/GC)';
col = col+GC;
%CB
colorwheel(col+(1:CB), 2) = 255 - floor(255*(0:CB-1)/CB)';
colorwheel(col+(1:CB), 3) = 255;
col = col+CB;
%BM
colorwheel(col+(1:BM), 3) = 255;
colorwheel(col+(1:BM), 1) = floor(255*(0:BM-1)/BM)';
col = col+BM;
%MR
colorwheel(col+(1:MR), 3) = 255 - floor(255*(0:MR-1)/MR)';
colorwheel(col+(1:MR), 1) = 255;
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
region_to_shape.m
|
.m
|
Semantic-Cosegmentation-master/code/Ours/region_to_shape.m
| 2,301 |
utf_8
|
47925c4dc400a8d41c1f05e006daeb3d
|
function polar_values_descrete=region_to_shape(im_region)
if nargin==0
im_region=imread('50.png');
end
[region_i region_j]=find(im_region(:,:,1));
region_i_mean=mean(region_i);
region_j_mean=mean(region_j);
region_size=length(region_i);
region_size_normalize=10000;
im_edge=edge(im_region);
[edge_i edge_j]=find(im_edge);
edge_i=(edge_i-region_i_mean)*region_size_normalize/region_size;
edge_j=(edge_j-region_j_mean)*region_size_normalize/region_size;
polar_values=zeros(length(edge_i),2);
for edge_index=1:length(edge_i)
polar_values(edge_index,:)=[ij_to_angle(edge_i(edge_index),edge_j(edge_index)) norm([edge_i(edge_index) edge_j(edge_index)])];
end
[~, sorted_indexes]=sort(polar_values(:,1));
polar_values=polar_values(sorted_indexes,:);
polar_values_descrete=zeros(360,1);
polar_value_descrete_index=1;
for polar_value_index=1:size(polar_values,1)-1
if polar_values(polar_value_index)>polar_value_descrete_index
polar_values_descrete(polar_value_descrete_index)=polar_values(polar_value_index,2);
polar_value_descrete_index=polar_value_descrete_index+1;
end
end
if length(polar_values)==0
polar_values_descrete=40*ones(360,1);
polar_values(1,:)=[1 40];
end
for polar_value_descrete_index=360:-1:1
if polar_values_descrete(polar_value_descrete_index)==0
polar_values_descrete(polar_value_descrete_index)=polar_values(end,2);
end
end
% polar_values_descrete = (polar_values_descrete - min(polar_values_descrete))/(max(polar_values_descrete) - min(polar_values_descrete));
% polar_values_descrete=polar_values_descrete-30;%mean(polar_values_descrete);
% polar_values_descrete=polar_values_descrete/norm(polar_values_descrete);
%
end
function ij_angle=ij_to_angle(i,j)
if (j==0)&&(i>0)
ij_angle=90;
elseif (j==0)&&(i<0)
ij_angle=270;
elseif (j>0)&&(i==0)
ij_angle=0;
elseif (j<0)&&(i==0)
ij_angle=180;
elseif (j>0)&&(i>0)
ij_angle=atand(i/j);
elseif (j>0)&&(i<0)
ij_angle=atand(i/j)+360;
elseif (j<0)&&(i>0)
ij_angle=atand(i/j)+180;
elseif (j<0)&&(i<0)
ij_angle=atand(i/j)+180;
end
end
|
github
|
GYZHikari/Semantic-Cosegmentation-master
|
gene_weight.m
|
.m
|
Semantic-Cosegmentation-master/code/Ours/gene_weight.m
| 826 |
utf_8
|
61eb07fae858ed2653a0b66fba7fb527
|
function affmat = gene_weight( feature, nodes, theta)
affmat = zeros(numel(nodes), numel(nodes));
%% attach addtional connection/edge
edges = edges_between(nodes);
%% compute affinity matrix value
row = edges(:,1); col = edges(:,2);
ind = sub2ind(size(affmat), row, col);
tmp = sum( (feature(row,:) - feature(col,:)).^2, 2);
valDistances = sqrt(tmp)+eps;
minVal = min(valDistances);
valDistances=(valDistances-minVal)/(max(valDistances)-minVal);
weights=exp(-theta*valDistances);
affmat(ind) = weights;
ind = sub2ind(size(affmat), col, row);
affmat(ind) = weights;
end
function edges = edges_between(inds)
if isempty(inds)
edges = [];
end
num = length(inds);
mat = tril(ones(num), -1);
[row, col] = find(mat);
edges = [inds(row), inds(col)];
end
|
github
|
siprob/arhmm_mcmc-master
|
arhmm_est_cpu.m
|
.m
|
arhmm_mcmc-master/arhmm_est_cpu.m
| 1,882 |
utf_8
|
911a9f82c561722b95f1ea9e0a72b254
|
%{
Parallel MCMC sampling of AR-HMMs for stochastic time series prediction.
- Calculate predictions for a given set of AR-HMMs and an initial observation sequence.
Written by I. R. Sipos ([email protected]) and A. Ceffer ([email protected])
(Department of Networked Systems and Services,
Budapest University of Technology and Economics, Budapest, Hungary, 2016.)
Intended for academic purposes on an as is basis. Any feedback is appreciated.
Please refer to:
(1) SIPOS, I. Róbert. Parallel stratified MCMC sampling of AR-HMMs for stochastic time series prediction.
In: Proceedings, 4th Stochastic Modeling Techniques and Data Analysis (SMTDA2016). Valletta, 2016.
(2) SIPOS, I. Róbert; CEFFER, Attila; LEVENDOVSZKY, János. Parallel optimization of sparse portfolios with AR-HMMs.
Computational Economics, Online First. DOI: 10.1007/s10614-016-9579-y
%}
function [pred, LL] = arhmm_est_cpu(hmms, x)
warning('off');
addpath(genpath('HMMall'));
warning('on');
% Initializations.
K = size(hmms, 2);
pred = nan(1, K);
LL = nan(1, K);
T = length(x);
% Sequentially iterate through each AR-HMM.
for k = 1:K
hmm = hmms(:, k);
N = length(hmm.pi);
% Observation likelihood for time instance and each state.
obslik = ones(N, T-1)*eps;
for i = 1:N
for t = 1:T-1
if hmm.sigma(i) > 0
obslik(i, t) = normpdf(x(t+1)-hmm.rho(i)*x(t), hmm.mu(i), hmm.sigma(i));
end
end
end
% Call the forward-backward algorithm.
[~, ~, gamma, loglik] = fwdback(hmm.pi, hmm.A, obslik);
% Prediction.
alpha = gamma(:, end).' * hmm.A;
y = alpha * (hmm.rho.*x(end) + hmm.mu);
% Store the results.
pred(k) = y;
LL(k) = loglik;
end
end
|
github
|
siprob/arhmm_mcmc-master
|
cond_indep_fisher_z.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMstats/cond_indep_fisher_z.m
| 3,647 |
utf_8
|
e3291330222ba7b37c56cc824decff44
|
function [CI, r, p] = cond_indep_fisher_z(X, Y, S, C, N, alpha)
% COND_INDEP_FISHER_Z Test if X indep Y given Z using Fisher's Z test
% CI = cond_indep_fisher_z(X, Y, S, C, N, alpha)
%
% C is the covariance (or correlation) matrix
% N is the sample size
% alpha is the significance level (default: 0.05)
%
% See p133 of T. Anderson, "An Intro. to Multivariate Statistical Analysis", 1984
if nargin < 6, alpha = 0.05; end
r = partial_corr_coef(C, X, Y, S);
z = 0.5*log( (1+r)/(1-r) );
z0 = 0;
W = sqrt(N - length(S) - 3)*(z-z0); % W ~ N(0,1)
cutoff = norminv(1 - 0.5*alpha); % P(|W| <= cutoff) = 0.95
%cutoff = mynorminv(1 - 0.5*alpha); % P(|W| <= cutoff) = 0.95
if abs(W) < cutoff
CI = 1;
else % reject the null hypothesis that rho = 0
CI = 0;
end
p = normcdf(W);
%p = mynormcdf(W);
%%%%%%%%%
function p = normcdf(x,mu,sigma)
%NORMCDF Normal cumulative distribution function (cdf).
% P = NORMCDF(X,MU,SIGMA) computes the normal cdf with mean MU and
% standard deviation SIGMA at the values in X.
%
% The size of P is the common size of X, MU and SIGMA. A scalar input
% functions as a constant matrix of the same size as the other inputs.
%
% Default values for MU and SIGMA are 0 and 1 respectively.
% References:
% [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical
% Functions", Government Printing Office, 1964, 26.2.
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision: 1.1 $ $Date: 2005/04/26 02:29:17 $
if nargin < 3,
sigma = 1;
end
if nargin < 2;
mu = 0;
end
[errorcode x mu sigma] = distchck(3,x,mu,sigma);
if errorcode > 0
error('Requires non-scalar arguments to match in size.');
end
% Initialize P to zero.
p = zeros(size(x));
% Return NaN if SIGMA is not positive.
k1 = find(sigma <= 0);
if any(k1)
tmp = NaN;
p(k1) = tmp(ones(size(k1)));
end
% Express normal CDF in terms of the error function.
k = find(sigma > 0);
if any(k)
p(k) = 0.5 * erfc( - (x(k) - mu(k)) ./ (sigma(k) * sqrt(2)));
end
% Make sure that round-off errors never make P greater than 1.
k2 = find(p > 1);
if any(k2)
p(k2) = ones(size(k2));
end
%%%%%%%%
function x = norminv(p,mu,sigma);
%NORMINV Inverse of the normal cumulative distribution function (cdf).
% X = NORMINV(P,MU,SIGMA) finds the inverse of the normal cdf with
% mean, MU, and standard deviation, SIGMA.
%
% The size of X is the common size of the input arguments. A scalar input
% functions as a constant matrix of the same size as the other inputs.
%
% Default values for MU and SIGMA are 0 and 1 respectively.
% References:
% [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical
% Functions", Government Printing Office, 1964, 7.1.1 and 26.2.2
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision: 1.1 $ $Date: 2005/04/26 02:29:17 $
if nargin < 3,
sigma = 1;
end
if nargin < 2;
mu = 0;
end
[errorcode p mu sigma] = distchck(3,p,mu,sigma);
if errorcode > 0
error('Requires non-scalar arguments to match in size.');
end
% Allocate space for x.
x = zeros(size(p));
% Return NaN if the arguments are outside their respective limits.
k = find(sigma <= 0 | p < 0 | p > 1);
if any(k)
tmp = NaN;
x(k) = tmp(ones(size(k)));
end
% Put in the correct values when P is either 0 or 1.
k = find(p == 0);
if any(k)
tmp = Inf;
x(k) = -tmp(ones(size(k)));
end
k = find(p == 1);
if any(k)
tmp = Inf;
x(k) = tmp(ones(size(k)));
end
% Compute the inverse function for the intermediate values.
k = find(p > 0 & p < 1 & sigma > 0);
if any(k),
x(k) = sqrt(2) * sigma(k) .* erfinv(2 * p(k) - 1) + mu(k);
end
|
github
|
siprob/arhmm_mcmc-master
|
logistK.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMstats/logistK.m
| 7,253 |
utf_8
|
9539c8105ebca14d632373f5f9f4b70d
|
function [beta,post,lli] = logistK(x,y,w,beta)
% [beta,post,lli] = logistK(x,y,beta,w)
%
% k-class logistic regression with optional sample weights
%
% k = number of classes
% n = number of samples
% d = dimensionality of samples
%
% INPUT
% x dxn matrix of n input column vectors
% y kxn vector of class assignments
% [w] 1xn vector of sample weights
% [beta] dxk matrix of model coefficients
%
% OUTPUT
% beta dxk matrix of fitted model coefficients
% (beta(:,k) are fixed at 0)
% post kxn matrix of fitted class posteriors
% lli log likelihood
%
% Let p(i,j) = exp(beta(:,j)'*x(:,i)),
% Class j posterior for observation i is:
% post(j,i) = p(i,j) / (p(i,1) + ... p(i,k))
%
% See also logistK_eval.
%
% David Martin <[email protected]>
% May 3, 2002
% Copyright (C) 2002 David R. Martin <[email protected]>
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License as
% published by the Free Software Foundation; either version 2 of the
% License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
% 02111-1307, USA, or see http://www.gnu.org/copyleft/gpl.html.
% TODO - this code would be faster if x were transposed
error(nargchk(2,4,nargin));
debug = 0;
if debug>0,
h=figure(1);
set(h,'DoubleBuffer','on');
end
% get sizes
[d,nx] = size(x);
[k,ny] = size(y);
% check sizes
if k < 2,
error('Input y must encode at least 2 classes.');
end
if nx ~= ny,
error('Inputs x,y not the same length.');
end
n = nx;
% make sure class assignments have unit L1-norm
sumy = sum(y,1);
if abs(1-sumy) > eps,
sumy = sum(y,1);
for i = 1:k, y(i,:) = y(i,:) ./ sumy; end
end
clear sumy;
% if sample weights weren't specified, set them to 1
if nargin < 3,
w = ones(1,n);
end
% normalize sample weights so max is 1
w = w / max(w);
% if starting beta wasn't specified, initialize randomly
if nargin < 4,
beta = 1e-3*rand(d,k);
beta(:,k) = 0; % fix beta for class k at zero
else
if sum(beta(:,k)) ~= 0,
error('beta(:,k) ~= 0');
end
end
stepsize = 1;
minstepsize = 1e-2;
post = computePost(beta,x);
lli = computeLogLik(post,y,w);
for iter = 1:100,
%disp(sprintf(' logist iter=%d lli=%g',iter,lli));
vis(x,y,beta,lli,d,k,iter,debug);
% gradient and hessian
[g,h] = derivs(post,x,y,w);
% make sure Hessian is well conditioned
if rcond(h) < eps,
% condition with Levenberg-Marquardt method
for i = -16:16,
h2 = h .* ((1 + 10^i)*eye(size(h)) + (1-eye(size(h))));
if rcond(h2) > eps, break, end
end
if rcond(h2) < eps,
warning(['Stopped at iteration ' num2str(iter) ...
' because Hessian can''t be conditioned']);
break
end
h = h2;
end
% save lli before update
lli_prev = lli;
% Newton-Raphson with step-size halving
while stepsize >= minstepsize,
% Newton-Raphson update step
step = stepsize * (h \ g);
beta2 = beta;
beta2(:,1:k-1) = beta2(:,1:k-1) - reshape(step,d,k-1);
% get the new log likelihood
post2 = computePost(beta2,x);
lli2 = computeLogLik(post2,y,w);
% if the log likelihood increased, then stop
if lli2 > lli,
post = post2; lli = lli2; beta = beta2;
break
end
% otherwise, reduce step size by half
stepsize = 0.5 * stepsize;
end
% stop if the average log likelihood has gotten small enough
if 1-exp(lli/n) < 1e-2, break, end
% stop if the log likelihood changed by a small enough fraction
dlli = (lli_prev-lli) / lli;
if abs(dlli) < 1e-3, break, end
% stop if the step size has gotten too small
if stepsize < minstepsize, brea, end
% stop if the log likelihood has decreased; this shouldn't happen
if lli < lli_prev,
warning(['Stopped at iteration ' num2str(iter) ...
' because the log likelihood decreased from ' ...
num2str(lli_prev) ' to ' num2str(lli) '.' ...
' This may be a bug.']);
break
end
end
if debug>0,
vis(x,y,beta,lli,d,k,iter,2);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% class posteriors
function post = computePost(beta,x)
[d,n] = size(x);
[d,k] = size(beta);
post = zeros(k,n);
bx = zeros(k,n);
for j = 1:k,
bx(j,:) = beta(:,j)'*x;
end
for j = 1:k,
post(j,:) = 1 ./ sum(exp(bx - repmat(bx(j,:),k,1)),1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% log likelihood
function lli = computeLogLik(post,y,w)
[k,n] = size(post);
lli = 0;
for j = 1:k,
lli = lli + sum(w.*y(j,:).*log(post(j,:)+eps));
end
if isnan(lli),
error('lli is nan');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% gradient and hessian
%% These are computed in what seems a verbose manner, but it is
%% done this way to use minimal memory. x should be transposed
%% to make it faster.
function [g,h] = derivs(post,x,y,w)
[k,n] = size(post);
[d,n] = size(x);
% first derivative of likelihood w.r.t. beta
g = zeros(d,k-1);
for j = 1:k-1,
wyp = w .* (y(j,:) - post(j,:));
for ii = 1:d,
g(ii,j) = x(ii,:) * wyp';
end
end
g = reshape(g,d*(k-1),1);
% hessian of likelihood w.r.t. beta
h = zeros(d*(k-1),d*(k-1));
for i = 1:k-1, % diagonal
wt = w .* post(i,:) .* (1 - post(i,:));
hii = zeros(d,d);
for a = 1:d,
wxa = wt .* x(a,:);
for b = a:d,
hii_ab = wxa * x(b,:)';
hii(a,b) = hii_ab;
hii(b,a) = hii_ab;
end
end
h( (i-1)*d+1 : i*d , (i-1)*d+1 : i*d ) = -hii;
end
for i = 1:k-1, % off-diagonal
for j = i+1:k-1,
wt = w .* post(j,:) .* post(i,:);
hij = zeros(d,d);
for a = 1:d,
wxa = wt .* x(a,:);
for b = a:d,
hij_ab = wxa * x(b,:)';
hij(a,b) = hij_ab;
hij(b,a) = hij_ab;
end
end
h( (i-1)*d+1 : i*d , (j-1)*d+1 : j*d ) = hij;
h( (j-1)*d+1 : j*d , (i-1)*d+1 : i*d ) = hij;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% debug/visualization
function vis (x,y,beta,lli,d,k,iter,debug)
if debug<=0, return, end
disp(['iter=' num2str(iter) ' lli=' num2str(lli)]);
if debug<=1, return, end
if d~=3 | k>10, return, end
figure(1);
res = 100;
r = abs(max(max(x)));
dom = linspace(-r,r,res);
[px,py] = meshgrid(dom,dom);
xx = px(:); yy = py(:);
points = [xx' ; yy' ; ones(1,res*res)];
func = zeros(k,res*res);
for j = 1:k,
func(j,:) = exp(beta(:,j)'*points);
end
[mval,ind] = max(func,[],1);
hold off;
im = reshape(ind,res,res);
imagesc(xx,yy,im);
hold on;
syms = {'w.' 'wx' 'w+' 'wo' 'w*' 'ws' 'wd' 'wv' 'w^' 'w<'};
for j = 1:k,
[mval,ind] = max(y,[],1);
ind = find(ind==j);
plot(x(1,ind),x(2,ind),syms{j});
end
pause(0.1);
% eof
|
github
|
siprob/arhmm_mcmc-master
|
multipdf.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMstats/multipdf.m
| 1,192 |
utf_8
|
1fce56db4c9a59d35960bd25df11b1f9
|
function p = multipdf(x,theta)
%MULTIPDF Multinomial probability density function.
% p = multipdf(x,theta) returns the probabilities of
% vector x, under the multinomial distribution
% with parameter vector theta.
%
% Author: David Ross
%--------------------------------------------------------
% Check the arguments.
%--------------------------------------------------------
error(nargchk(2,2,nargin));
% make sure theta is a vector
if ndims(theta) > 2 | all(size(theta) > 1)
error('theta must be a vector');
end
% make sure x is of the appropriate size
if ndims(x) > 2 | any(size(x) ~= size(theta))
error('columns of X must have same length as theta');
end
%--------------------------------------------------------
% Main...
%--------------------------------------------------------
p = prod(theta .^ x);
p = p .* factorial(sum(x)) ./ prod(factorial_v(x));
%--------------------------------------------------------
% Function factorial_v(x): computes the factorial function
% on each element of x
%--------------------------------------------------------
function r = factorial_v(x)
if size(x,2) == 1
x = x';
end
r = [];
for y = x
r = [r factorial(y)];
end
|
github
|
siprob/arhmm_mcmc-master
|
metrop.m
|
.m
|
arhmm_mcmc-master/HMMall/netlab3.3/metrop.m
| 5,284 |
utf_8
|
df084b9ad36314e304a99b9b1f3c955e
|
function [samples, energies, diagn] = metrop(f, x, options, gradf, varargin)
%METROP Markov Chain Monte Carlo sampling with Metropolis algorithm.
%
% Description
% SAMPLES = METROP(F, X, OPTIONS) uses the Metropolis algorithm to
% sample from the distribution P ~ EXP(-F), where F is the first
% argument to METROP. The Markov chain starts at the point X and each
% candidate state is picked from a Gaussian proposal distribution and
% accepted or rejected according to the Metropolis criterion.
%
% SAMPLES = METROP(F, X, OPTIONS, [], P1, P2, ...) allows additional
% arguments to be passed to F(). The fourth argument is ignored, but
% is included for compatibility with HMC and the optimisers.
%
% [SAMPLES, ENERGIES, DIAGN] = METROP(F, X, OPTIONS) also returns a log
% of the energy values (i.e. negative log probabilities) for the
% samples in ENERGIES and DIAGN, a structure containing diagnostic
% information (position and acceptance threshold) for each step of the
% chain in DIAGN.POS and DIAGN.ACC respectively. All candidate states
% (including rejected ones) are stored in DIAGN.POS.
%
% S = METROP('STATE') returns a state structure that contains the state
% of the two random number generators RAND and RANDN. These are
% contained in fields randstate, randnstate.
%
% METROP('STATE', S) resets the state to S. If S is an integer, then
% it is passed to RAND and RANDN. If S is a structure returned by
% METROP('STATE') then it resets the generator to exactly the same
% state.
%
% The optional parameters in the OPTIONS vector have the following
% interpretations.
%
% OPTIONS(1) is set to 1 to display the energy values and rejection
% threshold at each step of the Markov chain. If the value is 2, then
% the position vectors at each step are also displayed.
%
% OPTIONS(14) is the number of samples retained from the Markov chain;
% default 100.
%
% OPTIONS(15) is the number of samples omitted from the start of the
% chain; default 0.
%
% OPTIONS(18) is the variance of the proposal distribution; default 1.
%
% See also
% HMC
%
% Copyright (c) Ian T Nabney (1996-2001)
if nargin <= 2
if ~strcmp(f, 'state')
error('Unknown argument to metrop');
end
switch nargin
case 1
% Return state of sampler
samples = get_state(f); % Function defined in this module
return;
case 2
% Set the state of the sampler
set_state(f, x); % Function defined in this module
return;
end
end
if 0
seed = 42;
randn('state', seed);
rand('state', seed)
end
display = options(1);
if options(14) > 0
nsamples = options(14);
else
nsamples = 100;
end
if options(15) >= 0
nomit = options(15);
else
nomit = 0;
end
if options(18) > 0.0
std_dev = sqrt(options(18));
else
std_dev = 1.0; % default
end
nparams = length(x);
% Set up string for evaluating potential function.
f = fcnchk(f, length(varargin));
samples = zeros(nsamples, nparams); % Matrix of returned samples.
if nargout >= 2
en_save = 1;
energies = zeros(nsamples, 1);
else
en_save = 0;
end
if nargout >= 3
diagnostics = 1;
diagn_pos = zeros(nsamples, nparams);
diagn_acc = zeros(nsamples, 1);
else
diagnostics = 0;
end
% Main loop.
n = - nomit + 1;
Eold = feval(f, x, varargin{:}); % Evaluate starting energy.
nreject = 0; % Initialise count of rejected states.
while n <= nsamples
xold = x;
% Sample a new point from the proposal distribution
x = xold + randn(1, nparams)*std_dev;
%fprintf('netlab propose: xold = %5.3f,%5.3f, xnew = %5.3f,%5.3f\n',...
% xold(1), xold(2), x(1), x(2));
% Now apply Metropolis algorithm.
Enew = feval(f, x, varargin{:}); % Evaluate new energy.
a = exp(Eold - Enew); % Acceptance threshold.
if (diagnostics & n > 0)
diagn_pos(n,:) = x;
diagn_acc(n,:) = a;
end
if (display > 1)
fprintf(1, 'New position is\n');
disp(x);
end
r = rand(1);
%fprintf('netlab: n=%d, a=%f/%f=%5.3f (%5.3f), r=%5.3f\n',...
% n, exp(-Enew), exp(-Eold), a, exp(-Enew)/exp(-Eold), r);
if a > r % Accept the new state.
Eold = Enew;
if (display > 0)
fprintf(1, 'Finished step %4d Threshold: %g\n', n, a);
end
else % Reject the new state
if n > 0
nreject = nreject + 1;
end
x = xold; % Reset position
if (display > 0)
fprintf(1, ' Sample rejected %4d. Threshold: %g\n', n, a);
end
end
if n > 0
samples(n,:) = x; % Store sample.
if en_save
energies(n) = Eold; % Store energy.
end
end
n = n + 1;
end
if (display > 0)
fprintf(1, '\nFraction of samples rejected: %g\n', ...
nreject/(nsamples));
end
if diagnostics
diagn.pos = diagn_pos;
diagn.acc = diagn_acc;
end
% Return complete state of the sampler.
function state = get_state(f)
state.randstate = rand('state');
state.randnstate = randn('state');
return
% Set state of sampler, either from full state, or with an integer
function set_state(f, x)
if isnumeric(x)
rand('state', x);
randn('state', x);
else
if ~isstruct(x)
error('Second argument to metrop must be number or state structure');
end
if (~isfield(x, 'randstate') | ~isfield(x, 'randnstate'))
error('Second argument to metrop must contain correct fields')
end
rand('state', x.randstate);
randn('state', x.randnstate);
end
return
|
github
|
siprob/arhmm_mcmc-master
|
hmc.m
|
.m
|
arhmm_mcmc-master/HMMall/netlab3.3/hmc.m
| 7,683 |
utf_8
|
64c15e958297afe69787b8617dc1a56a
|
function [samples, energies, diagn] = hmc(f, x, options, gradf, varargin)
%HMC Hybrid Monte Carlo sampling.
%
% Description
% SAMPLES = HMC(F, X, OPTIONS, GRADF) uses a hybrid Monte Carlo
% algorithm to sample from the distribution P ~ EXP(-F), where F is the
% first argument to HMC. The Markov chain starts at the point X, and
% the function GRADF is the gradient of the `energy' function F.
%
% HMC(F, X, OPTIONS, GRADF, P1, P2, ...) allows additional arguments to
% be passed to F() and GRADF().
%
% [SAMPLES, ENERGIES, DIAGN] = HMC(F, X, OPTIONS, GRADF) also returns a
% log of the energy values (i.e. negative log probabilities) for the
% samples in ENERGIES and DIAGN, a structure containing diagnostic
% information (position, momentum and acceptance threshold) for each
% step of the chain in DIAGN.POS, DIAGN.MOM and DIAGN.ACC respectively.
% All candidate states (including rejected ones) are stored in
% DIAGN.POS.
%
% [SAMPLES, ENERGIES, DIAGN] = HMC(F, X, OPTIONS, GRADF) also returns
% the ENERGIES (i.e. negative log probabilities) corresponding to the
% samples. The DIAGN structure contains three fields:
%
% POS the position vectors of the dynamic process.
%
% MOM the momentum vectors of the dynamic process.
%
% ACC the acceptance thresholds.
%
% S = HMC('STATE') returns a state structure that contains the state of
% the two random number generators RAND and RANDN and the momentum of
% the dynamic process. These are contained in fields randstate,
% randnstate and mom respectively. The momentum state is only used for
% a persistent momentum update.
%
% HMC('STATE', S) resets the state to S. If S is an integer, then it
% is passed to RAND and RANDN and the momentum variable is randomised.
% If S is a structure returned by HMC('STATE') then it resets the
% generator to exactly the same state.
%
% The optional parameters in the OPTIONS vector have the following
% interpretations.
%
% OPTIONS(1) is set to 1 to display the energy values and rejection
% threshold at each step of the Markov chain. If the value is 2, then
% the position vectors at each step are also displayed.
%
% OPTIONS(5) is set to 1 if momentum persistence is used; default 0,
% for complete replacement of momentum variables.
%
% OPTIONS(7) defines the trajectory length (i.e. the number of leap-
% frog steps at each iteration). Minimum value 1.
%
% OPTIONS(9) is set to 1 to check the user defined gradient function.
%
% OPTIONS(14) is the number of samples retained from the Markov chain;
% default 100.
%
% OPTIONS(15) is the number of samples omitted from the start of the
% chain; default 0.
%
% OPTIONS(17) defines the momentum used when a persistent update of
% (leap-frog) momentum is used. This is bounded to the interval [0,
% 1).
%
% OPTIONS(18) is the step size used in leap-frogs; default 1/trajectory
% length.
%
% See also
% METROP
%
% Copyright (c) Ian T Nabney (1996-2001)
% Global variable to store state of momentum variables: set by set_state
% Used to initialise variable if set
global HMC_MOM
if nargin <= 2
if ~strcmp(f, 'state')
error('Unknown argument to hmc');
end
switch nargin
case 1
samples = get_state(f);
return;
case 2
set_state(f, x);
return;
end
end
display = options(1);
if (round(options(5) == 1))
persistence = 1;
% Set alpha to lie in [0, 1)
alpha = max(0, options(17));
alpha = min(1, alpha);
salpha = sqrt(1-alpha*alpha);
else
persistence = 0;
end
L = max(1, options(7)); % At least one step in leap-frogging
if options(14) > 0
nsamples = options(14);
else
nsamples = 100; % Default
end
if options(15) >= 0
nomit = options(15);
else
nomit = 0;
end
if options(18) > 0
step_size = options(18); % Step size.
else
step_size = 1/L; % Default
end
x = x(:)'; % Force x to be a row vector
nparams = length(x);
% Set up strings for evaluating potential function and its gradient.
f = fcnchk(f, length(varargin));
gradf = fcnchk(gradf, length(varargin));
% Check the gradient evaluation.
if (options(9))
% Check gradients
feval('gradchek', x, f, gradf, varargin{:});
end
samples = zeros(nsamples, nparams); % Matrix of returned samples.
if nargout >= 2
en_save = 1;
energies = zeros(nsamples, 1);
else
en_save = 0;
end
if nargout >= 3
diagnostics = 1;
diagn_pos = zeros(nsamples, nparams);
diagn_mom = zeros(nsamples, nparams);
diagn_acc = zeros(nsamples, 1);
else
diagnostics = 0;
end
n = - nomit + 1;
Eold = feval(f, x, varargin{:}); % Evaluate starting energy.
nreject = 0;
if (~persistence | isempty(HMC_MOM))
p = randn(1, nparams); % Initialise momenta at random
else
p = HMC_MOM; % Initialise momenta from stored state
end
lambda = 1;
% Main loop.
while n <= nsamples
xold = x; % Store starting position.
pold = p; % Store starting momenta
Hold = Eold + 0.5*(p*p'); % Recalculate Hamiltonian as momenta have changed
if ~persistence
% Choose a direction at random
if (rand < 0.5)
lambda = -1;
else
lambda = 1;
end
end
% Perturb step length.
epsilon = lambda*step_size*(1.0 + 0.1*randn(1));
% First half-step of leapfrog.
p = p - 0.5*epsilon*feval(gradf, x, varargin{:});
x = x + epsilon*p;
% Full leapfrog steps.
for m = 1 : L - 1
p = p - epsilon*feval(gradf, x, varargin{:});
x = x + epsilon*p;
end
% Final half-step of leapfrog.
p = p - 0.5*epsilon*feval(gradf, x, varargin{:});
% Now apply Metropolis algorithm.
Enew = feval(f, x, varargin{:}); % Evaluate new energy.
p = -p; % Negate momentum
Hnew = Enew + 0.5*p*p'; % Evaluate new Hamiltonian.
a = exp(Hold - Hnew); % Acceptance threshold.
if (diagnostics & n > 0)
diagn_pos(n,:) = x;
diagn_mom(n,:) = p;
diagn_acc(n,:) = a;
end
if (display > 1)
fprintf(1, 'New position is\n');
disp(x);
end
if a > rand(1) % Accept the new state.
Eold = Enew; % Update energy
if (display > 0)
fprintf(1, 'Finished step %4d Threshold: %g\n', n, a);
end
else % Reject the new state.
if n > 0
nreject = nreject + 1;
end
x = xold; % Reset position
p = pold; % Reset momenta
if (display > 0)
fprintf(1, ' Sample rejected %4d. Threshold: %g\n', n, a);
end
end
if n > 0
samples(n,:) = x; % Store sample.
if en_save
energies(n) = Eold; % Store energy.
end
end
% Set momenta for next iteration
if persistence
p = -p;
% Adjust momenta by a small random amount.
p = alpha.*p + salpha.*randn(1, nparams);
else
p = randn(1, nparams); % Replace all momenta.
end
n = n + 1;
end
if (display > 0)
fprintf(1, '\nFraction of samples rejected: %g\n', ...
nreject/(nsamples));
end
if diagnostics
diagn.pos = diagn_pos;
diagn.mom = diagn_mom;
diagn.acc = diagn_acc;
end
% Store final momentum value in global so that it can be retrieved later
HMC_MOM = p;
return
% Return complete state of sampler (including momentum)
function state = get_state(f)
global HMC_MOM
state.randstate = rand('state');
state.randnstate = randn('state');
state.mom = HMC_MOM;
return
% Set complete state of sampler (including momentum) or just set randn
% and rand with integer argument.
function set_state(f, x)
global HMC_MOM
if isnumeric(x)
rand('state', x);
randn('state', x);
HMC_MOM = [];
else
if ~isstruct(x)
error('Second argument to hmc must be number or state structure');
end
if (~isfield(x, 'randstate') | ~isfield(x, 'randnstate') ...
| ~isfield(x, 'mom'))
error('Second argument to hmc must contain correct fields')
end
rand('state', x.randstate);
randn('state', x.randnstate);
HMC_MOM = x.mom;
end
return
|
github
|
siprob/arhmm_mcmc-master
|
gtminit.m
|
.m
|
arhmm_mcmc-master/HMMall/netlab3.3/gtminit.m
| 5,204 |
utf_8
|
ab76f6114a7e85375ade5e5889d5f6a7
|
function net = gtminit(net, options, data, samp_type, varargin)
%GTMINIT Initialise the weights and latent sample in a GTM.
%
% Description
% NET = GTMINIT(NET, OPTIONS, DATA, SAMPTYPE) takes a GTM NET and
% generates a sample of latent data points and sets the centres (and
% widths if appropriate) of NET.RBFNET.
%
% If the SAMPTYPE is 'REGULAR', then regular grids of latent data
% points and RBF centres are created. The dimension of the latent data
% space must be 1 or 2. For one-dimensional latent space, the
% LSAMPSIZE parameter gives the number of latent points and the
% RBFSAMPSIZE parameter gives the number of RBF centres. For a two-
% dimensional latent space, these parameters must be vectors of length
% 2 with the number of points in each of the x and y directions to
% create a rectangular grid. The widths of the RBF basis functions are
% set by a call to RBFSETFW passing OPTIONS(7) as the scaling
% parameter.
%
% If the SAMPTYPE is 'UNIFORM' or 'GAUSSIAN' then the latent data is
% found by sampling from a uniform or Gaussian distribution
% correspondingly. The RBF basis function parameters are set by a call
% to RBFSETBF with the DATA parameter as dataset and the OPTIONS
% vector.
%
% Finally, the output layer weights of the RBF are initialised by
% mapping the mean of the latent variable to the mean of the target
% variable, and the L-dimensional latent variale variance to the
% variance of the targets along the first L principal components.
%
% See also
% GTM, GTMEM, PCA, RBFSETBF, RBFSETFW
%
% Copyright (c) Ian T Nabney (1996-2001)
% Check for consistency
errstring = consist(net, 'gtm', data);
if ~isempty(errstring)
error(errstring);
end
% Check type of sample
stypes = {'regular', 'uniform', 'gaussian'};
if (strcmp(samp_type, stypes)) == 0
error('Undefined sample type.')
end
if net.dim_latent > size(data, 2)
error('Latent space dimension must not be greater than data dimension')
end
nlatent = net.gmmnet.ncentres;
nhidden = net.rbfnet.nhidden;
% Create latent data sample and set RBF centres
switch samp_type
case 'regular'
if nargin ~= 6
error('Regular type must specify latent and RBF shapes');
end
l_samp_size = varargin{1};
rbf_samp_size = varargin{2};
if round(l_samp_size) ~= l_samp_size
error('Latent sample specification must contain integers')
end
% Check existence and size of rbf specification
if any(size(rbf_samp_size) ~= [1 net.dim_latent]) | ...
prod(rbf_samp_size) ~= nhidden
error('Incorrect specification of RBF centres')
end
% Check dimension and type of latent data specification
if any(size(l_samp_size) ~= [1 net.dim_latent]) | ...
prod(l_samp_size) ~= nlatent
error('Incorrect dimension of latent sample spec.')
end
if net.dim_latent == 1
net.X = [-1:2/(l_samp_size-1):1]';
net.rbfnet.c = [-1:2/(rbf_samp_size-1):1]';
net.rbfnet = rbfsetfw(net.rbfnet, options(7));
elseif net.dim_latent == 2
net.X = gtm_rctg(l_samp_size);
net.rbfnet.c = gtm_rctg(rbf_samp_size);
net.rbfnet = rbfsetfw(net.rbfnet, options(7));
else
error('For regular sample, input dimension must be 1 or 2.')
end
case {'uniform', 'gaussian'}
if strcmp(samp_type, 'uniform')
net.X = 2 * (rand(nlatent, net.dim_latent) - 0.5);
else
% Sample from N(0, 0.25) distribution to ensure most latent
% data is inside square
net.X = randn(nlatent, net.dim_latent)/2;
end
net.rbfnet = rbfsetbf(net.rbfnet, options, net.X);
otherwise
% Shouldn't get here
error('Invalid sample type');
end
% Latent data sample and basis function parameters chosen.
% Now set output weights
[PCcoeff, PCvec] = pca(data);
% Scale PCs by eigenvalues
A = PCvec(:, 1:net.dim_latent)*diag(sqrt(PCcoeff(1:net.dim_latent)));
[temp, Phi] = rbffwd(net.rbfnet, net.X);
% Normalise X to ensure 1:1 mapping of variances and calculate weights
% as solution of Phi*W = normX*A'
normX = (net.X - ones(size(net.X))*diag(mean(net.X)))*diag(1./std(net.X));
net.rbfnet.w2 = Phi \ (normX*A');
% Bias is mean of target data
net.rbfnet.b2 = mean(data);
% Must also set initial value of variance
% Find average distance between nearest centres
% Ensure that distance of centre to itself is excluded by setting diagonal
% entries to realmax
net.gmmnet.centres = rbffwd(net.rbfnet, net.X);
d = dist2(net.gmmnet.centres, net.gmmnet.centres) + ...
diag(ones(net.gmmnet.ncentres, 1)*realmax);
sigma = mean(min(d))/2;
% Now set covariance to minimum of this and next largest eigenvalue
if net.dim_latent < size(data, 2)
sigma = min(sigma, PCcoeff(net.dim_latent+1));
end
net.gmmnet.covars = sigma*ones(1, net.gmmnet.ncentres);
% Sub-function to create the sample data in 2d
function sample = gtm_rctg(samp_size)
xDim = samp_size(1);
yDim = samp_size(2);
% Produce a grid with the right number of rows and columns
[X, Y] = meshgrid([0:1:(xDim-1)], [(yDim-1):-1:0]);
% Change grid representation
sample = [X(:), Y(:)];
% Shift grid to correct position and scale it
maxXY= max(sample);
sample(:,1) = 2*(sample(:,1) - maxXY(1)/2)./maxXY(1);
sample(:,2) = 2*(sample(:,2) - maxXY(2)/2)./maxXY(2);
return;
|
github
|
siprob/arhmm_mcmc-master
|
mlphess.m
|
.m
|
arhmm_mcmc-master/HMMall/netlab3.3/mlphess.m
| 1,633 |
utf_8
|
b91a15ca11b4886de6c1671c33a735d3
|
function [h, hdata] = mlphess(net, x, t, hdata)
%MLPHESS Evaluate the Hessian matrix for a multi-layer perceptron network.
%
% Description
% H = MLPHESS(NET, X, T) takes an MLP network data structure NET, a
% matrix X of input values, and a matrix T of target values and returns
% the full Hessian matrix H corresponding to the second derivatives of
% the negative log posterior distribution, evaluated for the current
% weight and bias values as defined by NET.
%
% [H, HDATA] = MLPHESS(NET, X, T) returns both the Hessian matrix H and
% the contribution HDATA arising from the data dependent term in the
% Hessian.
%
% H = MLPHESS(NET, X, T, HDATA) takes a network data structure NET, a
% matrix X of input values, and a matrix T of target values, together
% with the contribution HDATA arising from the data dependent term in
% the Hessian, and returns the full Hessian matrix H corresponding to
% the second derivatives of the negative log posterior distribution.
% This version saves computation time if HDATA has already been
% evaluated for the current weight and bias values.
%
% See also
% MLP, HESSCHEK, MLPHDOTV, EVIDENCE
%
% Copyright (c) Ian T Nabney (1996-2001)
% Check arguments for consistency
errstring = consist(net, 'mlp', x, t);
if ~isempty(errstring);
error(errstring);
end
if nargin == 3
% Data term in Hessian needs to be computed
hdata = datahess(net, x, t);
end
[h, hdata] = hbayes(net, hdata);
% Sub-function to compute data part of Hessian
function hdata = datahess(net, x, t)
hdata = zeros(net.nwts, net.nwts);
for v = eye(net.nwts);
hdata(find(v),:) = mlphdotv(net, x, t, v);
end
return
|
github
|
siprob/arhmm_mcmc-master
|
glmhess.m
|
.m
|
arhmm_mcmc-master/HMMall/netlab3.3/glmhess.m
| 4,024 |
utf_8
|
2d706b82d25cb35ff9467fe8837ef26f
|
function [h, hdata] = glmhess(net, x, t, hdata)
%GLMHESS Evaluate the Hessian matrix for a generalised linear model.
%
% Description
% H = GLMHESS(NET, X, T) takes a GLM network data structure NET, a
% matrix X of input values, and a matrix T of target values and returns
% the full Hessian matrix H corresponding to the second derivatives of
% the negative log posterior distribution, evaluated for the current
% weight and bias values as defined by NET. Note that the target data
% is not required in the calculation, but is included to make the
% interface uniform with NETHESS. For linear and logistic outputs, the
% computation is very simple and is done (in effect) in one line in
% GLMTRAIN.
%
% [H, HDATA] = GLMHESS(NET, X, T) returns both the Hessian matrix H and
% the contribution HDATA arising from the data dependent term in the
% Hessian.
%
% H = GLMHESS(NET, X, T, HDATA) takes a network data structure NET, a
% matrix X of input values, and a matrix T of target values, together
% with the contribution HDATA arising from the data dependent term in
% the Hessian, and returns the full Hessian matrix H corresponding to
% the second derivatives of the negative log posterior distribution.
% This version saves computation time if HDATA has already been
% evaluated for the current weight and bias values.
%
% See also
% GLM, GLMTRAIN, HESSCHEK, NETHESS
%
% Copyright (c) Ian T Nabney (1996-2001)
% Check arguments for consistency
errstring = consist(net, 'glm', x, t);
if ~isempty(errstring);
error(errstring);
end
ndata = size(x, 1);
nparams = net.nwts;
nout = net.nout;
p = glmfwd(net, x);
inputs = [x ones(ndata, 1)];
if nargin == 3
hdata = zeros(nparams); % Full Hessian matrix
% Calculate data component of Hessian
switch net.outfn
case 'linear'
% No weighting function here
out_hess = [x ones(ndata, 1)]'*[x ones(ndata, 1)];
for j = 1:nout
hdata = rearrange_hess(net, j, out_hess, hdata);
end
case 'logistic'
% Each output is independent
e = ones(1, net.nin+1);
link_deriv = p.*(1-p);
out_hess = zeros(net.nin+1);
for j = 1:nout
inputs = [x ones(ndata, 1)].*(sqrt(link_deriv(:,j))*e);
out_hess = inputs'*inputs; % Hessian for this output
hdata = rearrange_hess(net, j, out_hess, hdata);
end
case 'softmax'
bb_start = nparams - nout + 1; % Start of bias weights block
ex_hess = zeros(nparams); % Contribution to Hessian from single example
for m = 1:ndata
X = x(m,:)'*x(m,:);
a = diag(p(m,:))-((p(m,:)')*p(m,:));
ex_hess(1:nparams-nout,1:nparams-nout) = kron(a, X);
ex_hess(bb_start:nparams, bb_start:nparams) = a.*ones(net.nout, net.nout);
temp = kron(a, x(m,:));
ex_hess(bb_start:nparams, 1:nparams-nout) = temp;
ex_hess(1:nparams-nout, bb_start:nparams) = temp';
hdata = hdata + ex_hess;
end
otherwise
error(['Unknown activation function ', net.outfn]);
end
end
[h, hdata] = hbayes(net, hdata);
function hdata = rearrange_hess(net, j, out_hess, hdata)
% Because all the biases come after all the input weights,
% we have to rearrange the blocks that make up the network Hessian.
% This function assumes that we are on the jth output and that all outputs
% are independent.
bb_start = net.nwts - net.nout + 1; % Start of bias weights block
ob_start = 1+(j-1)*net.nin; % Start of weight block for jth output
ob_end = j*net.nin; % End of weight block for jth output
b_index = bb_start+(j-1); % Index of bias weight
% Put input weight block in right place
hdata(ob_start:ob_end, ob_start:ob_end) = out_hess(1:net.nin, 1:net.nin);
% Put second derivative of bias weight in right place
hdata(b_index, b_index) = out_hess(net.nin+1, net.nin+1);
% Put cross terms (input weight v bias weight) in right place
hdata(b_index, ob_start:ob_end) = out_hess(net.nin+1,1:net.nin);
hdata(ob_start:ob_end, b_index) = out_hess(1:net.nin, net.nin+1);
return
|
github
|
siprob/arhmm_mcmc-master
|
rbfhess.m
|
.m
|
arhmm_mcmc-master/HMMall/netlab3.3/rbfhess.m
| 3,138 |
utf_8
|
0a6ef29c8be32e9991cacfe42bdfa0b3
|
function [h, hdata] = rbfhess(net, x, t, hdata)
%RBFHESS Evaluate the Hessian matrix for RBF network.
%
% Description
% H = RBFHESS(NET, X, T) takes an RBF network data structure NET, a
% matrix X of input values, and a matrix T of target values and returns
% the full Hessian matrix H corresponding to the second derivatives of
% the negative log posterior distribution, evaluated for the current
% weight and bias values as defined by NET. Currently, the
% implementation only computes the Hessian for the output layer
% weights.
%
% [H, HDATA] = RBFHESS(NET, X, T) returns both the Hessian matrix H and
% the contribution HDATA arising from the data dependent term in the
% Hessian.
%
% H = RBFHESS(NET, X, T, HDATA) takes a network data structure NET, a
% matrix X of input values, and a matrix T of target values, together
% with the contribution HDATA arising from the data dependent term in
% the Hessian, and returns the full Hessian matrix H corresponding to
% the second derivatives of the negative log posterior distribution.
% This version saves computation time if HDATA has already been
% evaluated for the current weight and bias values.
%
% See also
% MLPHESS, HESSCHEK, EVIDENCE
%
% Copyright (c) Ian T Nabney (1996-2001)
% Check arguments for consistency
errstring = consist(net, 'rbf', x, t);
if ~isempty(errstring);
error(errstring);
end
if nargin == 3
% Data term in Hessian needs to be computed
[a, z] = rbffwd(net, x);
hdata = datahess(net, z, t);
end
% Add in effect of regularisation
[h, hdata] = hbayes(net, hdata);
% Sub-function to compute data part of Hessian
function hdata = datahess(net, z, t)
% Only works for output layer Hessian currently
if (isfield(net, 'mask') & ~any(net.mask(...
1:(net.nwts - net.nout*(net.nhidden+1)))))
hdata = zeros(net.nwts);
ndata = size(z, 1);
out_hess = [z ones(ndata, 1)]'*[z ones(ndata, 1)];
for j = 1:net.nout
hdata = rearrange_hess(net, j, out_hess, hdata);
end
else
error('Output layer Hessian only.');
end
return
% Sub-function to rearrange Hessian matrix
function hdata = rearrange_hess(net, j, out_hess, hdata)
% Because all the biases come after all the input weights,
% we have to rearrange the blocks that make up the network Hessian.
% This function assumes that we are on the jth output and that all outputs
% are independent.
% Start of bias weights block
bb_start = net.nwts - net.nout + 1;
% Start of weight block for jth output
ob_start = net.nwts - net.nout*(net.nhidden+1) + (j-1)*net.nhidden...
+ 1;
% End of weight block for jth output
ob_end = ob_start + net.nhidden - 1;
% Index of bias weight
b_index = bb_start+(j-1);
% Put input weight block in right place
hdata(ob_start:ob_end, ob_start:ob_end) = out_hess(1:net.nhidden, ...
1:net.nhidden);
% Put second derivative of bias weight in right place
hdata(b_index, b_index) = out_hess(net.nhidden+1, net.nhidden+1);
% Put cross terms (input weight v bias weight) in right place
hdata(b_index, ob_start:ob_end) = out_hess(net.nhidden+1, ...
1:net.nhidden);
hdata(ob_start:ob_end, b_index) = out_hess(1:net.nhidden, ...
net.nhidden+1);
return
|
github
|
siprob/arhmm_mcmc-master
|
dhmm_em.m
|
.m
|
arhmm_mcmc-master/HMMall/HMM/dhmm_em.m
| 4,081 |
utf_8
|
e23671f3809776edff04b1c4ec457169
|
function [LL, prior, transmat, obsmat, nrIterations] = ...
dhmm_em(data, prior, transmat, obsmat, varargin)
% LEARN_DHMM Find the ML/MAP parameters of an HMM with discrete outputs using EM.
% [ll_trace, prior, transmat, obsmat, iterNr] = learn_dhmm(data, prior0, transmat0, obsmat0, ...)
%
% Notation: Q(t) = hidden state, Y(t) = observation
%
% INPUTS:
% data{ex} or data(ex,:) if all sequences have the same length
% prior(i)
% transmat(i,j)
% obsmat(i,o)
%
% Optional parameters may be passed as 'param_name', param_value pairs.
% Parameter names are shown below; default values in [] - if none, argument is mandatory.
%
% 'max_iter' - max number of EM iterations [10]
% 'thresh' - convergence threshold [1e-4]
% 'verbose' - if 1, print out loglik at every iteration [1]
% 'obs_prior_weight' - weight to apply to uniform dirichlet prior on observation matrix [0]
%
% To clamp some of the parameters, so learning does not change them:
% 'adj_prior' - if 0, do not change prior [1]
% 'adj_trans' - if 0, do not change transmat [1]
% 'adj_obs' - if 0, do not change obsmat [1]
%
% Modified by Herbert Jaeger so xi are not computed individually
% but only their sum (over time) as xi_summed; this is the only way how they are used
% and it saves a lot of memory.
[max_iter, thresh, verbose, obs_prior_weight, adj_prior, adj_trans, adj_obs] = ...
process_options(varargin, 'max_iter', 10, 'thresh', 1e-4, 'verbose', 1, ...
'obs_prior_weight', 0, 'adj_prior', 1, 'adj_trans', 1, 'adj_obs', 1);
previous_loglik = -inf;
loglik = 0;
converged = 0;
num_iter = 1;
LL = [];
if ~iscell(data)
data = num2cell(data, 2); % each row gets its own cell
end
while (num_iter <= max_iter) & ~converged
% E step
[loglik, exp_num_trans, exp_num_visits1, exp_num_emit] = ...
compute_ess_dhmm(prior, transmat, obsmat, data, obs_prior_weight);
% M step
if adj_prior
prior = normalise(exp_num_visits1);
end
if adj_trans & ~isempty(exp_num_trans)
transmat = mk_stochastic(exp_num_trans);
end
if adj_obs
obsmat = mk_stochastic(exp_num_emit);
end
if verbose, fprintf(1, 'iteration %d, loglik = %f\n', num_iter, loglik); end
num_iter = num_iter + 1;
converged = em_converged(loglik, previous_loglik, thresh);
previous_loglik = loglik;
LL = [LL loglik];
end
nrIterations = num_iter - 1;
%%%%%%%%%%%%%%%%%%%%%%%
function [loglik, exp_num_trans, exp_num_visits1, exp_num_emit, exp_num_visitsT] = ...
compute_ess_dhmm(startprob, transmat, obsmat, data, dirichlet)
% COMPUTE_ESS_DHMM Compute the Expected Sufficient Statistics for an HMM with discrete outputs
% function [loglik, exp_num_trans, exp_num_visits1, exp_num_emit, exp_num_visitsT] = ...
% compute_ess_dhmm(startprob, transmat, obsmat, data, dirichlet)
%
% INPUTS:
% startprob(i)
% transmat(i,j)
% obsmat(i,o)
% data{seq}(t)
% dirichlet - weighting term for uniform dirichlet prior on expected emissions
%
% OUTPUTS:
% exp_num_trans(i,j) = sum_l sum_{t=2}^T Pr(X(t-1) = i, X(t) = j| Obs(l))
% exp_num_visits1(i) = sum_l Pr(X(1)=i | Obs(l))
% exp_num_visitsT(i) = sum_l Pr(X(T)=i | Obs(l))
% exp_num_emit(i,o) = sum_l sum_{t=1}^T Pr(X(t) = i, O(t)=o| Obs(l))
% where Obs(l) = O_1 .. O_T for sequence l.
numex = length(data);
[S O] = size(obsmat);
exp_num_trans = zeros(S,S);
exp_num_visits1 = zeros(S,1);
exp_num_visitsT = zeros(S,1);
exp_num_emit = dirichlet*ones(S,O);
loglik = 0;
for ex=1:numex
obs = data{ex};
T = length(obs);
%obslik = eval_pdf_cond_multinomial(obs, obsmat);
obslik = multinomial_prob(obs, obsmat);
[alpha, beta, gamma, current_ll, xi_summed] = fwdback(startprob, transmat, obslik);
loglik = loglik + current_ll;
exp_num_trans = exp_num_trans + xi_summed;
exp_num_visits1 = exp_num_visits1 + gamma(:,1);
exp_num_visitsT = exp_num_visitsT + gamma(:,T);
% loop over whichever is shorter
if T < O
for t=1:T
o = obs(t);
exp_num_emit(:,o) = exp_num_emit(:,o) + gamma(:,t);
end
else
for o=1:O
ndx = find(obs==o);
if ~isempty(ndx)
exp_num_emit(:,o) = exp_num_emit(:,o) + sum(gamma(:, ndx), 2);
end
end
end
end
|
github
|
siprob/arhmm_mcmc-master
|
mhmm_em.m
|
.m
|
arhmm_mcmc-master/HMMall/HMM/mhmm_em.m
| 5,884 |
utf_8
|
f63c5cc11c6d1ae9f2a0a94d8d639218
|
function [LL, prior, transmat, mu, Sigma, mixmat] = ...
mhmm_em(data, prior, transmat, mu, Sigma, mixmat, varargin);
% LEARN_MHMM Compute the ML parameters of an HMM with (mixtures of) Gaussians output using EM.
% [ll_trace, prior, transmat, mu, sigma, mixmat] = learn_mhmm(data, ...
% prior0, transmat0, mu0, sigma0, mixmat0, ...)
%
% Notation: Q(t) = hidden state, Y(t) = observation, M(t) = mixture variable
%
% INPUTS:
% data{ex}(:,t) or data(:,t,ex) if all sequences have the same length
% prior(i) = Pr(Q(1) = i),
% transmat(i,j) = Pr(Q(t+1)=j | Q(t)=i)
% mu(:,j,k) = E[Y(t) | Q(t)=j, M(t)=k ]
% Sigma(:,:,j,k) = Cov[Y(t) | Q(t)=j, M(t)=k]
% mixmat(j,k) = Pr(M(t)=k | Q(t)=j) : set to [] or ones(Q,1) if only one mixture component
%
% Optional parameters may be passed as 'param_name', param_value pairs.
% Parameter names are shown below; default values in [] - if none, argument is mandatory.
%
% 'max_iter' - max number of EM iterations [10]
% 'thresh' - convergence threshold [1e-4]
% 'verbose' - if 1, print out loglik at every iteration [1]
% 'cov_type' - 'full', 'diag' or 'spherical' ['full']
%
% To clamp some of the parameters, so learning does not change them:
% 'adj_prior' - if 0, do not change prior [1]
% 'adj_trans' - if 0, do not change transmat [1]
% 'adj_mix' - if 0, do not change mixmat [1]
% 'adj_mu' - if 0, do not change mu [1]
% 'adj_Sigma' - if 0, do not change Sigma [1]
%
% If the number of mixture components differs depending on Q, just set the trailing
% entries of mixmat to 0, e.g., 2 components if Q=1, 3 components if Q=2,
% then set mixmat(1,3)=0. In this case, B2(1,3,:)=1.0.
if ~isempty(varargin) & ~isstr(varargin{1}) % catch old syntax
error('optional arguments should be passed as string/value pairs')
end
[max_iter, thresh, verbose, cov_type, adj_prior, adj_trans, adj_mix, adj_mu, adj_Sigma, fun_eta, rcorr] = ...
process_options(varargin, 'max_iter', 10, 'thresh', 1e-4, 'verbose', 1, ...
'cov_type', 'full', 'adj_prior', 1, 'adj_trans', 1, 'adj_mix', 1, ...
'adj_mu', 1, 'adj_Sigma', 1, 'fun_eta', @mixgauss_prob, 'rcorr', data);
previous_loglik = -inf;
loglik = 0;
converged = 0;
num_iter = 1;
LL = [];
if ~iscell(data)
data = num2cell(data, [1 2]); % each elt of the 3rd dim gets its own cell
end
numex = length(data);
O = size(data{1},1);
Q = length(prior);
if isempty(mixmat)
mixmat = ones(Q,1);
end
M = size(mixmat,2);
if M == 1
adj_mix = 0;
end
while (num_iter <= max_iter) & ~converged
zzz = tic; %ABC
% E step
[loglik, exp_num_trans, exp_num_visits1, postmix, m, ip, op] = ...
ess_mhmm(prior, transmat, mixmat, mu, Sigma, data, fun_eta, rcorr);
% M step
if adj_prior
prior = normalise(exp_num_visits1);
end
if adj_trans
transmat = mk_stochastic(exp_num_trans);
end
if adj_mix
mixmat = mk_stochastic(postmix);
end
if adj_mu | adj_Sigma
[mu2, Sigma2] = mixgauss_Mstep(postmix, m, op, ip, 'cov_type', cov_type);
if adj_mu
mu = reshape(mu2, [O Q M]);
end
if adj_Sigma
Sigma = reshape(Sigma2, [O O Q M]);
end
end
if verbose, fprintf(1, 'iteration %d, loglik = %f\n', num_iter, loglik); end
%fprintf('%f\n', loglik); %ABC
num_iter = num_iter + 1;
converged = em_converged(loglik, previous_loglik, thresh);
previous_loglik = loglik;
LL = [LL loglik];
%fprintf('%s\n', toc(zzz)); %ABC
%toc(zzz);
end
%%%%%%%%%
function [loglik, exp_num_trans, exp_num_visits1, postmix, m, ip, op] = ...
ess_mhmm(prior, transmat, mixmat, mu, Sigma, data, fun_eta, rcorr)
% ESS_MHMM Compute the Expected Sufficient Statistics for a MOG Hidden Markov Model.
%
% Outputs:
% exp_num_trans(i,j) = sum_l sum_{t=2}^T Pr(Q(t-1) = i, Q(t) = j| Obs(l))
% exp_num_visits1(i) = sum_l Pr(Q(1)=i | Obs(l))
%
% Let w(i,k,t,l) = P(Q(t)=i, M(t)=k | Obs(l))
% where Obs(l) = Obs(:,:,l) = O_1 .. O_T for sequence l
% Then
% postmix(i,k) = sum_l sum_t w(i,k,t,l) (posterior mixing weights/ responsibilities)
% m(:,i,k) = sum_l sum_t w(i,k,t,l) * Obs(:,t,l)
% ip(i,k) = sum_l sum_t w(i,k,t,l) * Obs(:,t,l)' * Obs(:,t,l)
% op(:,:,i,k) = sum_l sum_t w(i,k,t,l) * Obs(:,t,l) * Obs(:,t,l)'
verbose = 0;
%[O T numex] = size(data);
numex = length(data);
O = size(data{1},1);
Q = length(prior);
M = size(mixmat,2);
exp_num_trans = zeros(Q,Q);
exp_num_visits1 = zeros(Q,1);
postmix = zeros(Q,M);
m = zeros(O,Q,M);
op = zeros(O,O,Q,M);
ip = zeros(Q,M);
mix = (M>1);
loglik = 0;
if verbose, fprintf(1, 'forwards-backwards example # '); end
for ex=1:numex
if verbose, fprintf(1, '%d ', ex); end
%obs = data(:,:,ex);
obs = data{ex};
T = size(obs,2);
if mix
%[B, B2] = mixgauss_prob(obs, mu, Sigma, mixmat);
[B, B2] = fun_eta(rcorr, mu, Sigma, mixmat);
[alpha, beta, gamma, current_loglik, xi_summed, gamma2] = ...
fwdback(prior, transmat, B, 'obslik2', B2, 'mixmat', mixmat);
else
%B = mixgauss_prob(obs, mu, Sigma);
B = fun_eta(rcorr, mu, Sigma);
[alpha, beta, gamma, current_loglik, xi_summed] = fwdback(prior, transmat, B);
end
loglik = loglik + current_loglik;
if verbose, fprintf(1, 'll at ex %d = %f\n', ex, loglik); end
exp_num_trans = exp_num_trans + xi_summed; % sum(xi,3);
exp_num_visits1 = exp_num_visits1 + gamma(:,1);
if mix
postmix = postmix + sum(gamma2,3);
else
postmix = postmix + sum(gamma,2);
gamma2 = reshape(gamma, [Q 1 T]); % gamma2(i,m,t) = gamma(i,t)
end
for i=1:Q
for k=1:M
w = reshape(gamma2(i,k,:), [1 T]); % w(t) = w(i,k,t,l)
wobs = obs .* repmat(w, [O 1]); % wobs(:,t) = w(t) * obs(:,t)
m(:,i,k) = m(:,i,k) + sum(wobs, 2); % m(:) = sum_t w(t) obs(:,t)
op(:,:,i,k) = op(:,:,i,k) + wobs * obs'; % op(:,:) = sum_t w(t) * obs(:,t) * obs(:,t)'
ip(i,k) = ip(i,k) + sum(sum(wobs .* obs, 2)); % ip = sum_t w(t) * obs(:,t)' * obs(:,t)
end
end
end
if verbose, fprintf(1, '\n'); end
|
github
|
siprob/arhmm_mcmc-master
|
subv2ind.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/subv2ind.m
| 1,574 |
utf_8
|
e85d0bab88fc0d35b803436fa1dc0e15
|
function ndx = subv2ind(siz, subv)
% SUBV2IND Like the built-in sub2ind, but the subscripts are given as row vectors.
% ind = subv2ind(siz,subv)
%
% siz can be a row or column vector of size d.
% subv should be a collection of N row vectors of size d.
% ind will be of size N * 1.
%
% Example:
% subv = [1 1 1;
% 2 1 1;
% ...
% 2 2 2];
% subv2ind([2 2 2], subv) returns [1 2 ... 8]'
% i.e., the leftmost digit toggles fastest.
%
% See also IND2SUBV.
if isempty(subv)
ndx = [];
return;
end
if isempty(siz)
ndx = 1;
return;
end
[ncases ndims] = size(subv);
%if length(siz) ~= ndims
% error('length of subscript vector and sizes must be equal');
%end
if all(siz==2)
%rbits = subv(:,end:-1:1)-1; % read from right to left, convert to 0s/1s
%ndx = bitv2dec(rbits)+1;
twos = pow2(0:ndims-1);
ndx = ((subv-1) * twos(:)) + 1;
%ndx = sum((subv-1) .* twos(ones(ncases,1), :), 2) + 1; % equivalent to matrix * vector
%ndx = sum((subv-1) .* repmat(twos, ncases, 1), 2) + 1; % much slower than ones
%ndx = ndx(:)';
else
%siz = siz(:)';
cp = [1 cumprod(siz(1:end-1))]';
%ndx = ones(ncases, 1);
%for i = 1:ndims
% ndx = ndx + (subv(:,i)-1)*cp(i);
%end
ndx = (subv-1)*cp + 1;
end
%%%%%%%%%%%
function d = bitv2dec(bits)
% BITV2DEC Convert a bit vector to a decimal integer
% d = butv2dec(bits)
%
% This is just like the built-in bin2dec, except the argument is a vector, not a string.
% If bits is an array, each row will be converted.
[m n] = size(bits);
twos = pow2(n-1:-1:0);
d = sum(bits .* twos(ones(m,1),:),2);
|
github
|
siprob/arhmm_mcmc-master
|
zipload.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/zipload.m
| 1,611 |
utf_8
|
67412c21b14bebb640784443e9e3bbd8
|
%ZIPLOAD Load compressed data file created with ZIPSAVE
%
% [data] = zipload( filename )
% filename: string variable that contains the name of the
% compressed file (do not include '.zip' extension)
% Use only with files created with 'zipsave'
% pkzip25.exe has to be in the matlab path. This file is a compression utility
% made by Pkware, Inc. It can be dowloaded from: http://www.pkware.com
% Or directly from ftp://ftp.pkware.com/pk250c32.exe, for the Windows 95/NT version.
% This function was tested using 'PKZIP 2.50 Command Line for Windows 9x/NT'
% It is important to use version 2.5 of the utility. Otherwise the command line below
% has to be changed to include the proper options of the compression utility you
% wish to use.
% This function was tested in MATLAB Version 5.3 under Windows NT.
% Fernando A. Brucher - May/25/1999
%
% Example:
% [loadedData] = zipload('testfile');
%--------------------------------------------------------------------
function [data] = zipload( filename )
%--- Decompress data file by calling pkzip (comand line command) ---
% Options used:
% 'extract' = decompress file
% 'silent' = no console output
% 'over=all' = overwrite files
%eval( ['!pkzip25 -extract -silent -over=all ', filename, '.zip'] )
eval( ['!pkzip25 -extract -silent -over=all ', filename, '.zip'] )
%--- Load data from decompressed file ---
% try, catch takes care of cases when pkzip fails to decompress a
% valid matlab format file
try
tmpStruc = load( filename );
data = tmpStruc.data;
catch, return, end
%--- Delete decompressed file ---
delete( [filename,'.mat'] )
|
github
|
siprob/arhmm_mcmc-master
|
plot_ellipse.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/plot_ellipse.m
| 507 |
utf_8
|
3a27bbd5c1bdfe99983171e96789da6d
|
% PLOT_ELLIPSE
% h=plot_ellipse(x,y,theta,a,b)
%
% This routine plots an ellipse with centre (x,y), axis lengths a,b
% with major axis at an angle of theta radians from the horizontal.
%
% Author: P. Fieguth
% Jan. 98
%
%http://ocho.uwaterloo.ca/~pfieguth/Teaching/372/plot_ellipse.m
function h=plot_ellipse(x,y,theta,a,b)
np = 100;
ang = [0:np]*2*pi/np;
R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
pts = [x;y]*ones(size(ang)) + R*[cos(ang)*a; sin(ang)*b];
h=plot( pts(1,:), pts(2,:) );
|
github
|
siprob/arhmm_mcmc-master
|
bipartiteMatchingHungarian.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/bipartiteMatchingHungarian.m
| 2,593 |
utf_8
|
983df7bc538a844b42427ae58d69c75b
|
% MATCH - Solves the weighted bipartite matching (or assignment)
% problem.
%
% Usage: a = match(C);
%
% Arguments:
% C - an m x n cost matrix; the sets are taken to be
% 1:m and 1:n; C(i, j) gives the cost of matching
% items i (of the first set) and j (of the second set)
%
% Returns:
%
% a - an m x 1 assignment vector, which gives the
% minimum cost assignment. a(i) is the index of
% the item of 1:n that was matched to item i of
% 1:m. If item i (of 1:m) was not matched to any
% item of 1:n, then a(i) is zero.
% Copyright (C) 2002 Mark A. Paskin
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
% USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [a] = optimalMatching(C)
% Trivial cases:
[p, q] = size(C);
if (p == 0)
a = [];
return;
elseif (q == 0)
a = zeros(p, 1);
return;
end
if 0
% First, reduce the problem by making easy optimal matches. If two
% elements agree that they are the best match, then match them up.
[x, a] = min(C, [], 2);
[y, b] = min(C, [], 1);
u = find(1:p ~= b(a(:)));
a(u) = 0;
v = find(1:q ~= a(b(:))');
C = C(u, v);
if (isempty(C)) return; end
end
% Get the (new) size of the two sets, u and v.
[m, n] = size(C);
%mx = realmax;
mx = 2*max(C(:));
mn = -2*min(C(:));
% Pad the affinity matrix to be square
if (m < n)
C = [C; mx * ones(n - m, n)];
elseif (n < m)
C = [C, mx * ones(m, m - n)];
end
% Run the Hungarian method. First replace infinite values by the
% largest (or smallest) finite values.
C(find(isinf(C) & (C > 0))) = mx;
C(find(isinf(C) & (C < 0))) = mn;
%fprintf('running hungarian\n');
[b, cost] = hungarian(C');
% Extract only the real assignments
ap = b(1:m)';
ap(find(ap > n)) = 0;
a = ap;
%% Incorporate this sub-assignment into the complete assignment
% k = find(ap);
% a(u(k)) = v(ap(k));
|
github
|
siprob/arhmm_mcmc-master
|
conf2mahal.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/conf2mahal.m
| 2,424 |
utf_8
|
682226ca8c1183325f4204e0c22de0a7
|
% CONF2MAHAL - Translates a confidence interval to a Mahalanobis
% distance. Consider a multivariate Gaussian
% distribution of the form
%
% p(x) = 1/sqrt((2 * pi)^d * det(C)) * exp((-1/2) * MD(x, m, inv(C)))
%
% where MD(x, m, P) is the Mahalanobis distance from x
% to m under P:
%
% MD(x, m, P) = (x - m) * P * (x - m)'
%
% A particular Mahalanobis distance k identifies an
% ellipsoid centered at the mean of the distribution.
% The confidence interval associated with this ellipsoid
% is the probability mass enclosed by it. Similarly,
% a particular confidence interval uniquely determines
% an ellipsoid with a fixed Mahalanobis distance.
%
% If X is an d dimensional Gaussian-distributed vector,
% then the Mahalanobis distance of X is distributed
% according to the Chi-squared distribution with d
% degrees of freedom. Thus, the Mahalanobis distance is
% determined by evaluating the inverse cumulative
% distribution function of the chi squared distribution
% up to the confidence value.
%
% Usage:
%
% m = conf2mahal(c, d);
%
% Inputs:
%
% c - the confidence interval
% d - the number of dimensions of the Gaussian distribution
%
% Outputs:
%
% m - the Mahalanobis radius of the ellipsoid enclosing the
% fraction c of the distribution's probability mass
%
% See also: MAHAL2CONF
% Copyright (C) 2002 Mark A. Paskin
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
% USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function m = conf2mahal(c, d)
m = chi2inv(c, d);
|
github
|
siprob/arhmm_mcmc-master
|
plotgauss2d.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/plotgauss2d.m
| 4,119 |
utf_8
|
1bf48827c7a74f224086a54411e4ac82
|
function h=plotgauss2d(mu, Sigma)
% PLOTGAUSS2D Plot a 2D Gaussian as an ellipse with optional cross hairs
% h=plotgauss2(mu, Sigma)
%
h = plotcov2(mu, Sigma);
return;
%%%%%%%%%%%%%%%%%%%%%%%%
% PLOTCOV2 - Plots a covariance ellipse with major and minor axes
% for a bivariate Gaussian distribution.
%
% Usage:
% h = plotcov2(mu, Sigma[, OPTIONS]);
%
% Inputs:
% mu - a 2 x 1 vector giving the mean of the distribution.
% Sigma - a 2 x 2 symmetric positive semi-definite matrix giving
% the covariance of the distribution (or the zero matrix).
%
% Options:
% 'conf' - a scalar between 0 and 1 giving the confidence
% interval (i.e., the fraction of probability mass to
% be enclosed by the ellipse); default is 0.9.
% 'num-pts' - the number of points to be used to plot the
% ellipse; default is 100.
%
% This function also accepts options for PLOT.
%
% Outputs:
% h - a vector of figure handles to the ellipse boundary and
% its major and minor axes
%
% See also: PLOTCOV3
% Copyright (C) 2002 Mark A. Paskin
function h = plotcov2(mu, Sigma, varargin)
if size(Sigma) ~= [2 2], error('Sigma must be a 2 by 2 matrix'); end
if length(mu) ~= 2, error('mu must be a 2 by 1 vector'); end
[p, ...
n, ...
plot_opts] = process_options(varargin, 'conf', 0.9, ...
'num-pts', 100);
h = [];
holding = ishold;
if (Sigma == zeros(2, 2))
z = mu;
else
% Compute the Mahalanobis radius of the ellipsoid that encloses
% the desired probability mass.
k = conf2mahal(p, 2);
% The major and minor axes of the covariance ellipse are given by
% the eigenvectors of the covariance matrix. Their lengths (for
% the ellipse with unit Mahalanobis radius) are given by the
% square roots of the corresponding eigenvalues.
if (issparse(Sigma))
[V, D] = eigs(Sigma);
else
[V, D] = eig(Sigma);
end
% Compute the points on the surface of the ellipse.
t = linspace(0, 2*pi, n);
u = [cos(t); sin(t)];
w = (k * V * sqrt(D)) * u;
z = repmat(mu, [1 n]) + w;
% Plot the major and minor axes.
L = k * sqrt(diag(D));
h = plot([mu(1); mu(1) + L(1) * V(1, 1)], ...
[mu(2); mu(2) + L(1) * V(2, 1)], plot_opts{:});
hold on;
h = [h; plot([mu(1); mu(1) + L(2) * V(1, 2)], ...
[mu(2); mu(2) + L(2) * V(2, 2)], plot_opts{:})];
end
h = [h; plot(z(1, :), z(2, :), plot_opts{:})];
if (~holding) hold off; end
%%%%%%%%%%%%
% CONF2MAHAL - Translates a confidence interval to a Mahalanobis
% distance. Consider a multivariate Gaussian
% distribution of the form
%
% p(x) = 1/sqrt((2 * pi)^d * det(C)) * exp((-1/2) * MD(x, m, inv(C)))
%
% where MD(x, m, P) is the Mahalanobis distance from x
% to m under P:
%
% MD(x, m, P) = (x - m) * P * (x - m)'
%
% A particular Mahalanobis distance k identifies an
% ellipsoid centered at the mean of the distribution.
% The confidence interval associated with this ellipsoid
% is the probability mass enclosed by it. Similarly,
% a particular confidence interval uniquely determines
% an ellipsoid with a fixed Mahalanobis distance.
%
% If X is an d dimensional Gaussian-distributed vector,
% then the Mahalanobis distance of X is distributed
% according to the Chi-squared distribution with d
% degrees of freedom. Thus, the Mahalanobis distance is
% determined by evaluating the inverse cumulative
% distribution function of the chi squared distribution
% up to the confidence value.
%
% Usage:
%
% m = conf2mahal(c, d);
%
% Inputs:
%
% c - the confidence interval
% d - the number of dimensions of the Gaussian distribution
%
% Outputs:
%
% m - the Mahalanobis radius of the ellipsoid enclosing the
% fraction c of the distribution's probability mass
%
% See also: MAHAL2CONF
% Copyright (C) 2002 Mark A. Paskin
function m = conf2mahal(c, d)
m = chi2inv(c, d); % matlab stats toolbox
|
github
|
siprob/arhmm_mcmc-master
|
zipsave.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/zipsave.m
| 1,480 |
utf_8
|
cc543374345b9e369d147c452008bc36
|
%ZIPSAVE Save data in compressed format
%
% zipsave( filename, data )
% filename: string variable that contains the name of the resulting
% compressed file (do not include '.zip' extension)
% pkzip25.exe has to be in the matlab path. This file is a compression utility
% made by Pkware, Inc. It can be dowloaded from: http://www.pkware.com
% This function was tested using 'PKZIP 2.50 Command Line for Windows 9x/NT'
% It is important to use version 2.5 of the utility. Otherwise the command line below
% has to be changed to include the proper options of the compression utility you
% wish to use.
% This function was tested in MATLAB Version 5.3 under Windows NT.
% Fernando A. Brucher - May/25/1999
%
% Example:
% testData = [1 2 3; 4 5 6; 7 8 9];
% zipsave('testfile', testData);
%
% Modified by Kevin Murphy, 26 Feb 2004, to use winzip
%------------------------------------------------------------------------
function zipsave( filename, data )
%--- Save data in a temporary file in matlab format (.mat)---
eval( ['save ''', filename, ''' data'] )
%--- Compress data by calling pkzip (comand line command) ---
% Options used:
% 'add' = add compressed files to the resulting zip file
% 'silent' = no console output
% 'over=all' = overwrite files
%eval( ['!pkzip25 -silent -add -over=all ', filename, '.zip ', filename,'.mat'] )
eval( ['!zip ', filename, '.zip ', filename,'.mat'] )
%--- Delete temporary matlab format file ---
delete( [filename,'.mat'] )
|
github
|
siprob/arhmm_mcmc-master
|
matprint.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/matprint.m
| 1,020 |
utf_8
|
e92a96dad0e0b9f25d2fe56280ba6393
|
% MATPRINT - prints a matrix with specified format string
%
% Usage: matprint(a, fmt, fid)
%
% a - Matrix to be printed.
% fmt - C style format string to use for each value.
% fid - Optional file id.
%
% Eg. matprint(a,'%3.1f') will print each entry to 1 decimal place
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk @ csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% March 2002
function matprint(a, fmt, fid)
if nargin < 3
fid = 1;
end
[rows,cols] = size(a);
% Construct a format string for each row of the matrix consisting of
% 'cols' copies of the number formating specification
fmtstr = [];
for c = 1:cols
fmtstr = [fmtstr, ' ', fmt];
end
fmtstr = [fmtstr '\n']; % Add a line feed
fprintf(fid, fmtstr, a'); % Print the transpose of the matrix because
% fprintf runs down the columns of a matrix.
|
github
|
siprob/arhmm_mcmc-master
|
plotcov3.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/plotcov3.m
| 4,040 |
utf_8
|
1f186acd56002148a3da006a9fc8b6a2
|
% PLOTCOV3 - Plots a covariance ellipsoid with axes for a trivariate
% Gaussian distribution.
%
% Usage:
% [h, s] = plotcov3(mu, Sigma[, OPTIONS]);
%
% Inputs:
% mu - a 3 x 1 vector giving the mean of the distribution.
% Sigma - a 3 x 3 symmetric positive semi-definite matrix giving
% the covariance of the distribution (or the zero matrix).
%
% Options:
% 'conf' - a scalar between 0 and 1 giving the confidence
% interval (i.e., the fraction of probability mass to
% be enclosed by the ellipse); default is 0.9.
% 'num-pts' - if the value supplied is n, then (n + 1)^2 points
% to be used to plot the ellipse; default is 20.
% 'plot-opts' - a cell vector of arguments to be handed to PLOT3
% to contol the appearance of the axes, e.g.,
% {'Color', 'g', 'LineWidth', 1}; the default is {}
% 'surf-opts' - a cell vector of arguments to be handed to SURF
% to contol the appearance of the ellipsoid
% surface; a nice possibility that yields
% transparency is: {'EdgeAlpha', 0, 'FaceAlpha',
% 0.1, 'FaceColor', 'g'}; the default is {}
%
% Outputs:
% h - a vector of handles on the axis lines
% s - a handle on the ellipsoid surface object
%
% See also: PLOTCOV2
% Copyright (C) 2002 Mark A. Paskin
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
% USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [h, s] = plotcov3(mu, Sigma, varargin)
if size(Sigma) ~= [3 3], error('Sigma must be a 3 by 3 matrix'); end
if length(mu) ~= 3, error('mu must be a 3 by 1 vector'); end
[p, ...
n, ...
plot_opts, ...
surf_opts] = process_options(varargin, 'conf', 0.9, ...
'num-pts', 20, ...
'plot-opts', {}, ...
'surf-opts', {});
h = [];
holding = ishold;
if (Sigma == zeros(3, 3))
z = mu;
else
% Compute the Mahalanobis radius of the ellipsoid that encloses
% the desired probability mass.
k = conf2mahal(p, 3);
% The axes of the covariance ellipse are given by the eigenvectors of
% the covariance matrix. Their lengths (for the ellipse with unit
% Mahalanobis radius) are given by the square roots of the
% corresponding eigenvalues.
if (issparse(Sigma))
[V, D] = eigs(Sigma);
else
[V, D] = eig(Sigma);
end
if (any(diag(D) < 0))
error('Invalid covariance matrix: not positive semi-definite.');
end
% Compute the points on the surface of the ellipsoid.
t = linspace(0, 2*pi, n);
[X, Y, Z] = sphere(n);
u = [X(:)'; Y(:)'; Z(:)'];
w = (k * V * sqrt(D)) * u;
z = repmat(mu(:), [1 (n + 1)^2]) + w;
% Plot the axes.
L = k * sqrt(diag(D));
h = plot3([mu(1); mu(1) + L(1) * V(1, 1)], ...
[mu(2); mu(2) + L(1) * V(2, 1)], ...
[mu(3); mu(3) + L(1) * V(3, 1)], plot_opts{:});
hold on;
h = [h; plot3([mu(1); mu(1) + L(2) * V(1, 2)], ...
[mu(2); mu(2) + L(2) * V(2, 2)], ...
[mu(3); mu(3) + L(2) * V(3, 2)], plot_opts{:})];
h = [h; plot3([mu(1); mu(1) + L(3) * V(1, 3)], ...
[mu(2); mu(2) + L(3) * V(2, 3)], ...
[mu(3); mu(3) + L(3) * V(3, 3)], plot_opts{:})];
end
s = surf(reshape(z(1, :), [(n + 1) (n + 1)]), ...
reshape(z(2, :), [(n + 1) (n + 1)]), ...
reshape(z(3, :), [(n + 1) (n + 1)]), ...
surf_opts{:});
if (~holding) hold off; end
|
github
|
siprob/arhmm_mcmc-master
|
exportfig.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/exportfig.m
| 30,663 |
utf_8
|
838a8ee93ca6a9b6a85a90fa68976617
|
function varargout = exportfig(varargin)
%EXPORTFIG Export a figure.
% EXPORTFIG(H, FILENAME) writes the figure H to FILENAME. H is
% a figure handle and FILENAME is a string that specifies the
% name of the output file.
%
% EXPORTFIG(H, FILENAME, OPTIONS) writes the figure H to FILENAME
% with options initially specified by the structure OPTIONS. The
% field names of OPTIONS must be legal parameters listed below
% and the field values must be legal values for the corresponding
% parameter. Default options can be set in releases prior to R12
% by storing the OPTIONS structure in the root object's appdata
% with the command
% setappdata(0,'exportfigdefaults', OPTIONS)
% and for releases after R12 by setting the preference with the
% command
% setpref('exportfig', 'defaults', OPTIONS)
%
% EXPORTFIG(...,PARAM1,VAL1,PARAM2,VAL2,...) specifies
% parameters that control various characteristics of the output
% file. Any parameter value can be the string 'auto' which means
% the parameter uses the default factory behavior, overriding
% any other default for the parameter.
%
% Format Paramter:
% 'Format' a string
% specifies the output format. Defaults to 'eps'. For a
% list of export formats type 'help print'.
% 'Preview' one of the strings 'none', 'tiff'
% specifies a preview for EPS files. Defaults to 'none'.
%
% Size Parameters:
% 'Width' a positive scalar
% specifies the width in the figure's PaperUnits
% 'Height' a positive scalar
% specifies the height in the figure's PaperUnits
% 'Bounds' one of the strings 'tight', 'loose'
% specifies a tight or loose bounding box. Defaults to 'tight'.
% 'Reference' an axes handle or a string
% specifies that the width and height parameters
% are relative to the given axes. If a string is
% specified then it must evaluate to an axes handle.
%
% Specifying only one dimension sets the other dimension
% so that the exported aspect ratio is the same as the
% figure's or reference axes' current aspect ratio.
% If neither dimension is specified the size defaults to
% the width and height from the figure's or reference
% axes' size. Tight bounding boxes are only computed for
% 2-D views and in that case the computed bounds enclose all
% text objects.
%
% Rendering Parameters:
% 'Color' one of the strings 'bw', 'gray', 'cmyk'
% 'bw' specifies that lines and text are exported in
% black and all other objects in grayscale
% 'gray' specifies that all objects are exported in grayscale
% 'rgb' specifies that all objects are exported in color
% using the RGB color space
% 'cmyk' specifies that all objects are exported in color
% using the CMYK color space
% 'Renderer' one of 'painters', 'zbuffer', 'opengl'
% specifies the renderer to use
% 'Resolution' a positive scalar
% specifies the resolution in dots-per-inch.
% 'LockAxes' one of 0 or 1
% specifies that all axes limits and ticks should be fixed
% while exporting.
%
% The default color setting is 'bw'.
%
% Font Parameters:
% 'FontMode' one of the strings 'scaled', 'fixed'
% 'FontSize' a positive scalar
% in 'scaled' mode multiplies with the font size of each
% text object to obtain the exported font size
% in 'fixed' mode specifies the font size of all text
% objects in points
% 'DefaultFixedFontSize' a positive scalar
% in 'fixed' mode specified the default font size in
% points
% 'FontSizeMin' a positive scalar
% specifies the minimum font size allowed after scaling
% 'FontSizeMax' a positive scalar
% specifies the maximum font size allowed after scaling
% 'FontEncoding' one of the strings 'latin1', 'adobe'
% specifies the character encoding of the font
% 'SeparateText' one of 0 or 1
% specifies that the text objects are stored in separate
% file as EPS with the base filename having '_t' appended.
%
% If FontMode is 'scaled' but FontSize is not specified then a
% scaling factor is computed from the ratio of the size of the
% exported figure to the size of the actual figure.
%
% The default 'FontMode' setting is 'scaled'.
%
% Line Width Parameters:
% 'LineMode' one of the strings 'scaled', 'fixed'
% 'LineWidth' a positive scalar
% 'DefaultFixedLineWidth' a positive scalar
% 'LineWidthMin' a positive scalar
% specifies the minimum line width allowed after scaling
% 'LineWidthMax' a positive scalar
% specifies the maximum line width allowed after scaling
% The semantics of 'Line' parameters are exactly the
% same as the corresponding 'Font' parameters, except that
% they apply to line widths instead of font sizes.
%
% Style Map Parameter:
% 'LineStyleMap' one of [], 'bw', or a function name or handle
% specifies how to map line colors to styles. An empty
% style map means styles are not changed. The style map
% 'bw' is a built-in mapping that maps lines with the same
% color to the same style and otherwise cycles through the
% available styles. A user-specified map is a function
% that takes as input a cell array of line objects and
% outputs a cell array of line style strings. The default
% map is [].
%
% Examples:
% exportfig(gcf,'fig1.eps','height',3);
% Exports the current figure to the file named 'fig1.eps' with
% a height of 3 inches (assuming the figure's PaperUnits is
% inches) and an aspect ratio the same as the figure's aspect
% ratio on screen.
%
% opts = struct('FontMode','fixed','FontSize',10,'height',3);
% exportfig(gcf, 'fig2.eps', opts, 'height', 5);
% Exports the current figure to 'fig2.eps' with all
% text in 10 point fonts and with height 5 inches.
%
% See also PREVIEWFIG, APPLYTOFIG, RESTOREFIG, PRINT.
% Copyright 2000 Ben Hinkle
% Email bug reports and comments to [email protected]
if (nargin < 2)
error('Too few input arguments');
end
% exportfig(H, filename, [options,] ...)
H = varargin{1};
if ~LocalIsHG(H,'figure')
error('First argument must be a handle to a figure.');
end
filename = varargin{2};
if ~ischar(filename)
error('Second argument must be a string.');
end
paramPairs = {varargin{3:end}};
if nargin > 2
if isstruct(paramPairs{1})
pcell = LocalToCell(paramPairs{1});
paramPairs = {pcell{:}, paramPairs{2:end}};
end
end
verstr = version;
majorver = str2num(verstr(1));
defaults = [];
if majorver > 5
if ispref('exportfig','defaults')
defaults = getpref('exportfig','defaults');
end
elseif exist('getappdata')
defaults = getappdata(0,'exportfigdefaults');
end
if ~isempty(defaults)
dcell = LocalToCell(defaults);
paramPairs = {dcell{:}, paramPairs{:}};
end
% Do some validity checking on param-value pairs
if (rem(length(paramPairs),2) ~= 0)
error(['Invalid input syntax. Optional parameters and values' ...
' must be in pairs.']);
end
auto.format = 'eps';
auto.preview = 'none';
auto.width = -1;
auto.height = -1;
auto.color = 'bw';
auto.defaultfontsize=10;
auto.fontsize = -1;
auto.fontmode='scaled';
auto.fontmin = 8;
auto.fontmax = 60;
auto.defaultlinewidth = 1.0;
auto.linewidth = -1;
auto.linemode=[];
auto.linemin = 0.5;
auto.linemax = 100;
auto.fontencoding = 'latin1';
auto.renderer = [];
auto.resolution = [];
auto.stylemap = [];
auto.applystyle = 0;
auto.refobj = -1;
auto.bounds = 'tight';
explicitbounds = 0;
auto.lockaxes = 1;
auto.separatetext = 0;
opts = auto;
% Process param-value pairs
args = {};
for k = 1:2:length(paramPairs)
param = lower(paramPairs{k});
if ~ischar(param)
error('Optional parameter names must be strings');
end
value = paramPairs{k+1};
switch (param)
case 'format'
opts.format = LocalCheckAuto(lower(value),auto.format);
if strcmp(opts.format,'preview')
error(['Format ''preview'' no longer supported. Use PREVIEWFIG' ...
' instead.']);
end
case 'preview'
opts.preview = LocalCheckAuto(lower(value),auto.preview);
if ~strcmp(opts.preview,{'none','tiff'})
error('Preview must be ''none'' or ''tiff''.');
end
case 'width'
opts.width = LocalToNum(value, auto.width);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.width)
error('Width must be a numeric scalar > 0');
end
end
case 'height'
opts.height = LocalToNum(value, auto.height);
if ~ischar(value) | ~strcmp(value,'auto')
if(~LocalIsPositiveScalar(opts.height))
error('Height must be a numeric scalar > 0');
end
end
case 'color'
opts.color = LocalCheckAuto(lower(value),auto.color);
if ~strcmp(opts.color,{'bw','gray','rgb','cmyk'})
error('Color must be ''bw'', ''gray'',''rgb'' or ''cmyk''.');
end
case 'fontmode'
opts.fontmode = LocalCheckAuto(lower(value),auto.fontmode);
if ~strcmp(opts.fontmode,{'scaled','fixed'})
error('FontMode must be ''scaled'' or ''fixed''.');
end
case 'fontsize'
opts.fontsize = LocalToNum(value,auto.fontsize);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.fontsize)
error('FontSize must be a numeric scalar > 0');
end
end
case 'defaultfixedfontsize'
opts.defaultfontsize = LocalToNum(value,auto.defaultfontsize);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.defaultfontsize)
error('DefaultFixedFontSize must be a numeric scalar > 0');
end
end
case 'fontsizemin'
opts.fontmin = LocalToNum(value,auto.fontmin);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.fontmin)
error('FontSizeMin must be a numeric scalar > 0');
end
end
case 'fontsizemax'
opts.fontmax = LocalToNum(value,auto.fontmax);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.fontmax)
error('FontSizeMax must be a numeric scalar > 0');
end
end
case 'fontencoding'
opts.fontencoding = LocalCheckAuto(lower(value),auto.fontencoding);
if ~strcmp(opts.fontencoding,{'latin1','adobe'})
error('FontEncoding must be ''latin1'' or ''adobe''.');
end
case 'linemode'
opts.linemode = LocalCheckAuto(lower(value),auto.linemode);
if ~strcmp(opts.linemode,{'scaled','fixed'})
error('LineMode must be ''scaled'' or ''fixed''.');
end
case 'linewidth'
opts.linewidth = LocalToNum(value,auto.linewidth);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.linewidth)
error('LineWidth must be a numeric scalar > 0');
end
end
case 'defaultfixedlinewidth'
opts.defaultlinewidth = LocalToNum(value,auto.defaultlinewidth);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.defaultlinewidth)
error(['DefaultFixedLineWidth must be a numeric scalar >' ...
' 0']);
end
end
case 'linewidthmin'
opts.linemin = LocalToNum(value,auto.linemin);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.linemin)
error('LineWidthMin must be a numeric scalar > 0');
end
end
case 'linewidthmax'
opts.linemax = LocalToNum(value,auto.linemax);
if ~ischar(value) | ~strcmp(value,'auto')
if ~LocalIsPositiveScalar(opts.linemax)
error('LineWidthMax must be a numeric scalar > 0');
end
end
case 'linestylemap'
opts.stylemap = LocalCheckAuto(value,auto.stylemap);
case 'renderer'
opts.renderer = LocalCheckAuto(lower(value),auto.renderer);
if ~ischar(value) | ~strcmp(value,'auto')
if ~strcmp(opts.renderer,{'painters','zbuffer','opengl'})
error(['Renderer must be ''painters'', ''zbuffer'' or' ...
' ''opengl''.']);
end
end
case 'resolution'
opts.resolution = LocalToNum(value,auto.resolution);
if ~ischar(value) | ~strcmp(value,'auto')
if ~(isnumeric(value) & (prod(size(value)) == 1) & (value >= 0));
error('Resolution must be a numeric scalar >= 0');
end
end
case 'applystyle' % means to apply the options and not export
opts.applystyle = 1;
case 'reference'
if ischar(value)
if strcmp(value,'auto')
opts.refobj = auto.refobj;
else
opts.refobj = eval(value);
end
else
opts.refobj = value;
end
if ~LocalIsHG(opts.refobj,'axes')
error('Reference object must evaluate to an axes handle.');
end
case 'bounds'
opts.bounds = LocalCheckAuto(lower(value),auto.bounds);
explicitbounds = 1;
if ~strcmp(opts.bounds,{'tight','loose'})
error('Bounds must be ''tight'' or ''loose''.');
end
case 'lockaxes'
opts.lockaxes = LocalToNum(value,auto.lockaxes);
case 'separatetext'
opts.separatetext = LocalToNum(value,auto.separatetext);
otherwise
error(['Unrecognized option ' param '.']);
end
end
% make sure figure is up-to-date
drawnow;
allLines = findall(H, 'type', 'line');
allText = findall(H, 'type', 'text');
allAxes = findall(H, 'type', 'axes');
allImages = findall(H, 'type', 'image');
allLights = findall(H, 'type', 'light');
allPatch = findall(H, 'type', 'patch');
allSurf = findall(H, 'type', 'surface');
allRect = findall(H, 'type', 'rectangle');
allFont = [allText; allAxes];
allColor = [allLines; allText; allAxes; allLights];
allMarker = [allLines; allPatch; allSurf];
allEdge = [allPatch; allSurf];
allCData = [allImages; allPatch; allSurf];
old.objs = {};
old.prop = {};
old.values = {};
% Process format
if strncmp(opts.format,'eps',3) & ~strcmp(opts.preview,'none')
args = {args{:}, ['-' opts.preview]};
end
hadError = 0;
oldwarn = warning;
try
% lock axes limits, ticks and labels if requested
if opts.lockaxes
old = LocalManualAxesMode(old, allAxes, 'TickMode');
old = LocalManualAxesMode(old, allAxes, 'TickLabelMode');
old = LocalManualAxesMode(old, allAxes, 'LimMode');
end
% Process size parameters
figurePaperUnits = get(H, 'PaperUnits');
oldFigureUnits = get(H, 'Units');
oldFigPos = get(H,'Position');
set(H, 'Units', figurePaperUnits);
figPos = get(H,'Position');
refsize = figPos(3:4);
if opts.refobj ~= -1
oldUnits = get(opts.refobj, 'Units');
set(opts.refobj, 'Units', figurePaperUnits);
r = get(opts.refobj, 'Position');
refsize = r(3:4);
set(opts.refobj, 'Units', oldUnits);
end
aspectRatio = refsize(1)/refsize(2);
if (opts.width == -1) & (opts.height == -1)
opts.width = refsize(1);
opts.height = refsize(2);
elseif (opts.width == -1)
opts.width = opts.height * aspectRatio;
elseif (opts.height == -1)
opts.height = opts.width / aspectRatio;
end
wscale = opts.width/refsize(1);
hscale = opts.height/refsize(2);
sizescale = min(wscale,hscale);
old = LocalPushOldData(old,H,'PaperPositionMode', ...
get(H,'PaperPositionMode'));
set(H, 'PaperPositionMode', 'auto');
newPos = [figPos(1) figPos(2)+figPos(4)*(1-hscale) ...
wscale*figPos(3) hscale*figPos(4)];
set(H, 'Position', newPos);
set(H, 'Units', oldFigureUnits);
% process line-style map
if ~isempty(opts.stylemap) & ~isempty(allLines)
oldlstyle = LocalGetAsCell(allLines,'LineStyle');
old = LocalPushOldData(old, allLines, {'LineStyle'}, ...
oldlstyle);
newlstyle = oldlstyle;
if ischar(opts.stylemap) & strcmpi(opts.stylemap,'bw')
newlstyle = LocalMapColorToStyle(allLines);
else
try
newlstyle = feval(opts.stylemap,allLines);
catch
warning(['Skipping stylemap. ' lasterr]);
end
end
set(allLines,{'LineStyle'},newlstyle);
end
% Process rendering parameters
switch (opts.color)
case {'bw', 'gray'}
if ~strcmp(opts.color,'bw') & strncmp(opts.format,'eps',3)
opts.format = [opts.format 'c'];
end
args = {args{:}, ['-d' opts.format]};
%compute and set gray colormap
oldcmap = get(H,'Colormap');
newgrays = 0.30*oldcmap(:,1) + 0.59*oldcmap(:,2) + 0.11*oldcmap(:,3);
newcmap = [newgrays newgrays newgrays];
old = LocalPushOldData(old, H, 'Colormap', oldcmap);
set(H, 'Colormap', newcmap);
%compute and set ColorSpec and CData properties
old = LocalUpdateColors(allColor, 'color', old);
old = LocalUpdateColors(allAxes, 'xcolor', old);
old = LocalUpdateColors(allAxes, 'ycolor', old);
old = LocalUpdateColors(allAxes, 'zcolor', old);
old = LocalUpdateColors(allMarker, 'MarkerEdgeColor', old);
old = LocalUpdateColors(allMarker, 'MarkerFaceColor', old);
old = LocalUpdateColors(allEdge, 'EdgeColor', old);
old = LocalUpdateColors(allEdge, 'FaceColor', old);
old = LocalUpdateColors(allCData, 'CData', old);
case {'rgb','cmyk'}
if strncmp(opts.format,'eps',3)
opts.format = [opts.format 'c'];
args = {args{:}, ['-d' opts.format]};
if strcmp(opts.color,'cmyk')
args = {args{:}, '-cmyk'};
end
else
args = {args{:}, ['-d' opts.format]};
end
otherwise
error('Invalid Color parameter');
end
if (~isempty(opts.renderer))
args = {args{:}, ['-' opts.renderer]};
end
if (~isempty(opts.resolution)) | ~strncmp(opts.format,'eps',3)
if isempty(opts.resolution)
opts.resolution = 0;
end
args = {args{:}, ['-r' int2str(opts.resolution)]};
end
% Process font parameters
if ~isempty(opts.fontmode)
oldfonts = LocalGetAsCell(allFont,'FontSize');
oldfontunits = LocalGetAsCell(allFont,'FontUnits');
set(allFont,'FontUnits','points');
switch (opts.fontmode)
case 'fixed'
if (opts.fontsize == -1)
set(allFont,'FontSize',opts.defaultfontsize);
else
set(allFont,'FontSize',opts.fontsize);
end
case 'scaled'
if (opts.fontsize == -1)
scale = sizescale;
else
scale = opts.fontsize;
end
newfonts = LocalScale(oldfonts,scale,opts.fontmin,opts.fontmax);
set(allFont,{'FontSize'},newfonts);
otherwise
error('Invalid FontMode parameter');
end
old = LocalPushOldData(old, allFont, {'FontSize'}, oldfonts);
old = LocalPushOldData(old, allFont, {'FontUnits'}, oldfontunits);
end
if strcmp(opts.fontencoding,'adobe') & strncmp(opts.format,'eps',3)
args = {args{:}, '-adobecset'};
end
% Process line parameters
if ~isempty(opts.linemode)
oldlines = LocalGetAsCell(allMarker,'LineWidth');
old = LocalPushOldData(old, allMarker, {'LineWidth'}, oldlines);
switch (opts.linemode)
case 'fixed'
if (opts.linewidth == -1)
set(allMarker,'LineWidth',opts.defaultlinewidth);
else
set(allMarker,'LineWidth',opts.linewidth);
end
case 'scaled'
if (opts.linewidth == -1)
scale = sizescale;
else
scale = opts.linewidth;
end
newlines = LocalScale(oldlines, scale, opts.linemin, opts.linemax);
set(allMarker,{'LineWidth'},newlines);
end
end
% adjust figure bounds to surround axes
if strcmp(opts.bounds,'tight')
if (~strncmp(opts.format,'eps',3) & LocalHas3DPlot(allAxes)) | ...
(strncmp(opts.format,'eps',3) & opts.separatetext)
if (explicitbounds == 1)
warning(['Cannot compute ''tight'' bounds. Using ''loose''' ...
' bounds.']);
end
opts.bounds = 'loose';
end
end
warning('off');
if ~isempty(allAxes)
if strncmp(opts.format,'eps',3)
if strcmp(opts.bounds,'loose')
args = {args{:}, '-loose'};
end
old = LocalPushOldData(old,H,'Position', oldFigPos);
elseif strcmp(opts.bounds,'tight')
oldaunits = LocalGetAsCell(allAxes,'Units');
oldapos = LocalGetAsCell(allAxes,'Position');
oldtunits = LocalGetAsCell(allText,'units');
oldtpos = LocalGetAsCell(allText,'Position');
set(allAxes,'units','points');
apos = LocalGetAsCell(allAxes,'Position');
oldunits = get(H,'Units');
set(H,'units','points');
origfr = get(H,'position');
fr = [];
for k=1:length(allAxes)
if ~strcmpi(get(allAxes(k),'Tag'),'legend')
axesR = apos{k};
r = LocalAxesTightBoundingBox(axesR, allAxes(k));
r(1:2) = r(1:2) + axesR(1:2);
fr = LocalUnionRect(fr,r);
end
end
if isempty(fr)
fr = [0 0 origfr(3:4)];
end
for k=1:length(allAxes)
ax = allAxes(k);
r = apos{k};
r(1:2) = r(1:2) - fr(1:2);
set(ax,'Position',r);
end
old = LocalPushOldData(old, allAxes, {'Position'}, oldapos);
old = LocalPushOldData(old, allText, {'Position'}, oldtpos);
old = LocalPushOldData(old, allText, {'Units'}, oldtunits);
old = LocalPushOldData(old, allAxes, {'Units'}, oldaunits);
old = LocalPushOldData(old, H, 'Position', oldFigPos);
old = LocalPushOldData(old, H, 'Units', oldFigureUnits);
r = [origfr(1) origfr(2)+origfr(4)-fr(4) fr(3:4)];
set(H,'Position',r);
else
args = {args{:}, '-loose'};
old = LocalPushOldData(old,H,'Position', oldFigPos);
end
end
% Process text in a separate file if needed
if opts.separatetext & ~opts.applystyle
% First hide all text and export
oldtvis = LocalGetAsCell(allText,'visible');
set(allText,'visible','off');
oldax = LocalGetAsCell(allAxes,'XTickLabel',1);
olday = LocalGetAsCell(allAxes,'YTickLabel',1);
oldaz = LocalGetAsCell(allAxes,'ZTickLabel',1);
null = cell(length(oldax),1);
[null{:}] = deal([]);
set(allAxes,{'XTickLabel'},null);
set(allAxes,{'YTickLabel'},null);
set(allAxes,{'ZTickLabel'},null);
print(H, filename, args{:});
set(allText,{'Visible'},oldtvis);
set(allAxes,{'XTickLabel'},oldax);
set(allAxes,{'YTickLabel'},olday);
set(allAxes,{'ZTickLabel'},oldaz);
% Now hide all non-text and export as eps in painters
[path, name, ext] = fileparts(filename);
tfile = fullfile(path,[name '_t.eps']);
tfile2 = fullfile(path,[name '_t2.eps']);
foundRenderer = 0;
for k=1:length(args)
if strncmp('-d',args{k},2)
args{k} = '-deps';
elseif strncmp('-zbuffer',args{k},8) | ...
strncmp('-opengl', args{k},6)
args{k} = '-painters';
foundRenderer = 1;
end
end
if ~foundRenderer
args = {args{:}, '-painters'};
end
allNonText = [allLines; allLights; allPatch; ...
allImages; allSurf; allRect];
oldvis = LocalGetAsCell(allNonText,'visible');
oldc = LocalGetAsCell(allAxes,'color');
oldaxg = LocalGetAsCell(allAxes,'XGrid');
oldayg = LocalGetAsCell(allAxes,'YGrid');
oldazg = LocalGetAsCell(allAxes,'ZGrid');
[null{:}] = deal('off');
set(allAxes,{'XGrid'},null);
set(allAxes,{'YGrid'},null);
set(allAxes,{'ZGrid'},null);
set(allNonText,'Visible','off');
set(allAxes,'Color','none');
print(H, tfile2, args{:});
set(allNonText,{'Visible'},oldvis);
set(allAxes,{'Color'},oldc);
set(allAxes,{'XGrid'},oldaxg);
set(allAxes,{'YGrid'},oldayg);
set(allAxes,{'ZGrid'},oldazg);
%hack up the postscript file
fid1 = fopen(tfile,'w');
fid2 = fopen(tfile2,'r');
line = fgetl(fid2);
while ischar(line)
if strncmp(line,'%%Title',7)
fprintf(fid1,'%s\n',['%%Title: ', tfile]);
elseif (length(line) < 3)
fprintf(fid1,'%s\n',line);
elseif ~strcmp(line(end-2:end),' PR') & ...
~strcmp(line(end-1:end),' L')
fprintf(fid1,'%s\n',line);
end
line = fgetl(fid2);
end
fclose(fid1);
fclose(fid2);
delete(tfile2);
elseif ~opts.applystyle
drawnow;
print(H, filename, args{:});
end
warning(oldwarn);
catch
warning(oldwarn);
hadError = 1;
end
% Restore figure settings
if opts.applystyle
varargout{1} = old;
else
for n=1:length(old.objs)
if ~iscell(old.values{n}) & iscell(old.prop{n})
old.values{n} = {old.values{n}};
end
set(old.objs{n}, old.prop{n}, old.values{n});
end
end
if hadError
error(deblank(lasterr));
end
%
% Local Functions
%
function outData = LocalPushOldData(inData, objs, prop, values)
outData.objs = {objs, inData.objs{:}};
outData.prop = {prop, inData.prop{:}};
outData.values = {values, inData.values{:}};
function cellArray = LocalGetAsCell(fig,prop,allowemptycell);
cellArray = get(fig,prop);
if nargin < 3
allowemptycell = 0;
end
if ~iscell(cellArray) & (allowemptycell | ~isempty(cellArray))
cellArray = {cellArray};
end
function newArray = LocalScale(inArray, scale, minv, maxv)
n = length(inArray);
newArray = cell(n,1);
for k=1:n
newArray{k} = min(maxv,max(minv,scale*inArray{k}(1)));
end
function gray = LocalMapToGray1(color)
gray = color;
if ischar(color)
switch color(1)
case 'y'
color = [1 1 0];
case 'm'
color = [1 0 1];
case 'c'
color = [0 1 1];
case 'r'
color = [1 0 0];
case 'g'
color = [0 1 0];
case 'b'
color = [0 0 1];
case 'w'
color = [1 1 1];
case 'k'
color = [0 0 0];
end
end
if ~ischar(color)
gray = 0.30*color(1) + 0.59*color(2) + 0.11*color(3);
end
function newArray = LocalMapToGray(inArray);
n = length(inArray);
newArray = cell(n,1);
for k=1:n
color = inArray{k};
if ~isempty(color)
color = LocalMapToGray1(color);
end
if isempty(color) | ischar(color)
newArray{k} = color;
else
newArray{k} = [color color color];
end
end
function newArray = LocalMapColorToStyle(inArray);
inArray = LocalGetAsCell(inArray,'Color');
n = length(inArray);
newArray = cell(n,1);
styles = {'-','--',':','-.'};
uniques = [];
nstyles = length(styles);
for k=1:n
gray = LocalMapToGray1(inArray{k});
if isempty(gray) | ischar(gray) | gray < .05
newArray{k} = '-';
else
if ~isempty(uniques) & any(gray == uniques)
ind = find(gray==uniques);
else
uniques = [uniques gray];
ind = length(uniques);
end
newArray{k} = styles{mod(ind-1,nstyles)+1};
end
end
function newArray = LocalMapCData(inArray);
n = length(inArray);
newArray = cell(n,1);
for k=1:n
color = inArray{k};
if (ndims(color) == 3) & isa(color,'double')
gray = 0.30*color(:,:,1) + 0.59*color(:,:,2) + 0.11*color(:,:,3);
color(:,:,1) = gray;
color(:,:,2) = gray;
color(:,:,3) = gray;
end
newArray{k} = color;
end
function outData = LocalUpdateColors(inArray, prop, inData)
value = LocalGetAsCell(inArray,prop);
outData.objs = {inData.objs{:}, inArray};
outData.prop = {inData.prop{:}, {prop}};
outData.values = {inData.values{:}, value};
if (~isempty(value))
if strcmp(prop,'CData')
value = LocalMapCData(value);
else
value = LocalMapToGray(value);
end
set(inArray,{prop},value);
end
function bool = LocalIsPositiveScalar(value)
bool = isnumeric(value) & ...
prod(size(value)) == 1 & ...
value > 0;
function value = LocalToNum(value,auto)
if ischar(value)
if strcmp(value,'auto')
value = auto;
else
value = str2num(value);
end
end
%convert a struct to {field1,val1,field2,val2,...}
function c = LocalToCell(s)
f = fieldnames(s);
v = struct2cell(s);
opts = cell(2,length(f));
opts(1,:) = f;
opts(2,:) = v;
c = {opts{:}};
function c = LocalIsHG(obj,hgtype)
c = 0;
if (length(obj) == 1) & ishandle(obj)
c = strcmp(get(obj,'type'),hgtype);
end
function c = LocalHas3DPlot(a)
zticks = LocalGetAsCell(a,'ZTickLabel');
c = 0;
for k=1:length(zticks)
if ~isempty(zticks{k})
c = 1;
return;
end
end
function r = LocalUnionRect(r1,r2)
if isempty(r1)
r = r2;
elseif isempty(r2)
r = r1;
elseif max(r2(3:4)) > 0
left = min(r1(1),r2(1));
bot = min(r1(2),r2(2));
right = max(r1(1)+r1(3),r2(1)+r2(3));
top = max(r1(2)+r1(4),r2(2)+r2(4));
r = [left bot right-left top-bot];
else
r = r1;
end
function c = LocalLabelsMatchTicks(labs,ticks)
c = 0;
try
t1 = num2str(ticks(1));
n = length(ticks);
tend = num2str(ticks(n));
c = strncmp(labs(1),t1,length(labs(1))) & ...
strncmp(labs(n),tend,length(labs(n)));
end
function r = LocalAxesTightBoundingBox(axesR, a)
r = [];
atext = findall(a,'type','text','visible','on');
if ~isempty(atext)
set(atext,'units','points');
res=LocalGetAsCell(atext,'extent');
for n=1:length(atext)
r = LocalUnionRect(r,res{n});
end
end
if strcmp(get(a,'visible'),'on')
r = LocalUnionRect(r,[0 0 axesR(3:4)]);
oldunits = get(a,'fontunits');
set(a,'fontunits','points');
label = text(0,0,'','parent',a,...
'units','points',...
'fontsize',get(a,'fontsize'),...
'fontname',get(a,'fontname'),...
'fontweight',get(a,'fontweight'),...
'fontangle',get(a,'fontangle'),...
'visible','off');
fs = get(a,'fontsize');
% handle y axis tick labels
ry = [0 -fs/2 0 axesR(4)+fs];
ylabs = get(a,'yticklabels');
yticks = get(a,'ytick');
maxw = 0;
if ~isempty(ylabs)
for n=1:size(ylabs,1)
set(label,'string',ylabs(n,:));
ext = get(label,'extent');
maxw = max(maxw,ext(3));
end
if ~LocalLabelsMatchTicks(ylabs,yticks) & ...
strcmp(get(a,'xaxislocation'),'bottom')
ry(4) = ry(4) + 1.5*ext(4);
end
if strcmp(get(a,'yaxislocation'),'left')
ry(1) = -(maxw+5);
else
ry(1) = axesR(3);
end
ry(3) = maxw+5;
r = LocalUnionRect(r,ry);
end
% handle x axis tick labels
rx = [0 0 0 fs+5];
xlabs = get(a,'xticklabels');
xticks = get(a,'xtick');
if ~isempty(xlabs)
if strcmp(get(a,'xaxislocation'),'bottom')
rx(2) = -(fs+5);
if ~LocalLabelsMatchTicks(xlabs,xticks);
rx(4) = rx(4) + 2*fs;
rx(2) = rx(2) - 2*fs;
end
else
rx(2) = axesR(4);
% exponent is still below axes
if ~LocalLabelsMatchTicks(xlabs,xticks);
rx(4) = rx(4) + axesR(4) + 2*fs;
rx(2) = -2*fs;
end
end
set(label,'string',xlabs(1,:));
ext1 = get(label,'extent');
rx(1) = -ext1(3)/2;
set(label,'string',xlabs(size(xlabs,1),:));
ext2 = get(label,'extent');
rx(3) = axesR(3) + (ext2(3) + ext1(3))/2;
r = LocalUnionRect(r,rx);
end
set(a,'fontunits',oldunits);
delete(label);
end
function c = LocalManualAxesMode(old, allAxes, base)
xs = ['X' base];
ys = ['Y' base];
zs = ['Z' base];
oldXMode = LocalGetAsCell(allAxes,xs);
oldYMode = LocalGetAsCell(allAxes,ys);
oldZMode = LocalGetAsCell(allAxes,zs);
old = LocalPushOldData(old, allAxes, {xs}, oldXMode);
old = LocalPushOldData(old, allAxes, {ys}, oldYMode);
old = LocalPushOldData(old, allAxes, {zs}, oldZMode);
set(allAxes,xs,'manual');
set(allAxes,ys,'manual');
set(allAxes,zs,'manual');
c = old;
function val = LocalCheckAuto(val, auto)
if ischar(val) & strcmp(val,'auto')
val = auto;
end
|
github
|
siprob/arhmm_mcmc-master
|
montageKPM.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/montageKPM.m
| 2,917 |
utf_8
|
3863707e80820a96eac8635dfccbbf11
|
function h = montageKPM(arg)
% montageKPM is like the built-in montage, but assumes input is MxNxK or filenames
%
% Converts patches (y,x,i) into patches(y,x,1,i)
% Also, adds a black border aroudn them
if iscell(arg)
h= montageFilenames(arg);
else
nr = size(arg,1); nc = size(arg,2); Npatches = size(arg,3);
patchesColor = reshape(arg, [nr nc 1 Npatches]);
patchesColor = patchesColor ./ max(patchesColor(:));
if 1
%put a black border around them for display purposes
border = 5;
bgColor = ones(1,1,class(patchesColor));
patchesColorBig = bgColor*ones(nr+2*border, nc+2*border, 1, Npatches, class(patchesColor));
%patchesColorBig = zeros(nr+2*border, nc+2*border, 1, Npatches, class(patchesColor));
patchesColorBig(border+1:end-border, border+1:end-border, :, :) = patchesColor;
else
patchesColorBig = patchesColor;
end
montage(patchesColorBig)
end
%%%%%%%%%%%%%
function h = montageFilenames(filenames)
%[nRows, nCols, nBands, nFrames] = size(a);
% Estimate nMontageColumns and nMontageRows given the desired ratio of
% Columns to Rows to be one (square montage).
aspectRatio = 1;
nMontageCols = sqrt(aspectRatio * nRows * nFrames / nCols);
% Make sure montage rows and columns are integers. The order in the adjustment
% matters because the montage image is created horizontally across columns.
nMontageCols = ceil(nMontageCols);
nMontageRows = ceil(nFrames / nMontageCols);
% Create the montage image.
b = a(1,1); % to inherit type
b(1,1) = 0; % from a
b = repmat(b, [nMontageRows*nRows, nMontageCols*nCols, nBands, 1]);
rows = 1 : nRows;
cols = 1 : nCols;
for i = 0:nMontageRows-1
for j = 0:nMontageCols-1,
k = j + i * nMontageCols + 1;
if k <= nFrames
b(rows + i * nRows, cols + j * nCols, :) = a(:,:,:,k);
else
break;
end
end
end
if isempty(cm)
hh = imshow(b);
else
hh = imshow(b,cm);
end
if nargout > 0
h = hh;
end
%--------------------------------------------------------------
%Parse Inputs Function
function [I,map] = parse_inputs(varargin)
% initialize variables
map = [];
iptchecknargin(1,2,nargin,mfilename);
iptcheckinput(varargin{1},{'uint8' 'double' 'uint16' 'logical' 'single' ...
'int16'},{},mfilename, 'I, BW, or RGB',1);
I = varargin{1};
if nargin==2
if isa(I,'int16')
eid = sprintf('Images:%s:invalidIndexedImage',mfilename);
msg1 = 'An indexed image can be uint8, uint16, double, single, or ';
msg2 = 'logical.';
error(eid,'%s %s',msg1, msg2);
end
map = varargin{2};
iptcheckinput(map,{'double'},{},mfilename,'MAP',1);
if ((size(map,1) == 1) && (prod(map) == numel(I)))
% MONTAGE(D,[M N P]) OBSOLETE
eid = sprintf('Images:%s:obsoleteSyntax',mfilename);
msg1 = 'MONTAGE(D,[M N P]) is an obsolete syntax.';
msg2 = 'Use multidimensional arrays to represent multiframe images.';
error(eid,'%s\n%s',msg1,msg2);
end
end
|
github
|
siprob/arhmm_mcmc-master
|
optimalMatching.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/optimalMatching.m
| 2,593 |
utf_8
|
983df7bc538a844b42427ae58d69c75b
|
% MATCH - Solves the weighted bipartite matching (or assignment)
% problem.
%
% Usage: a = match(C);
%
% Arguments:
% C - an m x n cost matrix; the sets are taken to be
% 1:m and 1:n; C(i, j) gives the cost of matching
% items i (of the first set) and j (of the second set)
%
% Returns:
%
% a - an m x 1 assignment vector, which gives the
% minimum cost assignment. a(i) is the index of
% the item of 1:n that was matched to item i of
% 1:m. If item i (of 1:m) was not matched to any
% item of 1:n, then a(i) is zero.
% Copyright (C) 2002 Mark A. Paskin
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
% USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [a] = optimalMatching(C)
% Trivial cases:
[p, q] = size(C);
if (p == 0)
a = [];
return;
elseif (q == 0)
a = zeros(p, 1);
return;
end
if 0
% First, reduce the problem by making easy optimal matches. If two
% elements agree that they are the best match, then match them up.
[x, a] = min(C, [], 2);
[y, b] = min(C, [], 1);
u = find(1:p ~= b(a(:)));
a(u) = 0;
v = find(1:q ~= a(b(:))');
C = C(u, v);
if (isempty(C)) return; end
end
% Get the (new) size of the two sets, u and v.
[m, n] = size(C);
%mx = realmax;
mx = 2*max(C(:));
mn = -2*min(C(:));
% Pad the affinity matrix to be square
if (m < n)
C = [C; mx * ones(n - m, n)];
elseif (n < m)
C = [C, mx * ones(m, m - n)];
end
% Run the Hungarian method. First replace infinite values by the
% largest (or smallest) finite values.
C(find(isinf(C) & (C > 0))) = mx;
C(find(isinf(C) & (C < 0))) = mn;
%fprintf('running hungarian\n');
[b, cost] = hungarian(C');
% Extract only the real assignments
ap = b(1:m)';
ap(find(ap > n)) = 0;
a = ap;
%% Incorporate this sub-assignment into the complete assignment
% k = find(ap);
% a(u(k)) = v(ap(k));
|
github
|
siprob/arhmm_mcmc-master
|
plotcov2.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/plotcov2.m
| 3,013 |
utf_8
|
4305f11ba0280ef8ebcad4c8a4c4013c
|
% PLOTCOV2 - Plots a covariance ellipse with major and minor axes
% for a bivariate Gaussian distribution.
%
% Usage:
% h = plotcov2(mu, Sigma[, OPTIONS]);
%
% Inputs:
% mu - a 2 x 1 vector giving the mean of the distribution.
% Sigma - a 2 x 2 symmetric positive semi-definite matrix giving
% the covariance of the distribution (or the zero matrix).
%
% Options:
% 'conf' - a scalar between 0 and 1 giving the confidence
% interval (i.e., the fraction of probability mass to
% be enclosed by the ellipse); default is 0.9.
% 'num-pts' - the number of points to be used to plot the
% ellipse; default is 100.
%
% This function also accepts options for PLOT.
%
% Outputs:
% h - a vector of figure handles to the ellipse boundary and
% its major and minor axes
%
% See also: PLOTCOV3
% Copyright (C) 2002 Mark A. Paskin
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
% USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = plotcov2(mu, Sigma, varargin)
if size(Sigma) ~= [2 2], error('Sigma must be a 2 by 2 matrix'); end
if length(mu) ~= 2, error('mu must be a 2 by 1 vector'); end
[p, ...
n, ...
plot_opts] = process_options(varargin, 'conf', 0.9, ...
'num-pts', 100);
h = [];
holding = ishold;
if (Sigma == zeros(2, 2))
z = mu;
else
% Compute the Mahalanobis radius of the ellipsoid that encloses
% the desired probability mass.
k = conf2mahal(p, 2);
% The major and minor axes of the covariance ellipse are given by
% the eigenvectors of the covariance matrix. Their lengths (for
% the ellipse with unit Mahalanobis radius) are given by the
% square roots of the corresponding eigenvalues.
if (issparse(Sigma))
[V, D] = eigs(Sigma);
else
[V, D] = eig(Sigma);
end
% Compute the points on the surface of the ellipse.
t = linspace(0, 2*pi, n);
u = [cos(t); sin(t)];
w = (k * V * sqrt(D)) * u;
z = repmat(mu, [1 n]) + w;
% Plot the major and minor axes.
L = k * sqrt(diag(D));
h = plot([mu(1); mu(1) + L(1) * V(1, 1)], ...
[mu(2); mu(2) + L(1) * V(2, 1)], plot_opts{:});
hold on;
h = [h; plot([mu(1); mu(1) + L(2) * V(1, 2)], ...
[mu(2); mu(2) + L(2) * V(2, 2)], plot_opts{:})];
end
h = [h; plot(z(1, :), z(2, :), plot_opts{:})];
if (~holding) hold off; end
|
github
|
siprob/arhmm_mcmc-master
|
ind2subv.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/ind2subv.m
| 1,206 |
utf_8
|
5c2e8689803ece8fca091e60c913809d
|
function sub = ind2subv(siz, ndx)
% IND2SUBV Like the built-in ind2sub, but returns the answer as a row vector.
% sub = ind2subv(siz, ndx)
%
% siz and ndx can be row or column vectors.
% sub will be of size length(ndx) * length(siz).
%
% Example
% ind2subv([2 2 2], 1:8) returns
% [1 1 1
% 2 1 1
% ...
% 2 2 2]
% That is, the leftmost digit toggle fastest.
%
% See also SUBV2IND
n = length(siz);
if n==0
sub = ndx;
return;
end
if all(siz==2)
sub = dec2bitv(ndx-1, n);
sub = sub(:,n:-1:1)+1;
return;
end
cp = [1 cumprod(siz(:)')];
ndx = ndx(:) - 1;
sub = zeros(length(ndx), n);
for i = n:-1:1 % i'th digit
sub(:,i) = floor(ndx/cp(i))+1;
ndx = rem(ndx,cp(i));
end
%%%%%%%%%%
function bits = dec2bitv(d,n)
% DEC2BITV Convert a decimal integer to a bit vector.
% bits = dec2bitv(d,n) is just like the built-in dec2bin, except the answer is a vector, not a string.
% n is an optional minimum length on the bit vector.
% If d is a vector, each row of the output array will be a bit vector.
if (nargin<2)
n=1; % Need at least one digit even for 0.
end
d = d(:);
[f,e]=log2(max(d)); % How many digits do we need to represent the numbers?
bits=rem(floor(d*pow2(1-max(n,e):0)),2);
|
github
|
siprob/arhmm_mcmc-master
|
process_options.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/process_options.m
| 4,394 |
utf_8
|
483b50d27e3bdb68fd2903a0cab9df44
|
% PROCESS_OPTIONS - Processes options passed to a Matlab function.
% This function provides a simple means of
% parsing attribute-value options. Each option is
% named by a unique string and is given a default
% value.
%
% Usage: [var1, var2, ..., varn[, unused]] = ...
% process_options(args, ...
% str1, def1, str2, def2, ..., strn, defn)
%
% Arguments:
% args - a cell array of input arguments, such
% as that provided by VARARGIN. Its contents
% should alternate between strings and
% values.
% str1, ..., strn - Strings that are associated with a
% particular variable
% def1, ..., defn - Default values returned if no option
% is supplied
%
% Returns:
% var1, ..., varn - values to be assigned to variables
% unused - an optional cell array of those
% string-value pairs that were unused;
% if this is not supplied, then a
% warning will be issued for each
% option in args that lacked a match.
%
% Examples:
%
% Suppose we wish to define a Matlab function 'func' that has
% required parameters x and y, and optional arguments 'u' and 'v'.
% With the definition
%
% function y = func(x, y, varargin)
%
% [u, v] = process_options(varargin, 'u', 0, 'v', 1);
%
% calling func(0, 1, 'v', 2) will assign 0 to x, 1 to y, 0 to u, and 2
% to v. The parameter names are insensitive to case; calling
% func(0, 1, 'V', 2) has the same effect. The function call
%
% func(0, 1, 'u', 5, 'z', 2);
%
% will result in u having the value 5 and v having value 1, but
% will issue a warning that the 'z' option has not been used. On
% the other hand, if func is defined as
%
% function y = func(x, y, varargin)
%
% [u, v, unused_args] = process_options(varargin, 'u', 0, 'v', 1);
%
% then the call func(0, 1, 'u', 5, 'z', 2) will yield no warning,
% and unused_args will have the value {'z', 2}. This behaviour is
% useful for functions with options that invoke other functions
% with options; all options can be passed to the outer function and
% its unprocessed arguments can be passed to the inner function.
% Copyright (C) 2002 Mark A. Paskin
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
% USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [varargout] = process_options(args, varargin)
% Check the number of input arguments
n = length(varargin);
if (mod(n, 2))
error('Each option must be a string/value pair.');
end
% Check the number of supplied output arguments
if (nargout < (n / 2))
error('Insufficient number of output arguments given');
elseif (nargout == (n / 2))
warn = 1;
nout = n / 2;
else
warn = 0;
nout = n / 2 + 1;
end
% Set outputs to be defaults
varargout = cell(1, nout);
for i=2:2:n
varargout{i/2} = varargin{i};
end
% Now process all arguments
nunused = 0;
for i=1:2:length(args)
found = 0;
for j=1:2:n
if strcmpi(args{i}, varargin{j})
varargout{(j + 1)/2} = args{i + 1};
found = 1;
break;
end
end
if (~found)
if (warn)
warning(sprintf('Option ''%s'' not used.', args{i}));
args{i}
else
nunused = nunused + 1;
unused{2 * nunused - 1} = args{i};
unused{2 * nunused} = args{i + 1};
end
end
end
% Assign the unused arguments
if (~warn)
if (nunused)
varargout{nout} = unused;
else
varargout{nout} = cell(0);
end
end
|
github
|
siprob/arhmm_mcmc-master
|
nonmaxsup.m
|
.m
|
arhmm_mcmc-master/HMMall/KPMtools/nonmaxsup.m
| 1,708 |
utf_8
|
ad451680a9d414f907da2969e0809c22
|
% NONMAXSUP - Non-maximal Suppression
%
% Usage: cim = nonmaxsup(im, radius)
%
% Arguments:
% im - image to be processed.
% radius - radius of region considered in non-maximal
% suppression (optional). Typical values to use might
% be 1-3. Default is 1.
%
% Returns:
% cim - image with pixels that are not maximal within a
% square neighborhood zeroed out.
% Copyright (C) 2002 Mark A. Paskin
%
% 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 cim = nonmaxsup(m, radius)
if (nargin == 1) radius = 1; end
% Extract local maxima by performing a grey scale morphological
% dilation and then finding points in the corner strength image that
% match the dilated image and are also greater than the threshold.
sze = 2 * radius + 1; % Size of mask.
mx = ordfilt2(m, sze^2, ones(sze)); % Grey-scale dilate.
cim = sparse(m .* (m == mx));
|
github
|
jordiolivares/visio.artificial-master
|
haarFeatureDemo.m
|
.m
|
visio.artificial-master/images_P5/haarFeatureDemo.m
| 6,707 |
utf_8
|
8fcda30aa7babd3f4ef6e434391b9163
|
function [ outClass, X, Y, selFeatures, error, predErr ] = haarFeatureDemo(numFeatures,X,Y,Yprev)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
outSize=[30,30];
close all;
% Get dataset
if ~exist('numFeatures','var'),
numFeatures=3;
end
% Create a new database if it is not provided
if ~exist('X','var') || ~exist('Y','var'),
[X,Y] = getDataBase(outSize,15);
else
% Remove previously rejected images
X2=X;
Y2=Y;
X=X(Yprev==1,:);
Y=Y(Yprev==1);
end
% Get the average face as model
model=uint8(round(reshape(mean(X(Y==1,:),1),outSize)));
% Ask as many features as we want
selFeatures=[];
predictions=[];
error=[];
predErr=[];
cascErr=[];
for f=1:numFeatures,
% Ask feature values
[rectPos,rectNeg,rectPosS,rectNegS]=selectFeature(model,outSize);
% Get feature values for all images in the dataset
fval=getRectVal(rectPosS,rectNegS,X,outSize);
% Get threshold value to build a weak classifier
[thr,polarity,pred,err]=getThreshold(fval,Y);
% Store the feature in the list of features
selFeatures=[selFeatures;rectPos rectNeg];
predictions=[predictions pred];
% Get the accumulate predictions
accPred=sum(predictions,2);
% Get the final prediction
outClass=sign(accPred);
% Store historical
error=[error err];
predErr=[predErr sum(outClass~=Y)/length(Y)];
%Show the features
subplot(2,3,[1 4]);
showFeatures(model,selFeatures);
% Show the values using the sum of rectangle pixels
subplot(2,3,2);
showFeatureVals(fval,Y,thr,polarity);title(sprintf('Feature Values. Polarity=%d',polarity));
legend('Face','No-face');
% Show the accumulated values
subplot(2,3,3);
stem(accPred);title('Accumulated Values');
% Show the values using the sum of rectangle pixels
subplot(2,3,5);
stem(outClass);title(['Final prediction. Error=' sprintf('%3.1f%%',round(err*100))]);
% Show error comparison between feature and ensemble
subplot(2,3,6);
if exist('Yprev','var'),
Ycascade=Y2;
Ycascade(Yprev==1)=outClass;
cascErr=[cascErr sum(Ycascade~=Y2)/length(Y2)];
errMat=[error;predErr;cascErr];
bar(errMat');title('Error values feature vs ensemble vs cascade');
legend('F. Error', 'Ens. Error' , 'Cascade Error');
else
errMat=[error;predErr;cascErr];
bar(errMat');title('Error values feature vs ensemble');
legend('F. Error', 'Ens. Error');
end
end
% Recover initial data
if exist('X2','var'),
X=X2;
Y=Y2;
Yprev(Yprev==1)=outClass;
outClass=Yprev;
end
end
function [rectPos,rectNeg,rectPosS,rectNegS]=selectFeature(model,outSize)
h=figure();
imshow(model);title('Select feature points');
[x,y]=ginput(2);
close(h);
mSize=size(model);
% Get the feature
rectPos=round([x(1) y(1) x(2)-x(1)+1 y(2)-y(1)+1]);
rectNeg=round([x(2)+1 y(1) rectPos(3) rectPos(4)]);
% Correct the feature
if rectNeg(2)+rectNeg(4)-1>mSize(1),
overLength=(rectNeg(2)+rectNeg(4)-1)-mSize(1);
rectPos(2)=rectPos(2)+overLength-1;
rectPos(4)=rectPos(4)-overLength;
rectNeg(4)=rectNeg(4)-overLength;
end
if rectNeg(1)+rectNeg(3)-1>mSize(2),
overLength=(rectNeg(1)+rectNeg(3)-1)-mSize(2);
rectPos(1)=rectPos(1)+overLength-1;
rectPos(3)=rectPos(3)-overLength;
rectNeg(3)=rectNeg(3)-overLength;
end
% Reescale the feature
s=outSize./mSize;
x=x*s(2);
y=y*s(1);
rectPosS=round([x(1) y(1) x(2)-x(1)+1 y(2)-y(1)+1]);
rectNegS=round([x(2)+1 y(1) rectPosS(3) rectPosS(4)]);
% Correct the feature
if rectNegS(2)+rectNegS(4)-1>outSize(1),
overLength=(rectNegS(2)+rectNegS(4)-1)-outSize(1);
rectPosS(2)=rectPosS(2)+overLength-1;
rectPosS(4)=rectPosS(4)-overLength;
rectNegS(4)=rectNegS(4)-overLength;
end
if rectNegS(1)+rectNegS(3)-1>outSize(2),
overLength=(rectNegS(1)+rectNegS(3)-1)-outSize(2);
rectPosS(1)=rectPosS(1)+overLength-1;
rectPosS(3)=rectPosS(3)-overLength;
rectNegS(3)=rectNegS(3)-overLength;
end
end
function showFeatures(model,selFeatures)
%Show the model
imshow(model);title('Selected features');
hold on;
for i=1:size(selFeatures,1),
rectPos=selFeatures(i,1:4);
rectNeg=selFeatures(i,5:8);
% Show feature
rectangle('position',rectPos,'facecolor','w');
rectangle('position',rectNeg,'facecolor','k');
end
end
function f=getRectVal(rectPos,rectNeg,X,outSize)
f=zeros(size(X,1),1);
for i=1:size(X,1),
% Get the image
image=reshape(X(i,:),outSize);
% Select the rectangle regions
r1=image(rectPos(2):rectPos(2)+rectPos(4)-1,rectPos(1):rectPos(1)+rectPos(3)-1);
r2=image(rectNeg(2):rectNeg(2)+rectNeg(4)-1,rectNeg(1):rectNeg(1)+rectNeg(3)-1);
% Evaluate the difference between region values
f(i)=sum(reshape(r1,1,[]))-sum(reshape(r2,1,[]));
end
end
function showFeatureVals(f,Y,thr,polarity)
plot(1:length(find(Y==1)),f(find(Y==1)),'g*', 1:length(find(Y==-1)), f(find(Y==-1)), 'r+'); hold on;
plot([0,length(Y)],[thr,thr],'k--','linewidth',2);
hold off;
end
function [thr,polarity,prediction,err]=getThreshold(s,Y)
% Get feature values for positive and negative samples
posVals=s(Y==1);
negVals=s(Y==-1);
% Check threshold value for polarity 1
minVal=min(posVals);
maxVal=max(negVals(negVals<minVal));
if isempty(maxVal),
maxVal=minVal;
end
thr1=(minVal+maxVal)/2;
prediction1=(s>=thr1)*2-1;
err1=sum(Y~=prediction1)/length(Y);
% Check threshold value for polarity -1
maxVal=max(posVals);
minVal=min(negVals(negVals>maxVal));
if isempty(minVal),
minVal=maxVal;
end
thr2=(minVal+maxVal)/2;
prediction2=(s<thr2)*2-1;
err2=sum(Y~=prediction2)/length(Y);
if err1<err2,
thr=thr1;
polarity=1;
prediction=prediction1;
err=err1;
else
thr=thr2;
polarity=-1;
prediction=prediction2;
err=err2;
end
end
|
github
|
jordiolivares/visio.artificial-master
|
ej53.m
|
.m
|
visio.artificial-master/images_P5/ej53.m
| 1,450 |
utf_8
|
2646d810245093f1e2fa9d2902278a60
|
function [ output_args ] = ej53( input_args )
%EJ53 Summary of this function goes here
% Detailed explanation goes here
addpath('ViolaJones','ViolaJones/SubFunctions');
% a)
[X, Y] = getDataBase([20 20]);
X = uint8(round(reshape(mean(X), [20 20])));
imshow(X);
rectangle('Position', [3 7 14 4], 'facecolor','k');
rectangle('Position', [3 9 14 2], 'facecolor','w');
% b)
figure;
subplot(2,3,1);
im = imread('images/landscape.jpg');
imshow(im);
subplot(2,3,4);
showIntegralImage(im);
subplot(2,3,2);
im = imread('images/natural.jpg');
imshow(im);
subplot(2,3,5);
showIntegralImage(im);
subplot(2,3,3);
im = imread('images/room.jpg');
imshow(im);
subplot(2,3,6);
showIntegralImage(im);
pause;
% c)
close all;
image = imread('images/testFaces1.jpg');
showFaces(image);
pause;
close all;
image = imread('images/testFaces2.jpg');
showFaces(image);
end
function showIntegralImage(image)
defaultoptions.Resize = false;
intImageStruct = GetIntegralImages(image,defaultoptions);
imagesc(intImageStruct.ii);colormap(jet);
end
function showFaces(image)
options.Rescale = false;
faces = ObjectDetection(image, 'ViolaJones/HaarCascades/haarcascade_frontalface_alt.mat', options);
imshow(image);
for i = 1:size(faces, 1)
rectangle('Position', faces(i,:), 'EdgeColor', 'b');
end
end
|
github
|
jordiolivares/visio.artificial-master
|
ej24.m
|
.m
|
visio.artificial-master/images_P2/ej24.m
| 1,282 |
utf_8
|
58db53473919bd455693025b2964462c
|
function [] = ej24()
%EJ24 Summary of this function goes here
% Detailed explanation goes here
einstein = imread('einstein.jpg');
monroe = imread('monroe.jpg');
h_monroe = hybrid(monroe, einstein, 6, 10);
background = zeros(size(h_monroe), 'uint8');
figure
subplot(3,3,1)
imshow(einstein);
subplot(3,3,2)
imshow(monroe);
subplot(3,3,3)
imshow(h_monroe);
subplot(3,3,4)
imshow(paste(background, imresize(h_monroe, 0.8)));
subplot(3,3,5)
imshow(paste(background, imresize(h_monroe, 0.7)));
subplot(3,3,6)
imshow(paste(background, imresize(h_monroe, 0.6)));
subplot(3,3,7)
imshow(paste(background, imresize(h_monroe, 0.5)));
subplot(3,3,8)
imshow(paste(background, imresize(h_monroe, 0.4)));
subplot(3,3,9)
imshow(paste(background, imresize(h_monroe, 0.3)));
end
function [result] = highpass(image, sigma)
lowpass = imgaussfilt(image, sigma);
result = image - lowpass;
end
function [image] = paste(background, foreground)
image = background;
sizes = size(foreground);
image(1:sizes(1), 1:sizes(2)) = foreground;
end
function [image] = hybrid(image1, image2, sigma1, sigma2)
lowpass = imgaussfilt(image1, sigma1);
image = lowpass + highpass(image2, sigma2);
end
|
github
|
jordiolivares/visio.artificial-master
|
gaussRandom.m
|
.m
|
visio.artificial-master/images_P3/gaussRandom.m
| 6,443 |
utf_8
|
8f6251f91754da2356403f31ea2ed4a7
|
function [ samples ] = gaussRandom( mu, sigma, numSamples )
% GAUSSRANDOM Sample a normal distribution with parameters mu and sigma
% Generate random points using a gaussian distribution
if size(sigma,1)==1,
sigma=eye(length(mu))*sigma;
end
samples = mvnrnd(mu,sigma,numSamples);
end
function [r,T] = mvnrnd(mu,sigma,cases,T)
% MVNRND Random vectors from the multivariate normal distribution.
% R = MVNRND(MU,SIGMA) returns an N-by-D matrix R of random vectors
% chosen from the multivariate normal distribution with mean vector MU,
% and covariance matrix SIGMA. MU is an N-by-D matrix, and MVNRND
% generates each row of R using the corresponding row of MU. SIGMA is a
% D-by-D symmetric positive semi-definite matrix, or a D-by-D-by-N array.
% If SIGMA is an array, MVNRND generates each row of R using the
% corresponding page of SIGMA, i.e., MVNRND computes R(I,:) using MU(I,:)
% and SIGMA(:,:,I). If the covariance matrix is diagonal, containing
% variances along the diagonal and zero covariances off the diagonal,
% SIGMA may also be specified as a 1-by-D matrix or a 1-by-D-by-N array,
% containing just the diagonal. If MU is a 1-by-D vector, MVNRND
% replicates it to match the trailing dimension of SIGMA.
%
% R = MVNRND(MU,SIGMA,N) returns a N-by-D matrix R of random vectors
% chosen from the multivariate normal distribution with 1-by-D mean
% vector MU, and D-by-D covariance matrix SIGMA.
%
% Example:
%
% mu = [1 -1]; Sigma = [.9 .4; .4 .3];
% r = mvnrnd(mu, Sigma, 500);
% plot(r(:,1),r(:,2),'.');
%
% See also MVTRND, MVNPDF, MVNCDF, NORMRND.
% R = MVNRND(MU,SIGMA,N,T) supplies the Cholesky factor T of
% SIGMA, so that SIGMA(:,:,J) == T(:,:,J)'*T(:,:,J) if SIGMA is a 3D array or SIGMA
% == T'*T if SIGMA is a matrix. No error checking is done on T.
%
% [R,T] = MVNRND(...) returns the Cholesky factor T, so it can be
% re-used to make later calls more efficient, although there are greater
% efficiency gains when SIGMA can be specified as a diagonal instead.
% Copyright 1993-2011 The MathWorks, Inc.
if nargin < 2 || isempty(mu) || isempty(sigma)
error(message('stats:mvnrnd:TooFewInputs'));
elseif ndims(mu) > 2
error(message('stats:mvnrnd:BadMu'));
elseif ndims(sigma) > 3
error(message('stats:mvnrnd:BadSigma'));
end
[n,d] = size(mu);
sz = size(sigma);
if sz(1)==1 && sz(2)>1
% Just the diagonal of Sigma has been passed in.
sz(1) = sz(2);
sigmaIsDiag = true;
else
sigmaIsDiag = false;
end
% Special case: if mu is a column vector, then use sigma to try
% to interpret it as a row vector.
if d == 1 && sz(1) == n
mu = mu';
[n,d] = size(mu);
end
% Get size of data.
if nargin < 3 || isempty(cases)
nocases = true; % cases not supplied
else
nocases = false; % cases was supplied
if n == cases
% mu is ok
elseif n == 1 % mu is a single row, make cases copies
n = cases;
mu = repmat(mu,n,1);
else
error(message('stats:mvnrnd:InputSizeMismatchMu'));
end
end
% Single covariance matrix
if ndims(sigma) == 2
% Make sure sigma is the right size
if sz(1) ~= sz(2)
error(message('stats:mvnrnd:BadCovariance2DSize'));
elseif ~isequal(sz, [d d])
error(message('stats:mvnrnd:InputSizeMismatch2DSigma'));
end
if nargin > 3
% sigma has already been factored, so use it.
r = randn(n,size(T,1)) * T + mu;
elseif sigmaIsDiag
% Just the diagonal of sigma has been specified.
if any(sigma<0)
error(message('stats:mvnrnd:BadDiagSigma'));
end
t = sqrt(sigma);
if nargout>1
T = diag(t);
end
r = bsxfun(@times,randn(n,d),t) + mu;
else
% Factor sigma using a function that will perform a Cholesky-like
% factorization as long as the sigma matrix is positive
% semi-definite (can have perfect correlation). Cholesky requires a
% positive definite matrix. sigma == T'*T
[T,err] = cholcov(sigma);
if err ~= 0
error(message('stats:mvnrnd:BadCovariance2DSymPos'));
end
r = randn(n,size(T,1)) * T + mu;
end
% Multiple covariance matrices
elseif ndims(sigma) == 3
% mu is a single row and cases not given, rep mu out to match sigma
if n == 1 && nocases % already know size(sigma,3) > 1
n = sz(3);
mu = repmat(mu,n,1);
end
% Make sure sigma is the right size
if sz(1) ~= sz(2) % Sigma is 3-D
error(message('stats:mvnrnd:BadCovariance3DSize'));
elseif (sz(1) ~= d) || (sz(2) ~= d) % Sigma is 3-D
error(message('stats:mvnrnd:InputSizeMismatch3DSigma'));
elseif sz(3) ~= n
error(message('stats:mvnrnd:InputSizeMismatchSigmaDimension'));
end
if nargin < 4
if nargout > 1
T = zeros(sz,class(sigma));
end
if sigmaIsDiag
sigma = reshape(sigma,sz(2),sz(3))';
if any(any(sigma<0))
error(message('stats:mvnrnd:BadDiagSigma'));
end
R = sqrt(sigma);
r = bsxfun(@times,randn(n,d),R) + mu;
if nargout > 1
for i=1:n
T(:,:,i) = diag(R(i,:));
end
end
else
r = zeros(n,d,superiorfloat(mu,sigma));
for i = 1:n
[R,err] = cholcov(sigma(:,:,i));
if err ~= 0
error(message('stats:mvnrnd:BadCovariance3DSymPos'));
end
Rrows = size(R,1);
r(i,:) = randn(1,Rrows) * R + mu(i,:);
if nargout > 1
T(1:Rrows,:,i) = R;
end
end
end
else
% T specified
r = zeros(n,d,superiorfloat(mu,sigma));
for i = 1:n
r(i,:) = randn(1,d) * T(:,:,i) + mu(i,:);
end
end
end
end
|
github
|
jordiolivares/visio.artificial-master
|
ej35.m
|
.m
|
visio.artificial-master/images_P3/ej35.m
| 1,838 |
ibm852
|
3c8d035d618415bd27c410708444776a
|
function [ output_args ] = ej35( input_args )
%EJ35 Summary of this function goes here
% Detailed explanation goes here
% a)
showMatches('starbucks.jpg', 'starbucks6.jpg');
pause
% b)
% Take elements out if you want to do the experiment for fewer elements
imatges = {'starbucks.jpg', 'starbucks2.png', 'starbucks4.jpg',...
'starbucks5.png', 'starbucks6.jpg', 'starbucksCup.jpg'};
% Or just uncomment this and comment the line above
%imatges = {'starbucks.jpg', 'starbucks2.png', 'starbucks4.jpg'};
sorted = sortBySimilarity(imatges);
close all;
for comb = sorted
showMatches(comb{1}, comb{2});
disp('Prem Enter per a la següent imatge:');
pause
end
% d)
im = imread('starbucks.jpg');
im45 = imrotate(imresize(im, 0.5), 45);
im97 = imrotate(imresize(im, 1.4), 97);
im140 = imrotate(imresize(im, 0.7), 140);
im200 = imrotate(imresize(im, 0.2), 200);
imwrite(im45, 'starbucks45.png');
imwrite(im97, 'starbucks97.png');
imwrite(im140, 'starbucks140.png');
imwrite(im200, 'starbucks200.png');
showMatches('starbucks45.png', 'starbucks6.jpg');
pause
showMatches('starbucks97.png', 'starbucks6.jpg');
pause
showMatches('starbucks140.png', 'starbucks6.jpg');
pause
showMatches('starbucks200.png', 'starbucks6.jpg');
end
function [output] = sortBySimilarity(list)
combinations = combnk(list, 2);
combinations = [combinations; fliplr(combinations)]';
combinations(3,:) = num2cell(zeros(size(combinations, 2),1));
for i = 1:size(combinations, 2)
[~, score] = showMatches(combinations{1, i}, combinations{2, i});
close;
combinations{3, i} = sum(score);
end
combinations = sortrows(combinations', [1 3])';
output = combinations;
end
|
github
|
jordiolivares/visio.artificial-master
|
ej31.m
|
.m
|
visio.artificial-master/images_P3/ej31.m
| 2,461 |
utf_8
|
a73520adedd4bd5204d530bfe79b295f
|
function [] = ej31()
%EJ31 Summary of this function goes here
% Detailed explanation goes here
frames = extractBackground('Barcelona.mp4');
video = VideoReader('Barcelona.mp4');
sampleFrame = read(video, 1757);
background = frames(:,:,:,12);
figure
subplot(1,2,1)
imshow(background);
title('Background');
subplot(1,2,2)
imshow(sampleFrame);
title('Image');
figure
subplot(1,1,1)
imshow(sampleFrame - background);
title('Moving parts')
end
function [backgroundFrames] = extractBackground(filename)
% Extracts the background of a video in each scene using the median
keyFrames = segmentVideo(filename, 250000);
video = VideoReader(filename);
videoFrames = video.NumberOfFrames;
video = VideoReader(filename);
backgroundFrames = zeros(video.Height, video.Width, 3, size(keyFrames, 1), 'uint8');
for i = 1:size(keyFrames, 1)
if i == size(keyFrames, 1)
numFrames = videoFrames - keyFrames(i);
else
numFrames = keyFrames(i+1) - keyFrames(i);
end
tmp = zeros(video.Height, video.Width, 3, numFrames, 'uint8');
for j = 1:numFrames
tmp(:,:,:, j) = readFrame(video);
end
% Median of all frames at that pixel coordinate
backgroundFrames(:,:,:,i) = median(tmp, 4);
end
end
function [keyFrames] = segmentVideo(filename, threshold)
% Segments the video using 'threshold' as a way to detect change of scene
video = VideoReader(filename);
keyFrames = 1;
previous_frame = readFrame(video);
current_frame = readFrame(video);
frame_count = 2;
while hasFrame(video)
if frameDiff(current_frame, previous_frame) > threshold
keyFrames = [keyFrames ; frame_count];
end
previous_frame = current_frame;
current_frame = readFrame(video);
frame_count = frame_count + 1;
end
end
function [difference] = frameDiff(frame1, frame2)
% Calculates the difference between images using the image histogram of
% each RGB channel
[tmp1, ~] = imhist(frame1(:,:,1));
[tmp2, ~] = imhist(frame2(:,:,1));
diffR = sum(abs(tmp1 - tmp2));
[tmp1, ~] = imhist(frame1(:,:,2));
[tmp2, ~] = imhist(frame2(:,:,2));
diffG = sum(abs(tmp1 - tmp2));
[tmp1, ~] = imhist(frame1(:,:,3));
[tmp2, ~] = imhist(frame2(:,:,3));
diffB = sum(abs(tmp1 - tmp2));
difference = diffR + diffG + diffB;
end
|
github
|
jordiolivares/visio.artificial-master
|
ej32.m
|
.m
|
visio.artificial-master/images_P3/ej32.m
| 1,115 |
utf_8
|
d5a23687195d4558e16b74681b460b88
|
function [ ] = ej32( )
%%%%%%%%%%%%% (a) %%%%%%%%%%%%%
cloud1 = gaussRandom([1,2], 0.1, 100);
cloud2 = gaussRandom([2,2], 0.1, 100);
cloud3 = gaussRandom([2,1], 0.1, 100);
figure
subplot(2,3,2)
plot(cloud1(:,1), cloud1(:,2), '.', cloud2(:,1), cloud2(:,2), '.', cloud3(:,1), cloud3(:,2), '.')
title('Original')
%%%%%%%%%%%%% (b) %%%%%%%%%%%%%
allPoints = [cloud1; cloud2; cloud3];
%%% k=2 %%%
[idx , C] = kmeans([cloud1 ; cloud2 ; cloud3], 2);
subplot(2,3,4)
plotClusters(2, idx, C, allPoints)
title('k=2')
%%% k=3 %%%
[idx , C] = kmeans([cloud1 ; cloud2 ; cloud3], 3);
subplot(2,3,5)
plotClusters(3, idx, C, allPoints)
title('k=3')
%%% k=4 %%%
[idx , C] = kmeans([cloud1 ; cloud2 ; cloud3], 4);
subplot(2,3,6)
plotClusters(4, idx, C, allPoints)
title('k=4')
end
function [] = plotClusters(k, idx, C, allPoints)
hold on
for i=1:k
cluster = allPoints(idx==i, :);
plot(cluster(:,1), cluster(:,2), '.')
plot(C(i,1), C(i,2), 'o')
end
end
|
github
|
jordiolivares/visio.artificial-master
|
ej13.m
|
.m
|
visio.artificial-master/images_P1/ej13.m
| 453 |
utf_8
|
12b07efedfd40d3c12a88caa9ff7ad49
|
function [ output ] = ej13()
car = imread('car_gray.jpg');
car_130 = auxiliar(car, 130);
figure
subplot(2,1,1)
imshow(car)
subplot(2,1,2)
imshow(car_130)
print('subplot_3_binarize.png', '-dpng');
close
end
function [ thresholded_image ] = auxiliar( image, threshold )
% Use the built-in function to binarize the image
thresholded_image = imbinarize(image, double(threshold) / 255.0);
end
|
github
|
jordiolivares/visio.artificial-master
|
ej411.m
|
.m
|
visio.artificial-master/images_P4/ej411.m
| 435 |
iso_8859_13
|
2e7195061f5cb72382168cefae30582b
|
function [ ] = testFiltros()
% Esta función pretende ilustrar el banco de filtros de la gaussiana
F=makeLMfilters();
% genera los filtros
visualizeFilters(F);
end
function [ ] = visualizeFilters(F)
% This function receives a bank of filters and visualize them by pseudocolors
figure, % visualiza todos los filtros
for k=1:size(F,3);
subplot(8,6,k);
imagesc(F(:,:,k)); colorbar;
end
end
|
github
|
jordiolivares/visio.artificial-master
|
makeLMfilters.m
|
.m
|
visio.artificial-master/images_P4/makeLMfilters.m
| 1,896 |
utf_8
|
91f2c95201e8f0112ddbc2abd05f854a
|
function F=makeLMfilters
% Returns the LML filter bank of size 49x49x48 in F. To convolve an
% image I with the filter bank you can either use the matlab function
% conv2, i.e. responses(:,:,i)=conv2(I,F(:,:,i),'valid'), or use the
% Fourier transform.
SUP=49; % Support of the largest filter (must be odd)
SCALEX=sqrt(2).^[1:3]; % Sigma_{x} for the oriented filters
NORIENT=6; % Number of orientations
NROTINV=12;
NBAR=length(SCALEX)*NORIENT;
NEDGE=length(SCALEX)*NORIENT;
NF=NBAR+NEDGE+NROTINV;
F=zeros(SUP,SUP,NF);
hsup=(SUP-1)/2;
[x,y]=meshgrid([-hsup:hsup],[hsup:-1:-hsup]);
orgpts=[x(:) y(:)]';
count=1;
for scale=1:length(SCALEX),
for orient=0:NORIENT-1,
angle=pi*orient/NORIENT; % Not 2pi as filters have symmetry
c=cos(angle);s=sin(angle);
rotpts=[c -s;s c]*orgpts;
F(:,:,count)=makefilter(SCALEX(scale),0,1,rotpts,SUP);
F(:,:,count+NEDGE)=makefilter(SCALEX(scale),0,2,rotpts,SUP);
count=count+1;
end;
end;
count=NBAR+NEDGE+1;
SCALES=sqrt(2).^[1:4];
for i=1:length(SCALES),
F(:,:,count)=normalise(fspecial('gaussian',SUP,SCALES(i)));
F(:,:,count+1)=normalise(fspecial('log',SUP,SCALES(i)));
F(:,:,count+2)=normalise(fspecial('log',SUP,3*SCALES(i)));
count=count+3;
end;
return
function f=makefilter(scale,phasex,phasey,pts,sup)
gx=gauss1d(3*scale,0,pts(1,:),phasex);
gy=gauss1d(scale,0,pts(2,:),phasey);
f=normalise(reshape(gx.*gy,sup,sup));
return
function g=gauss1d(sigma,mean,x,ord)
% Function to compute gaussian derivatives of order 0 <= ord < 3
% evaluated at x.
x=x-mean;num=x.*x;
variance=sigma^2;
denom=2*variance;
g=exp(-num/denom)/(pi*denom)^0.5;
switch ord,
case 1, g=-g.*(x/variance);
case 2, g=g.*((num-variance)/(variance^2));
end;
return
function f=normalise(f), f=f-mean(f(:)); f=f/sum(abs(f(:))); return
|
github
|
jordiolivares/visio.artificial-master
|
getFeatures.m
|
.m
|
visio.artificial-master/images_P4/getFeatures.m
| 517 |
utf_8
|
08549ab0fa2be0c5af292e13842a7182
|
function [ featuresVector ] = getFeatures( image )
%GETFEATURES Summary of this function goes here
% Detailed explanation goes here
F = makeLMfilters();
greyImage = rgb2gray(image);
featuresVector = zeros(1, size(F, 3));
for i = 1:size(F, 3)
featuresVector(i) = calculateFeature(F(:,:,i), greyImage);
end
end
function [meanConvolution] = calculateFeature(convolution, image)
convoluted = conv2(double(image), convolution, 'same');
meanConvolution = mean(convoluted(:));
end
|
github
|
vins24/bm_rng-master
|
degree_2_coef.m
|
.m
|
bm_rng-master/matlab/degree_2_coef.m
| 1,051 |
utf_8
|
76e213bb907ed966541fcc8c4897c1ea
|
%
% function to extract coefficients for a degree 2 polyonmial
%
% based on inspiration found in various MATLAB forums
%
function [my_coefs] = degree_2_coef(frac_bits, n, coef)
% n.m (Q notation)
% n = number bits for integer part of your number
% m = fractional bits, for example c1 = 12, c0 = 19 (passsed as array in frac_bits)
% frac_bits = [19,12];
% coef = input coefficients
m1 = frac_bits(1);
m2 = frac_bits(2);
m3 = frac_bits(3);
n1 = n(1);
n2 = n(2);
n3 = n(3);
for j= 1: size(coef,1)
% Converting decimal to binary of a signed fraction
d2b1 = dec2fix(coef(j,1), m1, n1);
d2b2 = dec2fix(coef(j,2), m2, n2);
d2b3 = dec2fix(coef(j,3), m3, n3);
% coefs in String cell array format
my_coefs{j,1} = strjoin(cellstr(num2str(d2b1'))','');
my_coefs{j,2} = strjoin(cellstr(num2str(d2b2'))','');
my_coefs{j,3} = strjoin(cellstr(num2str(d2b3'))','');
%fprintf('i=%4d C2=%s C1=%s C0=%s\n', j, my_coefs{j,3}, my_coefs{j,2}, my_coefs{j,1})
end
end
|
github
|
vins24/bm_rng-master
|
dec2twos.m
|
.m
|
bm_rng-master/matlab/dec2twos.m
| 1,742 |
utf_8
|
6fc10b62e47f86606bbcc2e04b51bbdc
|
%
% function to convert 2's compliment value to binary
%
% based on inspiration found in various MATLAB forums
%
function t = dec2twos(x, nbits)
% DEC2TWOS Convert decimal integer to binary string two's complement.
%
% Usage: T = DEC2TWOS(X, NBITS)
%
% Converts the signed decimal integer given by X (either a scalar, vector,
% or matrix) to the two's complement representation as a string. If X is a
% vector or matrix, T(i, :) is the representation for X(i) (the shape of X
% is not preserved).
%
% Example:
% >> dec2twos([23 3 -23 -3])
%
% ans =
%
% 010111
% 000011
% 101001
% 111101
%
% Inputs:
% -X: decimal integers to convert to two's complement.
% -NBITS: number of bits in the representation (optional, default is the
% fewest number of bits necessary).
%
% Outputs:
% -T: two's complement representation of X as a string.
%
% See also: TWOS2DEC, DEC2FIX, FIX2DEC, DEC2BIN, DEC2HEX, DEC2BASE.
error(nargchk(1, 2, nargin));
x = x(:);
maxx = max(abs(x));
nbits_min = nextpow2(maxx + (any(x == maxx))) + 1;
% Default number of bits.
if nargin == 1 || isempty(nbits)
nbits = nbits_min;
elseif nbits < nbits_min
warning('dec2twos:nbitsTooSmall', ['Minimum number of bits to ' ...
'represent maximum input x is %i, which is greater than ' ...
'input nbits = %i. Setting nbits = %i.'], ...
nbits_min, nbits, nbits_min)
nbits = nbits_min;
end
t = repmat('0', numel(x), nbits); % Initialize output: Case for x = 0
if any(x > 0)
t(x > 0, :) = dec2bin(x(x > 0), nbits); % Case for x > 0
end
if any(x < 0)
t(x < 0, :) = dec2bin(2^nbits + x(x < 0), nbits); % Case for x < 0
end
|
github
|
vins24/bm_rng-master
|
dec2fix.m
|
.m
|
bm_rng-master/matlab/dec2fix.m
| 2,256 |
utf_8
|
ded95370cf4bd96cf395fd4005061167
|
%
% function to convert 2's compliment value to binary
%
% based on inspiration found in various MATLAB forums
%
function f = dec2fix(x, nfracbits, nbits)
% DEC2FIX Convert decimal integer to binary string fixed point.
%
% Usage: F = DEC2FIX(X, NFRACBITS, NBITS)
%
% Converts the signed decimal integer given by X (either a scalar, vector,
% or matrix) to the two's complement representation as a string. If X is a
% vector or matrix, F(i, :) is the representation for X(i) (the shape of X
% is not preserved). Note that many fractional numbers that can be
% represented with a finite number of fractional digits cannot be
% represented by a finite number of fractional bits (specifically
% non-powers-of-two like 0.3), so input NFRACBITS is required to specify
% the precision for the number of fractional bits. Even powers-of-two
% fractional decimal numbers (like 0.5) require this input.
%
% Example:
% >> dec2fix([2.3 2.4 -2.3 -2.4], 3)
%
% ans =
%
% 010.010
% 010.011
% 101.110
% 101.101
%
% Inputs:
% -X: decimal integers to convert to two's complement.
% -NFRACBITS: number of bits to represent fractional part.
% -NBITS: total number of bits in the representation including the
% fractional bits (optional, default is the fewest number of bits
% necessary to represent the integer portion).
%
% Outputs:
% -F: fixed point representation of X as a string.
%
% See also: FIX2DEC, TWOS2DEC, DEC2TWOS, DEC2BIN, DEC2HEX, DEC2BASE.
error(nargchk(2, 3, nargin));
x = x(:);
maxx = max(abs(x));
nbits_min = max([nextpow2(maxx + (any(x == maxx))) + 1 + nfracbits, ...
nfracbits]);
% Default number of bits.
if nargin < 3
nbits = nbits_min;
elseif nbits < nbits_min
warning('dec2twos:nbitsTooSmall', ['Minimum number of bits to ' ...
'represent maximum input x is %i, which is greater than ' ...
'input nbits = %i. Setting nbits = %i.'], ...
nbits_min, nbits, nbits_min)
nbits = nbits_min;
end
% Convert to two's complement string.
f = dec2twos(round(x * 2.^nfracbits), nbits);
% Insert binary point.
f(:, end+1) = '_';
f = f(:, [1:(nbits-nfracbits), nbits+1, (nbits-nfracbits+1):nbits]);
|
github
|
vins24/bm_rng-master
|
lzd.m
|
.m
|
bm_rng-master/matlab/lzd.m
| 340 |
utf_8
|
342769b93194fbd08e5c6d943e64a1f1
|
%leading zero detector%
function [num_lzd] = lzd(u0)
num_lzd = 0;
t = u0;
% 0x800000000000
m = uint64(140737488355328);
for n = drange(1:48)
%for (i=0; i<47 ; i++) {
x = bitand(t, m, 'uint64');
if (x)
break;
else
num_lzd = num_lzd + 1;
t = bitshift(t, 1, 'uint64');
end
end
|
github
|
vins24/bm_rng-master
|
taus.m
|
.m
|
bm_rng-master/matlab/taus.m
| 1,166 |
utf_8
|
6b9e19d9415b909dae4abfb22c4fe301
|
function [s0, s1, s2, a] = taus(s0, s1, s2)
%a = 0;
x = uint32(0);
%a = (((s0 << 13) ^ s0) >> 19);
x = bitshift(s0, 13, 'uint32');
x= bitxor(x,s0);
x = bitshift(x,-19, 'uint32');
%a = bitshift((bitshift(s0, 13) ^ s0), -19);
%s0 = (((s0 & 0xFFFFFFFE) << 12) ^ a);
%s0 = bitshift(s0 & hex2dec('fffffffe'), 12) ^ x;
y = uint32(4294967294);
s0 = bitand(s0, y);
s0 = bitshift(s0, 12, 'uint32');
s0 = bitxor(s0, x);
%a = (((s1 << 2) ^ s1) >> 25);
%a = bitshift((bitshift(s1, 2) ^ s1), -25);
x = bitshift(s1,2);
x = bitxor(x,s1);
x = bitshift(x, -25, 'uint32');
%s1 = (((s1 & 0xFFFFFFF8) << 4) ^ a);
%s1 = bitshift(s1 & hex2dec('fffffff8'), 4) ^ x;
z = uint32(4294967288);
s1 = bitand(s1, z);
s1 = bitshift(s1, 4, 'uint32');
s1 = bitxor(s1, x);
%a = (((s2 << 3) ^ s2) >> 11);
%a = bitshift((bitshift(s2, 3) ^ s2), -11);
x = bitshift(s2, 3);
x = bitxor(x, s2);
x = bitshift(x,-11, 'uint32');
%s2 = (((s2 & 0xFFFFFFF0) << 17) ^ a);
%s2 = bitshift(s2 & hex2dec('fffffff0'), 17) ^ x;
m = uint32(4294967280);
s2 = bitand(s2, m);
s2 = bitshift(s2, 17, 'uint32');
s2 = bitxor(s2, x);
m = bitxor(s0,s1);
a = bitxor(m,s2);
end
|
github
|
vins24/bm_rng-master
|
degree_1_coef.m
|
.m
|
bm_rng-master/matlab/degree_1_coef.m
| 880 |
utf_8
|
7ca917c42bb19b2cbe700b7a246c69b5
|
%
% function to extract coefficients for a degree 1 polyonmial
%
% based on inspiration found in various MATLAB forums
%
function [my_coefs] = degree_1_coef(frac_bits, n, coef)
% n.m (Q notation)
% n = number bits for your number
% m = fractional bits, for example c1 = 12, c0 = 19 (passsed as array in frac_bits)
% frac_bits = [19,12];
% coef = input coefficients
m1 = frac_bits(1);
m2 = frac_bits(2);
n1 = n(1);
n2 = n(2);
for j= 1: size(coef,1)
% Converting decimal to binary of a signed fraction
d2b1 = dec2fix(coef(j,1), m1, n1);
d2b2 = dec2fix(coef(j,2), m2, n2);
% coefs in String cell array format
my_coefs{j,1} = strjoin(cellstr(num2str(d2b1'))','');
my_coefs{j,2} = strjoin(cellstr(num2str(d2b2'))','');
%fprintf('i=%4d C1=%12s C0=%12s\n', j, my_coefs{j,2}, my_coefs{j,1})
end
end
|
github
|
old-NWTC/FAST-master
|
PlotCertTestResults.m
|
.m
|
FAST-master/CertTest/PlotCertTestResults.m
| 26,846 |
utf_8
|
20415be42ae9440d9e1c9b5acccee429
|
function PlotCertTestResults( newPath, oldPath, PlotFAST, PlotAdams, PlotSimulink )
% FAST-ADAMS-Simulink CertTest comparisons:
%function PlotCertTestResults( newPath, oldPath, PlotFAST, PlotAdams, PlotSimulink )
% This function plots the FAST, ADAMS, and/or FAST_SFunc CertTest results,
% comparing .out/.plt, .elm, .asi, .pmf, and .eig files from the newPath
% with the files contained in oldPath. PlotFAST, PlotADAMS, and PlotSimulink
% are true/false values that can be set to avoid plotting results from
% particular CertTests (e.g., you can choose not to plot Simulink results)
%
% This function can produce hundreds of plots, so the files are saved as
% 150 dpi .png files in a directory called [oldPath "\Plots"] (which will
% be created if it doesn't already exist).
if nargin < 5
PlotSimulink = false;
end
if nargin < 4
PlotAdams = false;
end
if nargin < 3
PlotFAST = true;
end
if nargin < 2
oldPath = [ '.' filesep 'TstFiles' ];
end
if nargin == 0
newPath = '.';
end
descFiles = {'SFunc', 'Adams', 'FAST'};
plotFiles = [PlotSimulink, PlotAdams, PlotFAST];
for i= 1:26
fileRoot = ['Test' num2str(i,'%02.0f')];
oldRoot = strcat( oldPath, filesep, fileRoot, {'.SFunc', '_ADAMS', ''} );
newRoot = strcat( newPath, filesep, fileRoot, {'.SFunc', '_ADAMS', ''} );
if i == 14 % linearization case
oldFiles = strcat( oldRoot, {'.eig', '_LIN.out', '.eig'} );
newFiles = strcat( newRoot, {'.eig', '_LIN.out', '.eig'} );
nModes = 30;
CompareCertTestResults(3,newFiles(plotFiles), oldFiles(plotFiles), nModes, descFiles(plotFiles), ...
[fileRoot ' - First ' num2str(nModes) ' Natural Frequencies'], true, [fileRoot '_nf'] );
else
SavePngFiles = true; %setting this to false will keep ALL of the plot windows open
% SavePngFiles = false; %setting this to false will keep ALL of the plot windows open
% Compare time series
if i == 2 || i == 4 || i > 17 % use the new binary file format
oldFiles = strcat( oldRoot, {'.outb', '.plt', '.outb'} );
newFiles = strcat( newRoot, {'.outb', '.plt', '.outb'} );
else % use the text format
oldFiles = strcat( oldRoot, {'.out', '.plt', '.out'} );
newFiles = strcat( newRoot, {'.out', '.plt', '.out'} );
end
TitleLocDesc = cellstr(['new: ' newFiles{end} ' | old: ' oldFiles{end}]);
CompareCertTestResults(1,newFiles(plotFiles), oldFiles(plotFiles), [8, 7, 8], descFiles(plotFiles), [fileRoot ' Output Time Series'], SavePngFiles, [fileRoot '_ts'],TitleLocDesc );
end % time series
if i == 10
% Compare (.AD.out) .elm files
oldFiles = strcat( oldRoot, '.AD.out' );
newFiles = strcat( newRoot, '.AD.out' );
CompareCertTestResults(1,newFiles(plotFiles), oldFiles(plotFiles), [8, 7, 8], descFiles(plotFiles), [fileRoot ' AeroDyn Time Series'], true, [fileRoot '_ADts'] );
end % elm files
%% bjj: removed block for less plotting
continue;
if i==1 || i==3 || i==8
% Compare .azi files
oldFiles = strcat( oldRoot, '.azi' );
newFiles = strcat( newRoot, '.azi' );
CompareCertTestResults(1,newFiles(plotFiles), oldFiles(plotFiles), [7, 6, 7], descFiles(plotFiles), [fileRoot ' Azimuth Averages'] , true, [fileRoot '_azi'] );
end %azi files
if i==4 || i==7 || i==13 || i==17
% Compare .pmf files
oldFiles = strcat( oldRoot, '.pmf' );
newFiles = strcat( newRoot, '.pmf' );
if i == 4 || i == 17
CompareCertTestResults(2,newFiles(plotFiles), oldFiles(plotFiles), [ 8, 7, 8], descFiles(plotFiles), [fileRoot ' Probability Density Functions'], true, [fileRoot '_pmf'] );
else % these have TI and Mean Wind Speed in the header
CompareCertTestResults(2,newFiles(plotFiles), oldFiles(plotFiles), [11, 10, 11], descFiles(plotFiles), [fileRoot ' Probability Density Functions'], true, [fileRoot '_pmf'] );
end
end %pmf files
end
return;
end
%% --------------------------------------------------------------------------
function CompareCertTestResults(pltType, newFiles, oldFiles, HdrLines, descFiles, descTitle, savePlts, saveName, TitleLocDesc )
% Required Input:
% pltType - scalar that determines the content of the data files:
% when = 1, data file has one X column and many Y columns;
% when = 2, data file has X-Y columns.
% when = 3, data file is linearization output (files
% differ for differing output!)
% newFiles - cell array containing names of the new files to compare with oldFiles (no more than 7 files!)
% oldFiles - cell array containing names of the old files
%
% Optional Input:
% HdrLines - numeric array of size 3; default is [8, 7, 8]
% HdrLines(1) = total number of header lines in the file
% HdrLines(2) = number of the line containing the column titles
% HdrLines(3) = number of the line containing the column units
% descFiles - cell array containing description of the individual (new) files, displayed in plot legend
% descTitle - string or cell array containing a description of the plots, used in plot title
% savePlts - logical scalar; if true, plots will be saved as .png files in path(oldFiles)\Plots directory; default is false
% saveName - a RootName (relative to path(oldFiles)\Plots\) used to name the saved plots; default is RootName(oldFiles{1})
%
% Output:
% none
% set some constants for plotting
LineWidthConst = 3;
FntSz = 18;
LineColors = {[0 1 1],[1 0 1],[0 1 0],[0 0 1],[1 0 0],[1 1 0],[1 1 1]};
% set some parameters that won't change
OneXCol = 1;
ColPairs = 2;
NatFreq = 3;
% get the number of files and do some checking
numFiles = length(oldFiles);
numNew = length(newFiles);
if numFiles ~= numNew
error('CompareCertTestResults::oldFiles and newFiles file name cell arrays must be the same size for comparisons.');
end
if numFiles > length(LineColors)
error('CompareCertTestResults::too many files. there aren''t enough colors defined.');
end
% set some defaults for optional inputs
if nargin < 7
savePlts = false;
if nargin < 4
HdrLines = [8, 7, 8];
end
end
if nargin < 6 || isempty(descTitle) %short-circuting allowed!
descTitle = {'File Comparisons Using Old Files' oldFiles{:}};
else
descTitle = ['File Comparisons for ' descTitle];
end
if nargin > 8 %bjj:there is a better way to do this, but I don't feel like figuring it out right now
descTitle = cellstr(descTitle);
for i=1:length(TitleLocDesc)
descTitle{1+i}=TitleLocDesc{i};
end
end
if (nargin <= 4) || (numFiles ~= length(descFiles))
descFiles = cell(nf,1);
getTxt = true;
else
getTxt = false;
end
[pathstr, name ] = fileparts(oldFiles{1} );
if nargin < 8
saveName = name;
end
OutFilePath = [pathstr filesep 'Plots' ];
% make sure the directory exists; if not, create it
if ~exist(OutFilePath, 'dir')
mkdir( OutFilePath );
end
OutFileRoot = [OutFilePath filesep saveName];
% get the data for plotting
oldData = cell(numFiles,1);
newData = cell(numFiles,1);
%% Plot the Natural Frequencies and return
if pltType == NatFreq
nFreq = HdrLines(1);
fig = plotNaturalFrequencies( oldFiles, newFiles, descFiles, descTitle, nFreq, FntSz, LineColors );
set(fig,'paperorientation','landscape','paperposition',[0.25 0.25 10.5 8])
if savePlts
print(fig,'-dpng','-r150',[OutFileRoot '.png']);
close(fig)
end
return;
end
%% we're going to plot some x-y data...
nCols = 0;
nCols_new = 0;
oldCols = cell(numFiles,1);
colName = cell(numFiles,1);
oldUnits = cell(numFiles,1);
for iFile = 1:numFiles
if length(oldFiles{iFile}) > 4 && strcmpi( oldFiles{iFile}((end-4):end),'.outb' )
[oldData{iFile}, oldCols{iFile}, oldUnits{iFile}] = ReadFASTbinary(oldFiles{iFile});
else
[oldData{iFile}, oldCols{iFile}, oldUnits{iFile}] = ReadFASTtext(oldFiles{iFile}, '', HdrLines(1), HdrLines(2), HdrLines(3));
end
if length(newFiles{iFile}) > 4 && strcmpi( newFiles{iFile}((end-4):end),'.outb' )
[newData{iFile}, colName{iFile} ] = ReadFASTbinary(newFiles{iFile});
else
[newData{iFile}, colName{iFile} ] = ReadFASTtext(newFiles{iFile}, '', HdrLines(1), HdrLines(2), HdrLines(3));
end
nCols = max(nCols, size(oldData{iFile},2));
nCols_new = max(nCols_new, size(newData{iFile},2));
if getTxt
descFiles{iFile} = ['File ' num2str(iFile)];
end
end %iFile
if nCols == 0
disp(['CompareCertTestResults::No data found for ' saveName]);
return;
elseif pltType == ColPairs
if mod(nCols,2) ~= 0
error(['CompareCertTestResults::number of columns must be even for X-Y pairings for ' saveName]);
end
end
NoDiff = true(numFiles,1);
for iFile = 1:numFiles
[nr_Old, nc_Old] = size(oldData{iFile});
[nr_New, nc_New] = size(newData{iFile});
if nc_New == 0 || nc_Old == 0
NoDiff(iFile) = false;
else
if nCols ~= nc_Old || nCols ~= nc_New
%bjj: we're going to try to match the columns now (before this was an error)
disp(['CompareCertTestResults::number of columns differ in the file comparisons of old and new ' descFiles{iFile} ' files.']);
fprintf( ' File %i old: %i rows x %i columns\n new: %i rows x %i columns\n', ...
iFile, nr_Old, nc_Old, nr_New, nc_New );
end
if nr_Old ~= nr_New
disp('WARNING: CompareCertTestResults::number of rows differ in the file comparisons');
NoDiff(iFile) = false;
else
if pltType == OneXCol
t_diff = oldData{iFile}(:,1) - newData{iFile}(:,1);
if norm(t_diff,inf) > 0.005
% figure; plot(t_diff);
disp(['WARNING: CompareCertTestResults::X columns (column 1) in old and new ' descFiles{iFile} ...
' files differ by more than 0.005' oldUnits{iFile}{1} ] );
NoDiff(iFile) = false;
end
elseif pltType == ColPairs
t_diff = oldData{iFile}(:,1:2:end) - newData{iFile}(:,1:2:end);
if norm(t_diff(:),inf) > 0.005 %bjj this is probably not a very good test
% figure; plot(t_diff);
disp(['WARNING: CompareCertTestResults::X columns in old and new ' descFiles{iFile} ...
' files differ by more than 0.005 units.'] );
NoDiff(iFile) = false;
end %norm(t_diff(
end %OneXCol
end %nr_Old ~= nr_New
end %nc_New == 0 || nc_Old == 0
end %for iFile
% create the plots for time series-type data
switch pltType
case ColPairs
strd = 2;
case OneXCol
strd = 1;
otherwise
error(['CompareCertTestResults::invalid plot type ' num2str(pltType) ]);
end % switch
anyDiffPlot = false;
nCols = size(oldData{1},2);
for iPlot = 2:strd:nCols
% for iPlot = 100:strd:nCols
fig=figure;
ChannelName = oldCols{1}{iPlot};
[ChannelName_new,scaleFactor] = getNewChannelName(ChannelName);
HaveLabels = false; %if we don't find any labels for these plots, we can't plot them
for iFile = 1:numFiles
HaveLabels = false;
subplot(6,1,1:4);
hold on;
[yCol_old,err1] = getColIndx( ChannelName, oldCols{iFile}, oldFiles{iFile} );
[yCol_new,err2] = getColIndx( ChannelName_new, colName{iFile}, newFiles{iFile} );
if err1 || err2
continue
else
% fprintf('%10s (%3.0f) %10s (%3.0f)\n', ChannelName, yCol_old, ChannelName_new, yCol_new );
HaveLabels = true;
switch pltType
case ColPairs
xCol_old = yCol_old-1;
xCol_new = yCol_new-1;
case OneXCol
xCol_old = 1;
xCol_new = 1;
otherwise
error('Invalid pltType in PlotCertTestResults:CompareCertTestResults');
end
end
h1(1) = plot(oldData{iFile}(:,xCol_old), oldData{iFile}(:,yCol_old));
set(h1(1),'LineStyle','-', 'DisplayName',[descFiles{iFile} ', old'],'Color',LineColors{iFile}, 'LineWidth',LineWidthConst+1);
h1(2) = plot(newData{iFile}(:,xCol_new), newData{iFile}(:,yCol_new)/scaleFactor );
set(h1(2),'LineStyle',':', 'DisplayName',[descFiles{iFile} ', new'],'Color',LineColors{iFile}*0.75, 'LineWidth',LineWidthConst);
% set(h1(2),'LineStyle','--','DisplayName',[descFiles{iFile} ', new'],'Color',LineColors{iFile}*0.75, 'LineWidth',LineWidthConst+1);
currXLim = xlim;
if NoDiff(iFile)
anyDiffPlot = true;
% absolute difference
subplot(6,1,5);
AbsDiff = (oldData{iFile}(:,yCol_old)-newData{iFile}(:,yCol_new)/scaleFactor );
plot(oldData{iFile}(:,xCol_old) , AbsDiff, ...
'Displayname',descFiles{iFile},'Color',LineColors{iFile}, 'LineWidth',LineWidthConst);
hold on;
xlim(currXLim);
% relative difference (% of old)
subplot(6,1,6);
plot(oldData{iFile}(:,xCol_old) , 100*AbsDiff./ oldData{iFile}(:,yCol_old), ...
'Displayname',descFiles{iFile},'Color',LineColors{iFile}, 'LineWidth',LineWidthConst);
hold on;
xlim(currXLim);
end
end %iFile
if HaveLabels %did we find columns to match?
for iSubPl=1:3
if iSubPl == 3
subplot(6,1,1:4)
yTxt = {oldCols{iFile}{yCol_old}, oldUnits{iFile}{yCol_old}} ;
elseif anyDiffPlot
if iSubPl == 2
subplot(6,1,5)
yTxt = {'Difference' ,'(Old-New)', oldUnits{iFile}{yCol_old}};
else
subplot(6,1,6);
yTxt = {'Relative' 'Difference','(%)'};
xlabel([oldCols{iFile}{xCol_old} ' ' oldUnits{iFile}{xCol_old}],'FontSize',FntSz ) ;
end
else %difference plots
xlabel([oldCols{iFile}{xCol_old} ' ' oldUnits{iFile}{xCol_old}],'FontSize',FntSz ) ;
continue;
end
set(gca,'FontSize',FntSz,'gridlinestyle','-');
ylabel(yTxt);
grid on;
end %iSubPl
t=title( descTitle,'interpreter','none','FontSize',FntSz-1 );
% set(t,'interpreter','none')
% set(t,'FontSize',FntSz-1);
h=legend('show');
set(h,'interpreter','none','FontSize',FntSz-3); %'location','best');
set(fig,'paperorientation','landscape','paperposition',[0.25 0.25 10.5 8] ...
,'Name',oldCols{iFile}{yCol_old});
if savePlts
%Matlab 2012:
%print(['-f' num2str(fig)],'-dpng','-r150',[OutFileRoot '_' num2str(iPlot-1) '.png']);
%Matlab 2014b:
print(fig,'-dpng','-r150',[OutFileRoot '_' num2str(iPlot-1) '.png']);
close(fig)
end
else
close(fig)
end
end %iPlot
return;
end
%% ------------------------------------------------------------------------
function [ChannelName_new,scaleFact] = getNewChannelName(ChannelName)
scaleFact = 1.0;
if strcmpi(ChannelName,'WaveElev')
ChannelName_new = 'Wave1Elev';
elseif strncmpi( ChannelName,'Fair',4 ) && strcmpi( ChannelName((end-2):end), 'Ten') %TFair[i] = FairiTen
ChannelName_new = strrep( strrep( ChannelName,'Fair','TFair['),'Ten',']');
elseif strncmpi( ChannelName,'Anch',4 ) && strcmpi( ChannelName((end-2):end), 'Ten') %TAnch[i] = AnchiTen
ChannelName_new = strrep( strrep( ChannelName,'Anch','TAnch['),'Ten',']');
elseif strncmpi( ChannelName,'Anch',4 ) && strcmpi( ChannelName((end-2):end), 'Ten') %TAnch[i] = AnchiTen
ChannelName_new = strrep( strrep( ChannelName,'Anch','TAnch['),'Ten',']');
elseif strcmpi(ChannelName,'IntfXss')
ChannelName_new = 'IntfFXss';
elseif strcmpi(ChannelName,'IntfYss')
ChannelName_new = 'IntfFYss';
elseif strcmpi(ChannelName,'IntfZss')
ChannelName_new = 'IntfFZss';
elseif strcmpi(ChannelName,'ReactXss')
ChannelName_new = 'ReactFXss';
elseif strcmpi(ChannelName,'ReactYss')
ChannelName_new = 'ReactFYss';
elseif strcmpi(ChannelName,'ReactZss')
ChannelName_new = 'ReactFZss';
elseif strcmpi(ChannelName,'WindVxi')
ChannelName_new = 'Wind1VelX';
elseif strcmpi(ChannelName,'WindVyi')
ChannelName_new = 'Wind1VelY';
elseif strcmpi(ChannelName,'WindVzi')
ChannelName_new = 'Wind1VelZ';
% elseif strcmpi(ChannelName,'TTDspFA')
% ChannelName_new = 'TwHt1TPxi';
% elseif strcmpi(ChannelName,'TTDspSS')
% ChannelName_new = 'TwHt1TPyi';
% elseif strcmpi(ChannelName,'-TwrBsFxt')
% ChannelName_new = 'ReactFXss';
% scaleFact = 1000;
% elseif strcmpi(ChannelName,'-TwrBsFyt')
% ChannelName_new = 'ReactFYss';
% scaleFact = 1000;
% elseif strcmpi(ChannelName,'-TwrBsFzt')
% ChannelName_new = 'ReactFZss';
% scaleFact = 1000;
% elseif strcmpi(ChannelName,'-TwrBsMxt')
% ChannelName_new = 'ReactMXss';
% scaleFact = 1000;
% elseif strcmpi(ChannelName,'-TwrBsMyt')
% ChannelName_new = 'ReactMYss';
% scaleFact = 1000;
% elseif strcmpi(ChannelName,'-TwrBsMzt')
% ChannelName_new = 'ReactMZss';
% scaleFact = 1000;
else
ChannelName_new = strrep(ChannelName,'Wave1V','M1N1V');
ChannelName_new = strrep(ChannelName_new,'Wave1A','M1N1A');
%ChannelName_new = ChannelName_new;
end
if strncmpi(ChannelName_new,'TFair[',6)
ChannelName_new = strrep(ChannelName_new, 'TFair[','T[');
scaleFact = 1000;
elseif strncmpi(ChannelName_new,'TAnch[',6)
ChannelName_new = strrep(ChannelName_new, 'TAnch[','T_a[');
scaleFact = 1000;
end
return
end
%% ------------------------------------------------------------------------
function [Indx,err] = getColIndx( ColToFind, colNames, fileName )
Indx = find( strcmpi(ColToFind, colNames), 1, 'first' );
if isempty(Indx)
disp(['Error: ' ColToFind ' not found in ' fileName ]);
err = true;
else
err = false;
end
return
end
%% ------------------------------------------------------------------------
function [fig] = plotNaturalFrequencies( oldFiles, newFiles, descFiles, descTitle, nFreq, FntSz, LineColors )
nf = length(oldFiles);
OldData = cell(nf,1);
NewData = cell(nf,1);
% get the data
% barData = [];
% descTxt = cell(nf*2,1);
groupSpacing = 1; %this serves as our spacing between groupings (fraction of a bar)
nBars = 0;
maxNF = 0;
for iFile = 1:nf
OldData{iFile} = getEigenvaluesFromFile(oldFiles{iFile});
NewData{iFile} = getEigenvaluesFromFile(newFiles{iFile});
if ~isempty(OldData{iFile})
nBars = nBars + 1;
maxNF = max(maxNF, length(OldData{iFile}));
end
if ~isempty(NewData{iFile})
nBars = nBars + 1;
maxNF = max(maxNF, length(NewData{iFile}));
end
% indx = iFile*2;
% indxm1 = indx - 1 ;
%
% barData{:,indx } = getEigenvaluesFromFile(newFiles{iFile});
% barData{:,indxm1} = getEigenvaluesFromFile(oldFiles{iFile});
%
% descTxt{indx} = [descFiles{iFile} ', new'];
% descTxt{indxm1} = [descFiles{iFile} ', old'];
end
% create a bar plot
fig = figure;
t = title( descTitle,'interpreter','none','FontSize',FntSz );
set(t,'interpreter','none');
hold on;
barIndxStart = 1.5;
barIndx = barIndxStart;
groupSpacing = groupSpacing + nBars;
for iFile = 1:nf
L1 = length(OldData{iFile});
if L1 > 0
xAxis = ( 0:(L1-1) )*groupSpacing + barIndx;
h = bar(xAxis,OldData{iFile},1/groupSpacing);
set(h, 'FaceColor', LineColors{iFile}, 'DisplayName',[descFiles{iFile} ', old']);
barIndx = barIndx + 1;
end
L2 = length(NewData{iFile});
if L2 > 0
xAxis = ( 0:(L2-1) )*groupSpacing + barIndx;
h = bar(xAxis,OldData{iFile},1/groupSpacing);
set(h, 'FaceColor', LineColors{iFile}*0.65, 'DisplayName',[descFiles{iFile} ', new']);
barIndx = barIndx + 1;
end
end
if maxNF > 0
xAxis = ( 0:(maxNF-1) )*groupSpacing + barIndx - 0.5*nBars - 0.5;
% set(gca,'xlim',[1 maxNF*nBars+barIndx-1],'xtick',xAxis);
nFact = max(1,floor(nFreq/15)); %15 is max number of axis ticks
h=gca;
h.XTick = xAxis(1:nFact:end);
h.XTickLabel = 1:nFact:maxNF;
xlim([1, groupSpacing*nFreq]);
%bjj: there is something weird here, but I'm too tired to care
%set(h,'xtick',xAxis(1:nFact:end),'xticklab',1:nFact:maxNF);
% set(h,'xlim',[1 groupSpacing*nFreq]);
end
set(gca,'FontSize',FntSz-3,'ygrid','on','gridlinestyle','-');
ylabel('Full System Natural Frequency, Hz','FontSize',FntSz);
xlabel('Full System Mode Number','FontSize',FntSz);
box on;
h=legend('show');
set(h,'interpreter','none','FontSize',FntSz-3,'location','NorthWest');
return
end
%% ------------------------------------------------------------------------
function [eivalues] = getEigenvaluesFromFile(fileName)
fid = fopen(fileName);
if fid > 0
line = fgetl(fid);
while ischar(line)
if isempty( strfind(line, 'E I G E N V A L U E S') ) % ADAMS FILES HAVE THIS IDENTIFIER (but this could change in other versions!!!!)
if isempty( strfind(line, 'ans =') ) % Output from Matlab script (this could change, in other versions, too!!!!!)
% keep looking
line = fgetl(fid);
else
% read from Matlab (FAST) output file
dat = textscan( fid, '%f' ); %we'll read to the end of this section/file where there aren't any more numbers
eivalues = dat{1};
break;
end
else
% read from ADAMS output file
fgetl(fid); % header
% textscan( fid, '%*s%f', 'delimiter','+/-' ); %we're just getting the imaginary parts
dat = textscan( fid, '%f%f%*s%f' ); %we'll read to the end of this section (when there aren't numbers anymore)
eivalues = dat{3};
break;
end
end
fclose( fid );
else
disp( ['getEigenvaluesFromFile::Error ' num2str(fid) ' opening file, "' fileName '".' ]);
eivalues = [];
end
return;
end
%% ------------------------------------------------------------------------
|
github
|
kaltwang/2015doubly-master
|
tprod_testcases.m
|
.m
|
2015doubly-master/code/toolboxes/tprod/tprod_testcases.m
| 17,197 |
utf_8
|
26b0e1b54b6867e5d62e8956c84e01bd
|
function []=tprod_testcases(testCases,debugin)
% This file contains lots of test-cases to test the performance of the tprod
% files vs. the matlab built-ins.
%
%
% Copyright 2006- by Jason D.R. Farquhar ([email protected])
% Permission is granted for anyone to copy, use, or modify this
% software and accompanying documents for any uncommercial
% purposes, provided this copyright notice is retained, and note is
% made of any changes that have been made. This software and
% documents are distributed without any warranty, express or
% implied
if ( nargin < 1 || isempty(testCases) ) testCases={'acc','timing','blksz'}; end;
if ( ~iscell(testCases) ) testCases={testCases}; end;
if ( nargin < 2 ) debugin=1; end;
global DEBUG; DEBUG=debugin;
% fprintf('------------------ memory execption test ------------\n');
% ans=tprod(randn(100000,1),1,randn(100000,1)',1);
% ans=tprod(randn(100000,1),1,randn(100000,1)',1,'m');
%-----------------------------------------------------------------------
% Real , Real
if ( ~isempty(strmatch('acc',testCases)) )
fprintf('------------------- Accuracy tests -------------------\n');
X=complex(randn(101,101,101),randn(101,101,101));
Y=complex(randn(101,101),randn(101,101));
fprintf('\n****************\n Double Real X, Double Real Y\n******************\n')
accuracyTests(real(X),real(Y),'dRdR');
fprintf('\n****************\n Double Real X, Double Complex Y\n******************\n')
accuracyTests(real(X),Y,'dRdC');
fprintf('\n****************\n Double Complex X, Double Real Y\n******************\n')
accuracyTests(X,real(Y),'dCdR');
fprintf('\n****************\n Double Complex X, Double Complex Y\n******************\n')
accuracyTests(X,Y,'dCdC');
fprintf('\n****************\n Double Real X, Single Real Y\n******************\n')
accuracyTests(real(X),single(real(Y)),'dRsR');
fprintf('\n****************\n Double Real X, Single Complex Y\n******************\n')
accuracyTests(real(X),single(Y),'dRsC');
fprintf('\n****************\n Double Complex X, Single Real Y\n******************\n')
accuracyTests(X,single(real(Y)),'dCsR');
fprintf('\n****************\n Double Complex X, Single Complex Y\n******************\n')
accuracyTests(X,single(Y),'dCsC');
fprintf('\n****************\n Single Real X, Double Real Y\n******************\n')
accuracyTests(single(real(X)),real(Y),'sRdR');
fprintf('\n****************\n Single Real X, Double Complex Y\n******************\n')
accuracyTests(single(real(X)),Y,'sRdC');
fprintf('\n****************\n Single Complex X, Double Real Y\n******************\n')
accuracyTests(single(X),real(Y),'sCdR');
fprintf('\n****************\n Single Complex X, Double Complex Y\n******************\n')
accuracyTests(single(X),Y,'sCdC');
fprintf('\n****************\n Single Real X, Single Real Y\n******************\n')
accuracyTests(single(real(X)),single(real(Y)),'sRsR');
fprintf('\n****************\n Single Real X, Single Complex Y\n******************\n')
accuracyTests(single(real(X)),single(Y),'sRsC');
fprintf('\n****************\n Single Complex X, Single Real Y\n******************\n')
accuracyTests(single(X),single(real(Y)),'sCsR');
fprintf('\n****************\n Single Complex X, Single Complex Y\n******************\n')
accuracyTests(single(X),single(Y),'sCsC');
fprintf('All tests passed\n');
end
% fprintf('------------------- Timing tests -------------------\n');
if ( ~isempty(strmatch('timing',testCases)) )
%Timing tests
X=complex(randn(101,101,101),randn(101,101,101));
Y=complex(randn(101,101),randn(101,101));
fprintf('\n****************\n Real X, Real Y\n******************\n')
timingTests(real(X),real(Y),'RR');
fprintf('\n****************\n Real X, Complex Y\n******************\n')
timingTests(real(X),Y,'RC');
fprintf('\n****************\n Complex X, Real Y\n******************\n')
timingTests(X,real(Y),'CR');
fprintf('\n****************\n Complex X, Complex Y\n******************\n')
timingTests(X,Y,'CC');
end
% fprintf('------------------- Scaling tests -------------------\n');
% scalingTests([32,64,128,256]);
if( ~isempty(strmatch('blksz',testCases)) )
fprintf('------------------- Blksz tests -------------------\n');
blkSzTests([128 96 64 48 40 32 24 16 0],[128,256,512,1024,2048]);
end
return;
function []=accuracyTests(X,Y,str)
unitTest([str ' OuterProduct, [1],[2]'],tprod(X(:,1),1,Y(:,1),2,'m'),X(:,1)*Y(:,1).');
unitTest([str ' Inner product, [-1],[-1]'],tprod(X(:,1),-1,Y(:,1),-1,'m'),X(:,1).'*Y(:,1));
unitTest([str ' Matrix product, [1 -1],[-1 2]'],tprod(X(:,:,1),[1 -1],Y,[-1 2],'m'),X(:,:,1)*Y);
unitTest([str ' transposed matrix product, [-1 1],[-1 2]'],tprod(X(:,:,1),[-1 1],Y,[-1 2],'m'),X(:,:,1).'*Y);
unitTest([str ' Matrix frobenius norm, [-1 -2],[-1 -2]'],tprod(X(:,:,1),[-1 -2],Y,[-1 -2],'m'),sum(sum(X(:,:,1).*Y)));
unitTest([str ' transposed matrix frobenius norm, [-1 -2],[-2 -1]'],tprod(X(:,:,1),[-1 -2],Y,[-2 -1],'m'),sum(sum(X(:,:,1).'.*Y)));
unitTest([str ' ignored dims, [0 -2],[-2 2 1]'],tprod(Y(1,:),[0 -2],X(:,:,:),[-2 2 1],'m'),reshape(Y(1,:)*reshape(X,size(X,1),[]),size(X,2),size(X,3)).');
% Higher order matrix operations
unitTest([str ' spatio-temporal filter [-1 -2 1],[-1 -2]'],tprod(X,[-1 -2 1],Y,[-1 -2],'m'),reshape(Y(:).'*reshape(X,size(X,1)*size(X,2),size(X,3)),[size(X,3) 1]));
unitTest([str ' spatio-temporal filter (fallback) [-1 -2 1],[-1 -2]'],tprod(X,[-1 -2 1],Y,[-1 -2]),reshape(Y(:).'*reshape(X,size(X,1)*size(X,2),size(X,3)),[size(X,3) 1]));
unitTest([str ' spatio-temporal filter (order) [-1 -2],[-1 -2 1]'],tprod(Y,[-1 -2],X,[-1 -2 1]),reshape(Y(:).'*reshape(X,size(X,1)*size(X,2),size(X,3)),[size(X,3) 1]));
unitTest([str ' spatio-temporal filter (order) [-1 -2],[-1 -2 3]'],tprod(Y,[-1 -2],X,[-1 -2 3]),reshape(Y(:).'*reshape(X,size(X,1)*size(X,2),size(X,3)),[1 1 size(X,3)]));
unitTest([str ' transposed spatio-temporal filter [1 -2 -3],[-2 -3]'],tprod(X,[1 -2 -3],Y,[-2 -3],'m'),reshape(reshape(X,size(X,1),size(X,2)*size(X,3))*Y(:),[size(X,1) 1]));
unitTest([str ' matrix-vector product [-1 1 2][-1]'],tprod(X,[-1 1 2],Y(:,1),[-1],'m'),reshape(Y(:,1).'*reshape(X,[size(X,1) size(X,2)*size(X,3)]),[size(X,2) size(X,3)]));
unitTest([str ' spatial filter (fallback): [-1 2 3],[-1 1]'],tprod(X,[-1 2 3],Y,[-1 1]),reshape(Y.'*reshape(X,[size(X,1) size(X,2)*size(X,3)]),[size(Y,2) size(X,2) size(X,3)]));
unitTest([str ' spatial filter: [-1 2 3],[-1 1]'],tprod(X,[-1 2 3],Y,[-1 1],'m'),reshape(Y.'*reshape(X,[size(X,1) size(X,2)*size(X,3)]),[size(Y,2) size(X,2) size(X,3)]));
unitTest([str ' temporal filter [1 -2 3],[2 -2]'],tprod(X,[1 -2 3],Y(1,:),[2 -2],'m'),sum(X.*repmat(Y(1,:),[size(X,1) 1 size(X,3)]),2));
unitTest([str ' temporal filter [2 -2],[1 -2 3]'],tprod(Y(1,:),[2 -2],X,[1 -2 3],'m'),sum(X.*repmat(Y(1,:),[size(X,1) 1 size(X,3)]),2));
unitTest([str ' temporal filter [-2 2],[1 -2 3]'],tprod(Y(1,:).',[-2 2],X,[1 -2 3],'m'),sum(X.*repmat(Y(1,:),[size(X,1) 1 size(X,3)]),2));
unitTest([str ' temporal filter [-2 2],[1 -2 3]'],tprod(Y(1,:).',[-2 2],X,[1 -2 3],'m'),sum(X.*repmat(Y(1,:),[size(X,1) 1 size(X,3)]),2));
Xp=permute(X,[1 3 2]);
unitTest([str ' blk-code [-1 1 -2][-1 2 -2]'],tprod(X,[-1 1 -2],X,[-1 2 -2],'m'),reshape(Xp,[],size(Xp,3)).'*reshape(Xp,[],size(Xp,3)));
return;
function []=timingTests(X,Y,str);
% outer product simulation
fprintf([str ' OuterProduct [1][2]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic; for i=1:1000; Z=tprod(X(:,1),1,Y(:,1),2); end
fprintf('%30s %gs\n','tprod',toc/1000); % = .05 / .01
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic; for i=1:1000; Zm=tprod(X(:,1),1,Y(:,1),2,'m'); end
fprintf('%30s %gs\n','tprod m',toc/1000); % = .05 / .01
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic, for i=1:1000;T=X(:,1)*Y(:,1).';end;
fprintf('%30s %gs\n','MATLAB',toc/1000); % = .03 / .01
% matrix product
fprintf([str ' MatrixProduct [1 -1][-1 2]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic, for i=1:1000;Z=tprod(X(:,:,1),[1 -1],Y,[-1 2]);end
fprintf('%30s %gs\n','tprod',toc/1000);% = .28 / .06
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic, for i=1:1000;Zm=tprod(X(:,:,1),[1 -1],Y,[-1 2],'m');end
fprintf('%30s %gs\n','tprod m',toc/1000);% = .28 / .06
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic, for i=1:1000;T=X(:,:,1)*Y;end
fprintf('%30s %gs\n','MATLAB',toc/1000);% = .17 / .06
% transposed matrix product simulation
fprintf([str ' transposed Matrix Product [-1 1][2 -1]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic, for i=1:1000;Z=tprod(X(:,:,1),[-1 1],Y,[2 -1]);end
fprintf('%30s %gs\n','tprod',toc/1000);% =.3 / .06
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic, for i=1:1000;Zm=tprod(X(:,:,1),[-1 1],Y,[2 -1],'m');end
fprintf('%30s %gs\n','tprod m',toc/1000);% =.3 / .06
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic, for i=1:1000;T=X(:,:,1).'*Y.';end
fprintf('%30s %gs\n','MATLAB',toc/1000); % =.17 / .06
% Higher order matrix operations % times: P3-m 1.8Ghz 2048k / P4 2.4Ghz 512k
fprintf([str ' spatio-temporal filter [-1 -2 1] [-1 -2]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:500;Z=tprod(X,[-1 -2 1],Y,[-1 -2]);end,
fprintf('%30s %gs\n','tprod',toc/500);% =.26 / .18
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:500;Zm=tprod(X,[-1 -2 1],Y,[-1 -2],'m');end,
fprintf('%30s %gs\n','tprod m',toc/500);% =.26 / .18
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:500;T=reshape(Y(:).'*reshape(X,size(X,1)*size(X,2),size(X,3)),[size(X,3) 1]);end,
fprintf('%30s %gs\n','MATLAB',toc/500); %=.21 / .18
fprintf([str ' transposed spatio-temporal filter [1 -2 -3] [-2 -3]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:50;Z=tprod(X,[1 -2 -3],Y,[-2 -3]);end,
fprintf('%30s %gs\n','tprod',toc/50);% =.27 / .28
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:50;Zm=tprod(X,[1 -2 -3],Y,[-2 -3],'m');end,
fprintf('%30s %gs\n','tprod m',toc/50);% =.27 / .28
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:50;T=reshape(reshape(X,size(X,1),size(X,2)*size(X,3))*Y(:),[size(X,1) 1]);end,
fprintf('%30s %gs\n','MATLAB',toc/50); %=.24 / .26
% MATRIX vector product
fprintf([str ' matrix-vector product [-1 1 2] [-1]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:500; Z=tprod(X,[-1 1 2],Y(:,1),[-1]);end,
fprintf('%30s %gs\n','tprod',toc/500); %=.27 / .26
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:500; Zm=tprod(X,[-1 1 2],Y(:,1),[-1],'m');end,
fprintf('%30s %gs\n','tprod m',toc/500); %=.27 / .26
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:500; T=reshape(Y(:,1).'*reshape(X,[size(X,1) size(X,2)*size(X,3)]),[1 size(X,2) size(X,3)]);end,
fprintf('%30s %gs\n','MATLAB (reshape)',toc/500);%=.21 / .28
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:500; T=zeros([size(X,1),1,size(X,3)]);for k=1:size(X,3); T(:,:,k)=Y(1,:)*X(:,:,k); end,end,
fprintf('%30s %gs\n','MATLAB (loop)',toc/500); %=.49 /
% spatial filter
fprintf([str ' Spatial filter: [-1 2 3],[-1 1]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic;for i=1:500;Z=tprod(X,[-1 2 3],Y(:,1:2),[-1 1]);end;
fprintf('%30s %gs\n','tprod',toc/500);%=.39/.37
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic;for i=1:500;Zm=tprod(X,[-1 2 3],Y(:,1:2),[-1 1],'m');end;
fprintf('%30s %gs\n','tprod m',toc/500);%=.39/.37
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic;for i=1:500; T=reshape(Y(:,1:2).'*reshape(X,[size(X,1) size(X,2)*size(X,3)]),[2 size(X,2) size(X,3)]);end;
fprintf('%30s %gs\n','MATLAB',toc/500);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic;for i=1:500;T=zeros(2,size(X,2),size(X,3));for k=1:size(X,3);T(:,:,k)=Y(:,1:2).'*X(:,:,k);end;end;
fprintf('%30s %gs\n','MATLAB (loop)',toc/500); %=.76/.57
% temporal filter
fprintf([str ' Temporal filter: [1 -2 3],[2 -2]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:50; Z=tprod(X,[1 -2 3],Y,[2 -2]);end
fprintf('%30s %gs\n','tprod',toc/50); %=.27 / .31
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:50; T=zeros([size(X,1),size(Y,1),size(X,3)]);for k=1:size(X,3); T(:,:,k)=X(:,:,k)*Y(:,:).'; end,end,
fprintf('%30s %gs\n','MATLAB (loop)',toc/50); %= .50 /
%tic,for i=1:50; T=zeros([size(X,1),size(Y,1),size(X,3)]); for k=1:size(Y,1); T(:,k,:)=sum(X.*repmat(Y(k,:),[size(X,1) 1 size(X,3)]),2);end,end;
%fprintf('%30s %gs\n','MATLAB (repmat)',toc/50); %=3.9 / 3.3
fprintf([str ' Temporal filter2: [1 -2 3],[-2 2]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:50; Z=tprod(X,[1 -2 3],Y,[-2 2]);end
fprintf('%30s %gs\n','tprod',toc/50); %=.27 / .31
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:50; T=zeros([size(X,1),size(Y,1),size(X,3)]);for k=1:size(X,3); T(:,:,k)=X(:,:,k)*Y(:,:); end,end,
fprintf('%30s %gs\n','MATLAB (loop)',toc/50); %= .50 /
% Data Covariances
fprintf([str ' Channel-covariance/trial(3) [1 -1 3] [2 -1 3]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic;for i=1:50;Z=tprod(X,[1 -1 3],[],[2 -1 3]);end;
fprintf('%30s %gs\n','tprod',toc/50); %=8.36/7.6
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:50;T=zeros(size(X,1),size(X,1),size(X,3));for k=1:size(X,3); T(:,:,k)=X(:,:,k)*X(:,:,k)';end;end,
fprintf('%30s %gs\n','MATLAB (loop)',toc/50); %=9.66/7.0
% N.B. --- aligned over dim 1 takes 2x longer!
fprintf([str ' Channel-covariance/trial(1) [1 -1 2] [1 -1 3]\n']);
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic;for i=1:10;Z=tprod(X,[1 -1 2],[],[1 -1 3]);end;
fprintf('%30s %gs\n','tprod',toc/10); %= /37.2
A=complex(randn(size(X)),randn(size(X))); % flush cache?
tic,for i=1:10;T=zeros(size(X,1),size(X,1),size(X,3));for k=1:size(X,3);T(k,:,:)=shiftdim(X(k,:,:))'*shiftdim(X(k,:,:));end;end,
fprintf('%30s %gs\n','MATLAB',toc/10); %=17.2/25.8
return;
function []=scalingTests(Ns);
% Scaling test
fprintf('Simple test of the effect of the acc size\n');
for N=Ns;
fprintf('X=[%d x %d]\n',N,N*N);X=randn(N,N*N);Y=randn(N*N,1);
fprintf('[1 -1][-1]\n');
tic, for i=1:1000;Z=tprod(X,[1 -1],Y,[-1],'n');end
fprintf('%30s %gs\n','tprod',toc/1000);% = .28 / .06
tic, for i=1:1000;Z=tprod(X,[1 -1],Y,[-1],'mn');end
fprintf('%30s %gs\n','tprod m',toc/1000);% = .28 / .06
end
fprintf('Simple mat vs non mat tests\n');
for N=Ns;
fprintf('N=%d\n',N);X=randn(N,N,N);Y=randn(N,N);
fprintf('[1 -1 -2][-1 -2]\n');
tic, for i=1:1000;Z=tprod(X,[1 -1 -2],Y,[-1 -2]);end
fprintf('%30s %gs\n','tprod',toc/1000);% = .28 / .06
tic, for i=1:1000;Z=tprod(X,[1 -1 -2],Y,[-1 -2],'m');end
fprintf('%30s %gs\n','tprod m',toc/1000);% = .28 / .06
fprintf('[-1 -2 1][-1 -2]\n');
tic, for i=1:1000;Z=tprod(X,[-1 -2 1],Y,[-1 -2]);end
fprintf('%30s %gs\n','tprod',toc/1000);% = .28 / .06
tic, for i=1:1000;Z=tprod(X,[-1 -2 1],Y,[-1 -2],'m');end
fprintf('%30s %gs\n','tprod m',toc/1000);% = .28 / .06
fprintf('[-1 2 3][-1 1]\n');
tic, for i=1:100;Z=tprod(X,[-1 2 3],Y,[-1 1]);end
fprintf('%30s %gs\n','tprod',toc/100);% = .28 / .06
tic, for i=1:100;Z=tprod(X,[-1 2 3],Y,[-1 1],'m');end
fprintf('%30s %gs\n','tprod m',toc/100);% = .28 / .06
end
function []=blkSzTests(blkSzs,Ns);
fprintf('Blksz optimisation tests\n');
%blkSzs=[64 48 40 32 24 16 0];
tptime=zeros(numel(blkSzs+2));
for N=Ns;%[128,256,512,1024,2048];
X=randn(N,N);Y=randn(size(X));
for i=1:5;
% use tprod without matlab
for b=1:numel(blkSzs); blkSz=blkSzs(b);
clear T;T=randn(1024,1024); % clear cache
tic,for j=1:3;tprod(X,[1 -1],Y,[-1 2],'mn',blkSz);end;
tptime(b)=tptime(b)+toc;
end;
% tprod with defaults & matlab if possible
clear T;T=randn(1024,1024); % clear cache
tic,for j=1:3;tprod(X,[1 -1],Y,[-1 2]);end;
tptime(numel(blkSzs)+1)=tptime(numel(blkSzs)+1)+toc;
% the pure matlab code
clear T;T=randn(1024,1024); % clear cache
tic,for j=1:3; Z=X*Y;end;
tptime(numel(blkSzs)+2)=tptime(numel(blkSzs)+2)+toc;
end;
for j=1:numel(blkSzs);
fprintf('blk=%d, N = %d -> %gs \n',blkSzs(j),N,tptime(j));
end
fprintf('tprod, N = %d -> %gs \n',N,tptime(numel(blkSzs)+1));
fprintf('MATLAB, N = %d -> %gs \n',N,tptime(numel(blkSzs)+2));
fprintf('\n');
end;
return;
% simple function to check the accuracy of a test and report the result
function [testRes,trueRes,diff]=unitTest(testStr,testRes,trueRes,tol)
global DEBUG;
if ( nargin < 4 )
if ( isa(trueRes,'double') ) tol=1e-11;
elseif ( isa(trueRes,'single') ) tol=1e-5;
elseif ( isa(trueRes,'integer') )
warning('Integer inputs!'); tol=1;
elseif ( isa(trueRes,'logical') ) tol=0;
end
end
diff=abs(testRes-trueRes)./max(1,abs(testRes+trueRes));
fprintf('%60s = %0.3g ',testStr,max(diff(:)));
if ( max(diff(:)) > tol )
if ( exist('mimage') )
mimage(squeeze(testRes),squeeze(trueRes),squeeze(diff))
end
fprintf(' **FAILED***\n');
if ( DEBUG>0 )
warning([testStr ': failed!']),
fprintf('Type return to continue\b');keyboard;
end;
else
fprintf('Passed \n');
end
|
github
|
kaltwang/2015doubly-master
|
etprod.m
|
.m
|
2015doubly-master/code/toolboxes/tprod/etprod.m
| 3,882 |
utf_8
|
2f529c6b86be54251a59ae7f9db81d98
|
function [C,Atp,Btp]=etprod(Cidx,A,Aidx,B,Bidx)
% tprod wrapper to make calls more similar to Einstein Summation Convention
%
% [C,Atp,Btp]=etprod(Cidx,A,Aidx,B,Bidx);
% Wrapper function for tprod to map between Einstein summation
% convetion (ESC) and tprod's numeric calling convention e.g.
% 1) Matrix Matrix product:
% ESC: C_ij = A_ik B_kj <=> C = etprod('ij',A,'ik',B,'kj');
% 2) Vector outer product
% ESC: C_ij = A_i B_j <=> C = etprod('ij',A,'i',B,'j'); % A,B col vec
% C = etprod('ij',A,' i',B,' j'); % A,B row vec
% N.B. use spaces ' ' to indicate empty/ignored *singlenton* dimensions
% 3) Matrix vector product
% ESC: C_i = A_ik B_k <=> C = etprod('i',A,'ik',B,'k');
% 4) Spatial Filtering
% ESC: FX_fte = A_cte B_cf <=> C = etprod('fte',A,'cte',B,'cf')
% OR:
% C = etprod({'feat','time','epoch'},A,{'ch','time','epoch'},B,{'ch','feat'})
%
% Inputs:
% Cidx -- the list of dimension labels for the output
% A -- [n-d] array of the A values
% Aidx -- [ndims(A) x 1] (array, string, or cell array of strings)
% list of dimension labels for A array
% B -- [m-d] array of the B values
% Bidx -- [ndims(B) x 1] (array, string or cell array of strings)
% list of dimension labels for B array
% Outputs:
% C -- [p-d] array of output values. Dimension labels are as in Cidx
% Atp -- [ndims(A) x 1] A's dimspec as used in the core tprod call
% Btp -- [ndims(B) x 1] B's dimspec as used in the core tprod call
%
% See Also: tprod, tprod_testcases
%
% Copyright 2006- by Jason D.R. Farquhar ([email protected])
% Permission is granted for anyone to copy, use, or modify this
% software and accompanying documents for any uncommercial
% purposes, provided this copyright notice is retained, and note is
% made of any changes that have been made. This software and
% documents are distributed without any warranty, express or
% implied
if ( iscell(Aidx)~=iscell(Bidx) || iscell(Cidx)~=iscell(Aidx) )
error('Aidx,Bidx and Cidx cannot be of different types, all cells or arrays');
end
Atp = zeros(size(Aidx));
Btp = zeros(size(Bidx));
% Map inner product dimensions, to unique *negative* index
for i=1:numel(Aidx)
if ( iscell(Aidx) ) Bmatch = strcmp(Aidx{i}, Bidx);
else Bmatch = (Aidx(i)==Bidx);
end
if ( any(Bmatch) ) Btp(Bmatch)=-i; Atp(i)=-i; end;
end
% Spaces/empty values in the input become 0's, i.e. ignored dimensions
if ( iscell(Aidx) )
Btp(strcmp(' ',Bidx))=0;Btp(strcmp('',Bidx))=0;
Atp(strcmp(' ',Aidx))=0;Atp(strcmp('',Aidx))=0;
else
Btp(' '==Bidx)=0;
Atp(' '==Aidx)=0;
end
% Map to output position numbers, to correct *positive* index
for i=1:numel(Cidx);
if ( iscell(Aidx) )
Atp(strcmp(Cidx{i}, Aidx))=i;
Btp(strcmp(Cidx{i}, Bidx))=i;
else
Atp(Cidx(i)==Aidx)=i;
Btp(Cidx(i)==Bidx)=i;
end
end
% now do the tprod call.
global LOG; if ( isempty(LOG) ) LOG=0; end; % N.B. set LOG to valid fd to log
if ( LOG>0 )
fprintf(LOG,'tprod(%s,[%s], %s,[%s])\n',mxPrint(A),sprintf('%d ',Atp),mxPrint(B),sprintf('%d ',Btp));
end
C=tprod(A,Atp,B,Btp,'n');
return;
function [str]=mxPrint(mx)
sz=size(mx);
if ( isa(mx,'double') ) str='d'; else str='s'; end;
if ( isreal(mx)) str=[str 'r']; else str=[str 'c']; end;
str=[str ' [' sprintf('%dx',sz(1:end-1)) sprintf('%d',sz(end)) '] '];
return;
%----------------------------------------------------------------------------
function testCase();
A=randn(10,10); B=randn(10,10);
C2 = tprod(A,[1 -2],B,[-2 2]);
C = etprod('ij',A,'ik',B,'kj'); mad(C2,C)
C = etprod({'i' 'j'},A,{'i' 'k'},B,{'k' 'j'});
A=randn(100,100);B=randn(100,100,4);
C3 = tprod(A,[-1 -2],B,[-1 -2 3]);
C3 = tprod(B,[-1 -2 1],A,[-1 -2]);
C3 = tprod(A,[-1 -2],B,[-1 -2 1]);
C = etprod('3',A,'12',B,'123');
C = etprod([3],A,[1 2],B,[1 2 3]);
C = etprod({'3'},A,{'1' '2'},B,{'1' '2' '3'})
|
github
|
bryanbeyer/Scour_3D-master
|
getForce.m
|
.m
|
Scour_3D-master/getForce.m
| 837 |
utf_8
|
90e0c595340dfef15a868406befa1162
|
% written by: Stu Blair
% date: Jan 16, 2012
% purpose: get force vector for all solid nodes in an LBM domain
function F = getForce(solidNodes,streamTgtMat,LatticeSpeeds,bb_spd,fIn)
% determine number of solid nodes
numSolidNodes=length(solidNodes);
%deterimne number of dimensions
[numDim,numSpd]=size(LatticeSpeeds);
F = zeros(numSolidNodes,numDim);
% get forceContribMat - map of force contributors for each solid node
forceContribMat = zeros(numSolidNodes,numSpd);
for spd = 2:numSpd % stationary speed never contributes
forceContribMat(:,spd)=~ismember(streamTgtMat(solidNodes,spd),solidNodes);
end
e_alpha = LatticeSpeeds';
for spd=2:numSpd
f1 = fIn(solidNodes,spd)+fIn(streamTgtMat(solidNodes,spd),bb_spd(spd));
f2 = (f1).*forceContribMat(:,spd);
f3 = kron(f2,e_alpha(bb_spd(spd),:));
F = F + f3;
end
|
github
|
bryanbeyer/Scour_3D-master
|
D2Q9_lattice_parameters.m
|
.m
|
Scour_3D-master/D2Q9_lattice_parameters.m
| 227 |
utf_8
|
bddb7b96f31f4a63bcc5296912d9fed3
|
%
function [w, ex, ey,bb_spd] = D2Q9_lattice_parameters()
w = [4/9, 1/9, 1/9, 1/9, 1/9, 1/36, 1/36, 1/36, 1/36];
ex = [0, 1, 0, -1, 0, 1, -1, -1, 1];
ey = [0, 0, 1, 0, -1, 1, 1, -1, -1];
bb_spd = [1, 4, 5, 2, 3, 8, 9, 6, 7];
|
github
|
bryanbeyer/Scour_3D-master
|
RecMesh.m
|
.m
|
Scour_3D-master/RecMesh.m
| 2,177 |
utf_8
|
89522f9e5af20eb01c2d3e8572b58e49
|
% function [GCOORD,NODES,BOUNDARIES]= RecMesh(x_left,x_right,y_bottom,y_top,Nx,Ny)
%
% Written by: Stu Blair
% Date: 2/9/2010
% Purpose: provide mesh definition data structures for a structured,
% uniform rectangular mesh to be used with ME 4612 final project
function [GCOORD,NODES,BOUNDARIES] = RecMesh(x_left,x_right,y_bottom,y_top,Nx,Ny)
x_space = linspace(x_left,x_right,Nx);
y_space = linspace(y_bottom,y_top,Ny);
[X,Y] = meshgrid(x_space,y_space);
nnodes = Nx*Ny;
nnel = 4; %constant for rectangular elements
nel = (Nx-1)*(Ny - 1);
GCOORD = zeros(nnodes,2);
NODES = zeros(nel,nnel);
% === form the GCOORD array ===============================================
index = 0;
for j = 1:Ny
for i = 1:Nx
index = index+1;
GCOORD(index,1) = X(j,i);
GCOORD(index,2) = Y(j,i);
end
end
% =========================================================================
% ====== Form the NODES array =============================================
for j = 1:(Ny - 1)
for i = 1:(Nx - 1)
ele_index = (j-1)*(Nx-1)+i;
node1 = (j-1)*Nx + i;
node2 = node1+1;
node3 = node2+Nx;
node4 = node3-1;
NODES(ele_index,1) = node1;
NODES(ele_index,2) = node2;
NODES(ele_index,3) = node3;
NODES(ele_index,4) = node4;
end
end
% =========================================================================
BOUNDARIES.bottom = 1:Nx; %left-to-right
BOUNDARIES.right = Nx:Nx:Nx*(Ny); %bottom-to-top
BOUNDARIES.top = Nx*Ny:-1:(Nx*(Ny-1)+1);%right-to-left
BOUNDARIES.left = (Nx*(Ny-1)+1):-Nx:1;%top-to-bottom
% this array of BOUNDARIES will have ALL of the nodes on the given
% boundary. This is important for carrying out the boundary integrals on
% each side. Somehow, in the application of these BCs, I will have to deal
% with the fact that some nodes are shared between boundaries. For this
% simple geometry, the first and last node on each boundary is shared.
% based on the logic of forming this array, the nodes are ordered such that
% the domain is encircled counter-clockwise starting at the bottom
% left-hand corner.
|
github
|
bryanbeyer/Scour_3D-master
|
SetInletMacroscopicBCPoiss.m
|
.m
|
Scour_3D-master/SetInletMacroscopicBCPoiss.m
| 526 |
utf_8
|
5d29f4bdb2ab505f5a90c5e46ef420ea
|
% appropriate for D2Q9 grids only
function [ux,uy,rho]=SetInletMacroscopicBCPoiss(ux,uy,rho,fIn,u_bc,b,...
gcoord,inlet_node_list)
% set macroscopic inlet boundary conditions
ux(inlet_node_list) = (u_bc)*(1-((gcoord(inlet_node_list,2)-b).^2)./(b*b));
uy(inlet_node_list) = 0;
rho(inlet_node_list) = 1./(1-ux(inlet_node_list)).*(...
fIn(inlet_node_list,1)+fIn(inlet_node_list,3)+fIn(inlet_node_list,5)...
+2*(fIn(inlet_node_list,4)+fIn(inlet_node_list,7)+...
fIn(inlet_node_list,8)));
|
github
|
google/gps-measurement-tools-master
|
Utc2Gps.m
|
.m
|
gps-measurement-tools-master/opensource/Utc2Gps.m
| 3,937 |
utf_8
|
0593bea672dfa8778026636946dd5424
|
function [gpsTime,fctSeconds] = Utc2Gps(utcTime)
% [gpsTime,fctSeconds] = Utc2Gps(utcTime)
% Convert the UTC date and time to GPS week & seconds
%
% Inputs:
% utcTime: [mx6] matrix
% utcTime(i,:) = [year,month,day,hours,minutes,seconds]
% year must be specified using four digits, e.g. 1994
% year valid range: 1980 <= year <= 2099
%
% Outputs:
% gpsTime: [mx2] matrix [gpsWeek, gpsSeconds],
% gpsWeek = number of weeks since GPS epoch
% gpsSeconds = number of seconds into gpsWeek,
% fctSeconds: full cycle time = seconds since GPS epoch (1980/01/06 00:00 UTC)
% Other functions needed: JulianDay.m, LeapSeconds.m
%initialize outputs
gpsTime=[];
fctSeconds=[];
[bOk]=CheckUtcTimeInputs(utcTime);
if ~bOk
return
end
HOURSEC = 3600; MINSEC = 60;
daysSinceEpoch = floor(JulianDay(utcTime) - GpsConstants.GPSEPOCHJD);
gpsWeek = fix(daysSinceEpoch/7);
dayofweek = rem(daysSinceEpoch,7);
% calculate the number of seconds since Sunday at midnight:
gpsSeconds = dayofweek*GpsConstants.DAYSEC + utcTime(:,4)*HOURSEC + ...
utcTime(:,5)*MINSEC + utcTime(:,6);
gpsWeek = gpsWeek + fix(gpsSeconds/GpsConstants.WEEKSEC);
gpsSeconds = rem(gpsSeconds,GpsConstants.WEEKSEC);
% now add leapseconds
leapSecs = LeapSeconds(utcTime);
fctSeconds = gpsWeek(:)*GpsConstants.WEEKSEC + gpsSeconds(:) + leapSecs(:);
% when a leap second happens, utc time stands still for one second,
% so gps seconds get further ahead, so we add leapsecs in going to gps time
gpsWeek = fix(fctSeconds/GpsConstants.WEEKSEC);
iZ = gpsWeek==0;
gpsSeconds(iZ) = fctSeconds(iZ); %set gpsSeconds directly, because rem(x,0)=NaN
gpsSeconds(~iZ) = rem(fctSeconds(~iZ),gpsWeek(~iZ)*GpsConstants.WEEKSEC);
gpsTime=[gpsWeek,gpsSeconds];
assert(all(fctSeconds==gpsWeek*GpsConstants.WEEKSEC+gpsSeconds),...
'Error in computing gpsWeek, gpsSeconds');
end %end of function Utc2Gps
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [bOk] = CheckUtcTimeInputs(utcTime)
%utility function for Utc2Gps
%check inputs
if size(utcTime,2)~=6
error('utcTime must have 6 columns')
end
%check that year, month & day are integers
x = utcTime(:,1:3);
if any(any( (x-fix(x)) ~= 0 ))
error('year,month & day must be integers')
end
%check that year is in valid range
if ( any(utcTime(:,1)<1980) || any(utcTime(:,1)>2099) )
error('year must have values in the range: [1980:2099]')
end
%check validity of month, day and time
if (any(utcTime(:,2))<1 || any(utcTime(:,2))>12 )
error('The month in utcTime must be a number in the set [1:12]')
end
if (any(utcTime(:,3)<1) || any(utcTime(:,3)>31))
error('The day in utcTime must be a number in the set [1:31]')
end
if (any(utcTime(:,4)<0) || any(utcTime(:,4)>=24))
error('The hour in utcTime must be in the range [0,24)')
end
if (any(utcTime(:,5)<0) || any(utcTime(:,5)>=60))
error('The minutes in utcTime must be in the range [0,60)')
end
if (any(utcTime(:,6)<0) || any(utcTime(:,6)>60))
%Note: seconds can equal 60 exactly, on the second a leap second is added
error('The seconds in utcTime must be in the range [0,60]')
end
bOk = true;
end %end of function CheckUtcTimeInputs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2016 Google Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
|
github
|
google/gps-measurement-tools-master
|
WlsPvt.m
|
.m
|
gps-measurement-tools-master/opensource/WlsPvt.m
| 6,430 |
utf_8
|
0ccc707de9a099046e5ba3aaaf56badd
|
function [xHat,z,svPos,H,Wpr,Wrr] = WlsPvt(prs,gpsEph,xo)
% [xHat,z,svPos,H,Wpr,Wrr] = WlsPvt(prs,gpsEph,xo)
% calculate a weighted least squares PVT solution, xHat
% given pseudoranges, pr rates, and initial state
%
% Inputs:
% prs: matrix of raw pseudoranges, and pr rates, each row of the form:
% [trxWeek,trxSeconds,sv,prMeters,prSigmaMeters,prrMps,prrSigmaMps]
% trxWeek, trxSeconds: Rx time of measurement
% where trxSeconds = seconds in the current GPS week
% sv: satellite id number
% prMeters, prSigmaMeters: pseudorange and standard deviation (meters)
% prrMps, prrSigmaMps: pseudorange rate and standard deviation (m/s)
% gpsEph: matching vector of GPS ephemeris struct, defined in ReadRinexNav
% xo: initial (previous) state, [x,y,z,bc,xDot,yDot,xDot,bcDot]'
% in ECEF coordinates(meters and m/s)
%
% Outputs: xHat: estimate of state update
% z = [zPr; zPrr] a-posteriori residuals (measured-calculated)
% svPos: matrix of calculated sv positions and sv clock error:
% [sv prn, x,y,z (ecef m), dtsv (s),xDot,yDot,zDot, dtsvDot]
% H: H observation matrix corresponding to svs in svPos(:,1)
% Wpr,Wrr Weights used in WlsPvt = 1/diag(sigma measurements)
% use these matrices to compute variances of xHat
%
% The PVT solution = xo + xHat, in ECEF coordinates
% For unweighted solution, set all sigmas = 1
%Author: Frank van Diggelen
%Open Source code for processing Android GNSS Measurements
jWk=1; jSec=2; jSv=3; jPr=4; jPrSig=5; jPrr=6; jPrrSig=7;%index of columns
[bOk,numVal] = checkInputs(prs, gpsEph, xo);
if ~bOk
error('inputs not right size, or not properly aligned with each other')
end
xHat=[]; z=[]; H=[]; svPos=[];
xyz0 = xo(1:3);
bc = xo(4);
if numVal<4
return
end
ttxWeek = prs(:,jWk); %week of tx. Note - we could get a rollover, when ttx_sv
%goes negative, and it is handled in GpsEph2Pvt, where we work with fct
ttxSeconds = prs(:,jSec) - prs(:,jPr)/GpsConstants.LIGHTSPEED; %ttx by sv clock
% this is accurate satellite time of tx, because we use actual pseudo-ranges
% here, not corrected ranges
% write the equation for pseudorange to see the rx clock error exactly cancel
% to get precise GPS time: we subtract the satellite clock error from sv time,
% as done next:
dtsv = GpsEph2Dtsv(gpsEph,ttxSeconds);
dtsv = dtsv(:); %make into a column for compatibility with other time vectors
ttx = ttxSeconds - dtsv; %subtract dtsv from sv time to get true gps time
%calculate satellite position at ttx
[svXyzTtx,dtsv,svXyzDot,dtsvDot]=GpsEph2Pvt(gpsEph,[ttxWeek,ttx]);
svXyzTrx = svXyzTtx; %initialize svXyz at time of reception
%Compute weights ---------------------------------------------------
Wpr = diag(1./prs(:,jPrSig));
Wrr = diag(1./prs(:,jPrrSig));
%iterate on this next part tilL change in pos & line of sight vectors converge
xHat=zeros(4,1);
dx=xHat+inf;
whileCount=0; maxWhileCount=100;
%we expect the while loop to converge in < 10 iterations, even with initial
%position on other side of the Earth (see Stanford course AA272C "Intro to GPS")
while norm(dx) > GnssThresholds.MAXDELPOSFORNAVM
whileCount=whileCount+1;
assert(whileCount < maxWhileCount,...
'while loop did not converge after %d iterations',whileCount);
for i=1:length(gpsEph)
% calculate tflight from, bc and dtsv
dtflight = (prs(i,jPr)-bc)/GpsConstants.LIGHTSPEED + dtsv(i);
% Use of bc: bc>0 <=> pr too big <=> tflight too big.
% i.e. trx = trxu - bc/GpsConstants.LIGHTSPEED
% Use of dtsv: dtsv>0 <=> pr too small <=> tflight too small.
% i.e ttx = ttxsv - dtsv
svXyzTrx(i,:) = FlightTimeCorrection(svXyzTtx(i,:), dtflight);
end
%calculate line of sight vectors and ranges from satellite to xo
v = xyz0(:)*ones(1,numVal,1) - svXyzTrx';%v(:,i) = vector from sv(i) to xyz0
range = sqrt( sum(v.^2) );
v = v./(ones(3,1)*range); % line of sight unit vectors from sv to xo
svPos=[prs(:,3),svXyzTrx,dtsv(:)];
%calculate the a-priori range residual
prHat = range(:) + bc -GpsConstants.LIGHTSPEED*dtsv;
% Use of bc: bc>0 <=> pr too big <=> rangehat too big
% Use of dtsv: dtsv>0 <=> pr too small
zPr = prs(:,jPr)-prHat;
H = [v', ones(numVal,1)]; % H matrix = [unit vector,1]
%z = Hx, premultiply by W: Wz = WHx, and solve for x:
dx = pinv(Wpr*H)*Wpr*zPr;
% update xo, xhat and bc
xHat=xHat+dx;
xyz0=xyz0(:)+dx(1:3);
bc=bc+dx(4);
%Now calculate the a-posteriori range residual
zPr = zPr-H*dx;
end
% Compute velocities ---------------------------------------------------------
rrMps = zeros(numVal,1);
for i=1:numVal
%range rate = [satellite velocity] dot product [los from xo to sv]
rrMps(i) = -svXyzDot(i,:)*v(:,i);
end
prrHat = rrMps + xo(8) - GpsConstants.LIGHTSPEED*dtsvDot;
zPrr = prs(:,jPrr)-prrHat;
%z = Hx, premultiply by W: Wz = WHx, and solve for x:
vHat = pinv(Wrr*H)*Wrr*zPrr;
xHat = [xHat;vHat];
z = [zPr;zPrr];
end %end of function WlsPvt
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [bOk,numVal] = checkInputs(prs, gpsEph, xo)
%utility function for WlsPvt
jWk=1; jSec=2; jSv=3; jPr=4; jPrSig=5; jPrr=6; jPrrSig=7;%index of columns
bOk=false;
%check inputs
numVal=size(prs,1);
if (max(prs(:,jSec))-min(prs(:,jSec)))> eps
return
elseif length(gpsEph)~=numVal
return
elseif any(prs(:,jSv) ~= [gpsEph.PRN]')
return
elseif any(size(xo) ~= [8,1])
return
elseif size(prs,2)~=7
return
else
bOk = true;
end
%We insist that gpsEph and prs are aligned first.
%ClosestGpsEph.m does this, and passes back indices for prs - this is the way to
%do it right, so we don't have nested searches for svId
end %end of function checkInputs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2016 Google Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
|
github
|
google/gps-measurement-tools-master
|
Gps2Utc.m
|
.m
|
gps-measurement-tools-master/opensource/Gps2Utc.m
| 5,737 |
utf_8
|
32fa6bc33bc0de2d2058510f5773395b
|
function [utcTime] = Gps2Utc(gpsTime,fctSeconds)
% [utcTime] = Gps2Utc(gpsTime,[fctSeconds])
% Convert GPS time (week & seconds), or Full Cycle Time (seconds) to UTC
%
% Input: gpsTime, [mx2] matrix [gpsWeek, gpsSeconds],
% fctSeconds, [optional] Full Cycle Time (seconds)
%
% Outputs: utcTime, [mx6] matrix = [year,month,day,hours,minutes,seconds]
%
% If fctSeconds is provided, gpsTime is ignored
%
% Valid range of inputs:
% gps times corresponding to 1980/6/1 <= time < 2100/1/1
% i.e. [0,0] <= gpsTime < [6260, 432000]
% 0 <= fctSeconds < 3786480000
%
% See also: Utc2Gps
% Other functions needed: LeapSeconds.m
%Author: Frank van Diggelen
%Open Source code for processing Android GNSS Measurements
%Algorithm for handling leap seconds:
% When a leap second happens, utc time stands still for one second, so
% gps seconds get further ahead, so we subtract leapSecs to move from gps time
%
% 1) convert gpsTime to time = [yyyy,mm,dd,hh,mm,ss] (with no leap seconds)
% 2) look up leap seconds for time: ls = LeapSeconds(time);
% This is (usually) the correct leap second value. Unless:
% If (utcTime=time) and (utcTime=time+ls) straddle a leap second
% then we need to add 1 to ls
% So, after step 2) ...
% 3) convert gpsTime-ls to timeMLs
% 4) look up leap seconds: ls1 = LeapSeconds(timeMLs);
% 5) if ls1~=ls, convert (gpsTime-ls1) to UTC Time
%% Check inputs
if nargin<2 && size(gpsTime,2)~=2
error('gpsTime must have two columns')
end
if nargin<2
fctSeconds = gpsTime*[GpsConstants.WEEKSEC; 1];
end
%fct at 2100/1/1 00:00:00, not counting leap seconds:
fct2100 = [6260, 432000]*[GpsConstants.WEEKSEC; 1];
if any(fctSeconds<0) || any (fctSeconds >= fct2100)
error('gpsTime must be in this range: [0,0] <= gpsTime < [6260, 432000]');
end
%% Finished checks
%from now on work with fct
%% Apply algorithm for handling leaps seconds
% 1) convert gpsTime to time = [yyyy,mm,dd,hh,mm,ss] (with no leap seconds)
time = Fct2Ymdhms(fctSeconds);
% 2) look up leap seconds for time: ls = LeapSeconds(time);
ls = LeapSeconds(time);
% 3) convert gpsTime-ls to timeMLs
timeMLs = Fct2Ymdhms(fctSeconds-ls);
% 4) look up leap seconds: ls1 = LeapSeconds(timeMLs);
ls1 = LeapSeconds(timeMLs);
% 5) if ls1~=ls, convert (gpsTime-ls1) to UTC Time
if all(ls1==ls)
utcTime = timeMLs;
else
utcTime = Fct2Ymdhms(fctSeconds-ls1);
end
% NOTE:
% Gps2Utc.m doesn't produce 23:59:60, at a leap second.
% Instead, as the leap second occurs, the Gps2Utc.m sequence of
% UTC hh:mm:ss is 23:59:59, 00:00:00, 00:00:00
% and we keep it like that for code simplicity.
% Here are a sequence of UTC and GPS times around a leap second:
% formalUtcTimes = [1981 12 31 23 59 59; 1981 12 31 23 59 60; 1982 1 1 0 0 0];
% gpsTimes = [103 431999; 103 432000; 103 432001];
% >> Gps2Utc(gpsTimes)
% ans =
% 1981 12 31 23 59 59
% 1982 1 1 0 0 0
% 1982 1 1 0 0 0
% If you want to change this you could check LeapSeconds.m to see if you're
% exactly on the addition of a leap second, and then change the UTC format
% to include the '60' seconds
end %end of function Gps2Utc
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function time = Fct2Ymdhms(fctSeconds)
%Utility function for Gps2Utc
%Convert GPS full cycle time to [yyyy,mm,dd,hh,mm,ss.s] format
HOURSEC = 3600; MINSEC = 60;
monthDays=[31,28,31,30,31,30,31,31,30,31,30,31];%days each month (not leap year)
m=length(fctSeconds);
days = floor(fctSeconds / GpsConstants.DAYSEC) + 6;%days since 1980/1/1
years=zeros(m,1)+1980;
%decrement days by a year at a time, until we have calculated the year:
leap=ones(m,1); %1980 was a leap year
while (any(days > (leap+365)))
I = find(days > (leap+365) );
days(I) = days(I) - (leap(I) + 365);
years(I)=years(I)+1;
leap(I) = (rem(years(I),4) == 0); % leap = 1 on a leap year, 0 otherwise
% This works from 1901 till 2099, 2100 isn't a leap year (2000 is).
% Calculate the year, ie time(1)
end,
time=zeros(m,6);%initialize matrix
time(:,1)=years;
%decrement days by a month at a time, until we have calculated the month
% Calculate the month, ie time(:,2)
% Loop through m:
for i=1:m
month = 1;
if (rem(years(i),4) == 0) %This works from 1901 till 2099
monthDays(2)=29; %Make February have 29 days in a leap year
else
monthDays(2)=28;
end
while (days(i) > monthDays(month))
days(i) = days(i)-monthDays(month);
month = month+1;
end
time(i,2)=month;
end
time(:,3) = days;
sinceMidnightSeconds = rem(fctSeconds, GpsConstants.DAYSEC);
time(:,4) = fix(sinceMidnightSeconds/HOURSEC);
lastHourSeconds = rem(sinceMidnightSeconds, HOURSEC);
time(:,5) = fix(lastHourSeconds/MINSEC);
time(:,6) = rem(lastHourSeconds,MINSEC);
end %end of function Fct2Ymdhms
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2016 Google Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
|
github
|
google/gps-measurement-tools-master
|
ReadGnssLogger.m
|
.m
|
gps-measurement-tools-master/opensource/ReadGnssLogger.m
| 16,712 |
utf_8
|
20ec3397745d7b547f780418f11c351c
|
function [gnssRaw,gnssAnalysis] = ReadGnssLogger(dirName,fileName,dataFilter,gnssAnalysis)
%% [gnssRaw,gnssAnalysis]=ReadGnssLogger(dirName,fileName,[dataFilter],[gnssAnalysis]);
% Read the log file created by Gnss Logger App in Android
% Compatible with Android release N
%
% Input:
% dirName = string with directory of fileName,
% e.g. '~/Documents/MATLAB/Pseudoranges/2016-03-28'
% fileName = string with filename
% optional inputs:
% [dataFilter], nx2 cell array of pairs of strings,
% dataFilter{i,1} is a string with one of 'Raw' header values from the
% GnssLogger log file e.g. 'ConstellationType'
% dataFilter{i,2} is a string with a valid matlab expression, containing
% the header value, e.g. 'ConstellationType==1'
% See SetDataFilter.m for full rules and examples of dataFilter.
% [gnssAnalysis] structure containing analysis, incl list of missing fields
%
% Output:
% gnssRaw, all GnssClock and GnssMeasurement fields from log file, including:
% .TimeNanos (int64)
% .FullBiasNanos (int64)
% ...
% .Svid
% .ReceivedSvTimeNanos (int64)
% .PseudorangeRateMetersPerSecond
% ...
% and data fields created by this function:
% .allRxMillis (int64), full cycle time of measurement (milliseconds)
% accurate to one millisecond, it is convenient for matching up time
% tags. For computing accurate location, etc, you must still use
% TimeNanos and gnssMeas.tRxSeconds
%
% gnssAnalysis, structure containing analysis, including list of missing fields
%
% see also: SetDataFilter, ProcessGnssMeas
%Author: Frank van Diggelen
%Open Source code for processing Android GNSS Measurements
%factored into a few main sub-functions:
% MakeCsv()
% ReadRawCsv()
% FilterData()
% PackGnssRaw()
% CheckGnssClock()
% ReportMissingFields()
%% Initialize outputs and inputs
gnssRaw = [];
gnssAnalysis.GnssClockErrors = 'GnssClock Errors.';
gnssAnalysis.GnssMeasurementErrors = 'GnssMeasurement Errors.';
gnssAnalysis.ApiPassFail = '';
if nargin<3, dataFilter = []; end
%% check we have the right kind of fileName
extension = fileName(end-3:end);
if ~any(strcmp(extension,{'.txt','.csv'}))
error('Expecting file name of the form "*.txt", or "*.csv"');
end
%% read log file into a numeric matrix 'S', and a cell array 'header'
rawCsvFile = MakeCsv(dirName,fileName);
[header,C] = ReadRawCsv(rawCsvFile);
%% apply dataFilter
[bOk] = CheckDataFilter(dataFilter,header);
if ~bOk, return, end
[bOk,C] = FilterData(C,dataFilter,header);
if ~bOk, return, end
%% pack data into gnssRaw structure
[gnssRaw,missing] = PackGnssRaw(C,header);
%% check clock and measurements
[gnssRaw,gnssAnalysis] = CheckGnssClock(gnssRaw,gnssAnalysis);
gnssAnalysis = ReportMissingFields(gnssAnalysis,missing);
end %end of function ReadGnssLogger
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function csvFileName = MakeCsv(dirName,fileName)
%% make csv file, if necessary.
%And return extended csv file name (i.e. with full path in the name)
%TBD, maybe, do this entirely with Matlab read/write functions, make independent
%from grep and sed
%make extended file name
if dirName(end)~='/'
dirName = [dirName,'/']; %add /
end
csvFileName = [dirName,'raw.csv'];
if strcmp(fileName(end-3:end),'.csv')
return %input file is a csv file, nothing more to do here
end
extendedFileName = [dirName,fileName];
fprintf('\nReading file %s\n',extendedFileName)
%% read version
txtfileID = fopen(extendedFileName,'r');
if txtfileID<0
error('file ''%s'' not found',extendedFileName);
end
line='';
while isempty(strfind(lower(line),'version'))
line = fgetl(txtfileID);
if ~ischar(line) %eof or error occurred
if isempty(line)
error('\nError occurred while reading file %s\n',fileName)
end
break
end
end
if line==-1
fprintf('\nCould not find "Version" in input file %s\n',fileName)
return
end
%look for the beginning of the version number, e.g. 1.4.0.0
iDigits = regexp(line,'\d'); %index into the first number found in line
v = sscanf(line(iDigits(1):end),'%d.%d.%d.%d',4);
if length(v)<4
v(end+1:4,1)=0; %make v into a length 4 column vector
end
%Now extract the platform
k = strfind(line,'Platform:');
if any(k)
sPlatform = line(k+9:end);
else
sPlatform = '';%set empty if 'Platform:' not found
end
if isempty(strfind(sPlatform,'N'))
%add || strfind(platform,'O') and so on for future platforms
fprintf('\nThis version of ReadGnssLogger supports Android N\n')
fprintf('WARNING: did not find "Platform" type in log file, expected "Platform: N"\n')
fprintf('Please Update GnssLogger\n')
sPlatform = 'N';%assume version N
end
v1 = [1;4;0;0];
sCompare = CompareVersions(v,v1);
%Note, we need to check both the logger version (e.g. v1.0.0.0) and the
%Platform version "e.g. Platform: N" for any logic based on version
if strcmp(sCompare,'before')
fprintf('\nThis version of ReadGnssLogger supports v1.4.0.0 onwards\n')
error('Found "%s" in log file',line)
end
%% write csv file with header and numbers
%We could use grep and sed to make a csv file
%fclose(txtfileID);
% system(['grep -e ''Raw,'' ',extendedFileName,...
% ' | sed -e ''s/true/1/'' -e ''s/false/0/'' -e ''s/# //'' ',...
% ' -e ''s/Raw,//'' ',... %replace "Raw," with nothing
% '-e ''s/(//g'' -e ''s/)//g'' > ',csvFileName]);
%
% On versions from v1.4.0.0 N:
% grep on "Raw," replace alpha characters amongst the numbers,
% remove parentheses in the header,
% note use of /g for "global" so sed acts on every occurrence in each line
% csv file "prs.csv" now contains a header row followed by numerical data
%
%But we'll do the same thing using Matlab, so people don't need grep/sed:
csvfileID = fopen(csvFileName,'w');
while ischar(line)
line = fgetl(txtfileID);
if line == -1
break
endif
if isempty(strfind(line,'Raw,'))
continue %skip to next line
end
%Now 'line' contains the raw measurements header or data
line = strrep(line,'Raw,','');
line = strrep(line,'#',''); line = strrep(line,' ','');%remove '#' and spaces
%from versions v1.4.0.0 N we actually dont need to look for '(',')','true'
%or 'false' anymore. So we are done with replacing. That was easy.
fprintf(csvfileID,'%s\n',line);
end
fclose(txtfileID);
fclose(csvfileID);
if isempty(line) %line should be -1 at eof
error('\nError occurred while reading file %s\n',fileName)
end
end %end of function MakeCsv
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [header,C] = ReadRawCsv(rawCsvFile)
%% read data from csv file into a numerical matrix 'S' and cell array 'header'
%Note csvread fills ,, with zero, so we will need a lower level read function to
%tell the difference between empty fields and valid zeros
%T = readtable(csvFileName,'FileType','text'); %use this to debug
%read header row:
fid = fopen(rawCsvFile);
if fid<0
error('file ''%s'' not found',rawCsvFile);
end
headerString = fgetl(fid);
if isempty(strfind(headerString,'TimeNanos'))
error('\n"TimeNanos" string not found in file %s\n',fileName)
end
header=textscan(headerString,'%s','Delimiter',',');
header = header{1}; %this makes header a numFieldsx1 cell array
numFields = size(header,1);
%read lines using formatSpec so we get TimeNanos and FullBiasNanos as
%int64, everything else as doubles, and empty values as NaN
formatSpec='';
for i=1:numFields
%lotsa || here, because we are comparing a vector, 'header'
%to a specific string each time. Not sure how to do this another way
%and still be able to easily read and debug. Better safe than too clever.
%longs
if any(i == find(strcmp(header,'CodeType')))
formatSpec = strcat(formatSpec, ' %s');
elseif i == find(strcmp(header,'TimeNanos')) || ...
i == find(strcmp(header,'FullBiasNanos')) || ...
i == find(strcmp(header,'ReceivedSvTimeNanos')) || ...
i == find(strcmp(header,'ReceivedSvTimeUncertaintyNanos')) || ...
i == find(strcmp(header,'CarrierCycles'))
formatSpec = sprintf('%s %%d64',formatSpec);
elseif 0
%ints
% TBD maybe %d32 for ints: AccumulatedDeltaRangeState, ...
% ConstellationType, MultipathIndicator, State, Svid
formatSpec = sprintf('%s %%d32',formatSpec);
else
%everything else doubles
formatSpec = sprintf('%s %%f',formatSpec);
end
end
%Replace empty string fields with 'NaN'
C = textscan(fid,formatSpec,'Delimiter',',','EmptyValue',NaN);
%Replace CodeType string fields with 'NaN'
codeTypeHeaderIndex = find(strcmp(header,'CodeType'));
numberOfLogs = size(C{1},1);
C(codeTypeHeaderIndex) = {nan(numberOfLogs, 1)};
fclose(fid);
end% of function ReadRawCsv
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [bOk,C] = FilterData(C,dataFilter,header)
%% filter C based on contents of dataFilter
bOk = true;
iS = ones(size(C{1})); %initialize index into rows of C
for i=1:size(dataFilter,1)
j=find(strcmp(header,dataFilter{i,1}));%j = index into header
%we should always be a value of j, because checkDataFilter checks for this:
assert(any(j),'dataFilter{i} = %s not found in header\n',dataFilter{i,1})
%now we must evaluate the expression in dataFilter{i,2}, for example:
% 'BiasUncertaintyNanos < 1e7'
%assign the relevant cell of C to a variable with same name as the header
ts = sprintf('%s = C{%d};',header{j},j);
eval(ts);
%create an index vector from the expression in dataFilter{i,2}
ts = sprintf('iSi = %s;',dataFilter{i,2});
eval(ts);
%AND the iS index values on each iteration of i
iS = iS & iSi;
end
% Check if filter removes all values
if ~any(iS) %if all zeros
fprintf('\nAll measurements removed. Specify dataFilter less strictly than this:, ')
dataFilter(:,2)
bOk=false;
C=[];
return
end
% Keep only those values of C indexed by iS
for i=1:length(C)
C{i} = C{i}(iS);
end
end %end of function FilterDataS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [gnssRaw,missing] = PackGnssRaw(C,header)
%% pack data into gnssRaw, and report missing fields
assert(length(C)==length(header),...
'length(C) ~= length(header). This should have been checked before here')
gnssRaw = [];
%report clock fields present/missing, based on:
gnssClockFields = {...
'TimeNanos'
'TimeUncertaintyNanos'
'LeapSecond'
'FullBiasNanos'
'BiasUncertaintyNanos'
'DriftNanosPerSecond'
'DriftUncertaintyNanosPerSecond'
'HardwareClockDiscontinuityCount'
'BiasNanos'
};
missing.ClockFields = {};
%report measurements fields present/missing, based on:
gnssMeasurementFields = {...
'Cn0DbHz'
'ConstellationType'
'MultipathIndicator'
'PseudorangeRateMetersPerSecond'
'PseudorangeRateUncertaintyMetersPerSecond'
'ReceivedSvTimeNanos'
'ReceivedSvTimeUncertaintyNanos'
'State'
'Svid'
'AccumulatedDeltaRangeMeters'
'AccumulatedDeltaRangeUncertaintyMeters'
};
%leave these out for now, 'cause we dont care (for now), or they're deprecated,
% or they could legitimately be left out (because they are not computed in
% a particular GNSS implementation)
% SnrInDb, TimeOffsetNanos, CarrierFrequencyHz, CarrierCycles, CarrierPhase,
% CarrierPhaseUncertainty
missing.MeasurementFields = {};
%pack data into vector variables, if the fields are not NaNs
for j = 1:length(header)
if any(isfinite(C{j})) %not all NaNs
%TBD what if there are some NaNs, but not all. i.e. some missing
%data in the log file - TBD deal with this
eval(['gnssRaw.',header{j}, '=C{j};']);
elseif any(strcmp(header{j},gnssClockFields))
missing.ClockFields{end+1} = header{j};
elseif any(strcmp(header{j},gnssMeasurementFields))
missing.MeasurementFields{end+1} = header{j};
end
end
%So, if a field is not reported, it will be all NaNs from makeCsv, and the above
%code will not load it into gnssRaw. So when we call 'CheckGnssClock' it can
%check for missing fields in gnssRaw.
%TBD look for all zeros that can not legitimately be all zero,
%e.g. AccumulatedDeltaRangeMeters, and report these as missing data
end %end of function PackGnssRaw
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [gnssRaw,gnssAnalysis,bOk] = CheckGnssClock(gnssRaw,gnssAnalysis)
%% check clock values in gnssRaw
bOk = true;
sFail = ''; %initialize string to record failure messafes
N = length(gnssRaw.ReceivedSvTimeNanos);
%Insist on the presence of TimeNanos (time from hw clock)
if ~isfield(gnssRaw,'TimeNanos')
s = ' TimeNanos missing from GnssLogger File.';
fprintf('WARNING: %s\n',s);
sFail = [sFail,s];
bOk = false;
end
if ~isfield(gnssRaw,'FullBiasNanos')
s = 'FullBiasNanos missing from GnssLogger file.';
fprintf('WARNING: %s, we need it to get the week number\n',s);
sFail = [sFail,s];
bOk = false;
end
if ~isfield(gnssRaw,'BiasNanos')
gnssRaw.BiasNanos = zeros(N,1);
end
if ~isfield(gnssRaw,'HardwareClockDiscontinuityCount')
%possibly non fatal error, we assume there is no hardware clock discontinuity
%so we set to zero and move on, but we print a warning
gnssRaw.HardwareClockDiscontinuityCount = zeros(N,1);
fprintf('WARNING: Added HardwareClockDiscontinuityCount=0 because it is missing from GNSS Logger file\n');
end
%check FullBiasNanos, it should be negative values
bChangeSign = any(gnssRaw.FullBiasNanos<0) & any(gnssRaw.FullBiasNanos>0);
assert(~bChangeSign,...
'FullBiasNanos changes sign within log file, this should never happen');
%Now we know FullBiasNanos doesnt change sign,auto-detect sign of FullBiasNanos,
%if it is positive, give warning and change
if any(gnssRaw.FullBiasNanos>0)
gnssRaw.FullBiasNanos = -1*gnssRaw.FullBiasNanos;
fprintf('WARNING: FullBiasNanos wrong sign. Should be negative. Auto changing inside ReadGpsLogger\n');
gnssAnalysis.GnssClockErrors = [gnssAnalysis.GnssClockErrors,...
sprintf(' FullBiasNanos wrong sign.')];
end
%compute full cycle time of measurement, in milliseonds
gnssRaw.allRxMillis = int64((gnssRaw.TimeNanos - gnssRaw.FullBiasNanos)*1e-6);
%allRxMillis is now accurate to one millisecond (because it's an integer)
if ~bOk
gnssAnalysis.ApiPassFail = ['FAIL ',sFail];
end
end %end of function CheckGnssClock
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function gnssAnalysis = ReportMissingFields(gnssAnalysis,missing)
%% report missing clock and measurement fields in gnssAnalysis
%report missing clock fields
if ~isempty(missing.ClockFields)
gnssAnalysis.GnssClockErrors = sprintf(...
'%s Missing Fields:',gnssAnalysis.GnssClockErrors);
for i=1:length(missing.ClockFields)
gnssAnalysis.GnssClockErrors = sprintf(...
'%s %s,',gnssAnalysis.GnssClockErrors,missing.ClockFields{i});
end
gnssAnalysis.GnssClockErrors(end) = '.';%replace final comma with period
end
%report missing measurement fields
if ~isempty(missing.MeasurementFields)
gnssAnalysis.GnssMeasurementErrors = sprintf(...
'%s Missing Fields:',gnssAnalysis.GnssMeasurementErrors);
for i=1:length(missing.MeasurementFields)
gnssAnalysis.GnssMeasurementErrors = sprintf(...
'%s %s,',gnssAnalysis.GnssMeasurementErrors,...
missing.MeasurementFields{i});
end
gnssAnalysis.GnssMeasurementErrors(end) = '.';%replace last comma with period
end
%assign pass/fail
if ~any(strfind(gnssAnalysis.ApiPassFail,'FAIL')) %didn't already fail
if isempty(missing.ClockFields) && isempty(missing.MeasurementFields)
gnssAnalysis.ApiPassFail = 'PASS';
else
gnssAnalysis.ApiPassFail = 'FAIL BECAUSE OF MISSING FIELDS';
end
end
end %end of function ReportMissingFields
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2016 Google Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
|
github
|
google/gps-measurement-tools-master
|
ReadRinexNav.m
|
.m
|
gps-measurement-tools-master/opensource/ReadRinexNav.m
| 9,684 |
utf_8
|
61ac6db7bc356768f15c9f03a38f590c
|
function [gpsEph,iono] = ReadRinexNav(fileName)
% [gpsEph,iono] = ReadRinexNav(fileName)
%
% Read GPS ephemeris and iono data from an ASCII formatted RINEX 2.10 Nav file.
% Input:
% fileName - string containing name of RINEX formatted navigation data file
% Output:
% gpsEph: vector of ephemeris data, each element is an ephemeris structure
% structure order and orbit variable names follow RINEX 2.1 Table A4
% clock variable names af0, af1, af2 follow IS GPS 200
% gpsEph(i).PRN % SV PRN number
% gpsEph(i).Toc % Time of clock (seconds)
% gpsEph(i).af0 % SV clock bias (seconds)
% gpsEph(i).af1 % SV clock drift (sec/sec)
% gpsEph(i).af2 % SV clock drift rate (sec/sec2)
% gpsEph(i).IODE % Issue of data, ephemeris
% gpsEph(i).Crs % Sine harmonic correction to orbit radius (meters)
% gpsEph(i).Delta_n % Mean motion difference from computed value (radians/sec)
% gpsEph(i).M0 % Mean anomaly at reference time (radians)
% gpsEph(i).Cuc % Cosine harmonic correction to argument of lat (radians)
% gpsEph(i).e % Eccentricity (dimensionless)
% gpsEph(i).Cus % Sine harmonic correction to argument of latitude (radians)
% gpsEph(i).Asqrt % Square root of semi-major axis (meters^1/2)
% gpsEph(i).Toe % Reference time of ephemeris (seconds)
% gpsEph(i).Cic % Cosine harmonic correction to angle of inclination (radians)
% gpsEph(i).OMEGA % Longitude of ascending node at weekly epoch (radians)
% gpsEph(i).Cis % Sine harmonic correction to angle of inclination (radians)
% gpsEph(i).i0 % Inclination angle at reference time (radians)
% gpsEph(i).Crc % Cosine harmonic correction to the orbit radius (meters)
% gpsEph(i).omega % Argument of perigee (radians)
% gpsEph(i).OMEGA_DOT% Rate of right ascension (radians/sec)
% gpsEph(i).IDOT % Rate of inclination angle (radians/sec)
% gpsEph(i).codeL2 % codes on L2 channel
% gpsEph(i).GPS_Week % GPS week (to go with Toe), (NOT Mod 1024)
% gpsEph(i).L2Pdata % L2 P data flag
% gpsEph(i).accuracy % SV user range accuracy (meters)
% gpsEph(i).health % Satellite health
% gpsEph(i).TGD % Group delay (seconds)
% gpsEph(i).IODC % Issue of Data, Clock
% gpsEph(i).ttx % Transmission time of message (seconds)
% gpsEph(i).Fit_interval %fit interval (hours), zero if not known
%
% iono: ionospheric parameter structure
% iono.alpha = [alpha0, alpha1, alpha2, alpha3]
% iono.beta = [ beta0, beta1, beta2, beta3]
% if iono data is not present in the Rinex file, iono is returned empty.
fidEph = fopen(fileName);
[numEph,numHdrLines] = countEph(fidEph);
%Now read from the begining again, looking for iono parameters
frewind(fidEph);
iono = readIono(fidEph,numHdrLines);
%initialize ephemeris structure array:
gpsEph = InitializeGpsEph;
gpsEph = repmat(gpsEph,1,numEph);
%now read each ephemeris into gpsEph(j)
%RINEX defines the format in terms of numbers of characters, so that's how we
%read it, e.g. "gpsEph(j).PRN = str2num(line(1:2));" and so on
for j = 1:numEph
line = fgetl(fidEph);
gpsEph(j).PRN = str2num(line(1:2));
%NOTE: we use str2num, not str2double, since str2num handles 'D' for exponent
%% get Toc (Rinex gives this as UTC time yy,mm,dd,hh,mm,ss)
year = str2num(line(3:6));
%convert year to a 4-digit year, this code is good to the year 2080.
%From 2080 RINEX 2.1 is ambiguous and shouldnt be used, because is has a
%2-digit year, and 100 years will have passed since the GPS Epoch.
if year < 80,
year = 2000+year;
else
year = 1900+year;
end
month = str2num(line(7:9));
day = str2num(line(10:12));
hour = str2num(line(13:15));
minute = str2num(line(16:18));
second = str2num(line(19:22));
%convert Toc to gpsTime
gpsTime = Utc2Gps([year,month,day,hour,minute,second]);
gpsEph(j).Toc = gpsTime(2);
%% get all other parameters
gpsEph(j).af0 = str2num(line(23:41));
gpsEph(j).af1 = str2num(line(42:60));
gpsEph(j).af2 = str2num(line(61:79));
line = fgetl(fidEph);
gpsEph(j).IODE = str2num(line(4:22));
gpsEph(j).Crs = str2num(line(23:41));
gpsEph(j).Delta_n = str2num(line(42:60));
gpsEph(j).M0 = str2num(line(61:79));
line = fgetl(fidEph);
gpsEph(j).Cuc = str2num(line(4:22));
gpsEph(j).e = str2num(line(23:41));
gpsEph(j).Cus = str2num(line(42:60));
gpsEph(j).Asqrt = str2num(line(61:79));
line=fgetl(fidEph);
gpsEph(j).Toe = str2num(line(4:22));
gpsEph(j).Cic = str2num(line(23:41));
gpsEph(j).OMEGA = str2num(line(42:60));
gpsEph(j).Cis = str2num(line(61:79));
line = fgetl(fidEph);
gpsEph(j).i0 = str2num(line(4:22));
gpsEph(j).Crc = str2num(line(23:41));
gpsEph(j).omega = str2num(line(42:60));
gpsEph(j).OMEGA_DOT = str2num(line(61:79));
line = fgetl(fidEph);
gpsEph(j).IDOT = str2num(line(4:22));
gpsEph(j).codeL2 = str2num(line(23:41));
gpsEph(j).GPS_Week = str2num(line(42:60));
gpsEph(j).L2Pdata = str2num(line(61:79));
line = fgetl(fidEph);
gpsEph(j).accuracy = str2num(line(4:22));
gpsEph(j).health = str2num(line(23:41));
gpsEph(j).TGD = str2num(line(42:60));
gpsEph(j).IODC = str2num(line(61:79));
line = fgetl(fidEph);
gpsEph(j).ttx = str2num(line(4:22));
gpsEph(j).Fit_interval = str2num(line(23:41));
end
fclose(fidEph);
end %end of function ReadRinexNav
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [numEph,numHdrLines] = countEph(fidEph,fileName)
%utility function for ReadRinexNav
%Read past the header, and then read to the end, counting ephemerides:
numHdrLines = 0;
bFoundHeader = false;
while ~bFoundHeader %Read past the header
numHdrLines = numHdrLines+1;
line = fgetl(fidEph);
if ~ischar(line), break, end
k = strfind(line,'END OF HEADER');
if ~isempty(k),
bFoundHeader = true;
break
end
end
if ~bFoundHeader
error('Error reading file: %s\nExpected RINEX header not found',fileName);
end
%Now read to the end of the file
numEph = -1;
while 1
numEph = numEph+1;
line = fgetl(fidEph);
if line == -1,
break;
elseif length(line)~=79
%use this opportunity to check line is the right length
%because in the rest of ReadRinexNav we depend on line being this length
error('Incorrect line length encountered in RINEX file');
end
end;
%check that we read the expected number of lines:
if rem(numEph,8)~=0
error('Number of nav lines in %s should be divisible by 8',fileName);
end
numEph = numEph/8; %8 lines per ephemeris
end %end of function countEph
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function iono = readIono(fidEph,numHdrLines)
%utility function to read thru the header lines, and find iono parameters
iono = []; %return empty if iono not found
bIonoAlpha=false; bIonoBeta=false;
for i = 1:numHdrLines,
line = fgetl(fidEph);
% Look for iono parameters, and read them in
if ~isempty(strfind(line,'ION ALPHA')) %line contains iono alpha parameters
ii = strfind(line,'ION ALPHA');
iono.alpha=str2num(line(1:ii-1));
%If we have 4 parameters then we have the complete iono alpha
bIonoAlpha = (length(iono.alpha)==4);
end
if ~isempty(strfind(line,'ION BETA'))%line contains the iono beta parameters
ii = strfind(line,'ION BETA');
iono.beta=str2num(line(1:ii-1));
%If we have 4 parameters then we have the complete iono beta
bIonoBeta = (length(iono.beta)==4);
end
end
if ~(bIonoAlpha && bIonoBeta)
%if we didn't get both alpha and beta iono correctly, then return empty iono
iono=[];
end
end %end of function readIono
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function gpsEph = InitializeGpsEph
%utility function to initialize the ephemeris structure
gpsEph.PRN = 0;
gpsEph.Toc = 0;
gpsEph.af0 = 0;
gpsEph.af1 = 0;
gpsEph.af2 = 0;
gpsEph.IODE = 0;
gpsEph.Crs = 0;
gpsEph.Delta_n = 0;
gpsEph.M0 = 0;
gpsEph.Cuc = 0;
gpsEph.e = 0;
gpsEph.Cus = 0;
gpsEph.Asqrt = 0;
gpsEph.Toe = 0;
gpsEph.Cic = 0;
gpsEph.OMEGA = 0;
gpsEph.Cis = 0;
gpsEph.i0 = 0;
gpsEph.Crc = 0;
gpsEph.omega = 0;
gpsEph.OMEGA_DOT = 0;
gpsEph.IDOT = 0;
gpsEph.codeL2 = 0;
gpsEph.GPS_Week = 0;
gpsEph.L2Pdata = 0;
gpsEph.accuracy = 0;
gpsEph.health = 0;
gpsEph.TGD = 0;
gpsEph.IODC = 0;
gpsEph.ttx = 0;
gpsEph.Fit_interval= 0;
end %end of function InitializeEph
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2016 Google Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
|
github
|
google/gps-measurement-tools-master
|
ProcessGnssMeas.m
|
.m
|
gps-measurement-tools-master/opensource/ProcessGnssMeas.m
| 10,037 |
utf_8
|
bb97c6b42797c809f0db07298501eeda
|
function gnssMeas = ProcessGnssMeas(gnssRaw)
% gnssMeas = ProcessGnssMeas(gnssRaw)
% Process raw measurements read from ReadGnssLogger
% Using technique explained in "Raw GNSS Measurements from Android" tutorial
%
% Input: gnssRaw, output from ReadGnssLogger
% Output: gnssMeas structure formatted conveniently for batch processing:
%gnssMeas.FctSeconds = Nx1 Full cycle time tag of M batched measurements.
% .ClkDCount = Nx1 Hw clock discontinuity count
% .HwDscDelS = Nx1 Hw clock change during each discontiuity (seconds)
% .Svid = 1xM all svIds found in gnssRaw.
% .AzDeg = 1xM azimuth in degrees at last valid epoch
% .ElDeg = 1xM elevation, ditto
% .tRxSeconds = NxM time of reception, seconds of gps week
% .tTxSeconds = NxM time of transmission, seconds of gps week
% .PrM = NxM pseudoranges, row i corresponds to FctSeconds(i)
% .PrSigmaM = NxM pseudorange error estimate (1-sigma)
% .DelPrM = NxM change in pr while clock continuous
% .PrrMps = NxM pseudorange rate
% .PrrSigmaMps= NxM
% .AdrM = NxM accumulated delta range (= -k * carrier phase)
% .AdrSigmaM = NxM
% .AdrState = NxM
% .Cn0DbHz = NxM
%
% all gnssMeas values are doubles
%
% Az and El are returned NaN. Compute Az,El using ephemeris and lla,
% or read from NMEA or GnssStatus
%Author: Frank van Diggelen
%Open Source code for processing Android GNSS Measurements
% Filter valid values first, so that rollover checks, etc, are on valid data
gnssRaw = FilterValid(gnssRaw);
%anything within 1ms is considered same epoch:
allRxMilliseconds = double(gnssRaw.allRxMillis);
gnssMeas.FctSeconds = (unique(allRxMilliseconds))*1e-3;
N = length(gnssMeas.FctSeconds);
gnssMeas.ClkDCount = zeros(N,1);
gnssMeas.HwDscDelS = zeros(N,1);
gnssMeas.Svid = unique(gnssRaw.Svid)'; %all the sv ids found in gnssRaw
M = length(gnssMeas.Svid);
gnssMeas.AzDeg = zeros(1,M)+NaN;
gnssMeas.ElDeg = zeros(1,M)+NaN;
gnssMeas.tRxSeconds = zeros(N,M)+NaN; %time of reception, seconds of gps week
gnssMeas.tTxSeconds = zeros(N,M)+NaN; %time of transmission, seconds of gps week
gnssMeas.PrM = zeros(N,M)+NaN;
gnssMeas.PrSigmaM = zeros(N,M)+NaN;
gnssMeas.DelPrM = zeros(N,M)+NaN;
gnssMeas.PrrMps = zeros(N,M)+NaN;
gnssMeas.PrrSigmaMps= zeros(N,M)+NaN;
gnssMeas.AdrM = zeros(N,M)+NaN;
gnssMeas.AdrSigmaM = zeros(N,M)+NaN;
gnssMeas.AdrState = zeros(N,M);
gnssMeas.Cn0DbHz = zeros(N,M)+NaN;
%GPS Week number:
weekNumber = floor(-double(gnssRaw.FullBiasNanos)*1e-9/GpsConstants.WEEKSEC);
%check for fields that are commonly all zero and may be missing from gnssRaw
if ~isfield(gnssRaw,'BiasNanos')
gnssRaw.BiasNanos = 0;
end
if ~isfield(gnssRaw,'TimeOffsetNanos')
gnssRaw.TimeOffsetNanos = 0;
end
%compute time of measurement relative to start of week
%subtract big longs (i.e. time from 1980) before casting time of week as double
WEEKNANOS = int64(GpsConstants.WEEKSEC*1e9);
weekNumberNanos = int64(weekNumber)*int64(GpsConstants.WEEKSEC*1e9);
%compute tRxNanos using gnssRaw.FullBiasNanos(1), so that
% tRxNanos includes rx clock drift since the first epoch:
tRxNanos = gnssRaw.TimeNanos -gnssRaw.FullBiasNanos(1) - weekNumberNanos;
%Assert if Tow state ~=1, because then gnssRaw.FullBiasNanos(1) might be wrong
State = gnssRaw.State(1);
assert(bitand(State,2^0) & bitand(State,2^3),...
'gnssRaw.State(1) must have bits 0 and 3 true before calling ProcessGnssMeas')
%tRxNanos now since beginning of the week, unless we had a week rollover
%assert(all(tRxNanos <= WEEKNANOS),'tRxNanos should be <= WEEKNANOS')
%TBD check week rollover code, and add assert tRxNanos <= WEEKNANOS after
assert(all(tRxNanos >= 0),'tRxNanos should be >= 0')
%subtract the fractional offsets TimeOffsetNanos and BiasNanos:
tRxSeconds = (double(tRxNanos)-gnssRaw.TimeOffsetNanos-gnssRaw.BiasNanos)*1e-9;
tTxSeconds = double(gnssRaw.ReceivedSvTimeNanos)*1e-9;
%check for week rollover in tRxSeconds
[prSeconds,tRxSeconds] = CheckGpsWeekRollover(tRxSeconds,tTxSeconds);
%we are ready to compute pseudorange in meters:
PrM = prSeconds*GpsConstants.LIGHTSPEED;
PrSigmaM = double(gnssRaw.ReceivedSvTimeUncertaintyNanos)*1e-9*...
GpsConstants.LIGHTSPEED;
PrrMps = gnssRaw.PseudorangeRateMetersPerSecond;
PrrSigmaMps = gnssRaw.PseudorangeRateUncertaintyMetersPerSecond;
AdrM = gnssRaw.AccumulatedDeltaRangeMeters;
AdrSigmaM = gnssRaw.AccumulatedDeltaRangeUncertaintyMeters;
AdrState = gnssRaw.AccumulatedDeltaRangeState;
Cn0DbHz = gnssRaw.Cn0DbHz;
%Now pack these vectors into the NxM matrices
for i=1:N %i is index into gnssMeas.FctSeconds and matrix rows
%get index of measurements within 1ms of this time tag
J = find(abs(gnssMeas.FctSeconds(i)*1e3 - allRxMilliseconds)<1);
for j=1:length(J) %J(j) is index into gnssRaw.*
k = find(gnssMeas.Svid==gnssRaw.Svid(J(j)));
%k is the index into gnssMeas.Svid and matrix columns
gnssMeas.tRxSeconds(i,k) = tRxSeconds(J(j));
gnssMeas.tTxSeconds(i,k) = tTxSeconds(J(j));
gnssMeas.PrM(i,k) = PrM(J(j));
gnssMeas.PrSigmaM(i,k) = PrSigmaM(J(j));
gnssMeas.PrrMps(i,k) = PrrMps(J(j));
gnssMeas.PrrSigmaMps(i,k)= PrrSigmaMps(J(j));
gnssMeas.AdrM(i,k) = AdrM(J(j));
gnssMeas.AdrSigmaM(i,k) = AdrSigmaM(J(j));
gnssMeas.AdrState(i,k) = AdrState(J(j));
gnssMeas.Cn0DbHz(i,k) = Cn0DbHz(J(j));
end
%save the hw clock discontinuity count for this epoch:
gnssMeas.ClkDCount(i) = gnssRaw.HardwareClockDiscontinuityCount(J(1));
if gnssRaw.HardwareClockDiscontinuityCount(J(1)) ~= ...
gnssRaw.HardwareClockDiscontinuityCount(J(end))
error('HardwareClockDiscontinuityCount changed within the same epoch');
end
end
gnssMeas = GetDelPr(gnssMeas);
end %of function ProcessGnssMeas
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function gnssRaw = FilterValid(gnssRaw)
%utility function for ProcessGnssMeas,
%remove fields corresponding to measurements that are invalid
%NOTE: this makes it simpler to process data. But it removes data,
% so if you want to investigate *why* fields are invalid, then do so
% before calling this function
%check ReceivedSvTimeUncertaintyNanos, PseudorangeRateUncertaintyMetersPerSecond
%for now keep only Svid with towUnc<0.5 microseconds and prrUnc < 10 mps
iTowUnc = gnssRaw.ReceivedSvTimeUncertaintyNanos > GnssThresholds.MAXTOWUNCNS;
iPrrUnc = gnssRaw.PseudorangeRateUncertaintyMetersPerSecond > ...
GnssThresholds.MAXPRRUNCMPS;
iBad = iTowUnc | iPrrUnc;
if any(iBad)
numBad = sum(iBad);
%assert if we're about to remove everything:
assert(numBad<length(iBad),'Removing all measurements in gnssRaw')
names = fieldnames(gnssRaw);
for i=1:length(names)
ts = sprintf('gnssRaw.%s(iBad) = [];',names{i});
eval(ts); %remove fields for invalid meas
end
%explain to user what happened:
fprintf('\nRemoved %d bad meas inside ProcessGnssMeas>FilterValid because:\n',...
sum(iBad))
if any(iTowUnc)
fprintf('towUnc > %.0f ns\n',GnssThresholds.MAXTOWUNCNS)
end
if any(iPrrUnc)
fprintf('prrUnc > %.0f m/s\n',GnssThresholds.MAXPRRUNCMPS)
end
end
end %end of function FilterValid
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function gnssMeas = GetDelPr(gnssMeas)
% utility function for ProcessGnssMeas, compute DelPr
% gnssMeas.DelPrM = NxM, change in pr while clock is continuous
N = length(gnssMeas.FctSeconds);
M = length(gnssMeas.Svid);
bClockDis = [0;diff(gnssMeas.ClkDCount)~=0];%binary, 1 <=> clock discontinuity
%initialize first epoch to zero (by definition), rest to NaN
delPrM = zeros(N,M); delPrM(2:end,:) = NaN;
for j=1:M
i0=1; %i0 = index from where we compute DelPr
for i=2:N
if bClockDis(i) || isnan(gnssMeas.PrM(i0,j))
i0 = i; %reset to i if clock discont or a break in tracking
end
if bClockDis(i)
delPrM(i,j) = NaN;
else
delPrM(i,j) = gnssMeas.PrM(i,j) - gnssMeas.PrM(i0,j);
end
end
end
gnssMeas.DelPrM = delPrM;
end %of function GetDelPr
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [prSeconds,tRxSeconds] = CheckGpsWeekRollover(tRxSeconds,tTxSeconds)
%utility function for ProcessGnssMeas
prSeconds = tRxSeconds - tTxSeconds;
iRollover = prSeconds > GpsConstants.WEEKSEC/2;
if any(iRollover)
fprintf('\nWARNING: week rollover detected in time tags. Adjusting ...\n')
prS = prSeconds(iRollover);
delS = round(prS/GpsConstants.WEEKSEC)*GpsConstants.WEEKSEC;
prS = prS - delS;
%prS are in the range [-WEEKSEC/2 : WEEKSEC/2];
%check that common bias is not huge (like, bigger than 10s)
maxBiasSeconds = 10;
if any(prS>maxBiasSeconds)
error('Failed to correct week rollover\n')
else
prSeconds(iRollover) = prS; %put back into prSeconds vector
%Now adjust tRxSeconds by the same amount:
tRxSeconds(iRollover) = tRxSeconds(iRollover) - delS;
fprintf('Corrected week rollover\n')
end
end
%TBD Unit test this
end %end of function CheckGpsWeekRollover
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2016 Google Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
|
github
|
google/gps-measurement-tools-master
|
GetNasaHourlyEphemeris.m
|
.m
|
gps-measurement-tools-master/opensource/GetNasaHourlyEphemeris.m
| 7,264 |
utf_8
|
269885253c5a185948a02dab5d5de302
|
function [allGpsEph,allGloEph] = GetNasaHourlyEphemeris(utcTime,dirName)
%[allGpsEph,allGloEph] = GetNasaHourlyEphemeris(utcTime,dirName)
%Get hourly ephemeris files,
% If a GPS ephemeris file is in dirName, with valid ephemeris for at
% least 24 svs, then read it; else download from NASA's archive of
% Space Geodesy Data
%
%Output allGpsEph structure of ephemerides in format defined in ReadRinexNav.m
% TBD: allGloEph, and any other supported by the NSA ftp site
%
%examples of how to call GetNasaHourlyEphemeris:
%1) with /demoFiles and utcTime where ephemeris has already been downloaded:
% replace '~/...' with actual path:
% dirName = '~/Documents/MATLAB/gpstools/opensource/demoFiles';
% utcTime = [2016,8,22,22,50,00];
% [allGpsEph,allGloEph] = GetNasaHourlyEphemeris(utcTime,dirName)
%
%2) with utcTime for which ephemeris has not been downloaded,
% this exercises the automatic ftp download.
% Replace '~' with actual path:
% dirName = '~/Documents/MATLAB/gpstools/opensource/demoFiles';
% utcTime = [2016,5,ceil(rand(1,2).*[30,24]),0,0],%a random Hour and Day in May
% [allGpsEph,allGloEph] = GetNasaHourlyEphemeris(utcTime,dirName)
%
% More details:
% The Nasa ephemeris Unix-compressed.
% GetNasaHourlyEphemeris will automatically uncompress it, if you have the right
% uncompress function on you computer. If you need to install an unzip utility,
% see http://cddis.nasa.gov/ and http://www.gpzip.org
% Search for 'uncompress' in the GetNasaHourlyEphemeris function to find and
% edit the name of the unzip utility.
%Author: Frank van Diggelen
%Open Source code for processing Android GNSS Measurements
allGpsEph=[];allGloEph=[];
if nargin<2
dirName = [];
end
[bOk,dirName] = CheckInputs(utcTime,dirName);
if ~bOk, return, end
%Description of file names, see:
%http://cddis.gsfc.nasa.gov/Data_and_Derived_Products/GNSS/...
% broadcast_ephemeris_data.html#GPShourly
yearNumber4Digit = utcTime(1);
yearNumber2Digit = rem(utcTime(1),100);
dayNumber = DayOfYear(utcTime);
hourlyZFile = sprintf('hour%03d0.%02dn.Z',dayNumber,yearNumber2Digit);
ephFilename = hourlyZFile(1:end-2);
fullEphFilename = [dirName,ephFilename]; %full name (with directory specified)
%check if ephemeris file already exists (e.g. you downloaded it 'by hand')
%and if there are fresh ephemeris for lotsa sats within 2 hours of fctSeconds
bGotGpsEph = false;
if exist(fullEphFilename,'file')==2
%% file exists locally, so read it
fprintf('Reading GPS ephemeris from ''%s'' file in local directory\n',...
ephFilename);
fprintf('%s\n',dirName);
allGpsEph = ReadRinexNav(fullEphFilename);
[~,fctSeconds] = Utc2Gps(utcTime);
ephAge = [allGpsEph.GPS_Week]*GpsConstants.WEEKSEC + [allGpsEph.Toe] - ...
fctSeconds;
%get index into fresh and healthy ephemeris (health bit set => unhealthy)
iFreshAndHealthy = abs(ephAge)<GpsConstants.EPHVALIDSECONDS & ...
~[allGpsEph.health];
%TBD look at allEph.Fit_interval, and deal with values > 0
goodEphSvs = unique([allGpsEph(iFreshAndHealthy).PRN]);
if length(goodEphSvs)>=GnssThresholds.MINNUMGPSEPH
bGotGpsEph = true;
end
end
if ~bGotGpsEph
%% get ephemeris from Nasa site
ftpSiteName = 'cddis.gsfc.nasa.gov';
hourlyDir=sprintf('/gnss/data/hourly/%4d/%03d/',yearNumber4Digit,dayNumber);
fprintf('\nGetting GPS ephemeris ''%s'' from NASA ftp site ...',hourlyZFile)
fprintf('\nftp://%s%s\n',ftpSiteName,hourlyDir);
%check that the dirName has been properly specified
if strfind(dirName,'~')
fprintf('\nYou set: dirName = ''%s''\n',dirName)
fprintf('To download ephemeris from ftp,')
fprintf(' specify ''dirName'' with full path, and no tilde ''~''\n')
fprintf('Change ''dirName'' or download ephemeris file ''%s'' by hand\n',...
hourlyZFile);
fprintf('To unzip the *.Z file, see http://www.gzip.org/\n')
return
end
try
nasaFtp=ftp(ftpSiteName); %connect to ftp server and create ftp object
cd(nasaFtp,hourlyDir);
zF = mget(nasaFtp,hourlyZFile,dirName); %get compressed (.Z) file
catch
%failed automatic ftp, ask user to do this by hand
fprintf('\nAutomatic ftp download failed.\n')
fprintf('Please go to this ftp, ftp://cddis.gsfc.nasa.gov/ \n')
fprintf('and get this file:%s%s \n',hourlyDir,hourlyZFile);
fprintf('Extract contents to the directory with your pseudorange log file:\n')
fprintf('%s\n',dirName)
fprintf('To unzip the *.Z file, see http://www.gzip.org/\n')
fprintf('Then run this function again, it will read from that directory\n')
return
end
%Now we have the zipped file from nasa. Unzip it:
unzipCommand='uncompress';%edit if your platform uses something different
if any(strfind(computer,'PCWIN'))
unzipCommand='gunzip';
end
s = sprintf('%s "%s"',unzipCommand,zF{1}); %string for system command
[sysFlag,result] = system(s);
if any(sysFlag)
fprintf('\nError in GetNasaHourlyEphemeris.m\n')
fprintf('%s',result);
fprintf('System command ''%s'' failed\n',unzipCommand)
fprintf('Unzip contents of %s by hand. See http://www.gzip.org/\n',zF{1})
fprintf('Then run this function again, it will read the uncompressed file\n')
return
end
bOk = bOk && ~sysFlag;
if bOk
fprintf('\nSuccessfully downloaded ephemeris file ''%s''\n',ephFilename)
if ~isempty(dirName)
fprintf('to: %s\n',dirName);
end
else
end
end
allGpsEph = ReadRinexNav(fullEphFilename);
end %end of function GetNasaHourlyEphemeris
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [bOk,dirName] = CheckInputs(utcTime,dirName)
%% check we have the utcTime and right kind of dirName
if any(size(utcTime)~=[1,6])
error('utcTime must be a (1x6) vector')
end
if isempty(dirName), return, end
bOk = true;
if ~exist(dirName,'dir')
bOk = false;
fprintf('Error: directory ''%s'' not found\n',dirName);
if any(strfind(computer,'PCWIN')) && any(strfind(dirName,'/'))
fprintf('Looks like you''re using a PC, be sure your directory is specified with back-slashes ''\\''\n');
end
else
% check if there is a slash at the end of dirName
%decide what type of slash to use:
slashChar = '/'; %default
if any(strfind(dirName,'\'))
slashChar = '\';
end
if dirName(end)~=slashChar
dirName = [dirName,slashChar]; %add slash
end
end
end %end of function CheckInputs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2016 Google Inc.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
|
github
|
google/gps-measurement-tools-master
|
ReadNmeaFile.m
|
.m
|
gps-measurement-tools-master/NmeaUtils/ReadNmeaFile.m
| 9,958 |
utf_8
|
9a68e0e553a19e83a81a59402d4b90df
|
function [nmea,Msg] = ReadNmeaFile(dirName,fileName,Msg)
% [nmea,Msg] = ReadNmeaFile(dirName,fileName,[Msg]);
%
% Reads GGA and RMC data from a NMEA file.
% This function recognizes GGA data with quality of
% GPS fix (1)/RTK(4)/Float RTK(5)/Manual input(7) only.
% Output:
% nmea: structure array with one element per epoch.
% nmea(i).Gga,
% nmea(i).Rmc
%
% Each field of Gga, Rmc is a scalar => easy to extract vectors later.
%
% $--GGA,hhmmss.ss,llll.ll,a,yyyyy.yy,a,x,xx,x.x,x.x,M,x.x,M,x.x,xxxx*hh<CR><LF>
% UTC lat lon q num hdop altAboveMsl geoidHeight ...
% Gga.Time Day fraction
% .LatDeg Latitude in degrees
% .LonDeg Longitude in degrees
% .AltM Altitude above Ellipsoid in meters
% .NumSats = Number of satellites in use
% .Hdop
% .GeoidM = Gedoidal separation, "-" = mean-sea-level below ellipsoid
%
% $--RMC,hhmmss.sss,x,llll.ll,a,yyyyy.yy,a,x.x,x.x,xxxxxx,x.x,a,a*hh<CR><LF>
% Rmc.Datenum Date and Time = MATLAB datenum, use datevec(Rmc.Datenum) to get
% 1x6 date and time vector [yyy mm dd hh mm ss.s]
% .LatDeg Latitude in degrees
% .LonDeg Longitude in degrees
% .TrackDeg (degrees from true north)
% .SpeedKnots (knots)
%
% Release 2.3 of NMEA added a new field added to RMC just prior to the checksum,
% 'Mode': A=autonomous, D=differential, E=estimated, N=Data not valid.
%
% Msg, cell array of strings with status
%
% TBD
% .Gsv
%
% TBD remaining fields that are sometimes empty: magvar, valid, status, etc
%
% Examples from https://www.gpsinformation.org/dale/nmea.htm
% GGA Example,
% $GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
% Where:
% GGA Global Positioning System Fix Data
% 123519 Fix taken at 12:35:19 UTC
% 4807.038,N Latitude 48 deg 07.038' N
% 01131.000,E Longitude 11 deg 31.000' E
% 1 Fix quality:
% 0 = invalid
% 1 = GPS fix (SPS)
% 2 = DGPS fix
% 3 = PPS fix
% 4 = Real Time Kinematic
% 5 = Float RTK
% 6 = estimated (dead reckoning) (2.3 feature)
% 7 = Manual input mode
% 8 = Simulation mode
% 08 Number of satellites being tracked
% 0.9 Horizontal dilution of position
% 545.4,M Altitude, Meters, above mean sea level
% 46.9,M Height of geoid (mean sea level) above WGS84 ellipsoid
% (empty field) time in seconds since last DGPS update
% (empty field) DGPS station ID number
% *47 the checksum data, always begins with *
%
% RMC example,
% $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
%
% Where:
% RMC Recommended Minimum sentence C
% 123519 Fix taken at 12:35:19 UTC
% A Status A=active or V=Void.
% 4807.038,N Latitude 48 deg 07.038' N
% 01131.000,E Longitude 11 deg 31.000' E
% 022.4 Speed over the ground in knots
% 084.4 Track angle in degrees True
% 230394 Date - 23rd of March 1994
% 003.1,W Magnetic Variation
% *6A The checksum data, always begins with *
%
%% Initialize fields
if nargin<3
Msg = {};
end
nmea = [];
nmeaGga = struct('Time',{},'LatDeg',{},'LonDeg',{},'AltM',{},'NumSats',{},...
'Hdop',{},'GeoidM',{});
nmeaRmc = struct('Datenum',{},'LatDeg',{},'LonDeg',{},...
'TrackDeg',{},'SpeedKnots',{});
%define NaN fields for missing nmea messages
nanGga.Time=NaN; nanGga.LatDeg=NaN; nanGga.LonDeg=NaN; nanGga.AltM=NaN;
nanGga.NumSats=NaN; nanGga.Hdop=NaN; nanGga.GeoidM=NaN;
nanRmc.Datenum=NaN; nanRmc.LatDeg=NaN; nanRmc.LonDeg=NaN; nanRmc.TrackDeg=NaN;
nanRmc.SpeedKnots=NaN;
% Define recognized GGA fix qualities. Only lines with these qualities will be
% parsed as GGA data.
knownGgaQualities = [GgaQuality.GPS, GgaQuality.RTK,...
GgaQuality.FLOAT_RTK, GgaQuality.MANUAL];
%% read file and call parsers
fid = fopen(fullfile(dirName,fileName),'r');
if fid<0
Msg{end+1} = 'Error: file not found';
return
end
line = 'x';%initialize to some character
while ischar(line)
line = fgetl(fid);
%% remove characters before '$'
if ~ischar(line) || ~contains(line,'$')
continue
else
iDollar = strfind(line,'$');
line = line(iDollar(1):end);
end
%% parse nmea lines
[nmeaField,fieldType,quality] = parseGga(line);
if ~isempty(fieldType)
if any(knownGgaQualities(:) == quality)
nmeaGga(end+1) = nmeaField; %#ok<AGROW>
end
continue
end
%TBD:
%if isempty(fieldType)
%[nmeaField,fieldType] = parseGsv(line);
%end
[nmeaField,fieldType] = parseRmc(line);
if ~isempty(fieldType)
nmeaRmc(end+1) = nmeaField; %#ok<AGROW>
continue
end
end
fclose(fid);
if isempty(line) %line should be -1 at eof
Msg{end+1} = 'Error occurred while reading file';
nmea = [];
return
end
%% Pack all matching time tags:
N = length(nmeaGga); %make one nmea structure for each Gga field
if N==0
Msg{end+1} = sprintf('Found no recognized GGA data in %s.', fileName);
return
end
if isempty(nmeaRmc)
Msg{end+1} = sprintf('Found no RMC data in %s.', fileName);
return
end
nmea.Gga = nmeaGga(1);
nmea.Rmc = nmeaRmc(1);
nmea = repelem(nmea,N);
for i=1:N
nmea(i).Gga = nmeaGga(i);
ti = nmea(i).Gga.Time;
iR = find(ti == rem([nmeaRmc.Datenum],1));
if ~isempty(iR)
nmea(i).Rmc = nmeaRmc(iR(1));
else
nmea(i).Rmc=nanRmc;
end
end
end %end of function ReadNmeaFile
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Gga,fieldType,quality] = parseGga(line)
%% parse a gga message from the string 'line'
% $--GGA,hhmmss.ss,llll.ll,a,yyyyy.yy,a,x,xx,x.x,x.x,M,x.x,M,x.x,xxxx*hh
%format: %s %s %s %s %s %s %d %d %f %f %s %f %s %f %d %s
%fields: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
% UTC lat lon qual
% 8=num, 9=hdop, 10=altAboveMsl, 12=geoidHeight
Gga = ''; fieldType = ''; quality=-1;
line = upper(line);
if ~contains(line,'GGA,')
return
end
fieldType = 'Gga';
line = strrep(line,'*',','); %replace '*' with ','
C = textscan(line,'%s %s %s %s %s %s %d %d %f %f %s %f %s %f %d %s',...
'Delimiter',',','EmptyValue',NaN);
if ~isempty(C{2}{1})
hhmmss = sprintf('%010.3f',str2double(C{2}{1}));%hours mins secs, to 3 digits
%this allows us to capture the milliseconds in datenum:
d = datenum(hhmmss,'HHMMSS.FFF');
Gga.Time = d-floor(d);
else
Gga.Time = NaN;
end
ddmm = C{3}{1}; %deg and minutes
if isempty(ddmm)
Gga.LatDeg = NaN;
else
assert(strfind(ddmm,'.')==5,...
'GGA Latitude not defined correctly, should be ddmm.m');
Gga.LatDeg = str2double(ddmm(1:2)) + (str2double(ddmm(3:end))/60);
if strcmp(C{4}{1},'S')
Gga.LatDeg = -Gga.LatDeg;
end
end
dddmm = C{5}{1}; %deg and minutes
if isempty(dddmm)
Gga.LonDeg = NaN;
else
assert(strfind(dddmm,'.')==6,...
'GGA Longitude not defined correctly, should be dddmm.m');
Gga.LonDeg = str2double(dddmm(1:3)) + (str2double(dddmm(4:end))/60);
if strcmp(C{6}{1},'W')
Gga.LonDeg = -Gga.LonDeg;
end
end
Gga.AltM = C{10}+C{12}; %height above the ellipsoid (m)
quality = C{7}; %quality - identifies the source of this location
Gga.NumSats = C{8}; % Number of satellites in use
Gga.Hdop = C{9}; % HDOP
Gga.GeoidM = C{12}; % Gedoidal separation,"-" = mean-sea-level below ellipsoid
%leave the following out for now, to keep things simple:
% Gga.DiffAgeS = C{14}; %Age of Differental data
% Gga.DiffRefId= C{15}; % Differential reference station ID
end %end of function parseGga
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Rmc,fieldType] = parseRmc(line)
%% parse an rmc message from the string 'line'
% $--RMC,hhmmss.sss,x,llll.ll,a,yyyyy.yy,a,x.x,x.x,xxxxxx,x.x,a,a*hh
%format: %s %s %s %s %s %s %s %f %f %s %f %s %s %s
%fields: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
%example:
% $GPRMC,123519.0,A,4807.038,N,01131.000,E,022.4,084.4,230394,3.1,E,A*0B
% fields 1 2 3 4 5 6 7 8 9 10 11 12 13 14
% hhmmss.s status lat lon speed track ddmmyy magvar mode
Rmc = ''; fieldType = '';
line = upper(line);
if ~contains(line,'RMC,')
return
end
fieldType = 'Rmc';
line = strrep(line,'*',','); %replace '*' with ','
C = textscan(line,'%s %s %s %s %s %s %s %f %f %s %f %s %s %s',...
'Delimiter',',','EmptyValue',NaN);
if ~isempty(C{2}{1}) && ~isempty(C{10}{1})
hhmmss = sprintf('%010.3f',str2double(C{2}{1})); %hrs mins secs, to 3 digits
%this allows us to capture the milliseconds in datenum:
ddmmyy = C{10}{1}; %day month year
Rmc.Datenum = datenum([ddmmyy,hhmmss],'ddmmyyHHMMSS.FFF');
else
Rmc.Datenum = NaN;
end
ddmm = C{4}{1}; %deg and minutes
if isempty(ddmm)
Rmc.LatDeg = NaN;
else
assert(strfind(ddmm,'.')==5,...
'RMC Latitude not defined correctly, should be ddmm.m');
Rmc.LatDeg = str2double(ddmm(1:2)) + (str2double(ddmm(3:end))/60);
if strcmp(C{5}{1},'S')
Rmc.LatDeg = -Rmc.LatDeg;
end
end
dddmm = C{6}{1}; %deg and minutes
if isempty(dddmm)
Rmc.LonDeg = NaN;
else
assert(strfind(dddmm,'.')==6,...
'RMC Longitude not defined correctly, should be dddmm.m');
Rmc.LonDeg = str2double(dddmm(1:3)) + (str2double(dddmm(4:end))/60);
if strcmp(C{7}{1},'W')
Rmc.LonDeg = -Rmc.LonDeg;
end
end
trackDeg = C(9); %track in degrees from true North
Rmc.TrackDeg = trackDeg{1};
speedKnots = C(8); %speed in knots
Rmc.SpeedKnots = speedKnots{1};
end %end of function parseRmc
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
hanshuting/graph_ensemble-master
|
vec.m
|
.m
|
graph_ensemble-master/src/vec.m
| 1,567 |
utf_8
|
f3fc35a93c8a5b99b592835a0b810dd5
|
% Y = VEC(x) Given an m x n matrix x, this produces the vector Y of length
% m*n that contains the columns of the matrix x, stacked below each other.
%
% See also mat.
function x = vec(X)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% 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., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
%
[m n] = size(X);
x = reshape(X,m*n,1);
|
github
|
hanshuting/graph_ensemble-master
|
anneal.m
|
.m
|
graph_ensemble-master/src/util/anneal.m
| 8,126 |
utf_8
|
a2fc8f6d4866e3078bce3e438d38a6ea
|
function [minimum,fval] = anneal(loss, parent, options)
% ANNEAL Minimizes a function with the method of simulated annealing
% (Kirkpatrick et al., 1983)
%
% ANNEAL takes three input parameters, in this order:
%
% LOSS is a function handle (anonymous function or inline) with a loss
% function, which may be of any type, and needn't be continuous. It does,
% however, need to return a single value.
%
% PARENT is a vector with initial guess parameters. You must input an
% initial guess.
%
% OPTIONS is a structure with settings for the simulated annealing. If no
% OPTIONS structure is provided, ANNEAL uses a default structure. OPTIONS
% can contain any or all of the following fields (missing fields are
% filled with default values):
%
% Verbosity: Controls output to the screen.
% 0 suppresses all output
% 1 gives final report only [default]
% 2 gives temperature changes and final report
% Generator: Generates a new solution from an old one.
% Any function handle that takes a solution as input and
% gives a valid solution (i.e. some point in the solution
% space) as output.
% The default function generates a row vector which
% slightly differs from the input vector in one element:
% @(x) (x+(randperm(length(x))==length(x))*randn/100)
% Other examples of possible solution generators:
% @(x) (rand(3,1)): Picks a random point in the unit cube
% @(x) (ceil([9 5].*rand(2,1))): Picks a point in a 9-by-5
% discrete grid
% Note that if you use the default generator, ANNEAL only
% works on row vectors. For loss functions that operate on
% column vectors, use this generator instead of the
% default:
% @(x) (x(:)'+(randperm(length(x))==length(x))*randn/100)'
% InitTemp: The initial temperature, can be any positive number.
% Default is 1.
% StopTemp: Temperature at which to stop, can be any positive number
% smaller than InitTemp.
% Default is 1e-8.
% StopVal: Value at which to stop immediately, can be any output of
% LOSS that is sufficiently low for you.
% Default is -Inf.
% CoolSched: Generates a new temperature from the previous one.
% Any function handle that takes a scalar as input and
% returns a smaller but positive scalar as output.
% Default is @(T) (.8*T)
% MaxConsRej: Maximum number of consecutive rejections, can be any
% positive number.
% Default is 1000.
% MaxTries: Maximum number of tries within one temperature, can be
% any positive number.
% Default is 300.
% MaxSuccess: Maximum number of successes within one temperature, can
% be any positive number.
% Default is 20.
%
%
% Usage:
% [MINIMUM,FVAL] = ANNEAL(LOSS,NEWSOL,[OPTIONS]);
% MINIMUM is the solution which generated the smallest encountered
% value when input into LOSS.
% FVAL is the value of the LOSS function evaluated at MINIMUM.
% OPTIONS = ANNEAL();
% OPTIONS is the default options structure.
%
%
% Example:
% The so-called "six-hump camelback" function has several local minima
% in the range -3<=x<=3 and -2<=y<=2. It has two global minima, namely
% f(-0.0898,0.7126) = f(0.0898,-0.7126) = -1.0316. We can define and
% minimise it as follows:
% camel = @(x,y)(4-2.1*x.^2+x.^4/3).*x.^2+x.*y+4*(y.^2-1).*y.^2;
% loss = @(p)camel(p(1),p(2));
% [x f] = ANNEAL(loss,[0 0])
% We get output:
% Initial temperature: 1
% Final temperature: 3.21388e-007
% Consecutive rejections: 1027
% Number of function calls: 6220
% Total final loss: -1.03163
% x =
% -0.0899 0.7127
% f =
% -1.0316
% Which reasonably approximates the analytical global minimum (note
% that due to randomness, your results will likely not be exactly the
% same).
% Reference:
% Kirkpatrick, S., Gelatt, C.D., & Vecchi, M.P. (1983). Optimization by
% Simulated Annealing. _Science, 220_, 671-680.
% [email protected]
% $Revision: v5 $ $Date: 2006/04/26 12:54:04 $
% Modified by Shuting Han, 4/15/2016
def = struct(...
'CoolSched',@(T) (.8*T),...
'Generator',@(x) toggle(x),...
'InitTemp',1,...
'MaxConsRej',1000,...
'MaxSuccess',20,...
'MaxTries',300,...
'StopTemp',1e-8,...
'StopVal',-Inf,...
'Verbosity',1);
% 'Generator',@(x) (x+(randperm(length(x))==length(x))*randn/100),...
% Check input
if ~nargin %user wants default options, give it and stop
minimum = def;
return
elseif nargin<2, %user gave only objective function, throw error
error('MATLAB:anneal:noParent','You need to input a first guess.');
elseif nargin<3, %user gave no options structure, use default
options=def;
else %user gave all input, check if options structure is complete
if ~isstruct(options)
error('MATLAB:anneal:badOptions',...
'Input argument ''options'' is not a structure')
end
fs = {'CoolSched','Generator','InitTemp','MaxConsRej',...
'MaxSuccess','MaxTries','StopTemp','StopVal','Verbosity'};
for nm=1:length(fs)
if ~isfield(options,fs{nm}), options.(fs{nm}) = def.(fs{nm}); end
end
end
% main settings
newsol = options.Generator; % neighborhood space function
Tinit = options.InitTemp; % initial temp
minT = options.StopTemp; % stopping temp
cool = options.CoolSched; % annealing schedule
minF = options.StopVal;
max_consec_rejections = options.MaxConsRej;
max_try = options.MaxTries;
max_success = options.MaxSuccess;
report = options.Verbosity;
k = 1; % boltzmann constant
% counters etc
itry = 0;
success = 0;
finished = 0;
consec = 0;
T = Tinit;
initenergy = loss(parent);
oldenergy = initenergy;
total = 0;
if report==2, fprintf(1,'\n T = %7.5f, loss = %10.5f\n',T,oldenergy); end
while ~finished;
itry = itry+1; % just an iteration counter
current = parent;
% % Stop / decrement T criteria
if itry >= max_try || success >= max_success;
if T < minT || consec >= max_consec_rejections;
finished = 1;
total = total + itry;
break;
else
T = cool(T); % decrease T according to cooling schedule
if report==2, % output
fprintf(1,' T = %7.5f, loss = %10.5f\n',T,oldenergy);
end
total = total + itry;
itry = 1;
success = 1;
end
end
newparam = newsol(current);
newenergy = loss(newparam);
if (newenergy < minF),
parent = newparam;
oldenergy = newenergy;
break
end
if (oldenergy-newenergy > 1e-6)
parent = newparam;
oldenergy = newenergy;
success = success+1;
consec = 0;
else
if (rand < exp( (oldenergy-newenergy)/(k*T) ));
parent = newparam;
oldenergy = newenergy;
success = success+1;
else
consec = consec+1;
end
end
end
minimum = parent;
fval = oldenergy;
if report;
fprintf(1, '\n Initial temperature: \t%g\n', Tinit);
fprintf(1, ' Final temperature: \t%g\n', T);
fprintf(1, ' Consecutive rejections: \t%i\n', consec);
fprintf(1, ' Number of function calls:\t%i\n', total);
fprintf(1, ' Total final loss: \t%g\n', fval);
end
function [y] = toggle(x)
indx = randi(length(x),1);
y = x;
y(indx) = 1-y(indx);
end
end
|
github
|
hanshuting/graph_ensemble-master
|
graphProperties.m
|
.m
|
graph_ensemble-master/src/util/graphProperties.m
| 4,236 |
utf_8
|
85256a2e4937e41679ec818c7a9c2068
|
function [ L, EGlob, CClosed, ELocClosed, COpen, ELocOpen ] = graphProperties( varargin )
% graphProperties: compute properties of a graph from its adjacency matrix
% usage: [L,EGlob,CClosed,ELocClosed,COpen,ELocOpen] = graphProperties(A);
%
% arguments:
% A (nxn) - adjacency matrix of a graph G
%
% L (scalar) - characteristic path length
% EGlob (scalar) - global efficiency
% CClosed (scalar) - clustering coefficient (closed neighborhood)
% ELocClosed (scalar) - local efficiency (closed neighborhood)
% COpen (scalar) - clustering coefficient (open neighborhood)
% ELocOpen (scalar) - local efficiency (open neighborhood)
%
% author: Nathan D. Cahill
% email: [email protected]
% date: 10 April 2014
% get adjacency matrix from list of inputs
A = parseInputs(varargin{:});
% get number of vertices
n = size(A,1);
% shortest path distances between each node
D = graphallshortestpaths(A);
% characteristic path length
L = sum(D(:))/(n*(n-1));
% global efficiency
EGlob = (sum(sum(1./(D+eye(n)))) - n)/(n*(n-1));
% subgraphs of G induced by the neighbors of each vertex
[MClosed,kClosed,MOpen,kOpen] = subgraphs(A);
% local clustering coefficient in each subgraph
[CLocClosed,CLocOpen] = deal(zeros(n,1));
for i = 1:n
CLocClosed(i) = sum(MClosed{i}(:))/...
(numel(kClosed{i})*(numel(kClosed{i})-1));
CLocOpen(i) = sum(MOpen{i}(:))/...
(numel(kOpen{i})*(numel(kOpen{i})-1));
end
% clustering coefficients
CClosed = mean(CLocClosed);
COpen = mean(CLocOpen);
% local efficiency of each subgraph
[ELocSGClosed,ELocSGOpen] = deal(zeros(n,1));
for i = 1:n
% distance matrix and number of vertices for current subgraph
DSGClosed = graphallshortestpaths(MClosed{i});
DSGOpen = graphallshortestpaths(MOpen{i});
nSGClosed = numel(kClosed{i});
nSGOpen = numel(kOpen{i});
% efficiency of current subgraph
ELocSGClosed(i) = (sum(sum(1./(DSGClosed+eye(nSGClosed)))) - nSGClosed)/...
(nSGClosed*(nSGClosed-1));
ELocSGOpen(i) = (sum(sum(1./(DSGOpen+eye(nSGOpen)))) - nSGOpen)/...
(nSGOpen*(nSGOpen-1));
end
% local efficiency of graph
ELocClosed = mean(ELocSGClosed);
ELocOpen = mean(ELocSGOpen);
end
function A = parseInputs(varargin)
% parseInputs: test that input is an adjacency matrix
% check number of inputs
narginchk(1,1);
% get first input
A = varargin{1};
% test to make sure A is a square matrix
if ~isnumeric(A) || ~ismatrix(A) || size(A,1)~=size(A,2)
error([mfilename,':ANotSquare'],'Input must be a square matrix.');
end
% test to make sure A only contains zeros and ones
if any((A~=0)&(A~=1))
error([mfilename,':ANotValid'],...
'Input matrix must contain only zeros and ones.');
end
% change A to sparse if necessary
if ~issparse(A)
A = sparse(A);
end
end
function [MClosed,kClosed,MOpen,kOpen] = subgraphs(A)
% subgraphs: compute adjacency matrices for each vertex in a graph
% usage: [MClosed,kClosed,MOpen,kOpen] = subgraphs(A);
%
% arguments:
% A - (nxn) adjacency matrix of a graph G
%
% MClosed, MOpen - (nx1) cell arrays containing adjacency matrices of the
% subgraphs corresponding to neighbors of each vertex. For example,
% MClosed{j} is the adjacency matrix of the subgraph of G
% corresponding to the closed neighborhood of the jth vertex of G,
% and kClosed{j} is the list of vertices of G that are in the
% subgraph (and represent the corresponding rows/columns of
% MClosed{j})
%
% author: Nathan D. Cahill
% email: [email protected]
% date: 10 Apr 2014
% number of vertices
n = size(A,1);
% initialize indices of neighboring vertices, and adjacency matrices
[kClosed,kOpen] = deal(cell(n,1));
[MClosed,MOpen] = deal(cell(n,1));
% loop through each vertex, determining its neighbors
for i=1:n
% find indices of neighbors of vertex v_i
k1 = find(A(i,:)); % vertices with edge beginning at v_i
k2 = find(A(:,i)); % vertices with edge ending at v_i
kOpen{i} = union(k1,k2); % vertices in neighborhood of v_i
kClosed{i} = union(kOpen{i},i);
% extract submatrix describing adjacency of neighbors of v_i
MOpen{i} = A(kOpen{i},kOpen{i});
MClosed{i} = A(kClosed{i},kClosed{i});
end
end
|
github
|
hanshuting/graph_ensemble-master
|
makeShuffledData.m
|
.m
|
graph_ensemble-master/src/graphs/makeShuffledData.m
| 1,065 |
utf_8
|
001f9896d283081f75d86871214c70ad
|
function [] = makeShuffledData(param)
expt_name = param.expt_name;
ee = param.ee;
num_shuff = param.num_shuff;
data_path = param.data_path;
shuff_path_base = param.shuff_path_base;
% make shuffled data
for n = 1:length(expt_name)
expt_ee = ee{n};
load([data_path expt_name{n} '\' expt_name{n} '.mat']);
num_node = size(Spikes,1);
for e = 1:length(expt_ee)
fprintf('processing %s_%s...\n',expt_name{n},expt_ee{e});
% set save path
shuff_path = [shuff_path_base 'shuffled_' ...
expt_name{n} '_' expt_ee{e} '_loopy\'];
if ~exist(shuff_path)
mkdir(shuff_path);
end
% load data
load([data_path expt_name{n} '\' expt_name{n} '_' expt_ee{e} '.mat']);
data_raw = data;
% shuffle
for i = 1:num_shuff
data = shuffle(data_raw','exchange')';
save([shuff_path 'shuffled_' expt_name{n} '_' expt_ee{e} '_'...
num2str(i) '.mat'],'data');
end
end
end
|
github
|
hanshuting/graph_ensemble-master
|
makeCCgraph.m
|
.m
|
graph_ensemble-master/src/graphs/makeCCgraph.m
| 1,833 |
utf_8
|
b4f28b4118e500e6b4d12c424dbcbe27
|
function [] = makeCCgraph(param)
expt_name = param.expt_name;
ee = param.ee;
num_shuff = param.num_shuff;
data_path = param.data_path;
shuff_path_base = param.shuff_path_base;
p = param.p;
% make xcorr graph
for n = 1:length(expt_name)
expt_ee = ee{n};
load([data_path expt_name{n} '\' expt_name{n} '.mat']);
num_node = size(Spikes,1);
for e = 1:length(expt_ee)
fprintf('processing %s_%s...\n',expt_name{n},expt_ee{e});
% load real and random models
shuff_path = [shuff_path_base 'shuffled_' ...
expt_name{n} '_' expt_ee{e} '_loopy\'];
% load data
load([data_path expt_name{n} '\' expt_name{n} '_' expt_ee{e} '.mat']);
% calculate correlation
cc = corr(data);
% threshold correlation with shuffled data
shuff_cc = zeros(size(cc,1),size(cc,2),num_shuff);
for i = 1:num_shuff
load([shuff_path 'shuffled_' expt_name{n} '_' expt_ee{e} '_'...
num2str(i) '.mat']);
shuff_cc(:,:,i) = corr(data);
end
cc_thresh = zeros(size(cc));
for i = 1:size(cc,1)
for j = 1:size(cc,2)
if all(isnan(shuff_cc(i,j,:)))
continue;
end
ccdist = fitdist(squeeze(shuff_cc(i,j,:)),'normal');
cc_thresh(i,j) = icdf(ccdist,1-p);
end
end
% generate graph
cc_graph = cc>cc_thresh;
cc_graph = cc_graph-diag(diag(cc_graph));
cc_weight = cc.*cc_graph;
% save results
ccpath = [param.result_path_base '\' expt_name{n} '\cc\'];
save([ccpath expt_name{n} '_' expt_ee{e} '_cc_graph.mat'],...
'cc_graph','cc_weight','-v7.3');
end
end
end
|
github
|
hanshuting/graph_ensemble-master
|
getEdgeId.m
|
.m
|
graph_ensemble-master/src/paramter_estimation/getEdgeId.m
| 488 |
utf_8
|
1796dddb717073f46cbb8ed01d2680eb
|
% Given the edge indices, return its id in Vt
% The edges in Vt are ordered in increasing order of
% for edges (i,j) such that i < j
% e.g. for graph with 6 nodes (1,2),(1,3), .... ,(3,6),(4,5),(4,6),(5,6)
function id = getEdgeId(N,edge)
E = size(edge,1);
id = zeros(E,1);
for e=1:E
i = edge(e,1);
j = edge(e,2);
if(i >= j)
continue;
end
id(e) = N*(i-1) - sum(1:(i-1)) + (j-i);
end
id(find(id == 0)) = [];
end
|
github
|
hanshuting/graph_ensemble-master
|
lasso_node_by_node.m
|
.m
|
graph_ensemble-master/src/loopy_model/structure_learning/lasso_node_by_node.m
| 2,865 |
utf_8
|
41ca9c74c1fc182736cd2a9f895fee26
|
% LASSO_NODE_BY_NODE Tries to predict one variable as a function of another
% and return lasso coefficients in a matrix, where each row refers to a
% lasso logistic regression and each column a coefficient.
%
% Input
% samples: logical matrix where each row is a sample and each column a node
% relative_lambda: relative regularization factor (relative to the lambda
% that drives all coefficients to zero.
% option 'variable_groups': array that marks with integers which variable
% belongs to each group, so a variable is not predicted by variables of
% the same group
%
% Return
% coefficients: matrix where each row refers to a lasso logistic
% regression and each column a coefficient
function [coefficients] = lasso_node_by_node(samples, relative_lambda, varargin)
% parse input arguments
parser = inputParser;
is_logical_matrix = @(x) ismatrix(x);
parser.addRequired('samples', is_logical_matrix);
parser.addRequired('relative_lambda', @isnumeric);
parser.addParamValue('variable_groups', [], @isnumeric);
parser.parse(samples, relative_lambda, varargin{:});
variable_groups = parser.Results.variable_groups;
node_count = size(samples,2);
% ensures variable groups is a vector of integers with node count size
if isempty(variable_groups)
variable_groups = uint8(1:node_count);
elseif length(variable_groups) ~= node_count
error('variable_group variable must have one element per node');
else
variable_groups = uint8(variable_groups);
end
% each line of the coefficients comes from a regression, there is one
% regression per node, that generates one coefficient per other node
% (but diagonal is zero since we cannot use own node to predict itself,
% and for each line columns corresponding to variables in the same group
% are zero as well).
% We will store these values in the lasso_coefficients square matrix
lasso_coefficients = zeros(node_count);
disp('Starting Lasso Logistic Regression');
% let's try to predict each node based on the others using lasso
for label_node = 1:node_count
% feature nodes are all nodes except the ones in the same group
% (including the node that is being labeled)
group_nodes = find(variable_groups == variable_groups(label_node));
feature_nodes = setdiff(1:node_count, group_nodes);
X = samples(:,feature_nodes);
Y = samples(:,label_node);
B = lassoglm(X,Y, 'binomial', 'LambdaRatio', relative_lambda, 'NumLambda', 2);
% B = lassoglm(X,Y, 'poisson', 'LambdaRatio', relative_lambda, 'NumLambda', 2); %SH 20160329
lasso_coefficients(label_node, feature_nodes) = B(:,1)';
fprintf('.');
end
fprintf('\n');
coefficients = lasso_coefficients;
end
|
github
|
hanshuting/graph_ensemble-master
|
lasso_node_by_node_parallel.m
|
.m
|
graph_ensemble-master/src/loopy_model/structure_learning/lasso_node_by_node_parallel.m
| 3,218 |
utf_8
|
e0267c6e0324844b22866ba9591c73e1
|
% WORKS ONLY IF PARALLEL COMPUTING TOLLBOX IS INSTALLED
%
% LASSO_NODE_BY_NODE Tries to predict one variable as a function of another
% and return lasso coefficients in a matrix, where each row refers to a
% lasso logistic regression and each column a coefficient.
%
% Input
% samples: logical matrix where each row is a sample and each column a node
% relative_lambda: relative regularization factor (relative to the lambda
% that drives all coefficients to zero.
% option 'variable_groups': array that marks with integers which variable
% belongs to each group, so a variable is not predicted by variables of
% the same group
%
% Return
% coefficients: matrix where each row refers to a lasso logistic
% regression and each column a coefficient
function [coefficients] = lasso_node_by_node_parallel(samples, relative_lambda, varargin)
% parse input arguments
parser = inputParser;
is_logical_matrix = @(x) ismatrix(x);
parser.addRequired('samples', is_logical_matrix);
parser.addRequired('relative_lambda', @isnumeric);
parser.addParamValue('variable_groups', [], @isnumeric);
parser.parse(samples, relative_lambda, varargin{:});
variable_groups = parser.Results.variable_groups;
node_count = size(samples,2);
% ensures variable groups is a vector of integers with node count size
if isempty(variable_groups)
variable_groups = uint8(1:node_count);
elseif length(variable_groups) ~= node_count
error('variable_group variable must have one element per node');
else
variable_groups = uint8(variable_groups);
end
% each line of the coefficients comes from a regression, there is one
% regression per node, that generates one coefficient per other node
% (but diagonal is zero since we cannot use own node to predict itself,
% and for each line columns corresponding to variables in the same group
% are zero as well).
% We will store these values in the lasso_coefficients square matrix
lasso_coefficients = zeros(node_count);
sliced_coefficients = cell(node_count,1);
disp('Starting Lasso Logistic Regression (Parallel)');
% let's try to predict each node based on the others using lasso
poolobj = parpool;
parfor label_node = 1:node_count
% feature nodes are all nodes except the ones in the same group
% (including the node that is being labeled)
group_nodes = find(variable_groups == variable_groups(label_node));
feature_nodes = setdiff(1:node_count, group_nodes);
X = samples(:,feature_nodes);
Y = samples(:,label_node);
B = lassoglm(X,Y, 'binomial', 'LambdaRatio', relative_lambda, 'NumLambda', 2);
sliced_coefficients{label_node} = B(:,1)';
fprintf(' %d ', label_node);
end
delete(poolobj);
fprintf('\n');
for label_node = 1:node_count
group_nodes = find(variable_groups == variable_groups(label_node));
feature_nodes = setdiff(1:node_count, group_nodes);
lasso_coefficients(label_node, feature_nodes) = sliced_coefficients{label_node};
end
coefficients = lasso_coefficients;
end
|
github
|
hanshuting/graph_ensemble-master
|
learn_structures_by_density.m
|
.m
|
graph_ensemble-master/src/loopy_model/structure_learning/learn_structures_by_density.m
| 5,481 |
utf_8
|
aaef90286007e048e8a9fe7cba04ae25
|
% LEARN_STRUCTURES_BY_DENSITY
%
% Input
% samples: logical matrix where each row is a sample and each column a node
% relative_lambda: relative regularization factor (relative to the lambda
% that drives all coefficients to zero.
% densities: vector of densities to be tried.
% option variable_groups: array that marks with integers which variable
% belongs to each group, so a variable is not predicted by variables of
% the same group. Edges are only possible between variables in the same
% group.
%
% Return
% graph_structures: cell array, each one containing a adjacency matrix to
% the respective threshold
function [graph_structures, numeric_graph_structure] = learn_structures_by_density(samples, relative_lambda, densities, variable_groups)
% parse input arguments
parser = inputParser;
% is_logical_matrix = @(x) ismatrix(x) && islogical(x);
is_logical_matrix = @(x) ismatrix(x);
parser.addRequired('samples', is_logical_matrix);
parser.addRequired('relative_lambda', @isnumeric);
parser.addRequired('densities', @isnumeric);
variable_groups_chk = @(x)validateattributes(x, {'cell'}, {'vector'});
parser.addOptional('variable_groups', [], variable_groups_chk);
if nargin < 4
parser.parse(samples, relative_lambda, densities);
variable_groups = parser.Results.variable_groups;
else
parser.parse(samples, relative_lambda, densities, variable_groups);
end
node_count = size(samples,2);
if iscell(variable_groups)
coefficients = lasso_node_by_node_group(samples, relative_lambda, 'variable_groups', variable_groups);
else
coefficients = lasso_node_by_node(samples, relative_lambda, 'variable_groups', variable_groups);
end
% if there are negative values in the symmetric coefficients means that
% one edge was predicted to be both attractive and repulsive in the two
% different lassos. We will just zero those variables (at the moment I
% wrote the code, 10/1820 edges with the Columbia data would have this
% problem so it is really rare)
multiplied_coefficients = coefficients .* coefficients';
negative_values_indexes = find(multiplied_coefficients < 0);
if negative_values_indexes
% TODO: This is an odd metric -- first, negative_values_indexes has
% an entry for each half edge, so its length is twice the number of
% undirected edges affected.
% Second, multiplied_coefficients seems inappropriate as some max
% set of edges to compare against, since if coefficient(i, j) > 0
% but coefficient(j, i) == 0, edge (i, j) will not be included in
% length(find(multiplied_coefficients ~= 0)), even though it will
% show up as a positive edge in numeric_graph_structure and may
% very well become an actual edge if greater than threshold.
fprintf('Found %d/%d edges that had contradicting weight signs in both lassos.\n',...
length(negative_values_indexes), length(find(multiplied_coefficients ~= 0)));
summed_negative_values = coefficients + coefficients';
summed_negative_values = summed_negative_values(negative_values_indexes);
fprintf('The mean of the contradicting pairs after summing is %d, with the max summed pair at %d.\n', ...
mean(summed_negative_values(:)), max(summed_negative_values(:)));
fprintf('Compare with %d, the mean of all coefficient pairs.\n', ...
2*mean(coefficients(coefficients ~= 0)));
% coefficients(negative_values_indexes) = 0;
end
% numeric graph structure
numeric_graph_structure = (coefficients + coefficients');
if iscell(variable_groups)
% Convert variable_groups to logical matrix
eligible_edges = zeros(node_count, node_count);
for ii = 1:node_count
eligible_edges(ii, variable_groups{ii}) = 1;
end
eligible_edges = logical(eligible_edges);
assert(all(all(eligible_edges == eligible_edges')), ...
'variable_groups must be symmetric.');
edge_vector = numeric_graph_structure(triu(eligible_edges, 1));
else
edge_vector = vecUT(numeric_graph_structure);
end
max_edge_count = numel(edge_vector);
% for each given density produce an adjacency matrix
graph_structures = cell(1,numel(densities));
for ii = 1:numel(densities)
density = densities(ii);
% now let's find what is the threshold we should use to get a certain density
threshold = quantile(edge_vector, 1 - density);
if ~threshold
fprintf('Lambda is too big, such that it is not possible to achieve the desired graph density.\n');
fprintf('Target was %.f edges, but only able to identify %d non-zero coefficients\n', ...
max_edge_count * density, numel(find(edge_vector > 0)));
threshold = 0;
end
% now identify the indexes of the edges that will be kept
graph_structures{ii} = logical(numeric_graph_structure > threshold);
fprintf('Report\n');
fprintf('Total possible edges: %i\n', max_edge_count);
fprintf('Density wanted: %f%%\n', density * 100);
fprintf('Edges wanted: %.f\n', density * max_edge_count);
fprintf('Non-zero coefficients: %i\n', numel(find(edge_vector > 0)));
fprintf('Selected edges: %i\n', numel(find(edge_vector > threshold)));
end
end
|
github
|
hanshuting/graph_ensemble-master
|
run.m
|
.m
|
graph_ensemble-master/src/expt_framework/run.m
| 9,683 |
utf_8
|
5e21d0fbfd12a7c34828364e728cb642
|
%% Experiment: Parameter Estimation for Real data
% Description:
% - Learn multiple structures with various regularizers (lambda) and
% tolerance values
% - Train the parameters with respect to each of the structure learned
% in the previous step with various values of parameter estimation
% regularizer
% - Predict (test) the learned models in the previous step on validation data
% - Finally, choose the optimal model based on validation likelihood
%
% Inputs (with example):
% params.lambda = 1e-10;
% params.use_built_in_lasso = false;
%
% Quick run in MATLAB:
% In root folder, after loading startup.m, run:
% runExpt('structure_learning_synthetic', 1)
% Quick run on command line:
% \run.sh Parameter_estimation 1
function run(params)
%Kate: if result is already computed, we are done
fsave = sprintf('%s/results/%s', params.exptDir, ...
params.saveFileName);
if(exist(fsave))
%loads 'model_collection'!!!!
fprintf('Loading existing %s', fsave);
load(fsave);
disp(model_collection);
for i = 1:numel(model_collection.models)
fprintf('model %d:\n', i);
model = model_collection.models{i};
if(isfield(model, 'test_likelihood'))
continue;
end
fprintf('Computing training likelihood\n');
model.train_likelihood = compute_avg_log_likelihood( ...
model.theta.node_potentials, ...
model.theta.edge_potentials, ...
model.theta.logZ, ...
model_collection.x_train);
%Kate: reverting changes by rvtonge from 11/11/15:
% Compute test likelihood
fprintf('Computing test likelihood\n');
model.test_likelihood = compute_avg_log_likelihood( ...
model.theta.node_potentials, ...
model.theta.edge_potentials, ...
model.theta.logZ, ...
model_collection.x_test);
model_collection.models{i} = model;
end
else
%% Get the data
X = params.data;
sample_count = size(X,1);
x_train_base = X(1:floor(params.split*sample_count),:);
x_test_base = X((floor(params.split*sample_count)+1):sample_count,:);
%% Prep data
x_train = add_lookback_nodes(x_train_base, params.time_span);
x_test = add_lookback_nodes(x_test_base, params.time_span);
stim_count = size(params.stimuli, 2);
% Append any stimulus nodes
if stim_count > 0
assert(sample_count == size(params.stimuli, 1), ...
'Stimuli and neuron data must have same number of samples.')
x_train = [x_train params.stimuli(1:floor(params.split*sample_count),:)];
x_test = [x_test params.stimuli((floor(params.split*sample_count)+1):sample_count,:)];
end
% define allowed edges via variable groups
% One variable group entry per node. Each group entry is a (possibly
% empty) list of other node indexes.
if params.time_span > 1
num_groups = size(x_train,2);
variable_groups = cell(1, num_groups);
base_node_count = size(params.data, 2);
% Indexes of current timestep nodes
origidx = 1:base_node_count;
% Indexes of prev timestep nodes
dupidx = base_node_count+1:(num_groups - stim_count);
% Always consider fully connected graph at current timestep
variable_groups(origidx) = all_but_me(1, base_node_count);
if strcmp(params.edges, 'full')
% Fully connect all neuron nodes.
variable_groups = all_but_me(1, params.time_span * base_node_count);
% variable_groups = uint16(1:size(x_train, 2));
else
if strcmp(params.edges, 'simple')==0
fprintf('Invalid edges parameter. Resorting to default setting "simple".\n');
params.edges = 'simple';
end
fprintf('Prohibiting edges between offset nodes.\n');
% Add edge from every current timestep node to every
% added previous timestep node.
% Add half edges from orig nodes to every dup node.
variable_groups(origidx) = cellfun(@(x) [x dupidx], ...
variable_groups(origidx),'UniformOutput',false);
% Set half edge from every dup edge to every orig node.
variable_groups(dupidx) = {origidx};
end
% Always connect stimulus nodes to all non-stimulus nodes
% NOTE: Does NOT connect stimulus nodes to each other
stimidx = (num_groups - stim_count + 1):num_groups;
% Half edges from neuron nodes to stimulus nodes
for ii = [origidx dupidx]
variable_groups{ii} = [variable_groups{ii} stimidx];
end
% Half edges from stimulus nodes to neuron nodes
for ii = stimidx
variable_groups{ii} = [origidx dupidx];
end
if params.no_same_neuron_edges
fprintf('Removing all edges between same-neuron nodes.\n');
for ii = origidx
this_node_idxs = ii:base_node_count:params.time_span*base_node_count;
for jj = this_node_idxs
variable_groups{jj} = setdiff(variable_groups{jj}, this_node_idxs);
end
end
end
else
% Fully connect ALL nodes (including stimulus)
% variable_groups = uint16(1:size(x_train, 2));
variable_groups = all_but_me(1, size(x_train, 2));
end
%% Instantiate object that runs the algorithm
if strcmp(params.structure_type, 'loopy')
model_collection = LoopyModelCollection(x_train, x_test, ...
's_lambda_count',params.s_lambda_count, ...
's_lambda_min',params.s_lambda_min, ...
's_lambda_max',params.s_lambda_max, ...
'density_count',params.density_count, ...
'density_min',params.density_min, ...
'density_max',params.density_max, ...
'p_lambda_count',params.p_lambda_count, ...
'p_lambda_min',params.p_lambda_min, ...
'p_lambda_max',params.p_lambda_max);
% 'time_span', params.time_span);
model_collection.variable_groups = variable_groups;
else
% when training a tree there is no need for density and structure
% lambda
model_collection = LoopyModelCollection(x_train, x_test, ...
'p_lambda_count',params.p_lambda_count, ...
'p_lambda_min',params.p_lambda_min, ...
'p_lambda_max',params.p_lambda_max);
end
%% Structure Learninig
fprintf('Structure Learning...\n');
if strcmp(params.structure_type, 'loopy')
% learn loopy models
model_collection = model_collection.do_loopy_structure_learning();
else
% learn tree model (learns single structure)
model_collection = model_collection.do_chowliu_structure_learning();
end
%% Parameter Estimation
fprintf('Parameter Estimation...\n');
disp(model_collection);
% Training
model_collection = model_collection.do_parameter_estimation( ...
'BCFW_max_iterations', params.BCFW_max_iterations, ...
'compute_true_logZ', params.compute_true_logZ, ...
'reweight_denominator', params.reweight_denominator);
end
% SH
for i = 1:numel(model_collection.models)
fprintf('model %d:\n', i);
model = model_collection.models{i};
model.time_span = params.time_span;
if(isfield(model, 'test_likelihood'))
continue;
end
fprintf('Computing training likelihood\n');
model.train_likelihood = compute_avg_log_likelihood( ...
model.theta.node_potentials, ...
model.theta.edge_potentials, ...
model.theta.logZ, ...
model_collection.x_train);
%Kate: reverting changes by rvtonge from 11/11/15:
% Compute test likelihood
fprintf('Computing test likelihood\n');
model.test_likelihood = compute_avg_log_likelihood( ...
model.theta.node_potentials, ...
model.theta.edge_potentials, ...
model.theta.logZ, ...
model_collection.x_test);
model_collection.models{i} = model;
end
% Saves results
disp(model_collection);
save(sprintf('%s/results/%s', params.exptDir, params.saveFileName), 'model_collection');
end
function [indices] = all_but_me(low, high)
%ALL_BUT_ME Cell array of all sets that omit one integer from range [low, high].
N = high - low + 1;
tmp = repmat((low:high)', 1, N);
tmp = tmp(~eye(size(tmp)));
tmp = reshape(tmp,N - 1, N)';
indices = num2cell(tmp, 2)';
end
|
github
|
hanshuting/graph_ensemble-master
|
infer_structure.m
|
.m
|
graph_ensemble-master/src/structure_learning/infer_structure/infer_structure.m
| 6,225 |
utf_8
|
f7f75dfecc3e22ffb7e95247341bd512
|
% INFER_STRUCTURE Infers the structure of MRF of binary variables based on samples
%
% Input
% samples: logical matrix where each row is a sample and each column a node
% lambda: regularization factor
% options:
% 'graph_build_method': ['and', 'or', 'average', 'raw']. How to conciliate
% the fact that sometimes node A is used to predict B, but B is not
% used to predict A. 'and' methods need both to happen to put an
% edge between nodes, 'or' only needs one of them, and 'average'
% checks the lasso coefficient on average is above tolerance.
% 'raw' returns the assymetric matrix which rows are just the
% output of the lasso regression.
% Default: 'and'
% 'return_logical': [true, false]. Whether to return a thresholded
% logical matrix representing the connection or to return the numeric
% weights predicted for each edge. Default: true
% 'tolerance': Only used if 'return_logical' is true. Threshold for
% the lasso coefficients, above which a node is considered
% relevant to predict another (i.e. connected). Default: 0.1
% 'use_built_in_lasso': [true, false]. If true uses matlab lasso
% regression, else uses Boyd binaries. Default: false
% 'use_relative_lambda': interprets lambda not as an absolute value
% but as a proportions of the maximum lambda. Only works when
% 'use_built_in_lasso' is set. Default: false.
% 'use_lasso_regression': does regression instead of logistic
% regression. Option kept so we can make tests. Default: false.
function [ graph_structure,graph_values] = infer_structure( samples, lambda, varargin )
% parse input arguments
parser = inputParser;
is_logical_matrix = @(x) ismatrix(x) && islogical(x);
parser.addRequired('samples', is_logical_matrix);
parser.addRequired('lambda', @isnumeric);
parser.addParamValue('tolerance', 0, @isnumeric);
parser.addParamValue('graph_build_method', 'and', @ischar);
parser.addParamValue('return_logical', true, @islogical);
parser.addParamValue('use_built_in_lasso', false, @islogical);
parser.addParamValue('use_relative_lambda', false, @islogical);
parser.addParamValue('use_lasso_regression', false, @islogical);
parser.addParamValue('preknown_edges',-1,@isscalar);
parser.parse(samples, lambda, varargin{:});
tolerance = parser.Results.tolerance;
graph_build_method = parser.Results.graph_build_method;
return_logical = parser.Results.return_logical;
use_built_in_lasso = parser.Results.use_built_in_lasso;
use_relative_lambda = parser.Results.use_relative_lambda;
use_lasso_regression = parser.Results.use_lasso_regression;
preknown_edges = parser.Results.preknown_edges;
node_count = size(samples,2);
% each line of the coefficients comes from a regression, there is one
% regression per node, that generates one coefficient per other node
% (but diagonal is zero since we cannot use own node to predict itself)
lasso_coefficients = zeros(node_count);
disp('Starting Lasso Logistic Regression');
% let's try to predict each node based on the others using lasso
for label_node = 1:node_count
feature_nodes = setdiff(1:node_count,[label_node]);
X = samples(:,feature_nodes);
Y = samples(:,label_node);
if use_built_in_lasso
if use_lasso_regression
if use_relative_lambda
B = lasso(X,Y,'LambdaRatio', lambda, 'NumLambda', 2);
else
B = lasso(X,Y,'Lambda', lambda);
end
else
if use_relative_lambda
B = lassoglm(X,Y, 'binomial', 'LambdaRatio', lambda, 'NumLambda', 2);
else
B = lassoglm(X,Y, 'binomial', 'Lambda', lambda);
end
end
lasso_coefficients(label_node, feature_nodes) = abs(B(:,1)');
else
% lasso solver accepts inputs as files, using temp files
features_file = tempname;
mmwrite(features_file, samples(:,feature_nodes));
labels_file = tempname;
mmwrite(labels_file, samples(:,label_node));
% solver outputs file, getting temp path for output
trained_model_file = tempname;
% call lasso solver
system(sprintf('thirdparty/l1_logreg-0.8.2/src_c/l1_logreg_train -q -s %s %s %.32f %s', features_file, labels_file, lambda, trained_model_file));
% get classifier coefficients (except intercept term)
trained_model = full(mmread(trained_model_file));
lasso_coefficients(label_node, feature_nodes) = abs(trained_model(2:end));
end
fprintf('.');
end
disp('');
% now use coefficients to infer graph structure
switch graph_build_method
case 'and'
graph_structure = min(lasso_coefficients, lasso_coefficients');
case 'or'
graph_structure = max(lasso_coefficients, lasso_coefficients');
case 'average'
graph_structure = (lasso_coefficients + lasso_coefficients')/2;
case 'raw'
graph_structure = lasso_coefficients;
end
% if output should be logical, then compare with threshold
if return_logical
disp('Returning thresholded estimated structure')
graph_values = graph_structure;
graph_structure = triu(graph_structure,1);
if preknown_edges ~= -1
[~,edgeInd] = sort(graph_structure(:),'descend');
edges = zeros(size(graph_structure(:)));
edges(edgeInd(1:preknown_edges)) = 1;
graph_structure = reshape(edges,size(graph_structure));
graph_structure = max(graph_structure,graph_structure');
else
graph_structure = graph_structure >= tolerance;
end
else
graph_values = graph_structure;
disp('Returning non-thresholded estimated structure')
end
% Make sure diagonal values are 0
graph_structure = graph_structure .* (1 - diag(ones(1,node_count)));
end
|
github
|
hanshuting/graph_ensemble-master
|
simple_infer_structure.m
|
.m
|
graph_ensemble-master/src/structure_learning/simple_infer_structure/simple_infer_structure.m
| 2,383 |
utf_8
|
b80d3b54863048cad93e5bd158ee3730
|
% SIMPLE_INFER_STRUCTURE Infers the structure of MRF of binary variables based on samples
% This is a cleaned up version of the INFER_STRUCTURE function, holding
% only options that matter most.
%
% Besides that, this model return graph for multiple thresholds without
% repeating the lasso regression.
%
% Input
% samples: logical matrix where each row is a sample and each column a node
% relative_lambda: relative regularization factor (relative to the lambda
% that drives all coefficients to zero.
% thresholds: vector of thresholds to be tried.
%
% Return
% graph_structures: cell array, each one containing a adjacency matrix to
% the respective threshold
function [graph_structures,numeric_graph_structure] = simple_infer_structure(samples, relative_lambda, thresholds)
% parse input arguments
parser = inputParser;
is_logical_matrix = @(x) ismatrix(x) && islogical(x);
parser.addRequired('samples', is_logical_matrix);
parser.addRequired('relative_lambda', @isnumeric);
parser.addRequired('thresholds', @isnumeric);
parser.parse(samples, relative_lambda, thresholds);
node_count = size(samples,2);
% each line of the coefficients comes from a regression, there is one
% regression per node, that generates one coefficient per other node
% (but diagonal is zero since we cannot use own node to predict itself)
% We will store these values in the lasso_coefficient square matrix
lasso_coefficients = zeros(node_count);
disp('Starting Lasso Logistic Regression');
% let's try to predict each node based on the others using lasso
for label_node = 1:node_count
feature_nodes = setdiff(1:node_count, label_node);
X = samples(:,feature_nodes);
Y = samples(:,label_node);
B = lassoglm(X,Y, 'binomial', 'LambdaRatio', relative_lambda, 'NumLambda', 2);
lasso_coefficients(label_node, feature_nodes) = abs(B(:,1)');
fprintf('.');
end
fprintf('\n');
% make matrix symmetric
numeric_graph_structure = max(lasso_coefficients, lasso_coefficients');
% for each threshold produce an adjacency matrix
graph_structures = cell(1,numel(thresholds));
i = 0;
for threshold = thresholds
i = i + 1;
graph_structures{i} = (numeric_graph_structure >= threshold);
end
end
|
github
|
hanshuting/graph_ensemble-master
|
infer_structures_with_given_densities.m
|
.m
|
graph_ensemble-master/src/structure_learning/simple_infer_structure/infer_structures_with_given_densities.m
| 3,368 |
utf_8
|
2d5f3acec6c44a1c2da18589aa93b321
|
% SIMPLE_INFER_STRUCTURE Infers the structure of MRF of binary variables based on samples
% This is a cleaned up version of the INFER_STRUCTURE function, holding
% only options that matter most.
%
% Besides that, this model return graph for multiple thresholds without
% repeating the lasso regression.
%
% Input
% samples: logical matrix where each row is a sample and each column a node
% relative_lambda: relative regularization factor (relative to the lambda
% that drives all coefficients to zero.
% thresholds: vector of thresholds to be tried.
%
% Return
% graph_structures: cell array, each one containing a adjacency matrix to
% the respective threshold
function [graph_structures,numeric_graph_structure] = infer_structures_with_given_densities(samples, relative_lambda, densities)
% parse input arguments
parser = inputParser;
is_logical_matrix = @(x) ismatrix(x) && islogical(x);
parser.addRequired('samples', is_logical_matrix);
parser.addRequired('relative_lambda', @isnumeric);
parser.addRequired('densities', @isnumeric);
parser.parse(samples, relative_lambda, densities);
node_count = size(samples,2);
coefficients = lasso_node_by_node(samples,relative_lambda);
% Remove descripancies
symmetric_coefficients = coefficients .* coefficients';
% if there are negative values in the symmetric coefficients means that
% one edge was predicted to be both attractive and repulsive in the two
% different lassos. We will just zero those variables (at the moment I
% wrote the code 10/1810 edges would have this problem)
negative_values_indexes = find(symmetric_coefficients < 0);
if negative_values_indexes
fprintf('Found %d/%d edges that had contradicting weight signs in both lassos. Zero these coefficients\n', length(negative_values_indexes), length(find(symmetric_coefficients > 0)));
symmetric_coefficients(negative_values_indexes) = 0;
end
% numeric graph structure
numeric_graph_structure = (coefficients + coefficients');
% for each given density produce an adjacency matrix
graph_structures = cell(1,numel(densities));
i = 0;
for density = densities
% now let's find what is the threshold we should use to get a certain density
threshold = quantile(vecUT(symmetric_coefficients), 1 - density);
if ~threshold
fprintf('Lambda is too big, such that it is not possible to achieve the desired graph density.\n');
fprintf('Target was %d edges, but only able to identify %d non-zero coefficients\n', ...
nchoosek(node_count, 2) * density, length(find(vecUT(symmetric_coefficients) > 0)));
threshold = 0;
end
% now identify the indexes of the edges that will be kept
i = i + 1;
graph_structures{i} = logical(symmetric_coefficients > threshold);
fprintf('Report\n');
fprintf('Total possible edges: %i\n', nchoosek(node_count, 2));
fprintf('Density wanted: %f%%\n', density * 100);
fprintf('Edges wanted: %i\n', density * nchoosek(node_count, 2));
fprintf('Non-zero coefficients: %i\n', length(find(vecUT(symmetric_coefficients) > 0)));
fprintf('Selected edges: %i\n', length(find(vecUT(symmetric_coefficients) > threshold)));
end
end
|
github
|
hanshuting/graph_ensemble-master
|
lasso_node_by_node_old.m
|
.m
|
graph_ensemble-master/src/structure_learning/simple_infer_structure/lasso_node_by_node_old.m
| 2,786 |
utf_8
|
dd66948eed4f923240712e0ca1e02d9c
|
% LASSO_NODE_BY_NODE Tries to predict one variable as a function of another
% and return lasso coefficients in a matrix, where each row refers to a
% lasso logistic regression and each column a coefficient.
%
% Input
% samples: logical matrix where each row is a sample and each column a node
% relative_lambda: relative regularization factor (relative to the lambda
% that drives all coefficients to zero.
% option 'variable_groups': array that marks with integers which variable
% belongs to each group, so a variable is not predicted by variables of
% the same group
%
% Return
% coefficients: matrix where each row refers to a lasso logistic
% regression and each column a coefficient
function [coefficients] = lasso_node_by_node(samples, relative_lambda, varargin)
% parse input arguments
parser = inputParser;
is_logical_matrix = @(x) ismatrix(x) && islogical(x);
parser.addRequired('samples', is_logical_matrix);
parser.addRequired('relative_lambda', @isnumeric);
parser.addParamValue('variable_groups', [], @isnumeric);
parser.parse(samples, relative_lambda, varargin);
variable_groups = parser.Results.variable_groups;
node_count = size(samples,2);
% ensures variable groups is a vector of integers with node count size
if length(variable_groups) == 0
variable_groups = uint8(zeros(1,node_count));
elseif length(variable_groups) ~= node_count
error('variable_group variable must have one element per node');
else
variable_groups = uint8(variable_groups);
end
% each line of the coefficients comes from a regression, there is one
% regression per node, that generates one coefficient per other node
% (but diagonal is zero since we cannot use own node to predict itself,
% and for each line columns corresponding to variables in the same group
% are zero as well).
% We will store these values in the lasso_coefficients square matrix
lasso_coefficients = zeros(node_count);
disp('Starting Lasso Logistic Regression');
% let's try to predict each node based on the others using lasso
for label_node = 1:node_count
% feature nodes are all nodes except the ones in the same group
% (including the node that is being labeled)
group_nodes = find(variable_groups == variable_groups(label_node));
feature_nodes = setdiff(1:node_count, group_nodes);
X = samples(:,feature_nodes);
Y = samples(:,label_node);
B = lassoglm(X,Y, 'binomial', 'LambdaRatio', relative_lambda, 'NumLambda', 2);
lasso_coefficients(label_node, feature_nodes) = B(:,1)';
fprintf('.');
end
fprintf('\n');
coefficients = lasso_coefficients;
end
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
cheegerpartition.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/CodeLSA/helper_functions/cheegerpartition.m
| 548 |
utf_8
|
8e15bda04a98bfb56b6f04e376ed64c4
|
%evaluates the cheeger constant for a given partition
function h=cheegerpartition(group,simMat);
d=sum(simMat,2); %grade of each node (sum of distances on the row)
[IcutA,IcutB]=meshgrid(group-1,2-group); %bool that indicates if a group is connected to A and/or B
IcutAB=and(IcutA,IcutB); %indeces of nodes of A connected to B
cutAB=sum(simMat(find(IcutAB))); %sum of arcs from A to B
%compute the cheeger constant for this partition
h=cutAB/min(sum(d(find(group==1))),sum(d(find(group==2))));
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
evaluatenormalcut.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/CodeLSA/helper_functions/evaluatenormalcut.m
| 889 |
utf_8
|
ca9fd58a1d309f136b115628b7ca3ca5
|
%evaluates the normal cut function
% group is a vector of zeros and ones that indicates the two partitions
% simMat is the similarity matrix
function cost=evaluatenormalcut(group,simMat);
d=sum(simMat,2); %grade of each node (sum of distances on the row)
assocA=sum(d(find(group==0))); %association of cluster A
assocB=sum(d(find(group==1))); %association of cluster B
[IcutA,IcutB]=meshgrid(group,1-group); %bool that indicates if a group is connected to A and/or B
IcutAB=and(IcutA,IcutB); %indeces of nodes of A connected to B
IcutBA=not(or(IcutA,IcutB)); %indeces of nodes of B connected to A
cutAB=sum(simMat(find(IcutAB))); %sum of arcs from A to B
cutBA=sum(simMat(find(IcutBA))); %sum of arcs from B to A
cost=cutAB/assocA+cutBA/assocB; %normal cut cost function
|
github
|
xijunlee/Undergraduate-Thesis-Project-master
|
spectralcluster.m
|
.m
|
Undergraduate-Thesis-Project-master/new_algorithm(lxl)/CodeLSA/helper_functions/spectralcluster.m
| 765 |
utf_8
|
bb76077d06ddfb666bba7353094f70c1
|
% affmat is the affinity matrix A
% k is the number of largest eigenvectors in matrix L
% num_class is the number of classes
%diagmat is the diagonal matrix D^(-0.5)
% Lmat is the matrix L
%X and Y ar matrices formed from eigenvectors of L
% IDX is the clustering results
% errorsum is the distance from kmeans
function [diagMat,LMat,X,Y,IDX,errorsum]= spectralcluster(affMat,k,num_class)
numDT=size(affMat,2);
diagMat= diag((sum(affMat,2)).^(-1./2));
LMat=diagMat*affMat*diagMat;
[v,d]=eigs(LMat,k);
X=v(:,1:k);
normX=(sum(X.^2,2)).^(1./2);
Y=zeros(size(X));
for index=1:numDT
Y(index,:)=X(index,:)./normX(index,1);
end
[IDX,C,sumd] = kmeans(Y,num_class,'EmptyAction','drop','Replicates',10);
%[C,IDX] = kmeans(Y,num_class);
errorsum=1;%sum(sum(sumd));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.