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
Hadisalman/stoec-master
logphi.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/logphi.m
2,261
utf_8
69fbcfc9d9913da15644d5f0a0368d5f
% Safe computation of logphi(z) = log(normcdf(z)) and its derivatives % dlogphi(z) = normpdf(x)/normcdf(x). % The function is based on index 5725 in Hart et al. and gsl_sf_log_erfc_e. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2013-11-13. function [lp,dlp,d2lp,d3lp] = logphi(z) z = real(z); % support for real arguments only lp = zeros(size(z)); % allocate memory id1 = z.*z<0.0492; % first case: close to zero lp0 = -z(id1)/sqrt(2*pi); c = [ 0.00048204; -0.00142906; 0.0013200243174; 0.0009461589032; -0.0045563339802; 0.00556964649138; 0.00125993961762116; -0.01621575378835404; 0.02629651521057465; -0.001829764677455021; 2*(1-pi/3); (4-pi)/3; 1; 1]; f = 0; for i=1:14, f = lp0.*(c(i)+f); end, lp(id1) = -2*f-log(2); id2 = z<-11.3137; % second case: very small r = [ 1.2753666447299659525; 5.019049726784267463450; 6.1602098531096305441; 7.409740605964741794425; 2.9788656263939928886 ]; q = [ 2.260528520767326969592; 9.3960340162350541504; 12.048951927855129036034; 17.081440747466004316; 9.608965327192787870698; 3.3690752069827527677 ]; num = 0.5641895835477550741; for i=1:5, num = -z(id2).*num/sqrt(2) + r(i); end den = 1.0; for i=1:6, den = -z(id2).*den/sqrt(2) + q(i); end e = num./den; lp(id2) = log(e/2) - z(id2).^2/2; id3 = ~id2 & ~id1; lp(id3) = log(erfc(-z(id3)/sqrt(2))/2); % third case: rest if nargout>1 % compute first derivative dlp = zeros(size(z)); % allocate memory dlp( id2) = abs(den./num) * sqrt(2/pi); % strictly positive first derivative dlp(~id2) = exp(-z(~id2).*z(~id2)/2-lp(~id2))/sqrt(2*pi); % safe computation if nargout>2 % compute second derivative d2lp = -dlp.*abs(z+dlp); % strictly negative second derivative if nargout>3 % compute third derivative d3lp = -d2lp.*abs(z+2*dlp)-dlp; % strictly positive third derivative end end end
github
Hadisalman/stoec-master
gauher.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/gauher.m
2,245
utf_8
441ef6c145fe66f1b7ca9da6207f6003
% compute abscissas and weight factors for Gaussian-Hermite quadrature % % CALL: [x,w] = gauher(N) % % x = base points (abscissas) % w = weight factors % N = number of base points (abscissas) (integrates an up to (2N-1)th order % polynomial exactly) % % p(x)=exp(-x^2/2)/sqrt(2*pi), a =-Inf, b = Inf % % The Gaussian Quadrature integrates a (2n-1)th order % polynomial exactly and the integral is of the form % b N % Int ( p(x)* F(x) ) dx = Sum ( w_j* F( x_j ) ) % a j=1 % % this procedure uses the coefficients a(j), b(j) of the % recurrence relation % % b p (x) = (x - a ) p (x) - b p (x) % j j j j-1 j-1 j-2 % % for the various classical (normalized) orthogonal polynomials, % and the zero-th moment % % 1 = integral w(x) dx % % of the given polynomial's weight function w(x). Since the % polynomials are orthonormalized, the tridiagonal matrix is % guaranteed to be symmetric. function [x,w]=gauher(N) if N==20 % return precalculated values x=[ -7.619048541679757;-6.510590157013656;-5.578738805893203; -4.734581334046057;-3.943967350657318;-3.18901481655339 ; -2.458663611172367;-1.745247320814127;-1.042945348802751; -0.346964157081356; 0.346964157081356; 1.042945348802751; 1.745247320814127; 2.458663611172367; 3.18901481655339 ; 3.943967350657316; 4.734581334046057; 5.578738805893202; 6.510590157013653; 7.619048541679757]; w=[ 0.000000000000126; 0.000000000248206; 0.000000061274903; 0.00000440212109 ; 0.000128826279962; 0.00183010313108 ; 0.013997837447101; 0.061506372063977; 0.161739333984 ; 0.260793063449555; 0.260793063449555; 0.161739333984 ; 0.061506372063977; 0.013997837447101; 0.00183010313108 ; 0.000128826279962; 0.00000440212109 ; 0.000000061274903; 0.000000000248206; 0.000000000000126 ]; else b = sqrt( (1:N-1)/2 )'; [V,D] = eig( diag(b,1) + diag(b,-1) ); w = V(1,:)'.^2; x = sqrt(2)*diag(D); end
github
Hadisalman/stoec-master
elsympol.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/elsympol.m
699
utf_8
33e751b982c07eb890d26629bf71f595
% Evaluate the order R elementary symmetric polynomial Newton's identity aka % the Newton–Girard formulae: http://en.wikipedia.org/wiki/Newton's_identities % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2010-01-10. function E = elsympol(Z,R) % evaluate 'power sums' of the individual terms in Z sz = size(Z); P = zeros([sz(1:2),R]); for r=1:R, P(:,:,r) = sum(Z.^r,3); end E = zeros([sz(1:2),R+1]); % E(:,:,r+1) yields polynomial r E(:,:,1) = ones(sz(1:2)); if R==0, return, end % init recursion E(:,:,2) = P(:,:,1); if R==1, return, end % init recursion for r=2:R for i=1:r E(:,:,r+1) = E(:,:,r+1) + P(:,:,i).*E(:,:,r+1-i)*(-1)^(i-1)/r; end end
github
Hadisalman/stoec-master
minimize.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/minimize.m
11,191
utf_8
69603a3c319cf5374483af20b033f10e
function [X, fX, i] = minimize(X, f, length, varargin) % Minimize a differentiable multivariate function using conjugate gradients. % % Usage: [X, fX, i] = minimize(X, f, length, P1, P2, P3, ... ) % % X initial guess; may be of any type, including struct and cell array % f the name or pointer to the function to be minimized. The function % f must return two arguments, the value of the function, and it's % partial derivatives wrt the elements of X. The partial derivative % must have the same type as X. % length length of the run; if it is positive, it gives the maximum number of % line searches, if negative its absolute gives the maximum allowed % number of function evaluations. Optionally, length can have a second % component, which will indicate the reduction in function value to be % expected in the first line-search (defaults to 1.0). % P1, P2, ... parameters are passed to the function f. % % X the returned solution % fX vector of function values indicating progress made % i number of iterations (line searches or function evaluations, % depending on the sign of "length") used at termination. % % The function returns when either its length is up, or if no further progress % can be made (ie, we are at a (local) minimum, or so close that due to % numerical problems, we cannot get any closer). NOTE: If the function % terminates within a few iterations, it could be an indication that the % function values and derivatives are not consistent (ie, there may be a bug in % the implementation of your "f" function). % % The Polack-Ribiere flavour of conjugate gradients is used to compute search % directions, and a line search using quadratic and cubic polynomial % approximations and the Wolfe-Powell stopping criteria is used together with % the slope ratio method for guessing initial step sizes. Additionally a bunch % of checks are made to make sure that exploration is taking place and that % extrapolation will not be unboundedly large. % % See also: checkgrad % % Copyright (C) 2001 - 2010 by Carl Edward Rasmussen, 2010-01-03 INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket EXT = 3.0; % extrapolate maximum 3 times the current step-size MAX = 20; % max 20 function evaluations per line search RATIO = 10; % maximum allowed slope ratio SIG = 0.1; RHO = SIG/2; % SIG and RHO are the constants controlling the Wolfe- % Powell conditions. SIG is the maximum allowed absolute ratio between % previous and new slopes (derivatives in the search direction), thus setting % SIG to low (positive) values forces higher precision in the line-searches. % RHO is the minimum allowed fraction of the expected (from the slope at the % initial point in the linesearch). Constants must satisfy 0 < RHO < SIG < 1. % Tuning of SIG (depending on the nature of the function to be optimized) may % speed up the minimization; it is probably not worth playing much with RHO. % The code falls naturally into 3 parts, after the initial line search is % started in the direction of steepest descent. 1) we first enter a while loop % which uses point 1 (p1) and (p2) to compute an extrapolation (p3), until we % have extrapolated far enough (Wolfe-Powell conditions). 2) if necessary, we % enter the second loop which takes p2, p3 and p4 chooses the subinterval % containing a (local) minimum, and interpolates it, unil an acceptable point % is found (Wolfe-Powell conditions). Note, that points are always maintained % in order p0 <= p1 <= p2 < p3 < p4. 3) compute a new search direction using % conjugate gradients (Polack-Ribiere flavour), or revert to steepest if there % was a problem in the previous line-search. Return the best value so far, if % two consecutive line-searches fail, or whenever we run out of function % evaluations or line-searches. During extrapolation, the "f" function may fail % either with an error or returning Nan or Inf, and minimize should handle this % gracefully. if max(size(length)) == 2, red=length(2); length=length(1); else red=1; end if length>0, S='Linesearch'; else S='Function evaluation'; end i = 0; % zero the run length counter ls_failed = 0; % no previous line search has failed [f0 df0] = feval(f, X, varargin{:}); % get function value and gradient Z = X; X = unwrap(X); df0 = unwrap(df0); fprintf('%s %6i; Value %4.6e\r', S, i, f0); if exist('fflush','builtin') fflush(stdout); end fX = f0; i = i + (length<0); % count epochs?! s = -df0; d0 = -s'*s; % initial search direction (steepest) and slope x3 = red/(1-d0); % initial step is red/(|s|+1) while i < abs(length) % while not finished i = i + (length>0); % count iterations?! X0 = X; F0 = f0; dF0 = df0; % make a copy of current values if length>0, M = MAX; else M = min(MAX, -length-i); end while 1 % keep extrapolating as long as necessary x2 = 0; f2 = f0; d2 = d0; f3 = f0; df3 = df0; success = 0; while ~success && M > 0 try M = M - 1; i = i + (length<0); % count epochs?! [f3 df3] = feval(f, rewrap(Z,X+x3*s), varargin{:}); df3 = unwrap(df3); if isnan(f3) || isinf(f3) || any(isnan(df3)+isinf(df3)), error(' '),end success = 1; catch % catch any error which occured in f x3 = (x2+x3)/2; % bisect and try again end end if f3 < F0, X0 = X+x3*s; F0 = f3; dF0 = df3; end % keep best values d3 = df3'*s; % new slope if d3 > SIG*d0 || f3 > f0+x3*RHO*d0 || M == 0 % are we done extrapolating? break end x1 = x2; f1 = f2; d1 = d2; % move point 2 to point 1 x2 = x3; f2 = f3; d2 = d3; % move point 3 to point 2 A = 6*(f1-f2)+3*(d2+d1)*(x2-x1); % make cubic extrapolation B = 3*(f2-f1)-(2*d1+d2)*(x2-x1); x3 = x1-d1*(x2-x1)^2/(B+sqrt(B*B-A*d1*(x2-x1))); % num. error possible, ok! if ~isreal(x3) || isnan(x3) || isinf(x3) || x3 < 0 % num prob | wrong sign? x3 = x2*EXT; % extrapolate maximum amount elseif x3 > x2*EXT % new point beyond extrapolation limit? x3 = x2*EXT; % extrapolate maximum amount elseif x3 < x2+INT*(x2-x1) % new point too close to previous point? x3 = x2+INT*(x2-x1); end end % end extrapolation while (abs(d3) > -SIG*d0 || f3 > f0+x3*RHO*d0) && M > 0 % keep interpolating if d3 > 0 || f3 > f0+x3*RHO*d0 % choose subinterval x4 = x3; f4 = f3; d4 = d3; % move point 3 to point 4 else x2 = x3; f2 = f3; d2 = d3; % move point 3 to point 2 end if f4 > f0 x3 = x2-(0.5*d2*(x4-x2)^2)/(f4-f2-d2*(x4-x2)); % quadratic interpolation else A = 6*(f2-f4)/(x4-x2)+3*(d4+d2); % cubic interpolation B = 3*(f4-f2)-(2*d2+d4)*(x4-x2); x3 = x2+(sqrt(B*B-A*d2*(x4-x2)^2)-B)/A; % num. error possible, ok! end if isnan(x3) || isinf(x3) x3 = (x2+x4)/2; % if we had a numerical problem then bisect end x3 = max(min(x3, x4-INT*(x4-x2)),x2+INT*(x4-x2)); % don't accept too close [f3 df3] = feval(f, rewrap(Z,X+x3*s), varargin{:}); df3 = unwrap(df3); if f3 < F0, X0 = X+x3*s; F0 = f3; dF0 = df3; end % keep best values M = M - 1; i = i + (length<0); % count epochs?! d3 = df3'*s; % new slope end % end interpolation if abs(d3) < -SIG*d0 && f3 < f0+x3*RHO*d0 % if line search succeeded X = X+x3*s; f0 = f3; fX = [fX' f0]'; % update variables fprintf('%s %6i; Value %4.6e\r', S, i, f0); if exist('fflush','builtin') fflush(stdout); end s = (df3'*df3-df0'*df3)/(df0'*df0)*s - df3; % Polack-Ribiere CG direction df0 = df3; % swap derivatives d3 = d0; d0 = df0'*s; if d0 > 0 % new slope must be negative s = -df0; d0 = -s'*s; % otherwise use steepest direction end x3 = x3 * min(RATIO, d3/(d0-realmin)); % slope ratio but max RATIO ls_failed = 0; % this line search did not fail else X = X0; f0 = F0; df0 = dF0; % restore best point so far if ls_failed || i > abs(length) % line search failed twice in a row break; % or we ran out of time, so we give up end s = -df0; d0 = -s'*s; % try steepest x3 = 1/(1-d0); ls_failed = 1; % this line search failed end end X = rewrap(Z,X); fprintf('\n'); if exist('fflush','builtin') fflush(stdout); end function v = unwrap(s) % Extract the numerical values from "s" into the column vector "v". The % variable "s" can be of any type, including struct and cell array. % Non-numerical elements are ignored. See also the reverse rewrap.m. v = []; if isnumeric(s) v = s(:); % numeric values are recast to column vector elseif isstruct(s) v = unwrap(struct2cell(orderfields(s))); % alphabetize, conv to cell, recurse elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially v = [v; unwrap(s{i})]; end end % other types are ignored function [s v] = rewrap(s, v) % Map the numerical elements in the vector "v" onto the variables "s" which can % be of any type. The number of numerical elements must match; on exit "v" % should be empty. Non-numerical entries are just copied. See also unwrap.m. if isnumeric(s) if numel(v) < numel(s) error('The vector for conversion contains too few elements') end s = reshape(v(1:numel(s)), size(s)); % numeric values are reshaped v = v(numel(s)+1:end); % remaining arguments passed on elseif isstruct(s) [s p] = orderfields(s); p(p) = 1:numel(p); % alphabetize, store ordering [t v] = rewrap(struct2cell(s), v); % convert to cell, recurse s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially [s{i} v] = rewrap(s{i}, v); end end % other types are not processed
github
Hadisalman/stoec-master
minimize_v2.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/minimize_v2.m
11,952
utf_8
d8aad9cf50639371a892fbcc202eed7c
% minimize.m - minimize a smooth differentiable multivariate function using % LBFGS (Limited memory LBFGS) or CG (Conjugate Gradients) % Usage: [X, fX, i] = minimize(X, F, p, other, ... ) % where % X is an initial guess (any type: vector, matrix, cell array, struct) % F is the objective function (function pointer or name) % p parameters - if p is a number, it corresponds to p.length below % p.length allowed 1) # linesearches or 2) if -ve minus # func evals % p.method minimization method, 'BFGS', 'LBFGS' or 'CG' % p.verbosity 0 quiet, 1 line, 2 line + warnings (default), 3 graphical % p.mem number of directions used in LBFGS (default 100) % other, ... other parameters, passed to the function F % X returned minimizer % fX vector of function values showing minimization progress % i final number of linesearches or function evaluations % The function F must take the following syntax [f, df] = F(X, other, ...) % where f is the function value and df its partial derivatives. The types of X % and df must be identical (vector, matrix, cell array, struct, etc). % % Copyright (C) 1996 - 2011 by Carl Edward Rasmussen, 2011-10-13. % Permission is hereby granted, free of charge, to any person OBTAINING A COPY % OF THIS SOFTWARE AND ASSOCIATED DOCUMENTATION FILES (THE "SOFTWARE"), TO DEAL % IN THE SOFTWARE WITHOUT RESTRICTION, INCLUDING WITHOUT LIMITATION THE RIGHTS % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell % copies of the Software, and to permit persons to whom the Software is % furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER % LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, % OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE % SOFTWARE. function [X, fX, i] = minimize(X, F, p, varargin) if isnumeric(p), p = struct('length', p); end % convert p to struct if p.length > 0, p.S = 'linesearch #'; else p.S = 'function evaluation #'; end; x = unwrap(X); % convert initial guess to vector if ~isfield(p,'method'), if length(x) > 1000, p.method = @LBFGS; else p.method = @BFGS; end; end % set default method if ~isfield(p,'verbosity'), p.verbosity = 2; end % default 1 line text output if ~isfield(p,'MFEPLS'), p.MFEPLS = 10; end % Max Func Evals Per Line Search if ~isfield(p,'MSR'), p.MSR = 100; end % Max Slope Ratio default f(F, X, varargin{:}); % set up the function f [fx, dfx] = f(x); % initial function value and derivatives if p.verbosity, printf('Initial Function Value %4.6e\r', fx); end if p.verbosity > 2, clf; subplot(211); hold on; xlabel(p.S); ylabel('function value'); plot(p.length < 0, fx, '+'); drawnow; end [x, fX, i] = feval(p.method, x, fx, dfx, p); % minimize using direction method X = rewrap(X, x); % convert answer to original representation if p.verbosity, printf('\n'); end function [x, fx, i] = CG(x0, fx0, dfx0, p) if ~isfield(p, 'SIG'), p.SIG = 0.1; end % default for line search quality i = p.length < 0; ok = 0; % initialize resource counter r = -dfx0; s = -r'*r; b = -1/(s-1); bs = -1; fx = fx0; % steepest descent while i < abs(p.length) b = b*bs/min(b*s,bs/p.MSR); % suitable initial step size using slope ratio [x, b, fx0, dfx, i] = lineSearch(x0, fx0, dfx0, r, s, b, i, p); if i < 0 % if line search failed i = -i; if ok, ok = 0; r = -dfx; else break; end % try steepest or stop else ok = 1; bs = b*s; % record step times slope (for slope ratio method) r = (dfx'*(dfx-dfx0))/(dfx0'*dfx0)*r - dfx; % Polack-Ribiere CG end s = r'*dfx; if s >= 0, r = -dfx; s = r'*dfx; ok = 0; end % slope must be -ve x0 = x; dfx0 = dfx; fx = [fx; fx0]; % replace old values with new ones end function [x, fx, i] = BFGS(x0, fx0, dfx0, p) if ~isfield(p, 'SIG'), p.SIG = 0.5; end % default for line search quality i = p.length < 0; ok = 0; % initialize resource counter x = x0; fx = fx0; r = -dfx0; s = -r'*r; b = -1/(s-1); H = eye(length(x0)); while i < abs(p.length) [x, b, fx0, dfx, i] = lineSearch(x0, fx0, dfx0, r, s, b, i, p); if i < 0 i = -i; if ok, ok = 0; else break; end; % try steepest or stop else ok = 1; t = x - x0; y = dfx - dfx0; ty = t'*y; Hy = H*y; H = H + (ty+y'*Hy)/ty^2*t*t' - 1/ty*Hy*t' - 1/ty*t*Hy'; % BFGS update end r = -H*dfx; s = r'*dfx; x0 = x; dfx0 = dfx; fx = [fx; fx0]; end function [x, fx, i] = LBFGS(x0, fx0, dfx0, p) if ~isfield(p, 'SIG'), p.SIG = 0.5; end % default for line search quality n = length(x0); k = 0; ok = 0; x = x0; fx = fx0; bs = -1/p.MSR; if isfield(p, 'mem'), m = p.mem; else m = min(100, n); end % set memory size a = zeros(1, m); t = zeros(n, m); y = zeros(n, m); % allocate memory i = p.length < 0; % initialize resource counter while i < abs(p.length) q = dfx0; for j = rem(k-1:-1:max(0,k-m),m)+1 a(j) = t(:,j)'*q/rho(j); q = q-a(j)*y(:,j); end if k == 0, r = -q/(q'*q); else r = -t(:,j)'*y(:,j)/(y(:,j)'*y(:,j))*q; end for j = rem(max(0,k-m):k-1,m)+1 r = r-t(:,j)*(a(j)+y(:,j)'*r/rho(j)); end s = r'*dfx0; if s >= 0, r = -dfx0; s = r'*dfx0; k = 0; ok = 0; end b = bs/min(bs,s/p.MSR); % suitable initial step size (usually 1) if isnan(r) | isinf(r) % if nonsense direction i = -i; % try steepest or stop else [x, b, fx0, dfx, i] = lineSearch(x0, fx0, dfx0, r, s, b, i, p); end if i < 0 % if line search failed i = -i; if ok, ok = 0; k = 0; else break; end % try steepest or stop else j = rem(k,m)+1; t(:,j) = x-x0; y(:,j) = dfx-dfx0; rho(j) = t(:,j)'*y(:,j); ok = 1; k = k+1; bs = b*s; end x0 = x; dfx0 = dfx; fx = [fx; fx0]; % replace and add values end function [x, a, fx, df, i] = lineSearch(x0, f0, df0, d, s, a, i, p) if p.length < 0, LIMIT = min(p.MFEPLS, -i-p.length); else LIMIT = p.MFEPLS; end p0.x = 0.0; p0.f = f0; p0.df = df0; p0.s = s; p1 = p0; % init p0 and p1 j = 0; p3.x = a; wp(p0, p.SIG, 0); % set step & Wolfe-Powell conditions if p.verbosity > 2 A = [-a a]/5; nd = norm(d); subplot(212); hold off; plot(0, f0, 'k+'); hold on; plot(nd*A, f0+s*A, 'k-'); xlabel('distance in line search direction'); ylabel('function value'); end while 1 % keep extrapolating as long as necessary ok = 0; while ~ok & j < LIMIT try % try, catch and bisect to safeguard extrapolation evaluation j = j+1; [p3.f p3.df] = f(x0+p3.x*d); p3.s = p3.df'*d; ok = 1; if isnan(p3.f+p3.s) | isinf(p3.f+p3.s) error('Objective function returned Inf or NaN',''); end; catch if p.verbosity > 1, printf('\n'); warning(lasterr); end % warn or silence p3.x = (p1.x+p3.x)/2; ok = 0; p3.f = NaN; % bisect, and retry end end if p.verbosity > 2 plot(nd*p3.x, p3.f, 'b+'); plot(nd*(p3.x+A), p3.f+p3.s*A, 'b-'); drawnow end if wp(p3) | j >= LIMIT, break; end % done? p0 = p1; p1 = p3; % move points back one unit p3.x = p0.x + minCubic(p1.x-p0.x, p1.f-p0.f, p0.s, p1.s, 1); % cubic extrap end while 1 % keep interpolating as long as necessary if p1.f > p3.f, p2 = p3; else p2 = p1; end % make p2 the best so far if wp(p2) > 1 | j >= LIMIT, break; end % done? p2.x = p1.x + minCubic(p3.x-p1.x, p3.f-p1.f, p1.s, p3.s, 0); % cubic interp j = j+1; [p2.f p2.df] = f(x0+p2.x*d); p2.s = p2.df'*d; if p.verbosity > 2 plot(nd*p2.x, p2.f, 'r+'); plot(nd*(p2.x+A), p2.f+p2.s*A, 'r'); drawnow end if wp(p2) > -1 & p2.s > 0 | wp(p2) < -1, p3 = p2; else p1 = p2; end % bracket end x = x0+p2.x*d; fx = p2.f; df = p2.df; a = p2.x; % return the value found if p.length < 0, i = i+j; else i = i+1; end % count func evals or line searches if p.verbosity, printf('%s %6i; value %4.6e\r', p.S, i, fx); end if wp(p2) < 2, i = -i; end % indicate faliure if p.verbosity > 2 if i>0, plot(norm(d)*p2.x, fx, 'go'); end subplot(211); plot(abs(i), fx, '+'); drawnow; end function z = minCubic(x, df, s0, s1, extr) % minimizer of approximating cubic INT = 0.1; EXT = 5.0; % interpolate and extrapolation limits A = -6*df+3*(s0+s1)*x; B = 3*df-(2*s0+s1)*x; if B<0, z = s0*x/(s0-s1); else z = -s0*x*x/(B+sqrt(B*B-A*s0*x)); end if extr % are we extrapolating? if ~isreal(z) | ~isfinite(z) | z < x | z > x*EXT, z = EXT*x; end % fix bad z z = max(z, (1+INT)*x); % extrapolate by at least INT else % else, we are interpolating if ~isreal(z) | ~isfinite(z) | z < 0 | z > x, z = x/2; end; % fix bad z z = min(max(z, INT*x), (1-INT)*x); % at least INT away from the boundaries end function y = wp(p, SIG, RHO) persistent a b c sig rho; if nargin == 3 % if three arguments, then set up the Wolfe-Powell conditions a = RHO*p.s; b = p.f; c = -SIG*p.s; sig = SIG; rho = RHO; y= 0; else if p.f > a*p.x+b % function value too large? if a > 0, y = -1; else y = -2; end else if p.s < -c, y = 0; elseif p.s > c, y = 1; else y = 2; end % if sig*abs(p.s) > c, a = rho*p.s; b = p.f-a*p.x; c = sig*abs(p.s); end end end function [fx, dfx] = f(varargin) persistent F p; if nargout == 0 p = varargin; if ischar(p{1}), F = str2func(p{1}); else F = p{1}; end else [fx, dfx] = F(rewrap(p{2}, varargin{1}), p{3:end}); dfx = unwrap(dfx); end function v = unwrap(s) % extract num elements of s (any type) into v (vector) v = []; if isnumeric(s) v = s(:); % numeric values are recast to column vector elseif isstruct(s) v = unwrap(struct2cell(orderfields(s))); % alphabetize, conv to cell, recurse elseif iscell(s) % cell array elements are for i = 1:numel(s), v = [v; unwrap(s{i})]; end % handled sequentially end % other types are ignored function [s v] = rewrap(s, v) % map elements of v (vector) onto s (any type) if isnumeric(s) if numel(v) < numel(s) error('The vector for conversion contains too few elements') end s = reshape(v(1:numel(s)), size(s)); % numeric values are reshaped v = v(numel(s)+1:end); % remaining arguments passed on elseif isstruct(s) [s p] = orderfields(s); p(p) = 1:numel(p); % alphabetize, store ordering [t v] = rewrap(struct2cell(s), v); % convert to cell, recurse s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially [s{i} v] = rewrap(s{i}, v); end end % other types are not processed function printf(varargin) fprintf(varargin{:}); if exist('fflush','builtin'), fflush(stdout); end
github
Hadisalman/stoec-master
sq_dist.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/sq_dist.m
1,967
utf_8
75b906d47729b33d7567f1353ced2f83
% sq_dist - a function to compute a matrix of all pairwise squared distances % between two sets of vectors, stored in the columns of the two matrices, a % (of size D by n) and b (of size D by m). If only a single argument is given % or the second matrix is empty, the missing matrix is taken to be identical % to the first. % % Usage: C = sq_dist(a, b) % or: C = sq_dist(a) or equiv.: C = sq_dist(a, []) % % Where a is of size Dxn, b is of size Dxm (or empty), C is of size nxm. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2010-12-13. function C = sq_dist(a, b) if nargin<1 || nargin>3 || nargout>1, error('Wrong number of arguments.'); end bsx = exist('bsxfun','builtin'); % since Matlab R2007a 7.4.0 and Octave 3.0 if ~bsx, bsx = exist('bsxfun'); end % bsxfun is not yet "builtin" in Octave [D, n] = size(a); % Computation of a^2 - 2*a*b + b^2 is less stable than (a-b)^2 because numerical % precision can be lost when both a and b have very large absolute value and the % same sign. For that reason, we subtract the mean from the data beforehand to % stabilise the computations. This is OK because the squared error is % independent of the mean. if nargin==1 % subtract mean mu = mean(a,2); if bsx a = bsxfun(@minus,a,mu); else a = a - repmat(mu,1,size(a,2)); end b = a; m = n; else [d, m] = size(b); if d ~= D, error('Error: column lengths must agree.'); end mu = (m/(n+m))*mean(b,2) + (n/(n+m))*mean(a,2); if bsx a = bsxfun(@minus,a,mu); b = bsxfun(@minus,b,mu); else a = a - repmat(mu,1,n); b = b - repmat(mu,1,m); end end if bsx % compute squared distances C = bsxfun(@plus,sum(a.*a,1)',bsxfun(@minus,sum(b.*b,1),2*a'*b)); else C = repmat(sum(a.*a,1)',1,m) + repmat(sum(b.*b,1),n,1) - 2*a'*b; end C = max(C,0); % numerical noise can cause C to negative i.e. C > -1e-14
github
Hadisalman/stoec-master
cov_deriv_sq_dist.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/cov_deriv_sq_dist.m
1,906
utf_8
625e697b220630f920d967bce06884e7
% Compute derivative k'(x^p,x^q) of a stationary covariance k(d2) (ard or iso) % w.r.t. to squared distance d2 = (x^p - x^q)'*inv(P)*(x^p - x^q) measure. Here % P is either diagonal with ARD parameters ell_1^2,...,ell_D^2 where D is the % dimension of the input space or ell^2 times the unit matrix for isotropic % covariance. % The derivatives can only be computed for one of the following eight % covariance functions: cov{Matern|PP|RQ|SE}{iso|ard}. % % Copyright (c) by Hannes Nickisch, 2013-10-28. % % See also INFFITC.M, COVFITC.M. function Kp = cov_deriv_sq_dist(cov,hyp,x,z) if nargin<4, z = []; end % make sure, z exists xeqz = numel(z)==0; dg = strcmp(z,'diag') && numel(z)>0; % determine mode if iscell(cov), covstr = cov{1}; else covstr = cov; end if ~ischar(covstr), covstr = func2str(covstr); end if numel([strfind(covstr,'iso'),strfind(covstr,'ard')])==0 error('Only iso|ard covariances allowed for derivatives w.r.t. xu.') elseif numel([strfind(covstr,'covLIN'); strfind(covstr,'covGabor'); strfind(covstr,'covPER')])>0 error('Gabor|LIN|PER covariances not allowed for derivatives w.r.t. xu.') end [n,D] = size(x); if numel(strfind(covstr,'iso')), id = 1:D; else id = 1; end % *iso covariance ell1 = exp(hyp(1)); % first characteristic length scale Kp = feval(cov{:},hyp,x,z,1); % use derivative w.r.t. log(ell(1)) % precompute squared distances if dg % vector kxx d2 = zeros(n,1); else if xeqz % symmetric matrix Kxx d2 = sq_dist(x(:,id)'/ell1); else % cross covariances Kxz d2 = sq_dist(x(:,id)'/ell1,z(:,id)'/ell1); end end Kp = -1/2*Kp./d2; Kp(d2==0) = 0;
github
Hadisalman/stoec-master
unwrap.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/unwrap.m
651
utf_8
47d4deafec9cfdde0a4c291b3825c401
% Extract the numerical values from "s" into the column vector "v". The % variable "s" can be of any type, including struct and cell array. % Non-numerical elements are ignored. See also the reverse rewrap.m. function v = unwrap(s) v = []; if isnumeric(s) v = s(:); % numeric values are recast to column vector elseif isstruct(s) v = unwrap(struct2cell(orderfields(s))); % alphabetize, conv to cell, recurse elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially v = [v; unwrap(s{i})]; end end % other types are ignored
github
Hadisalman/stoec-master
glm_invlink_expexp.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/glm_invlink_expexp.m
427
utf_8
99a5cdb9880a947109671401c7398199
% Compute the log intensity for the inverse link function g(f) = exp(-exp(-f)). % % The function is used in GLM likelihoods such as likPoisson, likGamma, likBeta % and likInvGauss. % % Copyright (c) by Hannes Nickisch, 2013-10-16. function [lg,dlg,d2lg,d3lg] = glm_invlink_expexp(f) lg = -exp(-f); if nargout>1 dlg = -lg; if nargout>2 d2lg = lg; if nargout>2 d3lg = -lg; end end end
github
Hadisalman/stoec-master
glm_invlink_logistic.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/glm_invlink_logistic.m
686
utf_8
b21f086f037b6560c290e0044e0beef5
% Compute the log intensity for the inverse link function g(f) = log(1+exp(f))). % % The function is used in GLM likelihoods such as likPoisson, likGamma, likBeta % and likInvGauss. % % Copyright (c) by Hannes Nickisch, 2013-10-16. function [lg,dlg,d2lg,d3lg] = glm_invlink_logistic(f) l1pef = max(0,f) + log(1+exp(-abs(f))); % safely compute log(1+exp(f)) lg = log(l1pef); id = f<-15; lg(id) = f(id); % fix log(log(1+exp(f))) limits if nargout>1 sm = 1./(1+exp(-f)); dlg = sm./l1pef; dlg(f<-15) = 1; if nargout>2 sp = 1./(1+exp(f)); d2lg = dlg.*(sp-dlg); if nargout>2 d3lg = d2lg.*(sp-2*dlg) - dlg.*sp.*sm; end end end
github
Hadisalman/stoec-master
minimize_v1.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/minimize_v1.m
11,202
utf_8
cd58ba0b83b1121423ed9a53b33562a1
function [X, fX, i] = minimize_old(X, f, length, varargin) % Minimize a differentiable multivariate function using conjugate gradients. % % Usage: [X, fX, i] = minimize(X, f, length, P1, P2, P3, ... ) % % X initial guess; may be of any type, including struct and cell array % f the name or pointer to the function to be minimized. The function % f must return two arguments, the value of the function, and it's % partial derivatives wrt the elements of X. The partial derivative % must have the same type as X. % length length of the run; if it is positive, it gives the maximum number of % line searches, if negative its absolute gives the maximum allowed % number of function evaluations. Optionally, length can have a second % component, which will indicate the reduction in function value to be % expected in the first line-search (defaults to 1.0). % P1, P2, ... parameters are passed to the function f. % % X the returned solution % fX vector of function values indicating progress made % i number of iterations (line searches or function evaluations, % depending on the sign of "length") used at termination. % % The function returns when either its length is up, or if no further progress % can be made (ie, we are at a (local) minimum, or so close that due to % numerical problems, we cannot get any closer). NOTE: If the function % terminates within a few iterations, it could be an indication that the % function values and derivatives are not consistent (ie, there may be a bug in % the implementation of your "f" function). % % The Polack-Ribiere flavour of conjugate gradients is used to compute search % directions, and a line search using quadratic and cubic polynomial % approximations and the Wolfe-Powell stopping criteria is used together with % the slope ratio method for guessing initial step sizes. Additionally a bunch % of checks are made to make sure that exploration is taking place and that % extrapolation will not be unboundedly large. % % See also: checkgrad % % Copyright (C) 2001 - 2010 by Carl Edward Rasmussen, 2010-01-03 INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket EXT = 3.0; % extrapolate maximum 3 times the current step-size MAX = 20; % max 20 function evaluations per line search RATIO = 10; % maximum allowed slope ratio SIG = 0.1; RHO = SIG/2; % SIG and RHO are the constants controlling the Wolfe- % Powell conditions. SIG is the maximum allowed absolute ratio between % previous and new slopes (derivatives in the search direction), thus setting % SIG to low (positive) values forces higher precision in the line-searches. % RHO is the minimum allowed fraction of the expected (from the slope at the % initial point in the linesearch). Constants must satisfy 0 < RHO < SIG < 1. % Tuning of SIG (depending on the nature of the function to be optimized) may % speed up the minimization; it is probably not worth playing much with RHO. % The code falls naturally into 3 parts, after the initial line search is % started in the direction of steepest descent. 1) we first enter a while loop % which uses point 1 (p1) and (p2) to compute an extrapolation (p3), until we % have extrapolated far enough (Wolfe-Powell conditions). 2) if necessary, we % enter the second loop which takes p2, p3 and p4 chooses the subinterval % containing a (local) minimum, and interpolates it, unil an acceptable point % is found (Wolfe-Powell conditions). Note, that points are always maintained % in order p0 <= p1 <= p2 < p3 < p4. 3) compute a new search direction using % conjugate gradients (Polack-Ribiere flavour), or revert to steepest if there % was a problem in the previous line-search. Return the best value so far, if % two consecutive line-searches fail, or whenever we run out of function % evaluations or line-searches. During extrapolation, the "f" function may fail % either with an error or returning Nan or Inf, and minimize should handle this % gracefully. if max(size(length)) == 2, red=length(2); length=length(1); else red=1; end if length>0, S='Linesearch'; else S='Function evaluation'; end i = 0; % zero the run length counter ls_failed = 0; % no previous line search has failed [f0 df0] = feval(f, X, varargin{:}); % get function value and gradient Z = X; X = unwrap(X); df0 = unwrap(df0); fprintf('%s %6i; Value %4.6e\r', S, i, f0); if exist('fflush','builtin') fflush(stdout); end fX = f0; i = i + (length<0); % count epochs?! s = -df0; d0 = -s'*s; % initial search direction (steepest) and slope x3 = red/(1-d0); % initial step is red/(|s|+1) while i < abs(length) % while not finished i = i + (length>0); % count iterations?! X0 = X; F0 = f0; dF0 = df0; % make a copy of current values if length>0, M = MAX; else M = min(MAX, -length-i); end while 1 % keep extrapolating as long as necessary x2 = 0; f2 = f0; d2 = d0; f3 = f0; df3 = df0; success = 0; while ~success && M > 0 try M = M - 1; i = i + (length<0); % count epochs?! [f3 df3] = feval(f, rewrap(Z,X+x3*s), varargin{:}); df3 = unwrap(df3); if isnan(f3) || isinf(f3) || any(isnan(df3)+isinf(df3)), error(''), end success = 1; catch % catch any error which occured in f x3 = (x2+x3)/2; % bisect and try again end end if f3 < F0, X0 = X+x3*s; F0 = f3; dF0 = df3; end % keep best values d3 = df3'*s; % new slope if d3 > SIG*d0 || f3 > f0+x3*RHO*d0 || M == 0 % are we done extrapolating? break end x1 = x2; f1 = f2; d1 = d2; % move point 2 to point 1 x2 = x3; f2 = f3; d2 = d3; % move point 3 to point 2 A = 6*(f1-f2)+3*(d2+d1)*(x2-x1); % make cubic extrapolation B = 3*(f2-f1)-(2*d1+d2)*(x2-x1); x3 = x1-d1*(x2-x1)^2/(B+sqrt(B*B-A*d1*(x2-x1))); % num. error possible, ok! if ~isreal(x3) || isnan(x3) || isinf(x3) || x3 < 0 % num prob | wrong sign? x3 = x2*EXT; % extrapolate maximum amount elseif x3 > x2*EXT % new point beyond extrapolation limit? x3 = x2*EXT; % extrapolate maximum amount elseif x3 < x2+INT*(x2-x1) % new point too close to previous point? x3 = x2+INT*(x2-x1); end end % end extrapolation while (abs(d3) > -SIG*d0 || f3 > f0+x3*RHO*d0) && M > 0 % keep interpolating if d3 > 0 || f3 > f0+x3*RHO*d0 % choose subinterval x4 = x3; f4 = f3; d4 = d3; % move point 3 to point 4 else x2 = x3; f2 = f3; d2 = d3; % move point 3 to point 2 end if f4 > f0 x3 = x2-(0.5*d2*(x4-x2)^2)/(f4-f2-d2*(x4-x2)); % quadratic interpolation else A = 6*(f2-f4)/(x4-x2)+3*(d4+d2); % cubic interpolation B = 3*(f4-f2)-(2*d2+d4)*(x4-x2); x3 = x2+(sqrt(B*B-A*d2*(x4-x2)^2)-B)/A; % num. error possible, ok! end if isnan(x3) || isinf(x3) x3 = (x2+x4)/2; % if we had a numerical problem then bisect end x3 = max(min(x3, x4-INT*(x4-x2)),x2+INT*(x4-x2)); % don't accept too close [f3 df3] = feval(f, rewrap(Z,X+x3*s), varargin{:}); df3 = unwrap(df3); if f3 < F0, X0 = X+x3*s; F0 = f3; dF0 = df3; end % keep best values M = M - 1; i = i + (length<0); % count epochs?! d3 = df3'*s; % new slope end % end interpolation if abs(d3) < -SIG*d0 && f3 < f0+x3*RHO*d0 % if line search succeeded X = X+x3*s; f0 = f3; fX = [fX' f0]'; % update variables fprintf('%s %6i; Value %4.6e\r', S, i, f0); if exist('fflush','builtin') fflush(stdout); end s = (df3'*df3-df0'*df3)/(df0'*df0)*s - df3; % Polack-Ribiere CG direction df0 = df3; % swap derivatives d3 = d0; d0 = df0'*s; if d0 > 0 % new slope must be negative s = -df0; d0 = -s'*s; % otherwise use steepest direction end x3 = x3 * min(RATIO, d3/(d0-realmin)); % slope ratio but max RATIO ls_failed = 0; % this line search did not fail else X = X0; f0 = F0; df0 = dF0; % restore best point so far if ls_failed || i > abs(length) % line search failed twice in a row break; % or we ran out of time, so we give up end s = -df0; d0 = -s'*s; % try steepest x3 = 1/(1-d0); ls_failed = 1; % this line search failed end end X = rewrap(Z,X); fprintf('\n'); if exist('fflush','builtin') fflush(stdout); end % Extract the numerical values from "s" into the column vector "v". The % variable "s" can be of any type, including struct and cell array. % Non-numerical elements are ignored. See also the reverse rewrap.m. function v = unwrap(s) v = []; if isnumeric(s) v = s(:); % numeric values are recast to column vector elseif isstruct(s) v = unwrap(struct2cell(orderfields(s))); % alphabetize, conv to cell, recurse elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially v = [v; unwrap(s{i})]; end end % other types are ignored % Map the numerical elements in the vector "v" onto the variables "s" which can % be of any type. The number of numerical elements must match; on exit "v" % should be empty. Non-numerical entries are just copied. See also unwrap.m. function [s v] = rewrap(s, v) if isnumeric(s) if numel(v) < numel(s) error('The vector for conversion contains too few elements') end s = reshape(v(1:numel(s)), size(s)); % numeric values are reshaped v = v(numel(s)+1:end); % remaining arguments passed on elseif isstruct(s) [s p] = orderfields(s); p(p) = 1:numel(p); % alphabetize, store ordering [t v] = rewrap(struct2cell(s), v); % convert to cell, recurse s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially [s{i} v] = rewrap(s{i}, v); end end % other types are not processed
github
Hadisalman/stoec-master
rewrap.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/rewrap.m
1,014
utf_8
64b6d7c0f51a8c77ddd012370a288b20
% Map the numerical elements in the vector "v" onto the variables "s" which can % be of any type. The number of numerical elements must match; on exit "v" % should be empty. Non-numerical entries are just copied. See also unwrap.m. function [s v] = rewrap(s, v) if isnumeric(s) if numel(v) < numel(s) error('The vector for conversion contains too few elements') end s = reshape(v(1:numel(s)), size(s)); % numeric values are reshaped v = v(numel(s)+1:end); % remaining arguments passed on elseif isstruct(s) [s p] = orderfields(s); p(p) = 1:numel(p); % alphabetize, store ordering [t v] = rewrap(struct2cell(s), v); % convert to cell, recurse s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially [s{i} v] = rewrap(s{i}, v); end end % other types are not processed
github
Hadisalman/stoec-master
solve_chol.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/solve_chol.m
994
utf_8
f4d6cd4b9e7b0a955c2c8709a4894dd3
% solve_chol - solve linear equations from the Cholesky factorization. % Solve A*X = B for X, where A is square, symmetric, positive definite. The % input to the function is R the Cholesky decomposition of A and the matrix B. % Example: X = solve_chol(chol(A),B); % % NOTE: The program code is written in the C language for efficiency and is % contained in the file solve_chol.c, and should be compiled using matlabs mex % facility. However, this file also contains a (less efficient) matlab % implementation, supplied only as a help to people unfamiliar with mex. If % the C code has been properly compiled and is available, it automatically % takes precendence over the matlab code in this file. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2010-09-18. function X = solve_chol(L, B) if nargin ~= 2 || nargout > 1 error('Wrong number of arguments.'); end if size(L,1) ~= size(L,2) || size(L,1) ~= size(B,1) error('Wrong sizes of matrix arguments.'); end X = L\(L'\B);
github
Hadisalman/stoec-master
glm_invlink_logit.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/glm_invlink_logit.m
786
utf_8
b2fc9a03b835c7f6643f37b29eac8c0b
% Compute the log intensity for the inverse link function g(f) = 1/(1+exp(-f)). % % The function is used in GLM likelihoods such as likPoisson, likGamma, likBeta % and likInvGauss. % % Copyright (c) by Hannes Nickisch, 2013-10-16. function varargout = glm_invlink_logit(f) varargout = cell(nargout, 1); % allocate the right number of output arguments [varargout{:}] = glm_invlink_logistic(f); if nargout>0 elg = exp(varargout{1}); varargout{1} = f - elg; if nargout>1 dlg = varargout{2}; varargout{2} = 1 - elg.*dlg; if nargout>2 d2lg = varargout{3}; varargout{3} = -elg.*(dlg.^2+d2lg); if nargout>3 d3lg = varargout{4}; varargout{4} = -elg.*(dlg.^3+3*d2lg.*dlg+d3lg); end end end end
github
Hadisalman/stoec-master
minimize_lbfgsb_gradfun.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/minimize_lbfgsb_gradfun.m
2,390
utf_8
0eca58fc12d068780d735fd5a83ebdfa
function G = minimize_lbfgsb_gradfun(X,varargin) % extract input arguments varargin = varargin{1}; strctX = varargin{2}; f = varargin{1}; % global variables serve as communication interface between calls global minimize_lbfgsb_iteration_number global minimize_lbfgsb_objective global minimize_lbfgsb_gradient global minimize_lbfgsb_X if norm(unwrap(X)-unwrap(minimize_lbfgsb_X))>1e-10 [y,G] = feval(f,rewrap(strctX,X),varargin{3:end}); else y = minimize_lbfgsb_objective(minimize_lbfgsb_iteration_number); G = minimize_lbfgsb_gradient; end % memorise gradient and position minimize_lbfgsb_gradient = G; minimize_lbfgsb_X = X; G = unwrap(G); % Extract the numerical values from "s" into the column vector "v". The % variable "s" can be of any type, including struct and cell array. % Non-numerical elements are ignored. See also the reverse rewrap.m. function v = unwrap(s) v = []; if isnumeric(s) v = s(:); % numeric values are recast to column vector elseif isstruct(s) v = unwrap(struct2cell(orderfields(s)));% alphabetize, conv to cell, recurse elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially v = [v; unwrap(s{i})]; end end % other types are ignored % Map the numerical elements in the vector "v" onto the variables "s" which can % be of any type. The number of numerical elements must match; on exit "v" % should be empty. Non-numerical entries are just copied. See also unwrap.m. function [s v] = rewrap(s, v) if isnumeric(s) if numel(v) < numel(s) error('The vector for conversion contains too few elements') end s = reshape(v(1:numel(s)), size(s)); % numeric values are reshaped v = v(numel(s)+1:end); % remaining arguments passed on elseif isstruct(s) [s p] = orderfields(s); p(p) = 1:numel(p); % alphabetize, store ordering [t v] = rewrap(struct2cell(s), v); % convert to cell, recurse s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially [s{i} v] = rewrap(s{i}, v); end end % other types are not processed
github
Hadisalman/stoec-master
minimize_lbfgsb.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/minimize_lbfgsb.m
4,476
utf_8
10c2d1fef0bdc071cd35d3904c88f0ed
function [X, fX, i] = minimize_lbfgsb(X, f, length, varargin) % Minimize a differentiable multivariate function using quasi Newton. % % Usage: [X, fX, i] = minimize_lbfgsb(X, f, length, P1, P2, P3, ... ) % % X initial guess; may be of any type, including struct and cell array % f the name or pointer to the function to be minimized. The function % f must return two arguments, the value of the function, and it's % partial derivatives wrt the elements of X. The partial derivative % must have the same type as X. % length length of the run; if it is positive, it gives the maximum number of % line searches, if negative its absolute gives the maximum allowed % number of function evaluations. Optionally, length can have a second % component, which will indicate the reduction in function value to be % expected in the first line-search (defaults to 1.0). % P1, P2 ... parameters are passed to the function f. % % X the returned solution % fX vector of function values indicating progress made % i number of iterations (line searches or function evaluations, % depending on the sign of "length") used at termination. % % The function returns when either its length is up, or if no further progress % can be made (ie, we are at a (local) minimum, or so close that due to % numerical problems, we cannot get any closer). NOTE: If the function % terminates within a few iterations, it could be an indication that the % function values and derivatives are not consistent (ie, there may be a bug in % the implementation of your "f" function). % % Copyright (C) 2010 by Hannes Nickisch, 2010-02-05 % global variables serve as communication interface between calls global minimize_lbfgsb_iteration_number global minimize_lbfgsb_objective global minimize_lbfgsb_gradient global minimize_lbfgsb_X % init global variables minimize_lbfgsb_iteration_number = 0; minimize_lbfgsb_objective = Inf; minimize_lbfgsb_gradient = 0*unwrap(X); minimize_lbfgsb_X = X; X0 = X; lb = -Inf*ones(size(unwrap(X0))); ub = Inf*ones(size(unwrap(X0))); maxiter = abs(length); % max number of iterations % no callback routine used so far % m is the number of saved vectors used to estimate the Hessian % factr is the precision 1e-12 X = lbfgsb( unwrap(X0), lb, ub, 'minimize_lbfgsb_objfun', ... 'minimize_lbfgsb_gradfun', ... {f,X0,varargin{:}}, [], ... 'maxiter',maxiter, 'm',4, 'factr',1e-12, 'pgtol',1e-5); i = minimize_lbfgsb_iteration_number; fX = minimize_lbfgsb_objective; X = rewrap(X0,X); % clear global variables clear minimize_lbfgsb_iteration_number clear minimize_lbfgsb_objective clear minimize_lbfgsb_gradient clear minimize_lbfgsb_X % Extract the numerical values from "s" into the column vector "v". The % variable "s" can be of any type, including struct and cell array. % Non-numerical elements are ignored. See also the reverse rewrap.m. function v = unwrap(s) v = []; if isnumeric(s) v = s(:); % numeric values are recast to column vector elseif isstruct(s) v = unwrap(struct2cell(orderfields(s)));% alphabetize, conv to cell, recurse elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially v = [v; unwrap(s{i})]; end end % other types are ignored % Map the numerical elements in the vector "v" onto the variables "s" which can % be of any type. The number of numerical elements must match; on exit "v" % should be empty. Non-numerical entries are just copied. See also unwrap.m. function [s v] = rewrap(s, v) if isnumeric(s) if numel(v) < numel(s) error('The vector for conversion contains too few elements') end s = reshape(v(1:numel(s)), size(s)); % numeric values are reshaped v = v(numel(s)+1:end); % remaining arguments passed on elseif isstruct(s) [s p] = orderfields(s); p(p) = 1:numel(p); % alphabetize, store ordering [t v] = rewrap(struct2cell(s), v); % convert to cell, recurse s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially [s{i} v] = rewrap(s{i}, v); end end % other types are not processed
github
Hadisalman/stoec-master
minimize_lbfgsb_objfun.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/minimize_lbfgsb_objfun.m
2,695
utf_8
d9bbd3614b193a06603c12f33f877104
function y = minimize_lbfgsb_objfun(X,varargin) % extract input arguments varargin = varargin{1}; strctX = varargin{2}; f = varargin{1}; % global variables serve as communication interface between calls global minimize_lbfgsb_iteration_number global minimize_lbfgsb_objective global minimize_lbfgsb_gradient global minimize_lbfgsb_X recompute = 0; if minimize_lbfgsb_iteration_number==0 recompute = 1; else if norm(unwrap(X)-unwrap(minimize_lbfgsb_X))>1e-10 recompute = 1; end end if recompute [y,G] = feval(f,rewrap(strctX,X),varargin{3:end}); else y = minimize_lbfgsb_objective(minimize_lbfgsb_iteration_number); G = minimize_lbfgsb_gradient; end % increase global counter, memorise objective function, gradient and position minimize_lbfgsb_iteration_number = minimize_lbfgsb_iteration_number+1; minimize_lbfgsb_objective(minimize_lbfgsb_iteration_number,1) = y; minimize_lbfgsb_gradient = G; minimize_lbfgsb_X = X; % Extract the numerical values from "s" into the column vector "v". The % variable "s" can be of any type, including struct and cell array. % Non-numerical elements are ignored. See also the reverse rewrap.m. function v = unwrap(s) v = []; if isnumeric(s) v = s(:); % numeric values are recast to column vector elseif isstruct(s) v = unwrap(struct2cell(orderfields(s)));% alphabetize, conv to cell, recurse elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially v = [v; unwrap(s{i})]; end end % other types are ignored % Map the numerical elements in the vector "v" onto the variables "s" which can % be of any type. The number of numerical elements must match; on exit "v" % should be empty. Non-numerical entries are just copied. See also unwrap.m. function [s v] = rewrap(s, v) if isnumeric(s) if numel(v) < numel(s) error('The vector for conversion contains too few elements') end s = reshape(v(1:numel(s)), size(s)); % numeric values are reshaped v = v(numel(s)+1:end); % remaining arguments passed on elseif isstruct(s) [s p] = orderfields(s); p(p) = 1:numel(p); % alphabetize, store ordering [t v] = rewrap(struct2cell(s), v); % convert to cell, recurse s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially [s{i} v] = rewrap(s{i}, v); end end % other types are not processed
github
Hadisalman/stoec-master
logsumexp2.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/logsumexp2.m
454
utf_8
aa7e4f12a67c8f2e12bc5d9113b9abd0
% Compute y = log( sum(exp(x),2) ), the softmax in a numerically safe way by % subtracting the row maximum to avoid cancelation after taking the exp % the sum is done along the rows. % % Copyright (c) by Hannes Nickisch, 2013-10-16. function [y,x] = logsumexp2(logx) N = size(logx,2); max_logx = max(logx,[],2); % we have all values in the log domain, and want to calculate a sum x = exp(logx-max_logx*ones(1,N)); y = log(sum(x,2)) + max_logx;
github
Hadisalman/stoec-master
lik_epquad.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/lik_epquad.m
1,622
utf_8
9f92aef26b02e08fcee8f74617ebd05d
% Compute infEP part of a likelihood function based on the infLaplace part using % Gaussian-Hermite quadrature. % % The function is used in GLM likelihoods such as likPoisson, likGamma, likBeta % and likInvGauss. % % Copyright (c) by Hannes Nickisch, 2013-10-16. function varargout = lik_epquad(lik,hyp,y,mu,s2) n = max([length(y),length(mu),length(s2)]); on = ones(n,1); N = 20; [t,w] = gauher(N); oN = ones(1,N); lw = ones(n,1)*log(w'); y = y(:).*on; mu = mu(:).*on; sig = sqrt(s2(:)).*on; % vectors only [lpi,dlpi,d2lpi] = feval(lik{:},hyp,y*oN,sig*t'+mu*oN,[],'infLaplace'); lZ = s(lpi+lw); dlZ = {}; d2lZ = {}; if nargout>1 % 1st derivative wrt mean % Using p*dlp=dp, p=exp(lp), Z=sum_i wi*pi, dZ = sum_i wi*dpi we obtain % dlZ = sum_i exp(lpi-lZ+lwi)*dlpi = sum_i ai*dlpi. a = exp(lpi - lZ*oN + lw); dlZ = sum(a.*dlpi,2); if nargout>2 % 2nd derivative wrt mean % Using d2lZ=(d2Z*Z-dZ^2)/Z^2 <=> d2Z=Z*(d2lZ+dlZ^2) and % d2Z = sum_i wi*d2Zi, we get d2lZ = sum_i ai*(d2lpi+dlpi^2)-dlZ^2. d2lZ = sum(a.*(d2lpi+dlpi.*dlpi),2) - dlZ.*dlZ; end end varargout = {lZ,dlZ,d2lZ}; % computes y = log( sum(exp(x),2) ), the softmax in a numerically safe way by % subtracting the row maximum to avoid cancelation after taking the exp % the sum is done along the rows function [y,x] = s(logx) N = size(logx,2); max_logx = max(logx,[],2); % we have all values in the log domain, and want to calculate a sum x = exp(logx-max_logx*ones(1,N)); y = log(sum(x,2)) + max_logx;
github
Hadisalman/stoec-master
glm_invlink_exp.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/util/glm_invlink_exp.m
443
utf_8
af4bb74d42054f7b470ed8aecfcf4607
% Compute the log intensity for the inverse link function g(f) = exp(f). % % The function is used in GLM likelihoods such as likPoisson, likGamma, likBeta % and likInvGauss. % % Copyright (c) by Hannes Nickisch, 2013-10-16. function [lg,dlg,d2lg,d3lg] = glm_invlink_exp(f) lg = f; if nargout>1 dlg = ones(size(f)); if nargout>2 d2lg = zeros(size(f)); if nargout>2 d3lg = zeros(size(f)); end end end
github
Hadisalman/stoec-master
covPeriodicNoDC.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/cov/covPeriodicNoDC.m
3,630
utf_8
32d02bd08932f22fe8302ce97b797d39
function K = covPeriodicNoDC(hyp, x, z, i) % Stationary covariance function for a smooth periodic function, with period p: % % k(x,x') = sf^2 * [k0(pi*(x-x')/p) - f(ell)] / [1 - f(ell)] % with k0(t) = exp( -2*sin^2(t)/ell^2 ) and f(ell) = \int 0..pi k0(t) dt. % % The constant (DC component) has been removed and marginal variance is sf^2. % The hyperparameters are: % % hyp = [ log(ell) % log(p) % log(sf) ] % % Note that covPeriodicNoDC converges to covCos as ell goes to infinity. % % Copyright (c) by James Robert Lloyd and Hannes Nickisch 2013-10-21. % % See also COVFUNCTIONS.M, COVCOS.M. if nargin<2, K = '3'; return; end % report number of parameters if nargin<3, z = []; end % make sure, z exists xeqz = numel(z)==0; dg = strcmp(z,'diag') && numel(z)>0; % determine mode [n,D] = size(x); if D>1, error('Covariance is defined for 1d data only.'), end ell = exp(hyp(1)); p = exp(hyp(2)); sf2 = exp(2*hyp(3)); % precompute distances if dg % vector kxx K = zeros(size(x,1),1); else if xeqz % symmetric matrix Kxx K = sqrt(sq_dist(x')); else % cross covariances Kxz K = sqrt(sq_dist(x',z')); end end K = 2*pi*K/p; if nargin<4 % covariances K = sf2*covD(K,ell); else if i==1 if ell>1e4 % limit for ell->infty K = zeros(size(K)); % no further progress in ell possible elseif 1/ell^2<3.75 cK = cos(K); ecK = exp(cK/ell^2); b0 = besseli(0,1/ell^2); b1 = besseli(1,1/ell^2); K = 2*(exp(1/ell^2)-ecK )*b1 ... - 2*(exp(1/ell^2)-ecK.*cK)*b0 ... + 4*exp(2*(cos(K/2)/ell).^2).*sin(K/2).^2; K = sf2/(ell*(exp(1/ell^2)-b0))^2 * K; else cK = cos(K); ecK = exp((cK-1)/ell^2); b0 = embi0(1/ell^2); b1 = embi1(1/ell^2); K = 2*(1-ecK)*b1 - 2*(1-ecK.*cK)*b0 ... + 4*exp(2*(cos(K/2).^2-1)/ell^2).*sin(K/2).^2; K = sf2/(ell*(1-b0))^2 * K; end elseif i==2 if ell>1e4 % limit for ell->infty K = sf2*sin(K).*K; elseif 1/ell^2<3.75 K = exp(cos(K)/ell^2).*sin(K).*K; K = sf2/ell^2/(exp(1/ell^2)-besseli(0,1/ell^2))*K; else K = exp((cos(K)-1)/ell^2).*sin(K).*K; K = sf2/ell^2/(1-embi0(1/ell^2))*K; end elseif i==3 K = 2*sf2*covD(K,ell); else error('Unknown hyperparameter') end end function K = covD(D,ell) % evaluate covariances from distances if ell>1e4 % limit for ell->infty K = cos(D); elseif 1/ell^2<3.75 K = exp(cos(D)/ell^2); b0 = besseli(0,1/ell^2); K = (K-b0)/(exp(1/ell^2)-b0); else K = exp((cos(D)-1)/ell^2); b0 = embi0(1/ell^2); K = (K-b0)/(1-b0); end function y = embi0(x) % = exp(-x)*besseli(0,x) => 9.8.2 Abramowitz & Stegun y = 3.75/x; y = 0.39894228 + 0.01328592*y + 0.00225319*y^2 - 0.00157565*y^3 ... + 0.00916281*y^4 - 0.02057706*y^5 + 0.02635537*y^6 - 0.01647633*y^7 ... + 0.00392377*y^8; y = y/sqrt(x); function y = embi1(x) % = exp(-x)*besseli(1,x) => 9.8.4 Abramowitz & Stegun y = 3.75/x; y = 0.39894228 - 0.03988024*y - 0.00362018*y^2 + 0.00163801*y^3 ... - 0.01031555*y^4 + 0.02282967*y^5 - 0.02895312*y^6 + 0.01787654*y^7 ... - 0.00420059*y^8; y = y/sqrt(x);
github
Hadisalman/stoec-master
covGrid.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/cov/covGrid.m
7,051
utf_8
45064e9c69d8e20f1122e20679e25085
function [K,Mx,xe] = covGrid(cov, xg, hyp, x, z, i) % covGrid - Kronecker covariance function based on a grid. % % The grid g is represented by its p axes xg = {x1,x2,..xp}. An axis xi is of % size (ni,di) and the grid g has size (n1,n2,..,np,D), where D=d1+d2+..+dp. % Hence, the grid contains N=n1*n2*..*np data points. The axes do neither need % to be sorted in any way nor do they need to be 1d i.e. ni>=1. % % The covGrid function can be used to expand the cell array xg into an expanded % multivariate grid xe of size (N,D) via: % [xe,nx,Dx] = covGrid('expand',xg); % The operation can be reverted by: % xg = covGrid('factor',{xe,ng,Dg}); % % The variables v={x,z} can either be a) grid indices or b) data points. % a) The variable v has size (nv,1) and contains integers from [1,N]. Then % the datapoints are obtained as g2 = reshape(g,N,D); v = g2(v,:). % b) The variable v has size (nv,D) and directly represents the data points. % The mechanism works for x and z separately. % % The resulting covariance matrix is given by: % K = kron( kron(...,K{2}), K{1} ) = K_p x .. x K_2 x K_1. % % The hyperparameters are: % hyp = [ hyp_1 % hyp_2 % .. % hyp_p ], % % Copyright (c) by Hannes Nickisch and Andrew Wilson 2014-12-04. % % See also COVFUNCTIONS.M, INFGRID.M. if nargin<2, error('Not enough parameters provided.'), end if strcmp(cov,'expand') % convert between full grid and axes representation [K,Mx,xe] = expandgrid(xg); return elseif strcmp(cov,'factor') K = factorgrid(xg{:}); return end p = numel(xg); ng = zeros(p,1); Dg = zeros(p,1); % number of Kronecker factors if numel(cov)~=p, error('We require p factors.'), end for ii = 1:p % iterate over covariance functions [ng(ii),Dg(ii)] = size(xg{ii}); f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary D = Dg(ii); j(ii) = cellstr(num2str(eval(feval(f{:})))); % collect nbr hypers end if nargin<4 % report number of parameters K = char(j(1)); for ii=2:length(cov), K = [K, '+', char(j(ii))]; end, return end if nargin<5, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode v = []; % v vector indicates to which covariance parameters belong for ii = 1:p, v = [v repmat(ii, 1, eval(char(j(ii))))]; end if nargin==6 && i>length(v), error('Unknown hyperparameter'), end toep = true(p,1); % grid along dimension is equispaced -> Toeplitz structure for ii=1:p if ng(ii)>1 % diagnose Toeplitz structure if data is linearly increasing dev = abs(diff(xg{ii})-ones(ng(ii)-1,1)*(xg{ii}(2,:)-xg{ii}(1,:))); toep(ii) = max(dev(:))<1e-9; end end N = prod(ng); n = size(x,1); D = sum(Dg); % expanded grid and data dimension ix = isidx(x,N); % determine whether x is an index or a data array if dg % evaluate as full dense vector for diagonal covariance case K = 1; % xg is not assumed to form a grid for z = 'diag' for ii = 1:length(cov) % iteration over factor functions f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary d = sum(Dg(1:ii-1))+(1:Dg(ii)); % dimensions of interest if nargin<6, i = 0; vi = 0; else vi = v(i); end; % which covariance function if i<=length(v) if ix, xii = xg{ii}; else xii = x(:,d); end % switch Kronecker/plain prod if ii==vi j = sum(v(1:i)==vi); % which parameter in that covariance Kj = feval(f{:}, hyp(v==ii), xii, z, j); % deriv Kronecker factor else Kj = feval(f{:}, hyp(v==ii), xii, z); % plain Kronecker factor end if ix, K = kron(K,Kj); else K = K.*Kj; end % switch Kronecker/plain prod else error('Unknown hyperparameter') end end if ix, K = K(x); end, return end if ~ix, error('Off-grid input only supported for z.'), end if isidx(z,N); Mz = z; z = covGrid('expand',xg); z = z(Mz,:); end K = cell(p,1); % covariance Kronecker factors for ii = 1:length(cov) % iteration over factor functions f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary d = sum(Dg(1:ii-1))+(1:Dg(ii)); % dimensions of interest if isnumeric(z) && ~isempty(z) % cross terms zd = z(:,d); elseif xeqz && toep(ii) % we have Toeplitz structure zd = xg{ii}(1,:); else % symmetric matrix zd = z; end if nargin<6, i = 0; vi = 0; else vi = v(i); end; % which covariance function if i<=length(v) if ii==vi j = sum(v(1:i)==vi); % which parameter in that covariance K{ii} = feval(f{:}, hyp(v==ii), xg{ii}, zd, j); % deriv Kronecker factor else K{ii} = feval(f{:}, hyp(v==ii), xg{ii}, zd); % plain Kronecker factor end else error('Unknown hyperparameter') end if xeqz && toep(ii), K{ii} = {'toep',K{ii}}; end % make Toeplitz explicit end if ~xeqz % expand cross terms Ks = K; K = Ks{1}; for ii = 2:p, K = kron1(Ks{ii},K); end if ix && (numel(x)~=N || max(abs(x-(1:N)'))>0), K = K(x,:); end end if nargout>1, if ix, Mx = sparse(1:n,x,1,n,N); end, end if nargout>2, xe = covGrid('expand',xg); end % perform kron along first dimension only % the code is equivalent to the following loop % z = zeros(size(x,1)*size(y,1),size(x,2)); % for i=1:size(z,2), z(:,i) = kron(x(:,i),y(:,i)); end function z = kron1(x,y) nx = size(x,1); ny = size(y,1); z = repmat(reshape(x,1,nx,[]),[ny,1,1]).*repmat(reshape(y,ny,1,[]),[1,nx,1]); z = reshape(z,nx*ny,[]); function r = isidx(i,N) % check whether i represents an integer index vector r = false; if numel(i)>0 && ~strcmp(i,'diag') && size(i,2)==1 && ndims(i)==2 if max(abs(i-floor(i)))<1e-13 if 0<min(i) && max(i)<=N, r = true; end end end function [x,ng,Dg] = expandgrid(xg) % expand a Kronecker grid p = numel(xg); x = xg{1}; % expanded grid data ng = zeros(p,1); Dg = zeros(p,1); [ng(1),Dg(1)] = size(xg{1}); for i=2:p szx = size(x); [ng(i),Dg(i)] = size(xg{i}); xold = repmat(reshape(x,[],1,szx(end)),[1,ng(i),1]); xnew = repmat(reshape(xg{i},[1,ng(i),Dg(i)]),[size(xold,1),1,1]); x = reshape(cat(3,xold,xnew),[szx(1:end-1),ng(i),szx(end)+Dg(i)]); end x = reshape(x,[],size(x,ndims(x))); function xg = factorgrid(x,ng,Dg) % factor a Kronecker grid p = numel(ng); xg = cell(p,1); % extract individual grid components xg for i=1:p x = reshape(x,[prod(ng(1:i-1)), ng(i), prod(ng(i+1:end)), sum(Dg)]); xg{i} = reshape(x(1,:,1,sum(Dg(1:i-1))+(1:Dg(i))), ng(i), Dg(i)); end
github
Hadisalman/stoec-master
covPERiso.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/cov/covPERiso.m
3,145
utf_8
7308c3f2001744df0d77cd5dc190c637
function K = covPERiso(cov, hyp, x, z, i) % Stationary periodic covariance function for an isotropic stationary covariance % function k0 such as covMaterniso, covPPiso, covRQiso and covSEiso. % Isotropic stationary means that the covariance function k0(x,z) depends on the % data points x,z only through the squared distance % dxz = (x-z)'*inv(P)*(x-z) where the P matrix is ell^2 times the unit matrix. % The covariance function is parameterized as: % % k(x,z) = k0(u(x),u(z)), u(x) = [sin(pi*x/p); cos(pi*x/p)] % % where the period p belongs to covPERiso and hyp0 belong to k0: % % hyp = [ log(p) % hyp0 ] % % The first hyperparameter of k0 is the log lengthscale hyp0(1) = log(ell). % Note that for k0 = covSEiso and D = 1, a faster alternative is covPeriodic. % % Copyright (c) by Hannes Nickisch, 2013-10-15. % % See also COVFUNCTIONS.M. nocov = false; % default case when no cov argument is provided if nargin==0, cov = {@covSEiso}; nocov = true; end % default case if isnumeric(cov) % detect old version where the cov parameter was missing % i <- z, z <- x, x <- hyp, hyp <- cov if nargin>3, i = z; end if nargin>2, z = x; end if nargin>1, x = hyp; end hyp = cov; cov = {@covSEiso}; nocov = true; end if nocov && nargin<2 || ~nocov && nargin<3 % report number of parameters K = ['(1+',feval(cov{:}),')']; return end if nocov && nargin<3 || ~nocov && nargin<4, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); p = exp(hyp(1)); if nocov && nargin<4 || ~nocov && nargin<5 [x,z] = u(x,z,p,dg); % apply the embedding u:IR^D->IR^2*D K = feval(cov{:},hyp(2:end),x,z); else if i==1 if dg % compute distance d d = zeros([n,1,D]); else if xeqz % symmetric matrix Kxx d = repmat(reshape(x,n,1,D),[1,n, 1])-repmat(reshape(x,1,n, D),[n,1,1]); else % cross covariances Kxz nz = size(z,1); d = repmat(reshape(x,n,1,D),[1,nz,1])-repmat(reshape(z,1,nz,D),[n,1,1]); end end d = 2*pi*d/p; dD2_dlp = -2*sum(sin(d).*d,3); % derivative dD2/dlog(p) [x,z] = u(x,z,p,dg); % apply the embedding u:IR^D->IR^2*D if dg % compute squared distances D2 = zeros(n,1); else if xeqz, D2 = sq_dist(x'); else D2 = sq_dist(x',z'); end end % reconstruct derivative w.r.t. D2 from derivative w.r.t. log(ell) dK_dD2 = feval(cov{:},hyp(2:end),x,z,1)./(-2*D2); dK_dD2(D2<1e-12) = 0; K = dK_dD2.*dD2_dlp; % apply chain rule else [x,z] = u(x,z,p,dg); % apply the embedding u:IR^D->IR^2*D K = feval(cov{:},hyp(2:end),x,z,i-1); end end function [x,z] = u(x,z,p,dg) % apply the embedding u:IR^D->IR^2*D x = 2*pi*x/p; x = [sin(x), cos(x)]; if numel(z)>0 && ~dg, z = 2*pi*z/p; z = [sin(z), cos(z)]; end
github
Hadisalman/stoec-master
covADD.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/cov/covADD.m
3,632
utf_8
45875a6c0e52c3f98448f40f6b6fc599
function K = covADD(cov, hyp, x, z, i) % Additive covariance function using a 1d base covariance function % cov(x^p,x^q;hyp) with individual hyperparameters hyp. % % k(x^p,x^q) = \sum_{r \in R} sf_r \sum_{|I|=r} % \prod_{i \in I} cov(x^p_i,x^q_i;hyp_i) % % hyp = [ hyp_1 % hyp_2 % ... % hyp_D % log(sf_R(1)) % ... % log(sf_R(end)) ] % % where hyp_d are the parameters of the 1d covariance function which are shared % over the different values of R(1) to R(end). % % Please see the paper Additive Gaussian Processes by Duvenaud, Nickisch and % Rasmussen, NIPS, 2011 for details. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2010-09-10. % % See also COVFUNCTIONS.M. R = cov{1}; nh = eval(feval(cov{2})); % number of hypers per individual covariance nr = numel(R); % number of different degrees of interaction if nargin<3 % report number of hyper parameters K = ['D*', int2str(nh), '+', int2str(nr)]; return end if nargin<4, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); % dimensionality sf2 = exp( 2*hyp(D*nh+(1:nr)) ); % signal variances of individual degrees Kd = Kdim(cov{2},hyp,x,z); % evaluate dimensionwise covariances K if nargin<5 % covariances EE = elsympol(Kd,max(R)); % Rth elementary symmetric polynomials K = 0; for ii=1:nr, K = K + sf2(ii)*EE(:,:,R(ii)+1); end % sf2 weighted sum else % derivatives if i <= D*nh % individual covariance function parameters j = fix(1+(i-1)/nh); % j is the dimension of the hyperparameter if dg, zj='diag'; else if xeqz, zj=[]; else zj=z(:,j); end, end dKj = feval(cov{2},hyp(nh*(j-1)+(1:nh)),x(:,j),zj,i-(j-1)*nh); % other dK=0 % the final derivative is a sum of multilinear terms, so if only one term % depends on the hyperparameter under consideration, we can factorise it % out and compute the sum with one degree less E = elsympol(Kd(:,:,[1:j-1,j+1:D]),max(R)-1); % R-1th elementary sym polyn K = 0; for ii=1:nr, K = K + sf2(ii)*E(:,:,R(ii)); end % sf2 weighted sum K = dKj.*K; elseif i <= D*nh+nr EE = elsympol(Kd,max(R)); % Rth elementary symmetric polynomials j = i-D*nh; K = 2*sf2(j)*EE(:,:,R(j)+1); % rest of the sf2 weighted sum else error('Unknown hyperparameter') end end % evaluate dimensionwise covariances K function K = Kdim(cov,hyp,x,z) [n,D] = size(x); % dimensionality nh = eval(feval(cov)); % number of hypers per individual covariance if nargin<4, z = []; end % make sure, z exists xeqz = numel(z)==0; dg = strcmp(z,'diag') && numel(z)>0; % determine mode if dg % allocate memory K = zeros(n,1,D); else if xeqz, K = zeros(n,n,D); else K = zeros(n,size(z,1),D); end end for d=1:D hyp_d = hyp(nh*(d-1)+(1:nh)); % hyperparamter of dimension d if dg K(:,:,d) = feval(cov,hyp_d,x(:,d),'diag'); else if xeqz K(:,:,d) = feval(cov,hyp_d,x(:,d)); else K(:,:,d) = feval(cov,hyp_d,x(:,d),z(:,d)); end end end
github
Hadisalman/stoec-master
covPERard.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/cov/covPERard.m
3,588
utf_8
47dfb8b9857ef5e9bc3693bb6e5c0aa9
function K = covPERard(cov, hyp, x, z, i) % Stationary periodic covariance function for a stationary covariance function % k0 such as covMaternard, covPPard, covRQard and covSEard. % Stationary means that the covariance function k0(x,z) depends on the % data points x,z only through the squared distance % dxz = (x-z)'*inv(P)*(x-z) where the P matrix is diagonal with ARD parameters % ell_1^2,...,ell_D^2, where D is the dimension of the input space. % The covariance function is parameterized as: % % k(x,z) = k0(u(x),u(z)), u(x) = [sin(pi*x/p); cos(pi*x/p)] % % where the period p belongs to covPERiso and hyp0 belong to k0: % % hyp = [ log(p_1) % log(p_2) % . % log(p_D) % hyp0 ] % % The first D hyperparameters of k0 are the log lengthscales such that % hyp0(i) = log(ell(i)) for i=1..D. % Note that for k0 = covSEard and D = 1, a faster alternative is covPeriodic. % % Copyright (c) by Hannes Nickisch, 2013-10-16. % % See also COVFUNCTIONS.M. nocov = false; % default case when no cov argument is provided if nargin==0, cov = {@covSEard}; nocov = true; end % default case if isnumeric(cov) % detect old version where the cov parameter was missing % i <- z, z <- x, x <- hyp, hyp <- cov if nargin>3, i = z; end if nargin>2, z = x; end if nargin>1, x = hyp; end hyp = cov; cov = {@covSEard}; nocov = true; end if nocov && nargin<2 || ~nocov && nargin<3 % report number of parameters K = ['(D+',feval(cov{:}),')']; return end if nocov && nargin<3 || ~nocov && nargin<4, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); p = exp(hyp(1:D)); lell = hyp(D+(1:D)); hyp0 = [lell; lell; hyp(2*D+1:end)]; if nocov && nargin<4 || ~nocov && nargin<5 [x,z] = u(x,z,p,dg); % apply the embedding u:IR^D->IR^2*D K = feval(cov{:},hyp0,x,z); else if i<=D if dg % compute distance d di = zeros([n,1]); else if xeqz % symmetric matrix Kxx di = repmat(reshape(x(:,i),n, 1),[1, n])... -repmat(reshape(x(:,i),1, n),[n, 1]); else % cross covariances Kxz nz = size(z,1); di = repmat(reshape(x(:,i),n, 1),[1,nz])... -repmat(reshape(z(:,i),1,nz),[n, 1]); end end di = 2*pi*di/p(i); dD2_dlpi = -2*sin(di).*di; % derivative dD2i/dlog(p(i)) [x,z] = u(x,z,p,dg); % apply the embedding u:IR^D->IR^2*D if dg % compute squared distances D2 = zeros(n,1); else if xeqz D2 = sq_dist(x(:,[i,i+D])'); else D2 = sq_dist(x(:,[i,i+D])',z(:,[i,i+D])'); end end % reconstruct derivative w.r.t. D2i from derivative w.r.t. log(ell(i)) dK_dD2 = feval(cov{:},hyp0,x,z,i) + feval(cov{:},hyp0,x,z,i+D); dK_dD2 = dK_dD2./(-2*D2); dK_dD2(D2<1e-12) = 0; K = dK_dD2.*dD2_dlpi; % apply chain rule else [x,z] = u(x,z,p,dg); % apply the embedding u:IR^D->IR^2*D if i<=2*D K = feval(cov{:},hyp0,x,z,i-D) + feval(cov{:},hyp0,x,z,i); else K = feval(cov{:},hyp0,x,z,i); end end end function [x,z] = u(x,z,p,dg) % apply the embedding u:IR^D->IR^2*D x = 2*pi*x*diag(1./p); x = [sin(x), cos(x)]; if numel(z)>0 && ~dg, z = 2*pi*z*diag(1./p); z = [sin(z), cos(z)]; end
github
Hadisalman/stoec-master
infMCMC.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/inf/infMCMC.m
10,673
utf_8
346201720f95a22a681c50bd2535b84c
function [post nlZ dnlZ] = infMCMC(hyp, mean, cov, lik, x, y, par) % Markov Chain Monte Carlo (MCMC) sampling from posterior and % Annealed Importance Sampling (AIS) for marginal likelihood estimation. % % The algorithms are not to be used as a black box, since the acceptance rate % of the samplers need to be carefully monitored. Also, there are no derivatives % of the marginal likelihood available. % % There are additional parameters: % - par.sampler switch between the samplers 'hmc' or 'ess' % - par.Nsample num of samples % - par.Nskip num of steps out of which one sample kept % - par.Nburnin num of burn in samples (corresponds to Nskip*Nburning steps) % - par.Nais num of AIS runs to remove finite temperature bias % Default values are 'sampler=hmc', Nsample=200, Nskip=40, Nburnin=10, Nais=3. % % The Hybrid Monte Carlo Sampler (HMC) is implemented as described in the % technical report: Probabilistic Inference using MCMC Methods by Radford Neal, % CRG-TR-93-1, 1993. % % Instead of sampling from f ~ 1/Zf * N(f|m,K) P(y|f), we use a % parametrisation in terms of alpha = inv(K)*(f-m) and sample from % alpha ~ P(a) = 1/Za * N(a|0,inv(K)) P(y|K*a+m) to increase numerical % stability since log P(a) = -(a'*K*a)/2 + log P(y|K*a+m) + C and its % gradient can be computed safely. % % The leapfrog stepsize as a time discretisation stepsize comes with a % tradeoff: % - too small: frequently accept, slow exploration, accurate dynamics % - too large: seldomly reject, fast exploration, inaccurate dynamics % In order to balance between the two extremes, we adaptively adjust the % stepsize in order to keep the acceptance rate close to a target acceptance % rate. Taken from http://deeplearning.net/tutorial/hmc.html. % % The code issues a warning in case the overall acceptance rate did deviate % strongly from the target. This can indicate problems with the sampler. % % The Elliptical Slice Sampler (ESS) is a straight implementation that is % inspired by the code shipped with the paper: Elliptical slice sampling by % Iain Murray, Ryan Prescott Adams and David J.C. MacKay, AISTATS 2010. % % Annealed Importance Sampling (AIS) to determine the marginal likelihood is % described in the technical report: AIS, Radford Neal, 1998. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2012-11-07. % % See also INFMETHODS.M. if nargin<7, par = []; end % analyse parameter structure if isfield(par,'sampler'), alg=par.sampler; else alg = 'hmc'; end if isfield(par,'Nsample'), N =par.Nsample; else N = 200; end if isfield(par,'Nskip'), Ns =par.Nskip; else Ns = 40; end if isfield(par,'Nburnin'), Nb =par.Nburnin; else Nb = 10; end if isfield(par,'Nais'), R =par.Nais; else R = 3; end K = feval(cov{:}, hyp.cov, x); % evaluate the covariance matrix m = feval(mean{:}, hyp.mean, x); % evaluate the mean vector n = size(K,1); [cK,fail] = chol(K); % try an ordinary Cholesky decomposition if fail, sr2 = 1e-8*sum(diag(K))/n; cK = chol(K+sr2*eye(n)); end % regularise T = (N+Nb)*Ns; % overall number of steps [alpha,Na] = sample(K,cK,m,y,lik,hyp.lik, N,Nb,Ns, alg); % sample w/o annealing post.alpha = alpha; al = sum(alpha,2)/N; post.L = -(cK\(cK'\eye(n)) + al*al' - alpha*alpha'/N); % inv(K) - cov(alpha) post.sW = []; post.acceptance_rate_MCMC = Na/T; % additional output parameter if nargout>1 % annealed importance sampling % discrete time t from 1 to T and temperature tau from tau(1)=0 to tau(T)=1 taus = [zeros(1,Nb),linspace(0,1,N)].^4; % annealing schedule, effort at start % the fourth power idea is taken from the Kuss&Rasmussen paper, 2005 JMLR % Z(t) := \int N(f|m,K) lik(f)^taus(t) df hence Z(1) = 1 and Z(T) = Z % Z = Z(T)/Z(1) = prod_t Z(t)/Z(t-1); % ln Z(t)/Z(t-1) = ( tau(t)-tau(t-1) ) * loglik(f_t) lZ = zeros(R,1); dtaus = diff(taus(Nb+(1:N))); % we have: sum(dtaus)==1 for r=1:R [A,Na] = sample(K,cK,m,y,lik,hyp.lik, N,Nb,Ns, alg, taus); % AIS for t=2:N % evaluate the likelihood sample-wise lp = feval(lik{:},hyp.lik,y,K*A(:,t)+m,[],'infLaplace'); lZ(r) = lZ(r)+dtaus(t-1)*sum(lp); end post.acceptance_rate_AIS(r) = Na/T; % additional output parameters end nlZ = log(R)-logsumexp(lZ); % remove finite temperature bias, softmax average if nargout>2 % marginal likelihood derivatives are not computed dnlZ = struct('cov',0*hyp.cov, 'mean',0*hyp.mean, 'lik',0*hyp.lik); end end %% choose between HMC and ESS depending on the alg string function [alpha,Na] = sample(K,cK,m,y,lik,hyp, N,Nb,Ns, alg, varargin) if strcmpi(alg,'hmc') [alpha,Na] = sample_hmc(K, m,y,lik,hyp, N,Nb,Ns, varargin{:}); else [alpha,Na] = sample_ess(cK,m,y,lik,hyp, N,Nb,Ns, varargin{:}); end %% sample using elliptical slices function [alpha,T] = sample_ess(cK,m,y,lik,hyp, N,Nb,Ns, taus) if nargin>=9, tau = taus(1); else tau = 1; end % default is no annealing T = (N+Nb)*Ns; % overall number of steps F = zeros(size(m,1),N); for t=1:T if nargin>=9, tau = taus(1+floor((t-1)/Ns)); end % parameter from schedule if t==1, f=0*m; l=sum(feval(lik{:},hyp,y,f+m)); end % init sample f & lik l r = cK'*randn(size(m)); % random sample from N(0,K) [f,l] = sample_ess_step(f,l,r,m,y,lik,hyp,tau); if mod(t,Ns)==0 % keep one state out of Ns if t/Ns>Nb, F(:,t/Ns-Nb) = f; end % wait for Nb burn-in steps end end alpha = cK\(cK'\F); %% elliptical slice sampling: one step function [f,l] = sample_ess_step(f,l,r,m,y,lik,hyp,tau) if nargin<7, tau=1; end, if tau>1, tau=1; end, if tau<0, tau=0; end h = log(rand) + tau*l; % acceptance threshold a = rand*2*pi; amin = a-2*pi; amax = a; % bracket whole ellipse k = 0; % emergency break while true % slice sampling loop; f for proposed angle diff; check if on slice fp = f*cos(a) + r*sin(a); % move on ellipsis defined by r l = sum(feval(lik{:},hyp,y,fp+m)); if tau*l>h || k>20, break, end % exit if new point is on slice or exhausted if a>0, amax=a; elseif a<0, amin=a; end % shrink slice to rejected point a = rand*(amax-amin) + amin; k = k+1; % propose new angle difference; break end f = fp; % accept %% sample using Hamiltonian dynamics as proposal algorithm function [alpha,Na] = sample_hmc(K,m,y,lik,hyp, N,Nb,Ns, taus) % use adaptive stepsize rule to enforce a specific acceptance rate epmin = 1e-6; % minimum leapfrog stepsize epmax = 9e-1; % maximum leapfrog stepsize ep = 1e-2; % initial leapfrog stepsize acc_t = 0.9; % target acceptance rate acc = 0; % current acceptance rate epinc = 1.02; % increase factor of stepsize if acceptance rate is below target epdec = 0.98; % decrease factor of stepsize if acceptance rate is above target lam = 0.01; % exponential moving average computation of the acceptance rate % 2/(3*lam) steps half height; lam/nstep = 0.02/33, 0.01/66, 0.005/133 l = 20; % number of leapfrog steps to perform for one step n = size(K,1); T = (N+Nb)*Ns; % overall number of steps alpha = zeros(n,N); % sample points al = zeros(n,1); % current position if nargin>=9, tau = taus(1); else tau = 1; end % default is no annealing [gold,eold] = E(al,K,m,y,lik,hyp,tau); % initial energy, gradient Na = 0; % number of accepted points for t=1:T if nargin>=9, tau = taus(1+floor((t-1)/Ns)); end % parameter from schedule p = randn(n,1); % random initial momentum q = al; g = gold; Hold = (p'*p)/2 + eold; % H = Ekin + Epot => Hamiltonian for ll=1:l % leapfrog discretization steps, Euler like p = p - (ep/2)*g; % half step in momentum p q = q + ep*p; % full step in position q g = E(q,K,m,y,lik,hyp,tau); % compute new gradient g p = p - (ep/2)*g; % half step in momentum p end [g,e] = E(q,K,m,y,lik,hyp,tau); H = (p'*p)/2 + e; % recompute Hamiltonian acc = (1-lam)*acc; % decay current acceptance rate if log(rand) < Hold-H % accept with p = min(1,exp(Hold-H)) al = q; % keep new state, gold = g; % gradient eold = e; % and potential energy acc = acc + lam; % increase rate due to acceptance Na = Na+1; % increase number accepted steps end if acc>acc_t % too large acceptance rate => increase leapfrog stepsize ep = epinc*ep; else % too small acceptance rate => decrease leapfrog stepsize ep = epdec*ep; end if ep<epmin, ep = epmin; end % clip stepsize ep to [epmin,epmax] if ep>epmax, ep = epmax; end if mod(t,Ns)==0 % keep one state out of Ns if t/Ns>Nb, alpha(:,t/Ns-Nb) = al; end % wait for Nb burn-in steps end end if Na/T<acc_t*0.9 || 1.07*acc_t<Na/T % Acceptance rate in the right ballpark? fprintf('The acceptance rate %1.2f%% is not within',100*Na/T) fprintf(' [%1.1f, %1.1f]%%\n', 100*acc_t*0.9, 100*acc_t*1.07) if nargin<9 warning('Bad (HMC) acceptance rate') else warning('Bad (AIS) acceptance rate') end end %% potential energy function value and its gradient function [g,e] = E(al,K,m,y,lik,hyp,tau) % E(f) = E(al) = al'*K*al/2 - tau*loglik(f), f = K*al+m % g(f) = g(al) = al - tau*dloglik(f) => dE/dal = K*( al-dloglik(f) ) if nargin<7, tau=1; end, if tau>1, tau=1; end, if tau<0, tau=0; end Kal = K*al; [lp,dlp] = feval(lik{:},hyp,y,Kal+m,[],'infLaplace'); g = Kal-K*(tau*dlp); if nargout>1, e = (al'*Kal)/2 - tau*sum(lp); end %% y = logsumexp(x) = log(sum(exp(x(:))) avoiding overflow function y=logsumexp(x) mx = max(x(:)); y = log(sum(exp(x(:)-mx)))+mx;
github
Hadisalman/stoec-master
infKL.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/inf/infKL.m
10,925
utf_8
25a0bb16b3bced105beb3520acf7f57e
function [post nlZ dnlZ] = infKL(hyp, mean, cov, lik, x, y) % Approximation to the posterior Gaussian Process by minimization of the % KL-divergence. The function is structurally very similar to infEP; the % only difference being the local divergence measure minimised. % In infEP, one minimises KL(p,q) whereas in infKL one minimises KL(q,p) % locally be iterating over the sites. For log-concave likelihoods, the % latter minimisation constitutes a 2d joint convex problem, so convergence % is guaranteed. % The function takes a specified covariance function (see covFunctions.m) and % likelihood function (see likFunctions.m), and is designed to be used with % gp.m. See also infMethods.m. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2013-09-13. % % See also INFMETHODS.M. out = false; persistent last_ttau last_tnu % keep tilde parameters between calls tol = 1e-3; max_sweep = 15; min_sweep = 2; % tolerance to stop KL iterations n = size(x,1); K = feval(cov{:}, hyp.cov, x); % evaluate the covariance matrix m = feval(mean{:}, hyp.mean, x); % evaluate the mean vector % A note on naming: variables are given short but descriptive names in % accordance with Rasmussen & Williams "GPs for Machine Learning" (2006): mu % and s2 are mean and variance, nu and tau are natural parameters. A leading t % means tilde, a subscript _ni means "not i" (for cavity parameters), or _n % for a vector of cavity parameters. N(f|mu,Sigma) represents the posterior. % marginal likelihood for ttau = tnu = zeros(n,1); equals n*log(2) for likCum* nlZ0 = -sum(likKL(diag(K),lik,hyp.lik,y,m)); if any(size(last_ttau) ~= [n 1]) % find starting point for tilde parameters ttau = zeros(n,1); % initialize to zero if we have no better guess tnu = zeros(n,1); Sigma = K; % initialize Sigma and mu, the parameters of .. mu = m; % .. the Gaussian posterior approximation nlZ = nlZ0; else ttau = last_ttau; % try the tilde values from previous call tnu = last_tnu; [Sigma,mu,L,alpha,nlZ] = klComputeParams(K,y,ttau,tnu,lik,hyp,m); if nlZ > nlZ0 % if zero is better .. ttau = zeros(n,1); % .. then initialize with zero instead tnu = zeros(n,1); Sigma = K; % initialize Sigma and mu, the parameters of .. mu = m; % .. the Gaussian posterior approximation nlZ = nlZ0; end end nlZ_old = Inf; sweep = 0; % converged, max. sweeps or min. sweeps? while (nlZ_old-nlZ > tol && sweep < max_sweep) || sweep<min_sweep nlZ_old = nlZ; sweep = sweep+1; if out, fprintf('Sweep %d, nlZ=%f\n',sweep,nlZ), end for i = randperm(n) % iterate EP updates (in random order) over examples tau_ni = 1/Sigma(i,i)-ttau(i); % first find the cavity distribution .. nu_ni = mu(i)/Sigma(i,i)-tnu(i); % .. params tau_ni and nu_ni ttau_old = ttau(i); tnu_old = tnu(i); % find the new tilde params, keep old [mi,svi] = klmin(lik, hyp.lik, y(i), nu_ni,tau_ni); % KL projection ttau(i) = 1/svi^2-tau_ni; ttau(i) = max(ttau(i),0); % enforce positivity i.e. lower bound ttau by zero tnu(i) = mi/svi^2-nu_ni; dtt = ttau(i)-ttau_old; dtn = tnu(i)-tnu_old; % rank-1 update Sigma .. si = Sigma(:,i); ci = dtt/(1+dtt*si(i)); Sigma = Sigma - ci*si*si'; mu = mu - (ci*(mu(i)+si(i)*dtn)-dtn)*si; % .. and recompute mu end % recompute since repeated rank-one updates can destroy numerical precision [Sigma,mu,L,alpha,nlZ,A] = klComputeParams(K,y,ttau,tnu,lik,hyp,m); end if sweep == max_sweep && nlZ_old-nlZ > tol error('maximum number of sweeps exceeded in function infKL') end last_ttau = ttau; last_tnu = tnu; % remember for next call post.alpha = alpha; post.sW = sqrt(ttau); post.L = L; % return posterior params if nargout>2 % do we want derivatives? v = diag(Sigma); [lp,df,d2f,dv] = likKL(v,lik,hyp.lik,y,mu); dnlZ = hyp; % allocate space for derivatives for j=1:length(hyp.cov) % covariance hypers dK = feval(cov{:},hyp.cov,x,[],j); AdK = A*dK; z = diag(AdK) + sum(A.*AdK,2) - sum(A'.*AdK,1)'; dnlZ.cov(j) = alpha'*dK*(alpha/2-df) - z'*dv; end for j=1:length(hyp.lik) % likelihood hypers lp_dhyp = likKL(v,lik,hyp.lik,y,K*post.alpha+m,[],[],j); dnlZ.lik(j) = -sum(lp_dhyp); end for j=1:length(hyp.mean) % mean hypers dm = feval(mean{:}, hyp.mean, x, j); dnlZ.mean(j) = -alpha'*dm; end end % function to compute the parameters of the Gaussian approximation, Sigma and % mu, from the current site parameters, ttau and tnu. Also returns L and upper % bound on negative marginal likelihood. function [Sigma,mu,L,alpha,nlZ,A] = klComputeParams(K,y,ttau,tnu,lik,hyp,m) n = length(tnu); % number of training cases sW = sqrt(ttau); % compute Sigma and mu L = chol(eye(n)+sW*sW'.*K); % L'*L=B=eye(n)+sW*K*sW V = L'\(repmat(sW,1,n).*K); Sigma = K - V'*V; alpha = tnu-sW.*solve_chol(L,sW.*(K*tnu+m)); mu = K*alpha+m; v = diag(Sigma); A = (eye(n)+K*diag(ttau))\eye(n); % A = Sigma*inv(K) lp = likKL(v,lik,hyp.lik,y,mu); % evaluate likelihood nlZ = -sum(lp) - (logdet(A)-alpha'*(mu-m)-trace(A)+n)/2; % upper bound on -lZ % We compute the Gaussian Q(f)=N(f|m,s^2) minimising the KL divergence % KL(Q||P) where P is the product of the cavity distribution q_n(f) and the % likelihood p(y|f) such that P(f) = 1/Z * q_n(f)*p(y|f). % The cavity distribution q_n(f) is an unnormalised Gaussian with precision % parameter tau_n and location parameter nu_n, hence the cavity can be written % as q_n(f) = exp(nu_n*f-tau_n/2*f^2). % The minimisation is convex iff. the likelihood p(y|f) is log-concave. The % optimisation is performed using Newton descent with backtracking line search. function [m,s,kl] = klmin(lik, hyp, y, nu_n, tau_n) ep = 1e-9; % tiny Hessian ridge for stability gthresh = 1e-8; % gradient convergence threshold lik_str = lik{1}; if ~ischar(lik_str), lik_str = func2str(lik_str); end if strcmp(lik_str,'likGauss') % likGauss can be done analytically sn2 = exp(2*hyp); s = 1/sqrt(1/sn2+tau_n); m = s^2*(nu_n+y/sn2); % init variables to minimum else s = 1/sqrt(tau_n); m = nu_n/tau_n; % init variables to cavity distribution end ll = likKL(s^2,lik,hyp,y,m); % evaluate likelihood kl = (s^2+m^2)*tau_n/2 - log(s) - nu_n*m - ll; % init the KL div up to a const for i=1:20 [ll,dm,d2m,dv,d2v,dmdv] = likKL(s^2,lik,hyp,y,m); % evaluate likelihood klold = kl; mold = m; sold = s; % remember last value kl = (s^2+m^2)*tau_n/2 - log(s) - nu_n*m - ll; % KL-divergence up to const dm = tau_n*m-nu_n-dm; d2m = tau_n-d2m; % compute kl derivatives ds = s*tau_n-1/s-2*s*dv; d2s = tau_n+1/s^2-2*dv-(2*s)^2*d2v; dmds=-2*s*dmdv; detH = ((d2m+ep)*(d2s+ep)-dmds^2); % Hessian determinant m = m-(dm*(d2s+ep)-ds*dmds)/detH; s = s-(ds*(d2m+ep)-dm*dmds)/detH; % Newton for j=1:10 % backtracking line search if klold>kl, break, end % we did descend so no need to step back m = (m+mold)/2; s = (s+sold)/2; kl = (s^2+m^2)*tau_n/2 - log(s) - nu_n*m - likKL(s^2,lik,hyp,y,m); end d = abs(dm)+abs(dv); % overall gradient if j==10, m = mold; s = sold; d = 0; end if d<gthresh, break, end end % log(det(A)) for det(A)>0 using the LU decomposition of A function y = logdet(A) [L,U] = lu(A); u = diag(U); if prod(sign(u))~=det(L), error('det(A)<=0'), end y = sum(log(abs(u))); % Gaussian smoothed likelihood function; instead of p(y|f)=lik(..,f,..) compute % log likKL(f) = int log lik(..,t,..) N(f|t,v), where % v .. marginal variance = (positive) smoothing width, and % lik .. lik function such that feval(lik{:},varargin{:}) yields a result. % All return values are separately integrated using Gaussian-Hermite quadrature. % Gaussian smoothed likelihood function; instead of p(y|f)=lik(..,f,..) compute % likKL(f) = int lik(..,t,..) N(f|t,v), where % v .. marginal variance = (positive) smoothing width, and % lik .. lik function such that feval(lik{:},varargin{:}) yields a result. % All return values are separately integrated using Gaussian-Hermite quadrature. function [ll,df,d2f,dv,d2v,dfdv] = likKL(v, lik, varargin) N = 20; % number of quadrature points [t,w] = gauher(N); % location and weights for Gaussian-Hermite quadrature f = varargin{3}; % obtain location of evaluation sv = sqrt(v); % smoothing width ll = 0; df = 0; d2f = 0; dv = 0; d2v = 0; dfdv = 0; % init return arguments for i=1:N % use Gaussian quadrature varargin{3} = f + sv*t(i); % coordinate transform of the quadrature points [lp,dlp,d2lp] = feval(lik{:},varargin{1:3},[],'infLaplace',varargin{6:end}); if nargout>0, ll = ll + w(i)*lp; % value of the integral if nargout>1, df = df + w(i)*dlp; % derivative w.r.t. mean if nargout>2, d2f = d2f + w(i)*d2lp; % 2nd derivative w.r.t. mean if nargout>3 % derivative w.r.t. variance ai = t(i)./(2*sv+eps); dvi = dlp.*ai; dv = dv + w(i)*dvi; % no 0 div if nargout>4 % 2nd derivative w.r.t. variance d2v = d2v + w(i)*(d2lp.*(t(i)^2/2)-dvi)./(v+eps)/2; % no 0 div if nargout>5 % mixed second derivatives dfdv = dfdv + w(i)*(ai.*d2lp); end end end end end end end % likLaplace can be done analytically lik_str = lik{1}; if ~ischar(lik_str), lik_str = func2str(lik_str); end if strcmp(lik_str,'likLaplace') b = exp(varargin{1})/sqrt(2); y = varargin{2}; sv = sqrt(v); mu = (f-y)/b; z = (f-y)./sv; Nz = exp(-z.^2/2)/sqrt(2*pi); Cz = (1+erf(z/sqrt(2)))/2; ll = (1-2*Cz).*mu - 2/b*sv.*Nz - log(2*b); df = (1-2*Cz)/b; d2f = -2*Nz./(b*(sv+eps)); dv = d2f/2; d2v = (z.*z-1)./(v+eps).*d2f/4; dfdv = -z.*d2f./(2*sv+eps); end
github
Hadisalman/stoec-master
infFITC_EP.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/inf/infFITC_EP.m
12,117
utf_8
a2c1fccebe29502421d32ed7ab5fcd14
function [post nlZ dnlZ] = infFITC_EP(hyp, mean, cov, lik, x, y) % FITC-EP approximation to the posterior Gaussian process. The function is % equivalent to infEP with the covariance function: % Kt = Q + G; G = diag(g); g = diag(K-Q); Q = Ku'*inv(Kuu + snu2*eye(nu))*Ku; % where Ku and Kuu are covariances w.r.t. to inducing inputs xu and % snu2 = sn2/1e6 is the noise of the inducing inputs. We fixed the standard % deviation of the inducing inputs snu to be a one per mil of the measurement % noise's standard deviation sn. In case of a likelihood without noise % parameter sn2, we simply use snu2 = 1e-6. % For details, see The Generalized FITC Approximation, Andrew Naish-Guzman and % Sean Holden, NIPS, 2007. % % The implementation exploits the Woodbury matrix identity % inv(Kt) = inv(G) - inv(G)*Ku'*inv(Kuu+Ku*inv(G)*Ku')*Ku*inv(G) % in order to be applicable to large datasets. The computational complexity % is O(n nu^2) where n is the number of data points x and nu the number of % inducing inputs in xu. % The posterior N(f|h,Sigma) is given by h = m+mu with mu = nn + P'*gg and % Sigma = inv(inv(K)+diag(W)) = diag(d) + P'*R0'*R'*R*R0*P. Here, we use the % site parameters: b,w=$b,\pi$=tnu,ttau, P=$P'$, nn=$\nu$, gg=$\gamma$ % % The function takes a specified covariance function (see covFunctions.m) and % likelihood function (see likFunctions.m), and is designed to be used with % gp.m and in conjunction with covFITC. % % The inducing points can be specified through 1) the 2nd covFITC parameter or % by 2) providing a hyp.xu hyperparameters. Note that 2) has priority over 1). % In case 2) is provided and derivatives dnlZ are requested, there will also be % a dnlZ.xu field allowing to optimise w.r.t. to the inducing points xu. However % the derivatives dnlZ.xu can only be computed for one of the following eight % covariance functions: cov{Matern|PP|RQ|SE}{iso|ard}. % % Copyright (c) by Hannes Nickisch, 2013-10-29. % % See also INFMETHODS.M, COVFITC.M. persistent last_ttau last_tnu % keep tilde parameters between calls tol = 1e-4; max_sweep = 20; min_sweep = 2; % tolerance to stop EP iterations inf = 'infEP'; cov1 = cov{1}; if isa(cov1, 'function_handle'), cov1 = func2str(cov1); end if ~strcmp(cov1,'covFITC'); error('Only covFITC supported.'), end % check cov if isfield(hyp,'xu'), cov{3} = hyp.xu; end % hyp.xu is provided, replace cov{3} [diagK,Kuu,Ku] = feval(cov{:}, hyp.cov, x); % evaluate covariance matrix if ~isempty(hyp.lik) % hard coded inducing inputs noise sn2 = exp(2*hyp.lik(end)); snu2 = 1e-6*sn2; % similar to infFITC else snu2 = 1e-6; end [n, D] = size(x); nu = size(Kuu,1); m = feval(mean{:}, hyp.mean, x); % evaluate the mean vector rot180 = @(A) rot90(rot90(A)); % little helper functions chol_inv = @(A) rot180(chol(rot180(A))')\eye(nu); % chol(inv(A)) R0 = chol_inv(Kuu+snu2*eye(nu)); % initial R, used for refresh O(nu^3) V = R0*Ku; d0 = diagK-sum(V.*V,1)'; % initial d, needed for refresh O(n*nu^2) % A note on naming: variables are given short but descriptive names in % accordance with Rasmussen & Williams "GPs for Machine Learning" (2006): mu % and s2 are mean and variance, nu and tau are natural parameters. A leading t % means tilde, a subscript _ni means "not i" (for cavity parameters), or _n % for a vector of cavity parameters. % marginal likelihood for ttau = tnu = zeros(n,1); equals n*log(2) for likCum* nlZ0 = -sum(feval(lik{:}, hyp.lik, y, m, diagK, inf)); if any(size(last_ttau) ~= [n 1]) % find starting point for tilde parameters ttau = zeros(n,1); % initialize to zero if we have no better guess tnu = zeros(n,1); [d,P,R,nn,gg] = epfitcRefresh(d0,Ku,R0,V, ttau,tnu); % compute initial repres. nlZ = nlZ0; else ttau = last_ttau; % try the tilde values from previous call tnu = last_tnu; [d,P,R,nn,gg] = epfitcRefresh(d0,Ku,R0,V, ttau,tnu); % compute initial repres. nlZ = epfitcZ(d,P,R,nn,gg,ttau,tnu,d0,R0,Ku,y,lik,hyp,m,inf); if nlZ > nlZ0 % if zero is better .. ttau = zeros(n,1); % .. then initialize with zero instead tnu = zeros(n,1); [d,P,R,nn,gg] = epfitcRefresh(d0,Ku,R0,V, ttau,tnu); % initial repres. nlZ = nlZ0; end end nlZ_old = Inf; sweep = 0; % converged, max. sweeps or min. sweeps? while (abs(nlZ-nlZ_old) > tol && sweep < max_sweep) || sweep<min_sweep nlZ_old = nlZ; sweep = sweep+1; for i = randperm(n) % iterate EP updates (in random order) over examples pi = P(:,i); t = R*(R0*pi); % temporary variables sigmai = d(i) + t'*t; mui = nn(i) + pi'*gg; % post moments O(nu^2) tau_ni = 1/sigmai-ttau(i); % first find the cavity distribution .. nu_ni = mui/sigmai+m(i)*tau_ni-tnu(i); % .. params tau_ni and nu_ni % compute the desired derivatives of the indivdual log partition function [lZ, dlZ, d2lZ] = feval(lik{:}, hyp.lik, y(i), nu_ni/tau_ni, 1/tau_ni, inf); ttaui = -d2lZ /(1+d2lZ/tau_ni); ttaui = max(ttaui,0); % enforce positivity i.e. lower bound ttau by zero tnui = ( dlZ + (m(i)-nu_ni/tau_ni)*d2lZ )/(1+d2lZ/tau_ni); [d,P(:,i),R,nn,gg,ttau,tnu] = ... % update representation epfitcUpdate(d,P(:,i),R,nn,gg, ttau,tnu,i,ttaui,tnui, m,d0,Ku,R0); end % recompute since repeated rank-one updates can destroy numerical precision [d,P,R,nn,gg] = epfitcRefresh(d0,Ku,R0,V, ttau,tnu); [nlZ,nu_n,tau_n] = epfitcZ(d,P,R,nn,gg,ttau,tnu,d0,R0,Ku,y,lik,hyp,m,inf); end if sweep == max_sweep warning('maximum number of sweeps reached in function infEP') end last_ttau = ttau; last_tnu = tnu; % remember for next call post.sW = sqrt(ttau); % unused for FITC_EP prediction with gp.m dd = 1./(d0+1./ttau); alpha = tnu./(1+d0.*ttau); RV = R*V; R0tV = R0'*V; alpha = alpha - (RV'*(RV*alpha)).*dd; % long alpha vector for ordinary infEP post.alpha = R0tV*alpha; % alpha = R0'*V*inv(Kt+diag(1./ttau))*(tnu./ttau) B = R0tV.*repmat(dd',nu,1); L = B*R0tV'; B = B*RV'; post.L = B*B' - L; % L = -R0'*V*inv(Kt+diag(1./ttau))*V'*R0 if nargout>2 % do we want derivatives? dnlZ = hyp; % allocate space for derivatives RVdd = RV.*repmat(dd',nu,1); for i=1:length(hyp.cov) [ddiagK,dKuu,dKu] = feval(cov{:}, hyp.cov, x, [], i); % eval cov derivatives dA = 2*dKu'-R0tV'*dKuu; % dQ = dA*R0tV w = sum(dA.*R0tV',2); v = ddiagK-w; % w = diag(dQ); v = diag(dK)-diag(dQ); z = dd'*(v+w) - sum(RVdd.*RVdd,1)*v - sum(sum( (RVdd*dA)'.*(R0tV*RVdd') )); dnlZ.cov(i) = (z - alpha'*(alpha.*v) - (alpha'*dA)*(R0tV*alpha))/2; end for i = 1:numel(hyp.lik) % likelihood hypers dlik = feval(lik{:}, hyp.lik, y, nu_n./tau_n, 1./tau_n, inf, i); dnlZ.lik(i) = -sum(dlik); if i==numel(hyp.lik) % since snu2 is a fixed fraction of sn2, there is a covariance-like term % in the derivative as well v = sum(R0tV.*R0tV,1)'; z = sum(sum( (RVdd*R0tV').^2 )) - sum(RVdd.*RVdd,1)*v; z = z + post.alpha'*post.alpha - alpha'*(v.*alpha); dnlZ.lik(i) = dnlZ.lik(i) + snu2*z; end end [junk,dlZ] = feval(lik{:}, hyp.lik, y, nu_n./tau_n, 1./tau_n, inf);% mean hyps for i = 1:numel(hyp.mean) dm = feval(mean{:}, hyp.mean, x, i); dnlZ.mean(i) = -dlZ'*dm; end if isfield(hyp,'xu') % derivatives w.r.t. inducing points xu xu = cov{3}; cov = cov{2}; % get the non FITC part of the covariance function Kpu = cov_deriv_sq_dist(cov,hyp.cov,xu,x); % d K(xu,x ) / d D^2 Kpuu = cov_deriv_sq_dist(cov,hyp.cov,xu); % d K(xu,xu) / d D^2 if iscell(cov), covstr = cov{1}; else covstr = cov; end if ~ischar(covstr), covstr = func2str(covstr); end if numel(strfind(covstr,'iso'))>0 % characteristic length scale e = 2*exp(-2*hyp.cov(1)); else e = 2*exp(-2*hyp.cov(1:D)); end B = (R0'*R0)*Ku; W = ttau; t = W./(1+W.*d0); diag_dK = alpha.*alpha + sum(RVdd.*RVdd,1)' - t; v = diag_dK+t; % BdK = B * ( dnlZ/dK - diag(diag(dnlZ/dK)) ) BdK = (B*alpha)*alpha' - B.*repmat(v',nu,1); BdK = BdK + (B*RVdd')*RVdd; A = Kpu.*BdK; C = Kpuu.*(BdK*B'); C = diag(sum(C,2)-sum(A,2)) - C; dnlZ.xu = A*x*diag(e) + C*xu*diag(e); % bring in data and inducing points end end % refresh the representation of the posterior from initial and site parameters % to prevent possible loss of numerical precision after many epfitcUpdates % effort is O(n*nu^2) provided that nu<n function [d,P,R,nn,gg] = epfitcRefresh(d0,P0,R0,R0P0, w,b) nu = size(R0,1); % number of inducing points rot180 = @(A) rot90(rot90(A)); % little helper functions chol_inv = @(A) rot180(chol(rot180(A))')\eye(nu); % chol(inv(A)) t = 1./(1+d0.*w); % temporary variable O(n) d = d0.*t; % O(n) P = repmat(t',nu,1).*P0; % O(n*nu) T = repmat((w.*t)',nu,1).*R0P0; % temporary variable O(n*nu^2) R = chol_inv(eye(nu)+R0P0*T'); % O(n*nu^3) nn = d.*b; % O(n) gg = R0'*(R'*(R*(R0P0*(t.*b)))); % O(n*nu) % compute the marginal likelihood approximation % effort is O(n*nu^2) provided that nu<n function [nlZ,nu_n,tau_n] = ... epfitcZ(d,P,R,nn,gg,ttau,tnu, d0,R0,P0, y,lik,hyp,m,inf) T = (R*R0)*P; % temporary variable diag_sigma = d + sum(T.*T,1)'; mu = nn + P'*gg; % post moments O(n*nu^2) tau_n = 1./diag_sigma-ttau; % compute the log marginal likelihood nu_n = mu./diag_sigma-tnu+m.*tau_n; % vectors of cavity parameters lZ = feval(lik{:}, hyp.lik, y, nu_n./tau_n, 1./tau_n, inf); nu = size(gg,1); U = (R0*P0)'.*repmat(1./sqrt(d0+1./ttau),1,nu); L = chol(eye(nu)+U'*U); ld = 2*sum(log(diag(L))) + sum(log(1+d0.*ttau)); t = T*tnu; tnu_Sigma_tnu = tnu'*(d.*tnu) + t'*t; nlZ = ld/2 -sum(lZ) -tnu_Sigma_tnu/2 ... -(nu_n-m.*tau_n)'*((ttau./tau_n.*(nu_n-m.*tau_n)-2*tnu)./(ttau+tau_n))/2 ... +sum(tnu.^2./(tau_n+ttau))/2-sum(log(1+ttau./tau_n))/2; % update the representation of the posterior to reflect modification of the site % parameters by w(i) <- wi and b(i) <- bi % effort is O(nu^2) % Pi = P(:,i) is passed instead of P to prevent allocation of a new array function [d,Pi,R,nn,gg,w,b] = ... epfitcUpdate(d,Pi,R,nn,gg, w,b, i,wi,bi, m,d0,P0,R0) dwi = wi-w(i); dbi = bi-b(i); hi = nn(i) + m(i) + Pi'*gg; % posterior mean of site i O(nu) t = 1+dwi*d(i); d(i) = d(i)/t; % O(1) nn(i) = d(i)*bi; % O(1) r = 1+d0(i)*w(i); r = r*r/dwi + r*d0(i); v = R*(R0*P0(:,i)); r = 1/(r+v'*v); if r>0 R = cholupdate(R,sqrt( r)*R'*v,'-'); else R = cholupdate(R,sqrt(-r)*R'*v,'+'); end gg = gg + ((dbi-dwi*(hi-m(i)))/t)*(R0'*(R'*(R*(R0*Pi)))); % O(nu^2) w(i) = wi; b(i) = bi; % update site parameters O(1) Pi = Pi/t; % O(nu)
github
Hadisalman/stoec-master
infFITC_Laplace.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/inf/infFITC_Laplace.m
11,364
utf_8
1de345e37242cee549b4d7841e348f84
function [post nlZ dnlZ] = infFITC_Laplace(hyp, mean, cov, lik, x, y) % FITC-Laplace approximation to the posterior Gaussian process. The function is % equivalent to infLaplace with the covariance function: % Kt = Q + G; G = diag(g); g = diag(K-Q); Q = Ku'*inv(Kuu + snu2*eye(nu))*Ku; % where Ku and Kuu are covariances w.r.t. to inducing inputs xu and % snu2 = sn2/1e6 is the noise of the inducing inputs. We fixed the standard % deviation of the inducing inputs snu to be a one per mil of the measurement % noise's standard deviation sn. In case of a likelihood without noise % parameter sn2, we simply use snu2 = 1e-6. % % The implementation exploits the Woodbury matrix identity % inv(Kt) = inv(G) - inv(G)*Ku'*inv(Kuu+Ku*inv(G)*Ku')*Ku*inv(G) % in order to be applicable to large datasets. The computational complexity % is O(n nu^2) where n is the number of data points x and nu the number of % inducing inputs in xu. % The posterior N(f|h,Sigma) is given by h = m+mu with mu = nn + P'*gg and % Sigma = inv(inv(K)+diag(W)) = diag(d) + P'*R0'*R'*R*R0*P. % % The function takes a specified covariance function (see covFunctions.m) and % likelihood function (see likFunctions.m), and is designed to be used with % gp.m and in conjunction with covFITC. % % The inducing points can be specified through 1) the 2nd covFITC parameter or % by 2) providing a hyp.xu hyperparameters. Note that 2) has priority over 1). % In case 2) is provided and derivatives dnlZ are requested, there will also be % a dnlZ.xu field allowing to optimise w.r.t. to the inducing points xu. However % the derivatives dnlZ.xu can only be computed for one of the following eight % covariance functions: cov{Matern|PP|RQ|SE}{iso|ard}. % % Copyright (c) by Hannes Nickisch, 2013-10-28. % % See also INFMETHODS.M, COVFITC.M. persistent last_alpha % copy of the last alpha if any(isnan(last_alpha)), last_alpha = zeros(size(last_alpha)); end % prevent tol = 1e-6; % tolerance for when to stop the Newton iterations smax = 2; Nline = 10; thr = 1e-4; % line search parameters maxit = 20; % max number of Newton steps in f inf = 'infLaplace'; cov1 = cov{1}; if isa(cov1, 'function_handle'), cov1 = func2str(cov1); end if ~strcmp(cov1,'covFITC'); error('Only covFITC supported.'), end % check cov if isfield(hyp,'xu'), cov{3} = hyp.xu; end % hyp.xu is provided, replace cov{3} [diagK,Kuu,Ku] = feval(cov{:}, hyp.cov, x); % evaluate covariance matrix if ~isempty(hyp.lik) % hard coded inducing inputs noise sn2 = exp(2*hyp.lik(end)); snu2 = 1e-6*sn2; % similar to infFITC else snu2 = 1e-6; end [n, D] = size(x); nu = size(Kuu,1); m = feval(mean{:}, hyp.mean, x); % evaluate the mean vector rot180 = @(A) rot90(rot90(A)); % little helper functions chol_inv = @(A) rot180(chol(rot180(A))')\eye(nu); % chol(inv(A)) R0 = chol_inv(Kuu+snu2*eye(nu)); % initial R, used for refresh O(nu^3) V = R0*Ku; d0 = diagK-sum(V.*V,1)'; % initial d, needed for refresh O(n*nu^2) Psi_old = Inf; % make sure while loop starts by the largest old objective val if any(size(last_alpha)~=[n,1]) % find a good starting point for alpha and f alpha = zeros(n,1); f = mvmK(alpha,V,d0)+m; % start at mean if sizes not match [lp,dlp,d2lp] = feval(lik{:},hyp.lik,y,f,[],inf); W=-d2lp; Psi_new = -sum(lp); else alpha = last_alpha; f = mvmK(alpha,V,d0)+m; % try last one [lp,dlp,d2lp] = feval(lik{:},hyp.lik,y,f,[],inf); W=-d2lp; Psi_new = alpha'*(f-m)/2 - sum(lp); % objective for last alpha Psi_def = -feval(lik{:},hyp.lik,y,m,[],inf); % objective for default init f==m if Psi_def < Psi_new % if default is better, we use it alpha = zeros(n,1); f = mvmK(alpha,V,d0)+m; [lp,dlp,d2lp] = feval(lik{:},hyp.lik,y,f,[],inf); W=-d2lp; Psi_new=-sum(lp); end end isWneg = any(W<0); % flag indicating whether we found negative values of W it = 0; % this happens for the Student's t likelihood while Psi_old - Psi_new > tol && it<maxit % begin Newton Psi_old = Psi_new; it = it+1; if isWneg % stabilise the Newton direction in case W has negative values W = max(W,0); % stabilise the Hessian to guarantee postive definiteness tol = 1e-8; % increase accuracy to also get the derivatives right % In Vanhatalo et. al., GPR with Student's t likelihood, NIPS 2009, they use % a more conservative strategy then we do being equivalent to 2 lines below. % nu = exp(hyp.lik(1)); % degree of freedom hyperparameter % W = W + 2/(nu+1)*dlp.^2; % add ridge according to Vanhatalo end b = W.*(f-m) + dlp; dd = 1./(1+W.*d0); RV = chol_inv(eye(nu)+(V.*repmat((W.*dd)',nu,1))*V')*V; dalpha = dd.*b - (W.*dd).*(RV'*(RV*(dd.*b))) - alpha; % Newt dir + line search [s,Psi_new,Nfun,alpha,f,dlp,W] = brentmin(0,smax,Nline,thr, ... @Psi_line,4,dalpha,alpha,hyp,V,d0,m,lik,y,inf); isWneg = any(W<0); end % end Newton's iterations last_alpha = alpha; % remember for next call [lp,dlp,d2lp,d3lp] = feval(lik{:},hyp.lik,y,f,[],inf); W=-d2lp; isWneg=any(W<0); post.alpha = R0'*(V*alpha); % return the posterior parameters post.sW = sqrt(abs(W)).*sign(W); % preserve sign in case of negative dd = 1./(1+d0.*W); % temporary variable O(n) A = eye(nu)+(V.*repmat((W.*dd)',nu,1))*V'; % temporary variable O(n*nu^2) R0tV = R0'*V; B = R0tV.*repmat((W.*dd)',nu,1); % temporary variables O(n*nu^2) post.L = -B*R0tV'; % L = -R0'*V*inv(Kt+diag(1./ttau))*V'*R0, first part if any(1+d0.*W<0) B = B*V'; post.L = post.L + (B*inv(A))*B'; nlZ = NaN; dnlZ = struct('cov',0*hyp.cov, 'mean',0*hyp.mean, 'lik',0*hyp.lik); warning('W is too negative; nlZ and dnlZ cannot be computed.') return end nlZ = alpha'*(f-m)/2 - sum(lp) - sum(log(dd))/2 + sum(log(diag(chol(A)))); RV = chol_inv(A)*V; RVdd = RV.*repmat((W.*dd)',nu,1); % RVdd needed for dnlZ B = B*RV'; post.L = post.L + B*B'; if nargout>2 % do we want derivatives? dnlZ = hyp; % allocate space for derivatives [d,P,R] = fitcRefresh(d0,Ku,R0,V,W); % g = diag(inv(inv(K)+W))/2 g = d/2 + sum(((R*R0)*P).^2,1)'/2; t = W./(1+W.*d0); dfhat = g.*d3lp; % deriv. of nlZ wrt. fhat: dfhat=diag(inv(inv(K)+W)).*d3lp/2 for i=1:length(hyp.cov) % covariance hypers [ddiagK,dKuu,dKu] = feval(cov{:}, hyp.cov, x, [], i); % eval cov derivatives dA = 2*dKu'-R0tV'*dKuu; % dQ = dA*R0tV w = sum(dA.*R0tV',2); v = ddiagK-w; % w = diag(dQ); v = diag(dK)-diag(dQ); dnlZ.cov(i) = ddiagK'*t - sum(RVdd.*RVdd,1)*v; % explicit part dnlZ.cov(i) = dnlZ.cov(i)-sum(sum((RVdd*dA).*(RVdd*R0tV'))); % explicit part dnlZ.cov(i) = dnlZ.cov(i)/2-alpha'*(dA*(R0tV*alpha)+v.*alpha)/2; % explicit b = dA*(R0tV*dlp) + v.*dlp; % b-K*(Z*b) = inv(eye(n)+K*diag(W))*b KZb = mvmK(mvmZ(b,RVdd,t),V,d0); dnlZ.cov(i) = dnlZ.cov(i) - dfhat'*( b-KZb ); % implicit part end for i=1:length(hyp.lik) % likelihood hypers [lp_dhyp,dlp_dhyp,d2lp_dhyp] = feval(lik{:},hyp.lik,y,f,[],inf,i); dnlZ.lik(i) = -g'*d2lp_dhyp - sum(lp_dhyp); % explicit part b = mvmK(dlp_dhyp,V,d0); % implicit part dnlZ.lik(i) = dnlZ.lik(i) - dfhat'*(b-mvmK(mvmZ(b,RVdd,t),V,d0)); if i==numel(hyp.lik) % since snu2 is a fixed fraction of sn2, there is a covariance-like term % in the derivative as well snu = sqrt(snu2); T = chol_inv(Kuu + snu2*eye(nu)); T = T'*(T*(snu*Ku)); t = sum(T.*T,1)'; z = alpha'*(T'*(T*alpha)-t.*alpha) - sum(RVdd.*RVdd,1)*t; z = z + sum(sum( (RVdd*T').^2 )); b = (t.*dlp-T'*(T*dlp))/2; KZb = mvmK(mvmZ(b,RVdd,t),V,d0); z = z - dfhat'*( b-KZb ); dnlZ.lik(i) = dnlZ.lik(i) + z; end end for i=1:length(hyp.mean) % mean hypers dm = feval(mean{:}, hyp.mean, x, i); dnlZ.mean(i) = -alpha'*dm; % explicit part Zdm = mvmZ(dm,RVdd,t); dnlZ.mean(i) = dnlZ.mean(i) - dfhat'*(dm-mvmK(Zdm,V,d0)); % implicit part end if isfield(hyp,'xu') % derivatives w.r.t. inducing points xu xu = cov{3}; cov = cov{2}; % get the non FITC part of the covariance function Kpu = cov_deriv_sq_dist(cov,hyp.cov,xu,x); % d K(xu,x ) / d D^2 Kpuu = cov_deriv_sq_dist(cov,hyp.cov,xu); % d K(xu,xu) / d D^2 if iscell(cov), covstr = cov{1}; else covstr = cov; end if ~ischar(covstr), covstr = func2str(covstr); end if numel(strfind(covstr,'iso'))>0 % characteristic length scale e = 2*exp(-2*hyp.cov(1)); else e = 2*exp(-2*hyp.cov(1:D)); end q = dfhat - mvmZ(mvmK(dfhat,V,d0),RVdd,t); % implicit part B = (R0'*R0)*Ku; diag_dK = alpha.*alpha + sum(RVdd.*RVdd,1)' - t + 2*dlp.*q; v = diag_dK+t; % BdK = B * ( dnlZ/dK - diag(diag(dnlZ/dK)) ) BdK = (B*alpha)*alpha' - B.*repmat(v',nu,1) + (B*dlp)*q' + (B*q)*dlp'; BdK = BdK + (B*RVdd')*RVdd; A = Kpu.*BdK; C = Kpuu.*(BdK*B'); C = diag(sum(C,2)-sum(A,2)) - C; dnlZ.xu = A*x*diag(e) + C*xu*diag(e); % bring in data and inducing points end end % matrix vector multiplication with Z=inv(K+inv(W)) function Zx = mvmZ(x,RVdd,t) Zx = t.*x - RVdd'*(RVdd*x); % matrix vector multiplication with approximate covariance matrix function Kal = mvmK(al,V,d0) Kal = V'*(V*al) + d0.*al; % criterion Psi at alpha + s*dalpha for line search function [Psi,alpha,f,dlp,W] = Psi_line(s,dalpha,alpha,hyp,V,d0,m,lik,y,inf) alpha = alpha + s*dalpha; f = mvmK(alpha,V,d0)+m; [lp,dlp,d2lp] = feval(lik{:},hyp.lik,y,f,[],inf); W = -d2lp; Psi = alpha'*(f-m)/2 - sum(lp); % refresh the representation of the posterior from initial and site parameters % to prevent possible loss of numerical precision after many epfitcUpdates % effort is O(n*nu^2) provided that nu<n % Sigma = inv(inv(K)+diag(W)) = diag(d) + P'*R0'*R'*R*R0*P. function [d,P,R] = fitcRefresh(d0,P0,R0,R0P0, w) nu = size(R0,1); % number of inducing points rot180 = @(A) rot90(rot90(A)); % little helper functions chol_inv = @(A) rot180(chol(rot180(A))')\eye(nu); % chol(inv(A)) t = 1./(1+d0.*w); % temporary variable O(n) d = d0.*t; % O(n) P = repmat(t',nu,1).*P0; % O(n*nu) T = repmat((w.*t)',nu,1).*R0P0; % temporary variable O(n*nu^2) R = chol_inv(eye(nu)+R0P0*T'); % O(n*nu^3)
github
Hadisalman/stoec-master
infGrid.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/inf/infGrid.m
7,627
utf_8
cca2d1208eb8763b1f518d5106ec6fd5
function [post nlZ dnlZ] = infGrid(hyp, mean, cov, lik, x, y, opt) % Inference for a GP with Gaussian likelihood and covGrid covariance. % The (Kronecker) covariance matrix used is given by: % K = kron( kron(...,K{2}), K{1} ) = K_p x .. x K_2 x K_1. % % Compute a parametrization of the posterior, the negative log marginal % likelihood and its derivatives w.r.t. the hyperparameters. % The result is exact for complete grids, otherwise results are approximate. % See also "help infMethods". % % The function takes a specified covariance function (see covFunctions.m) and % likelihood function (see likFunctions.m), and is designed to be used with % gp.m and in conjunction with covFITC and likGauss. % % Copyright (c) by Hannes Nickisch and Andrew Wilson, 2014-12-03. % % See also INFMETHODS.M, COVGRID.M. if iscell(lik), likstr = lik{1}; else likstr = lik; end if ~ischar(likstr), likstr = func2str(likstr); end if ~strcmp(likstr,'likGauss') % NOTE: no explicit call to likGauss error('Inference with infGrid only possible with Gaussian likelihood.'); end cov1 = cov{1}; if isa(cov1, 'function_handle'), cov1 = func2str(cov1); end if ~strcmp(cov1,'covGrid'); error('Only covGrid supported.'), end % check cov xg = cov{3}; p = numel(xg); % underlying grid N = 1; D = 0; for i=1:p, N = N*size(xg{i},1); D = D+size(xg{i},2); end % dims [K,M,xe] = feval(cov{:}, hyp.cov, x); % evaluate covariance mat constituents xe = M*xe; n = size(xe,1); m = feval(mean{:}, hyp.mean, xe); % evaluate mean vector if nargin<=6, opt = []; end % make opt variable available if isfield(opt,'cg_tol'), cgtol = opt.cg_tol; % stop conjugate gradients else cgtol = 1e-5; end if isfield(opt,'cg_maxit'), cgmit = opt.cg_maxit; % number of cg iterations else cgmit = min(n,20); end for j=1:numel(K) if iscell(K{j}) && strcmp(K{j}{1},'toep'), K{j} = toeplitz(K{j}{2}); end end sn2 = exp(2*hyp.lik); % noise variance of likGauss V = cell(size(K)); E = cell(size(K)); % eigenvalue decomposition for j=1:numel(K) if iscell(K{j}) && strcmp(K{j}{1},'toep') [V{j},E{j}] = eigr(toeplitz(K{j}{2})); else [V{j},E{j}] = eigr(K{j}); end end e = 1; for i=1:numel(E), e = kron(diag(E{i}),e); end % eigenvalue diagonal if numel(m)==N s = 1./(e+sn2); ord = 1:N; % V*diag(s)*V' = inv(K+sn2*eye(N)) else [eord,ord] = sort(e,'descend'); % sort long vector of eigenvalues s = 1./((n/N)*eord(1:n) + sn2); % approx using top n eigenvalues end if numel(m)==N % decide for Kronecker magic or conjugate gradients L = @(k) kronmvm(V,repmat(-s,1,size(k,2)).*kronmvm(V,k,1)); % mvm callback else % go for conjugate gradients mvm = @(t) mvmK(t,K,sn2,M); % single parameter mvm L = @(k) -solveMVM(k,mvm,cgtol,cgmit); end alpha = -L(y-m); post.alpha = alpha; % return the posterior parameters post.sW = ones(n,1)/sqrt(sn2); % sqrt of noise precision post.L = L; % function to compute inv(K+sn2*eye(N))*Ks if nargout>1 % do we want the marginal likelihood? lda = -sum(log(s)); % exact kron % exact: lda = 2*sum(log(diag(chol(M*kronmvm(K,eye(N))*M'+sn2*eye(n))))); nlZ = (y-m)'*alpha/2 + n*log(2*pi)/2 + lda/2; if nargout>2 % do we want derivatives? dnlZ = hyp; % allocate space for derivatives, define Q=inv(M*K*M'+sn2*I) Mtal = M'*alpha; % blow up alpha vector from n to N for i = 1:numel(hyp.cov) dK = feval(cov{:}, hyp.cov, x, [], i); for j=1:numel(dK) % expand Toeplitz if iscell(dK{j}) && strcmp(dK{j}{1},'toep') dK{j} = toeplitz(dK{j}{2}); end end P = cell(size(dK)); % auxiliary Kronecker matrix P = V'*dK*V for j = 1:numel(dK), P{j} = sum((V{j}'*dK{j}).*V{j}',2); end p = 1; for j=1:numel(P), p = kron(P{j},p); end % p = diag(P) p = (n/N)*p(ord(1:n)); % approximate if incomplete grid observation dnlZ.cov(i) = (p'*s - Mtal'*kronmvm(dK,Mtal))/2; end dnlZ.lik = sn2*(sum(s) - alpha'*alpha); % sum(s) = trace(Q) for i = 1:numel(hyp.mean) dnlZ.mean(i) = -feval(mean{:}, hyp.mean, xe, i)'*alpha; end end end % Solve x=A*b with symmetric A(n,n), b(n,m), x(n,m) using conjugate gradients. % The method is along the lines of PCG but suited for matrix inputs b. function [x,flag,relres,iter,r] = conjgrad(A,b,tol,maxit) if nargin<3, tol = 1e-10; end if nargin<4, maxit = min(size(b,1),20); end x0 = zeros(size(b)); x = x0; if isnumeric(A), r = b-A*x; else r = b-A(x); end, r2 = sum(r.*r,1); r2new = r2; nb = sqrt(sum(b.*b,1)); flag = 0; iter = 1; relres = sqrt(r2)./nb; todo = relres>=tol; if ~any(todo), flag = 1; return, end on = ones(size(b,1),1); r = r(:,todo); d = r; for iter = 2:maxit if isnumeric(A), z = A*d; else z = A(d); end a = r2(todo)./sum(d.*z,1); a = on*a; x(:,todo) = x(:,todo) + a.*d; r = r - a.*z; r2new(todo) = sum(r.*r,1); relres = sqrt(r2new)./nb; cnv = relres(todo)<tol; todo = relres>=tol; d = d(:,~cnv); r = r(:,~cnv); % get rid of converged if ~any(todo), flag = 1; return, end b = r2new./r2; % Fletcher-Reeves d = r + (on*b(todo)).*d; r2 = r2new; end % solve q = mvm(p) via conjugate gradients function q = solveMVM(p,mvm,varargin) [q,flag,relres,iter] = conjgrad(mvm,p,varargin{:}); % like pcg if ~flag,error('Not converged after %d iterations, r=%1.2e\n',iter,relres),end % mvm so that q = M*K*M'*p + sn2*p using the Kronecker representation function q = mvmK(p,K,sn2,M) q = M*kronmvm(K,M'*p) + sn2*p; % Perform a matrix vector multiplication b = A*x with a matrix A being a % Kronecker product given by A = kron( kron(...,As{2}), As{1} ). function b = kronmvm(As,x,transp) if nargin>2 && ~isempty(transp) && transp % transposition by transposing parts for i=1:numel(As), As{i} = As{i}'; end end m = zeros(numel(As),1); n = zeros(numel(As),1); % extract sizes for i=1:numel(n) if iscell(As{i}) && strcmp(As{i}{1},'toep') m(i) = size(As{i}{2},1); n(i) = size(As{i}{2},1); else [m(i),n(i)] = size(As{i}); end end d = size(x,2); b = x; for i=1:numel(n) a = reshape(b,[prod(m(1:i-1)), n(i), prod(n(i+1:end))*d]); % prepare input tmp = reshape(permute(a,[1,3,2]),[],n(i))*As{i}'; b = permute(reshape(tmp,[size(a,1),size(a,3),m(i)]),[1,3,2]); end b = reshape(b,prod(m),d); % bring result in correct shape % Real eigenvalues and eigenvectors up to the rank of a real symmetric matrix. % Decompose A into V*D*V' with orthonormal matrix V and diagonal matrix D. % Diagonal entries of D obave the rank r of the matrix A as returned by % the call rank(A,tol) are zero. function [V,D] = eigr(A,tol) [V,D] = eig((A+A')/2); n = size(A,1); % decomposition of strictly symmetric A d = max(real(diag(D)),0); [d,ord] = sort(d,'descend'); % tidy up and sort if nargin<2, tol = size(A,1)*eps(max(d)); end, r = sum(d>tol); % get rank(A) d(r+1:n) = 0; D = diag(d); % set junk eigenvalues to strict zeros V(:,1:r) = real(V(:,ord(1:r))); V(:,r+1:n) = null(V(:,1:r)'); % ortho completion
github
Hadisalman/stoec-master
infEP.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/inf/infEP.m
5,886
utf_8
bc70721e1eea7c28c46653d36d1cd851
function [post nlZ dnlZ] = infEP(hyp, mean, cov, lik, x, y) % Expectation Propagation approximation to the posterior Gaussian Process. % The function takes a specified covariance function (see covFunctions.m) and % likelihood function (see likFunctions.m), and is designed to be used with % gp.m. See also infMethods.m. In the EP algorithm, the sites are % updated in random order, for better performance when cases are ordered % according to the targets. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2013-09-13. % % See also INFMETHODS.M. persistent last_ttau last_tnu % keep tilde parameters between calls tol = 1e-4; max_sweep = 10; min_sweep = 2; % tolerance to stop EP iterations inf = 'infEP'; n = size(x,1); K = feval(cov{:}, hyp.cov, x); % evaluate the covariance matrix m = feval(mean{:}, hyp.mean, x); % evaluate the mean vector % A note on naming: variables are given short but descriptive names in % accordance with Rasmussen & Williams "GPs for Machine Learning" (2006): mu % and s2 are mean and variance, nu and tau are natural parameters. A leading t % means tilde, a subscript _ni means "not i" (for cavity parameters), or _n % for a vector of cavity parameters. N(f|mu,Sigma) is the posterior. % marginal likelihood for ttau = tnu = zeros(n,1); equals n*log(2) for likCum* nlZ0 = -sum(feval(lik{:}, hyp.lik, y, m, diag(K), inf)); if any(size(last_ttau) ~= [n 1]) % find starting point for tilde parameters ttau = zeros(n,1); tnu = zeros(n,1); % init to zero if no better guess Sigma = K; % initialize Sigma and mu, the parameters of .. mu = m; nlZ = nlZ0; % .. the Gaussian posterior approximation else ttau = last_ttau; tnu = last_tnu; % try the tilde values from previous call [Sigma,mu,L,alpha,nlZ] = epComputeParams(K, y, ttau, tnu, lik, hyp, m, inf); if nlZ > nlZ0 % if zero is better .. ttau = zeros(n,1); tnu = zeros(n,1); % .. then init with zero instead Sigma = K; % initialize Sigma and mu, the parameters of .. mu = m; nlZ = nlZ0; % .. the Gaussian posterior approximation end end nlZ_old = Inf; sweep = 0; % converged, max. sweeps or min. sweeps? while (abs(nlZ-nlZ_old) > tol && sweep < max_sweep) || sweep<min_sweep nlZ_old = nlZ; sweep = sweep+1; for i = randperm(n) % iterate EP updates (in random order) over examples tau_ni = 1/Sigma(i,i)-ttau(i); % first find the cavity distribution .. nu_ni = mu(i)/Sigma(i,i)-tnu(i); % .. params tau_ni and nu_ni % compute the desired derivatives of the indivdual log partition function [lZ, dlZ, d2lZ] = feval(lik{:}, hyp.lik, y(i), nu_ni/tau_ni, 1/tau_ni, inf); ttau_old = ttau(i); tnu_old = tnu(i); % find the new tilde params, keep old ttau(i) = -d2lZ /(1+d2lZ/tau_ni); ttau(i) = max(ttau(i),0); % enforce positivity i.e. lower bound ttau by zero tnu(i) = ( dlZ - nu_ni/tau_ni*d2lZ )/(1+d2lZ/tau_ni); dtt = ttau(i)-ttau_old; dtn = tnu(i)-tnu_old; % rank-1 update Sigma .. si = Sigma(:,i); ci = dtt/(1+dtt*si(i)); Sigma = Sigma - ci*si*si'; % takes 70% of total time mu = mu - (ci*(mu(i)+si(i)*dtn)-dtn)*si; % .. and recompute mu end % recompute since repeated rank-one updates can destroy numerical precision [Sigma,mu,L,alpha,nlZ] = epComputeParams(K, y, ttau, tnu, lik, hyp, m, inf); end if sweep == max_sweep && abs(nlZ-nlZ_old) > tol error('maximum number of sweeps exceeded in function infEP') end last_ttau = ttau; last_tnu = tnu; % remember for next call post.alpha = alpha; post.sW = sqrt(ttau); post.L = L; % return posterior params if nargout>2 % do we want derivatives? dnlZ = hyp; % allocate space for derivatives tau_n = 1./diag(Sigma)-ttau; % compute the log marginal likelihood nu_n = mu./diag(Sigma)-tnu; % vectors of cavity parameters sW = sqrt(ttau); F = alpha*alpha'-repmat(sW,1,n).*solve_chol(L,diag(sW)); % covariance hypers for i=1:length(hyp.cov) dK = feval(cov{:}, hyp.cov, x, [], i); dnlZ.cov(i) = -sum(sum(F.*dK))/2; end for i = 1:numel(hyp.lik) % likelihood hypers dlik = feval(lik{:}, hyp.lik, y, nu_n./tau_n, 1./tau_n, inf, i); dnlZ.lik(i) = -sum(dlik); end [junk,dlZ] = feval(lik{:}, hyp.lik, y, nu_n./tau_n, 1./tau_n, inf);% mean hyps for i = 1:numel(hyp.mean) dm = feval(mean{:}, hyp.mean, x, i); dnlZ.mean(i) = -dlZ'*dm; end end % function to compute the parameters of the Gaussian approximation, Sigma and % mu, and the negative log marginal likelihood, nlZ, from the current site % parameters, ttau and tnu. Also returns L (useful for predictions). function [Sigma,mu,L,alpha,nlZ] = epComputeParams(K,y,ttau,tnu,lik,hyp,m,inf) n = length(y); % number of training cases sW = sqrt(ttau); % compute Sigma and mu L = chol(eye(n)+sW*sW'.*K); % L'*L=B=eye(n)+sW*K*sW V = L'\(repmat(sW,1,n).*K); Sigma = K - V'*V; alpha = tnu-sW.*solve_chol(L,sW.*(K*tnu+m)); mu = K*alpha+m; v = diag(Sigma); tau_n = 1./diag(Sigma)-ttau; % compute the log marginal likelihood nu_n = mu./diag(Sigma)-tnu; % vectors of cavity parameters lZ = feval(lik{:}, hyp.lik, y, nu_n./tau_n, 1./tau_n, inf); p = tnu-m.*ttau; q = nu_n-m.*tau_n; % auxiliary vectors nlZ = sum(log(diag(L))) - sum(lZ) - p'*Sigma*p/2 + (v'*p.^2)/2 ... - q'*((ttau./tau_n.*q-2*p).*v)/2 - sum(log(1+ttau./tau_n))/2;
github
Hadisalman/stoec-master
infVB.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/inf/infVB.m
6,024
utf_8
ff46ca9c2cce23402f0058955fe60b93
function [post, nlZ, dnlZ] = infVB(hyp, mean, cov, lik, x, y, opt) % Variational approximation to the posterior Gaussian process. % The function takes a specified covariance function (see covFunctions.m) and % likelihood function (see likFunctions.m), and is designed to be used with % gp.m. See also infMethods.m. % % Minimisation of an upper bound on the negative marginal likelihood using a % sequence of infLaplace calls where the smoothed likelihood % likVB(f) = lik(..,g,..) * exp(b*(f-g)), g = sign(f-z)*sqrt((f-z)^2+v)+z, where % v .. marginal variance = (positive) smoothing width, and % lik .. lik function such that p(y|f)=lik(..,f,..). % % The problem is convex whenever the likelihood is log-concave. At the end, the % optimal width W is obtained analytically. % % Copyright (c) by Hannes Nickisch 2014-03-20. % % See also INFMETHODS.M. n = size(x,1); K = feval(cov{:}, hyp.cov, x); % evaluate the covariance matrix m = feval(mean{:}, hyp.mean, x); % evaluate the mean vector if iscell(lik), likstr = lik{1}; else likstr = lik; end if ~ischar(likstr), likstr = func2str(likstr); end if nargin<=6, opt = []; end % make opt variable available if ~isfield(opt,'postL'), opt.postL = false; end % not compute L in infLaplace if isfield(opt,'out_nmax'), out_nmax = opt.out_nmax; % maximal no of outer loops else out_nmax = 15; end % default value if isfield(opt,'out_tol'), out_tol = opt.out_tol; % outer loop convergence else out_tol = 1e-5; end % default value sW = ones(n,1); % init with some reasonable value opt.postL = false; % avoid computation of L inside infLaplace for i=1:out_nmax U = chol(eye(n)+sW*sW'.*K)'\(repmat(sW,1,n).*K); v = diag(K) - sum(U.*U,1)'; % v = diag( inv(inv(K)+diag(sW.*sW)) ) post = infLaplace(hyp, m, K, {@likVB,v,lik}, x, y, opt); % post.sW is very different from the optimal sW for non Gaussian likelihoods sW_old = sW; f = m+K*post.alpha; % posterior mean [lp,dlp,d2lp,sW,b,z] = feval(@likVB,v,lik,hyp.lik,y,f); if max(abs(sW-sW_old))<out_tol, break, end % diagnose convergence end alpha = post.alpha; post.sW = sW; % posterior parameters post.L = chol(eye(n)+sW*sW'.*K); % recompute L'*L = B =eye(n)+sW*K*sW ga = 1./(sW.*sW); be = b+z./ga; % variance, lower bound offset from likVB h = f.*(2*be-f./ga) - 2*lp - v./ga; % h(ga) = s*(2*b-f/ga)+ h*(s) - v*(1/ga) c = b+(z-m)./ga; t = post.L'\(c./sW); nlZ = sum(log(diag(post.L))) + (sum(h) + t'*t - (be.*be)'*ga )/2; % var. bound if nargout>2 % do we want derivatives? iKtil = repmat(sW,1,n).*solve_chol(post.L,diag(sW));% sW*B^-1*sW=inv(K+inv(W)) dnlZ = hyp; % allocate space for derivatives for j=1:length(hyp.cov) % covariance hypers dK = feval(cov{:}, hyp.cov, x, [], j); if j==1, w = iKtil*(c.*ga); end dnlZ.cov(j) = sum(sum(iKtil.*dK))/2 - (w'*dK*w)/2; end if ~strcmp(likstr,'likGauss') % likelihood hypers for j=1:length(hyp.lik) sign_fmz = 2*(f-z>=0)-1; % strict sign mapping; sign(0) = 1 g = sign_fmz.*sqrt((f-z).^2 + v) + z; dhhyp = -2*feval(lik{:},hyp.lik,y,g,[],'infLaplace',j); dnlZ.lik(j) = sum(dhhyp)/2; end else % special treatment for the Gaussian case dnlZ.lik = sum(sum( (post.L'\eye(n)).^2 )) - exp(2*hyp.lik)*(alpha'*alpha); end for j=1:length(hyp.mean) % mean hypers dm = feval(mean{:}, hyp.mean, x, j); dnlZ.mean(j) = -alpha'*dm; end end % Smoothed likelihood function; instead of p(y|f)=lik(..,f,..) compute % likVB(f) = lik(..,g,..)*exp(b*(f-g)), g = sign(f-z)*sqrt((f-z)^2+v)+z, where % v .. marginal variance = (positive) smoothing width, and % lik .. lik function such that feval(lik{:},varargin{:}) yields a result. % The smoothing results from a lower bound on the likelihood: % p(y|f) \ge exp( (b+z/ga)*f - f.^2/(2*ga) - h(ga)/2 ) function [varargout] = likVB(v, lik, varargin) [b,z] = feval(lik{:},varargin{1:2},[],zeros(size(v)),'infVB'); f = varargin{3}; % obtain location of evaluation sign_fmz = 2*(f-z>=0)-1; % strict sign mapping; sign(0) = 1 g = sign_fmz.*sqrt((f-z).^2 + v) + z; varargin{3} = g; id = v==0 | abs(f./sqrt(v+eps))>1e10; % correct asymptotics of f -> +/-Inf varargout = cell(nargout,1); % allocate output, eval lik(..,g,..) [varargout{1:min(nargout,3)}] = feval(lik{:},varargin{1:3},[],'infLaplace'); if nargout>0 lp = varargout{1}; varargout{1} = lp + b.*(f-g); varargout{1}(id) = lp(id); % correct asymptotics of f -> +/-Inf if nargout>1 % first derivative dg_df = (abs(f-z)+eps)./(abs(g-z)+eps); % stabilised dg/df for v=0, f=0 dlp = varargout{2}; varargout{2} = dlp.*dg_df + b.*(1-dg_df); varargout{2}(id) = dlp(id); % correct asymptotics of f -> +/-Inf if nargout>2 % second derivative d2lp = varargout{3}; g_e = g-z + sign_fmz*eps; v_g3 = v./(g_e.*g_e.*g_e); % stabilised v./g.^3 to cover v=0 and f=0 varargout{3} = (dlp-b).*v_g3 + d2lp.*dg_df.*dg_df; varargout{3}(id) = d2lp(id); % correct asymptotics of f -> +/-Inf if nargout>3 W = abs( (b-dlp)./(g-z+sign_fmz/1.5e8) ); % optimal sW value varargout{4} = sqrt(W); if nargout>4 varargout{5} = b; if nargout>5 varargout{6} = z; end end end end end end
github
Hadisalman/stoec-master
infLaplace.m
.m
stoec-master/code/Include/gpml-matlab-v3.5-2014-12-08/inf/infLaplace.m
7,949
utf_8
297780be514bf1d87f826763094f104f
function [post nlZ dnlZ] = infLaplace(hyp, mean, cov, lik, x, y, opt) % Laplace approximation to the posterior Gaussian process. % The function takes a specified covariance function (see covFunctions.m) and % likelihood function (see likFunctions.m), and is designed to be used with % gp.m. See also infMethods.m. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2013-05-02. % % See also INFMETHODS.M. persistent last_alpha % copy of the last alpha if any(isnan(last_alpha)), last_alpha = zeros(size(last_alpha)); end % prevent if nargin<=6, opt = []; end % make opt variable available if isfield(opt,'postL'), postL = opt.postL; % recompute matrix L for post else postL = true; end % default value inf = 'infLaplace'; n = size(x,1); if isnumeric(cov), K = cov; % use provided covariance matrix else K = feval(cov{:}, hyp.cov, x); end % evaluate the covariance matrix if isnumeric(mean), m = mean; % use provided mean vector else m = feval(mean{:}, hyp.mean, x); end % evaluate the mean vector likfun = @(f) feval(lik{:},hyp.lik,y,f,[],inf); % log likelihood function if any(size(last_alpha)~=[n,1]) % find a good starting point for alpha and f alpha = zeros(n,1); % start at mean if sizes do not match else alpha = last_alpha; % try last one if Psi(alpha,m,K,likfun) > -sum(likfun(m)) % default f==m better => use it alpha = zeros(n,1); end end % switch between optimisation methods alpha = irls(alpha, m,K,likfun, opt); % run optimisation f = K*alpha+m; % compute latent function values last_alpha = alpha; % remember for next call [lp,dlp,d2lp,d3lp] = likfun(f); W = -d2lp; isWneg = any(W<0); post.alpha = alpha; % return the posterior parameters post.sW = sqrt(abs(W)).*sign(W); % preserve sign in case of negative % diagnose optimality err = @(x,y) norm(x-y)/max([norm(x),norm(y),1]); % we need to have alpha = dlp % dev = err(alpha,dlp); if dev>1e-4, warning('Not at optimum %1.2e.',dev), end if postL || nargout>1 if isWneg % switch between Cholesky and LU decomposition mode % For post.L = -inv(K+diag(1./W)), we us the non-default parametrisation. [ldA, iA, post.L] = logdetA(K,W); % A=eye(n)+K*W is as safe as symmetric B nlZ = alpha'*(f-m)/2 - sum(lp) + ldA/2; else sW = post.sW; post.L = chol(eye(n)+sW*sW'.*K); % recompute nlZ = alpha'*(f-m)/2 + sum(log(diag(post.L))-lp); % ..(f-m)/2 -lp +ln|B|/2 end end if nargout>2 % do we want derivatives? dnlZ = hyp; % allocate space for derivatives if isWneg % switch between Cholesky and LU decomposition mode Z = -post.L; % inv(K+inv(W)) g = sum(iA.*K,2)/2; % deriv. of ln|B| wrt W; g = diag(inv(inv(K)+diag(W)))/2 else Z = repmat(sW,1,n).*solve_chol(post.L,diag(sW)); %sW*inv(B)*sW=inv(K+inv(W)) C = post.L'\(repmat(sW,1,n).*K); % deriv. of ln|B| wrt W g = (diag(K)-sum(C.^2,1)')/2; % g = diag(inv(inv(K)+W))/2 end dfhat = g.*d3lp; % deriv. of nlZ wrt. fhat: dfhat=diag(inv(inv(K)+W)).*d3lp/2 for i=1:length(hyp.cov) % covariance hypers dK = feval(cov{:}, hyp.cov, x, [], i); dnlZ.cov(i) = sum(sum(Z.*dK))/2 - alpha'*dK*alpha/2; % explicit part b = dK*dlp; % b-K*(Z*b) = inv(eye(n)+K*diag(W))*b dnlZ.cov(i) = dnlZ.cov(i) - dfhat'*( b-K*(Z*b) ); % implicit part end for i=1:length(hyp.lik) % likelihood hypers [lp_dhyp,dlp_dhyp,d2lp_dhyp] = feval(lik{:},hyp.lik,y,f,[],inf,i); dnlZ.lik(i) = -g'*d2lp_dhyp - sum(lp_dhyp); % explicit part b = K*dlp_dhyp; % b-K*(Z*b) = inv(eye(n)+K*diag(W))*b dnlZ.lik(i) = dnlZ.lik(i) - dfhat'*( b-K*(Z*b) ); % implicit part end for i=1:length(hyp.mean) % mean hypers dm = feval(mean{:}, hyp.mean, x, i); dnlZ.mean(i) = -alpha'*dm; % explicit part dnlZ.mean(i) = dnlZ.mean(i) - dfhat'*(dm-K*(Z*dm)); % implicit part end end % Evaluate criterion Psi(alpha) = alpha'*K*alpha + likfun(f), where % f = K*alpha+m, and likfun(f) = feval(lik{:},hyp.lik,y, f, [],inf). function [psi,dpsi,f,alpha,dlp,W] = Psi(alpha,m,K,likfun) f = K*alpha+m; [lp,dlp,d2lp] = likfun(f); W = -d2lp; psi = alpha'*(f-m)/2 - sum(lp); if nargout>1, dpsi = K*(alpha-dlp); end % Run IRLS Newton algorithm to optimise Psi(alpha). function alpha = irls(alpha, m,K,likfun, opt) if isfield(opt,'irls_maxit'), maxit = opt.irls_maxit; % max no of Newton steps else maxit = 20; end % default value if isfield(opt,'irls_Wmin'), Wmin = opt.irls_Wmin; % min likelihood curvature else Wmin = 0.0; end % default value if isfield(opt,'irls_tol'), tol = opt.irls_tol; % stop Newton iterations else tol = 1e-6; end % default value smin_line = 0; smax_line = 2; % min/max line search steps size range nmax_line = 10; % maximum number of line search steps thr_line = 1e-4; % line search threshold Psi_line = @(s,alpha,dalpha) Psi(alpha+s*dalpha, m,K,likfun); % line search pars_line = {smin_line,smax_line,nmax_line,thr_line}; % line seach parameters search_line = @(alpha,dalpha) brentmin(pars_line{:},Psi_line,5,alpha,dalpha); f = K*alpha+m; [lp,dlp,d2lp] = likfun(f); W = -d2lp; n = size(K,1); Psi_new = Psi(alpha,m,K,likfun); Psi_old = Inf; % make sure while loop starts by the largest old objective val it = 0; % this happens for the Student's t likelihood while Psi_old - Psi_new > tol && it<maxit % begin Newton Psi_old = Psi_new; it = it+1; % limit stepsize W = max(W,Wmin); % reduce step size by increasing curvature of problematic W sW = sqrt(W); L = chol(eye(n)+sW*sW'.*K); % L'*L=B=eye(n)+sW*K*sW b = W.*(f-m) + dlp; dalpha = b - sW.*solve_chol(L,sW.*(K*b)) - alpha; % Newton dir + line search [s_line,Psi_new,n_line,dPsi_new,f,alpha,dlp,W] = search_line(alpha,dalpha); end % end Newton's iterations % Compute the log determinant ldA and the inverse iA of a square nxn matrix % A = eye(n) + K*diag(w) from its LU decomposition; for negative definite A, we % return ldA = Inf. We also return mwiA = -diag(w)/A. function [ldA,iA,mwiA] = logdetA(K,w) [m,n] = size(K); if m~=n, error('K has to be nxn'), end A = eye(n)+K.*repmat(w',n,1); [L,U,P] = lu(A); u = diag(U); % compute LU decomposition, A = P'*L*U signU = prod(sign(u)); % sign of U detP = 1; % compute sign (and det) of the permutation matrix P p = P*(1:n)'; for i=1:n % swap entries if i~=p(i), detP = -detP; j = find(p==i); p([i,j]) = p([j,i]); end end if signU~=detP % log becomes complex for negative values, encoded by infinity ldA = Inf; else % det(L) = 1 and U triangular => det(A) = det(P)*prod(diag(U)) ldA = sum(log(abs(u))); end if nargout>1, iA = U\(L\P); end % return the inverse if required if nargout>2, mwiA = -repmat(w,1,n).*iA; end
github
Hadisalman/stoec-master
ipdm.m
.m
stoec-master/code/Include/InterPointDistanceMatrix/ipdm.m
39,104
utf_8
d686ea7e03c771fcb892fb17417b3f23
function d = ipdm(data1,varargin) % ipdm: Inter-Point Distance Matrix % usage: d = ipdm(data1) % usage: d = ipdm(data1,data2) % usage: d = ipdm(data1,prop,value) % usage: d = ipdm(data1,data2,prop,value) % % Arguments: (input) % data1 - array of data points, each point is one row. p dimensional % data will be represented by matrix with p columns. % If only data1 is provided, then the distance matrix % is computed between all pairs of rows of data1. % % If your data is one dimensional, it MUST form a column % vector. A row vector of length n will be interpreted as % an n-dimensional data set. % % data2 - second array, supplied only if distances are to be computed % between two sets of points. % % % Class support: data1 and data2 are assumed to be either % single or double precision. I have not tested this code to % verify its success on integer data of any class. % % % Additional parameters are expected to be property/value pairs. % Property/value pairs are pairs of arguments, the first of which % (properties) must always be a character string. These strings % may be shortened as long as the shortening is unambiguous. % Capitalization is ignored. Valid properties for ipdm are: % % 'Metric', 'Subset', 'Limit', 'Result' % % 'Metric' - numeric flag - defines the distance metric used % metric = 2 --> (DEFAULT) Euclidean distance = 2-norm % The standard distance metric. % % metric = 1 --> 1-norm = sum of absolute differences % Also sometimes known as the "city block % metric", since this is the sum of the % differences in each dimension. % % metric = inf --> infinity-norm = maximum difference % over all dimensions. The name refers % to the limit of the p-norm, as p % approaches infinity. % % metric = 0 --> minimum difference over all dimensions. % This is not really a useful norm in % practice. % % Note: while other distance metrics exist, IMHO, these % seemed to be the common ones. % % % 'Result' - A string variable that denotes the style of returned % result. Valid result types are 'Array', 'Structure'. % Capitalization is ignored, and the string may be % shortened if you wish. % % result = 'Array' --> (DEFAULT) A matrix of all % interpoint distances will be generated. % This array may be large. If this option % is specified along with a minimum or % maximum value, then those elements above % or below the limiting values will be % set as -inf or +inf, as appropriate. % % When any of 'LargestFew', 'SmallestFew', % or 'NearestNeighbor' are set, then the % resulting array will be a sparse matrix % if 'array' is specified as the result. % % result = 'Structure' --> A list of all computed distances, % defined as a structure. This structure % will have fields named 'rowindex', % 'columnindex', and 'distance'. % % This option will be useful when a subset % criterion for the distances has been % specified, since then the distance matrix % may be very sparsely populated. Distances % for pairs outside of the criterion will % not be returned. % % % 'Subset' - Character string, any of: % % 'All', 'Maximum', 'Minimum', 'LargestFew', 'SmallestFew', % 'NearestNeighbor', 'FarthestNeighbor', or empty % % Like properties, capitalization is ignored here, and % any unambiguous shortening of the word is acceptable. % % DEFAULT = 'All' % % Some interpoint distance matrices can be huge. Often % these matrices are too large to be fully retained in % memory, yet only the pair of points with the largest % or smallest distance may be needed. When only some % subset of the complete set of distances is of interest, % these options allow you to specify which distances will % be returned. % % If 'result' is defined to be an array, then a sparse % matrix will be returned for the 'LargestFew', 'SmallestFew', % 'NearestNeighbor', and 'FarthestNeighbor' subset classes. % 'Minimum' and 'Maximum' will yield full matrices by % default. If a structure is specified, then only those % elements which have been identified will be returned. % % Where a subset is specified, its limiting value is % specified by the 'Limit' property. Call that value k. % % % 'All' --> (DEFAULT) Return all interpoint distances % % 'Minimum' --> Only look for those distances above % the cutoff k. All other distances will % be returned as -inf. % % 'Maximum' --> Only look for those distances below % the cutoff k. All other distances will % be returned as +inf. % % 'SmallestFew' --> Only return the subset of the k % smallest distances. Where only one data % set is provided, only the upper triangle % of the inter-point distance matrix will % be generated since that matrix is symmetric. % % 'LargestFew' --> Only return the subset of the k % largest distances. Where only one data % set is provided, only the upper triangle % of the inter-point distance matrix will % be generated since that matrix is symmetric. % % 'NearestNeighbor' --> Only return the single nearest % neighbor in data2 to each point in data1. % No limiting value is required for this % option. If multiple points have the same % nearest distance, then return the first % such point found. With only one input set, % a point will not be its own nearest % neighbor. % % Note that exact replicates in a single set % will cause problems, since a sparse matrix % is returned by default. Since they will have % a zero distance, they will not show up in % the sparse matrix. A structure return will % show those points as having a zero distance % though. % % 'FarthestNeighbor' --> Only return the single farthest % neighbor to each point. No limiting value % is required for this option. If multiple % points have the same farthest distance, % then return the first such point found. % % % 'Limit' - scalar numeric value or []. Used only when some % Subset is specified. % % DEFAULT = [] % % % 'ChunkSize' - allows a user with lower RAM limits % to force the code to only grab smaller chunks of RAM % at a time (where possible). This parameter is specified % in bytes of RAM. The default is 32 megabytes, or 2^22 % elements in any piece of the distance matrix. Only some % options will break the problem into chunks, thus as long % as a full matrix is expected to be returned, there seems % no reason to break the problem up into pieces. % % DEFAULT = 2^25 % % % Arguments: (output) % d - array of interpoint distances, or a struct wth the % fields {'rowindex', 'columnindex', 'distance'}. % % d(i,j) represents the distance between point i % (from data1) and point j (from data2). % % If only one (n1 x p) array is supplied, then d will % be an array of size == [n1,n1]. % % If two arrays (of sizes n1 x p and n2 x p) then d % will be an array of size == [n1,n2]. % % % Efficiency considerations: % Where possible, this code will use bsxfun to compute its % distances. % % % Example: % Compute the interpoint distances between all pairs of points % in a list of 5 points, in 2 dimensions and using Euclidean % distance as the distance metric. % % A = randn(5,2); % d = ipdm(A,'metric',2) % d = % 0 2.3295 3.2263 2.0263 2.8244 % 2.3295 0 1.1485 0.31798 1.0086 % 3.2263 1.1485 0 1.4318 1.8479 % 2.0263 0.31798 1.4318 0 1.0716 % 2.8244 1.0086 1.8479 1.0716 0 % % (see the demo file for many other examples) % % See also: pdist % % Author: John D'Errico % e-mail: [email protected] % Release: 1.0 % Release date: 2/26/08 % Default property values params.Metric = 2; params.Result = 'array'; params.Subset = 'all'; params.Limit = []; params.ChunkSize = 2^25; % untangle the arguments if nargin<1 % if called with no arguments, then the user probably % needs help. Give it to them. help ipdm return end % were two sets of data provided? pvpairs = {}; if nargin==1 % only 1 set of data provided dataflag = 1; data2 = []; else if ischar(varargin{1}) dataflag = 1; data2 = []; pvpairs = varargin; else dataflag = 2; data2 = varargin{1}; if nargin>2 pvpairs = varargin(2:end); end end end % get data sizes for later [n1,dim] = size(data1); if dataflag == 2 n2 = size(data2,1); end % Test the class of the input variables if ~(isa(data1,'double') || isa(data1,'single')) || ... ((dataflag == 2) && ~(isa(data2,'double') || isa(data2,'single'))) error('data points must be either single or double precision variables.') end % do we need to process any property/value pairs? if nargin>2 params = parse_pv_pairs(params,pvpairs); % check for problems in the properties % was a legal Subset provided? if ~isempty(params.Subset) && ~ischar(params.Subset) error('If provided, ''Subset'' must be character') elseif isempty(params.Subset) params.Subset = 'all'; end valid = {'all','maximum','minimum','largestfew','smallestfew', ... 'nearestneighbor','farthestneighbor'}; ind = find(strncmpi(params.Subset,valid,length(params.Subset))); if (length(ind)==1) params.Subset = valid{ind}; else error(['Invalid Subset: ',params.Subset]) end % was a limit provided? if ~ismember(params.Subset,{'all','nearestneighbor','farthestneighbor'}) && ... isempty(params.Limit) error('No limit provided, but a Subset that requires a limit value was specified') end % check the limit values for validity if length(params.Limit)>1 error('Limit must be scalar or empty') end switch params.Subset case {'largestfew', 'smallestfew'} % must be at least 1, and an integer if (params.Limit<1) || (round(params.Limit)~=params.Limit) error('Limit must be a positive integer for LargestFew or NearestFew') end end % was a legal Result provided? if isempty(params.Result) params.result = 'Array'; elseif ~ischar(params.Result) error('If provided, ''Result'' must be character or empty') end valid = {'array','structure'}; ind = find(strncmpi(params.Result,valid,length(params.Result))); if (length(ind)==1) params.Result = valid{ind}; else error(['Invalid Result: ',params.Subset]) end % check for the metric if isempty(params.Metric) params.Metric = 2; elseif (length(params.Metric)~=1) || ~ismember(params.Metric,[0 1 2 inf]) error('If supplied, ''Metric'' must be a scalar, and one of [0 1 2 inf]') end end % if nargin>2 % If Metric was given as 2, but the dimension is only 1, then it will % be slightly faster (and equivalent) to use the 1-norm Metric. if (dim == 1) && (params.Metric == 2) params.Metric = 1; end % Can we use bsxfun to compute the interpoint distances? % Older Matlab releases will not have bsxfun, but if it is % around, it will ne both faster and less of a memory hog. params.usebsxfun = (5==exist('bsxfun','builtin')); % check for dimension mismatch if 2 sets if (dataflag==2) && (size(data2,2)~=dim) error('If 2 point sets provided, then both must have the same number of columns') end % Total number of distances to compute, in case I must do it in batches if dataflag==1 n2 = n1; end ntotal = n1*n2; % FINALLY!!! Compute inter-point distances switch params.Subset case 'all' % The complete set of interpoint distances. There is no need % to break this into chunks, since we must return all distances. % If that is too much to compute in memory, then it will fail % anyway when we try to store the result. bsxfun will at least % do the computation efficiently. % One set or two? if dataflag == 1 d = distcomp(data1,data1,params); else d = distcomp(data1,data2,params); end % Must we return it as a struct? if params.Result(1) == 's' [rind,cind] = ndgrid(1:size(d,1),1:size(d,2)); ds.rowindex = rind(:); ds.columnindex = cind(:); ds.distance = d(:); d = ds; end case {'minimum' 'maximum'} % There is no reason to break this into pieces if the result % sill be filled in the end with +/- inf. Only break it up % if the final result is a struct. if ((ntotal*8)<=params.ChunkSize) || (params.Result(1) == 'a') % its small enough to do it all at once % One set or two? if dataflag == 1 d = distcomp(data1,data1,params); else d = distcomp(data1,data2,params); end % Must we return it as a struct? if params.Result(1) == 'a' % its an array, fill the unwanted distances with +/- inf if params.Subset(2) == 'i' % minimum d(d<=params.Limit) = -inf; else % maximum d(d>=params.Limit) = +inf; end else % a struct will be returned if params.Subset(2) == 'i' % minimum [dist.rowindex,dist.columnindex] = find(d>=params.Limit); else % maximum [dist.rowindex,dist.columnindex] = find(d<=params.Limit); end dist.distance = d(dist.rowindex + n1*(dist.columnindex-1)); d = dist; end else % we need to break this into chunks. This branch % will always return a struct. % this is the number of rows of data1 that we will % process at a time. bs = floor(params.ChunkSize/(8*n2)); bs = min(n1,max(1,bs)); % Accumulate the result into a cell array. Do it this % way because we don't know in advance how many elements % that we will find satisfying the minimum or maximum % limit specified. accum = cell(0,1); % now loop over the chunks batch = 1:bs; while ~isempty(batch) % One set or two? if dataflag == 1 dist = distcomp(data1(batch,:),data1,params); else dist = distcomp(data1(batch,:),data2,params); end % big or small as requested if ('i'==params.Subset(2)) % minimum value specified [I,J,V] = find(dist>=params.Limit); else % maximum limit [I,J] = find(dist<=params.Limit); I = I(:); J = J(:); V = dist(I + (J-1)*length(batch)); I = I + (batch(1)-1); end % and stuff them into the cell structure if ~isempty(V) accum{end+1,1} = [I,J,V(:)]; %#ok end % increment the batch batch = batch + bs; if batch(end)>n1 batch(batch>n1) = []; end end % convert the cells into one flat array accum = cell2mat(accum); if isempty(accum) d.rowindex = []; d.columnindex = []; d.distance = []; else % we found something % sort on the second column, to put them in a reasonable order accum = sortrows(accum,[2 1]); d.rowindex = accum(:,1); d.columnindex = accum(:,2); d.distance = accum(:,3); end end case {'smallestfew' 'largestfew'} % find the k smallest/largest distances. k is % given by params.Limit % if only 1 set, params.Limit must be less than n*(n-1)/2 if dataflag == 1 params.Limit = min(params.Limit,n1*(n1-1)/2); end % is this a large problem? if ((ntotal*8) <= params.ChunkSize) % small potatoes % One set or two? if dataflag == 1 dist = distcomp(data1,data1,params); % if only one data set, set the diagonal and % below that to +/- inf so we don't find it. temp = find(tril(ones(n1,n1),0)); if params.Subset(1) == 's' dist(temp) = inf; else dist(temp) = -inf; end else dist = distcomp(data1,data2,params); end % sort the distances to find those we need if ('s'==params.Subset(1)) % smallestfew [val,tags] = sort(dist(:),'ascend'); else % largestfew [val,tags] = sort(dist(:),'descend'); end val = val(1:params.Limit); tags = tags(1:params.Limit); % recover the row and column index from the linear % index returned by sort in tags. [d.rowindex,d.columnindex] = ind2sub([n1,size(dist,2)],tags); % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse(d.rowindex,d.columnindex,val,n1,size(dist,2)); else % a structure d.distance = val; end else % chunks % this is the number of rows of data1 that we will % process at a time. bs = floor(params.ChunkSize/(8*n2)); bs = min(n1,max(1,bs)); % We need to find the extreme cases. There are two possible % algorithms, depending on how many total elements we will % search for. % 1. Only a very few total elements. % 2. A relatively large number of total elements, forming % a significant fraction of the total set. % % Case #1 would suggest to retain params.Limit numberr of % elements from each batch, then at the end, sort them all % to find the best few. Case #2 will result in too many % elements to retain, so we must distinguish between these % alternatives. if (8*params.Limit*n1/bs) <= params.ChunkSize % params.Limit is small enough to fall into case #1. % Accumulate the result into a cell array. Do it this % way because we don't know in advance how many elements % that we will find satisfying the minimum or maximum % limit specified. accum = cell(0,1); % now loop over the chunks batch = (1:bs)'; while ~isempty(batch) % One set or two? if dataflag == 1 dist = distcomp(data1(batch,:),data1,params); k = find(tril(ones(length(batch),n2),batch(1)-1)); if ('s'==params.Subset(1)) dist(k) = inf; else dist(k) = -inf; end else dist = distcomp(data1(batch,:),data2,params); end % big or small as requested, keeping only the best % params.Limit number of elements if ('s'==params.Subset(1)) % minimum value specified [tags,tags] = sort(dist(:),1,'ascend'); tags = tags(1:min(bs,params.Limit)); [I,J] = ndgrid(batch,1:n2); ijv = [I(tags),J(tags),dist(tags)]; else % maximum limit [tags,tags] = sort(dist(:),1,'descend'); tags = tags(1:min(bs,params.Limit)); [I,J] = ndgrid(batch,1:n2); ijv = [I(tags),J(tags),dist(tags)]; end % catch for the bug when batch ends up as a scalar % in that case, matlab indexing of a vector causes a problem. if numel(batch) == 1 ijv = reshape(ijv,[],3); end % and stuff them into the cell structure accum{end+1,1} = ijv; %#ok % increment the batch batch = batch + bs; if batch(end)>n1 batch(batch>n1) = []; end end % convert the cells into one flat array accum = cell2mat(accum); % keep only the params.Limit best of those singled out accum = sortrows(accum,3); if ('s'==params.Subset(1)) % minimum value specified accum = accum(1:params.Limit,:); else % minimum value specified accum = accum(end + 1 - (1:params.Limit),:); end d.rowindex = accum(:,1); d.columnindex = accum(:,2); d.distance = accum(:,3); % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse(d.rowindex,d.columnindex,d.distance,n1,size(dist,2)); end else % params.Limit forces us into the domain of case #2. % Here we cannot retain params.Limit elements from each chunk. % so we will grab each chunk and append it to the best elements % found so far, then filter out the best after each chunk is % done. This may be slower than we want, but its the only way. ijv = zeros(0,3); % loop over the chunks batch = (1:bs)'; while ~isempty(batch) % One set or two? if dataflag == 1 dist = distcomp(data1(batch,:),data1,params); k = find(tril(ones(length(batch),n2),batch(1)-1)); if ('s'==params.Subset(1)) dist(k) = inf; else dist(k) = -inf; end else dist = distcomp(data1(batch,:),data2,params); end [I,J] = ndgrid(batch,1:n2); ijv = [ijv;[I(:),J(:),dist(:)]]; %#ok % big or small as requested, keeping only the best % params.Limit number of elements if size(ijv,1) > params.Limit if ('s'==params.Subset(1)) % minimum value specified [tags,tags] = sort(ijv(:,3),1,'ascend'); else [tags,tags] = sort(ijv(:,3),1,'ascend'); end ijv = ijv(tags(1:params.Limit),:); end % increment the batch batch = batch + bs; if batch(end)>n1 batch(batch>n1) = []; end end % They are fully trimmed down. stuff a structure d.rowindex = ijv(:,1); d.columnindex = ijv(:,2); d.distance = ijv(:,3); % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse(d.rowindex,d.columnindex,d.distance,n1,size(dist,2)); end end end case {'nearestneighbor' 'farthestneighbor'} % find the closest/farthest neighbor for every point % is this a large problem? Or a 1-d problem? if dim == 1 % its a 1-d nearest/farthest neighbor problem. we can % special case these easily enough, and all the distance % metric options are the same in 1-d. % first split it into the farthest versus nearest cases. if params.Subset(1) == 'f' % farthest away % One set or two? if dataflag == 1 [d2min,minind] = min(data1); [d2max,maxind] = max(data1); else [d2min,minind] = min(data2); [d2max,maxind] = max(data2); end d.rowindex = (1:n1)'; d.columnindex = repmat(maxind,n1,1); d.distance = repmat(d2max,n1,1); % which endpoint was further away? k = abs((data1 - d2min)) >= abs((data1 - d2max)); if any(k) d.columnindex(k) = minind; d.distance(k) = d2min; end else % nearest. this is mainly a sort and some fussing around. d.rowindex = (1:n1)'; d.columnindex = ones(n1,1); d.distance = zeros(n1,1); % One set or two? if dataflag == 1 % if only one data point, then we are done if n1 == 2 % if exactly two data points, its trivial d.columnindex = [2 1]; d.distance = repmat(abs(diff(data1)),2,1); elseif n1>2 % at least three points. do a sort. [sorted_data,tags] = sort(data1); % handle the first and last points separately d.columnindex(tags(1)) = tags(2); d.distance(tags(1)) = sorted_data(2) - sorted_data(1); d.columnindex(tags(end)) = tags(end-1); d.distance(tags(end)) = sorted_data(end) - sorted_data(end-1); ind = (2:(n1-1))'; d1 = sorted_data(ind) - sorted_data(ind-1); d2 = sorted_data(ind+1) - sorted_data(ind); k = d1 < d2; d.distance(tags(ind(k))) = d1(k); d.columnindex(tags(ind(k))) = tags(ind(k)-1); k = ~k; d.distance(tags(ind(k))) = d2(k); d.columnindex(tags(ind(k))) = tags(ind(k)+1); end % if n1 == 2 else % Two sets of data. still really a sort and some fuss. if n2 == 1 % there is only one point in data2 d.distance = abs(data1 - data2); % d.columnindex is already set correctly else % At least two points in data2 % We need to sort all the data points together, but also % know which points from each set went where. ind12 and % bool12 will help keep track. ind12 = [1:n1,1:n2]'; bool12 = [zeros(n1,1);ones(n2,1)]; [sorted_data,tags] = sort([data1;data2]); ind12 = ind12(tags); bool12 = bool12(tags); % where did each point end up after the sort? loc1 = find(~bool12); loc2 = find(bool12); % for each point in data1, what is the (sorted) data2 % element which appears most nearly to the left of it? cs = cumsum(bool12); leftelement = cs(loc1); % any points which fell below the minimum element in data2 % will have a zero for the index of the element on their % left. fix this. leftelement = max(1,leftelement); % likewise, any point greater than the max in data2 will % have an n2 in left element. this too will be a problem % later, so fix it. leftelement = min(n2-1,leftelement); % distance to the left hand element dleft = abs(sorted_data(loc1) - sorted_data(loc2(leftelement))); dright = abs(sorted_data(loc1) - sorted_data(loc2(leftelement+1))); % find the points which are closer to the left element in data2 k = (dleft < dright); d.distance(ind12(loc1(k))) = dleft(k); d.columnindex(ind12(loc1(k))) = ind12(loc2(leftelement(k))); k = ~k; d.distance(ind12(loc1(k))) = dright(k); d.columnindex(ind12(loc1(k))) = ind12(loc2(leftelement(k)+1)); end % if n2 == 1 end % if dataflag == 1 end % if params.Subset(1) == 'f' % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse(d.rowindex,d.columnindex,d.distance,n1,n2); end elseif (ntotal>1000) && (((params.Metric == 0) && (params.Subset(1) == 'n')) || ... ((params.Metric == inf) && (params.Subset(1) == 'f'))) % nearest/farthest neighbour in n>1 dimensions, but for an % infinity norm metric. Reduce this to a sequence of % 1-d problems, each of which will be faster in general. % do this only if the problem is moderately large, since % we must overcome the extra overhead of the recursive % calls to ipdm. % do the first dimension if dataflag == 1 d = ipdm(data1(:,1),data1(:,1),'subset',params.Subset,'metric',params.Metric,'result','struct'); else d = ipdm(data1(:,1),data2(:,1),'subset',params.Subset,'metric',params.Metric,'result','struct'); end % its slightly different for nearest versus farthest here % now, loop over dimensions for i = 2:dim if dataflag == 1 di = ipdm(data1(:,i),data1(:,i),'subset',params.Subset,'metric',params.Metric,'result','struct'); else di = ipdm(data1(:,i),data2(:,i),'subset',params.Subset,'metric',params.Metric,'result','struct'); end % did any of the distances change? if params.Metric == 0 % the 0 norm, with nearest neighbour, so take the % smallest distance in any dimension. k = d.distance > di.distance; else % inf norm. so take the largest distance across dimensions k = d.distance < di.distance; end if any(k) d.distance(k) = di.distance(k); d.columnindex(k) = di.columnindex(k); end end % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse(d.rowindex,d.columnindex,d.distance,n1,n2); end elseif ((ntotal*8) <= params.ChunkSize) % None of the other special cases apply, so do it using brute % force for the small potatoes problem. % One set or two? if dataflag == 1 dist = distcomp(data1,data1,params); else dist = distcomp(data1,data2,params); end % if only one data set and if a nearest neighbor % problem, set the diagonal to +inf so we don't find it. if (dataflag==1) && (n1>1) && ('n'==params.Subset(1)) diagind = (1:n1) + (0:n1:(n1^2-1)); dist(diagind) = +inf; end if ('n'==params.Subset(1)) % nearest [val,j] = min(dist,[],2); else % farthest [val,j] = max(dist,[],2); end % create the matrix as a sparse one or a struct? if params.Result(1)=='a' % its an array, so make the array sparse. d = sparse((1:n1)',j,val,n1,size(dist,2)); else % a structure d.rowindex = (1:n1)'; d.columnindex = j; d.distance = val; end else % break it into chunks bs = floor(params.ChunkSize/(8*n2)); bs = min(n1,max(1,bs)); % pre-allocate the result d.rowindex = (1:n1)'; d.columnindex = zeros(n1,1); d.distance = zeros(n1,1); % now loop over the chunks batch = 1:bs; while ~isempty(batch) % One set or two? if dataflag == 1 dist = distcomp(data1(batch,:),data1,params); else dist = distcomp(data1(batch,:),data2,params); end % if only one data set and if a nearest neighbor % problem, set the diagonal to +inf so we don't find it. if (dataflag==1) && (n1>1) && ('n'==params.Subset(1)) diagind = 1:length(batch); diagind = diagind + (diagind-2+batch(1))*length(batch); dist(diagind) = +inf; end % big or small as requested if ('n'==params.Subset(1)) % nearest [val,j] = min(dist,[],2); else % farthest [val,j] = max(dist,[],2); end % and stuff them into the result structure d.columnindex(batch) = j; d.distance(batch) = val; % increment the batch batch = batch + bs; if batch(end)>n1 batch(batch>n1) = []; end end % did we need to return a struct or an array? if params.Result(1) == 'a' % an array. make it a sparse one d = sparse(d.rowindex,d.columnindex,d.distance,n1,n2); end end % if dim == 1 end % switch params.Subset % End of mainline % ====================================================== % begin subfunctions % ====================================================== function d = distcomp(set1,set2,params) % Subfunction to compute all distances between two sets of points dim = size(set1,2); % can we take advantage of bsxfun? % Note: in theory, there is no need to loop over the dimensions. We % could Just let bsxfun do ALL the work, then wrap a sum around the % outside. In practice, this tends to create large intermediate % arrays, especially in higher numbers of dimensions. Its also when % we might gain here by use of a vectorized code. This will only be % a serious gain when the number of points is relatively small and % the dimension is large. if params.usebsxfun % its a recent enough version of matlab that we can % use bsxfun at all. n1 = size(set1,1); n2 = size(set2,1); if (dim>1) && ((n1*n2*dim)<=params.ChunkSize) % its a small enough problem that we might gain by full % use of bsxfun switch params.Metric case 2 d = sum(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim])).^2,3); case 1 d = sum(abs(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim]))),3); case inf d = max(abs(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim]))),[],3); case 0 d = min(abs(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim]))),[],3); end else % too big, so that the ChunkSize will have been exceeded, or just 1-d if params.Metric == 2 d = bsxfun(@minus,set1(:,1),set2(:,1)').^2; else d = abs(bsxfun(@minus,set1(:,1),set2(:,1)')); end for i=2:dim switch params.Metric case 2 d = d + bsxfun(@minus,set1(:,i),set2(:,i)').^2; case 1 d = d + abs(bsxfun(@minus,set1(:,i),set2(:,i)')); case inf d = max(d,abs(bsxfun(@minus,set1(:,i),set2(:,i)'))); case 0 d = min(d,abs(bsxfun(@minus,set1(:,i),set2(:,i)'))); end end end else % Cannot use bsxfun. Sigh. Do things the hard (and slower) way. n1 = size(set1,1); n2 = size(set2,1); if params.Metric == 2 % Note: While some people might use a different Euclidean % norm computation based on expanding the square of the % difference of two numbers, that computation is inherantly % inaccurate when implemented in floating point arithmetic. % While it might be faster, I won't use it here. Sorry. d = (repmat(set1(:,1),1,n2) - repmat(set2(:,1)',n1,1)).^2; else d = abs(repmat(set1(:,1),1,n2) - repmat(set2(:,1)',n1,1)); end for i=2:dim switch params.Metric case 2 d = d + (repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1)).^2; case 1 d = d + abs(repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1)); case inf d = max(d,abs(repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1))); case 0 d = min(d,abs(repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1))); end end end % if 2 norm, then we must sqrt at the end if params.Metric==2 d = sqrt(d); end % ============================================================== % end main ipdm % begin included function - parse_pv_pairs % ============================================================== function params=parse_pv_pairs(params,pv_pairs) % parse_pv_pairs: parses sets of property value pairs, allows defaults % usage: params=parse_pv_pairs(default_params,pv_pairs) % % arguments: (input) % default_params - structure, with one field for every potential % property/value pair. Each field will contain the default % value for that property. If no default is supplied for a % given property, then that field must be empty. % % pv_array - cell array of property/value pairs. % Case is ignored when comparing properties to the list % of field names. Also, any unambiguous shortening of a % field/property name is allowed. % % arguments: (output) % params - parameter struct that reflects any updated property/value % pairs in the pv_array. % % Example usage: % First, set default values for the parameters. Assume we % have four parameters that we wish to use optionally in % the function examplefun. % % - 'viscosity', which will have a default value of 1 % - 'volume', which will default to 1 % - 'pie' - which will have default value 3.141592653589793 % - 'description' - a text field, left empty by default % % The first argument to examplefun is one which will always be % supplied. % % function examplefun(dummyarg1,varargin) % params.Viscosity = 1; % params.Volume = 1; % params.Pie = 3.141592653589793 % % params.Description = ''; % params=parse_pv_pairs(params,varargin); % params % % Use examplefun, overriding the defaults for 'pie', 'viscosity' % and 'description'. The 'volume' parameter is left at its default. % % examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world') % % params = % Viscosity: 10 % Volume: 1 % Pie: 3 % Description: 'Hello world' % % Note that capitalization was ignored, and the property 'viscosity' % was truncated as supplied. Also note that the order the pairs were % supplied was arbitrary. npv = length(pv_pairs); n = npv/2; if n~=floor(n) error 'Property/value pairs must come in PAIRS.' end if n<=0 % just return the defaults return end if ~isstruct(params) error 'No structure for defaults was supplied' end % there was at least one pv pair. process any supplied propnames = fieldnames(params); lpropnames = lower(propnames); for i=1:n p_i = lower(pv_pairs{2*i-1}); v_i = pv_pairs{2*i}; ind = strmatch(p_i,lpropnames,'exact'); if isempty(ind) ind = find(strncmp(p_i,lpropnames,length(p_i))); if isempty(ind) error(['No matching property found for: ',pv_pairs{2*i-1}]) elseif length(ind)>1 error(['Ambiguous property name: ',pv_pairs{2*i-1}]) end end p_i = propnames{ind}; % override the corresponding default in params. % Use setfield for comptability issues with older releases. params = setfield(params,p_i,v_i); %#ok end
github
Hadisalman/stoec-master
domain2meshgrid.m
.m
stoec-master/code/Include/vectorized_meshgrid/domain2meshgrid.m
2,502
utf_8
8adb8734c239cfe0c94f31fb942ea979
function [X, Y, Z] = domain2meshgrid(domain, resolution) %DOMAIN2MESHGRID(domain, resolution) generate meshgrid on parallelepiped % [X, Y] = DOMAIN2MESHGRID(domain, resolution) creates the matrices % X, Y definining a meshgrid covering the 2D rectangular domain % domain = [xmin, xmax, ymin, ymax] with resolution = [nx, ny] points % per each coordinate dimension. % % [X, Y, Z] = DOMAIN2MESHGRID(domain, resolution) results into a % meshgrid over a 3D parallelepiped domain. % % input (2D Case) % domain = extremal values of parallelepiped % = [xmin, xmax, ymin, ymax] % resolution = # points /dimension % = [nx, ny] % % output (2D case) % X = [ny x nx] matrix of grid point abscissas % Y = [ny x nx] matrix of grid point ordinates % % input (3D Case) % domain = [xmin, xmax, ymin, ymax, zmin, zmax] % resolution = [nx, ny, nz] % % output (3D case) % X = [ny x nx x nz] matrix of grid point abscissas % Y = [ny x nx x nz] matrix of grid point ordinates % Z = [ny x nz x nz] matrix of grid point coordinates % % See also DOMAIN2VEC, VEC2MESHGRID, MESHGRID2VEC, MESHGRID. % % File: domain2meshgrid.m % Author: Ioannis Filippidis, [email protected] % Date: 2012.01.14 - % Language: MATLAB R2011b % Purpose: generate meshgrid on domain given a resolution % Copyright: Ioannis Filippidis, 2012- %% check input if size(domain, 1) ~= 1 error('size(domain, 1) ~= 1') end ndim = size(domain, 2) /2; if ~isint(ndim) error('Non-integer domain dimension.') end if ~isequal(size(resolution), [1, ndim] ) error('size(resolution) ~= [1, ndim]') end if ndim == 2 [X, Y] = linmeshgrid2d(domain, resolution); elseif ndim == 3 [X, Y, Z] = linmeshgrid3d(domain, resolution); end function [X, Y] = linmeshgrid2d(domain, resolution) xmin = domain(1, 1); xmax = domain(1, 2); ymin = domain(1, 3); ymax = domain(1, 4); nx = resolution(1, 1); ny = resolution(1, 2); x = linspace(xmin, xmax, nx); y = linspace(ymin, ymax, ny); [X, Y] = meshgrid(x, y); function [X, Y, Z] = linmeshgrid3d(domain, resolution) xmin = domain(1, 1); xmax = domain(1, 2); ymin = domain(1, 3); ymax = domain(1, 4); zmin = domain(1, 5); zmax = domain(1, 6); nx = resolution(1, 1); ny = resolution(1, 2); nz = resolution(1, 3); x = linspace(xmin, xmax, nx); y = linspace(ymin, ymax, ny); z = linspace(zmin, zmax, nz); [X, Y, Z] = meshgrid(x, y, z);
github
Hadisalman/stoec-master
example_vectorized_surf_plot.m
.m
stoec-master/code/Include/vectorized_meshgrid/example_vectorized_surf_plot.m
696
utf_8
1d885f126747d5f8ca76f6df48533d2a
function [] = example_vectorized_surf_plot % File: example_vectorized_surf_plot.m % Author: Ioannis Filippidis, [email protected] % Date: 2012.01.14 - 2012.02.11 % Language: MATLAB R2011b % Purpose: test meshgrid interface to functions taking as argument a % matrix of column vectors % Copyright: Ioannis Filippidis, 2012- dom = [-2, 2, -2, 2]; res = [31, 30]; [X, Y] = domain2meshgrid(dom, res); q = meshgrid2vec(X, Y); f = testf(q); f = vec2meshgrid(f, X); surf(X, Y, f) function [f] = testf(q) q0 = [1, 2].'; q_q0 = bsxfun(@minus, q, q0); f = sqrt(sum(q_q0.^2, 1) ); % instead use vnorm (Mathworks File Exchange) f = cos(f) .*sin(f);
github
Hadisalman/stoec-master
meshgrid2vec.m
.m
stoec-master/code/Include/vectorized_meshgrid/meshgrid2vec.m
1,541
utf_8
9b720737c64121c57177aa22a8b26e88
function [q] = meshgrid2vec(xgv, ygv, zgv) %MESHGRID2VEC meshgrid matrices to matrix of column vectors % % [q] = MESHGRIDVEC(xgv, ygv) takes the matrix of abscissas XGV and % ordinates YGV of meshgrid points as returned by MESHGRID and arranges % them as vectors comprising the columns of matrix Q. % % [q] = MESHGRIDVEC(xgv, ygv, zgv) does the same for the 3D case. % % input % xgv = matrix of meshgrid points' abscissas % = [#(points / y axis) x #(points / x axis) ] (2D case) or % = [#(points / y axis) x #(points / x axis) x #(points / z axis) ] % (3D case) % ygv = matrix of meshgrid points' ordinates % = similar dimensions with xgv % zgv = matrix of meshgrid points' coordinates % = similar dimensions with xgv % % output % q = [#dim x #(meshgrid points) ] % % See also DOMAIN2VEC, VEC2MESHGRID, DOMAIN2MESHGRID, MESHGRID. % % File: meshgrid2vec.m % Author: Ioannis Filippidis, [email protected] % Date: 2012.01.14 - % Language: MATLAB R2011b % Purpose: convert meshgrid matrices to matrix of column vectors % Copyright: Ioannis Filippidis, 2012- % check input if nargin == 2 ndim = 2; elseif nargin == 3 ndim = 3; else error('works only for ndim = 2 or ndim = 3/') end if ndim == 2 q = meshgridvec2d(xgv, ygv); elseif ndim == 3 q = meshgridvec3d(xgv, ygv, zgv); end function [q] = meshgridvec2d(x, y) q = [x(:), y(:) ].'; function [q] = meshgridvec3d(x, y, z) q = [x(:), y(:), z(:) ].';
github
Hadisalman/stoec-master
stlread.m
.m
stoec-master/code/Include/CMU_include/stlread.m
3,981
utf_8
f1c11b51cd13528daae6802cfcd3b539
function varargout = stlread(file) % STLREAD imports geometry from an STL file into MATLAB. % FV = STLREAD(FILENAME) imports triangular faces from the ASCII or binary % STL file idicated by FILENAME, and returns the patch struct FV, with fields % 'faces' and 'vertices'. % % [F,V] = STLREAD(FILENAME) returns the faces F and vertices V separately. % % [F,V,N] = STLREAD(FILENAME) also returns the face normal vectors. % % The faces and vertices are arranged in the format used by the PATCH plot % object. % Copyright 2011 The MathWorks, Inc. if ~exist(file,'file') error(['File ''%s'' not found. If the file is not on MATLAB''s path' ... ', be sure to specify the full path to the file.'], file); end fid = fopen(file,'r'); if ~isempty(ferror(fid)) error(lasterror); %#ok end M = fread(fid,inf,'uint8=>uint8'); fclose(fid); [f,v,n] = stlbinary(M); %if( isbinary(M) ) % This may not be a reliable test % [f,v,n] = stlbinary(M); %else % [f,v,n] = stlascii(M); %end varargout = cell(1,nargout); switch nargout case 2 varargout{1} = f; varargout{2} = v; case 3 varargout{1} = f; varargout{2} = v; varargout{3} = n; otherwise varargout{1} = struct('faces',f,'vertices',v); end end function [F,V,N] = stlbinary(M) F = []; V = []; N = []; if length(M) < 84 error('MATLAB:stlread:incorrectFormat', ... 'Incomplete header information in binary STL file.'); end % Bytes 81-84 are an unsigned 32-bit integer specifying the number of faces % that follow. numFaces = typecast(M(81:84),'uint32'); %numFaces = double(numFaces); if numFaces == 0 warning('MATLAB:stlread:nodata','No data in STL file.'); return end T = M(85:end); F = NaN(numFaces,3); V = NaN(3*numFaces,3); N = NaN(numFaces,3); numRead = 0; while numRead < numFaces % Each facet is 50 bytes % - Three single precision values specifying the face normal vector % - Three single precision values specifying the first vertex (XYZ) % - Three single precision values specifying the second vertex (XYZ) % - Three single precision values specifying the third vertex (XYZ) % - Two unused bytes i1 = 50 * numRead + 1; i2 = i1 + 50 - 1; facet = T(i1:i2)'; n = typecast(facet(1:12),'single'); v1 = typecast(facet(13:24),'single'); v2 = typecast(facet(25:36),'single'); v3 = typecast(facet(37:48),'single'); n = double(n); v = double([v1; v2; v3]); % Figure out where to fit these new vertices, and the face, in the % larger F and V collections. fInd = numRead + 1; vInd1 = 3 * (fInd - 1) + 1; vInd2 = vInd1 + 3 - 1; V(vInd1:vInd2,:) = v; F(fInd,:) = vInd1:vInd2; N(fInd,:) = n; numRead = numRead + 1; end end function [F,V,N] = stlascii(M) warning('MATLAB:stlread:ascii','ASCII STL files currently not supported.'); F = []; V = []; N = []; end % TODO: Change the testing criteria! Some binary STL files still begin with % 'solid'. function tf = isbinary(A) % ISBINARY uses the first line of an STL file to identify its format. if isempty(A) || length(A) < 5 error('MATLAB:stlread:incorrectFormat', ... 'File does not appear to be an ASCII or binary STL file.'); end if strcmpi('solid',char(A(1:5)')) tf = false; % ASCII else tf = true; % Binary end end
github
Hadisalman/stoec-master
icp.m
.m
stoec-master/code/Include/CMU_include/icp.m
18,647
utf_8
eb909b597a19b75b55810daee50f1676
function [TR, TT, ER, t] = icp(q,p,varargin) % Perform the Iterative Closest Point algorithm on three dimensional point % clouds. % % [TR, TT] = icp(q,p) returns the rotation matrix TR and translation % vector TT that minimizes the distances from (TR * p + TT) to q. % p is a 3xm matrix and q is a 3xn matrix. % % [TR, TT] = icp(q,p,k) forces the algorithm to make k iterations % exactly. The default is 10 iterations. % % [TR, TT, ER] = icp(q,p,k) also returns the RMS of errors for k % iterations in a (k+1)x1 vector. ER(0) is the initial error. % % [TR, TT, ER, t] = icp(q,p,k) also returns the calculation times per % iteration in a (k+1)x1 vector. t(0) is the time consumed for preprocessing. % % Additional settings may be provided in a parameter list: % % Boundary % {[]} | 1x? vector % If EdgeRejection is set, a vector can be provided that indexes into % q and specifies which points of q are on the boundary. % % EdgeRejection % {false} | true % If EdgeRejection is true, point matches to edge vertices of q are % ignored. Requires that boundary points of q are specified using % Boundary or that a triangulation matrix for q is provided. % % Extrapolation % {false} | true % If Extrapolation is true, the iteration direction will be evaluated % and extrapolated if possible using the method outlined by % Besl and McKay 1992. % % Matching % {bruteForce} | Delaunay | GLtree | kDtree % Specifies how point matching should be done. % bruteForce is usually the slowest and kDtree is the fastest. % Note that the kDtree option is depends on the Statistics Toolbox % v. 7.3 or higher. % Note that the GLtree option is depending on the GLtree3DFEX % implementation at Matlab Central File ID: #24607. % % Minimize % {point} | plane | lmaPoint % Defines whether point to point or point to plane minimization % should be performed. point is based on the SVD approach and is % usually the fastest. plane will often yield higher accuracy. It % uses linearized angles and requires surface normals for all points % in q. Calculation of surface normals requires substantial pre % proccessing. % The option lmaPoint does point to point minimization using the non % linear least squares Levenberg Marquardt algorithm. Results are % generally the same as in points, but computation time may differ. % % Normals % {[]} | n x 3 matrix % A matrix of normals for the n points in q might be provided. % Normals of q are used for point to plane minimization. % Else normals will be found through a PCA of the 4 nearest % neighbors. % % ReturnAll % {false} | true % Determines whether R and T should be returned for all iterations % or only for the last one. If this option is set to true, R will be % a 3x3x(k+1) matrix and T will be a 3x1x(k+1) matrix. % % Triangulation % {[]} | ? x 3 matrix % A triangulation matrix for the points in q can be provided, % enabling EdgeRejection. The elements should index into q, defining % point triples that act together as triangles. % % Verbose % {false} | true % Enables extrapolation output in the Command Window. % % Weight % {@(match)ones(1,m)} | Function handle % For point or plane minimization, a function handle to a weighting % function can be provided. The weighting function will be called % with one argument, a 1xm vector that specifies point pairs by % indexing into q. The weighting function should return a 1xm vector % of weights for every point pair. % % WorstRejection % {0} | scalar in ]0; 1[ % Reject a given percentage of the worst point pairs, based on their % Euclidean distance. % % Martin Kjer and Jakob Wilm, Technical University of Denmark, 2011 % Use the inputParser class to validate input arguments. inp = inputParser; inp.addRequired('q', @(x)isreal(x) && size(x,1) == 3); inp.addRequired('p', @(x)isreal(x) && size(x,1) == 3); inp.addOptional('iter', 10, @(x)x > 0 && x < 10^5); inp.addParamValue('Boundary', [], @(x)size(x,1) == 1); inp.addParamValue('EdgeRejection', false, @(x)islogical(x)); inp.addParamValue('Extrapolation', false, @(x)islogical(x)); validMatching = {'bruteForce','Delaunay','kDtree','GLtree'}; inp.addParamValue('Matching', 'bruteForce', @(x)any(strcmpi(x,validMatching))); validMinimize = {'point','plane','lmapoint'}; inp.addParamValue('Minimize', 'point', @(x)any(strcmpi(x,validMinimize))); inp.addParamValue('Normals', [], @(x)isreal(x) && size(x,1) == 3); inp.addParamValue('NormalsData', [], @(x)isreal(x) && size(x,1) == 3); inp.addParamValue('ReturnAll', false, @(x)islogical(x)); inp.addParamValue('Triangulation', [], @(x)isreal(x) && size(x,2) == 3); inp.addParamValue('Verbose', false, @(x)islogical(x)); inp.addParamValue('Weight', @(x)ones(1,length(x)), @(x)isa(x,'function_handle')); inp.addParamValue('WorstRejection', 0, @(x)isscalar(x) && x > 0 && x < 1); inp.parse(q,p,varargin{:}); arg = inp.Results; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Actual implementation % Allocate vector for RMS of errors in every iteration. t = zeros(arg.iter+1,1); % Start timer tic; Np = size(p,2); % Transformed data point cloud pt = p; % Allocate vector for RMS of errors in every iteration. ER = zeros(arg.iter+1,1); % Initialize temporary transform vector and matrix. T = zeros(3,1); R = eye(3,3); % Initialize total transform vector(s) and rotation matric(es). TT = zeros(3,1, arg.iter+1); TR = repmat(eye(3,3), [1,1, arg.iter+1]); % If Minimize == 'plane', normals are needed if (strcmp(arg.Minimize, 'plane') && isempty(arg.Normals)) arg.Normals = lsqnormest(q,4); end % If Matching == 'Delaunay', a triangulation is needed if strcmp(arg.Matching, 'Delaunay') DT = DelaunayTri(transpose(q)); end % If Matching == 'kDtree', a kD tree should be built (req. Stat. TB >= 7.3) if strcmp(arg.Matching, 'kDtree') kdOBJ = KDTreeSearcher(transpose(q)); end % If Matching == 'GLtree', a GL tree should be built (req. File ID: #24607) if strcmp(arg.Matching, 'GLtree') GLPNTR = BuildGLTree3DFEX(transpose(q)); end % If edge vertices should be rejected, find edge vertices if arg.EdgeRejection if isempty(arg.Boundary) bdr = find_bound(q, arg.Triangulation); else bdr = arg.Boundary; end end if arg.Extrapolation % Initialize total transform vector (quaternion ; translation vec.) qq = [ones(1,arg.iter+1);zeros(6,arg.iter+1)]; % Allocate vector for direction change and change angle. dq = zeros(7,arg.iter+1); theta = zeros(1,arg.iter+1); end t(1) = toc; % Go into main iteration loop for k=1:arg.iter % Do matching switch arg.Matching case 'bruteForce' [match mindist] = match_bruteForce(q,pt); case 'Delaunay' [match mindist] = match_Delaunay(q,pt,DT); case 'GLtree' [match mindist] = match_GLtree(q,pt,GLPNTR); case 'kDtree' [match mindist] = match_kDtree(q,pt,kdOBJ); end % If matches to edge vertices should be rejected if arg.EdgeRejection p_idx = not(ismember(match, bdr)); q_idx = match(p_idx); mindist = mindist(p_idx); else p_idx = true(1, Np); q_idx = match; end % If worst matches should be rejected if arg.WorstRejection edge = round((1-arg.WorstRejection)*sum(p_idx)); pairs = find(p_idx); [~, idx] = sort(mindist); p_idx(pairs(idx(edge:end))) = false; q_idx = match(p_idx); mindist = mindist(p_idx); end if k == 1 ER(k) = sqrt(sum(mindist.^2)/length(mindist)); end switch arg.Minimize case 'point' % Determine weight vector weights = arg.Weight(match); [R,T] = eq_point(q(:,q_idx),pt(:,p_idx), weights(p_idx)); case 'plane' weights = arg.Weight(match); [R,T] = eq_plane(q(:,q_idx),pt(:,p_idx),arg.Normals(:,q_idx),weights(p_idx)); case 'lmaPoint' [R,T] = eq_lmaPoint(q(:,q_idx),pt(:,p_idx)); end % Add to the total transformation TR(:,:,k+1) = R*TR(:,:,k); TT(:,:,k+1) = R*TT(:,:,k)+T; % Apply last transformation pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np); % Root mean of objective function ER(k+1) = rms_error(q(:,q_idx), pt(:,p_idx)); % If Extrapolation, we might be able to move quicker if arg.Extrapolation qq(:,k+1) = [rmat2quat(TR(:,:,k+1));TT(:,:,k+1)]; dq(:,k+1) = qq(:,k+1) - qq(:,k); theta(k+1) = (180/pi)*acos(dot(dq(:,k),dq(:,k+1))/(norm(dq(:,k))*norm(dq(:,k+1)))); if arg.Verbose disp(['Direction change ' num2str(theta(k+1)) ' degree in iteration ' num2str(k)]); end if k>2 && theta(k+1) < 10 && theta(k) < 10 d = [ER(k+1), ER(k), ER(k-1)]; v = [0, -norm(dq(:,k+1)), -norm(dq(:,k))-norm(dq(:,k+1))]; vmax = 25 * norm(dq(:,k+1)); dv = extrapolate(v,d,vmax); if dv ~= 0 q_mark = qq(:,k+1) + dv * dq(:,k+1)/norm(dq(:,k+1)); q_mark(1:4) = q_mark(1:4)/norm(q_mark(1:4)); qq(:,k+1) = q_mark; TR(:,:,k+1) = quat2rmat(qq(1:4,k+1)); TT(:,:,k+1) = qq(5:7,k+1); % Reapply total transformation pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np); % Recalculate root mean of objective function % Note this is costly and only for fun! switch arg.Matching case 'bruteForce' [~, mindist] = match_bruteForce(q,pt); case 'Delaunay' [~, mindist] = match_Delaunay(q,pt,DT); case 'GLtree' [~, mindist] = match_GLtree(q,pt,GLPNTR); case 'kDtree' [~, mindist] = match_kDtree(q,pt,kdOBJ); end ER(k+1) = sqrt(sum(mindist.^2)/length(mindist)); end end end t(k+1) = toc; end if not(arg.ReturnAll) TR = TR(:,:,end); TT = TT(:,:,end); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_bruteForce(q, p) m = size(p,2); n = size(q,2); match = zeros(1,m); mindist = zeros(1,m); for ki=1:m d=zeros(1,n); for ti=1:3 d=d+(q(ti,:)-p(ti,ki)).^2; end [mindist(ki),match(ki)]=min(d); end mindist = sqrt(mindist); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_Delaunay(q, p, DT) match = transpose(nearestNeighbor(DT, transpose(p))); mindist = sqrt(sum((p-q(:,match)).^2,1)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_GLtree(q, p, GLPNTR) [match mindist] = NNSearch3DFEX(transpose(q), transpose(p), GLPNTR); match = transpose(match); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_kDtree(~, p, kdOBJ) [match mindist] = knnsearch(kdOBJ,transpose(p)); match = transpose(match); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_point(q,p,weights) m = size(p,2); n = size(q,2); % normalize weights weights = weights ./ sum(weights); % find data centroid and deviations from centroid q_bar = q * transpose(weights); q_mark = q - repmat(q_bar, 1, n); % Apply weights q_mark = q_mark .* repmat(weights, 3, 1); % find data centroid and deviations from centroid p_bar = p * transpose(weights); p_mark = p - repmat(p_bar, 1, m); % Apply weights %p_mark = p_mark .* repmat(weights, 3, 1); N = p_mark*transpose(q_mark); % taking points of q in matched order [U,~,V] = svd(N); % singular value decomposition R = V*transpose(U); T = q_bar - R*p_bar; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_plane(q,p,n,weights) n = n .* repmat(weights,3,1); c = cross(p,n); cn = vertcat(c,n); C = cn*transpose(cn); b = - [sum(sum((p-q).*repmat(cn(1,:),3,1).*n)); sum(sum((p-q).*repmat(cn(2,:),3,1).*n)); sum(sum((p-q).*repmat(cn(3,:),3,1).*n)); sum(sum((p-q).*repmat(cn(4,:),3,1).*n)); sum(sum((p-q).*repmat(cn(5,:),3,1).*n)); sum(sum((p-q).*repmat(cn(6,:),3,1).*n))]; X = C\b; cx = cos(X(1)); cy = cos(X(2)); cz = cos(X(3)); sx = sin(X(1)); sy = sin(X(2)); sz = sin(X(3)); R = [cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz; cy*sz cx*cz+sx*sy*sz cx*sy*sz-cz*sx; -sy cy*sx cx*cy]; T = X(4:6); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_lmaPoint(q,p) Rx = @(a)[1 0 0; 0 cos(a) -sin(a); 0 sin(a) cos(a)]; Ry = @(b)[cos(b) 0 sin(b); 0 1 0; -sin(b) 0 cos(b)]; Rz = @(g)[cos(g) -sin(g) 0; sin(g) cos(g) 0; 0 0 1]; Rot = @(x)Rx(x(1))*Ry(x(2))*Rz(x(3)); myfun = @(x,xdata)Rot(x(1:3))*xdata+repmat(x(4:6),1,length(xdata)); options = optimset('Algorithm', 'levenberg-marquardt'); x = lsqcurvefit(myfun, zeros(6,1), p, q, [], [], options); R = Rot(x(1:3)); T = x(4:6); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Extrapolation in quaternion space. Details are found in: % % Besl, P., & McKay, N. (1992). A method for registration of 3-D shapes. % IEEE Transactions on pattern analysis and machine intelligence, 239?256. function [dv] = extrapolate(v,d,vmax) p1 = polyfit(v,d,1); % linear fit p2 = polyfit(v,d,2); % parabolic fit v1 = -p1(2)/p1(1); % linear zero crossing v2 = -p2(2)/(2*p2(1)); % polynomial top point if issorted([0 v2 v1 vmax]) || issorted([0 v2 vmax v1]) disp('Parabolic update!'); dv = v2; elseif issorted([0 v1 v2 vmax]) || issorted([0 v1 vmax v2])... || (v2 < 0 && issorted([0 v1 vmax])) disp('Line based update!'); dv = v1; elseif v1 > vmax && v2 > vmax disp('Maximum update!'); dv = vmax; else disp('No extrapolation!'); dv = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Determine the RMS error between two point equally sized point clouds with % point correspondance. % ER = rms_error(p1,p2) where p1 and p2 are 3xn matrices. function ER = rms_error(p1,p2) dsq = sum(power(p1 - p2, 2),1); ER = sqrt(mean(dsq)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Converts (orthogonal) rotation matrices R to (unit) quaternion % representations % % Input: A 3x3xn matrix of rotation matrices % Output: A 4xn matrix of n corresponding quaternions % % http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion function quaternion = rmat2quat(R) Qxx = R(1,1,:); Qxy = R(1,2,:); Qxz = R(1,3,:); Qyx = R(2,1,:); Qyy = R(2,2,:); Qyz = R(2,3,:); Qzx = R(3,1,:); Qzy = R(3,2,:); Qzz = R(3,3,:); w = 0.5 * sqrt(1+Qxx+Qyy+Qzz); x = 0.5 * sign(Qzy-Qyz) .* sqrt(1+Qxx-Qyy-Qzz); y = 0.5 * sign(Qxz-Qzx) .* sqrt(1-Qxx+Qyy-Qzz); z = 0.5 * sign(Qyx-Qxy) .* sqrt(1-Qxx-Qyy+Qzz); quaternion = reshape([w;x;y;z],4,[]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Converts (unit) quaternion representations to (orthogonal) rotation matrices R % % Input: A 4xn matrix of n quaternions % Output: A 3x3xn matrix of corresponding rotation matrices % % http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#From_a_quaternion_to_an_orthogonal_matrix function R = quat2rmat(quaternion) q0(1,1,:) = quaternion(1,:); qx(1,1,:) = quaternion(2,:); qy(1,1,:) = quaternion(3,:); qz(1,1,:) = quaternion(4,:); R = [q0.^2+qx.^2-qy.^2-qz.^2 2*qx.*qy-2*q0.*qz 2*qx.*qz+2*q0.*qy; 2*qx.*qy+2*q0.*qz q0.^2-qx.^2+qy.^2-qz.^2 2*qy.*qz-2*q0.*qx; 2*qx.*qz-2*q0.*qy 2*qy.*qz+2*q0.*qx q0.^2-qx.^2-qy.^2+qz.^2]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Least squares normal estimation from point clouds using PCA % % H. Hoppe, T. DeRose, T. Duchamp, J. McDonald, and W. Stuetzle. % Surface reconstruction from unorganized points. % In Proceedings of ACM Siggraph, pages 71:78, 1992. % % p should be a matrix containing the horizontally concatenated column % vectors with points. k is a scalar indicating how many neighbors the % normal estimation is based upon. % % Note that for large point sets, the function performs significantly % faster if Statistics Toolbox >= v. 7.3 is installed. % % Jakob Wilm 2010 function n = lsqnormest(p, k) m = size(p,2); n = zeros(3,m); v = ver('stats'); if str2double(v.Version) >= 7.3 neighbors = transpose(knnsearch(transpose(p), transpose(p), 'k', k+1)); else neighbors = kNearestNeighbors(p, p, k+1); end for i = 1:m x = p(:,neighbors(2:end, i)); p_bar = 1/k * sum(x,2); P = (x - repmat(p_bar,1,k)) * transpose(x - repmat(p_bar,1,k)); %spd matrix P %P = 2*cov(x); [V,D] = eig(P); [~, idx] = min(diag(D)); % choses the smallest eigenvalue n(:,i) = V(:,idx); % returns the corresponding eigenvector end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Boundary point determination. Given a set of 3D points and a % corresponding triangle representation, returns those point indices that % define the border/edge of the surface. function bound = find_bound(pts, poly) %Correcting polygon indices and converting datatype poly = double(poly); pts = double(pts); %Calculating freeboundary points: TR = TriRep(poly, pts(1,:)', pts(2,:)', pts(3,:)'); FF = freeBoundary(TR); %Output bound = FF(:,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
Hadisalman/stoec-master
normcdf.m
.m
stoec-master/code/Include/GP optimization/normcdf.m
3,991
utf_8
8a98cdb0d640bfd5a9a0a8fc1b3be30e
function [varargout] = normcdf(x,varargin) %NORMCDF Normal cumulative distribution function (cdf). % P = NORMCDF(X,MU,SIGMA) returns the cdf of the normal distribution with % mean MU and standard deviation SIGMA, evaluated 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. % % [P,PLO,PUP] = NORMCDF(X,MU,SIGMA,PCOV,ALPHA) produces confidence bounds % for P when the input parameters MU and SIGMA are estimates. PCOV is a % 2-by-2 matrix containing the covariance matrix of the estimated parameters. % ALPHA has a default value of 0.05, and specifies 100*(1-ALPHA)% confidence % bounds. PLO and PUP are arrays of the same size as P containing the lower % and upper confidence bounds. % % [...] = NORMCDF(...,'upper') computes the upper tail probability of the % normal distribution. This can be used to compute a right-tailed p-value. % To compute a two-tailed p-value, use 2*NORMCDF(-ABS(X),MU,SIGMA). % % See also ERF, ERFC, NORMFIT, NORMINV, NORMLIKE, NORMPDF, NORMRND, NORMSTAT. % References: % [1] Abramowitz, M. and Stegun, I.A. (1964) Handbook of Mathematical % Functions, Dover, New York, 1046pp., sections 7.1, 26.2. % [2] Evans, M., Hastings, N., and Peacock, B. (1993) Statistical % Distributions, 2nd ed., Wiley, 170pp. % Copyright 1993-2013 The MathWorks, Inc. if nargin<1 error(message('stats:normcdf:TooFewInputsX')); end if nargin>1 && strcmpi(varargin{end},'upper') % Compute upper tail and remove 'upper' flag uflag=true; varargin(end) = []; elseif nargin>1 && ischar(varargin{end})&& ~strcmpi(varargin{end},'upper') error(message('stats:cdf:UpperTailProblem')); else uflag=false; end [varargout{1:max(1,nargout)}] = localnormcdf(uflag,x,varargin{:}); function [p,plo,pup] = localnormcdf(uflag,x,mu,sigma,pcov,alpha) if nargin < 3 mu = 0; end if nargin < 4 sigma = 1; end % More checking if we need to compute confidence bounds. if nargout>1 if nargin<5 error(message('stats:normcdf:TooFewInputsCovariance')); end if ~isequal(size(pcov),[2 2]) error(message('stats:normcdf:BadCovarianceSize')); end if nargin<6 alpha = 0.05; elseif ~isnumeric(alpha) || numel(alpha)~=1 || alpha<=0 || alpha>=1 error(message('stats:normcdf:BadAlpha')); end end try z = (x-mu) ./ sigma; if uflag==true z = -z; end catch error(message('stats:normcdf:InputSizeMismatch')); end % Prepare output p = NaN(size(z),class(z)); if nargout>=2 plo = NaN(size(z),class(z)); pup = NaN(size(z),class(z)); end % Set edge case sigma=0 if uflag==true p(sigma==0 & x<mu) = 1; p(sigma==0 & x>=mu) = 0; if nargout>=2 plo(sigma==0 & x<mu) = 1; plo(sigma==0 & x>=mu) = 0; pup(sigma==0 & x<mu) = 1; pup(sigma==0 & x>=mu) = 0; end else p(sigma==0 & x<mu) = 0; p(sigma==0 & x>=mu) = 1; if nargout>=2 plo(sigma==0 & x<mu) = 0; plo(sigma==0 & x>=mu) = 1; pup(sigma==0 & x<mu) = 0; pup(sigma==0 & x>=mu) = 1; end end % Normal cases if isscalar(sigma) if sigma>0 todo = true(size(z)); else return; end else todo = sigma>0; end z = z(todo); % Use the complementary error function, rather than .5*(1+erf(z/sqrt(2))), % to produce accurate near-zero results for large negative x. p(todo) = 0.5 * erfc(-z ./ sqrt(2)); % Compute confidence bounds if requested. if nargout>=2 zvar = (pcov(1,1) + 2*pcov(1,2)*z + pcov(2,2)*z.^2) ./ (sigma.^2); if any(zvar<0) error(message('stats:normcdf:BadCovarianceSymPos')); end normz = -norminv(alpha/2); halfwidth = normz * sqrt(zvar); zlo = z - halfwidth; zup = z + halfwidth; plo(todo) = 0.5 * erfc(-zlo./sqrt(2)); pup(todo) = 0.5 * erfc(-zup./sqrt(2)); end
github
Hadisalman/stoec-master
EI.m
.m
stoec-master/code/Include/GP optimization/EI.m
300
utf_8
5b9d33eba552e84709c55f4269598d1a
% Elif Ayvali 06/16/2015 [email protected] % yEI: the value of y to 'improve over'. % ymu: the mean of GP posterior % ys: the standard deviation of GP posterior function res = EI(yEI,ymu,ys2) eps=0.01; ys=sqrt(ys2); res = (ymu-yEI-eps).*normcdf((ymu-yEI-eps)./ys)+ys.*normpdf((ymu-yEI-eps)./ys); end
github
Hadisalman/stoec-master
dEI.m
.m
stoec-master/code/Include/GP optimization/dEI.m
300
utf_8
5b9d33eba552e84709c55f4269598d1a
% Elif Ayvali 06/16/2015 [email protected] % yEI: the value of y to 'improve over'. % ymu: the mean of GP posterior % ys: the standard deviation of GP posterior function res = EI(yEI,ymu,ys2) eps=0.01; ys=sqrt(ys2); res = (ymu-yEI-eps).*normcdf((ymu-yEI-eps)./ys)+ys.*normpdf((ymu-yEI-eps)./ys); end
github
Hadisalman/stoec-master
UCB.m
.m
stoec-master/code/Include/GP optimization/UCB.m
291
utf_8
7f1ab1acc4b7626fd0040a1744b963ab
% Elif Ayvali 11/03/2015 [email protected] % Upper Confidence Bound % ymu: the mean of GP posterior % ys: the standard deviation of GP posterior function res = UCB(ymu,ys2,k) switch nargin case 2 beta=1.96; case 3 beta = k; end ys=sqrt(ys2); res =ymu+beta.*ys; end
github
Hadisalman/stoec-master
wEI.m
.m
stoec-master/code/Include/GP optimization/wEI.m
388
utf_8
755514e7605e817c6b08a6b344557ade
% Elif Ayvali 06/16/2015 [email protected] % yEI: the value of y to 'improve over'. % ymu: the mean of GP posterior % ys: the standard deviation of GP posterior % w = 0 global exploration % w = 1 local exploitation %w=0.5 wEI becomes EI function res = wEI(yEI,ymu,ys2,w) eps=0.01; ys=sqrt(ys2); res = w*(ymu-yEI-eps).*normcdf((ymu-yEI-eps)./ys)+(1-w)*ys.*normpdf((ymu-yEI-eps)./ys); end
github
cdebacco/SpringRank-master
crossValidation.m
.m
SpringRank-master/matlab/crossValidation.m
4,379
utf_8
14bd7c4736dcb2871ea12cb112972663
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % [sig_a,sig_L] = crossValidation(A,folds,reps) % % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % folds is the number of folks k in a k-fold cross validation % reps is the number of random repetitions desired over the k-folds. For % example, folds=5 and reps=7 would divide the data into 5 folds, % performing tests, and repeating those tests 7 times independently. % % OUTPUTS: % sig_a is the local accuracy (\sigma_a in the paper) % sig_L is the global accuracy (\sigma_L in the paper) function [sig_a,sig_L] = crossValidation(A,folds,reps) % convert to sparse for improved performance if ~issparse(A) A = sparse(A); end % NOTE: We perform cross validation over *interacting pairs* so we're not % dividing the edges of the network into k groups, but dividing the % interactions into k groups. Here is an example that clarifies the % difference. If there is a pair of nodes (i,j) with A(i,j) = 1 and % A(j,i)=3, this would count as ONE interacting pair, not four. There are % other interpretations of how to split edges into a training and a test % set, and these may be application dependent. All this writing here is % just to clarify *exactly* how this code works. % Find interacting pairs [r,c,v] = find(triu(A+transpose(A))); % Number of interacting pairs M = length(v); % Size of each fold foldSize = floor(M/folds); % preallocate; note that DIM2 should be increased if you are testing more % than one method. sig_a = zeros(reps*folds,1); sig_L = zeros(reps*folds,1); % iterate over reps for rep = 1:reps % shuffle interactions idx = shuffle(1:M); % build K-1 folds of equal size for f = 1:folds-1 fold{f} = idx( (f-1)*foldSize+1 : f*foldSize); end % then put the remainder in the final Kth fold fold{folds} = idx( (folds-1)*foldSize+1 : end); % iterate over folds for f = 1:folds % Print fprintf('Cross validation progress: Rep %i/%i, Fold %i/%i.\n',... rep,reps,f,folds); % bookkeeping foldrep = f+(rep-1)*folds; % build the testset of indices test_i = r(fold{f}); test_j = c(fold{f}); test = sub2ind(size(A),test_i,test_j); testpose = sub2ind(size(A),test_j,test_i); % build the training set by setting testset interactions to zero. TRAIN = A; TRAIN(test) = 0; TRAIN(testpose) = 0; % Build the TEST set. TEST = A-TRAIN; numTestEdges = sum(sum(TEST)); % train springRank on the TRAINset s0 = springRank(TRAIN); bloc0 = betaLocal(TRAIN,s0); bglob0 = betaGlobal(TRAIN,s0); % springRank accuracies on TEST set sig_a(foldrep,1) = localAccuracy(TEST,s0,bloc0); sig_L(foldrep,1) = -globalAccuracy(TEST,s0,bglob0)/numTestEdges; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NOTE THAT IF YOU WANT TO COMPARE OTHER METHODS TO SPRINGRANK, % THIS IS THE PLACE THAT THEY SHOULD BE INCLUDED. % Commented out, below, you can see the call to springRank with the % regularization, as well as the call to BTL and its separate % accuracy. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % train regularized springRank on the TRAINset % s2 = springRankFull(TRAIN,2); % bloc2 = betaLocal2(TRAIN,s2); % bglob2 = betaGlobal(TRAIN,s2); % % regularized springRank accuracies on TEST set % sig_a(foldrep,2) = localAccuracy(TEST,s2,bloc2); % sig_L(foldrep,2) = -globalAccuracy(TEST,s2,bglob2)/numTestEdges; % % train BTL on the TRAINset % bt = btl(TRAIN,1e-3); % % BTL accuracies on TEST set % sig_a(foldrep,3) = localAccuracy_BTL(TEST,bt); % sig_L(foldrep,3) = -globalAccuracy_BTL(TEST,bt)/numTestEdges; end end
github
cdebacco/SpringRank-master
betaLocal.m
.m
SpringRank-master/matlab/betaLocal.m
1,031
utf_8
f1ad8be3f40d4591b7210456f33b5576
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % b = betaLocal(A,s) % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % s is the Nx1 vector of node positions (ranks) % OUTPUTS: % b is the optimal inverse temperature (beta) under the LOCAL accuracy, % which we call \sigma_a in the paper. function [b] = betaLocal(A,s) global M r M = A; r = s; b = fminbnd(@negacc,1e-6,1000); end function [a] = negacc(b) global M r m = sum(sum(M)); n = length(r); y = 0; for i=1:n for j=1:n d = r(i) - r(j); y = y + abs( M(i,j)- (M(i,j) + M(j,i))*((1+exp(-2*b*d))^(-1)) ); end end a = y/m-1; end
github
cdebacco/SpringRank-master
colleyMatrix.m
.m
SpringRank-master/matlab/colleyMatrix.m
1,090
utf_8
62e2ddddd76c55ce9c4418f954bee9e3
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % r = colleyMatrix(A) % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % OUTPUTS: % r is the Nx1 vector of the Colley Matrix ranks function [r] = colleyMatrix(A) %Aij = i beats j %therefore out-degree = sum over j = wins %therefore in-degree = sum over i = losses A(1:max(size(A))+1:end) = 0; wins = sum(A,2); losses = sum(A,1)'; total = wins+losses; matches = A+transpose(A); n = size(A,1); C = zeros(n,n); b = zeros(n,1); for i=1:n b(i) = 1 + (wins(i)-losses(i))/2; for j=1:n if i==j C(i,j) = 2+total(i); else C(i,j) = -matches(i,j); end end end r = C\b;
github
cdebacco/SpringRank-master
springRank.m
.m
SpringRank-master/matlab/springRank.m
1,565
utf_8
05483c2c0427fb4ac7d99a357effccca
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % s = springRank(A) % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % OUTPUTS: % s is a N-vector of node positions according to SpringRank function [s] = springRank(A) % Input check for sparsity if issparse(A) % Great. We like sparse. else A = sparse(A); % Still works, but slower warning('Input matrix not sparse; much faster if A is a sparse matrix.') end % Number of vertices N = size(A,2); % out-degree and in-degree VECTORS dout = sum(A,2); din = sum(A,1); % out-degree and in-degree DIAGONAL MATRICES Dout = diag(dout(1:N-1)); Din = diag(din(1:N-1)); % out-degree and in-degree for vertex N dNout = dout(N); dNin = din(N); B = Dout + Din - A(1:N-1,1:N-1) - transpose(A(1:N-1,1:N-1))... - repmat(A(N,1:N-1),N-1,1) - repmat(transpose(A(1:N-1,N)),N-1,1); b = diag(Dout)-diag(Din)+dNout-dNin; % Sparse solve. Use [t,~] to suppress warnings. [t,~] = bicgstab(B,b,1e-12,200); % ranks s = [t;0]; % adjust mean of each component to be 0 [nComponents,~,members] = networkComponents(A); for n = 1:nComponents s(members{n}) = s(members{n})-mean(s(members{n})); end
github
cdebacco/SpringRank-master
ranks2svg.m
.m
SpringRank-master/matlab/ranks2svg.m
2,966
utf_8
85d15849f335c0cfa3085e3c096f0db9
% Code by Daniel Larremore % Santa Fe Institute % [email protected] % http://danlarremore.com % v3 function [energy] = ranks2svg(A,s,filename) [r,c,v] = find(A); energy = (s(r)-s(c)-1).^2; energy = lin(energy/max(energy),0.05,0.3); % wid = 800; % Must be at least 400 hei = 800; % Must be at least 400 aspectRatio = 0.4; wid = hei*aspectRatio; s = max(s)-s; %flip orientation so top ranked shows up highest y = (s-min(s))/(max(s)-min(s))*(7/8)*hei+hei/16; % colors c_fill = [10,10,10]; %color - circle fill % c_fill = 'none'; c_stroke = [10,10,10]; %color - circle stroke c_down = [41,143,170]; %color - edges down c_up = [170,48,41]; %color - edges up s_min = 1; %edge stroke min s_max = 4; %edge stroke max r_min = 1; %circle min radius r_max = 3; %circle max radius swirl = 0.75; % bind sizes of circles to k. Q = A; Q(1:size(Q,1)+1:end)=0; % kill diagonal k = sum(Q,2); % bind to out degree. k = lin(k,r_min,r_max); % transform edge weights in v to range [s_min,s_max] w = lin(v,s_min,s_max); fid = fopen(filename,'w'); fprintf(fid,'<svg width="%i" height="%i" id="vis">',wid,hei); fprintf(fid,'\n'); % Paths for i=1:length(v) fr = y(r(i)); to = y(c(i)); anchor_y = swirl*fr+(1-swirl)*to; anchor_x = (wid/2)-sign(fr-to)*abs(fr-to)*aspectRatio; if sign(fr-to) < 0 rgb = getColor_identity(c_down,energy); opacity = 0.15; fprintf(fid,'<path d="M%f %f Q %f %f %f %f" stroke-width="%f" stroke="rgb(%i,%i,%i)" stroke-opacity="%f" fill="none"/>',... wid/2,fr,... anchor_x,anchor_y,wid/2,to,... w(i),... rgb(1),... rgb(2),... rgb(3),... opacity); else rgb = getColor_identity(c_up,energy); opacity = 0.15; fprintf(fid,'<path d="M%f %f Q %f %f %f %f" stroke-width="%f" stroke="rgb(%i,%i,%i)" stroke-opacity="%f" fill="none"/>',... wid/2,fr,... anchor_x,anchor_y,wid/2,to,... w(i),... rgb(1),... rgb(2),... rgb(3),... opacity); end fprintf(fid,'\n'); end % Circles n = size(A,1); for i=1:n if strcmp(c_fill,'none')==1 fprintf(fid,'<circle class="node" r="%f" style="fill: none; stroke: rgb(%i,%i,%i); stroke-width:1" cx="%f" cy="%f"/>',... k(i),c_stroke(1),c_stroke(2),c_stroke(3),wid/2,y(i) ); else fprintf(fid,'<circle class="node" r="%f" style="fill: rgb(%i,%i,%i); stroke: rgb(%i,%i,%i); stroke-width:1" cx="%f" cy="%f"/>',... k(i),c_fill(1),c_fill(2),c_fill(3),c_stroke(1),c_stroke(2),c_stroke(3),wid/2,y(i) ); end fprintf(fid,'\n'); end fprintf(fid,'</svg>'); fclose(fid); end function [y] = lin(x,m,M) y = (x - min(x))/(max(x)-min(x))*(M-m)+m; end function [rgb] = getColor_linearToWhite(rgb_base,scalar) M = max(rgb_base); rgb = round(rgb_base+(M-rgb_base)*scalar); end function [rgb] = getColor_identity(rgb_base,scalar) rgb = rgb_base; end
github
cdebacco/SpringRank-master
pageRank.m
.m
SpringRank-master/matlab/pageRank.m
843
utf_8
ed72c5ff10741e4c8c07d5eddf3ea0d2
% Parameter M adjacency matrix where M_i,j represents the link from 'j' to 'i', such that for all 'j' % sum(i, M_i,j) = 1 % Parameter d damping factor % Parameter v_quadratic_error quadratic error for v % Return v, a vector of ranks such that v_i is the i-th rank from [0, 1] function v = pageRank(A, d, v_quadratic_error) N = max(size(A)); % N is equal to either dimension of M and the number of documents M = zeros(N,N); for j=1:N if sum(A(:,j)) > 0 M(:,j)=A(:,j)/sum(A(:,j)); else M(:,j) = 1/N; end end % v = rand(N, 1); v = ones(N,1); v = v ./ norm(v, 1); % This is now L1, not L2 last_v = ones(N, 1) * inf; M_hat = (d .* M) + (((1 - d) / N) .* ones(N, N)); while(norm(v - last_v, 2) > v_quadratic_error) last_v = v; v = M_hat * v; v = v/norm(v,1); % removed the L2 norm of the iterated PR end
github
cdebacco/SpringRank-master
globalAccuracy.m
.m
SpringRank-master/matlab/globalAccuracy.m
1,078
utf_8
a5b96f21a21c715028ec162644c233c2
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % y = globalAccuracy(A,s,b) % % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % s is the Nx1 vector of node positions (ranks) % b is the inverse temperature (called beta in the paper) % % OUTPUTS: % y is the global accuracy (called \sigma_L in the paper) function y = globalAccuracy(A,s,b) % number of nodes n = length(s); % accumulate the log likelihood score elementwise y = 0; for i=1:n for j=1:n d = s(i) - s(j); p = (1+exp(-2*b*d))^(-1); if p==0 || p==1 % do nothing else y = y + A(i,j)*log(p)+A(j,i)*log(1-p); end end end end
github
cdebacco/SpringRank-master
rankCentrality.m
.m
SpringRank-master/matlab/rankCentrality.m
1,424
utf_8
a8fd8534646737e069618cad2e5473da
% Rank Centrality % Implemented by Dan Larremore, University of Colorado Boulder % April 8, 2018 % % Based on the manuscript % Rank Centrality: Ranking from Pairwise Comparisons % Sahand Negahban, Sewoong Oh, Devavrat Shah % 2017 % function [rc] = rankCentrality(A) % In their text, a_ij = # of times j is preferred over i. % In the SpringRank paper, we usually assume the opposite. % Here, we'll use the authors' direction, but note that whenever we call % this code, we'll have to pass the transpose of A. % Note that there are no self-loops in this model, so we will check, % discard, and warn N = size(A,1); if sum(diag(A)) > 0 % fprintf('Warning: self-loops detected (and ignored)\n') A(1:N+1:end) = 0; end % see Eq 5 of https://arxiv.org/pdf/1209.1688.pdf % We're going to regularize. % They suggest epsilon = 1. % This seems extreme? % Not listed in the paper, but this is important. We have to regularize the % matrix A before we compute dmax. regularization = 1; A = A+regularization; % Find dmax dout = sum(A,2); dmax = max(dout); % Eq 5 P = (1/dmax) * A./(A+transpose(A)); % But we need to make sure that the matrix remains stochastic by making the % rows sum to 1. Without regularization, Eq 1 says P(i,i) = 1 - dout(i)/dmax; % Instead, we're going to just do this "manually" P(1:N+1:end) = 0; for i=1:N P(i,i) = 1-sum(P(i,:)); end [V,~] = eigs(transpose(P),1); rc = V / sum(V); end
github
cdebacco/SpringRank-master
springRankHamiltonian.m
.m
SpringRank-master/matlab/springRankHamiltonian.m
1,292
utf_8
c5d299fe7f9d0c8d492690a9ecaa1037
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % H = springRankHamiltonian(s,A,mu) % INPUTS: % s is a N-vector of node positions % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % mu can be a scalar or a NxN matrix % OUTPUTS: % H is the scalar spring energy of the system; % NOTE: assumes spring rest length of 1 function [H] = springRankHamiltonian(s,A,mu) % assuming A is sparse, faster to go through entries of A. [r,c,v] = find(A); % preallocate container of hamiltonian values. h = zeros(size(v)); % NOTE: i = r(n) and j = c(n) % Probably could be faster if length(mu)==1 % SCALAR spring constant for n = 1:length(v) h(n) = v(n) * (s(r(n))-s(c(n))-1)^2; end h = h*mu; else % MATRIX of spring constants for n = 1:length(v) h(n) = v(n) * mu(r(n),c(n)) * (s(r(n))-s(c(n))-1)^2; end end % sum up, divide by 2, and return H = sum(h)/2;
github
cdebacco/SpringRank-master
globalAccuracy_BTL.m
.m
SpringRank-master/matlab/globalAccuracy_BTL.m
440
utf_8
b2b67332100fdf1041556c3ca6219483
% Code by Daniel Larremore % Santa Fe Institute % [email protected] % http://danlarremore.com % evaluate the local accuracy of edge direction prediction function y = globalAccuracy_BTL(A,g) n = length(g); y = 0; for i=1:n for j=1:n p = g(i)/(g(i)+g(j)); % BTL probability if p==0 || p==1 || isnan(p) % do nothing else y = y + A(i,j)*log(p)+A(j,i)*log(1-p); end end end
github
cdebacco/SpringRank-master
mvr.m
.m
SpringRank-master/matlab/mvr.m
3,709
utf_8
0fba16216b6fa253d5fe1c15b5843c39
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % [order,violations,A] = mvr(A) % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % n_samples is an integer number of independent replicates of the MVR MCMC % search procedure. % OUTPUTS: % best_ranks is a vector of ranks. ONE IS BEST. N IS WORST % best_violations is the number of violations % best_A is the reordered matrix whose lower triangle contains min. viols. function [best_ranks,best_violations,best_A] = mvr(A,n_samples) best_violations = size(A,1)^2; for n = 1:n_samples [ranks,violations,A] = mvr_single(A); if violations < best_violations best_violations = violations; best_ranks = ranks; best_A = A; end end end function [ranks,violations,A] = mvr_single(A) violations = compute_violations(A); N = size(A,1); %order = shuffle(1:N); order =1:N; A(:,:) = A(order,:); A(:,:) = A(:,order); step = 1; fails = 0; % fprintf('Initial\t\t\t\tviolations\t%i\n',violations); hist_viols(step) = violations; hist_viols_backup(step) = violations; hist_fails(step) = fails; % RANDOM STEPS - Randomly swap till N^2 failures in a row. while 1 i = randi(N); % choose random node j = randi(N); % choose second random node. while j==i % make sure different i = randi(N); j = randi(N); end dx = compute_violations_change(A,i,j); if dx < 0 order([i,j]) = order([j,i]); A([i,j],:) = A([j,i],:); A(:,[i,j]) = A(:,[j,i]); step = step+1; hist_swaps(step,:) = [i,j]; hist_fails(step) = fails; hist_viols(step) = hist_viols(step-1)+dx; violations = compute_violations(A); hist_viols_backup(step) = violations; % fprintf('swap %i ~ %i \t --> %i\tviolations\t%i\t%i\n',i,j,dx,violations,fails) fails = 0; else fails = fails+1; end if fails == N^2 A(1,:); % fprintf('----- Too much fails -----\n'); break end end % DETERMINISTIC STEPS - Find any local steps deterministically by search. while 1 dxbest = 0; for i=1:N-1 for j=i+1:N dx = compute_violations_change(A,i,j); if dx < dxbest bestSwap = [i,j]; dxbest = dx; end end end if dxbest==0 % fprintf('---- no improvement, exiting ----\n'); [~,ranks] = sort(order); return; end i = bestSwap(1); j = bestSwap(2); order([i,j]) = order([j,i]); % before = compute_violations(A); A([i,j],:) = A([j,i],:); A(:,[i,j]) = A(:,[j,i]); % after = compute_violations(A); step = step+1; hist_swaps(step,:) = [i,j]; hist_viols(step) = hist_viols(step-1)+dxbest; violations = compute_violations(A); hist_viols_backup(step) = violations; % fprintf('swap %i ~ %i \t --> %i\tviolations\t%i\n',i,j,dxbest,violations) end end function dx = compute_violations_change(A,ii,jj) % Let's arbitrarily choose i to fall (larger rank number) and j to rise % (smaller rank number). i = min(ii,jj); j = max(ii,jj); dx= full(-sum(A(j,i:j-1)) ... +sum(A(i,i+1:j)) ... -sum(A(i+1:j-1,i)) ... +sum(A(i+1:j-1,j))); end function x = compute_violations(B) x = full(sum(sum(tril(B,-1)))); end
github
cdebacco/SpringRank-master
btl.m
.m
SpringRank-master/matlab/btl.m
1,384
utf_8
7a35f00eac95fc913ce8d85daf13199e
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % g = btl(A,tol) % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % tol is the accuracy tolerance desired for successive iterations % OUTPUTS: % s is the Nx1 vector of Davids Score % NOTE: implementation of a regularized version (for dangling node) % version of the algorithm presented in % Hunter DR (2004) MM algorithms for generalized Bradley-Terry models. % Annals of Statistics pp. 384?406 function [g] = btl(A,tol) A(1:max(size(A))+1:end) = 0; N = size(A,1); g = rand(1,N); % random initial guesss wins = sum(A,2); matches = A+transpose(A); totalMatches = sum(matches); g_prev = rand(1,N); eps=1e-6; while norm(g-g_prev) > tol g_prev = g; for i=1:N if totalMatches(i)>0 q = matches(i,:)./(g_prev(i)+g_prev); q(i) = []; g(i) = (wins(i)+eps)/sum(q); else g(i) = 0; end end g = g/sum(g); end g = transpose(g); end
github
cdebacco/SpringRank-master
localAccuracy_BTL.m
.m
SpringRank-master/matlab/localAccuracy_BTL.m
460
utf_8
982e9879799160f78b833eb9ff58d5e9
% Code by Daniel Larremore % Santa Fe Institute % [email protected] % http://danlarremore.com % evaluate the local accuracy of edge direction prediction function a = localAccuracy_BTL(A,g) m = sum(sum(A)); n = length(g); y = 0; for i=1:n for j=1:n p = g(i)/(g(i)+g(j)); % BTL probability if isnan(p) % do nothing else y = y + abs( A(i,j)-( A(i,j) + A(j,i) )*p ); end end end a = 1-0.5*y/m;
github
cdebacco/SpringRank-master
betaGlobal.m
.m
SpringRank-master/matlab/betaGlobal.m
1,016
utf_8
5ce0dabb8de3c08dc206f76792c59ffa
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % b = betaGlobal(A,s,varargin) % % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % s is the Nx1 vector of node positions (ranks) % % OUTPUTS: % b is the optimal inverse temperature (beta) under the GLOBAL accuracy, % which we call \sigma_\ell in the paper. function [b] = betaGlobal(A,s) global M r M = A; r = s; b = fzero(@f,0.1); end function [y] = f(b) global M r n = length(r); y = 0; for i=1:n for j=1:n d = r(i) - r(j); pij = (1+exp(-2*b*d))^(-1); y = y + d*(M(i,j) - (M(i,j)+M(j,i))*pij); end end end
github
cdebacco/SpringRank-master
localAccuracy.m
.m
SpringRank-master/matlab/localAccuracy.m
1,047
utf_8
c2e66140ef330c17dadfea25fb924b1e
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % a = localAccuracy(A,s,b) % % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % s is the Nx1 vector of node positions (ranks) % b is the inverse temperature (called beta in the paper) % % OUTPUTS: % a is the local accuracy (called \sigma_a in the paper) function a = localAccuracy(A,s,b) % total edges m = sum(sum(A)); % number of vertices n = length(s); % accumulate accuracy of predictions y = 0; for i=1:n for j=1:n d = s(i) - s(j); p = (1+exp(-2*b*d))^(-1); y = y + abs( A(i,j)-( A(i,j) + A(j,i) )*p ); end end % cleanup a = 1-0.5*y/m;
github
cdebacco/SpringRank-master
networkComponents.m
.m
SpringRank-master/matlab/networkComponents.m
2,678
utf_8
71e8c66191349a50896bef05ed228869
% [nComponents,sizes,members] = networkComponents(A) % % Daniel Larremore % April 24, 2014 % [email protected] % http://danlarremore.com % Comments and suggestions always welcome. % % INPUTS: % A Matrix. This function takes as an input a % network adjacency matrix A, for a network that is undirected. If you % provide a network that is directed, this code is going to make it % undirected before continuing. Since link weights will not affect % component sizes, weighted and unweighted networks work equally well. You % may provide a "full" or a "sparse" matrix. % % OUTPUTS: % nComponents INT - The number of components in the network. % sizes vector<INT> - a vector of component sizes, sorted, % descending. % members cell<vector<INT>> a cell array of vectors, each % entry of which is a membership list for that component, sorted, % descending by component size. % % Example: (uncomment and copy and paste into MATLAB command window) % % Generate a 1000 node network adjacency matrix, A % A = floor(1.0015*rand(1000,1000)); A=A+A'; A(A==2)=1; A(1:1001:end) = 0; % % Call networkComponents function % [nComponents,sizes,members] = networkComponents(A); % % get the size of the largest component % sizeLC = sizes(1); % % get a network adjacency matrix for ONLY the largest component % LC = A(members{1},members{1}); function [nComponents,sizes,members] = networkComponents(A) % Number of nodes N = size(A,1); % Remove diagonals A(1:N+1:end) = 0; % make symmetric, just in case it isn't A=A+A'; % Have we visited a particular node yet? isDiscovered = zeros(N,1); % Empty members cell members = {}; % check every node for n=1:N if ~isDiscovered(n) % started a new group so add it to members members{end+1} = n; % account for discovering n isDiscovered(n) = 1; % set the ptr to 1 ptr = 1; while (ptr <= length(members{end})) % find neighbors nbrs = find(A(:,members{end}(ptr))); % here are the neighbors that are undiscovered newNbrs = nbrs(isDiscovered(nbrs)==0); % we can now mark them as discovered isDiscovered(newNbrs) = 1; % add them to member list members{end}(end+1:end+length(newNbrs)) = newNbrs; % increment ptr so we check the next member of this component ptr = ptr+1; end end end % number of components nComponents = length(members); for n=1:nComponents % compute sizes of components sizes(n) = length(members{n}); end [sizes,idx] = sort(sizes,'descend'); members = members(idx); end
github
cdebacco/SpringRank-master
davidScore.m
.m
SpringRank-master/matlab/davidScore.m
836
utf_8
d9ab89c7af3f1d00a6344d70f6eb069b
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % s = davidScore(A) % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % OUTPUTS: % s is the Nx1 vector of Davids Score function [s] = davidScore(A) P = A./(A+A'); % Pij = Aij / (Aij + Aji) P(isnan(P)) = 0; P(1:size(P,1)+1:end) = 0; % ensure there are no entries on the diagonal w = sum(P,2); l = sum(transpose(P),2); w2 = P*w; l2 = transpose(P)*l; s = w+w2-l-l2;
github
cdebacco/SpringRank-master
pvalueNullModel.m
.m
SpringRank-master/matlab/pvalueNullModel.m
2,323
utf_8
d5d34bc9134164f5885f99d0ac17b9e6
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % [p,H0,H] = pvalueNullModel(A,n_repetitions) % % INPUTS: % A is a NxN matrix representing a directed network % A can be weighted (integer or non-integer) % A(i,j) = # of dominance interactions by i toward j. % A(i,j) = # of times that j endorsed i. % n_repetitions is the number of randomizations that you would like to use % to calculate the p-value. Higher numbers mean a better estimate of % probability that the p-value is meant to represent. Lower numbers may % be required for very large networks whose randomizations are expensive % or slow. % % OUTPUTS: % p is the p-value described in the paper for the probability that a % network A whose edge directions are randomized would have a lower % ground-state energy than the original network A % H0 is the ground state energy of A % H is the vector of ground state energies associated with randomizations % of the directions of A. function [p,H0,H] = pvalueNullModel(A,n_repetitions) % First determine what kind of matrix we have. Integer or non-integer? [~,~,v] = find(A); if sum(mod(v,1)==0)==length(v) isInteger = 1; Abar = A+A'; else isInteger = 0; end % Preallocate H = zeros(n_repetitions,1); H0 = springRankHamiltonian(springRank(A),A,1); % Iterate over repetitions for n = 1:n_repetitions % Two different randomization schemes, depending on whether or not the % network is integer or scalar. if isInteger B = randomEdgeDirectionsInt(Abar); else B = randomEdgeDirectionsScalar(A); end H(n) = springRankHamiltonian(springRank(B),B,1); end p = sum(H<H0)/n_repetitions; end function [B] = randomEdgeDirectionsInt(Abar) N = max(size(Abar)); [r,c,v] = find(triu(Abar,1)); up = binornd(v,0.5); down = v - up; B = sparse([r;c],[c;r],[up;down],N,N); end function [B] = randomEdgeDirectionsScalar(A) N = max(size(A)); [r,c,v] = find(A); for i=1:length(v) if rand < 0.5 temp = r(i); r(i) = c(i); c(i) = temp; end end B = sparse(r,c,v,N,N); end
github
cdebacco/SpringRank-master
generativeModel.m
.m
SpringRank-master/matlab/generativeModel.m
976
utf_8
6e6489e870ab1ebdb5db9b2a7b8d5569
% SpringRank % CODE -> https://github.com/cdebacco/SpringRank % PAPER -> http://danlarremore.com/pdf/SpringRank_2017_PrePrint.pdf % Code by Daniel Larremore % University of Colorado at Boulder % BioFrontiers Institute & Dept of Computer Science % [email protected] % http://danlarremore.com % % [A,P] = generativeModel(c,b,s) % INPUTS: % c is the overall sparsity constant % b is the inverse temperature (called beta in the paper) % s is the Nx1 vector of planted node positions % OUTPUTS: % A is a directed network adjacency matrix; A(i,j)=1 if i dominates j, e.g. % P is a full NxN matrix; P(i,j) = expected number of edges from i to j function [A,P] = generativeModel(c,b,s) % number of vertices N = length(s); % preallocate P P = zeros(N,N); for i=1:N for j=1:N % compute expected number of edges from i to j P(i,j) = c*exp(-b/2*(s(i)-s(j)-1)^2); end end % draw poisson random numbers from P and return A = sparse(poissrnd(P));
github
aamiranis/sampling_theory-master
test_eig_lopcg_proj.m
.m
sampling_theory-master/test_eig_lopcg_proj.m
2,708
utf_8
790f3462b25ee42dba9720dc49b4a527
function test_eig_lopcg_proj(Ln, S) k = 8; N = length(Ln); % Ln = Ln + 0.1 * speye(length(Ln)); Ln_k = Ln^k; % S = rand(length(Ln),1) > 0.05; % S = true(length(Ln),1); S(10) = false; [y1,s1] = eigs(Ln_k(S,S), 1, 'sm'); s1 % function x = operatorA(x) % for i = 1:k % x = Ln * x; % end % end % % C = ichol(Ln); prec_fun = @(x)C\(C'\x); % function x = operatorT(x) % for i = 1:k % x = prec_fun(x); % end % end % initial_x = ones(sum(S),1); % initial_x = initial_x / norm(initial_x); % [ y2, s2, failure_flag, log ] = eig_lopcg_proj( initial_x, S, @(x)operatorA(x), @(x)operatorT(x), 1e-4, N); % s2 % plot(log10(log(:,end))); % initial_x = ones(length(Ln),1); % initial_x = initial_x / norm(initial_x); % [ y2, s2 ] = lobpcg( initial_x, @(x)operatorA(x), [], @(x)operatorT(x), 1e-4, 500 ); % y2 = y2(S); % s2 function result = operatorA(x) N = size(Ln,1); M = size(x,2); result = zeros(N,M); if (M == 1) result(S) = x; else result(S,:) = x; end for i = 1:k % result = (L * result + result) / 3; result = Ln * result; end if (M == 1) result = result(S); else result = result(S,:); end end % function x = operatorT(x) % precon_tol = 1e-4; % max_iter_precon = 500; % % k_cg = 0; % % r_cg = x - operatorA(x); % p_cg = r_cg; % rr_cg_old = r_cg'*r_cg; % % while ( (sqrt(rr_cg_old) > precon_tol) && (k_cg <= max_iter_precon) ) % k_cg = k_cg + 1; % % A_times_p_int = operatorA(p_cg); % % alpha_cg = rr_cg_old / (p_cg' * A_times_p_int); % x = x + alpha_cg * p_cg; % r_cg = r_cg - alpha_cg * A_times_p_int; % % rr_cg_new = r_cg'*r_cg; % p_cg = r_cg + (rr_cg_new/rr_cg_old) * p_cg; % % rr_cg_old = rr_cg_new; % end % end % C = ichol(Ln); prec_fun = @(x)C\(C'\x); % function result = operatorT(x) % M = size(x,2); % result = zeros(N,M); % % if (M == 1) % result(S) = x; % else % result(S,:) = x; % end % % for i = 1:k % result = prec_fun(result); % end % % if (M == 1) % result = result(S); % else % result = result(S,:); % end % end initial_x = ones(sum(S),1); for j = 1:size(initial_x,2) initial_x(:,j) = initial_x(:,j)/norm(initial_x(:,j)); end % [y2, s2, failure_flag, lambda_history, residual_norm_history] = lobpcg(initial_x, @(x)operatorA(x), 1e-4, N); % plot(log10(residual_norm_history')); [ y2, s2, failure_flag, log ] = eig_lopcg( initial_x, @(x)operatorA(x), 1e-4, N); plot(log10(log(:,end))); s2(1) figure, plot([y1 y2]); % plot(abs(y1)-abs(y2)); end
github
aamiranis/sampling_theory-master
compute_S_L_k_lobpcg.m
.m
sampling_theory-master/sampling_methods/max_lambda_min_L_k/compute_S_L_k_lobpcg.m
3,369
utf_8
371f985ac6d087cbc8ef29edaa7ebd8d
function [ S_opt, count ] = compute_S_L_k_lobpcg( L, prec_fun, k, num_nodes_to_add, current_S_opt ) % AUTHOR: Aamir Anis, USC % This function computes the optimal sampling set of a given size % "S_opt_size" that maximizes the cutoff frequency. % % % % PARAMETER DESCRIPTION % % INPUT % L_k: kth power of Laplacian % S_opt_size: Desired size of the optimal set % k: Power of Laplacian while computing cutoff, higher the order, % greater the accuracy, but the complexity is also higher. % % OUTPUT % S_opt: Optimal set as a logical vector % omega: cutoff of the optimal set % omega_list: List of computed cutoffs % % % % % fprintf('Starting optimal set search...\n'); N = length(L); count = 0; % Initialization : If previous state available, initialize to that if (exist('current_S_opt','var')) S_opt = current_S_opt; else S_opt = false(N,1); end omega = 0; function result = operatorA(x) M = size(x,2); result = zeros(N,M); if (M == 1) result(~S_opt) = x; else result(~S_opt,:) = x; end for i = 1:k % result = (L * result + result) / 3; result = L * result; end if (M == 1) result = result(~S_opt); else result = result(~S_opt,:); end % result = result - omega * x; count = count + k; end function x = operatorT(x) precon_tol = 1e-4; max_iter_precon = N/10; k_cg = 0; r_cg = x - operatorA(x); p_cg = r_cg; rr_cg_old = r_cg'*r_cg; while ( (sqrt(rr_cg_old) > precon_tol) && (k_cg <= max_iter_precon) ) k_cg = k_cg + 1; A_times_p_int = operatorA(p_cg); alpha_cg = rr_cg_old / (p_cg' * A_times_p_int); x = x + alpha_cg * p_cg; r_cg = r_cg - alpha_cg * A_times_p_int; rr_cg_new = r_cg'*r_cg; p_cg = r_cg + (rr_cg_new/rr_cg_old) * p_cg; rr_cg_old = rr_cg_new; end end % function result = operatorT(x) % M = size(x,2); % result = zeros(N,M); % % if (M == 1) % result(~S_opt) = x; % else % result(~S_opt,:) = x; % end % % for i = 1:k % result = prec_fun(result); % end % % if (M == 1) % result = result(~S_opt); % else % result = result(~S_opt,:); % end % end % iterations_for_convergence = zeros(num_nodes_to_add,1); for iter = 1:num_nodes_to_add % tic % fprintf('Iteration %d of %d...\n', iter, num_nodes_to_add); % create index vector for Sc from indicator functions q = find(~S_opt); % compute minimum eigen-pair: efficient way initial_x = ones(length(q),1); initial_x = initial_x / norm(initial_x); [y, ~, failure_flag] = lobpcg(initial_x, @(x)operatorA(x), 1e-3, N); % [y, omega, failure_flag, lambda_history, residual_norm_history] = lobpcg(initial_x, @(x)operatorA(x), [], @(x)operatorT(x), 1e-4, N); if (failure_flag == 1) fprintf('k = %d did not converge while adding node %d.\n', k, iter); end % find direction of maximum increment in reduced (|Sc|) dimensions [~,max_index] = max(abs(y)); % Find corresponding node in N dimensions node_to_add = q(max_index); % Update indicator function S_opt(node_to_add) = 1; % fprintf('Nodes added = %d...\n', sum(S_opt)); % toc end % fprintf('Finished.\n'); end
github
aamiranis/sampling_theory-master
compute_S_L_k_lobpcg_proj.m
.m
sampling_theory-master/sampling_methods/max_lambda_min_L_k/compute_S_L_k_lobpcg_proj.m
2,083
utf_8
eb8313912525ab67ab720b05bdd3c2f0
function [ S_opt, count ] = compute_S_L_k_lobpcg_proj( L, prec_fun, k, num_nodes_to_add, current_S_opt ) % AUTHOR: Aamir Anis, USC % This function computes the optimal sampling set of a given size % "S_opt_size" that maximizes the cutoff frequency. % % % % PARAMETER DESCRIPTION % % INPUT % L_k: kth power of Laplacian % S_opt_size: Desired size of the optimal set % k: Power of Laplacian while computing cutoff, higher the order, % greater the accuracy, but the complexity is also higher. % % OUTPUT % S_opt: Optimal set as a logical vector % omega: cutoff of the optimal set % omega_list: List of computed cutoffs % % % % % fprintf('Starting optimal set search...\n'); N = length(L); count = 0; % Initialization : If previous state available, initialize to that if (exist('current_S_opt','var')) S_opt = current_S_opt; else S_opt = false(N,1); end function x = operatorA(x) for i = 1:k x = L * x; end count = count + k; end function x = operatorT(x) for i = 1:k x = prec_fun(x); end end % iterations_for_convergence = zeros(num_nodes_to_add,1); for iter = 1:num_nodes_to_add % tic % fprintf('Iteration %d of %d...\n', iter, num_nodes_to_add); % create index vector for Sc from indicator functions q = find(~S_opt); % compute minimum eigen-pair: efficient way initial_x = ones(length(q),1); initial_x = initial_x / norm(initial_x); [ y, omega, failure_flag, log ] = eig_lopcg_proj( initial_x, ~S_opt, @(x)operatorA(x), @(x)operatorT(x), 1e-4, 500); % log(:,3) failure_flag = abs(1 - failure_flag); if (failure_flag == 1) fprintf('k = %d did not converge while adding node %d.\n', k, iter); end % find direction of maximum increment in reduced (|Sc|) dimensions [~,max_index] = max(abs(y)); % Find corresponding node in N dimensions node_to_add = q(max_index); % Update indicator function S_opt(node_to_add) = 1; % fprintf('Nodes added = %d...\n', sum(S_opt)); % toc end % fprintf('Finished.\n'); end
github
aamiranis/sampling_theory-master
pdftops.m
.m
sampling_theory-master/results/exportfig/pdftops.m
3,053
utf_8
6eb261c6107aedd03ceace4ccbce285c
function varargout = pdftops(cmd) %PDFTOPS Calls a local pdftops executable with the input command % % Example: % [status result] = pdftops(cmd) % % Attempts to locate a pdftops executable, finally asking the user to % specify the directory pdftops was installed into. The resulting path is % stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have pdftops (from the Xpdf package) % installed on your system. You can download this from: % http://www.foolabs.com/xpdf % % IN: % cmd - Command string to be passed into pdftops. % % OUT: % status - 0 iff command ran without problem. % result - Output from pdftops. % Copyright: Oliver Woodford, 2009-2010 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path % under linux. % Call pdftops [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd)); return function path = xpdf_path % Return a valid path % Start with the currently set path path = user_string('pdftops'); % Check the path works if check_xpdf_path(path) return end % Check whether the binary is on the path if ispc bin = 'pdftops.exe'; else bin = 'pdftops'; end if check_store_xpdf_path(bin) path = bin; return end % Search the obvious places if ispc path = 'C:\Program Files\xpdf\pdftops.exe'; else path = '/usr/local/bin/pdftops'; end if check_store_xpdf_path(path) return end % Ask the user to enter the path while 1 if strncmp(computer,'MAC',3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.')) end base = uigetdir('/', 'Pdftops not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) path = [base bin_dir{a} bin]; if exist(path, 'file') == 2 break; end end if check_store_xpdf_path(path) return end end error('pdftops executable not found.'); function good = check_store_xpdf_path(path) % Check the path is valid good = check_xpdf_path(path); if ~good return end % Update the current default path to the path found if ~user_string('pdftops', path) warning('Path to pdftops executable could not be saved. Enter it manually in pdftops.txt.'); return end return function good = check_xpdf_path(path) % Check the path is valid [good message] = system(sprintf('"%s" -h', path)); % system returns good = 1 even when the command runs % Look for something distinct in the help text good = ~isempty(strfind(message, 'PostScript')); return
github
aamiranis/sampling_theory-master
isolate_axes.m
.m
sampling_theory-master/results/exportfig/isolate_axes.m
3,307
utf_8
43cbadba85146816219993a4e1de54cb
%ISOLATE_AXES Isolate the specified axes in a figure on their own % % Examples: % fh = isolate_axes(ah) % fh = isolate_axes(ah, vis) % % This function will create a new figure containing the axes specified, and % also their associated legends and colorbars. The axes specified must all % be in the same figure, but they will generally only be a subset of the % axes in the figure. % % IN: % ah - An array of axes handles, which must come from the same figure. % vis - A boolean indicating whether the new figure should be visible. % Default: false. % % OUT: % fh - The handle of the created figure. % Copyright (C) Oliver Woodford 2011-2012 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs % 16/3/2012 Moved copyfig to its own function. Thanks to Bob Fratantonio % for pointing out that the function is also used in export_fig.m. function fh = isolate_axes(ah, vis) % Make sure we have an array of handles if ~all(ishandle(ah)) error('ah must be an array of handles'); end % Check that the handles are all for axes, and are all in the same figure fh = ancestor(ah(1), 'figure'); nAx = numel(ah); for a = 1:nAx if ~strcmp(get(ah(a), 'Type'), 'axes') error('All handles must be axes handles.'); end if ~isequal(ancestor(ah(a), 'figure'), fh) error('Axes must all come from the same figure.'); end end % Tag the axes so we can find them in the copy old_tag = get(ah, 'Tag'); if nAx == 1 old_tag = {old_tag}; end set(ah, 'Tag', 'ObjectToCopy'); % Create a new figure exactly the same as the old one fh = copyfig(fh); %copyobj(fh, 0); if nargin < 2 || ~vis set(fh, 'Visible', 'off'); end % Reset the axes tags for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Find the objects to save ah = findall(fh, 'Tag', 'ObjectToCopy'); if numel(ah) ~= nAx close(fh); error('Incorrect number of axes found.'); end % Set the axes tags to what they should be for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Keep any legends and colorbars which overlap the subplots lh = findall(fh, 'Type', 'axes', '-and', {'Tag', 'legend', '-or', 'Tag', 'Colorbar'}); nLeg = numel(lh); if nLeg > 0 ax_pos = get(ah, 'OuterPosition'); if nAx > 1 ax_pos = cell2mat(ax_pos(:)); end ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2); leg_pos = get(lh, 'OuterPosition'); if nLeg > 1; leg_pos = cell2mat(leg_pos); end leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2); for a = 1:nAx % Overlap test ah = [ah; lh(leg_pos(:,1) < ax_pos(a,3) & leg_pos(:,2) < ax_pos(a,4) &... leg_pos(:,3) > ax_pos(a,1) & leg_pos(:,4) > ax_pos(a,2))]; end end % Get all the objects in the figure axs = findall(fh); % Delete everything except for the input axes and associated items delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)]))); return function ah = allchildren(ah) ah = allchild(ah); if iscell(ah) ah = cell2mat(ah); end ah = ah(:); return function ph = allancestors(ah) ph = []; for a = 1:numel(ah) h = get(ah(a), 'parent'); while h ~= 0 ph = [ph; h]; h = get(h, 'parent'); end end return
github
aamiranis/sampling_theory-master
pdf2eps.m
.m
sampling_theory-master/results/exportfig/pdf2eps.m
1,524
utf_8
037f9109e96ab4385d13019a29db4639
%PDF2EPS Convert a pdf file to eps format using pdftops % % Examples: % pdf2eps source dest % % This function converts a pdf file to eps format. % % This function requires that you have pdftops, from the Xpdf suite of % functions, installed on your system. This can be downloaded from: % http://www.foolabs.com/xpdf % %IN: % source - filename of the source pdf file to convert. The filename is % assumed to already have the extension ".pdf". % dest - filename of the destination eps file. The filename is assumed to % already have the extension ".eps". % Copyright (C) Oliver Woodford 2009-2010 % Thanks to Aldebaro Klautau for reporting a bug when saving to % non-existant directories. function pdf2eps(source, dest) % Construct the options string for pdftops options = ['-q -paper match -eps -level2 "' source '" "' dest '"']; % Convert to eps using pdftops [status message] = pdftops(options); % Check for error if status % Report error if isempty(message) error('Unable to generate eps. Check destination directory is writable.'); else error(message); end end % Fix the DSC error created by pdftops fid = fopen(dest, 'r+'); if fid == -1 % Cannot open the file return end fgetl(fid); % Get the first line str = fgetl(fid); % Get the second line if strcmp(str(1:min(13, end)), '% Produced by') fseek(fid, -numel(str)-1, 'cof'); fwrite(fid, '%'); % Turn ' ' into '%' end fclose(fid); return
github
aamiranis/sampling_theory-master
print2array.m
.m
sampling_theory-master/results/exportfig/print2array.m
6,161
utf_8
155b53ad27b25177fbcb3cd67ec6615e
%PRINT2ARRAY Exports a figure to an image array % % Examples: % A = print2array % A = print2array(figure_handle) % A = print2array(figure_handle, resolution) % A = print2array(figure_handle, resolution, renderer) % [A bcol] = print2array(...) % % This function outputs a bitmap image of the given figure, at the desired % resolution. % % If renderer is '-painters' then ghostcript needs to be installed. This % can be downloaded from: http://www.ghostscript.com % % IN: % figure_handle - The handle of the figure to be exported. Default: gcf. % resolution - Resolution of the output, as a factor of screen % resolution. Default: 1. % renderer - string containing the renderer paramater to be passed to % print. Default: '-opengl'. % % OUT: % A - MxNx3 uint8 image of the figure. % bcol - 1x3 uint8 vector of the background color % Copyright (C) Oliver Woodford 2008-2011 % 5/9/2011 Set EraseModes to normal when using opengl or zbuffer renderers. % Thanks to Pawel Kocieniewski for reporting the issue. % 21/9/2011 Bug fix: unit8 -> uint8! % Thanks to Tobias Lamour for reporting the issue. % 14/11/2011 Bug fix: stop using hardcopy(), as it interfered with figure % size and erasemode settings. Makes it a bit slower, but more reliable. % Thanks to Phil Trinh and Meelis Lootus for reporting the issues. % 9/12/2011 Pass font path to ghostscript. % 27/1/2012 Bug fix affecting painters rendering tall figures. Thanks to % Ken Campbell for reporting it. % 3/4/2012 Bug fix to median input. Thanks to Andy Matthews for reporting % it. function [A bcol] = print2array(fig, res, renderer) % Generate default input arguments, if needed if nargin < 2 res = 1; if nargin < 1 fig = gcf; end end % Warn if output is large old_mode = get(fig, 'Units'); set(fig, 'Units', 'pixels'); px = get(fig, 'Position'); set(fig, 'Units', old_mode); npx = prod(px(3:4)*res)/1e6; if npx > 30 % 30M pixels or larger! warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx); end % Retrieve the background colour bcol = get(fig, 'Color'); % Set the resolution parameter res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))]; % Generate temporary file name tmp_nam = [tempname '.tif']; if nargin > 2 && strcmp(renderer, '-painters') % Print to eps file tmp_eps = [tempname '.eps']; print2eps(tmp_eps, fig, renderer, '-loose'); try % Initialize the command to export to tiff using ghostscript cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc']; % Set the font path fp = font_path(); if ~isempty(fp) cmd_str = [cmd_str ' -sFONTPATH="' fp '"']; end % Add the filenames cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"']; % Execute the ghostscript command ghostscript(cmd_str); catch % Delete the intermediate file delete(tmp_eps); rethrow(lasterror); end % Delete the intermediate file delete(tmp_eps); % Read in the generated bitmap A = imread(tmp_nam); % Delete the temporary bitmap file delete(tmp_nam); % Set border pixels to the correct colour if isequal(bcol, 'none') bcol = []; elseif isequal(bcol, [1 1 1]) bcol = uint8([255 255 255]); else for l = 1:size(A, 2) if ~all(reshape(A(:,l,:) == 255, [], 1)) break; end end for r = size(A, 2):-1:l if ~all(reshape(A(:,r,:) == 255, [], 1)) break; end end for t = 1:size(A, 1) if ~all(reshape(A(t,:,:) == 255, [], 1)) break; end end for b = size(A, 1):-1:t if ~all(reshape(A(b,:,:) == 255, [], 1)) break; end end bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1)); for c = 1:size(A, 3) A(:,[1:l-1, r+1:end],c) = bcol(c); A([1:t-1, b+1:end],:,c) = bcol(c); end end else if nargin < 3 renderer = '-opengl'; end err = false; % Set paper size old_mode = get(fig, 'PaperPositionMode'); set(fig, 'PaperPositionMode', 'auto'); try % Print to tiff file print(fig, renderer, res_str, '-dtiff', tmp_nam); % Read in the printed file A = imread(tmp_nam); % Delete the temporary file delete(tmp_nam); catch ex err = true; end % Reset paper size set(fig, 'PaperPositionMode', old_mode); % Throw any error that occurred if err rethrow(ex); end % Set the background color if isequal(bcol, 'none') bcol = []; else bcol = bcol * 255; if isequal(bcol, round(bcol)) bcol = uint8(bcol); else bcol = squeeze(A(1,1,:)); end end end % Check the output size is correct if isequal(res, round(res)) px = [px([4 3])*res 3]; if ~isequal(size(A), px) % Correct the output size A = A(1:min(end,px(1)),1:min(end,px(2)),:); end end return % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); return
github
aamiranis/sampling_theory-master
eps2pdf.m
.m
sampling_theory-master/results/exportfig/eps2pdf.m
5,151
utf_8
b356d73460fdebe8ef6fa428d5b2c125
%EPS2PDF Convert an eps file to pdf format using ghostscript % % Examples: % eps2pdf source dest % eps2pdf(source, dest, crop) % eps2pdf(source, dest, crop, append) % eps2pdf(source, dest, crop, append, gray) % eps2pdf(source, dest, crop, append, gray, quality) % % This function converts an eps file to pdf format. The output can be % optionally cropped and also converted to grayscale. If the output pdf % file already exists then the eps file can optionally be appended as a new % page on the end of the eps file. The level of bitmap compression can also % optionally be set. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % %IN: % source - filename of the source eps file to convert. The filename is % assumed to already have the extension ".eps". % dest - filename of the destination pdf file. The filename is assumed to % already have the extension ".pdf". % crop - boolean indicating whether to crop the borders off the pdf. % Default: true. % append - boolean indicating whether the eps should be appended to the % end of the pdf as a new page (if the pdf exists already). % Default: false. % gray - boolean indicating whether the output pdf should be grayscale or % not. Default: false. % quality - scalar indicating the level of image bitmap quality to % output. A larger value gives a higher quality. quality > 100 % gives lossless output. Default: ghostscript prepress default. % Copyright (C) Oliver Woodford 2009-2011 % Suggestion of appending pdf files provided by Matt C at: % http://www.mathworks.com/matlabcentral/fileexchange/23629 % Thank you to Fabio Viola for pointing out compression artifacts, leading % to the quality setting. % Thank you to Scott for pointing out the subsampling of very small images, % which was fixed for lossless compression settings. % 9/12/2011 Pass font path to ghostscript. function eps2pdf(source, dest, crop, append, gray, quality) % Intialise the options string for ghostscript options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"']; % Set crop option if nargin < 3 || crop options = [options ' -dEPSCrop']; end % Set the font path fp = font_path(); if ~isempty(fp) options = [options ' -sFONTPATH="' fp '"']; end % Set the grayscale option if nargin > 4 && gray options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray']; end % Set the bitmap quality if nargin > 5 && ~isempty(quality) options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false']; if quality > 100 options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"']; else options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode']; v = 1 + (quality < 80); quality = 1 - quality / 100; s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v); options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s); end end % Check if the output file exists if nargin > 3 && append && exist(dest, 'file') == 2 % File exists - append current figure to the end tmp_nam = tempname; % Copy the file copyfile(dest, tmp_nam); % Add the output file names options = [options ' -f "' tmp_nam '" "' source '"']; try % Convert to pdf using ghostscript [status message] = ghostscript(options); catch % Delete the intermediate file delete(tmp_nam); rethrow(lasterror); end % Delete the intermediate file delete(tmp_nam); else % File doesn't exist or should be over-written % Add the output file names options = [options ' -f "' source '"']; % Convert to pdf using ghostscript [status message] = ghostscript(options); end % Check for error if status % Report error if isempty(message) error('Unable to generate pdf. Check destination directory is writable.'); else error(message); end end return % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); return
github
aamiranis/sampling_theory-master
copyfig.m
.m
sampling_theory-master/results/exportfig/copyfig.m
846
utf_8
289162022c603c9e11a52b6d56329188
%COPYFIG Create a copy of a figure, without changing the figure % % Examples: % fh_new = copyfig(fh_old) % % This function will create a copy of a figure, but not change the figure, % as copyobj sometimes does, e.g. by changing legends. % % IN: % fh_old - The handle of the figure to be copied. Default: gcf. % % OUT: % fh_new - The handle of the created figure. % Copyright (C) Oliver Woodford 2012 function fh = copyfig(fh) % Set the default if nargin == 0 fh = gcf; end % Is there a legend? if isempty(findobj(fh, 'Type', 'axes', 'Tag', 'legend')) % Safe to copy using copyobj fh = copyobj(fh, 0); else % copyobj will change the figure, so save and then load it instead tmp_nam = [tempname '.fig']; hgsave(fh, tmp_nam); fh = hgload(tmp_nam); delete(tmp_nam); end return
github
aamiranis/sampling_theory-master
user_string.m
.m
sampling_theory-master/results/exportfig/user_string.m
2,339
utf_8
f9b2326571e9d13eccc99ce441efd788
%USER_STRING Get/set a user specific string % % Examples: % string = user_string(string_name) % saved = user_string(string_name, new_string) % % Function to get and set a string in a system or user specific file. This % enables, for example, system specific paths to binaries to be saved. % % IN: % string_name - String containing the name of the string required. The % string is extracted from a file called (string_name).txt, % stored in the same directory as user_string.m. % new_string - The new string to be saved under the name given by % string_name. % % OUT: % string - The currently saved string. Default: ''. % saved - Boolean indicating whether the save was succesful % Copyright (C) Oliver Woodford 2011 % This method of saving paths avoids changing .m files which might be in a % version control system. Instead it saves the user dependent paths in % separate files with a .txt extension, which need not be checked in to % the version control system. Thank you to Jonas Dorn for suggesting this % approach. function string = user_string(string_name, string) if ~ischar(string_name) error('string_name must be a string.'); end % Create the full filename string_name = fullfile(fileparts(mfilename('fullpath')), '.ignore', [string_name '.txt']); if nargin > 1 % Set string if ~ischar(string) error('new_string must be a string.'); end % Make sure the save directory exists dname = fileparts(string_name); if ~exist(dname, 'dir') % Create the directory try if ~mkdir(dname) string = false; return end catch string = false; return end % Make it hidden try fileattrib(dname, '+h'); catch end end % Write the file fid = fopen(string_name, 'w'); if fid == -1 string = false; return end try fwrite(fid, string, '*char'); catch fclose(fid); string = false; return end fclose(fid); string = true; else % Get string fid = fopen(string_name, 'r'); if fid == -1 string = ''; return end string = fread(fid, '*char')'; fclose(fid); end return
github
aamiranis/sampling_theory-master
export_fig.m
.m
sampling_theory-master/results/exportfig/export_fig.m
29,468
utf_8
e1fc4fe8c0dcd6f758389b63c10a52bf
%EXPORT_FIG Exports figures suitable for publication % % Examples: % im = export_fig % [im alpha] = export_fig % export_fig filename % export_fig filename -format1 -format2 % export_fig ... -nocrop % export_fig ... -transparent % export_fig ... -native % export_fig ... -m<val> % export_fig ... -r<val> % export_fig ... -a<val> % export_fig ... -q<val> % export_fig ... -<renderer> % export_fig ... -<colorspace> % export_fig ... -append % export_fig ... -bookmark % export_fig(..., handle) % % This function saves a figure or single axes to one or more vector and/or % bitmap file formats, and/or outputs a rasterized version to the % workspace, with the following properties: % - Figure/axes reproduced as it appears on screen % - Cropped borders (optional) % - Embedded fonts (vector formats) % - Improved line and grid line styles % - Anti-aliased graphics (bitmap formats) % - Render images at native resolution (optional for bitmap formats) % - Transparent background supported (pdf, eps, png) % - Semi-transparent patch objects supported (png only) % - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff) % - Variable image compression, including lossless (pdf, eps, jpg) % - Optionally append to file (pdf, tiff) % - Vector formats: pdf, eps % - Bitmap formats: png, tiff, jpg, bmp, export to workspace % % This function is especially suited to exporting figures for use in % publications and presentations, because of the high quality and % portability of media produced. % % Note that the background color and figure dimensions are reproduced % (the latter approximately, and ignoring cropping & magnification) in the % output file. For transparent background (and semi-transparent patch % objects), use the -transparent option or set the figure 'Color' property % to 'none'. To make axes transparent set the axes 'Color' property to % 'none'. Pdf, eps and png are the only file formats to support a % transparent background, whilst the png format alone supports transparency % of patch objects. % % The choice of renderer (opengl, zbuffer or painters) has a large impact % on the quality of output. Whilst the default value (opengl for bitmaps, % painters for vector formats) generally gives good results, if you aren't % satisfied then try another renderer. Notes: 1) For vector formats (eps, % pdf), only painters generates vector graphics. 2) For bitmaps, only % opengl can render transparent patch objects correctly. 3) For bitmaps, % only painters will correctly scale line dash and dot lengths when % magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when % using painters. % % When exporting to vector format (pdf & eps) and bitmap format using the % painters renderer, this function requires that ghostscript is installed % on your system. You can download this from: % http://www.ghostscript.com % When exporting to eps it additionally requires pdftops, from the Xpdf % suite of functions. You can download this from: % http://www.foolabs.com/xpdf % %IN: % filename - string containing the name (optionally including full or % relative path) of the file the figure is to be saved as. If % a path is not specified, the figure is saved in the current % directory. If no name and no output arguments are specified, % the default name, 'export_fig_out', is used. If neither a % file extension nor a format are specified, a ".png" is added % and the figure saved in that format. % -format1, -format2, etc. - strings containing the extensions of the % file formats the figure is to be saved as. % Valid options are: '-pdf', '-eps', '-png', % '-tif', '-jpg' and '-bmp'. All combinations % of formats are valid. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -transparent - option indicating that the figure background is to be % made transparent (png, pdf and eps output only). % -m<val> - option where val indicates the factor to magnify the % on-screen figure dimensions by when generating bitmap % outputs. Default: '-m1'. % -r<val> - option val indicates the resolution (in pixels per inch) to % export bitmap outputs at, keeping the dimensions of the % on-screen figure. Default: sprintf('-r%g', get(0, % 'ScreenPixelsPerInch')). Note that the -m and -r options % change the same property. % -native - option indicating that the output resolution (when outputting % a bitmap format) should be such that the vertical resolution % of the first suitable image found in the figure is at the % native resolution of that image. To specify a particular % image to use, give it the tag 'export_fig_native'. Notes: % This overrides any value set with the -m and -r options. It % also assumes that the image is displayed front-to-parallel % with the screen. The output resolution is approximate and % should not be relied upon. Anti-aliasing can have adverse % effects on image quality (disable with the -a1 option). % -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to % use for bitmap outputs. '-a1' means no anti- % aliasing; '-a4' is the maximum amount (default). % -<renderer> - option to force a particular renderer (painters, opengl % or zbuffer) to be used over the default: opengl for % bitmaps; painters for vector formats. % -<colorspace> - option indicating which colorspace color figures should % be saved in: RGB (default), CMYK or gray. CMYK is only % supported in pdf, eps and tiff output. % -q<val> - option to vary bitmap image quality (in pdf, eps and jpg % files only). Larger val, in the range 0-100, gives higher % quality/lower compression. val > 100 gives lossless % compression. Default: '-q95' for jpg, ghostscript prepress % default for pdf & eps. Note: lossless compression can % sometimes give a smaller file size than the default lossy % compression, depending on the type of images. % -append - option indicating that if the file (pdfs only) already % exists, the figure is to be appended as a new page, instead % of being overwritten (default). % -bookmark - option to indicate that a bookmark with the name of the % figure is to be created in the output file (pdf only). % handle - The handle of the figure or axes (can be an array of handles % of several axes, but these must be in the same figure) to be % saved. Default: gcf. % %OUT: % im - MxNxC uint8 image array of the figure. % alpha - MxN single array of alphamatte values in range [0,1], for the % case when the background is transparent. % % Some helpful examples and tips can be found at: % http://sites.google.com/site/oliverwoodford/software/export_fig % % See also PRINT, SAVEAS. % Copyright (C) Oliver Woodford 2008-2012 % The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG % (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782). % The idea for using pdftops came from the MATLAB newsgroup (id: 168171). % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928). % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id: % 20979). % The idea of appending figures in pdfs came from Matt C in comments on the % FEX (id: 23629) % Thanks to Roland Martin for pointing out the colour MATLAB % bug/feature with colorbar axes and transparent backgrounds. % Thanks also to Andrew Matthews for describing a bug to do with the figure % size changing in -nodisplay mode. I couldn't reproduce it, but included a % fix anyway. % Thanks to Tammy Threadgill for reporting a bug where an axes is not % isolated from gui objects. % 23/02/12: Ensure that axes limits don't change during printing % 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for % reporting it). % 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling % bookmarking of figures in pdf files. % 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep % tick marks fixed. function [im alpha] = export_fig(varargin) % Make sure the figure is rendered correctly _now_ so that properties like % axes limits are up-to-date. drawnow; % Parse the input arguments [fig options] = parse_args(nargout, varargin{:}); % Isolate the subplot, if it is one cls = strcmp(get(fig(1), 'Type'), 'axes'); if cls % Given handles of one or more axes, so isolate them from the rest fig = isolate_axes(fig); else old_mode = get(fig, 'InvertHardcopy'); end % Hack the font units where necessary (due to a font rendering bug in % print?). This may not work perfectly in all cases. Also it can change the % figure layout if reverted, so use a copy. magnify = options.magnify * options.aa_factor; if isbitmap(options) && magnify ~= 1 fontu = findobj(fig, 'FontUnits', 'normalized'); if ~isempty(fontu) % Some normalized font units found if ~cls fig = copyfig(fig); set(fig, 'Visible', 'off'); fontu = findobj(fig, 'FontUnits', 'normalized'); cls = true; end set(fontu, 'FontUnits', 'points'); end end % MATLAB "feature": axes limits can change when printing Hlims = findall(fig, 'Type', 'axes'); if ~cls % Record the old axes limit and tick modes Xlims = make_cell(get(Hlims, 'XLimMode')); Ylims = make_cell(get(Hlims, 'YLimMode')); Zlims = make_cell(get(Hlims, 'ZLimMode')); Xtick = make_cell(get(Hlims, 'XTickMode')); Ytick = make_cell(get(Hlims, 'YTickMode')); Ztick = make_cell(get(Hlims, 'ZTickMode')); end % Set all axes limit and tick modes to manual, so the limits and ticks can't change set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual'); % Set to print exactly what is there set(fig, 'InvertHardcopy', 'off'); % Set the renderer switch options.renderer case 1 renderer = '-opengl'; case 2 renderer = '-zbuffer'; case 3 renderer = '-painters'; otherwise renderer = '-opengl'; % Default for bitmaps end % Do the bitmap formats first if isbitmap(options) % Get the background colour if options.transparent && (options.png || options.alpha) % Get out an alpha channel % MATLAB "feature": black colorbar axes can change to white and vice versa! hCB = findobj(fig, 'Type', 'axes', 'Tag', 'Colorbar'); if isempty(hCB) yCol = []; xCol = []; else yCol = get(hCB, 'YColor'); xCol = get(hCB, 'XColor'); if iscell(yCol) yCol = cell2mat(yCol); xCol = cell2mat(xCol); end yCol = sum(yCol, 2); xCol = sum(xCol, 2); end % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); % Set the background colour to black, and set size in case it was % changed internally tcol = get(fig, 'Color'); set(fig, 'Color', 'k', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==0), 'YColor', [0 0 0]); set(hCB(xCol==0), 'XColor', [0 0 0]); % Print large version to array B = print2array(fig, magnify, renderer); % Downscale the image B = downsize(single(B), options.aa_factor); % Set background to white (and set size) set(fig, 'Color', 'w', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==3), 'YColor', [1 1 1]); set(hCB(xCol==3), 'XColor', [1 1 1]); % Print large version to array A = print2array(fig, magnify, renderer); % Downscale the image A = downsize(single(A), options.aa_factor); % Set the background colour (and size) back to normal set(fig, 'Color', tcol, 'Position', pos); % Compute the alpha map alpha = round(sum(B - A, 3)) / (255 * 3) + 1; A = alpha; A(A==0) = 1; A = B ./ A(:,:,[1 1 1]); clear B % Convert to greyscale if options.colourspace == 2 A = rgb2grey(A); end A = uint8(A); % Crop the background if options.crop [alpha v] = crop_background(alpha, 0); A = A(v(1):v(2),v(3):v(4),:); end if options.png % Compute the resolution res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; % Save the png imwrite(A, [options.name '.png'], 'Alpha', alpha, 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); % Clear the png bit options.png = false; end % Return only one channel for greyscale if isbitmap(options) A = check_greyscale(A); end if options.alpha % Store the image im = A; % Clear the alpha bit options.alpha = false; end % Get the non-alpha image if isbitmap(options) alph = alpha(:,:,ones(1, size(A, 3))); A = uint8(single(A) .* alph + 255 * (1 - alph)); clear alph end if options.im % Store the new image im = A; end else % Print large version to array if options.transparent % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); tcol = get(fig, 'Color'); set(fig, 'Color', 'w', 'Position', pos); A = print2array(fig, magnify, renderer); set(fig, 'Color', tcol, 'Position', pos); tcol = 255; else [A tcol] = print2array(fig, magnify, renderer); end % Crop the background if options.crop A = crop_background(A, tcol); end % Downscale the image A = downsize(A, options.aa_factor); if options.colourspace == 2 % Convert to greyscale A = rgb2grey(A); else % Return only one channel for greyscale A = check_greyscale(A); end % Outputs if options.im im = A; end if options.alpha im = A; alpha = zeros(size(A, 1), size(A, 2), 'single'); end end % Save the images if options.png res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); end if options.bmp imwrite(A, [options.name '.bmp']); end % Save jpeg with given quality if options.jpg quality = options.quality; if isempty(quality) quality = 95; end if quality > 100 imwrite(A, [options.name '.jpg'], 'Mode', 'lossless'); else imwrite(A, [options.name '.jpg'], 'Quality', quality); end end % Save tif images in cmyk if wanted (and possible) if options.tif if options.colourspace == 1 && size(A, 3) == 3 A = double(255 - A); K = min(A, [], 3); K_ = 255 ./ max(255 - K, 1); C = (A(:,:,1) - K) .* K_; M = (A(:,:,2) - K) .* K_; Y = (A(:,:,3) - K) .* K_; A = uint8(cat(3, C, M, Y, K)); clear C M Y K K_ end append_mode = {'overwrite', 'append'}; imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1}); end end % Now do the vector formats if isvector(options) % Set the default renderer to painters if ~options.renderer renderer = '-painters'; end % Generate some filenames tmp_nam = [tempname '.eps']; if options.pdf pdf_nam = [options.name '.pdf']; else pdf_nam = [tempname '.pdf']; end % Generate the options for print p2eArgs = {renderer}; if options.colourspace == 1 p2eArgs = [p2eArgs {'-cmyk'}]; end if ~options.crop p2eArgs = [p2eArgs {'-loose'}]; end try % Generate an eps print2eps(tmp_nam, fig, p2eArgs{:}); % Remove the background, if desired if options.transparent && ~isequal(get(fig, 'Color'), 'none') eps_remove_background(tmp_nam); end % Add a bookmark to the PDF if desired if options.bookmark fig_nam = get(fig, 'Name'); if isempty(fig_nam) warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.'); end add_bookmark(tmp_nam, fig_nam); end % Generate a pdf eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality); catch ex % Delete the eps delete(tmp_nam); rethrow(ex); end % Delete the eps delete(tmp_nam); if options.eps try % Generate an eps from the pdf pdf2eps(pdf_nam, [options.name '.eps']); catch ex if ~options.pdf % Delete the pdf delete(pdf_nam); end rethrow(ex); end if ~options.pdf % Delete the pdf delete(pdf_nam); end end end if cls % Close the created figure close(fig); else % Reset the hardcopy mode set(fig, 'InvertHardcopy', old_mode); % Reset the axes limit and tick modes for a = 1:numel(Hlims) set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a}); end end return function [fig options] = parse_args(nout, varargin) % Parse the input arguments % Set the defaults fig = get(0, 'CurrentFigure'); options = struct('name', 'export_fig_out', ... 'crop', true, ... 'transparent', false, ... 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters 'pdf', false, ... 'eps', false, ... 'png', false, ... 'tif', false, ... 'jpg', false, ... 'bmp', false, ... 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray 'append', false, ... 'im', nout == 1, ... 'alpha', nout == 2, ... 'aa_factor', 3, ... 'magnify', 1, ... 'bookmark', false, ... 'quality', []); native = false; % Set resolution to native of an image % Go through the other arguments for a = 1:nargin-1 if all(ishandle(varargin{a})) fig = varargin{a}; elseif ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' switch lower(varargin{a}(2:end)) case 'nocrop' options.crop = false; case {'trans', 'transparent'} options.transparent = true; case 'opengl' options.renderer = 1; case 'zbuffer' options.renderer = 2; case 'painters' options.renderer = 3; case 'pdf' options.pdf = true; case 'eps' options.eps = true; case 'png' options.png = true; case {'tif', 'tiff'} options.tif = true; case {'jpg', 'jpeg'} options.jpg = true; case 'bmp' options.bmp = true; case 'rgb' options.colourspace = 0; case 'cmyk' options.colourspace = 1; case {'gray', 'grey'} options.colourspace = 2; case {'a1', 'a2', 'a3', 'a4'} options.aa_factor = str2double(varargin{a}(3)); case 'append' options.append = true; case 'bookmark' options.bookmark = true; case 'native' native = true; otherwise val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q))(\d*\.)?\d+(e-?\d+)?', 'match')); if ~isscalar(val) error('option %s not recognised', varargin{a}); end switch lower(varargin{a}(2)) case 'm' options.magnify = val; case 'r' options.magnify = val ./ get(0, 'ScreenPixelsPerInch'); case 'q' options.quality = max(val, 0); end end else [p options.name ext] = fileparts(varargin{a}); if ~isempty(p) options.name = [p filesep options.name]; end switch lower(ext) case {'.tif', '.tiff'} options.tif = true; case {'.jpg', '.jpeg'} options.jpg = true; case '.png' options.png = true; case '.bmp' options.bmp = true; case '.eps' options.eps = true; case '.pdf' options.pdf = true; otherwise options.name = varargin{a}; end end end end % Check we have a figure handle if isempty(fig) error('No figure found'); end % Set the default format if ~isvector(options) && ~isbitmap(options) options.png = true; end % Check whether transparent background is wanted (old way) if isequal(get(fig, 'Color'), 'none') options.transparent = true; end % If requested, set the resolution to the native vertical resolution of the % first suitable image found if native && isbitmap(options) % Find a suitable image list = findobj(fig, 'Type', 'image', 'Tag', 'export_fig_native'); if isempty(list) list = findobj(fig, 'Type', 'image', 'Visible', 'on'); end for hIm = list(:)' % Check height is >= 2 height = size(get(hIm, 'CData'), 1); if height < 2 continue end % Account for the image filling only part of the axes, or vice % versa yl = get(hIm, 'YData'); if isscalar(yl) yl = [yl(1)-0.5 yl(1)+height+0.5]; else if ~diff(yl) continue end yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1)); end hAx = get(hIm, 'Parent'); yl2 = get(hAx, 'YLim'); % Find the pixel height of the axes oldUnits = get(hAx, 'Units'); set(hAx, 'Units', 'pixels'); pos = get(hAx, 'Position'); set(hAx, 'Units', oldUnits); if ~pos(4) continue end % Found a suitable image % Account for stretch-to-fill being disabled pbar = get(hAx, 'PlotBoxAspectRatio'); pos = min(pos(4), pbar(2)*pos(3)/pbar(1)); % Set the magnification to give native resolution options.magnify = (height * diff(yl2)) / (pos * diff(yl)); break end end return function A = downsize(A, factor) % Downsample an image if factor == 1 % Nothing to do return end try % Faster, but requires image processing toolbox A = imresize(A, 1/factor, 'bilinear'); catch % No image processing toolbox - resize manually % Lowpass filter - use Gaussian as is separable, so faster % Compute the 1d Gaussian filter filt = (-factor-1:factor+1) / (factor * 0.6); filt = exp(-filt .* filt); % Normalize the filter filt = single(filt / sum(filt)); % Filter the image padding = floor(numel(filt) / 2); for a = 1:size(A, 3) A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid'); end % Subsample A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:); end return function A = rgb2grey(A) A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); return function A = check_greyscale(A) % Check if the image is greyscale if size(A, 3) == 3 && ... all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ... all(reshape(A(:,:,2) == A(:,:,3), [], 1)) A = A(:,:,1); % Save only one channel for 8-bit output end return function [A v] = crop_background(A, bcol) % Map the foreground pixels [h w c] = size(A); if isscalar(bcol) && c > 1 bcol = bcol(ones(1, c)); end bail = false; for l = 1:w for a = 1:c if ~all(A(:,l,a) == bcol(a)) bail = true; break; end end if bail break; end end bail = false; for r = w:-1:l for a = 1:c if ~all(A(:,r,a) == bcol(a)) bail = true; break; end end if bail break; end end bail = false; for t = 1:h for a = 1:c if ~all(A(t,:,a) == bcol(a)) bail = true; break; end end if bail break; end end bail = false; for b = h:-1:t for a = 1:c if ~all(A(b,:,a) == bcol(a)) bail = true; break; end end if bail break; end end % Crop the background, leaving one boundary pixel to avoid bleeding on % resize v = [max(t-1, 1) min(b+1, h) max(l-1, 1) min(r+1, w)]; A = A(v(1):v(2),v(3):v(4),:); return function eps_remove_background(fname) % Remove the background of an eps file % Open the file fh = fopen(fname, 'r+'); if fh == -1 error('Not able to open file %s.', fname); end % Read the file line by line while true % Get the next line l = fgets(fh); if isequal(l, -1) break; % Quit, no rectangle found end % Check if the line contains the background rectangle if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +rf *[\n\r]+', 'start'), 1) % Set the line to whitespace and quit l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' '; fseek(fh, -numel(l), 0); fprintf(fh, l); break; end end % Close the file fclose(fh); return function b = isvector(options) b = options.pdf || options.eps; return function b = isbitmap(options) b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha; return % Helper function function A = make_cell(A) if ~iscell(A) A = {A}; end return function add_bookmark(fname, bookmark_text) % Adds a bookmark to the temporary EPS file after %%EndPageSetup % Read in the file fh = fopen(fname, 'r'); if fh == -1 error('File %s not found.', fname); end try fstrm = fread(fh, '*char')'; catch ex fclose(fh); rethrow(ex); end fclose(fh); % Include standard pdfmark prolog to maximize compatibility fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse')); % Add page bookmark fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text)); % Write out the updated file fh = fopen(fname, 'w'); if fh == -1 error('Unable to open %s for writing.', fname); end try fwrite(fh, fstrm, 'char*1'); catch ex fclose(fh); rethrow(ex); end fclose(fh); return
github
aamiranis/sampling_theory-master
ghostscript.m
.m
sampling_theory-master/results/exportfig/ghostscript.m
4,215
utf_8
621b90eb2972a74b0f4094afa317e96d
function varargout = ghostscript(cmd) %GHOSTSCRIPT Calls a local GhostScript executable with the input command % % Example: % [status result] = ghostscript(cmd) % % Attempts to locate a ghostscript executable, finally asking the user to % specify the directory ghostcript was installed into. The resulting path % is stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have Ghostscript installed on your % system. You can download this from: http://www.ghostscript.com % % IN: % cmd - Command string to be passed into ghostscript. % % OUT: % status - 0 iff command ran without problem. % result - Output from ghostscript. % Copyright: Oliver Woodford, 2009-2010 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on % Mac OS. % Thanks to Nathan Childress for the fix to the default location on 64-bit % Windows systems. % 27/4/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and % Shaun Kline for pointing out the issue % 4/5/11 - Thanks to David Chorlian for pointing out an alternative % location for gs on linux. % Call ghostscript [varargout{1:nargout}] = system(sprintf('"%s" %s', gs_path, cmd)); return function path = gs_path % Return a valid path % Start with the currently set path path = user_string('ghostscript'); % Check the path works if check_gs_path(path) return end % Check whether the binary is on the path if ispc bin = {'gswin32c.exe', 'gswin64c.exe'}; else bin = {'gs'}; end for a = 1:numel(bin) path = bin{a}; if check_store_gs_path(path) return end end % Search the obvious places if ispc default_location = 'C:\Program Files\gs\'; dir_list = dir(default_location); if isempty(dir_list) default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems dir_list = dir(default_location); end executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'}; ver_num = 0; % If there are multiple versions, use the newest for a = 1:numel(dir_list) ver_num2 = sscanf(dir_list(a).name, 'gs%g'); if ~isempty(ver_num2) && ver_num2 > ver_num for b = 1:numel(executable) path2 = [default_location dir_list(a).name executable{b}]; if exist(path2, 'file') == 2 path = path2; ver_num = ver_num2; end end end end if check_store_gs_path(path) return end else bin = {'/usr/bin/gs', '/usr/local/bin/gs'}; for a = 1:numel(bin) path = bin{a}; if check_store_gs_path(path) return end end end % Ask the user to enter the path while 1 if strncmp(computer, 'MAC', 3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Ghostscript not found. Please locate the program.')) end base = uigetdir('/', 'Ghostcript not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) for b = 1:numel(bin) path = [base bin_dir{a} bin{b}]; if exist(path, 'file') == 2 if check_store_gs_path(path) return end end end end end error('Ghostscript not found. Have you installed it from www.ghostscript.com?'); function good = check_store_gs_path(path) % Check the path is valid good = check_gs_path(path); if ~good return end % Update the current default path to the path found if ~user_string('ghostscript', path) warning('Path to ghostscript installation could not be saved. Enter it manually in ghostscript.txt.'); return end return function good = check_gs_path(path) % Check the path is valid [good message] = system(sprintf('"%s" -h', path)); good = good == 0; return
github
aamiranis/sampling_theory-master
print2eps.m
.m
sampling_theory-master/results/exportfig/print2eps.m
6,295
utf_8
afc45df95a67e7d634c24d5c2b265207
%PRINT2EPS Prints figures to eps with improved line styles % % Examples: % print2eps filename % print2eps(filename, fig_handle) % print2eps(filename, fig_handle, options) % % This function saves a figure as an eps file, with two improvements over % MATLAB's print command. First, it improves the line style, making dashed % lines more like those on screen and giving grid lines their own dotted % style. Secondly, it substitutes original font names back into the eps % file, where these have been changed by MATLAB, for up to 11 different % fonts. % %IN: % filename - string containing the name (optionally including full or % relative path) of the file the figure is to be saved as. A % ".eps" extension is added if not there already. If a path is % not specified, the figure is saved in the current directory. % fig_handle - The handle of the figure to be saved. Default: gcf. % options - Additional parameter strings to be passed to print. % Copyright (C) Oliver Woodford 2008-2012 % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928) % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % 14/11/2011 Fix a MATLAB bug rendering black or white text incorrectly. % Thanks to Mathieu Morlighem for reporting the issue and obtaining a fix % from TMW. % 8/12/2011 Added ability to correct fonts. Several people have requested % this at one time or another, and also pointed me to printeps (fex id: % 7501), so thank you to them. My implementation (which was not inspired by % printeps - I'd already had the idea for my approach) goes % slightly further in that it allows multiple fonts to be swapped. % 14/12/2011 Fix bug affecting font names containing spaces. Many thanks to % David Szwer for reporting the issue. % 25/1/2012 Add a font not to be swapped. Thanks to Anna Rafferty and Adam % Jackson for reporting the issue. Also fix a bug whereby using a font % alias can lead to another font being swapped in. % 10/4/2012 Make the font swapping case insensitive. function print2eps(name, fig, varargin) options = {'-depsc2'}; if nargin < 2 fig = gcf; elseif nargin > 2 options = [options varargin]; end % Construct the filename if numel(name) < 5 || ~strcmpi(name(end-3:end), '.eps') name = [name '.eps']; % Add the missing extension end % Find all the used fonts in the figure font_handles = findall(fig, '-property', 'FontName'); fonts = get(font_handles, 'FontName'); if ~iscell(fonts) fonts = {fonts}; end % Map supported font aliases onto the correct name fontsl = lower(fonts); for a = 1:numel(fonts) f = fontsl{a}; f(f==' ') = []; switch f case {'times', 'timesnewroman', 'times-roman'} fontsl{a} = 'times-roman'; case {'arial', 'helvetica'} fontsl{a} = 'helvetica'; case {'newcenturyschoolbook', 'newcenturyschlbk'} fontsl{a} = 'newcenturyschlbk'; otherwise end end fontslu = unique(fontsl); % Determine the font swap table matlab_fonts = {'Helvetica', 'Times-Roman', 'Palatino', 'Bookman', 'Helvetica-Narrow', 'Symbol', ... 'AvantGarde', 'NewCenturySchlbk', 'Courier', 'ZapfChancery', 'ZapfDingbats'}; matlab_fontsl = lower(matlab_fonts); require_swap = find(~ismember(fontslu, matlab_fontsl)); unused_fonts = find(~ismember(matlab_fontsl, fontslu)); font_swap = cell(3, 0); for a = 1:min(numel(require_swap), numel(unused_fonts)) ind = find(strcmp(fontslu{require_swap(a)}, fontsl)); n = numel(ind); font_swap(1,end+1:end+n) = reshape(mat2cell(font_handles(ind), ones(n, 1)), 1, []); font_swap(2,end-n+1:end) = matlab_fonts(unused_fonts(a)); font_swap(3,end-n+1:end) = reshape(fonts(ind), 1, []); end % Swap the fonts for a = 1:size(font_swap, 2) set(font_swap{1,a}, 'FontName', font_swap{2,a}); end % Set paper size old_mode = get(fig, 'PaperPositionMode'); set(fig, 'PaperPositionMode', 'auto'); % MATLAB bug fix - black and white text can come out inverted sometimes % Find the white and black text white_text_handles = findobj(fig, 'Type', 'text'); M = get(white_text_handles, 'Color'); if iscell(M) M = cell2mat(M); end M = sum(M, 2); black_text_handles = white_text_handles(M == 0); white_text_handles = white_text_handles(M == 3); % Set the font colors slightly off their correct values set(black_text_handles, 'Color', [0 0 0] + eps); set(white_text_handles, 'Color', [1 1 1] - eps); % Print to eps file print(fig, options{:}, name); % Reset the font colors set(black_text_handles, 'Color', [0 0 0]); set(white_text_handles, 'Color', [1 1 1]); % Reset paper size set(fig, 'PaperPositionMode', old_mode); % Correct the fonts if ~isempty(font_swap) % Reset the font names in the figure for a = 1:size(font_swap, 2) set(font_swap{1,a}, 'FontName', font_swap{3,a}); end % Replace the font names in the eps file font_swap = font_swap(2:3,:); try swap_fonts(name, font_swap{:}); catch warning('swap_fonts() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.'); return end end % Fix the line styles try fix_lines(name); catch warning('fix_lines() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.'); end return function swap_fonts(fname, varargin) % Read in the file fh = fopen(fname, 'r'); if fh == -1 error('File %s not found.', fname); end try fstrm = fread(fh, '*char')'; catch ex fclose(fh); rethrow(ex); end fclose(fh); % Replace the font names for a = 1:2:numel(varargin) fstrm = regexprep(fstrm, [varargin{a} '-?[a-zA-Z]*\>'], varargin{a+1}(~isspace(varargin{a+1}))); end % Write out the updated file fh = fopen(fname, 'w'); if fh == -1 error('Unable to open %s for writing.', fname2); end try fwrite(fh, fstrm, 'char*1'); catch ex fclose(fh); rethrow(ex); end fclose(fh); return
github
aamiranis/sampling_theory-master
sgwt_cheby_square.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_cheby_square.m
1,940
utf_8
5dd1536abce104317a8094bb4c7fcc51
% sgwt_cheby_square : Chebyshev coefficients for square of polynomial % % function d=sgwt_cheby_square(c) % % Inputs : % c - Chebyshev coefficients for p(x) = sum c(1+k) T_k(x) ; 0<=K<=M % % Outputs : % d - Chebyshev coefficients for p(x)^2 = sum d(1+k) T_k(x) ; % 0<=k<=2*M % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function d=sgwt_cheby_square(c) M=numel(c)-1; cp=c; cp(1)=.5*c(1); % adjust cp so that % p(x) = sum cp(1+k) T_k(x) % for all k>=0 (rather than with special case for k=0) % % Then formula for dp in terms of cp is simpler. % Ref: my notes, july 20, 2009 dp=zeros(1,2*M+1); % keep in mind : due to indexing from 1 % c(1+k) is k'th Chebyshev coefficient for m=0:(2*M) if (m==0) dp(1+m)=dp(1+m)+.5*cp(1)^2; for i=0:M dp(1+m)=dp(1+m)+.5*cp(1+i)^2; end elseif (m<=M) for i=0:m dp(1+m)=dp(1+m)+.5*cp(1+i)*cp(1+m-i); end for i=0:(M-m) dp(1+m)=dp(1+m)+.5*cp(1+i)*cp(1+i+m); end for i=m:M dp(1+m)=dp(1+m)+.5*cp(1+i)*cp(1+i-m); end else % M<m<=2*M for i=(m-M):M dp(1+m)=dp(1+m)+.5*cp(1+i)*cp(1+m-i); end end end d=dp; d(1)=2*dp(1);
github
aamiranis/sampling_theory-master
sgwt_kernel_abspline3.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_kernel_abspline3.m
1,879
utf_8
2cb063d47b5ee454c07302c6428e7dc5
% sgwt_kernel_abspline3 : Monic polynomial / cubic spline / power law decay kernel % % function r = sgwt_kernel_abspline3(x,alpha,beta,t1,t2) % % defines function g(x) with g(x) = c1*x^alpha for 0<x<x1 % g(x) = c3/x^beta for x>t2 % cubic spline for t1<x<t2, % Satisfying g(t1)=g(t2)=1 % % Inputs : % x : array of independent variable values % alpha : exponent for region near origin % beta : exponent decay % t1, t2 : determine transition region % % Outputs : % r - result (same size as x) % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function r = sgwt_kernel_abspline3(x,alpha,beta,t1,t2) r=zeros(size(x)); % compute spline coefficients % M a = v M=[[1 t1 t1^2 t1^3];... [1 t2 t2^2 t2^3];... [0 1 2*t1 3*t1^2];... [0 1 2*t2 3*t2^2]]; %v=[t1^alpha ; t2^(-beta) ; alpha*t1^(alpha-1) ; -beta*t2^(-beta-1)]; v=[1 ; 1 ; t1^(-alpha)*alpha*t1^(alpha-1) ; -beta*t2^(-beta-1)*t2^beta]; a=M\v; r1=find(x>=0 & x<t1); r2=find(x>=t1 & x<t2); r3=find(x>=t2); r(r1)=x(r1).^alpha*t1^(-alpha); r(r3)=x(r3).^(-beta)*t2^(beta); x2=x(r2); r(r2)=a(1)+a(2)*x2+a(3)*x2.^2+a(4)*x2.^3; % tmp=polyval(flipud(a),x2); % keyboard
github
aamiranis/sampling_theory-master
sgwt_kernel_abspline5.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_kernel_abspline5.m
2,174
utf_8
f6125a68524de3c1b9d68a60c20b04b9
% sgwt_kernel_abspline5 : Monic polynomial / quintic spline / power law decay kernel % % function r = sgwt_kernel_abspline5(x,alpha,beta,t1,t2) % % Defines function g(x) with g(x) = c1*x^alpha for 0<x<x1 % g(x) = c3/x^beta for x>t2 % quintic spline for t1<x<t2, % Satisfying g(t1)=g(t2)=1 % g'(t1)=g'(t2) % g''(t1)=g''(t2) % % Inputs : % x : array of independent variable values % alpha : exponent for region near origin % beta : exponent decay % t1, t2 : determine transition region % % Outputs : % r - result (same size as x) % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function r = sgwt_kernel_abspline5(x,alpha,beta,t1,t2) r=zeros(size(x)); % compute spline coefficients % M a = v M=[[1 t1 t1^2 t1^3 t1^4 t1^5];... [1 t2 t2^2 t2^3 t2^4 t2^5];... [0 1 2*t1 3*t1^2 4*t1^3 5*t1^4];... [0 1 2*t2 3*t2^2 4*t2^3 5*t2^4]; [0 0 2 6*t1 12*t1^2 20*t1^3];... [0 0 2 6*t2 12*t2^2 20*t2^3]... ]; %v=[t1^alpha ; t2^(-beta) ; alpha*t1^(alpha-1) ; -beta*t2^(-beta-1)]; v=[1 ; 1 ; ... t1^(-alpha)*alpha*t1^(alpha-1) ; -beta*t2^(-beta-1)*t2^beta; ... t1^(-alpha)*alpha*(alpha-1)*t1^(alpha-2);-beta*(-beta-1)*t2^(-beta-2)*t2^beta ]; a=M\v; r1=find(x>=0 & x<t1); r2=find(x>=t1 & x<t2); r3=find(x>=t2); r(r1)=x(r1).^alpha*t1^(-alpha); r(r3)=x(r3).^(-beta)*t2^(beta); x2=x(r2); r(r2)=a(1)+a(2)*x2+a(3)*x2.^2+a(4)*x2.^3+a(5)*x2.^4+a(6)*x2.^5; % tmp=polyval(flipud(a),x2); % keyboard
github
aamiranis/sampling_theory-master
sgwt_adjoint.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_adjoint.m
1,328
utf_8
a1b915af5342360927ac1e544a9e812c
% sgwt_adjoint : Compute adjoint of sgw transform % % function adj=sgwt_inverse(y,L,c,arange) % % Inputs: % y - sgwt coefficients % L - laplacian % c - cell array of Chebyshev coefficients defining transform % arange - spectral approximation range % % Outputs: % adj - computed sgwt adjoint applied to y % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function adj=sgwt_adjoint(y,L,c,arange) assert(iscell(c)); N=size(L,1); % first compute adj = W^*y ( sort of slowly ) adj=zeros(N,1); %fprintf('computing adjoint\n'); for j=1:numel(c) tmp=sgwt_cheby_op(y{j},L,c{j},arange); adj=adj+tmp; end
github
aamiranis/sampling_theory-master
sgwt_cheby_coeff.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_cheby_coeff.m
1,552
utf_8
fcab96b5fc2ee0008daebc18b441206e
% sgwt_cheby_coeff : Compute Chebyshev coefficients of given function % % function c=sgwt_cheby_coeff(g,m,N,arange) % % Inputs: % g - function handle, should define function on arange % m - maximum order Chebyshev coefficient to compute % N - grid order used to compute quadrature (default is m+1) % arange - interval of approximation (defaults to [-1,1] ) % % Outputs: % c - array of Chebyshev coefficients, ordered such that c(j+1) is % j'th Chebyshev coefficient % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function c=sgwt_cheby_coeff(g,m,N,arange) if ~exist('N','var') N=m+1; end if ~exist('arange','var') arange=[-1, 1]; end a1=(arange(2)-arange(1))/2; a2=(arange(2)+arange(1))/2; for j=1:m+1 c(j) = sum ( g(a1* cos( (pi*((1:N)-0.5))/N) + a2).*cos(pi*(j-1)*((1:N)-.5)/N) )*2/N; end
github
aamiranis/sampling_theory-master
sgwt_meshmat.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_meshmat.m
2,230
utf_8
8be6b355e7542c5588dd4ccf2006a51c
% sgwt_meshmat : Adjacency matrix for regular 2d mesh % % function A=meshmat_p(dim,varargin) % % Inputs: % dim - size of 2d mesh % Selectable control parameters: % boundary - 'rectangle' or 'torus' % % Outputs: % A - adjacency matrix % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function A=sgwt_meshmat(dim,varargin) control_params={'boundary','rectangle'}; argselectAssign(control_params); argselectCheck(control_params,varargin); argselectAssign(varargin); if (numel(dim)==1) dim=[1 1]*dim; end % build adjacency matrix : find i,j coordinates of center points % and right and bottom neighbors, then build connectivity matrix. % For each valid center,neighbor pair, will add A(center,neighbor)=1 % and A(neighbor,center)=1, so A will be symmetric N=prod(dim); [alli,allj]=find(ones(dim)); % (ci(k),cj(k)) has neighbor (ni(k),nj(k)) ci=[alli;alli]; cj=[allj;allj]; ni=[alli ; alli+1]; nj=[allj+1; allj]; switch boundary case 'rectangle' % prune edges at boundary valid=(ni>=1 & ni<=dim(1) & nj>=1 & nj<=dim(2)); ni=ni(valid); nj=nj(valid); ci=ci(valid); cj=cj(valid); cind=dim(1)*(cj-1)+ci; nind=dim(1)*(nj-1)+ni; case 'torus' % wrap indices to make torus ni=mod(ni,dim(1))+1; nj=mod(nj,dim(2))+1; cind=dim(1)*(cj-1)+ci; nind=dim(1)*(nj-1)+ni; otherwise error('unknown boundary option'); end % assemble connection matrix A=sparse([cind,nind],[nind,cind],ones(1,2*numel(ni)),N,N);
github
aamiranis/sampling_theory-master
sgwt_irregular_meshmat.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_irregular_meshmat.m
2,155
utf_8
d04f2a817116506446dea051cf5100f7
% sgwt_irregular_meshmat : Adjacency matrix from irregular domain mask % % function A = sgwt_irregular_meshmat(mask) % % Computes the adjaceny matrix of graph for given 2-d irregular % domain. Vertices of graph correspond to nonzero elements of % mask. Edges in graph connect to (up to) 4 nearest neighbors. % % Inputs : % % mask - binary map of desired 2-d irregular domain % % Outputs: % A - adjacency matrix of graph for irregular domain % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function A =sgwt_irregular_meshmat(mask) ind=nan(size(mask)); ind(logical(mask))=1:nnz(mask); N=nnz(mask); % there will be, at most, 2*N edges % so 4*N nonzero elements in A % generate list of edges % i j 1 % whenever vertex i connects to vertex j i=zeros(4*N,1); j=zeros(4*N,1); % Create array of indices % ni{k} are pixels that have neighbor type k % nj{k} are the inidices of pixels of the corresponding neighbor % % k=1 'top' k=2 'right' k=3 'bottom' k=4 'left' offset_list={[1 0],[0 1],[-1 0],[0 -1]}; for k=1:numel(offset_list) offset=offset_list{k}; nmask=shift(mask,offset); nind=shift(ind,offset); hnm =mask & shift(mask,offset); % hnm "has neighbor mask" is one for pixels that have the neighbor % defined by offset, zero for pixels that do not have such a neighbor ni{k}=ind(hnm); nj{k}=nind(hnm); end i=[ni{1};ni{2};ni{3};ni{4}]; j=[nj{1};nj{2};nj{3};nj{4}]; A=sparse(i,j,ones(size(i)));
github
aamiranis/sampling_theory-master
sgwt_view_design.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_view_design.m
2,044
utf_8
247bd54a5a76a94390e1b9c63c10f32b
% sgwt_view_design : display filter design in spectral domain % % function sgwt_view_design(g,t,arange) % % This function graphs the input scaling function and wavelet % kernels, indicates the wavelet scales by legend, and also shows % the sum of squares G and corresponding frame bounds for the transform. % % Inputs : % g - cell array of function handles for scaling function and % wavelet kernels % t - array of wavelet scales corresponding to wavelet kernels in g % arange - approximation range % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function sgwt_view_design(g,t,arange) x=linspace(arange(1),arange(2),1e3); clf hold on J=numel(g)-1; co=get(gca,'ColorOrder'); co=repmat(co,[J,1]); G=0*x; for n=0:J plot(x,g{1+n}(x),'Color',co(1+n,:)); G=G+g{1+n}(x).^2; end plot(x,G,'k'); [A,B]=sgwt_framebounds(g,arange(1),arange(2)); hline(A,'m:'); hline(B,'g:'); leglabels{1}='h'; for j=1:J if ~isempty(t) leglabels{1+j}=sprintf('t=%.2f',t(j)); else leglabels{1+j}=''; end end leglabels{J+2}='G'; leglabels{J+3}='A'; leglabels{J+4}='B'; %set(gca,'Ytick',0:3); legend(leglabels) title(['Scaling function kernel h(x), Wavelet kernels g(t_j x), Sum ' ... 'of Squares G, and Frame Bounds']); function hline(y,varargin) xl=xlim; plot(xl,y*[1 1],varargin{:});
github
aamiranis/sampling_theory-master
sgwt_randmat.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_randmat.m
1,167
utf_8
11ba319fb1710fe43c0b282b8f4fbd31
% sgwt_randmat : Compute random (Erdos-Renyi model) graph % % function A=sgwt_randmat(N,thresh) % % Inputs : % N - number of vertices % thresh - probability of connection of each edge % % Outputs : % A - adjacency matrix % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function [A]=sgwt_randmat(N,thresh) assert(thresh<=1 && thresh>=0); A=rand(N)>1-thresh; B=triu(A); A=B+B'; for i=1:size(A,1) A(i,i)=0; end A=sparse(A);
github
aamiranis/sampling_theory-master
sgwt_rough_lmax.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_rough_lmax.m
1,675
utf_8
e86284557ee6b70d9b5bc8538c8677d6
% sgwt_rough_lmax : Rough upper bound on maximum eigenvalue of L % % function lmax=sgwt_rough_lmax(L) % % Runs Arnoldi algorithm with a large tolerance, then increases % calculated maximum eigenvalue by 1 percent. For much of the SGWT % machinery, we need to approximate the wavelet kernels on an % interval that contains the spectrum of L. The only cost of using % a larger interval is that the polynomial approximation over the % larger interval may be a slightly worse approxmation on the % actual spectrum. As this is a very mild effect, it is not likely % necessary to obtain very tight bonds on the spectrum of L % % Inputs : % L - input graph Laplacian % % Outputs : % lmax - estimated upper bound on maximum eigenvalue of L % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function lmax=sgwt_rough_lmax(L) opts=struct('tol',5e-3,'p',10,'disp',0); lmax=eigs(L,1,'lm',opts); lmax=lmax*1.01; % just increase by 1 percent to be robust to error
github
aamiranis/sampling_theory-master
sgwt_kernel_meyer.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_kernel_meyer.m
1,224
utf_8
5537c2610259b92be34a5fea5be86ac8
% sgwt_kernel_meyer : evaluates meyer wavelet kernel and scaling function % function r=sgwt_kernel_meyer(x,kerneltype) % % Inputs % x : array of independent variable values % kerneltype : string, either 'sf' or 'wavelet' % % Ouputs % r : array of function values, same size as x. % % meyer wavelet kernel : supported on [2/3,8/3] % meyer scaling function kernel : supported on [0,4/3] % % Use of this kernel for SGWT proposed by Nora Leonardi and Dimitri Van De Ville, % "Wavelet Frames on Graphs Defined by fMRI Functional Connectivity" % International Symposium on Biomedical Imaging, 2011 function r=sgwt_kernel_meyer(x,kerneltype) l1=2/3; l2=4/3;%2*l1; l3=8/3;%4*l1; v=@(x) x.^4.*(35-84*x+70*x.^2-20*x.^3) ; r1ind=find(x>=0 & x<l1); r2ind=find(x>=l1 & x<l2); r3ind=find(x>=l2 & x<l3); % as we initialize r with zero, computed function will implicitly be zero for % all x not in one of the three regions defined above r=zeros(size(x)); switch kerneltype case 'sf' r(r1ind)=1; r(r2ind)=cos((pi/2)*v(abs(x(r2ind))/l1-1)); case 'wavelet' r(r2ind)=sin((pi/2)*v(abs(x(r2ind))/l1-1)); r(r3ind)=cos((pi/2)*v(abs(x(r3ind))/l2-1)); otherwise error(sprintf('unknown kernel type %s',kerneltype)); end
github
aamiranis/sampling_theory-master
sgwt_cheby_eval.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_cheby_eval.m
1,740
utf_8
351350401b5c3068e214d45848ee0f76
% sgwt_cheby_eval : Evaluate shifted Chebyshev polynomial on given domain % % function r=sgwt_cheby_eval(x,c,arange) % % Compute Chebyshev polynomial of laplacian applied to input. % This is primarily for visualization % % Inputs: % x - input values to evaluate polynomial on % c - Chebyshev coefficients (c(1+j) is jth coefficient) % arange - interval of approximation. Note that x need not be inside % arange, but the polynomial will no longer be near the % approximated function outside of arange. % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function r=sgwt_cheby_eval(x,c,arange) % By setting the operator L to mean (pointwise) multiplication by x, % and f to be vector of ones, p(L)f will contain p(x) at each % point. This lets us use sgwt_cheby_op to evaluate the Chebyshev polynomials. L=spdiags(x(:),0,speye(numel(x))); f=ones(size(x(:))); r=sgwt_cheby_op(f,L,c,arange); if iscell(r) for k=1:numel(r) r{k}=reshape(r{k},size(x)); end else r=reshape(r,size(x)); end
github
aamiranis/sampling_theory-master
sgwt_cheby_op.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_cheby_op.m
2,505
utf_8
5183cc2390cb62eeed472b015abc0fd2
% sgwt_cheby_op : Chebyshev polynomial of Laplacian applied to vector % % function r=sgwt_cheby_op(f,L,c,arange) % % Compute (possibly multiple) polynomials of laplacian (in Chebyshev % basis) applied to input. % % Coefficients for multiple polynomials may be passed as a cell array. This is % equivalent to setting % r{1}=sgwt_cheby_op(f,L,c{1},arange); % r{2}=sgwt_cheby_op(f,L,c{2},arange); % ... % % but is more efficient as the Chebyshev polynomials of L applied % to f can be computed once and shared. % % Inputs: % f- input vector % L - graph laplacian (should be sparse) % c - Chebyshev coefficients. If c is a plain array, then they are % coefficients for a single polynomial. If c is a cell array, % then it contains coefficients for multiple polynomials, such % that c{j}(1+k) is k'th Chebyshev coefficient the j'th polynomial. % arange - interval of approximation % % Outputs: % r - result. If c is cell array, r will be cell array of vectors % size of f. If c is a plain array, r will be a vector the size % of f. % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function r=sgwt_cheby_op(f,L,c,arange) if ~iscell(c) r=sgwt_cheby_op(f,L,{c},arange); r=r{1}; return; end Nscales=numel(c); M=zeros(size(Nscales)); for j=1:Nscales M(j)=numel(c{j}); end assert(all(M>=2)); maxM=max(M); %Twf_new = T_j(L) f %Twf_cur T_{j-1}(L) f %TWf_old T_{j-2}(L) f a1=(arange(2)-arange(1))/2; a2=(arange(2)+arange(1))/2; Twf_old=f; %j=0; Twf_cur=(L*f-a2*f)/a1; % j=1; for j=1:Nscales r{j}=.5*c{j}(1)*Twf_old + c{j}(2)*Twf_cur; end for k=2:maxM Twf_new = (2/a1)*(L*Twf_cur-a2*Twf_cur)-Twf_old; for j=1:Nscales if 1+k<=M(j) r{j}=r{j}+c{j}(k+1)*Twf_new; end end Twf_old=Twf_cur; Twf_cur=Twf_new; end
github
aamiranis/sampling_theory-master
sgwt_inverse.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_inverse.m
1,944
utf_8
f162cbfdf8957b52d971032bbf6d8e5c
% sgwt_inverse : Compute inverse sgw transform, via conjugate gradients % % function r=sgwt_inverse(y,L,c,arange) % % Inputs: % y - sgwt coefficients % L - laplacian % c - cell array of Chebyshev coefficients defining transform % arange - spectral approximation range % % Selectable Control Parameters % tol - tolerance for conjugate gradients (default 1e-6) % % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function r=sgwt_inverse(y,L,c,arange,varargin) control_params={'tol',1e-6}; argselectAssign(control_params); argselectCheck(control_params,varargin); argselectAssign(varargin); assert(iscell(c)); N=size(L,1); % first compute adj = W^*y ( sort of slowly ) fprintf('computing adjoint\n'); adj=sgwt_adjoint(y,L,c,arange); % W^* W % compute P(x) = p(x)^2 fprintf('computing cheby coeff for P=p^2\n'); for j=1:numel(c) M(j)=numel(c{j}); end maxM=max(M); % dkh : code below could remove unnecessary use of cell arrays. d{1}=zeros(1,1+2*(maxM-1)); for j=1:numel(c) cpad{j}=zeros(maxM,1); cpad{j}(1:M(j))=c{j}; d{1}=d{1}+sgwt_cheby_square(cpad{j}); end wstarw = @(x) sgwt_cheby_op(x,L,d{1},arange); %% conjugate gradients fprintf('computing inverse by conjugate gradients\n'); r=pcg(wstarw,adj,tol);
github
aamiranis/sampling_theory-master
sgwt_kernel_simple_tf.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_kernel_simple_tf.m
941
utf_8
b1e5ddf012d9da6e0f1dc36cb52e473c
% sgwt_kernel_simple_tf : evaluates "simple" tight-frame kernel % % this is similar to meyer kernel, but simpler % % function is essentially sin^2(x) in ascending part, % essentially cos^2 in descending part. % % function r= sgwt_kernel_simple_tf(x,kerneltype) % % Inputs % x : array of independent variable values % kerneltype : string, either 'sf' or 'wavelet' % % Ouputs % r : array of function values, same size as x. % % simple tf wavelet kernel : supported on [1/4,1] % simple tf scaling function kernel : supported on [0,1/2] % function r= sgwt_kernel_simple_tf(x,kerneltype) % h : [0,1]->[0,1] must satisfy h(0)=0, h(1)=1 . h=@(x) sin(pi*x/2).^2; r1ind=find(x>=0 & x<0.25); r2ind=find(x>=.25 & x<0.5); r3ind=find(x>=.5 & x<1); r=zeros(size(x)); switch kerneltype case 'sf' r(r1ind)=1; r(r2ind)=sqrt(1-h(4*x(r2ind)-1).^2); case 'wavelet' r(r2ind)=h(4*(x(r2ind)-1/4)); r(r3ind)=sqrt(1-h(2*x(r3ind)-1).^2); end
github
aamiranis/sampling_theory-master
sgwt_check_connected.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_check_connected.m
1,099
utf_8
f1f8b67da83442e06b1d3e495595fb2c
% sgwt_check_connected : Check connectedness of graph % % function r=sgwt_check_connected(A) % % returns 1 if graph is connected, 0 otherwise % Uses boost graph library breadth first search % % Inputs : % A - adjacency matrix % % Outputs : % r - result % % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function r=sgwt_check_connected(A) d=bfs(A,1); r=~any(d==-1);
github
aamiranis/sampling_theory-master
sgwt_framebounds.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_framebounds.m
1,434
utf_8
9d7475831d87b18cd390d84dd8e5317e
% sgwt_framebounds : Compute approximate frame bounds for given sgw transform % % function [A,B,sg2,x]=sgwt_framebounds(g,lmin,lmax) % % Inputs : % g - function handles computing sgwt scaling function and wavelet % kernels % lmin,lmax - minimum nonzero, maximum eigenvalue % % Outputs : % A , B - frame bounds % sg2 - array containing sum of g(s_i*x)^2 (for visualization) % x - x values corresponding to sg2 % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function [A,B,sg2,x]=sgwt_framebounds(g,lmin,lmax) N=1e4; % number of points for line search x=linspace(lmin,lmax,N); Nscales=numel(g); sg2=zeros(size(x)); for ks=1:Nscales sg2=sg2+(g{ks}(x)).^2; end A=min(sg2); B=max(sg2);
github
aamiranis/sampling_theory-master
sgwt_delta.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_delta.m
1,086
utf_8
35b91034385c7a5ad54d4c636df108d8
% sgwt_delta : Return vector with one nonzero entry equal to 1. % % function r=sgwt_delta(N,j) % % Returns length N vector with r(j)=1, all others zero % % Inputs : % N - length of vector % j - position of "delta" impulse % % Outputs: % r - returned vector % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function r=sgwt_delta(N,j) r=zeros(N,1); r(j)=1;
github
aamiranis/sampling_theory-master
sgwt_laplacian.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_laplacian.m
2,419
utf_8
c69f646e26bdc6127f0acea3a9ea5778
% sgwt_laplacian : Compute graph laplacian from connectivity matrix % % function L = sgwt_laplacian(A,varargin) % % Connectivity matrix A must be symmetric. A may have arbitrary % non-negative values, in which case the graph is a weighted % graph. The weighted graph laplacian follows the definition in % "Spectral Graph Theory" by Fan R. K. Chung % % Inputs : % A - adjacency matrix % Selectable Input parameters : % 'opt' - may be 'raw' or 'normalized' (default raw) to select % un-normalized or normalized laplacian % % Outputs : % L - graph Laplacian % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function L = sgwt_laplacian(A,varargin) control_params={'opt','raw'}; % or normalized argselectAssign(control_params); argselectCheck(control_params,varargin); argselectAssign(varargin); N=size(A,1); if N~=size(A,2) error('A must be square'); end degrees=vec(full(sum(A))); % to deal with loops, must extract diagonal part of A diagw=diag(A); % w will consist of non-diagonal entries only [ni2,nj2,w2]=find(A); ndind=find(ni2~=nj2); % as assured here ni=ni2(ndind); nj=nj2(ndind); w=w2(ndind); di=vec(1:N); % diagonal indices switch opt case 'raw' % non-normalized laplacian L=D-A L=sparse([ni;di],[nj;di],[-w;degrees-diagw],N,N); case 'normalized' % normalized laplacian D^(-1/2)*(D-A)*D^(-1/2) % diagonal entries dL=(1-diagw./degrees); % will produce NaN for degrees==0 locations dL(degrees==0)=0;% which will be fixed here % nondiagonal entries ndL=-w./vec( sqrt(degrees(ni).*degrees(nj)) ); L=sparse([ni;di],[nj;di],[ndL;dL],N,N); otherwise error('unknown option'); end
github
aamiranis/sampling_theory-master
sgwt_filter_design.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_filter_design.m
3,113
utf_8
1fe642bdc562bf76e4ef0d65828d3be3
% sgwt_filter_design : Return list of scaled wavelet kernels and derivatives % % g{1} is scaling function kernel, % g{2} ... g{Nscales+1} are wavelet kernels % % function [g,t]=sgwt_filter_design(lmax,Nscales,varargin) % % Inputs : % lmax - upper bound on spectrum % Nscales - number of wavelet scales % % selectable parameters : % designtype % lpfactor - default 20. lmin=lmax/lpfactor will be used to determine % scales, then scaling function kernel will be created to % fill the lowpass gap. % % Outputs : % g - wavelet and scaling function kernel function handles % t - values of scale parameters used for wavelet kernels % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function [g,t]=sgwt_filter_design(lmax,Nscales,varargin) control_params={'designtype','abspline3','lpfactor',20,... 'a',2,... 'b',2,... 't1',1,... 't2',2,... }; argselectAssign(control_params); argselectCheck(control_params,varargin); argselectAssign(varargin); switch designtype case 'abspline3' lmin=lmax/lpfactor; t=sgwt_setscales(lmin,lmax,Nscales); gl = @(x) exp(-x.^4); glp = @(x) -4*x.^3 .*exp(-x.^4); gb= @(x) sgwt_kernel_abspline3(x,a,b,t1,t2); for j=1:Nscales g{j+1}=@(x) gb(t(j)*x); end % find maximum of g's ... % I could get this analytically as it is a cubic spline, but % this also works. f=@(x) -gb(x); xstar=fminbnd(f,1,2); gamma_l=-f(xstar); lminfac=.6*lmin; g{1}=@(x) gamma_l*gl(x/lminfac); case 'mexican_hat' lmin=lmax/lpfactor; t=sgwt_setscales(lmin,lmax,Nscales); gb=@(x) x.*exp(-x); gl = @(x) exp(-x.^4); for j=1:Nscales g{j+1}=@(x) gb(t(j)*x); end lminfac=.4*lmin; g{1}=@(x) 1.2*exp(-1)*gl(x/lminfac); case 'meyer' t=(4/(3*lmax)) * 2.^(Nscales-1:-1:0); g{1}= @(x) sgwt_kernel_meyer(t(1)*x,'sf'); for j=1:Nscales g{j+1}= @(x) sgwt_kernel_meyer(t(j)*x,'wavelet'); end case 'simple_tf' t=(1/(2*lmax)) * 2.^(Nscales-1:-1:0); g{1}= @(x) sgwt_kernel_simple_tf(t(1)*x,'sf'); for j=1:Nscales g{j+1}= @(x) sgwt_kernel_simple_tf(t(j)*x,'wavelet'); end otherwise error('Unknown design type'); end
github
aamiranis/sampling_theory-master
sgwt_setscales.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_setscales.m
1,879
utf_8
f3a9d5e3ffe5388b2b3f13f7e9ed799f
% sgwt_setscales : Compute a set of wavelet scales adapted to spectrum bounds % % function s=sgwt_setscales(lmin,lmax,Nscales) % % returns a (possibly good) set of wavelet scales given minimum nonzero and % maximum eigenvalues of laplacian % % returns scales logarithmicaly spaced between minimum and maximum % "effective" scales : i.e. scales below minumum or above maximum % will yield the same shape wavelet (due to homogoneity of sgwt kernel : % currently assuming sgwt kernel g given as abspline with t1=1, t2=2) % % Inputs : % lmin,lmax - minimum nonzero and maximum eigenvalue of % Laplacian. Note that in design of transform with % scaling function, lmin may be taken just as a fixed % fraction of lmax, and may not actually be the % smallest nonzero eigenvalue % Nscales - # of wavelet scales % % Outputs : % s - wavelet scales % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function s=sgwt_setscales(lmin,lmax,Nscales) t1=1; t2=2; smin=t1/lmax; smax=t2/lmin; % scales should be decreasing ... higher j should give larger s s=exp(linspace(log(smax),log(smin),Nscales));
github
aamiranis/sampling_theory-master
sgwt_ftsd.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/sgwt_ftsd.m
1,488
utf_8
c93b3db59098b389b8e86258845f0900
% sgwt_ftsd : Compute forward transform in spectral domain % % function r=sgwt_ftsd(f,g,t,L) % % Compute forward transform by explicitly computing eigenvectors and % eigenvalues of graph laplacian % % Uses persistent variables to store eigenvectors, so decomposition % will be computed only on first call % % Inputs: % f - input data % g - sgw kernel % t - desired wavelet scale % L - graph laplacian % % Outputs: % r - output wavelet coefficients % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function r=sgwt_ftsd(f,g,t,L) persistent V D Lold if (isempty(V) || any(vec(L~=Lold))) fprintf('Diagonalizing %g x %g L (could take some time ...)\n',size(L,1),size(L,2)); [V,D]=eig(full(L)); Lold=L; end lambda=diag(D); fhat=V'*f; r=V*(fhat.*g(t*lambda));
github
aamiranis/sampling_theory-master
sgwt_demo3.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/demo/sgwt_demo3.m
4,022
utf_8
172a5b137553c10796f84fb7239e2804
% sgwt_demo3 : Image decomposition with SGWT wavelets based on local adjacency. % % This demo builds the SGWT transform on a graph representing % adjacency on a pixel mesh with 4-nearest neighbor connectivity. % This demonstrates inverse on problem with large dimension. % % The demo loads an image file and decomposes the image with the SGWT, % showing the coefficients as images at each scale. The demo does not show % the individual wavelets (this could be done by replacing the input % image by a "delta image" with a single unit nonzero pixel) . % % The inverse is then computed, from the original coefficients as well as % from a modified set of coefficients where only coefficients at one % scale are preserved. This shows that the SGWT can generate a % multiresolution decomposition for images. We don't claim that this % particular local-adjacency based transform is better for image % processing than other available wavelet image decompositions, but it % demonstrates the flexibility of the SGWT. % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function sgwt_demo3 global SGWT_ROOT close all; fprintf('Welcome to SGWT demo #3\n'); % load image imname = [fileparts(mfilename('fullpath')),filesep,'paques_attack.png']; fprintf('loading image %s\n',imname); im = double( imread(imname) ); % build mesh adjacency graph fprintf('Building mesh adjacency graph\n'); A=sgwt_meshmat(size(im)); % transform fprintf('Calculating graph Laplacian\n'); L=sgwt_laplacian(A); fprintf('Measuring largest eigenvalue, lmax = '); lmax=sgwt_rough_lmax(L); arange=[0,lmax]; fprintf('%g\n',lmax); Nscales=5; fprintf('Designing transform in spectral domain\n'); [g,t]=sgwt_filter_design(lmax,Nscales); m=25; % order of polynomial approximation fprintf('Computing Chebyshev polynomials of order %g for fast transform \n',m); for k=1:numel(g) c{k}=sgwt_cheby_coeff(g{k},m,m+1,arange); end fprintf('Computing forward transform\n'); wpall=sgwt_cheby_op(im(:),L,c,arange); % invert with all subbands fprintf('Computing inverse transform with all coefficients\n'); imr1=sgwt_inverse(wpall,L,c,arange); imr1=reshape(imr1,size(im)); ks=3; % scale at which to keep coefficients, set all others to zero. fprintf('\nsetting all coefficients to zero except wavelet scale %g\n',ks-1); % invert with only one scale for k=1:numel(wpall) wpall2{k}=zeros(size(wpall{k})); end wpall2{ks}=wpall{ks}; fprintf('Computing inverse transform with coefficients from wavelet scale %g only\n',ks-1); imr2=sgwt_inverse(wpall2,L,c,arange); imr2=reshape(imr2,size(im)); %% display results figure(1) set(gcf,'position',[ 5 730 350 350]); sgwt_show_im(im) title('original image'); set(gcf,'menubar','none') figure(2) set(gcf,'position',[365 730 350 350]); sgwt_show_im(imr1) title('reconstuction from all coefficients'); set(gcf,'menubar','none') figure(3) set(gcf,'position',[725 730 350 350]); sgwt_show_im(imr2); title(sprintf('reconstruction only from wavelets at scale %g',ks-1)); set(gcf,'menubar','none') figure(4) set(gcf,'position',[0 0 1150 700]); set(gcf,'menubar','none') for k=1:Nscales+1 subplot(2,3,k); sgwt_show_im(reshape(wpall{k},size(im))); if k==1 title('Scaling function coefficients'); else title(sprintf('Wavelet coefficients at scale %g',k-1)); end end
github
aamiranis/sampling_theory-master
sgwt_demo2.m
.m
sampling_theory-master/reconstruction_methods/pocs_bandlimited/sgwt_toolbox/demo/sgwt_demo2.m
6,384
utf_8
7bab07e6514e903305e5afaf1ba24716
% sgwt_demo2 : Allows exploring wavelet scale and approximation accuracy % % This demo builds the SGWT for the minnesota traffic graph, a graph % representing the connectivity of the minnesota highway system. One center % vertex is chosen, and then the exact (naive forward transform) and the % approximate (via chebyshev polynomial approximation) wavelet transforms % are computed for a particular value of the wavelet scale t. The relative % error of the exact and approximate wavelets is computed. The user may % then adjust the value of t, the degree m of the chebyshev polynomial % approximation, and the center vertex in order to explore their effects. % This file is part of the SGWT toolbox (Spectral Graph Wavelet Transform toolbox) % Copyright (C) 2010, David K. Hammond. % % The SGWT toolbox 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 3 of the License, or % (at your option) any later version. % % The SGWT toolbox 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 the SGWT toolbox. If not, see <http://www.gnu.org/licenses/>. function sgwt_demo2 close all fprintf('Welcome to SGWT demo #2\n'); % touch variables to be shared among sub-functions gb=[]; c=[]; % create UI elements fh=figure('Visible','on','Name','demo 2 ui','Position',[425,920,400,150]); uipanelh=uipanel('Parent',fh,'Title','','Units','pixels','BorderType','none'); tsliderh=uicontrol(uipanelh,'style','slider','max',50,'min',0,'value',1,... 'sliderstep',[.005 .1],'position',[25,10,300,20],... 'callback',{@tslider_callback}); msliderh=uicontrol(uipanelh,'style','slider','max',100,'min',1,'value',20,... 'sliderstep',[.001 .1],'position',[25,60,300,20],... 'callback',{@mslider_callback}); jbuttonh=uicontrol(uipanelh,'style','pushbutton','position',[50,110,150,20],... 'string','Select center vertex','callback',{@jbutton_callback}); ttexth=uicontrol(uipanelh,'style','text','string','','position',[325,10,100,20]); mtexth=uicontrol(uipanelh,'style','text','string','','position',[325,60,100,20]); jtexth=uicontrol(uipanelh,'style','text','string','','position',[325,100,100,20]); uicontrol(uipanelh,'style','text','string',... 'Chebyshev polynomial order (m)','position',... [60,80,200,20]); uicontrol(uipanelh,'style','text','string',... 'Wavelet scale (t)','position',... [60,30,200,20]); %% Load graph and compute Laplacian fprintf('Loading minnesota traffic graph\n'); Q=load('minnesota.mat'); xy=Q.xy; A=Q.A; N=size(A,1); x=xy(:,1); y=xy(:,2); fprintf('Computing graph laplacian\n') [ki,kj]=find(A); L=sgwt_laplacian(A); fprintf('Measuring largest eigenvalue, lmax = '); lmax=sgwt_rough_lmax(L); fprintf('%g\n',lmax); arange=[0 lmax]; msize=100; % initial values t=3; % wavelet scale m=20; % chebyshev polynomial order, for approximation jcenter=550; fprintf('\n'); update_uitext; update_graphfig update_kernel update_waveletfigs function update_graphfig figure(2) set(gcf,'renderer','zbuffer'); fprintf('Displaying traffic graph\n'); set(gcf,'position',[0,600,400,400]); %clf('reset'); hold on scatter(x,y,msize,[.5 .5 .5],'.'); plot([x(ki)';x(kj)'],[y(ki)';y(kj)'],'k'); set(gca,'Xtick',[]); set(gca,'Ytick',[]); axis equal axis off scatter(x(jcenter),y(jcenter),msize,'r.'); drawnow end function update_kernel % select wavelet kernel t1=1; t2=2; a=2; b=2; tmin=t1/lmax; % scales t<tmin will show same wavelet shape as t=tmin, as % wavelet kernel g is monomial in interval [0,1) set(tsliderh,'min',tmin); gb= @(x) sgwt_kernel_abspline3(x,a,b,t1,t2); g=@(x) gb(t*x); % polynomial approximation for k=1:numel(g) c=sgwt_cheby_coeff(g,m,m+1,arange); end lambda=linspace(0,lmax,1e3); figure(3) set(gcf,'position',[425,580,600,250]) plot(lambda,g(lambda),lambda,sgwt_cheby_eval(lambda,c,arange)); legend('Exact Wavelet kernel','Chebyshev polynomial approximation'); end function update_waveletfigs fprintf('\nReomputing wavelets with t=%g, m=%g\n',t,m); d=sgwt_delta(N,jcenter); fprintf('Computing wavelet by naive forward transform\n'); figure(4) set(gcf,'position',[0,100,400,400]) wp_e=sgwt_ftsd(d,gb,t,L); show_wavelet(wp_e,x,y); % show wavelet (naive) title('exact wavelet (naive forward transform)'); fprintf('Computing wavelet by Chebyshev approximation\n'); figure(5) set(gcf,'position',[425,100,400,400]) % show wavelet (chebyshev) wp_c=sgwt_cheby_op(d,L,c,arange); show_wavelet(wp_c,x,y); title('approximate wavelet (transform via chebyshev approximation)'); relerr=norm(wp_e-wp_c)/norm(wp_e); fprintf('Relative error between exact and approximate wavelet %g\n',relerr) end function show_wavelet(wp,x,y) [Fs,s_ind]=sort(abs(wp),'descend'); scatter(x(s_ind),y(s_ind),msize,wp(s_ind),'.'); caxis([-1 1]*max(abs(wp))); hcb=colorbar('location','north'); set(gca,'Xtick',[]); set(gca,'Ytick',[]); cxt=get(hcb,'Xtick'); cxt=[cxt(1),0,cxt(end)]; set(hcb,'Xtick',cxt); cpos=get(hcb,'Position'); cpos(4)=.02; % make colorbar thinner set(hcb,'Position',cpos); axis equal axis off end function update_uitext set(ttexth,'string',sprintf('t=%0.3f',t)); set(mtexth,'string',sprintf('m=%g',m)); set(jtexth,'string',sprintf('j=%g',jcenter)); end function tslider_callback(source,eventdata) t=get(tsliderh,'value'); update_uitext; update_kernel; update_waveletfigs; end function mslider_callback(source,eventdata) newm=get(msliderh,'value'); if newm<m m=floor(newm); else m=ceil(newm); end set(msliderh,'value',m); update_uitext; update_kernel; update_waveletfigs; end function jbutton_callback(source,eventdata) figure(2) fprintf('Select new center vertex\n'); [xp,yp]=ginput(1); oldjcenter=jcenter; jcenter=argmin((xp-x).^2+(yp-y).^2); scatter(x(jcenter),y(jcenter),msize,'r.'); scatter(x(oldjcenter),y(oldjcenter),msize,[.5 .5 .5],'.'); drawnow update_uitext update_waveletfigs end end function i = argmin(x) i=min(find(x==min(x))); end