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
kd383/GPML_SLD-master
priorSmoothBox1.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/prior/priorSmoothBox1.m
1,771
utf_8
4fc9d6491b923568cc0b19a1894509a5
function [lp,dlp] = priorSmoothBox1(a,b,eta,x) % Univariate smoothed box prior distribution with linear decay in the log domain % and infinite support over the whole real axis. % Compute log-likelihood and its derivative or draw a random sample. % The prior distribution is parameterized as: % % p(x) = 1/w*sigmoid(eta*(x-a))*(1-sigmoid(eta*(x-b))), % where w = abs(b-a) and sigmoid(z) = 1/(1+exp(-z)) % % a(1x1) is the lower bound parameter, b(1x1) is the upper bound parameter, % eta(1x1)>0 is the slope parameter and x(1xN) contains query hyperparameters % for prior evaluation. Larger values of eta make the distribution more % box-like. % % The distribution p(x) has mean and variance given by: % mu = (a+b)/2 and s2 = w^2/(1-exp(-2*g))*(1+(pi/g)^2)/12, g = eta*w/2. % % /------------\ % / \ % -------- | | --------> x % a b % % For more help on design of priors, try "help priorDistributions". % % Copyright (c) by Jose Vallet and Hannes Nickisch, 2015-03-27. % % See also PRIORDISTRIBUTIONS.M. if nargin<3, error('a, b and eta parameters need to be provided'), end if b<=a, error('b must be greater than a.'), end if ~(isscalar(a)&&isscalar(b)&&isscalar(eta)) error('a, b and eta parameters need to be scalar values') end if nargin<4 % inverse sampling u = exp((b-a)*eta*rand()); lp = log((u-1)/(exp(-eta*a)-u*exp(-eta*b)))/eta; return end [lpa,dlpa] = logr(eta*(x-a)); [lpb,dlpb] = logr(-eta*(x-b)); lp = lpa + lpb - log(b-a) + log(1-exp((a-b)*eta)); dlp = eta*(dlpa - dlpb); % r(z) = 1/(1+exp(-z)), log(r(z)) = -log(1+exp(-z)) function [lr,dlr] = logr(z) lr = z; ok = -35<z; lr(ok) = -log(1+exp(-z(ok))); dlr = 1./(1+exp(z));
github
kd383/GPML_SLD-master
infFITC.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/infFITC.m
244
utf_8
5fdeba09c14e9397cb2b684c841f258a
% Wrapper to infGaussLik to remain backwards compatible. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2016-08-25. function varargout = infFITC(varargin) varargout = cell(nargout, 1); [varargout{:}] = infGaussLik(varargin{:});
github
kd383/GPML_SLD-master
logphi.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/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
kd383/GPML_SLD-master
gauher.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/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
kd383/GPML_SLD-master
elsympol.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/elsympol.m
992
utf_8
5cc9210f574e7f44bea2f0619d1637aa
% Evaluate the order R elementary symmetric polynomials using Newton's identity, % the Newton-Girard formulae: http://en.wikipedia.org/wiki/Newton's_identities % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2010-01-10. % speedup contributed by Truong X. Nghiem, 2016-01-20. function E = elsympol(Z,R) sz = size(Z); % evaluate 'power sums' of the individual terms in Z E = zeros([sz(1:2),R+1]); % E(:,:,r+1) yields polynomial r % fast and efficient version of: for r=1:R, P(:,:,r) = sum(Z.^r,3); end Zr = Z; P(:,:,1) = sum(Zr,3); for r=2:R, Zr = Zr.*Z; P(:,:,r) = sum(Zr,3); end 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 E(:,:,r+1) = P(:,:,1).*E(:,:,r)/r; % i=1 is simpler than the rest for i=2:r E(:,:,r+1) = E(:,:,r+1) + P(:,:,i).*E(:,:,r+1-i)*(-1)^(i-1)/r; end end
github
kd383/GPML_SLD-master
minimize.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/minimize.m
11,190
utf_8
58c59070538bcf9d709052c85e4a9c2f
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
kd383/GPML_SLD-master
sq_dist.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/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
kd383/GPML_SLD-master
any2vec.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/any2vec.m
653
utf_8
d703596b446303a8c82e4de32786fad1
% 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 vec2any.m. function v = any2vec(s) v = []; if isnumeric(s) v = s(:); % numeric values are recast to column vector elseif isstruct(s) v = any2vec(struct2cell(orderfields(s)));% alphabetize, conv to cell, recurse elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially v = [v; any2vec(s{i})]; end end % other types are ignored
github
kd383/GPML_SLD-master
glm_invlink_expexp.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/glm_invlink_expexp.m
423
utf_8
56f87c54a6964c850f79e867c5d4b291
% Compute the log intensity for the inverse link function g(f) = exp(-exp(-f)). % Output range: 0 <= g(f) <= 1. % % The function can be used in GLM likelihoods such as likBeta. % % Copyright (c) by Hannes Nickisch, 2016-10-04. 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
kd383/GPML_SLD-master
covGrid.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/covGrid.m
312
utf_8
57193d84d2b7b76d5acaf055348cfa51
% Wrapper to apxGrid to remain backwards compatible. % % Note that covGrid is not a valid covariance function on its own right. % % Copyright (c) by Hannes Nickisch and Andrew Wilson 2016-08-25. function varargout = covGrid(varargin) varargout = cell(nargout, 1); [varargout{:}] = apxGrid(varargin{:});
github
kd383/GPML_SLD-master
glm_invlink_logistic.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/glm_invlink_logistic.m
709
utf_8
5b8da5da4ad55f7e13652c79e9ae2954
% Compute the log intensity for the inverse link function g(f) = log(1+exp(f))). % Output range: 0 <= g(f). % % The function can be used in GLM likelihoods such as likPoisson, likGamma, and % likInvGauss. % % Copyright (c) by Hannes Nickisch, 2016-10-04. 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
kd383/GPML_SLD-master
vec2any.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/vec2any.m
1,016
utf_8
917a9d3bb4112736eac9cbf3730f6f40
% 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 any2vec.m. function [s v] = vec2any(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] = vec2any(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] = vec2any(s{i}, v); end end % other types are not processed
github
kd383/GPML_SLD-master
infFITC_EP.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/infFITC_EP.m
235
utf_8
47597e3d3b6166acd5d61066547317f3
% Wrapper to infEP to remain backwards compatible. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2016-12-14. function varargout = infFITC_EP(varargin) varargout = cell(nargout, 1); [varargout{:}] = infEP(varargin{:});
github
kd383/GPML_SLD-master
vfe_xu_opt.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/vfe_xu_opt.m
3,265
utf_8
2c1a9383671fb35ff92e5c18815df0b0
% Optimize inducing inputs for the VFE approximation (not FITC). % % One can perform a gradient-based optimisation of the inducing inputs xu by % specifying them via hyp.xu rather than through {@apxSparse,cov,xu}. % % An alternative way of optimising xu (in order to overcome local minima) is % to simply compute the expected change in marginal likelihood of a set of % candidate inducing points z and performing replacing the least relevant % inducing input in xu with the most promising candidate from z. Efficient % candidate scoring is only possible for the VFE approximation i.e. we use % opt = struct('s',0.0); and lik = @likGauss; in the following. % % The call % [hyp,nlZ] = vfe_xu_opt(hyp,mean,cov,x,y, z,nswap); % changes the inducing inputs in hyp.xu as to minimise nlZ. At most nswap % swapping operations are performed between hyp.xu and the candidates in z. % At the end the negative marginal likelihood nlZ is the same as obtained by % [post nlZ] = infGaussLik(hyp, mean, cov, lik, x, y, opt) % where opt = struct('s',0.0); and lik = @likGauss. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2017-02-17. % % See also apx.m, infGaussLik.m. function [hyp,nlZ] = vfe_xu_opt(hyp,mean,cov,x,y, z,nswap) nlZmin = inf; u = hyp.xu; cov = cov{2}; for i=1:nswap [nlZ,du,dz] = vfe(hyp,mean,{'apxSparse',cov,u},x,y,z); if nlZ<nlZmin umin = u; nlZmin = nlZ; [dum,iu] = min(du); [dzm,iz] = min(dz); fprintf('%03d) nlZ=%1.4e -> %1.4e\n',i,nlZ,nlZ+dum+dzm) ui = u(iu,:); u(iu,:) = z(iz,:); z(iz,:) = ui; else fprintf('%03d) nlZ=%1.4e ~< %1.4e\n',i,nlZmin,nlZ) nlZ = nlZmin; u = umin; break end end hyp.xu = u; function [nlZ,du,dz] = vfe(hyp,mean,cov,x,y,z) [n, D] = size(x); % dimensions m = feval(mean{:}, hyp.mean, x); % evaluate mean vector sn2 = exp(2*hyp.lik); % noise variance of likGauss xu = cov{3}; nu = size(xu,1); % extract inducing points k = @(x,z) feval(cov{2}{:},hyp.cov,x,z); % shortcut for covariance function Kuu = k(xu,xu); Ku = k(xu,x); diagK = k(x,'diag'); % get the building blocks snu2 = 1e-6*(trace(Kuu)/nu); % stabilise by 0.1% of signal std Luu = chol(Kuu+snu2*eye(nu)); % Kuu + snu2*I = Luu'*Luu dgiKuu = sum((Luu\eye(nu)).^2,2); % diag(inv(Kuu)) V = Luu'\Ku; Lu = chol(eye(nu) + V*V'/sn2); % V = inv(Luu')*Ku => V'*V = Q r = y-m; R = Luu\V; B = Lu'\V; alpha = r/sn2 - (B'*(B*r))/(sn2*sn2); t = max(diagK-sum(V.*V,1)',0)/sn2; nlZ = r'*alpha/2 + sum(log(diag(Lu))) + sum(t)/2 + n*log(2*pi*sn2)/2; if nargout>1 q = R/sn2 - (R*B')*B/(sn2*sn2); du = (R*alpha).^2./(dgiKuu-sum(R.*q,2))/2 ... % aKa + log(1-sum(R.*q,2)./dgiKuu)/2 ... % logdet Lui + sum(R.*R,2)./dgiKuu/sn2/2; % dst2 end if nargout>2 Kzu = k(z,xu); Kz = k(x,z); diagKz = k(z,'diag'); % query new cross-terms R = Kzu*R-Kz'; q = R/sn2 - (R*B')*B/(sn2*sn2); c = max(diagKz-sum((Kzu/Luu).^2,2),0); dz = -(R*alpha).^2./(c+sum(R.*q,2))/2 ... + log(1+sum(R.*q,2)./c)/2 - sum(R.*R,2)./c/sn2/2; end
github
kd383/GPML_SLD-master
infFITC_Laplace.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/infFITC_Laplace.m
250
utf_8
4ea7b03dd38fc20a2bcd4eef8f3237b5
% Wrapper to infLaplace to remain backwards compatible. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2016-10-13. function varargout = infFITC_Laplace(varargin) varargout = cell(nargout, 1); [varargout{:}] = infLaplace(varargin{:});
github
kd383/GPML_SLD-master
infExact.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/infExact.m
245
utf_8
b85c546a2f76f0535f4bc5c5cc03e804
% Wrapper to infGaussLik to remain backwards compatible. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2016-08-25. function varargout = infExact(varargin) varargout = cell(nargout, 1); [varargout{:}] = infGaussLik(varargin{:});
github
kd383/GPML_SLD-master
solve_chol.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/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
kd383/GPML_SLD-master
covFITC.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/covFITC.m
385
utf_8
d4456aefc33a8cdf1f555980e65abae9
% Wrapper to apxSparse to remain backwards compatible. % % Note that covFITC is not a valid covariance function on its own right. % % Copyright (c) by Ed Snelson, Carl Edward Rasmussen % and Hannes Nickisch, 2016-08-25. function varargout = covFITC(varargin) varargout = cell(nargout, 1); [varargout{:}] = apxSparse(varargin{:});
github
kd383/GPML_SLD-master
glm_invlink_logit.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/glm_invlink_logit.m
835
utf_8
d5d14b52f5422b6f3497b6cc8a239f4e
% Compute the log intensity for the inverse link function g(f) = 1/(1+exp(-f)). % Output range: 0 <= g(f) <= 1. % % The function can be used in GLM likelihoods such as likBeta. % % Copyright (c) by Hannes Nickisch, 2016-10-04. 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} = min(f-elg,0); % upper bound g by 1 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
kd383/GPML_SLD-master
minimize_lbfgsb_gradfun.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/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
kd383/GPML_SLD-master
glm_invlink_logistic2.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/glm_invlink_logistic2.m
870
utf_8
1fd6d55db008cfb0517988106bc6b3e6
% Compute the log intensity for the inverse link function (twice logistic) % g(f) = h(f*(1+a*h(f))), where is the logistic h(f) = log(1+exp(f))). % Output range: 0 <= g(f). % % The function can be used in GLM likelihoods such as likPoisson, likGamma, and % likInvGauss. % % See Seeger et al., Bayesian Intermittent Demand Forecasting for Large % Inventories, NIPS, 2016. % % Copyright (c) by Hannes Nickisch, 2016-10-04. function [lg,dlg,d2lg,d3lg] = glm_invlink_logistic2(a,f) [lh,dlh,d2lh,d3lh] = glm_invlink_logistic(f); h = exp(lh); ft = f + a*f.*h; dft = 1 + a*h.*(1 + f.*dlh); w = a*h.*(dlh.^2 + d2lh); d2ft = 2*a*h.*dlh + f.*w; d3ft = 3*w + a*f.*h.*(dlh.^3+3*d2lh.*dlh+d3lh); [lgt,dlgt,d2lgt,d3lgt] = glm_invlink_logistic(ft); lg = lgt; dlg = dlgt.*dft; d2lg = d2lgt.*dft.^2 + dlgt.*d2ft; d3lg = d3lgt.*dft.^3 + 3*d2lgt.*dft.*d2ft + dlgt.*d3ft;
github
kd383/GPML_SLD-master
minimize_lbfgsb.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/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
kd383/GPML_SLD-master
minimize_lbfgsb_objfun.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/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
kd383/GPML_SLD-master
logsumexp2.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/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
kd383/GPML_SLD-master
minimize_minfunc.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/minimize_minfunc.m
5,472
utf_8
1f17d182bc7f64339c8eefbd76605d25
function [X, f, i, exitflag, output] = minimize_minfunc(X, f, options, varargin) % Minimize a differentiable multivariate function using minFunc. % (http://www.cs.ubc.ca/~schmidtm/Software/minFunc.html) % To be used with GPML toolbox. % % Usage: [X, f, i, exitflag, output] = ... % minimize_minfunc(X, f, options/length, P1, P2, ... ) % % 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. % options options to be given to minFunc (see minFunc for details); or % 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. Alternatively, the length of the % run (and other options) can be specified by the option structure. % P1, P2 ... parameters are passed to the function f. % % X the returned solution % f function value at the returned solution % i number of iterations (line searches or function evaluations, % depending on the sign of "length") used at termination. % exitflag returns an exit condition % output returns a structure with other information % Supported Output Options % iterations - number of iterations taken % funcCount - number of function evaluations % algorithm - algorithm used % firstorderopt - first-order optimality % message - exit message % trace.funccount - function evaluations after each iteration % trace.fval - function value after each iteration % % 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) 2016 by Truong X. Nghiem, 2016-01-22 me = mfilename; % what is my filename? mydir = which(me); mydir = mydir(1:end-2-numel(me)); % where am I located addpath([mydir,'minfunc'],[mydir,'minfunc/compiled']) % add library % Check the option if isempty(options) % Use default options options = struct(); elseif isnumeric(options) && isscalar(options) if options < 0 options = struct('MaxFunEvals', -options); elseif options > 0 options = struct('MaxIter', options); else error('Run length must be non-zero.'); end end assert(isstruct(options), 'Invalid option / length argument.'); % Convert objective function to function_handle if ischar(f) && ~isempty(f), f = str2func(f); end assert(isa(f, 'function_handle'), 'Invalid objective function.'); % Remember that X and the derivative returned by f may not be vectors, so % we must use rewrap and unwrap. X0 = X; % Save the structure / type of X fw = @(cur_x,varargin) wrapped_f(cur_x, f, X0, varargin{:}); [X, f, exitflag, output] = minFunc(fw, unwrap(X0), options,varargin{:}); i = output.funcCount; % X is a vector, we may need to re-wrap it back to the given structure X = rewrap(X0,X); function [fval, dval] = wrapped_f(cur_x, f, X0, varargin) % This function calls unwrap() and rewrap() before and after % calling f % cur_X is a vector; dval must be a vector tmp = rewrap(X0, cur_x); [fval, dstruct] = feval(f,tmp,varargin{:}); % dstruct can be a structure -> convert it to vector dval = unwrap(dstruct); 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
kd383/GPML_SLD-master
lik_epquad.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/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
kd383/GPML_SLD-master
glm_invlink_exp.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/glm_invlink_exp.m
466
utf_8
d88c5e637e5ed1f9db34a94bb0c3b81e
% Compute the log intensity for the inverse link function g(f) = exp(f). % Output range: 0 <= g(f). % % The function can be used in GLM likelihoods such as likPoisson, likGamma, and % likInvGauss. % % Copyright (c) by Hannes Nickisch, 2016-10-04. 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
kd383/GPML_SLD-master
WolfeLineSearch.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/minfunc/WolfeLineSearch.m
10,590
utf_8
f962bc5ae0a1e9f80202a9aaab106dab
function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(... x,t,d,f,g,gtd,c1,c2,LS_interp,LS_multi,maxLS,progTol,debug,doPlot,saveHessianComp,funObj,varargin) % % Bracketing Line Search to Satisfy Wolfe Conditions % % Inputs: % x: starting location % t: initial step size % d: descent direction % f: function value at starting location % g: gradient at starting location % gtd: directional derivative at starting location % c1: sufficient decrease parameter % c2: curvature parameter % debug: display debugging information % LS_interp: type of interpolation % maxLS: maximum number of iterations % progTol: minimum allowable step length % doPlot: do a graphical display of interpolation % funObj: objective function % varargin: parameters of objective function % % Outputs: % t: step length % f_new: function value at x+t*d % g_new: gradient value at x+t*d % funEvals: number function evaluations performed by line search % H: Hessian at initial guess (only computed if requested % Evaluate the Objective and Gradient at the Initial Step if nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x+t*d,varargin{:}); end funEvals = 1; gtd_new = g_new'*d; % Bracket an Interval containing a point satisfying the % Wolfe criteria LSiter = 0; t_prev = 0; f_prev = f; g_prev = g; gtd_prev = gtd; nrmD = max(abs(d)); done = 0; while LSiter < maxLS %% Bracketing Phase if ~isLegal(f_new) || ~isLegal(g_new) if debug fprintf('Extrapolated into illegal region, switching to Armijo line-search\n'); end t = (t + t_prev)/2; % Do Armijo if nargout == 5 [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(... x,t,d,f,f,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,... funObj,varargin{:}); else [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(... x,t,d,f,f,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,... funObj,varargin{:}); end funEvals = funEvals + armijoFunEvals; return; end if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev) bracket = [t_prev t]; bracketFval = [f_prev f_new]; bracketGval = [g_prev g_new]; break; elseif abs(gtd_new) <= -c2*gtd bracket = t; bracketFval = f_new; bracketGval = g_new; done = 1; break; elseif gtd_new >= 0 bracket = [t_prev t]; bracketFval = [f_prev f_new]; bracketGval = [g_prev g_new]; break; end temp = t_prev; t_prev = t; minStep = t + 0.01*(t-temp); maxStep = t*10; if LS_interp <= 1 if debug fprintf('Extending Braket\n'); end t = maxStep; elseif LS_interp == 2 if debug fprintf('Cubic Extrapolation\n'); end t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep); elseif LS_interp == 3 t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot); end f_prev = f_new; g_prev = g_new; gtd_prev = gtd_new; if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; end if LSiter == maxLS bracket = [0 t]; bracketFval = [f f_new]; bracketGval = [g g_new]; end %% Zoom Phase % We now either have a point satisfying the criteria, or a bracket % surrounding a point satisfying the criteria % Refine the bracket until we find a point satisfying the criteria insufProgress = 0; Tpos = 2; LOposRemoved = 0; while ~done && LSiter < maxLS % Find High and Low Points in bracket [f_LO LOpos] = min(bracketFval); HIpos = -LOpos + 3; % Compute new trial value if LS_interp <= 1 || ~isLegal(bracketFval) || ~isLegal(bracketGval) if debug fprintf('Bisecting\n'); end t = mean(bracket); elseif LS_interp == 2 if debug fprintf('Grad-Cubic Interpolation\n'); end t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot); else % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nonTpos = -Tpos+3; if LOposRemoved == 0 oldLOval = bracket(nonTpos); oldLOFval = bracketFval(nonTpos); oldLOGval = bracketGval(:,nonTpos); end t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot); end % Test that we are making sufficient progress if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1 if debug fprintf('Interpolation close to boundary'); end if insufProgress || t>=max(bracket) || t <= min(bracket) if debug fprintf(', Evaluating at 0.1 away from boundary\n'); end if abs(t-max(bracket)) < abs(t-min(bracket)) t = max(bracket)-0.1*(max(bracket)-min(bracket)); else t = min(bracket)+0.1*(max(bracket)-min(bracket)); end insufProgress = 0; else if debug fprintf('\n'); end insufProgress = 1; end else insufProgress = 0; end % Evaluate new point if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; armijo = f_new < f + c1*t*gtd; if ~armijo || f_new >= f_LO % Armijo condition not satisfied or not lower than lowest % point bracket(HIpos) = t; bracketFval(HIpos) = f_new; bracketGval(:,HIpos) = g_new; Tpos = HIpos; else if abs(gtd_new) <= - c2*gtd % Wolfe conditions satisfied done = 1; elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0 % Old HI becomes new LO bracket(HIpos) = bracket(LOpos); bracketFval(HIpos) = bracketFval(LOpos); bracketGval(:,HIpos) = bracketGval(:,LOpos); if LS_interp == 3 if debug fprintf('LO Pos is being removed!\n'); end LOposRemoved = 1; oldLOval = bracket(LOpos); oldLOFval = bracketFval(LOpos); oldLOGval = bracketGval(:,LOpos); end end % New point becomes new LO bracket(LOpos) = t; bracketFval(LOpos) = f_new; bracketGval(:,LOpos) = g_new; Tpos = LOpos; end if ~done && abs(bracket(1)-bracket(2))*nrmD < progTol if debug fprintf('Line-search bracket has been reduced below progTol\n'); end break; end end %% if LSiter == maxLS if debug fprintf('Line Search Exceeded Maximum Line Search Iterations\n'); end end [f_LO LOpos] = min(bracketFval); t = bracket(LOpos); f_new = bracketFval(LOpos); g_new = bracketGval(:,LOpos); % Evaluate Hessian at new point if nargout == 5 && funEvals > 1 && saveHessianComp [f_new,g_new,H] = funObj(x + t*d,varargin{:}); funEvals = funEvals + 1; end end %% function [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot); alpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep); alpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep); if alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1) if debug fprintf('Cubic Extrapolation\n'); end t = alpha_c; else if debug fprintf('Secant Extrapolation\n'); end t = alpha_s; end end %% function [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot); % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nonTpos = -Tpos+3; gtdT = bracketGval(:,Tpos)'*d; gtdNonT = bracketGval(:,nonTpos)'*d; oldLOgtd = oldLOGval'*d; if bracketFval(Tpos) > oldLOFval alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot); if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval) if debug fprintf('Cubic Interpolation\n'); end t = alpha_c; else if debug fprintf('Mixed Quad/Cubic Interpolation\n'); end t = (alpha_q + alpha_c)/2; end elseif gtdT'*oldLOgtd < 0 alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) sqrt(-1) gtdT],doPlot); if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos)) if debug fprintf('Cubic Interpolation\n'); end t = alpha_c; else if debug fprintf('Quad Interpolation\n'); end t = alpha_s; end elseif abs(gtdT) <= abs(oldLOgtd) alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],... doPlot,min(bracket),max(bracket)); alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],... doPlot,min(bracket),max(bracket)); if alpha_c > min(bracket) && alpha_c < max(bracket) if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos)) if debug fprintf('Bounded Cubic Extrapolation\n'); end t = alpha_c; else if debug fprintf('Bounded Secant Extrapolation\n'); end t = alpha_s; end else if debug fprintf('Bounded Secant Extrapolation\n'); end t = alpha_s; end if bracket(Tpos) > oldLOval t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t); else t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t); end else t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); end end
github
kd383/GPML_SLD-master
minFunc_processInputOptions.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/minfunc/minFunc_processInputOptions.m
4,103
utf_8
8822581c3541eabe5ce7c7927a57c9ab
function [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,optTol,progTol,method,... corrections,c1,c2,LS_init,cgSolve,qnUpdate,cgUpdate,initialHessType,... HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,... Damped,HvFunc,bbType,cycle,... HessianIter,outputFcn,useMex,useNegCurv,precFunc,... LS_type,LS_interp,LS_multi,DerivativeCheck] = ... minFunc_processInputOptions(o) % Constants SD = 0; CSD = 1; BB = 2; CG = 3; PCG = 4; LBFGS = 5; QNEWTON = 6; NEWTON0 = 7; NEWTON = 8; TENSOR = 9; verbose = 1; verboseI= 1; debug = 0; doPlot = 0; method = LBFGS; cgSolve = 0; o = toUpper(o); if isfield(o,'DISPLAY') switch(upper(o.DISPLAY)) case 0 verbose = 0; verboseI = 0; case 'FINAL' verboseI = 0; case 'OFF' verbose = 0; verboseI = 0; case 'NONE' verbose = 0; verboseI = 0; case 'FULL' debug = 1; case 'EXCESSIVE' debug = 1; doPlot = 1; end end DerivativeCheck = 0; if isfield(o,'DERIVATIVECHECK') switch(upper(o.DERIVATIVECHECK)) case 1 DerivativeCheck = 1; case 'ON' DerivativeCheck = 1; end end LS_init = 0; LS_type = 1; LS_interp = 2; LS_multi = 0; Fref = 1; Damped = 0; HessianIter = 1; c2 = 0.9; if isfield(o,'METHOD') m = upper(o.METHOD); switch(m) case 'TENSOR' method = TENSOR; case 'NEWTON' method = NEWTON; case 'MNEWTON' method = NEWTON; HessianIter = 5; case 'PNEWTON0' method = NEWTON0; cgSolve = 1; case 'NEWTON0' method = NEWTON0; case 'QNEWTON' method = QNEWTON; Damped = 1; case 'LBFGS' method = LBFGS; case 'BB' method = BB; LS_type = 0; Fref = 20; case 'PCG' method = PCG; c2 = 0.2; LS_init = 2; case 'SCG' method = CG; c2 = 0.2; LS_init = 4; case 'CG' method = CG; c2 = 0.2; LS_init = 2; case 'CSD' method = CSD; c2 = 0.2; Fref = 10; LS_init = 2; case 'SD' method = SD; LS_init = 2; end end maxFunEvals = getOpt(o,'MAXFUNEVALS',1000); maxIter = getOpt(o,'MAXITER',500); optTol = getOpt(o,'OPTTOL',1e-5); progTol = getOpt(o,'PROGTOL',1e-9); corrections = getOpt(o,'CORRECTIONS',100); corrections = getOpt(o,'CORR',corrections); c1 = getOpt(o,'C1',1e-4); c2 = getOpt(o,'C2',c2); LS_init = getOpt(o,'LS_INIT',LS_init); cgSolve = getOpt(o,'CGSOLVE',cgSolve); qnUpdate = getOpt(o,'QNUPDATE',3); cgUpdate = getOpt(o,'CGUPDATE',2); initialHessType = getOpt(o,'INITIALHESSTYPE',1); HessianModify = getOpt(o,'HESSIANMODIFY',0); Fref = getOpt(o,'FREF',Fref); useComplex = getOpt(o,'USECOMPLEX',0); numDiff = getOpt(o,'NUMDIFF',0); LS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1); Damped = getOpt(o,'DAMPED',Damped); HvFunc = getOpt(o,'HVFUNC',[]); bbType = getOpt(o,'BBTYPE',0); cycle = getOpt(o,'CYCLE',3); HessianIter = getOpt(o,'HESSIANITER',HessianIter); outputFcn = getOpt(o,'OUTPUTFCN',[]); useMex = getOpt(o,'USEMEX',1); useNegCurv = getOpt(o,'USENEGCURV',1); precFunc = getOpt(o,'PRECFUNC',[]); LS_type = getOpt(o,'LS_type',LS_type); LS_interp = getOpt(o,'LS_interp',LS_interp); LS_multi = getOpt(o,'LS_multi',LS_multi); end function [v] = getOpt(options,opt,default) if isfield(options,opt) if ~isempty(getfield(options,opt)) v = getfield(options,opt); else v = default; end else v = default; end end function [o] = toUpper(o) if ~isempty(o) fn = fieldnames(o); for i = 1:length(fn) o = setfield(o,upper(fn{i}),getfield(o,fn{i})); end end end
github
kd383/GPML_SLD-master
mexAll_octave.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/util/minfunc/mex/mexAll_octave.m
529
utf_8
71ee15c617dd2bfc3de849feaeeeadae
% minFunc printf('Compiling minFunc files (octave version)...\n'); ## working around the lack of an -outdir option in octave's mex function mexme(fn) cmd = sprintf("mkoctfile --mex --output ../compiled/%s.mex %s.c", fn, fn) ; [ status output ] = system(cmd) ; if status!=0 error("Executing command %s\n", cmd); else delete(sprintf("%s.o", fn)); printf("%s compiled\n", fn); endif endfunction mexme("mcholC"); mexme("lbfgsC"); mexme("lbfgsAddC"); mexme("lbfgsProdC"); printf("Done.\n")
github
kd383/GPML_SLD-master
meanProd.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/mean/meanProd.m
1,637
utf_8
9ef1cd91495c7edf4cd263a7522833dc
function [m,dm] = meanProd(mean, hyp, x) % meanProd - compose a mean function as the product of other mean functions. % This function doesn't actually compute very much on its own, it merely does % some bookkeeping, and calls other mean functions to do the actual work. % % m(x) = \prod_i m_i(x) % % Copyright (c) by Carl Edward Rasmussen & Hannes Nickisch 2016-04-15. % % See also MEANFUNCTIONS.M. nm = numel(mean); for ii = 1:nm % iterate over mean functions f = mean(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary j(ii) = cellstr(feval(f{:})); % collect number hypers end if nargin<3 % report number of parameters m = char(j(1)); for ii=2:nm, m = [m, '+', char(j(ii))]; end; return end [n,D] = size(x); v = []; % v vector indicates to which mean parameters belong for ii = 1:nm, v = [v repmat(ii, 1, eval(char(j(ii))))]; end m = ones(n,1); mi = cell(nm,1); dmi = cell(nm,1); % allocate space for ii = 1:nm % iteration over factor functions f = mean(ii); if iscell(f{:}), f = f{:}; end % expand cell array if needed [mi{ii},dmi{ii}] = feval(f{:}, hyp(v==ii), x); m = m.*mi{ii}; % accumulate means end dm = @(q) dirder(q,mi,dmi,v,nm); % directional derivative function dhyp = dirder(q,mi,dmi,v,nm) dhyp = zeros(nm,1); for ii = 1:nm qi = q; for jj=1:nm, if ii~=jj, qi = qi .* mi{jj}; end, end % accumulate dhyp(v==ii,1) = dmi{ii}(qi); end
github
kd383/GPML_SLD-master
meanWSPC.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/mean/meanWSPC.m
1,155
utf_8
63678f0a2b4719e468e81085c69dd205
function [m,dm] = meanWSPC(d, hyp, x) % Weighted Sum of Projected Cosines or Random Kitchen Sink features. % % This function represents the feature function of a zero mean GP with % stationary covariance function. See the paper "Sparse spectrum GP regression" % by Lazaro-Gredilla et al., JMLR, 2010 for details. % % m(x) = sqrt(2/d) sum_j=1..d a_j * cos(w_j'*x + b_j) % % The hyperparameter is: % hyp = [w_1; b_1; a_1; ..; w_d; b_d; a_d] % % Copyright (c) by William Herlands and Hannes Nickisch, 2016-04-15. % % See also MEANFUNCTIONS.M. if nargin<3, m = sprintf('(D+2)*%d',d); return; end % report number of hypers [n,D] = size(x); if any(length(hyp)~=eval(sprintf('(D+2)*%d',d))) error('Incorrect number of hyperparameters for meanRKS.') end hyp = reshape(hyp,D+2,d); w = hyp(1:D,:); b = hyp(D+1,:); a = hyp(D+2,:)'; % separate hyps into w, b, a r = bsxfun(@plus,x*w,b); cr = cos(r); m = sqrt(2/d)*cr*a; % mean dm = @(q) dirder(q,x,a,r,cr,d); % directional derivative function dhyp = dirder(q,x,a,r,cr,d) msr = -sin(r); dhyp = [x'*(msr.*(q*a')); (q'*msr).*a'; q'*cr]; dhyp = sqrt(2/d)*dhyp(:);
github
kd383/GPML_SLD-master
meanDiscrete.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/mean/meanDiscrete.m
938
utf_8
8cd9e4ccebb561316bcac3893f21bd4b
function [m,dm] = meanDiscrete(s, hyp, x) % Mean function for discrete inputs x. Given a function defined on the % integers 1,2,3,..,s, the mean function is parametrized as: % % m(x) = mu_x, % % where mu is a fixed vector of length s. % % This implementation assumes that the inputs x are given as integers % between 1 and s, which simply index the provided vector. % % The hyperparameters are: % % hyp = [ mu_1 % mu_2 % .. % mu_s ] % % Copyright (c) by Roman Garnett and Hannes Nickisch, 2016-04-16. % % See also COVDISCRETE.M, MEANFUNCTIONS.M. if nargin==0, error('s must be specified.'), end % check for dimension if nargin<=2, m = num2str(s); return; end % report number of hyperparameters mu = hyp(:); m = mu(x(:)); % evaluate mean dm = @(q) dirder(q,s,x); function dmdhyp = dirder(q,s,x) dmdhyp = zeros(s,1); for i=1:s, dmdhyp(i) = sum(q(x==i)); end
github
kd383/GPML_SLD-master
meanGPexact.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/mean/meanGPexact.m
2,135
utf_8
ebac92262e0958da06afecabc8e8d265
function [m,dm] = meanGPexact(mean,cov,x,y, hypz,z) % Mean function being the predictive mean of a GP model: % % mu(z) = posterior mean of GP at location z as given by % mu(z) = gp(hyp,@infExact,mean,cov,@likGauss,x,y, z) where % hyp.mean = hyp_mean; hyp.lik = log(sn); hyp.cov = hyp.cov; % % The hyperparameters are: % % hypz = [ hyp_cov % log(sn) % hyp_mean ] % % where hyp_cov are the covariance function hyperparameters, sn is the % noise variance of the Gaussian likelihood and hyp_mean are the mean % function hyperparameters. % % Copyright (c) by Hannes Nickisch, 2016-04-16. % % See also MEANFUNCTIONS.M and MEANGP.M. if nargin<4, error('GP must be specified.'), end % check for dimension if isempty(mean), mean = @meanZero; end % set default and make cell if ~iscell(mean), mean = {mean}; end if isempty(cov), cov = @covSEiso; end if ~iscell(cov), cov = {cov}; end nms = feval(mean{:}); ncs = feval(cov{:}); % number of hyperparameter string if nargin<6, m = [ncs,'+1+',nms]; return, end % report number of hyperparameters [nz,D] = size(z); n = size(x,1); nc = eval(ncs); nm = eval(nms); hyp = vec2any(struct('cov',zeros(nc,1),'lik',0,'mean',zeros(nm,1)),hypz); [mu,dmu] = feval(mean{:},hyp.mean,x); [muz,dmuz] = feval(mean{:},hyp.mean,z); [K,dK] = feval(cov{:}, hyp.cov, x); [kz,dkz] = feval(cov{:}, hyp.cov, x,z); sn2 = exp(2*hyp.lik); % noise variance of likGauss if sn2<1e-6 % very tiny sn2 can lead to numerical trouble L = chol(K+sn2*eye(n)); sl = 1; % Cholesky factor of covariance with noise else L = chol(K/sn2+eye(n)); sl = sn2; % Cholesky factor of B end iKs = @(t) solve_chol(L,t)/sl; % iKs(t) = (K+sn2*eye(n))\t alpha = iKs(y-mu); m = muz+kz'*alpha; % eval posterior mean dm = @(q) dirder(q,alpha,dmu,dmuz,kz,dkz,iKs,dK,sn2); % directional derivative function dmdhyp = dirder(q,alpha,dmu,dmuz,kz,dkz,iKs,dK,sn2) v = iKs(kz*q); dmdhyp = [dkz(alpha*q')-dK(alpha*v'); -2*sn2*v'*alpha; dmuz(q)-dmu(v)];
github
kd383/GPML_SLD-master
meanPoly.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/mean/meanPoly.m
1,144
utf_8
37b5289c7c858a50ffa4834928ade29f
function [m,dm] = meanPoly(d, hyp, x) % meanPoly - compose a mean function as a polynomial. % % The degree d has to be a strictly positive integer. % % m(x) = sum_i=1..D sum_j=1..d a_ij * x_i^j % % The hyperparameter is: % % hyp = [ a_11 % a_21 % .. % a_D1 % a_12 % a_22 % .. % a_Dd] % % This function doesn't actually compute very much on its own, it merely does % some bookkeeping, and calls other mean function to do the actual work. % % Copyright (c) by Hannes Nickisch 2016-04-15. % % See also MEANFUNCTIONS.M. d = max(abs(floor(d)),1); % positive integer degree if nargin<3, m = ['D*',int2str(d)]; return; end % report number of hyperparams [n,D] = size(x); a = reshape(hyp,D,d); m = zeros(n,1); % allocate memory for j=1:d, m = m + (x.^j)*a(:,j); end % evaluate mean dm = @(q) dirder(q,x,a); % directional derivative function dhyp = dirder(q,x,a) [D,d] = size(a); dhyp = zeros(D*d,1); for j=1:d, dhyp((j-1)*D+(1:D)) = (x.^j)'*q(:); end
github
kd383/GPML_SLD-master
meanSum.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/mean/meanSum.m
1,536
utf_8
caf2e4aed8ec16eaca6eecb232e8a3d8
function [m,dm] = meanSum(mean, hyp, x) % meanSum - compose a mean function as the sum of other mean functions. % This function doesn't actually compute very much on its own, it merely does % some bookkeeping, and calls other mean functions to do the actual work. % % m(x) = \sum_i m_i(x) % % Copyright (c) by Carl Edward Rasmussen & Hannes Nickisch 2016-04-15. % % See also MEANFUNCTIONS.M. nm = numel(mean); for ii = 1:nm % iterate over mean functions f = mean(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary j(ii) = cellstr(feval(f{:})); % collect number hypers end if nargin<3 % report number of parameters m = char(j(1)); for ii=2:nm, m = [m, '+', char(j(ii))]; end; return end [n,D] = size(x); v = []; % v vector indicates to which mean parameters belong for ii = 1:nm, v = [v repmat(ii, 1, eval(char(j(ii))))]; end m = zeros(n,1); dmi = cell(nm,1); % allocate space for ii = 1:nm % iteration over summand functions f = mean(ii); if iscell(f{:}), f = f{:}; end % expand cell array if needed [mi,dmi{ii}] = feval(f{:}, hyp(v==ii), x); m = m+mi; % accumulate means end dm = @(q) dirder(q,dmi,v,nm); % directional derivative function dhyp = dirder(q,dmi,v,nm) dhyp = zeros(nm,1); for ii = 1:nm, dhyp(v==ii,1) = dmi{ii}(q); end
github
kd383/GPML_SLD-master
covNNone.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covNNone.m
2,181
utf_8
d3739df4147646dd3127df49ceb631aa
function [K,dK] = covNNone(hyp, x, z) % Neural network covariance function with a single parameter for the distance % measure. The covariance function is parameterized as: % % k(x,z) = sf2 * asin(x'*P*z / sqrt[(1+x'*P*x)*(1+z'*P*z)]) % % where the x and z vectors on the right hand side have an added extra bias % entry with unit value. P is ell^-2 times the unit matrix and sf2 controls the % signal variance. The hyperparameters are: % % hyp = [ log(ell) % log(sqrt(sf2) ] % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-04-23. % % See also COVFUNCTIONS.M. if nargin<2, K = '2'; return; end % report number of parameters if nargin<3, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode ell2 = exp(2*hyp(1)); sf2 = exp(2*hyp(2)); sx = 1 + sum(x.*x,2); if dg % vector kxx A = sx./(sx+ell2); sz = sx; else if xeqz % symmetric matrix Kxx S = 1 + x*x'; sz = sx; A = S./(sqrt(ell2+sx)*sqrt(ell2+sx)'); else % cross covariances Kxz S = 1 + x*z'; sz = 1 + sum(z.*z,2); A = S./(sqrt(ell2+sx)*sqrt(ell2+sz)'); end end K = sf2*asin(A); % covariances if nargout > 1 dK = @(Q) dirder(Q,K,A,sx,sz,ell2,sf2,x,z,dg,xeqz); % dir hyper derivative end function [dhyp,dx] = dirder(Q,K,A,sx,sz,ell2,sf2,x,z,dg,xeqz) n = size(x,1); if dg V = A; else vx = sx./(ell2+sx); if xeqz V = repmat(vx/2,1,n) + repmat(vx'/2,n,1); else vz = sz./(ell2+sz); nz = size(z,1); V = repmat(vx/2,1,nz) + repmat(vz'/2,n,1); end end P = Q./sqrt(1-A.*A); dhyp = [-2*sf2*sum(sum((A-A.*V).*P)); 2*Q(:)'*K(:)]; if nargout > 1 if dg dx = zeros(size(x)); else W = P./(sqrt(ell2+sx)*sqrt(ell2+sz)'); ssx = sqrt(ell2+sx); if xeqz, W = W+W'; z = x; ssz = ssx; else ssz = sqrt(ell2+sz); end dx = sf2*(W*z - bsxfun(@times,x,((W.*A)*ssz)./ssx)); end end
github
kd383/GPML_SLD-master
covWarp.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covWarp.m
1,985
utf_8
edfc0bebca248cfb80e7f7fe6a53ba17
function [K,dK] = covWarp(cov, p, dp, Dp, hyp, x, z) % Apply a covariance function to p(x) rather than x i.e. warp the inputs. % % This function doesn't actually compute very much on its own, it merely does % some bookkeeping, and calls another covariance function to do the actual work. % % The function computes: % k(x,z) = k0(p(x),p(z)) % Example: % k0 = {@covSEiso}; % p = @(x) sum(2*x,2); % dp = @(x) 2*x; % Dp = 1; % k = {@covWarp,p,dp,Dp}; % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-11-14. % % See also COVFUNCTIONS.M, COVMASK.M. nh_string = feval(cov{:}); % number of hyperparameters of the full covariance D = Dp; % make variable available if nargin<6, K = num2str(eval(nh_string)); return, end % number of parameters if nargin<7, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode if numel(p) ==0, p = @(x) x; end % default is identity if numel(dp)==0, dp = @(x) 1; end % default is one if eval(nh_string)~=length(hyp) % check hyperparameters error('number of hyperparameters does not match size of warped data') end px = p(x); if ~dg && ~xeqz, pz = p(z); else pz = z; end if nargout>1 [K,dK] = feval(cov{:}, hyp, px, pz); dK = @(Q) dirder(Q,dK,x,dp); else K = feval(cov{:}, hyp, px, pz); end function [dhyp,dx] = dirder(Q,dK,x,dp) if nargout>1 [dhyp,dx] = dK(Q); Dp = size(dx,2); dpx = dp(x); % size(dx)=[n,Dp] if ndims(dpx)<=2 % apply chain rule dx = bsxfun(@times,dx,dpx); % size(dpx)=[1,1] or [n,1] or [n,D] else dx = sum(bsxfun(@times,reshape(dx,[],1,Dp),dpx),3); % size(dpx)=[n,D,Dp] end % size(dx)=[n,D] else dhyp = dK(Q); end
github
kd383/GPML_SLD-master
covZero.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covZero.m
1,116
utf_8
8e584fb7aaec194e49fd84eb2c8ade2b
function [K,dK] = covZero(hyp, x, z) % Constant (degenerate) covariance function, with zero variance. % The covariance function is specified as: % % k(x,z) = 0 % % hyp = [ ] % % For more help on design of covariance functions, try "help covFunctions". % % Copyright (c) by Hannes Nickisch, 2016-04-17. % % See also COVFUNCTIONS.M. if nargin<2, K = '0'; return; end % report number of parameters if nargin<3, z = []; end % make sure, z exists dg = strcmp(z,'diag'); % determine mode n = size(x,1); if dg % vector kxx K = zeros(n,1); else if isempty(z) % symmetric matrix Kxx K = zeros(n,n); else % cross covariances Kxz K = zeros(n,size(z,1)); end end if nargout > 1 dK = @(Q) dirder(Q,K,x); % directional hyper derivative end function [dhyp,dx] = dirder(Q,K,x) dhyp = zeros(0,1); if nargout > 1, dx = zeros(size(x)); end
github
kd383/GPML_SLD-master
covOne.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covOne.m
1,112
utf_8
ad8b2c66ba87471c2aad1ef1da8b74e2
function [K,dK] = covOne(hyp, x, z) % Constant (degenerate) covariance function, with unit variance. % The covariance function is specified as: % % k(x,z) = 1 % % hyp = [ ] % % For more help on design of covariance functions, try "help covFunctions". % % Copyright (c) by Hannes Nickisch, 2016-04-17. % % See also COVFUNCTIONS.M. if nargin<2, K = '0'; return; end % report number of parameters if nargin<3, z = []; end % make sure, z exists dg = strcmp(z,'diag'); % determine mode n = size(x,1); if dg % vector kxx K = ones(n,1); else if isempty(z) % symmetric matrix Kxx K = ones(n,n); else % cross covariances Kxz K = ones(n,size(z,1)); end end if nargout > 1 dK = @(Q) dirder(Q,K,x); % directional hyper derivative end function [dhyp,dx] = dirder(Q,K,x) dhyp = zeros(0,1); if nargout > 1, dx = zeros(size(x)); end
github
kd383/GPML_SLD-master
covRQard.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covRQard.m
1,319
utf_8
4a01d96fc2dfed96d4da74a33d401733
function varargout = covRQard(varargin) % Wrapper for Rational Quadratic covariance function covRQ.m. % % Rational Quadratic covariance function with Automatic Relevance Determination % (ARD) distance measure. The covariance function is parameterized as: % % k(x,z) = sf^2 * [1 + (x-z)'*inv(P)*(x-z)/(2*alpha)]^(-alpha) % % where the P matrix is diagonal with ARD parameters ell_1^2,...,ell_D^2, where % D is the dimension of the input space, sf2 is the signal variance and alpha % is the shape parameter for the RQ covariance. The hyperparameters are: % % hyp = [ log(ell_1) % log(ell_2) % .. % log(ell_D) % log(sf) % log(alpha) ] % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-10-01. % % See also covRQ.M. varargout = cell(max(1,nargout),1); if nargin>0 % restore old hyper parameter order hyp = varargin{1}; if numel(hyp)>2, varargin{1} = hyp([1:end-2,end,end-1]); end end [varargout{:}] = covScale({'covRQ','ard',[]},varargin{:}); if nargout>1 % restore old hyper parameter order o2 = varargout{2}; varargout{2} = @(Q) dirder(Q,o2); end function [dKdhyp,dKdx] = dirder(Q,dK) if nargout>1, [dKdhyp,dKdx] = dK(Q); else dKdhyp = dK(Q); end dKdhyp = dKdhyp([1:end-2,end,end-1]);
github
kd383/GPML_SLD-master
covW.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covW.m
4,023
utf_8
949b84c4ea6880c67f04e823beccebf8
function [K,dK] = covW(i, hyp, x, z) % Wiener process covariance function, i times integrated. % % For i= 0, this is the Wiener process covariance, % for i= 1, this is the integrated Wiener process covariance (velocity), % for i= 2, this is the twice-integrated Wiener process covariance (accel.), % for i= 3, this is the thrice-integrated Wiener process covariance. % For i=-1, this is just the white noise covariance, see covNoise. % % If dw(x) is a Wiener process then dw(x+s^2)-dw(x) = N(0,s^2). % The Wiener process is the integral of a white noise process, see covEye. % % The covariance function -- given that x,z>=0 -- is specified as: % % k(x,z) = sf^2 * ki(x,z), where ki(x,z) is given for % different values of i by the following expressions % i = -1, ki(x,z) = \delta(x,z) % i >= 0, ki(x,z) = 1/ai*min(x,z)^(2*i+1) + bi*min(x,z)^(i+1) * |x-z| * ri(x,z), % with the coefficients ai, bi and the residual ri(x,z) defined as follows: % i = 0, ai = 1, bi = 0 % i = 1, ai = 3, bi = 1/ 2, ri(x,z) = 1 % i = 2, ai = 20, bi = 1/ 12, ri(x,z) = x+z-1/2*min(x,z) % i = 3, ai = 252, bi = 1/720, ri(x,z) = 5*max(x,z)^2+2*x*z+3*min(x,z)^2 % % See the paper Probabilistic ODE Solvers with Runge-Kutta Means by Schober, % Duvenaud and Hennig, NIPS, 2014, for more details. % % The hyperparameters are: % % hyp = [ log(sf) ] % % For more help on design of covariance functions, try "help covFunctions". % % Copyright (c) by Hannes Nickisch, 2017-10-05. % % See also COVEYE.M, COVFUNCTIONS.M. if nargin<3, K = '1'; return; end % report number of parameters if nargin<4, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); ox = ones(n,1); if D~=1, error('Covariance is defined for 1d data only.'), end if any(x<0) || (~xeqz && any(z<0)) error('Covariance is defined for nonnegative data only.') end sf = exp(hyp(1)); if dg % vector kxx Mn = x; Mx = x; I = ox; D = zeros(n,1); S = 2*x; P = x.*x; else if xeqz % symmetric matrix Kxx I = bsxfun(@le,x,x'); Mn = ox*x'; T = x*ox'; P = x*x'; else % cross covariances Kxz oz = ones(size(z)); I = bsxfun(@le,x,z'); Mn = ox*z'; T = x*oz'; P = x*z'; end D = T-Mn; S = T+Mn; % D = x-z, S = x+z, P = x*z, I = x<=z Mx = Mn; Mx(~I) = T(~I); Mn(I) = T(I); % Mn = min(x,z), Mx = max(x,z) end switch i case -1, K = double(abs(D)<eps*eps); case 0, K = Mn; case 1, K = Mn.^3/ 3 + abs(D).*Mn.^2/ 2; case 2, K = Mn.^5/ 20 + abs(D).*Mn.^3/ 12.*(S-Mn/2); case 3, K = Mn.^7/252 + abs(D).*Mn.^4/720.*(5*Mx.^2+2*P+3*Mn.^2); otherwise, error('unknown degree') end K = sf^2*K; % signal variance if nargout > 1 dK = @(Q) dirder(Q,K,I,Mn,Mx,D,S,P,sf,i,dg,xeqz,x); % directional deriv end function [dhyp,dx] = dirder(Q,K,I,Mn,Mx,D,S,P,sf,i,dg,xeqz,x) dhyp = 2*(Q(:)'*K(:)); % signal variance switch i case -1, dMn = 0; dD = 0; dS = 0; case 0, dMn = 1; dD = 0; dS = 0; case 1, dMn = Mn.^2+abs(D).*Mn; dD = Q.*sign(D).*Mn.^2/2; dS = 0; case 2, dMn = Mn.^4/4 + abs(D).*Mn.^2.*(S/4-Mn/6); dD = Q.*sign(D).*Mn.^3/12.*(S-Mn/2); dS = Q.*abs(D).*Mn.^3/12; case 3, dMn = Mn.^6/36 + abs(D).*Mn.^3/180.*(5*Mx.^2+2*P+9/2*Mn.^2); dD = Q.*sign(D).*Mn.^4/720.*(5*Mx.^2+2*P+3*Mn.^2); dS = 0; % dMx and dP are assumend to be small end Q = Q.*dMn; if nargout > 1 if dg dx = zeros(size(x)); else if xeqz dx = sum(Q.*I,2)+sum(Q.*(1-I),1)'+sum(dD,2)-sum(dD,1)'+sum(dS+dS',2); else dx = sum(Q.*I,2)+sum(dD,2)+sum(dS,2); end end dx = sf^2*dx; % signal variance end
github
kd383/GPML_SLD-master
covPeriodicNoDC.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covPeriodicNoDC.m
4,121
utf_8
ddc552a3a497084564de2a890aac7bef
function [K,dK] = covPeriodicNoDC(hyp, x, z) % Stationary covariance function for a smooth periodic function, with period p: % % k(x,z) = sf^2 * [k0(pi*(x-z)/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 2016-04-24. % % 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)); % extract hyperparams % precompute deviations and exploit symmetry of sin^2 if dg % vector txx T = zeros(size(x,1),1); else if xeqz % symmetric matrix Txx T = pi/p*bsxfun(@plus,x,-x'); else % cross covariances Txz T = pi/p*bsxfun(@plus,x,-z'); end end K = covD(2*T,ell); K = sf2*K; % covariance if nargout>1 ebi0 = embi0(1/ell^2); ebi1 = embi1(1/ell^2); dK = @(Q) dirder(Q,K,T,ell,p,sf2,xeqz,x,z,ebi0,ebi1); % directional hyp deriv end function [dhyp,dx] = dirder(Q,K,T,ell,p,sf2,xeqz,x,z,ebi0,ebi1) S2 = (sin(T)/ell).^2; if ell>1e4 % limit for ell->infty Z = zeros(size(T)); % no further progress in ell possible elseif 1/ell^2<3.75 cK = cos(2*T); ecK = exp(cK/ell^2); b0 = besseli(0,1/ell^2); b1 = besseli(1,1/ell^2); Z = 2*(exp(1/ell^2)-ecK )*b1 ... - 2*(exp(1/ell^2)-ecK.*cK)*b0 ... + 4*exp(2*(cos(T)/ell).^2).*sin(T).^2; Z = sf2/(ell*(exp(1/ell^2)-b0))^2 * Z; else cK = cos(2*T); ecK = exp((cK-1)/ell^2); b0 = ebi0; b1 = ebi1; Z = 2*(1-ecK)*b1 - 2*(1-ecK.*cK)*b0 ... + 4*exp(2*(cos(T).^2-1)/ell^2).*sin(T).^2; Z = sf2/(ell*(1-b0))^2 * Z; end if ell>1e4 % limit for ell->infty Y = 2*sf2* sin(2*T).*T; a = 1; elseif 1/ell^2<3.75 c = 1/(exp(1/ell^2)-b0)/ell^2; Y = 2*c*sf2*exp( cos(2*T) /ell^2).*sin(2*T).*T; a = 1/(1-b0*exp(-1/ell^2))/ell^2; else c = 1/(1-b0)/ell^2; Y = 2*c*sf2*exp((cos(2*T)-1)/ell^2).*sin(2*T).*T; a = c; end dhyp = [Z(:)'*Q(:); Y(:)'*Q(:); 2*(Q(:)'*K(:))]; if nargout > 1 Kdc = sf2*exp( -2*S2 ); % inkl. DC component R = Kdc.*sin(2*T).*Q./T; R(T==0) = 0; r2 = sum(R,2); r1 = sum(R,1)'; if xeqz y = bsxfun(@times,r1+r2,x) - (R+R')*x; else Rz = R*z; y = bsxfun(@times,r2,x) - Rz; end dx = -2*a*pi^2/p^2 * y; 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
kd383/GPML_SLD-master
covPoly.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covPoly.m
1,728
utf_8
05dd966400369bbcb5c67bd873904ba1
function [K,dK] = covPoly(mode,par,d,hyp,x,z) % Polynomial covariance function. The covariance function is parameterized as: % % k(x,z) = sf^2 * ( c + s )^d , where s = x*inv(P)*z is the dot product % % The hyperparameters are: % % hyp = [ hyp_dot % log(c) % log(sf) ] % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2017-09-26. % % See also covDot.m. if nargin<2, mode = 'eye'; par = []; end % default mode if ~ischar(mode) % make compatible to old interface version if nargin>3, z = hyp; end if nargin>2, x = d; end if nargin>1, hyp = par; end if nargin>0, d = mode; end mode = 'eye'; par = []; narg = nargin+2; else narg = nargin; end if narg<5, K = [covDot(mode,par),'+2']; return, end % report nr of parameters if narg<6, z = []; end % make sure, z exists [n,D] = size(x); % dimensions ne = eval(covDot(mode,par)); c = exp(hyp(ne+1)); % inhomogeneous offset sf2 = exp(2*hyp(ne+2)); % signal variance if d~=max(1,fix(d)), error('only nonzero integers allowed for d'), end % degree k = @(s) (c+s).^d; dk = @(s) d*(c+s).^(d-1); if nargout > 1 [K,dK0] = covScale({'covDot',mode,par,k,dk},hyp([1:ne,ne+2]),x,z); S = covDot(mode,par,@(s)s,[],hyp(1:ne),x,z); dK = @(Q) dirder(Q,S,dK0,c,d,sf2,ne); else K = covScale({'covDot',mode,par,k,dk},hyp([1:ne,ne+2]),x,z); end function [dhyp,dx] = dirder(Q,S,dK0,c,d,sf2,ne) if nargout > 1, [dhyp,dx] = dK0(Q); else dhyp = dK0(Q); end dhyp = [dhyp(1:ne); c*d*sf2*(Q(:)'*(c+S(:)).^(d-1)); dhyp(ne+1)]; % insert c
github
kd383/GPML_SLD-master
covPP.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covPP.m
1,920
utf_8
316ff11a633a645667943d2e5b47cd44
function varargout = covPP(mode, par, v, hyp, x, varargin) % Piecewise Polynomial covariance function with compact support, v = 0,1,2,3. % The covariance functions are 2v times contin. diff'ble and the corresponding % processes are hence v times mean-square diffble. The covariance function is: % % k(x,z) = max(1-r,0)^(j+v) * f(r,j) with j = floor(D/2)+v+1 % % where r is the Mahalanobis distance sqrt(maha(x,z)). The hyperparameters are: % % hyp = [ hyp_maha ] % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-05-23. % % See also covMaha.m. if nargin < 1, error('Mode cannot be empty.'); end % no default if nargin < 2, par = []; end % default varargout = cell(max(1, nargout), 1); % allocate mem for output if nargin<5, varargout{1} = covMaha(mode,par); return, end [n,D] = size(x); if all(v~=[0,1,2,3]), error('only 0,1,2 and 3 allowed for v'), end % degree j = floor(D/2)+v+1; % exponent switch v case 0, f = @(r,j) 1; df = @(r,j) 0; case 1, f = @(r,j) 1 + (j+1)*r; df = @(r,j) (j+1); case 2, f = @(r,j) 1 + (j+2)*r + ( j^2+ 4*j+ 3)/ 3*r.^2; df = @(r,j) (j+2) + 2*( j^2+ 4*j+ 3)/ 3*r; case 3, f = @(r,j) 1 + (j+3)*r + (6*j^2+36*j+45)/15*r.^2 ... + (j^3+9*j^2+23*j+15)/15*r.^3; df = @(r,j) (j+3) + 2*(6*j^2+36*j+45)/15*r ... + (j^3+9*j^2+23*j+15)/ 5*r.^2; end cs = @(r,e) (r<1).*max(1-r,0).^e; pp = @(r,j,v,f) cs(r,j+v ).* f(r,j); dpp = @(r,j,v,f) r.*cs(r,j+v-1).*( f(r,j)*(j+v) - max(1-r,0).*df(r,j) ); k = @(d2) pp( sqrt(d2), j, v, f ); dk = @(d2,k) set_zero( -(1/2)*dpp( sqrt(d2), j, v, f )./d2 , d2==0); [varargout{:}] = covMaha(mode, par, k, dk, hyp, x, varargin{:}); function A = set_zero(A,I), A(I) = 0;
github
kd383/GPML_SLD-master
covMaha.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covMaha.m
8,278
utf_8
0847696adc64057a0c27b85bb49a1ae8
function [K,dK,D2] = covMaha(mode, par, k, dk, hyp, x, z) % Mahalanobis distance-based covariance function. The covariance function is % parameterized as: % % k(x,z) = k(r^2), r^2 = maha(x,P,z) = (x-z)'*inv(P)*(x-z), % % where the matrix P is the metric. % % Parameters: % 1) mode,par: % We offer different modes (mode) with their respective parameters (par): % mode = par = inv(P) = hyp = % 'eye' [] eye(D) [] % 'iso' [] ell^2*eye(D) [log(ell)] % 'ard' [] diag(ell.^2) [log(ell_1); ..; log(ell_D)] % 'proj' d L'*L [L_11; L_21; ..; L_dD] % 'fact' d L'*L + diag(f) [L_11; L_21; ..; L_dD; log(f_1); ..; log(f_D)] % 'vlen' llen l(x,z)^2*eye(D) [hyp_llen] % In the last mode, the covariance function is turned into a nonstationary % covariance by a variable lengthscale l(x,z) = sqrt((len(x)^2+len(z)^2)/2), % where len(x) = exp(llen(x)) and llen is provided as additional parameter % in the form of a GPML mean function cell array. The final expression for the % 'vlen' covariance is: % k(x,z) = ( len(x)*len(z)/l(x,z)^2 )^(D/2) * k( (x-z)'*(x-z)/l(x,z)^2 ). % % 2) k,dk: % The functional form of the covariance is governed by two functions: % k: r^2 -> k(x,z), r^2 = maha(x,P,z) = (x-z)'*inv(P)*(x-z) % dk: r^2,k(x,z) -> d k(x,z) / d r2 % For example, the squared exponential covariance uses % k = @(r2) exp(-r2/2); dk = @(r2,k) (-1/2)*k; % Note that not all functions k,dk give rise to a valid i.e. positive % semidefinite covariance function k(x,z). % % 3) hyp,x,z: % These input parameters follow the usual covariance function interface. For the % composition of hyp, see 1). % % 4) K,dK: % See the usual covariance function interface. % % For more help on design of covariance functions, try "help covFunctions". % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2017-01-11. % % See also COVFUNCTIONS.M. if nargin<1, mode = 'eye'; end, if nargin <2, par = []; end % default values mode_list = '''eye'', ''iso'', ''ard'', ''proj'', ''fact'', or ''vlen'''; switch mode case 'eye', ne = '0'; case 'iso', ne = '1'; case 'ard', ne = 'D'; case 'proj', ne = [num2str(par),'*D']; case 'fact', ne = [num2str(par),'*D+D']; case 'vlen', ne = feval(par{:}); otherwise, error('Parameter mode is either %s.',mode_list) end if nargin<6, K = ne; return; end % report number of parameters if nargin<7, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % sort out different modes [n,D] = size(x); ne = eval(ne); % dimensions hyp = hyp(:); % make sure hyp is a column vector if numel(hyp)~=ne, error('Wrong number of hyperparameters'), end switch mode % mvm with metric A=inv(P) case {'eye','vlen'} A = @(x) x; dAdhyp = @(dAdiag,dAmvm) zeros(0,1); case 'iso', A = @(x) x*exp(-2*hyp); dAdhyp = @(dAdiag,dAmvm) -2*sum(A(dAdiag')); case 'ard', A = @(x) bsxfun(@times,x,exp(-2*hyp')); dAdhyp = @(dAdiag,dAmvm) -2*A(dAdiag')'; case 'proj', d = par; L = reshape(hyp,d,D); A = @(x) (x*L')*L; dAdhyp = @(dAdiag,dAmvm) 2*reshape(dAmvm(L')',d*D,1); case 'fact', d = par; L = reshape(hyp(1:d*D),d,D); f = exp(hyp(d*D+1:end)); A = @(x) (x*L')*L + bsxfun(@times,x,f'); dAdhyp = @(dAdiag,dAmvm)[2*reshape(dAmvm(L')',d*D,1); f.*dAdiag]; end [D2,dmaha] = maha(x,A,z); T = 1; L2 = 1; % compute Mahalanobis distance if isequal(mode,'vlen') % evaluate variable lengthscales lx = exp(feval(par{:},hyp,x)); % L2 = (lx^2+lz^2)/2, P = lx*lz if dg L2 = lx.*lx; P = L2; else if xeqz, lz = lx; else lz = exp(feval(par{:},hyp,z)); end L2 = bsxfun(@plus,(lx.*lx)/2,(lz.*lz)'/2); P = lx*lz'; end D2 = D2./L2; T = (P./L2).^(D/2); % non-stationary covariance end K = k(D2); % evaluate covariance if nargout > 1 % directional derivative dK = @(Q) dirder(Q,K,dk,T,D2,L2,dmaha,dAdhyp,mode,par,hyp,x,z,dg,xeqz); end if isequal(mode,'vlen'), K = K.*T; end function [dhyp,dx] = dirder(Q,K,dk,T,D2,L2,dmaha,dAdhyp, mode,par,hyp,x,z,dg,xeqz) R = T.*dk(D2,K).*Q; switch mode case 'eye', dx = dmaha(R); dhyp = zeros(0,1); % fast shortcut case 'iso', dx = dmaha(R); dhyp = -2*R(:)'*D2(:); % fast shortcut case 'vlen', dx = dmaha(R); lx2 = exp(-2*feval(par{:},hyp,x)); dx = bsxfun(@times,dx,lx2); D = size(x,2); % only correct for lx = const. if dg dhyp = zeros(size(hyp)); else [llx,dllx] = feval(par{:},hyp,x); lx = exp(llx); if xeqz, lz = lx; dllz = dllx; else [llz,dllz] = feval(par{:},hyp,z); lz = exp(llz); end A=(D/2)*Q.*K.*((lx*lz')./L2).^(D/2-1)./L2; B=(D2.*R+A.*(lx*lz'))./L2; dhyp = dllx(lx.*(A*lz-sum(B,2).*lx)) + dllz(lz.*(A'*lx-sum(B,1)'.*lz)); end otherwise, [dx,dAdiag,dAmvm] = dmaha(R); dhyp = dAdhyp(dAdiag,dAmvm); end % Mahalanobis squared distance function for A spd % D2 = maha(x,A,z) = (x-z)'*A*(x-z) % dx(Q) = d tr(Q'*D2) / d x % dA(Q) = d tr(Q'*D2) / d A function [D2,dmaha] = maha(x,A,z) if nargin<2, A = @(x) x; end % make sure the metric exists if nargin<3, z = []; end % make sure z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % sort out different modes n = size(x,1); m = size(z,1); % dimensions if dg % vector d2xx D2 = zeros(n,1); else % 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 xeqz mu = mean(x,1); else mu = (m/(n+m))*mean(z,1) + (n/(n+m))*mean(x,1); z = bsxfun(@minus,z,mu); end x = bsxfun(@minus,x,mu); Ax = A(x); sax = sum(x.*Ax,2); if xeqz % symmetric matrix D2xx Az = Ax; saz = sax; else % cross terms D2xz Az = A(z); saz = sum(z.*Az,2); end % remove numerical noise at the end and ensure that D2>=0 D2 = max(bsxfun(@plus,sax,bsxfun(@minus,saz',2*x*Az')),0); % computation end if nargout>1, dmaha = @(Q) maha_dirder(Q,x,A,z); end function [dx,dAdiag,dAmvm] = maha_dirder(Q,x,A,z) % directional derivative if nargin<3, z = []; end xeqz = isempty(z); dg = strcmp(z,'diag'); % sort out different modes q2 = sum(Q,2); q1 = sum(Q,1)'; sym = @(X) (X+X')/2; dAdense = size(x,2)<5; % estimated break-even between O(D*D*n) and O(4*D*n) if dg dx = zeros(size(x)); if nargout > 1 dAdiag = zeros(size(x,2),1); dAmvm = @(r) zeros(size(r)); end else if xeqz y = bsxfun(@times,q1+q2,x) - (Q+Q')*x; if nargout > 1 if dAdense % construct a dense matrix dA of size DxD in O(D*D*n) dA = sym(x'*y); dAdiag = diag(dA); dAmvm = @(r) dA*r; else % just perform an MVM avoiding a DxD matrix dA in O(4*D*n) dAdiag = sum(x.*y,1)'; dAmvm = @(r) (x'*(y*r) + y'*(x*r))/2; end end else Qz = Q*z; y = bsxfun(@times,q2,x) - Qz; if nargout > 1 yz = y-Qz; qz = bsxfun(@times,q1,z); if dAdense % construct a dense matrix dA of size DxD in O(D*D*n) dA = sym(x'*yz + z'*qz); dAdiag = diag(dA); dAmvm = @(r) dA*r; else % just perform an MVM avoiding a DxD matrix in O(8*D*n) dAdiag = sum(x.*yz,1)'+sum(z.*qz,1)'; dAmvm = @(r) (x'*(yz*r)+yz'*(x*r) + z'*(qz*r)+qz'*(z*r))/2; end end end dx = 2*A(y); end
github
kd383/GPML_SLD-master
apx.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/apx.m
33,771
utf_8
2265d86ef1af3ba038046c64d460356a
function K = apx(hyp,cov,x,opt) % (Approximate) linear algebra operations involving the covariance matrix K. % % A) Exact covariance computations. % There are no parameters in this mode. % Depending on the sign of W, we switch between % - the symmetric Cholesky mode [1], where B = I + sqrt(W)*K*sqrt(W), and % - the asymmetric LU mode [2], where B = I + K*W. % Note that (1) is faster but it is only applicable if all W are positive. % % B) Sparse covariance approximations aka FITC [4], VFE [5] and SPEP [3]. % We have a parameter opt.s from [0,1], the power in sparse power EP [3] % interpolating between the Fully Independent Training Conditionals (FITC) % approach [4] and a Variational Free Energy (VFE) approximation [5]. % In particular: % opt.s, default is 1.0 for FITC, opt.s = 0.0 corresponds to VFE. % Please see cov/apxSparse.m for details. % % C) Grid-based covariance approximations aka KISS-GP [6]. % Please see cov/apxGrid.m for further details and more parameters. % opt.cg_tol, default is 1e-6 as in Matlab's pcg function % opt.cg_maxit, default is min(n,20) as in Matlab's pcg function % The conjugate gradient-based linear system solver has two adjustable % parameters, the relative residual threshold for convergence opt.cg_tol and % the maximum number of MVMs opt.cg_maxit until the process stops. % opt.deg, default is 3 degree of interpolation polynomial % For equispaced axes, opt.deg sets the degree of the interpolation % polynomial along each of the p axes. Here 0 means nearest neighbor, % 1 means linear interpolation, and 3 uses a cubic. % For non-equispaced axes, only linear interpolation with inverse distance % weighting is offered and opt.deg is ignored. % % opt.ldB2_method string indicating the possible modes (details below) % - 'scale' => (i) scaled eigenvalue approach followed by Fiedler bound % - 'cheby' => (ii) stochastic estimation using Chebyshev polynomials % - 'lancz' => (iii) stochastic estimation using Lanczos iterations % (i) 'scale' the default method simply uses the eigenvalues of the % covariance matrix of the complete grid and rescales the values by the % ratio of number grid points N and number data points n; in case of % non-Gaussian inference i.e. W not being isotropic, we apply and % additional bounding step (Fiedler) % (ii) 'cheby' employs Monte-Carlo trace estimation aka the Hutchinson method % and Chebyshev polynomials to approximate the term log(det(B))/2 % stochastically, see [7]. The following parameters configure different % aspects of the estimator and are only valid if opt.ldB2_method='cheby' % opt.ldB2_hutch, default is 10, number of samples for the trace estim % opt.ldB2_cheby_degree, default is 15, degree of Chebyshev approx polynomial % opt.ldB2_maxit, default is 50, max # of MVMs to estimate max(eig(B)) % opt.ldB2_seed, default is [], random seed for the stoch trace estim % (iii) 'lancz' employs Monte-Carlo trace estimation aka the Hutchinson method % and Lanczos iterations with full Gram-Schmidt to approximate the % term log(det(B))/2 stochastically. % 'lancz-arpack' is the same as above only that the ARPACK reverse % communication interface is used and partial orthogonalisation is used. % The following parameters configure different aspects of the estimator % and are only valid if opt.ldB2_method = 'lancz*' % opt.ldB2_hutch, default is 10, number of samples for the trace estim % opt.ldB2_maxit, default is 50, max # of MVMs per Lanczos run % opt.ldB2_seed, default is [], random seed for the stoch trace estim % % opt.stat = true returns a little bit of output summarising the exploited % structure of the covariance of the grid. % The log-determinant approximation employs Fiedler's 1971 inequality and a % rescaled version of the eigenspectrum of the covariance evaluated on the % complete grid. % % The call K = apx(hyp,cov,x,opt) yields a structure K with a variety of % fields. % 1) Matrix-vector multiplication with covariance matrix % K.mvm(x) = K*x % 2) Projection and its transpose (unity except for mode B) Sparse approx.) % post.alpha = K.P(solveKiW(f-m)) % post.L = L = @(r) -K.P(solveKiW(K.Pt(r))) % 3) Linear algebra functions depending on W % [ldB2,solveKiW,dW,dldB2,L,triB] = K.fun(W) % a) Log-determinant (approximation), called f in the sequel % ldB2 = log(det(B))/2 % b) Solution of linear systems % solveKiW(r) = (K+inv(W)) \ r % c) Log-determinant (approximation) derivative w.r.t. W % dW = d f / d W, where f = ldB2(W), exact value dW = diag(inv(B)*K)/2 % d) Log-determinant (approximation) derivative w.r.t. hyperparameters % dhyp = dldB2(alpha,a,b) % Q = d f / d K, exact value would be Q = inv(K+inv(W)) % R = alpha*alpha' + 2*a*b' % Here dhyp(i) = tr( (Q-R)'*dKi )/2, where dKi = d K / d hyp(i). % e) Matrix (operator) to compute the predictive variance % L = -K.P(solveKiW(K.Pt(r))) either as a dense matrix or function. % See gp.m for details on post.L. % f) triB = trace(inv(B)) % % [1] Seeger, GPs for Machine Learning, sect. 4, TR, 2004. % [2] Jylanki, Vanhatalo & Vehtari, Robust GPR with a Student's-t % Likelihood, JMLR, 2011. % [3] Bui, Yan & Turner, A Unifying Framework for Sparse GP Approximation % using Power EP, 2016, https://arxiv.org/abs/1605.07066. % [4] Snelson & Ghahramani, Sparse GPs using pseudo-inputs, NIPS, 2006. % [5] Titsias, Var. Learning of Inducing Variables in Sparse GPs, AISTATS, 2009 % [6] Wilson & Nickisch, Kernel Interp. for Scalable Structured GPs, ICML, 2015 % [7] Han, Malioutov & Shin, Large-scale Log-det Computation through Stochastic % Chebyshev Expansions, ICML, 2015. % % Copyright (c) by Carl Edward Rasmussen, Kun Dong, Insu Han and % Hannes Nickisch 2017-05-05. % % See also apxSparse.m, apxGrid.m, gp.m. if nargin<4, opt = []; end % make sure variable exists if isnumeric(cov), c1 = 'numeric'; else c1 = cov{1}; end % detect matrix if isa(c1, 'function_handle'), c1 = func2str(c1); end % turn into string sparse = strcmp(c1,'apxSparse') || strcmp(c1,'covFITC'); grid = strcmp(c1,'apxGrid') || strcmp(c1,'covGrid'); exact = ~grid && ~sparse; if exact % A) Exact computations using dense matrix operations if strcmp(c1,'numeric'), K = cov; dK = []; % catch dense matrix case else [K,dK] = feval(cov{:},hyp.cov,x); % covariance matrix and dir derivative end K = struct('mvm',@(x)mvmK_exact(K,x), 'P',@(x)x, 'Pt',@(x)x,... % mvm and proj 'fun',@(W)ldB2_exact(W,K,dK)); elseif sparse % B) Sparse approximations if isfield(opt,'s'), s = opt.s; else s = 1.0; end % default is FITC xud = isfield(hyp,'xu'); % flag deciding whether to compute hyp.xu derivs if xud, cov{3} = hyp.xu; end % hyp.xu provided, replace cov{3} xu = cov{3}; nu = size(xu,1); % extract inducing points [Kuu, dKuu] = feval(cov{2}{:}, hyp.cov, xu); % get the building blocks [Ku, dKu] = feval(cov{2}{:}, hyp.cov, xu, x); [diagK, ddiagK] = feval(cov{2}{:}, hyp.cov, x, 'diag'); snud = isfield(hyp,'snu'); % flag deciding whether to compute hyp.snu derivs if snud, snu2 = exp(2*hyp.snu); % hyp.snu already provided else snu2 = 1e-6*(trace(Kuu)/nu); % stabilise by 0.1% of signal std end Luu = chol(Kuu+diag(snu2.*ones(nu,1))); % Kuu + diag(snu2) = Luu'*Luu V = Luu'\Ku; % V = inv(Luu')*Ku => V'*V = Q g = max(diagK-sum(V.*V,1)',0); % g = diag(K) - diag(Q) K.mvm = @(x) V'*(V*x) + bsxfun(@times,s*g,x); % efficient matrix-vector mult K.P = @(x) Luu\(V*x); K.Pt = @(x) V'*(Luu'\x); % projection operations K.fun = @(W) ldB2_sparse(W,V,g,Luu,dKuu,dKu,ddiagK,s,xud,snud,snu2); elseif grid % C) Grid approximations n = size(x,1); if isfield(opt,'cg_tol'), cgtol = opt.cg_tol; % stop conjugate gradients else cgtol = 1e-6; end % same as in pcg if isfield(opt,'cg_maxit'), cgmit = opt.cg_maxit; % number of cg iterations else cgmit = min(n,20); end % same as in pcg if isfield(opt,'deg'), deg = opt.deg; else deg = 3; end % interpol. degree if isfield(opt,'stat'), stat = opt.stat; else stat = false; end % show stat cgpar = {cgtol,cgmit}; xg = cov{3}; p = numel(xg); % conjugate gradient, grid if isfield(opt,'ldB2_method'), meth=opt.ldB2_method; else meth='scale'; end m = 10; d = 15; mit = 50; sd = []; % set default parameters if strncmpi(meth,'cheby',5) || strncmpi(meth,'lancz',5) if isfield(opt,'ldB2_hutch'), m = opt.ldB2_hutch; end if isfield(opt,'ldB2_cheby_degree'), d = opt.ldB2_cheby_degree; end if isfield(opt,'ldB2_maxit'), mit = opt.ldB2_maxit; end if isfield(opt,'ldB2_seed'), sd = opt.ldB2_seed; end if stat fprintf('Stochastic (%s) logdet estimation (%d,%d,[d=%d])\n',meth,m,mit,d) end else if stat, fprintf('Scaled eigval logdet estimation\n'); end end ldpar = {meth,m,d,mit,[],sd}; % logdet parameters [Kg,Mx] = feval(cov{:},hyp.cov,x,[],deg); % grid cov structure, interp matrix if stat % show some information about the nature of the p Kronecker factors fprintf(apxGrid('info',Kg,Mx,xg,deg)); end K.mvm = @(x) Mx*Kg.mvm(Mx'*x); % mvm with covariance matrix K.P = @(x)x; K.Pt = @(x)x; % projection operations K.fun = @(W) ldB2_grid(W,K,Kg,xg,Mx,cgpar,ldpar); K.Mx = Mx; end %% A) Exact computations using dense matrix operations ========================= function [ldB2,solveKiW,dW,dldB2,L,triB] = ldB2_exact(W,K,dK) isWneg = any(W<0); n = numel(W); if isWneg % switch between Cholesky and LU decomposition mode A = eye(n) + bsxfun(@times,K,W'); % asymmetric A = I+K*W [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 inf ldB2 = Inf; else % det(L) = 1 and U triangular => det(A) = det(P)*prod(diag(U)) ldB2 = sum(log(abs(u)))/2; end % compute inverse if required if nargout>1, Q = U\(L\P); solveKiW = @(r) bsxfun(@times,W,Q*r); end if nargout>4, L = -diag(W)*Q; end % overwrite L else % symmetric B = I+sW*K*sW sW = sqrt(W); L = chol(eye(n)+sW*sW'.*K); % Cholesky factor of B ldB2 = sum(log(diag(L))); % log(det(B))/2 solveKiW = @(r) bsxfun(@times,solve_chol(L,bsxfun(@times,r,sW)),sW); if nargout>2, Q = bsxfun(@times,1./sW,solve_chol(L,diag(sW))); end end if nargout>2 dW = sum(Q.*K,2)/2; % d log(det(B))/2 / d W = diag(inv(inv(K)+W)) triB = trace(Q); % triB = trace(inv(B)) dldB2 = @(varargin) ldB2_deriv_exact(W,dK,Q, varargin{:}); % derivatives end function dhyp = ldB2_deriv_exact(W,dK,Q, alpha,a,b) if nargin>3, R = alpha*alpha'; else R = 0; end if nargin>5, R = R + 2*a*b'; end dhyp.cov = dK( bsxfun(@times,Q,W) - R )/2; function z = mvmK_exact(K,x) if size(x,2)==size(x,1) && max(max( abs(x-eye(size(x))) ))<eps % x=eye(n) z = K; % avoid O(n^3) operation as it is trivial else z = K*x; end %% B) Sparse approximations ==================================================== function [ldB2,solveKiW,dW,dldB2,L,triB] = ldB2_sparse(W,V,g,Luu,... dKuu,dKu,ddiagK,s,xud,snud,snu2) z = s*g.*W; t = 1/s*log(z+1); i = z<1e-4; % s=0: t = g*W, s=1: t = log(g*W+1) t(i) = g(i).*W(i).*(1-z(i)/2+z(i).^2/3); % 2nd order Taylor for tiny z dt = 1./(z+1); d = W.*dt; % evaluate derivatives nu = size(Luu,1); Vd = bsxfun(@times,V,d'); Lu = chol(eye(nu) + V*Vd'); LuV = Lu'\V; % Lu'*Lu=I+V*diag(d)*V' ldB2 = sum(log(diag(Lu))) + sum(t)/2; % s=1 => t=log(g.*W+1), s=0 => t=g.*W md = @(r) bsxfun(@times,d,r); solveKiW = @(r) md(r) - md(LuV'*(LuV*md(r))); if nargout>2 % dW = d log(det(B))/2 / d W = diag(inv(inv(K)+W)) dW = sum(LuV.*((LuV*Vd')*V),1)' + s*g.*d.*sum(LuV.*LuV,1)'; dW = dt.*(g+sum(V.*V,1)'-dW)/2; % add trace "correction" term dldB2 = @(varargin) ldB2_deriv_sparse(V,Luu,d,LuV,dKuu,dKu,ddiagK,s,... xud,snud,snu2,varargin{:}); if nargout>4 L = solve_chol(Lu*Luu,eye(nu))-solve_chol(Luu,eye(nu)); % Sigma-inv(Kuu) end if nargout>5 r = 1./(z+1); R = (eye(nu) + V*bsxfun(@times,V',r.*W))\V; triB = r'*(1-W.*sum(V.*R)'.*r); end end function dhyp = ldB2_deriv_sparse(V,Luu,d,LuV,dKuu,dKu,ddiagK,s,... xud,snud,snu2,alpha,a,b) % K + 1./W = V'*V + inv(D), D = diag(d) % Q = inv(K+inv(W)) = inv(V'*V + diag(1./d)) = diag(d) - LuVd'*LuVd; LuVd = bsxfun(@times,LuV,d'); diagQ = d - sum(LuVd.*LuVd,1)'; F = Luu\V; Qu = bsxfun(@times,F,d') - (F*LuVd')*LuVd; if nargin>11, diagQ = diagQ-alpha.*alpha; Qu = Qu-(F*alpha)*alpha'; end Quu = Qu*F'; if nargin>13 diagQ = diagQ-2*a.*b; Qu = Qu-(F*a)*b'-(F*b)*a'; Quu = Quu-2*(F*a)*(F*b)'; end diagQ = s*diagQ + (1-s)*d; % take care of s parameter Qu = Qu - bsxfun(@times,F,diagQ'); Quu = Quu - bsxfun(@times,F,diagQ')*F'; if snud % compute inducing noise derivative dhyp.snu = -diag(Quu).*snu2; if numel(snu2)==1, dhyp.snu=sum(dhyp.snu); end else nu = size(Quu,1); Quu = Quu + 1e-6*trace(Quu)/nu*eye(nu); % fixed noise end if xud dhyp.cov = ddiagK(diagQ)/2; dhyp.xu = 0; [dc,dx] = dKu(Qu); dhyp.cov = dhyp.cov + dc; dhyp.xu = dhyp.xu + dx; [dc,dx] = dKuu(Quu); dhyp.cov = dhyp.cov - dc/2; dhyp.xu = dhyp.xu - dx/2; else dhyp.cov = ddiagK(diagQ)/2 + dKu(Qu) - dKuu(Quu)/2; end %% C) Grid approximations ===================================================== function [ldB2,solveKiW,dW,dldB2,L,triB] = ldB2_grid(W,K,Kg,xg,Mx,cgpar,ldpar) if all(W>=0) % well-conditioned symmetric case sW = sqrt(W); msW = @(x) bsxfun(@times,sW,x); mvmB = @(x) msW(K.mvm(msW(x)))+x; solveKiW = @(r) msW(linsolve(msW(r),mvmB,cgpar{:})); else % less well-conditioned symmetric case if some negative W mvmKiW = @(x) K.mvm(x)+bsxfun(@times,1./W,x); solveKiW = @(r) linsolve(r,mvmKiW,cgpar{:}); end % K*v = Mx*Kg.mvm(Mx'*v) dhyp.cov = []; % init if strncmpi(ldpar{1},'cheby',5) % stochastic estim: logdet cheby/hutchinson dK = @(a,b) apxGrid('dirder',Kg,xg,Mx,a,b); if nargout<3 % save some computation depending on required output ldB2 = ldB2_cheby(W,K.mvm,dK, ldpar{2:end}); else [ldB2,dhyp.cov,dW] = ldB2_cheby(W,K.mvm,dK, ldpar{2:end}); end elseif strncmpi(ldpar{1},'lancz',5)% stochastic estim: logdet lancz/hutchinson % the sign of the maxit parameter encodes whether ARPACK is used or not mv = ver('matlab'); % get Matlab version, ARPACK interface not in Octave if numel(mv)==0 ldpar{4} = -abs(ldpar{4}); end dK = @(a,b) apxGrid('dirder',Kg,xg,Mx,a,b); if nargout<3 % save some computation depending on required output ldB2 = ldB2_lanczos(W,K.mvm,dK, ldpar{[2,4,6]}); else [ldB2,dhyp.cov,dW] = ldB2_lanczos(W,K.mvm,dK, ldpar{[2,4,6]}); end else s = 3; % Whittle embedding overlap factor [V,ee,e] = apxGrid('eigkron',Kg,xg,s); % perform eigen-decomposition [ldB2,de,dW] = logdet_fiedler(e,W); % Fiedler's upper bound, derivatives de = de.*double(e>0); % chain rule of max(e,0) in eigkron, Q = V*diag(de)*V' if nargout>3, dhyp.cov = ldB2_deriv_grid_fiedler(Kg,xg,V,ee,de,s); end end dldB2 = @(varargin) ldB2_deriv_grid(dhyp, Kg,xg,Mx, varargin{:}); if ~isreal(ldB2), error('Too many negative W detected.'), end L = @(r) -K.P(solveKiW(K.Pt(r))); if nargout>5, error('triB not implemented'), end function dhyp = ldB2_deriv_grid_fiedler(Kg,xg,V,ee,de,s) p = numel(Kg.kron); % number of Kronecker factors ng = [apxGrid('size',xg)',1]; % grid dimension dhyp = []; % dhyp(i) = trace( V*diag(de)*V'*dKi ) for i=1:p z = reshape(de,ng); Vi = V{i}; for j=1:p, if i~=j, z = apxGrid('tmul',ee{j}(:)',z,j); end, end if isnumeric(Vi) Q = bsxfun(@times,Vi,z(:)')*Vi'; dhci = Kg.kron(i).dfactor(Q); else kii = Kg.kron(i).factor.kii; [junk,ni] = apxGrid('expand',xg{i}); di = numel(ni); xs = cell(di,1); % generic (Strang) circular embedding grid for j=1:di, n2 = floor(ni(j)-1/2)+1; xs{j} = [1:n2,n2-2*ni(j)+2:0]'; end Fz = real(fftn(reshape(z,[ni(:)',1]))); % imaginary part of deriv is zero rep = 2*s*ones(1,di); if di==1, rep = [rep,1]; end % replication Fzw = repmat(Fz,rep); % replicate i.e. perform transpose of circ operation [junk,xw] = apxGrid('circ',kii,ni,s); % get Whittle circ embedding grid [junk,dkwi] = kii(apxGrid('expand',xw)); % evaluate derivative dhci = dkwi(Fzw(:)); end dhyp = [dhyp; dhci]; end function dhyp = ldB2_deriv_grid(dhyp, Kg,xg,Mx, alpha,a,b) if nargin>4, dhyp.cov = dhyp.cov-apxGrid('dirder',Kg,xg,Mx,alpha,alpha)/2; end if nargin>6, dhyp.cov = dhyp.cov-apxGrid('dirder',Kg,xg,Mx,a,b); end function q = linsolve(p,mvm,varargin) % solve q = mvm(p) via conjugate gradients [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 % 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 % Upper determinant bound on log |K*diag(W)+I| using Fiedler's 1971 inequality. % K = kron( kron(...,K{2}), K{1} ), W = diag(w) both symmetric psd. % The bound is exact for W = w*ones(N,1). Here, E = eig(K) are the % eigenvalues of the matrix K. % See also Prob.III.6.14 in Matrix Analysis, Bhatia 1997. % % Given nxn spd matrices C and D with ordered nx1 eigenvalues c, d % then det(C+D) <= prod(c+flipud(d))=exp(ub). function [ub,dE,dW,ie,iw] = logdet_fiedler(E,W) [E,ie] = sort(E,'descend'); [W,iw] = sort(W,'descend'); % sort vectors N = numel(E); n = numel(W); k = n/N*E; % dimensions, approximate spectrum of K if n>N, k = [k;zeros(n-N,1)]; else k = k(1:n); end % extend/shrink to match W kw1 = k.*W+1; ub = sum(log(kw1))/2; % evaluate upper bound dW = zeros(n,1); dW(iw) = k./(2*kw1); m = min(n,N); % derivative w.r.t. W dE = zeros(N,1); dE(ie(1:m)) = W(1:m)./(N*2/n*kw1(1:m)); % deriative w.r.t. E % Approximate l = log(det(B))/2, where B = I + sqrt(W)*K*sqrt(W) and compute % the derivatives d l / d hyp w.r.t. covariance hyperparameters and % d l / d W the gradient w.r.t. the precision matrix W. % % Large-scale Log-det Computation through Stochastic Chebyshev Expansions % Insu Han, Dmitry Malioutov, Jinwoo Shin, ICML, 2015. % % Chebyshev polynomials T[0],..,T[d], where T[0](x)=1, T[1](x)=x, and % T[i+1](x)=2*x*T[i](x)-T[i-1](x). % dT[0](x)=0, dT[1](x)=1, dT[i+1](x)=2*T[i](x)+2*x*dT[i](x)-dT[i-1](x) % % W is the (diagonal) precision matrix represented by an nx1 vector % K is a function so that K(z) gives the mvm K*z % dK is a function so that dK(u,v) yields d trace(u'*K*v) / d hyp (dmvm = 2) % or so that dK(u) yields d K*u / d hyp (dmvm = 1) % % m is the number of random probe vectors, default values is 10 % d is the degree of the polynomial, default value is 15 % % maxit is the maximum number of iterations for the largest eigenvalue, % default value is 50 % emax is the maximum eigenvalue (in case it is known) % % seed is the seed for generating the random probe vectors % dmvm indicates derivative type, default is 2 % % Copyright (c) by Insu Han and Hannes Nickisch 2017-02-24. function [ldB2,dhyp,dW] = ldB2_cheby(W,K,dK, m,d, maxit,emax, seed,dmvm) sW = sqrt(W); n = numel(W); B = @(x) x + bsxfun(@times,sW, K(bsxfun(@times,sW,x) ));%B=I+sqrt(W)*K*sqrt(W) if nargin<6, maxit = 50; end, if nargin<9, dmvm = 2; end % set defaults if nargin<5, d = 15; end, if nargin<4, m = 10; end emaxconst = ~(nargin<7 || numel(emax)~=1); % given as a constant => no deriv if ~emaxconst % evaluate upper eigenvalue bound if n==1, emax = B(1); else opt.maxit = maxit; % number of iterations to estimate the largest eigval opt.issym = 1; opt.isreal = 1; % K is real symmetric and - of course - psd cstr = 'eigs(B,n,1,''lm'',opt)'; % compute largest eigenvalue if exist('evalc'), [txt,vmax,emax] = evalc(cstr); else [vmax,emax] = eval(cstr); end end if nargout>1 % compute d n*log(1+emax)/2 / d {hyp,W} r = sW.*vmax; dW = (K(r).*(r./W) + K(r).*(r./W))/2; % d emax / d W if dmvm==1, dhyp = dK(r)'*r; else dhyp = dK(r,r); end % d emax / d hyp dW = n/(2*(1+emax)) * dW; dhyp = n/(2*(1+emax)) * dhyp; % rescale % for the second term in ldB2 coming from the Chebyshev polynomial, we % ignore the dependency on the largest eigenvalue emax, which essentially % renders the derivative slightly incorrect end else dhyp = 0; dW = zeros(n,1); % init derivatives with zero end d = round(abs(d)); if d==0, error('We require d>0.'), end % emin = 1 a = 1+emax; del = 1-emax/a; ldB2 = n*log(a)/2; % scale eig(B) to [del,1-del] if emax>1e5 % del=1/(1+emax) fprintf('B has large condition number %1.2e\n',emax) fprintf('log(det(B))/2 is most likely overestimated\n') end s = 2/(emax-1); % compute scaling factor, s = 2/a/(1-2*del) A = @(x) s*B(x) - s*a/2*x; % apply scaling transform: [1,emax]->[-1,1] xk = cos(pi*((0:d)'+0.5)/(d+1)); % zeros of Tn(x) fk = log(((1-2*del)/2).*xk+0.5); % target function, [-1,1]->[del,1-del] Tk = ones(d+1,d+1); Tk(:,2) = xk; % init recursion for i=2:d, Tk(:,i+1) = 2*xk.*Tk(:,i) - Tk(:,i-1); end % evaluate polynomials c = 2/(d+1)*(Tk'*fk); c(1) = c(1)/2; % compute Chebyshev coefficients if nargin>7 && numel(seed)>0, randn('seed',seed), end % use seed V = sign(randn(n,m)); % bulk draw Rademacher variables p1 = [1; zeros(d,1)]; p2 = [0;1;zeros(d-1,1)]; % Chebyshev->usual coefficients p = c(1)*p1 + c(2)*p2; for i=2:d, p3 = [0;2*p2(1:d)]-p1; p = p + c(i+1)*p3; p1 = p2; p2 = p3; end if nargout<2 % no derivs requested; use bulk MVMs with A, one for each j=1..d % U = p(1)*V; AjV = V; for j=1:d, AjV = A(AjV); U = U + p(j+1)*AjV; end U1 = V; U2 = A(V); U = c(1)*U1 + c(2)*U2; % numerically more robust for i=2:d, U3 = 2*A(U2) - U1; U = U+c(i+1)*U3; U1 = U2; U2 = U3; end ldB2 = ldB2 + sum(sum(V.*U))/(2*m); % sum_{j=0..d} p(j+1)*trace(V'*A^j*U) elseif dmvm==1 % use MVM-based derivatives dA = @(x) s*bsxfun(@times,sW, dK(bsxfun(@times,sW,x) )); % derivative MVM if nargout>2 if norm(diff(W))>1e-12, error('Only isotropic dW supported.'), end dA = @(x) [dA(x), s*K(x)]; % augment to get deriv w.r.t. W=w*eye(n) end U = p(1)*V; AjV = V; dU = 0; for j=1:d if j==1, dAjV = dA(AjV); else dAjV = dA(AjV) + A(dAjV); end dU = dU + p(j+1)*dAjV; AjV = A(AjV); U = U + p(j+1)*AjV; end nh = size(dAjV,2)/size(AjV,2); dhyp = zeros(nh,1); for j=1:nh, dhyp(j) = sum(sum(V.*dU(:,(j-1)*m+(1:m))))/(2*m); end ldB2 = ldB2 + sum(sum(V.*U))/(2*m); % sum_{j=0..d} p(j+1)*trace(V'*B^j*U) if nargout>2, dW = dW + dhyp(nh)/n; nh = nh-1; dhyp = dhyp(1:nh); end else % deal with one random vector at a time Av = zeros(n,d+1); % all powers Av(:,j) = (A^j)*v for i=1:m v = V(:,i); Av(:,1) = v; for j=1:d, Av(:,j+1) = A(Av(:,j)); end ldB2 = ldB2 + (v'*Av*p)/(2*m); sWAv = bsxfun(@times,sW,Av); for j=1:d % p(1)*I + p(2)*A + p(3)*A^2 + .. + p(d+1)*A^d akj = s*p(j+1)/m; % equivalent to: k = 1:j; dhyp = dhyp + akj*dK(sWAv(:,j-k+1),sWAv(:,k)); % exploiting symmetry dK(a,b)=dK(b,a) reduces the computation to half k = 1:ceil((j-1)/2); dhyp = dhyp + akj *dK(sWAv(:,j-k+1),sWAv(:,k)); if mod(j,2) k = ceil(j/2); dhyp = dhyp + akj/2*dK(sWAv(:,j-k+1),sWAv(:,k)); end end if nargout>2, u = bsxfun(@times,1./sW,Av); w = K(sWAv); % precompute for j=1:d dWj = sum( u(:,j:-1:1).*w(:,1:j) + w(:,j:-1:1).*u(:,1:j), 2 ); dW = dW + s*p(j+1)/(4*m) * dWj; end end end end % Approximate l = log(det(B))/2, where B = I + sqrt(W)*K*sqrt(W) and % the derivatives d l / d hyp w.r.t. covariance hyperparameters and % d l / d W the gradient w.r.t. the (effective) precision matrix W. % % W is the (diagonal) precision matrix represented by an nx1 vector % K is a function so that K(z) gives the mvm K*z % dK is a function so that dK(u,v) yields d trace(u'*K*v) / d hyp (dmvm = 2) % or so that dK(u) yields d K*u / d hyp (dmvm = 1) % % m is the number of random probe vectors, default values is 10 % maxit is the number of Lanczos vectors, default value is 15 % % seed is the seed for generating the random probe vectors % dmvm indicates derivative type, default is 2 % % Copyright (c) by Kun Dong and Hannes Nickisch 2017-05-05. function [ld,dhyp,dW] = ldB2_lanczos(W,K,dK, m,maxit, seed,dmvm) n = numel(W); sW = sqrt(W); if nargin<6, seed = 42; end % massage parameters if nargin<5, maxit = 15; end, if nargin<4, m = 10; end % set default values arpack = maxit>0; maxit = abs(maxit); % sign encodes ARPACK versus plain if size(m,2)>1, V = m(1:n,:); m = size(m,2); else V = sign(randn(n,m)); end if nargin>5 && numel(seed)>0, randn('seed',seed), end % use seed if nargin<7, dmvm = 2; end, ld = 0; dhyp = 0; dW = 0; % set defaults sWm = @(v) bsxfun(@times,sW,v); % MVM with diag(sW) B = @(v) v + sWm(K(sWm(v))); if ~arpack [Qm,Tm] = lanczos_fast(B,n,V,maxit); end for j = 1:m if arpack [Q,T] = lanczos_arpack(B,V(:,j),maxit); % perform Lanczos with ARPACK else Q = squeeze(Qm(:,j,:)); T = squeeze(Tm(:,:,j)); end [Y,f] = eig(T); f = diag(f); ld = ld + n/(2*m) * (Y(1,:).^2*log(f)); % evaluate Stieltjes integral if nargout > 1 % go after derivatives v0 = sW.*V(:,j)/norm(V(:,j)); % avoid call to normc w0 = (Q*(T\[1; zeros(numel(f)-1,1)])).*sW; if dmvm==1, dhypj = dK(v0)'*w0; else dhypj = dK(v0,w0); end dhyp = dhyp + n/(2*m) * dhypj; if nargout>2, dW = dW + n/(2*m)*(K(v0).*(w0./W) + K(w0).*(v0./W))/2; end end end function [Q,T] = lanczos_full(B,v,d) % perform Lanczos with at most d MVMs alpha = zeros(d,1); beta = zeros(d,1); % for T v = v/norm(v,'fro'); n = numel(v); u = zeros(n,1); k = 1; Q = zeros(n,d); % mem for alg and res for k=1:d % do at most d iterations [u,v,alpha(k),beta(k)] = lanczos_step(u,v,B,Q(:,1:k-1)); Q(:,k) = u; % store Lanczos vectors for later usage if abs(beta(k))<1e-10, break, end % diagnose convergence end alpha = alpha(1:k); beta = beta(2:k); Q = Q(:,1:k); % truncate T = diag(alpha) + diag(beta,1 )+ diag(beta,-1); function [u,v,a,b] = lanczos_step(u,v,B,Q) % Lanczos step, $9.2.1 of Golub b = norm(v,'fro'); t = u; u = v/b; u = u - Q*(Q'*u); u = u/norm(u); % perform Gram-Schmidt r = B(u)-b*t; a = real(u'*r); v = r-a*u; function [Q,T] = lanczos_arpack(B,v,d) % perform Lanczos with at most d MVMs mv = ver('matlab'); % get the Matlab version if numel(mv)==0, error('No ARPACK reverse communication in Octave.'), end mv = str2double(mv.Version); old = mv<8;% Matlab 7.14=R2012a has old interface [junk,maxArraySize] = computer; m32 = maxArraySize==(2^31-1); % we have 32bit? if m32, intstr = 'int32'; else intstr = 'uint64'; end % according data types intconvert = @(x) feval(intstr,x); % init and allocate depending on # of bits n = length(v); v = bsxfun(@times,v,1./sqrt(sum(v.*v,1))); % avoid call to normc ido = intconvert(0); nev = intconvert(ceil((d+1)/2)); ncv = intconvert(d+1); ldv = intconvert(n); info = intconvert(1); lworkl = intconvert(int32(ncv)*(int32(ncv)+8)); iparam = zeros(11,1,intstr); ipntr = zeros(15,1,intstr); if exist('arpackc_reset'), arpackc_reset(); end iparam([1,3,7]) = [1,300,1]; tol = 1e-10; Q = zeros(n,ncv); workd = zeros(n,3); workl = zeros(lworkl,1); count = 0; while ido~=99 && count<=d count = count+1; if old arpackc('dsaupd',ido,'I',intconvert(n),'LM',nev,tol,v,... ncv,Q,ldv,iparam,ipntr,workd,workl,lworkl,info); else [ido,info] = arpackc('dsaupd',ido,'I',intconvert(n),'LM',nev,tol,v,... ncv,Q,ldv,iparam,ipntr,workd,workl,lworkl,info); end if info<0 error(message('ARPACKroutineError',aupdfun,full(double(info)))); end if ido == 1, inds = double(ipntr(1:3)); else inds = double(ipntr(1:2)); end rows = mod(inds-1,n)+1; cols = (inds-rows)/n+1; % referenced column of ipntr if ~all(rows==1), error(message('ipntrMismatchWorkdColumn',n)); end switch ido % reverse communication interface of ARPACK case -1, workd(:,cols(2)) = B(workd(:,cols(1))); case 1, workd(:,cols(3)) = workd(:,cols(1)); workd(:,cols(2)) = B(workd(:,cols(1))); case 2, workd(:,cols(2)) = workd(:,cols(1)); case 99 % converged otherwise, error(message('UnknownIdo')); end end ncv = int32(ncv); Q = Q(:,1:ncv-1); % extract results T = diag(workl(ncv+1:2*ncv-1))+diag(workl(2:ncv-1),1)+diag(workl(2:ncv-1),-1); function [Q,T] = lanczos_fast(Afun, n, Z, kmax) if nargin < 4, kmax = 150; end % initialization nZ = size(Z, 2); Q = zeros(n, nZ, kmax); alpha = zeros(kmax, nZ); beta = zeros(kmax, nZ); k = 0; qk = zeros(size(Z)); n1 = sqrt(sum(Z.^2)); r = bsxfun(@rdivide,Z,n1); b = ones(1,nZ); % Lanczos algorithm without reorthogonalization while k < kmax k = k+1; qkm1 = qk; qk = bsxfun(@rdivide,r,b); Q(:,:,k) = qk; Aqk = Afun(qk); alpha(k,:) = sum(qk.*Aqk); r = Aqk - bsxfun(@times,qk,alpha(k,:)) - bsxfun(@times,qkm1,b); b = sqrt(sum(r.^2)); beta(k,:) = b; end T = zeros(kmax,kmax,nZ); for j = 1:nZ T(:,:,j) = diag(alpha(:,j)) + diag(beta(1:end-1,j),1) + diag(beta(1:end-1,j),-1); end
github
kd383/GPML_SLD-master
covPER.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covPER.m
2,744
utf_8
1c61459cd15e6fc06d59b8e66bf447ac
function [K,dK] = covPER(mode, cov, hyp, x, z) % Periodic covariance function from an arbitrary covariance function k0 via % embedding IR^D into IC^D. % 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 covPER and hyp0 belongs to k0: % % hyp = [ hyp_p % hyp0 ] % % We offer three different modes: % 'eye': p = ones(D,1); hyp_p = []; % 'iso': p = exp(hyp_p)*ones(D,1); hyp_p = [log(p)]; % 'ard': p = exp(hyp_p); hyp_p = [log(p_1); ..; log(p_D)]; % % Note that for k0 = covSEiso and D = 1, a faster alternative is covPeriodic. % % Copyright (c) by Hannes Nickisch, 2016-04-25. % % See also COVFUNCTIONS.M. if nargin<2, error('We require a mode and a base covariance k0.'), end if isequal(mode,'ard'), ne = 'D'; elseif isequal(mode,'iso'), ne = '1'; elseif isequal(mode,'eye'), ne = '0'; else error('Parameter mode is either ''eye'', ''iso'' or ''ard''.'), end if nargin<4 % report number of parameters K = ['(',ne,'+',strrep(feval(cov{:}),'D','2*D'),')']; return end if nargin<5, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); ne = eval(ne); p = exp(hyp(1:ne)); if numel(p)==0, p = 1; end, p = p.*ones(D,1); % period par ux = u(x,p); uz = u(z,p); % apply the embedding u:IR^D->IR^2*D [K,dK0] = feval(cov{:},hyp(ne+1:end),ux,uz); % covariance function if nargout > 1 % directional derivative dK = @(Q) dirder(Q,dK0,p,mode,dg,xeqz,x,ux,z,uz,cov,hyp(ne+1:end)); end function [dhyp,dx] = dirder(Q,dK0,p,mode,dg,xeqz,x,ux,z,uz,cov,hypc) if dg % dx not required for dg so we assume zero dhyp = dK0(Q); dux = zeros(size(ux)); % only correct for stationary else [dhyp,dux] = dK0(Q); end if isequal(mode,'eye') dp = zeros(0,1); if nargout > 1, dx = duxdx(dux,ux,p); end else dx = duxdx(dux,ux,p); dp = -sum(dx.*x,1); if ~xeqz && ~dg [junk,dK0t] = feval(cov{:},hypc,uz,ux); [junk,duz] = dK0t(Q'); dp = dp - sum(duxdx(duz,uz,p).*z,1); end if isequal(mode,'iso'), dp = sum(dp); end end dhyp = [dp(:); dhyp]; function ux = u(x,p) % apply the embedding u:IR^D->IR^2*D if numel(x)==0 || ischar(x) ux = x; else ux = 2*pi*bsxfun(@times,x,1./p(:)'); ux = [sin(ux), cos(ux)]; end function dx = duxdx(du,ux,p) D = size(ux,2)/2; dx = bsxfun(@times, du(:,1:D).*ux(:,D+1:2*D), 2*pi./p(:)') ... -bsxfun(@times, du(:,D+1:2*D).*ux(:,1:D), 2*pi./p(:)');
github
kd383/GPML_SLD-master
covGE.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covGE.m
1,186
utf_8
0408e6341483b3f84ba8d55997213e13
function [K,dK] = covGE(mode, par, hyp, varargin) % Gamma Exponential covariance function. % The covariance function is parameterized as: % % k(x,z) = exp(-r^gamma), r = maha(x,z) % % where maha(x,z) is a Mahalanobis distance and gamma is the shape parameter % for the GE covariance. The hyperparameters are: % % hyp = [ hyp_maha % log(gamma/(2-gamma)) ] % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-04-27. % % See also COVFUNCTIONS.M. if nargin<1, mode = 'eye'; end, if nargin <2, par = []; end % default values if nargin<4, K = [covMaha(mode,par),'+1']; return, end gamma = 2/(1+exp(-hyp(end))); k = @(d2) exp(-d2.^(gamma/2)); dk = @(d2,k) -gamma/2*set_zero(k.*d2.^(gamma/2-1),d2==0); if nargout==2 [K,dKmaha,D2] = covMaha(mode,par,k,dk,hyp(1:end-1),varargin{:}); dK = @(Q) dirder(Q,K,D2,dKmaha,gamma); else K = covMaha(mode,par,k,dk,hyp(1:end-1),varargin{:}); end function [dhyp,dx] = dirder(Q,K,D2,dKmaha,gamma) if nargout==1 dhyp = dKmaha(Q); else [dhyp,dx] = dKmaha(Q); end Q = Q.*K; B = (gamma-2)*gamma/4 * D2.^(gamma/2) .* set_zero(log(D2),D2==0); dhyp = [dhyp; Q(:)'*B(:)]; function A = set_zero(A,I), A(I) = 0;
github
kd383/GPML_SLD-master
covLINone.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covLINone.m
1,478
utf_8
b9498a31ed150ecc1639a5dcb13d180b
function [K,dK] = covLINone(hyp, x, z) % Linear covariance function with a single hyperparameter. The covariance % function is parameterized as: % % k(x,z) = (x'*z + 1)/t^2; % % where the P matrix is t2 times the unit matrix. The second term plays the % role of the bias. The hyperparameter is: % % hyp = [ log(t) ] % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-04-23. % % See also COVFUNCTIONS.M. if nargin<2, K = '1'; return; end % report number of parameters if nargin<3, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode it2 = exp(-2*hyp); % t2 inverse % precompute inner products if dg % vector kxx K = sum(x.*x,2); else if xeqz % symmetric matrix Kxx K = x*x'; else % cross covariances Kxz K = x*z'; end end K = it2*(K+1); % covariances if nargout > 1, dK = @(Q) dirder(Q,K,x,z,it2,xeqz,dg); end % dir derivative function [dhyp,dx] = dirder(Q,K,x,z,it2,xeqz,dg) dhyp = -2*Q(:)'*K(:); if nargout>1 if dg dx = zeros(size(x)); else if xeqz dx = it2*(Q*x+Q'*x); else dx = it2*Q*z; end end end
github
kd383/GPML_SLD-master
covFBM.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covFBM.m
2,452
utf_8
557d97477e58c30d11b640492b88b785
function [K,dK] = covFBM(hyp, x, z) % Fractional Brownian motion covariance function with Hurst index h from (0,1). % % For h=1/2, this is the Wiener covariance, for h>1/2, the increments are % positively correlated and for h<1/2 the increments are negatively correlated. % % The covariance function -- given that x,z>=0 -- is specified as: % % k(x,z) = sf^2 / 2 * ( |x|^(2h) + |z|^(2h) - |x-z|^(2h) ), where % % sf^2 is the signal variance. % % The hyperparameters are: % % hyp = [ log(sf) % -log(1/h-1) ] % % For more help on design of covariance functions, try "help covFunctions". % % Copyright (c) by Hannes Nickisch, 2017-01-27. % % See also COVW.M, COVFUNCTIONS.M. if nargin<2, K = '2'; return; end % report number of parameters if nargin<3, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); ox = ones(n,1); if D~=1, error('Covariance is defined for 1d data only.'), end if any(x<0) || (~xeqz && any(z<0)) error('Covariance is defined for nonnegative data only.') end sf = exp(hyp(1)); h = 1/(1+exp(-hyp(2))); if dg % vector kxx X = x; Z = x; else if xeqz % symmetric matrix Kxx X = x*ox'; Z = X'; else % cross covariances Kxz oz = ones(size(z,1),1); X = x*oz'; Z = ox*z'; end end K = sf^2 * (abs(X).^(2*h) + abs(Z).^(2*h) - abs(X-Z).^(2*h))/2; % signal var if nargout > 1 dK = @(Q) dirder(Q,K,X,Z,h,sf,dg,xeqz); % directional deriv end function [dhyp,dx] = dirder(Q,K,X,Z,h,sf,dg,xeqz) Ax = abs(X); Az = abs(Z); Ad = abs(X-Z); R = sf^2 * ( fixnan(log(Ax).*Ax.^(2*h)) + fixnan(log(Az).*Az.^(2*h)) ... - fixnan(log(Ad).*Ad.^(2*h)) ); dhyp = [2*(Q(:)'*K(:)); (Q(:)'*R(:))*(h-h^2)]; % hyperparameters if nargout > 1 if dg dx = zeros(size(x)); else if xeqz R = sign(X).*Ax.^(2*h-1) - sign(X-Z).*Ad.^(2*h-1); dx = 2*h*sum(R.*(Q+Q'),2); else R = sign(X).*Ax.^(2*h-1) - sign(X-Z).*Ad.^(2*h-1); dx = 2*h*sum(R.*Q,2); end end dx = sf^2*dx/2; % signal variance end function B = fixnan(A), B = A; B(isnan(B)) = 0; % replace NaN by 0
github
kd383/GPML_SLD-master
covADD.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covADD.m
4,141
utf_8
f58af163e496f6be948dbfc1d9118972
function [K,dK] = covADD(cov, hyp, x, z) % Additive covariance function using 1d base covariance functions % cov_d(x_d,z_d;hyp_d) with individual hyperparameters hyp_d, d=1..D. % % k (x,z) = \sum_{r \in R} sf^2_r k_r(x,z), where 1<=r<=D and % k_r(x,z) = \sum_{|I|=r} \prod_{i \in I} cov_i(x_i,z_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=R(1),..,R(end) where 1<=r<=D. % % Usage: covADD({[1,3,4],cov}, ...) or % covADD({[1,3,4],cov_1,..,cov_D}, ...). % % 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, 2017-02-21. % multiple covariance support contributed by Truong X. Nghiem % % See also COVFUNCTIONS.M. R = fix(cov{1}); % only positive integers are allowed if min(R)<1, error('only positive R up to D allowed'), end nr = numel(R); % number of different degrees of interaction nc = numel(cov)-1; D = 1; % number of provided covariances, D for indiv. for j=1:nc, if ~iscell(cov{j+1}), cov{j+1} = {cov{j+1}}; end, end if nc==1, nh = eval(feval(cov{2}{:})); % no of hypers per individual covariance else nh = zeros(nc,1); for j=1:nc, nh(j) = eval(feval(cov{j+1}{:})); end, end if nargin<3 % report number of hyper parameters if nc==1, K = ['D*', int2str(nh), '+', int2str(nr)]; else K = ['(',int2str(nh(1))]; for ii=2:nc, K = [K,'+',int2str(nh(ii))]; end K = [K, ')+', int2str(nr)]; end return end if nargin<4, z = []; end % make sure, z exists [n,D] = size(x); % dimensionality if nc==1, nh = ones(D,1)*nh; cov = [cov(1),repmat(cov(2),1,D)]; end nch = sum(nh); % total number of cov hypers sf2 = exp( 2*hyp(nch+(1:nr)) ); % signal variances of individual degrees [Kd,dKd] = Kdim(cov(2:end),nh,hyp(1:nch),x,z); % eval dimensionwise 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 if nargout > 1 dK = @(Q) dirder(Q,Kd,dKd,EE,R,sf2); end function [dhyp,dx] = dirder(Q,Kd,dKd,EE,R,sf2) D = numel(dKd); n = size(Q,1); nr = numel(R); dhyp = zeros(0,1); if nargout > 1, dx = zeros(n,D); end % allocate if required for j=1:D % 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, the j-th elementary % covariance depends on the hyperparameter batch hyp(j) and inputs x(:,j) E = elsympol(Kd(:,:,[1:j-1,j+1:D]),max(R)-1); % R-1th elementary sym polyn Qj = 0; for ii=1:nr, Qj = Qj + sf2(ii)*E(:,:,R(ii)); end % sf2 weighted sum if nargout > 1, [dhypj,dxj] = dKd{j}(Qj.*Q); dx(:,j) = dxj; else dhypj = dKd{j}(Qj.*Q); end, dhyp = [dhyp; dhypj]; end dhyp = [dhyp; 2*squeeze(sum(sum(bsxfun(@times,EE(:,:,R+1),Q),1),2)).*sf2]; % evaluate dimensionwise covariances K function [K,dK] = Kdim(cov,nh,hyp,x,z) [n,D] = size(x); % dimensionality 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 dK = cell(D,1); for d=1:D hyp_d = hyp(sum(nh(1:d-1))+(1:nh(d))); % hyperparamter of dimension d if dg [K(:,:,d),dK{d}] = feval(cov{d}{:},hyp_d,x(:,d),'diag'); else if xeqz [K(:,:,d),dK{d}] = feval(cov{d}{:},hyp_d,x(:,d)); else [K(:,:,d),dK{d}] = feval(cov{d}{:},hyp_d,x(:,d),z(:,d)); end end end
github
kd383/GPML_SLD-master
covProd.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covProd.m
3,136
utf_8
1f0519c767c2410e29139c94fa58b031
function [K,dK] = covProd(cov, hyp, x, z) % covProd - compose a covariance function as the product of other covariance % functions. This function doesn't actually compute very much on its own, it % merely does some bookkeeping, and calls other covariance functions to do the % actual work. % % Note that cov = {cov1, cov2, .., false} turns of covariance matrix caching. % This option slows down the computations but can help out if you products of % many huge matrices lead to working memory shortage. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-04-18. % % See also COVFUNCTIONS.M. if isempty(cov), error('We require at least one factor.'), end if isnumeric(cov{end}) || islogical(cov{end}) % detect whether to cache cache = ~isequal(0,cov{end}) && ~isequal(false,cov{end}); cov = cov(1:end-1); % chop off last element from cov else cache = true; end nc = numel(cov); % number of terms in covariance function for ii = 1:nc % iterate over covariance functions f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary j(ii) = cellstr(feval(f{:})); % collect number hypers end if nargin<3 % report number of parameters K = char(j(1)); for ii=2:nc, K = [K, '+', char(j(ii))]; end, return end if nargin<4, z = []; end % make sure, z exists [n,D] = size(x); nh = numel(hyp); % number of hyperparameters v = []; % v vector indicates to which covariance parameters belong for ii = 1:nc, v = [v repmat(ii, 1, eval(char(j(ii))))]; end K = 1; Ki = cell(nc,1); dKi = cell(nc,1); % init K for ii = 1:nc % iteration over factor functions f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary if cache if nargin>1 [Ki{ii},dKi{ii}] = feval(f{:}, hyp(v==ii), x, z); Kii = Ki{ii}; % track else Ki{ii} = feval(f{:}, hyp(v==ii), x, z); Kii = Ki{ii}; end else Kii = feval(f{:}, hyp(v==ii), x, z); end K = K .* Kii; % accumulate covariances end dK = @(Q) dirder(Q,Ki,dKi,v,nc,nh,cov,hyp,x,z,cache); % directional derivative function [dhyp,dx] = dirder(Q,Ki,dKi,v,nc,nh,cov,hyp,x,z,cache) dhyp = zeros(nh,1); dx = 0; for ii = 1:nc Qi = Q; for jj=1:nc % accumulate if ii~=jj if cache Qi = Qi .* Ki{jj}; else f = cov(jj); if iscell(f{:}), f = f{:}; end % expand cell if necessary Qi = Qi .* feval(f{:}, hyp(v==jj), x, z); end end end if cache dKii = dKi{ii}; else f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell if necessary [junk,dKii] = feval(f{:}, hyp(v==ii), x, z); end if nargout==1 dhyp(v==ii,1) = dKii(Qi); else [dhyp(v==ii,1),dxi] = dKii(Qi); dx = dx+dxi; end end
github
kd383/GPML_SLD-master
covRQiso.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covRQiso.m
1,165
utf_8
662fd9158e87d9e809e77de537bbaca9
function varargout = covRQiso(varargin) % Wrapper for Rational Quadratic covariance function covRQ.m. % % Rational Quadratic covariance function with isotropic distance measure. The % covariance function is parameterized as: % % k(x,z) = sf^2 * [1 + (x-z)'*inv(P)*(x-z)/(2*alpha)]^(-alpha) % % where the P matrix is ell^2 times the unit matrix, sf2 is the signal % variance and alpha is the shape parameter for the RQ covariance. The % hyperparameters are: % % hyp = [ log(ell) % log(sf) % log(alpha) ] % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-10-01. % % See also covRQ.m. varargout = cell(max(1,nargout),1); if nargin>0 % restore old hyper parameter order hyp = varargin{1}; if numel(hyp)>2, varargin{1} = hyp([1:end-2,end,end-1]); end end [varargout{:}] = covScale({'covRQ','iso',[]},varargin{:}); if nargout>1 % restore old hyper parameter order o2 = varargout{2}; varargout{2} = @(Q) dirder(Q,o2); end function [dKdhyp,dKdx] = dirder(Q,dK) if nargout>1, [dKdhyp,dKdx] = dK(Q); else dKdhyp = dK(Q); end dKdhyp = dKdhyp([1:end-2,end,end-1]);
github
kd383/GPML_SLD-master
covMatern.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covMatern.m
3,060
utf_8
ca45c5dd70fb047a931ac0296b64ad16
function varargout = covMatern(mode, par, d, varargin) % Matern covariance function with nu = d/2 and isotropic distance measure. For % d=1 the function is also known as the exponential covariance function or the % Ornstein-Uhlenbeck covariance in 1d. The covariance function is: % % k(x,z) = f( sqrt(d)*r ) * exp(-sqrt(d)*r) % % with f(t)=1 for d=1, f(t)=1+t for d=3, f(t)=1+t+t^2/3 for d=5 and % f(t)=1+t+2*t^2/5+t^3/15 for d=7. % % The covariance function can also be expressed for non-integer d. % % k(x,z) = 2^(1-nu)/gamma(nu) * s^nu * besselk(nu,s), s = sqrt(2*nu)*r % % Note that for d->oo the covariance converges to the squared exponential. % % Here r is the Mahalanobis distance sqrt(maha(x,z)). The function takes a % "mode" parameter, which specifies precisely the Mahalanobis distance used, see % covMaha. The function returns either the number of hyperparameters (with less % than 3 input arguments) or it returns a covariance matrix and (optionally) a % derivative function. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-12-14. % % See also covSE.m, covMaha.m. if nargin < 1, error('Mode cannot be empty.'); end % no default value if nargin < 2, par = []; end % default varargout = cell(max(1, nargout), 1); % allocate mem for output if nargin < 5, varargout{1} = covMaha(mode,par); return, end if any(d==[1,3,5,7]) switch d % df(t) = (f(t)-f'(t))/t case 1, f = @(t) 1; df = @(t) 1./t; case 3, f = @(t) 1+t; df = @(t) 1; case 5, f = @(t) 1+t.*(1+t/3); df = @(t) (1+t)/3; case 7, f = @(t) 1+t.*(1+t.*(6+t)/15); df = @(t) (1+t+t.^2/3)/5; end m = @(t,f) f(t).*exp(-t); dm = @(t,f) df(t).*exp(-t); k = @(d2) m(sqrt(d*d2),f); if d==1 dk = @(d2,k) set_zero( -dm(sqrt( d2),f)/2, d2==0 ); % fix limit case d2->0 else dk = @(d2,k) -dm(sqrt(d*d2),f)*d/2; end else % use non-integer mode k = @(d2) psi(d2,d/2); dk = @(d2,k) dpsi(d2,k,d/2); end [varargout{:}] = covMaha(mode, par, k, dk, varargin{:}); function A = set_zero(A,I), A(I) = 0; function k = psi(d2,nu) % = 2^(1-nu)/gamma(nu) * r^nu*besselk(nu,r) book Eq 4.14 c = (1-nu)*log(2)-gammaln(nu); % evaluate 2^(1-nu)/gamma(nu) in log domain r = sqrt(2*nu*d2); k = exp(c+nu*log(r)).*besselk(nu,r); k(r<1e-7) = 1; % fix lim_r->0, see Abramowitz&Stegun 9.6.9 i = isnan(k) | isinf(k); % detect strange behavior if any(i), k(i) = exp(-d2(i)/2); end % fix limit_nu->oo covSE function dk = dpsi(d2,k,nu) r = sqrt(2*nu*d2); dk = -nu*0.5^nu/gamma(nu)*r.^(nu-2).*... (r.*besselk(nu-1,r)-2*nu*besselk(nu,r)+r.*besselk(nu+1,r)); i = isnan(dk) | isinf(dk); % detect strange behavior if any(i), dk(i) = (-1/2)*k(i); end % fix limit_nu->oo covSE
github
kd383/GPML_SLD-master
covRQ.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covRQ.m
1,181
utf_8
d112eee5d6ba568af6d5f1ee22849f3f
function [K,dK] = covRQ(mode, par, hyp, varargin) % Rational Quadratic covariance function. % The covariance function is parameterized as: % % k(x,z) = [1 + maha(x,z)/(2*alpha)]^(-alpha) % % where maha(x,z) is a Mahalanobis distance and alpha is the shape parameter % for the RQ covariance. The hyperparameters are: % % hyp = [ hyp_maha % log(alpha) ] % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-05-23. % % See also COVFUNCTIONS.M. if nargin < 1, error('Mode cannot be empty.'); end % no default if nargin < 2, par = []; end % default if nargin<4, K = [covMaha(mode,par),'+1']; return, end alpha = exp(hyp(end)); k = @(d2) (1+0.5*d2/alpha).^(-alpha); dk = @(d2,k) -k./(2+d2/alpha); if nargout==2 [K,dKmaha,D2] = covMaha(mode,par,k,dk,hyp(1:end-1),varargin{:}); dK = @(Q) dirder(Q,K,D2,dKmaha,alpha); else K = covMaha(mode,par,k,dk,hyp(1:end-1),varargin{:}); end function [dhyp,dx] = dirder(Q,K,D2,dKmaha,alpha) if nargout==1 dhyp = dKmaha(Q); else [dhyp,dx] = dKmaha(Q); end Q = Q.*K; B = 1+0.5*D2/alpha; dhyp = [dhyp; sum(sum( Q.*(0.5*D2./B-alpha*log(B)) ))];
github
kd383/GPML_SLD-master
covDot.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covDot.m
4,125
utf_8
389b9cdeecc1b3bf4d9b780e011f1a92
function [K,dK,S] = covDot(mode, par, k, dk, hyp, x, z) % Dot product-based covariance function. The covariance function is % parameterized as: % % k(x,z) = k(s), s = dot(x,z) = x'*inv(P)*z % % where the matrix P is the metric. % % Parameters: % 1) mode,par: % We offer different modes (mode) with their respective parameters (par): % mode = par = inv(P) = hyp = % 'eye' [] eye(D) [] % 'iso' [] ell^2*eye(D) [log(ell)] % 'ard' [] diag(ell.^2) [log(ell_1); ..; log(ell_D)] % 'proj' d L'*L [L_11; L_21; ..; L_dD] % 'fact' d L'*L + diag(f) [L_11; L_21; ..; L_dD; log(f_1); ..; log(f_D)] % % 2) k,dk: % The functional form of the covariance is governed by two functions: % k: s -> k(x,z), s = dot(x,z) = x'*inv(P)*z % dk: s,k(x,z) -> d k(x,z) / d s % For example, the linear covariance uses % k = @(s) (c+s).^d; dk = @(s) d*(c+s).^(d-1); % Note that not all functions k,dk give rise to a valid i.e. positive % semidefinite covariance function k(x,z). % % 3) hyp,x,z: % These input parameters follow the usual covariance function interface. For the % composition of hyp, see 1). % % 4) K,dK: % See the usual covariance function interface. % % For more help on design of covariance functions, try "help covFunctions". % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2017-09-26. % % See also COVFUNCTIONS.M. if nargin<1, mode = 'eye'; end, if nargin <2, par = []; end % default values mode_list = '''eye'', ''iso'', ''ard'', ''proj'', or ''fact''.'; switch mode case 'eye', ne = '0'; case 'iso', ne = '1'; case 'ard', ne = 'D'; case 'proj', ne = [num2str(par),'*D']; case 'fact', ne = [num2str(par),'*D+D']; otherwise, error('Parameter mode is either %s.',mode_list) end if nargin<6, K = ne; return; end % report number of parameters if nargin<7, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % sort out different modes [n,D] = size(x); ne = eval(ne); % dimensions hyp = hyp(:); % make sure hyp is a column vector if numel(hyp)~=ne, error('Wrong number of hyperparameters'), end switch mode % mvm with metric A=inv(P) case 'eye', A = @(x) x; dAdhyp = @(T) zeros(0,1); case 'iso', iell2 = exp(-2*hyp); A = @(x) x*iell2; dAdhyp = @(T) -2*iell2*trace(T); case 'ard', iell2 = exp(-2*hyp); A = @(x) bsxfun(@times,x,iell2'); dAdhyp = @(T) -2*iell2.*diag(T); case 'proj', d = par; L = reshape(hyp,d,D); A = @(x) (x*L')*L; dAdhyp = @(T) reshape(L*(T+T'),d*D,1); case 'fact', d = par; L = reshape(hyp(1:d*D),d,D); f = exp(hyp(d*D+1:end)); A = @(x) (x*L')*L + bsxfun(@times,x,f'); dAdhyp = @(T)[reshape(L*(T+T'),d*D,1); f.*diag(T)]; end % compute dot product if dg % vector sxx Az = A(x); z = x; S = sum(x.*Az,2); else if xeqz % symmetric matrix Sxx Az = A(x); z = x; else % cross terms Sxz Az = A(z); end S = x*Az'; end K = k(S); % covariance if nargout > 1 dK = @(Q) dirder(Q,S,dk,x,Az,z,dg,xeqz,dAdhyp,mode); % dir hyper derivative end function [dhyp,dx] = dirder(Q,S,dk,x,Az,z,dg,xeqz,dAdhyp,mode) R = dk(S).*Q; switch mode case 'eye', dhyp = zeros(0,1); % fast shortcuts case 'iso', dhyp = -2*R(:)'*S(:); case 'ard' if dg dhyp = -2*sum(x.*bsxfun(@times,R,Az),1)'; else dhyp = -2*sum(x.*(R*Az),1)'; end otherwise % generic computation if dg, T = bsxfun(@times,R,z); else T = R*z; end, T = x'*T; dhyp = dAdhyp(T); end if nargout > 1 if xeqz, dx = R*Az+R'*Az; else dx = R*Az; end end
github
kd383/GPML_SLD-master
covGabor.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covGabor.m
2,950
utf_8
95522109b2cb6e8dc9f3f68134433e3a
function [K,dK] = covGabor(mode, hyp, x, z) % Gabor covariance function with length scale ell and period p. The % covariance function is parameterized as: % % k(x,z) = h(x-z), h(t) = exp(-sum(t.^2./(2*ell.^2)))*cos(2*pi*sum(t./p)). % % The hyperparameters are: % % hyp = [ hyp_ell % hyp_p ] % % We offer three different modes: % 'eye': ell = ones(D,1); p = ones(D,1); % 'iso': ell = exp(hyp_ell)*ones(D,1); p = exp(hyp_p)*ones(D,1); % 'ard': ell = exp(hyp_ell) ; p = exp(hyp_p) ; % % Note that covSM implements a weighted sum of Gabor covariance functions, but % using an alternative (spectral) parameterization. % % For more help on design of covariance functions, try "help covFunctions". % % Copyright (c) by Hannes Nickisch, 2016-05-03. % % See also COVFUNCTIONS.M, COVGABORARD.M, COVSM.M. if nargin<1, error('We require a mode.'), end if isequal(mode,'ard'), np = 'D'; elseif isequal(mode,'iso'), np = '1'; elseif isequal(mode,'eye'), np = '0'; else error('Parameter mode is either ''eye'', ''iso'' or ''ard''.'), end if nargin<3, K = ['(2*',np,')']; return, end % report number of parameters if nargin<4, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); np = eval(np); % dimensionality p = exp(hyp(np+1:2*np)); if numel(p)==0, p = 1; end, p = p.*ones(D,1); % period [Kse,dKse] = covSE(mode,[],hyp(1:np),x,z); % squared exponential base covariance Dp = zeros(size(Kse)); % init sum(t)/p computation if ~dg if xeqz % symmetric matrix Kxx for d=1:D, Dp = Dp + bsxfun(@minus,x(:,d),x(:,d)')/p(d); end else % cross covariances Kxz for d=1:D, Dp = Dp + bsxfun(@minus,x(:,d),z(:,d)')/p(d); end end end C = cos(2*pi*Dp); K = Kse .* C; % covariance if nargout > 1 % directional derivative dK = @(Q) dirder(Q,C,Dp,Kse,dKse,np,dg,xeqz,x,z,D,p,mode); end function [dhyp,dx] = dirder(Q,C,Dp,Kse,dKse,np,dg,xeqz,x,z,D,p,mode) dhyp = zeros(2*np,1); % allocate memory if nargout > 1 [dhyp(1:np),dx] = dKse(Q.*C); else dhyp(1:np) = dKse(Q.*C); end if ~dg Q = Q .* Kse .* -sin(2*pi*Dp)*2*pi; if isequal(mode,'ard') for d=1:D if xeqz Dd = bsxfun(@minus,x(:,d),x(:,d)'); else Dd = bsxfun(@minus,x(:,d),z(:,d)'); end dhyp(np+d) = -(Q(:)'*Dd(:))/p(d); end elseif isequal(mode,'iso') dhyp(np+1) = -(Q(:)'*Dp(:)); end if nargout > 1 if xeqz dx = dx + (sum(Q,2)-sum(Q,1)')*(1./p)'; else dx = dx + sum(Q,2)*(1./p)'; end end end
github
kd383/GPML_SLD-master
covMask.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covMask.m
2,077
utf_8
fbb73ed86a404c471718a7040f0d4ac6
function [K,dK] = covMask(cov, hyp, x, z) % Apply a covariance function to a subset of the dimensions only. The subset can % either be specified by a 0/1 mask by a boolean mask or by an index set. % % This function doesn't actually compute very much on its own, it merely does % some bookkeeping, and calls another covariance function to do the actual work. % % The function computes: % k(x,z) = k0(x(mask),z(mask)) % Example: % k0 = {@covSEiso}; % msk = [1,3,7]; % k = {@covMask,{msk,k0{:}}}; % % The function was suggested by Iain Murray, 2010-02-18 and is based on an % earlier implementation of his dating back to 2009-06-16. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-11-14. % % See also COVFUNCTIONS.M. mask = fix(cov{1}(:)); % either a binary mask or an index set cov = cov(2); % covariance function to be masked if iscell(cov{:}), cov = cov{:}; end % properly unwrap nested cell arrays nh_string = feval(cov{:}); % number of hyperparameters of the full covariance if max(mask)<2 && length(mask)>1, mask = find(mask); end % convert 1/0->index D = length(mask); % masked dimension if nargin<3, K = num2str(eval(nh_string)); return, end % number of parameters if nargin<4, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode if eval(nh_string)~=length(hyp) % check hyperparameters error('number of hyperparameters does not match size of masked data') end xm = x(:,mask); if ~dg && ~xeqz, zm = z(:,mask); else zm = z; end if nargout>1 [K,dK] = feval(cov{:}, hyp, xm, zm); dK = @(Q) dirder(Q,dK,x,mask); else K = feval(cov{:}, hyp, xm, zm); end function [dhyp,dx] = dirder(Q,dK,x,mask) if nargout>1 [dhyp,dxm] = dK(Q); n = size(x,1); subs = [repmat((1:n)',length(mask),1), reshape(repmat(mask(:)',n,1),[],1)]; dx = accumarray(subs,dxm(:),size(x)); else dhyp = dK(Q); end
github
kd383/GPML_SLD-master
covSum.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covSum.m
2,619
utf_8
dd217e57b3859a67a2ed06b93ce7b5da
function [K,dK] = covSum(cov, hyp, x, z) % covSum - compose a covariance function as the sum of other covariance % functions. This function doesn't actually compute very much on its own, it % merely does some bookkeeping, and calls other covariance functions to do the % actual work. % % Note that cov = {cov1, cov2, .., false} turns of covariance matrix caching. % This option slows down the computations but can help out if you sums of % many huge matrices lead to working memory shortage. % % Copyright (c) by Carl Edward Rasmussen & Hannes Nickisch 2016-04-18. % % See also COVFUNCTIONS.M. if isempty(cov), error('We require at least one summand.'), end if isnumeric(cov{end}) || islogical(cov{end}) % detect whether to cache cache = ~isequal(0,cov{end}) && ~isequal(false,cov{end}); cov = cov(1:end-1); % chop off last element from cov else cache = true; end nc = numel(cov); % number of terms in covariance function for ii = 1:nc % iterate over covariance functions f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary j(ii) = cellstr(feval(f{:})); % collect number hypers end if nargin<3 % report number of parameters K = char(j(1)); for ii=2:nc, K = [K, '+', char(j(ii))]; end, return end if nargin<4, z = []; end % make sure, z exists [n,D] = size(x); v = []; % v vector indicates to which covariance parameters belong for ii = 1:nc, v = [v repmat(ii, 1, eval(char(j(ii))))]; end K = 0; dKi = cell(nc,1); % init K for ii = 1:nc % iteration over summand functions f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary if nargout>1 && cache [Kii,dKi{ii}] = feval(f{:}, hyp(v==ii), x, z); % keep track else Kii = feval(f{:}, hyp(v==ii), x, z); end K = K + Kii; % accumulate covariances end dK = @(Q) dirder(Q,dKi,v,nc,cov,hyp,x,z,cache); % directional derivative function [dhyp,dx] = dirder(Q,dKi,v,nc,cov,hyp,x,z,cache) dhyp = zeros(size(v,2),1); dx = 0; for ii = 1:nc if cache dKii = dKi{ii}; else f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell if necessary [junk,dKii] = feval(f{:}, hyp(v==ii), x, z); end if nargout > 1 [dhyp(v==ii,1),dxi] = dKii(Q); dx = dx+dxi; else dhyp(v==ii,1) = dKii(Q); end end
github
kd383/GPML_SLD-master
covEye.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covEye.m
1,506
utf_8
74ff8cf22ddc7da30f6541ca77daebbd
function [K,dK] = covEye(hyp, x, z) % Independent covariance function, i.e. "white noise", with unit variance. % The covariance function is specified as: % % k(x^p,x^q) = \delta(p,q) % % \delta(p,q) is a Kronecker delta function which is 1 iff p=q and zero % otherwise in mode 1). % In cross covariance mode 2) two data points x_p and z_q are considered equal % if their difference norm |x_p-z_q| is less than eps, the machine precision. % The hyperparameters are: % % hyp = [ ] % % For more help on design of covariance functions, try "help covFunctions". % % Copyright (c) by Hannes Nickisch, 2016-04-18. % % See also COVFUNCTIONS.M. tol = eps; % threshold on the norm when two vectors are considered to be equal if nargin<2, K = '0'; return; end % report number of parameters if nargin<3, z = []; end % make sure, z exists dg = strcmp(z,'diag'); % determine mode n = size(x,1); if dg % vector kxx K = ones(n,1); else if isempty(z) % symmetric matrix Kxx K = eye(n); else % cross covariances Kxz K = double(sq_dist(x',z')<tol*tol); end end if nargout > 1 dK = @(Q) dirder(Q,x); % directional hyper derivative end function [dhyp,dx] = dirder(Q,x) dhyp = zeros(0,1); if nargout > 1, dx = zeros(size(x)); end
github
kd383/GPML_SLD-master
covCos.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covCos.m
1,642
utf_8
fffb37510851e1faf2c666ca437a6a7b
function [K,dK] = covCos(hyp, x, z) % Stationary covariance function for a sinusoid with period p in 1d: % % k(x,z) = sf^2*cos(2*pi*(x-z)/p) % % where the hyperparameters are: % % hyp = [ log(p) % log(sf) ] % % Note that covPeriodicNoDC converges to covCos as ell goes to infinity. % % Copyright (c) by James Robert Lloyd and Hannes Nickisch, 2016-11-05. % % See also COVFUNCTIONS.M, COVPERIODICNODC.M. if nargin<2, K = '2'; return; end % report number of parameters if nargin<3, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); if D~=1, error('Covariance is defined for 1d data only.'), end p = exp(hyp(1)); sf2 = exp(2*hyp(2)); % precompute deviations and exploit symmetry of cos if dg % vector txx T = zeros(size(x,1),1); else if xeqz % symmetric matrix Txx T = 2*pi/p*bsxfun(@plus,x,-x'); else % cross covariances Txz T = 2*pi/p*bsxfun(@plus,x,-z'); end end K = sf2*cos(T); % covariances if nargout > 1 dK = @(Q) dirder(Q,K,T,x,p,sf2,dg,xeqz); end function [dhyp,dx] = dirder(Q,K,T,x,p,sf2,dg,xeqz) dhyp = [sf2*(sin(T(:)).*T(:))'*Q(:); 2*Q(:)'*K(:)]; if nargout > 1 R = -sf2*pi/p * Q .* sin(T); if dg dx = zeros(size(x)); else if xeqz dx = 2*(sum(R,2)-sum(R,1)'); else dx = 2*sum(R,2); end end end
github
kd383/GPML_SLD-master
covDiscrete.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covDiscrete.m
2,444
utf_8
1a59b16bbcb28d2299847efdfd9f941b
function [K,dK] = covDiscrete(s, hyp, x, z) % Covariance function for discrete inputs. Given a function defined on the % integers 1,2,3,..,s, the covariance function is parameterized as: % % k(x,z) = K_{xz}, % % where K is a matrix of size (s x s). % % This implementation assumes that the inputs x and z are given as integers % between 1 and s, which simply index the matrix K. % % The hyperparameters specify the upper-triangular part of the Cholesky factor % of K, where the (positive) diagonal elements are specified by their logarithm. % If L = chol(K), so K = L'*L, then the hyperparameters are: % % hyp = [ log(L_11) % L_21 % log(L_22) % L_31 % L_32 % .. % log(L_ss) ] % % The hyperparameters hyp can be generated from K using: % L = chol(K); L(1:(s+1):end) = log(diag(L)); % hyp = L(triu(true(s))); % % The covariance matrix K is obtained from the hyperparameters hyp by: % L = zeros(s); L(triu(true(s))) = hyp(:); % L(1:(s+1):end) = exp(diag(L)); K = L'*L; % % This parametrization allows unconstrained optimization of K. % % For more help on design of covariance functions, try "help covFunctions". % % Copyright (c) by Roman Garnett, 2016-04-18. % % See also MEANDISCRETE.M, COVFUNCTIONS.M. if nargin==0, error('s must be specified.'), end % check for dimension if nargin<3, K = num2str(s*(s+1)/2); return; end % report number of parameters if nargin<4, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode if xeqz, z = x; end % make sure we have a valid z L = zeros(s); L(triu(true(s))) = hyp(:); % build Cholesky factor L(1:(s+1):end) = exp(diag(L)); A = L'*L; % A is a placeholder for K to avoid a name clash with the return arg if dg K = A(sub2ind(size(A),fix(x),fix(x))); else K = A(fix(x),fix(z)); end if nargout > 1 dK = @(Q) dirder(Q,s,L,x,z,dg); % directional hyper derivative end function [dhyp,dx] = dirder(Q,s,L,x,z,dg) nx = numel(x); Ix = sparse(fix(x),1:nx,ones(nx,1),s,nx); % K==Ix'*L'*L*Iz if dg B = Ix*diag(Q)*Ix'; else nz = numel(z); Iz = sparse(fix(z),1:nz,ones(nz,1),s,nz); B = Iz*Q'*Ix'; end B = L*(B+B'); B(1:(s+1):end) = diag(B).*diag(L); % fix exp on diagonal dhyp = B(triu(true(s))); if nargout > 1, dx = zeros(size(x)); end
github
kd383/GPML_SLD-master
covULL.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covULL.m
2,045
utf_8
cee0f7f68e01ba6bdef5fbb1755e674b
function [K,dK] = covULL(hyp, x, z) % Stationary covariance function for an underdamped linear Langevin process % as obtained by filtering white noise through an underdamped 2nd order system % m * f''(x) + c * f'(x) + k * f(x) = N(0,sf^2). % % k(t) = a^2*exp(-mu*t) * ( sin(omega*t)/omega + cos(omega*t)/mu ), % where t = abs(x-z), and % mu = c/(2*m), omega = sqrt(k/m-mu^2), a = sf/(2*sqrt(m*k)) % % See https://en.wikipedia.org/wiki/Harmonic_oscillator % % where the hyperparameters are: % % hyp = [ log(mu) % log(omega) % log(a) ] % % Copyright (c) by Robert MacKay, 2016-11-15. % % See also COVFUNCTIONS.M. if nargin<2, K = '3'; return; end % report number of parameters if nargin<3, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); if D~=1, error('Covariance is defined for 1d data only.'), end mu = exp(hyp(1)); omega = exp(hyp(2)); a2 = exp(2*hyp(3)); % precompute deviations if dg % vector txx T = zeros(n,1); else if xeqz % symmetric matrix Txx T = bsxfun(@minus,x,x'); else % cross covariances Txz T = bsxfun(@minus,x,z'); end end K = a2*exp(-mu*abs(T)) .* ( sin(omega*abs(T))/omega + cos(omega*T)/mu ); % cov if nargout > 1 dK = @(Q) dirder(Q,K,T,mu,omega,a2,dg,xeqz); end function [dhyp,dx] = dirder(Q,K,T,mu,omega,a2,dg,xeqz) A = mu*abs(T).*K + a2/mu*exp(-mu*abs(T)) .* cos(omega*T); B = abs(T).*cos(omega*T) - sin(omega*abs(T))/omega - omega*T.*sin(omega*T)/mu; B = a2*exp(-mu*abs(T)) .* B; dhyp = [-A(:)'*Q(:); B(:)'*Q(:); 2*(K(:)'*Q(:))]; if nargout > 1 R = -a2*(mu/omega+omega/mu)*exp(-mu*abs(T)) .* sin(omega*T) .* Q; if dg dx = zeros(size(Q,1),1); else if xeqz dx = sum(R,2)-sum(R,1)'; else dx = sum(R,2); end end end
github
kd383/GPML_SLD-master
covScale.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covScale.m
3,216
utf_8
afdaa196951547c5f3a67e635ae0d485
function [K,dK] = covScale(cov, lsf, hyp, x, z) % covScale - compose a covariance function as a scaled version of another % one to model functions of the form f(x) = sf(x) f0(x), where sf(x) is a % scaling function determining the function's standard deviation given f0(x) % is normalised. % % The covariance function is parameterized as: % k(x,z) = sf(x) * k_0(x,z) * sf(z) % with an important special case being % k(x,z) = sf^2 * k_0(x,z). % % You can either use K = covScale(cov, lsf, hyp, x, z) where the log scaling % function lsf is a GPML mean function with hyperparameters hyp_sf yielding % hyp = [ hyp_cov % hyp_lsf ] % as hyperparameters % or you can use covScale(cov, hyp, x, z) to perform % rescaling by a scalar value sf specified as an additional variable yielding % hyp = [ hyp_cov % log(sf) ] % as hyperparameters. % % Copyright (c) by Carl Edward Rasmussen, Hannes Nickisch & Roman Garnett % 2016-04-26. % % See also COVFUNCTIONS.M. if nargin==0, error('cov function must be specified'), end if nargin<=1, lsf = []; end, narg = nargin; % set a default value if isnumeric(lsf)&&~isempty(lsf) % shift parameters if sf contains actually hyp if nargin>3, z = x; end if nargin>2, x = hyp; end if nargin>1, hyp = lsf; end narg = nargin+1; lsf = []; end % below we us narg instead of nargin to be independent of the parameter shift if isempty(lsf), ssf = '1'; else ssf = feval(lsf{:}); end % number of hypers if narg<4, K = ['(',feval(cov{:}),'+',ssf,')']; return, end if narg<5, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); % dimension of input data ncov = eval(feval(cov{:})); hyp_cov = hyp(1:ncov); % number of params, split hyp nsf = eval(ssf); hyp_lsf = hyp(ncov+(1:nsf)); scalar = isempty(lsf); if scalar, sf = exp(hyp_lsf); end if ncov+nsf~=numel(hyp), error('Wrong number of hyper parameters.'), end if nargout > 1 [K0,dK0] = feval(cov{:},hyp_cov,x,z); else K0 = feval(cov{:},hyp_cov,x,z); end if scalar sfx = sf; dsfx = @(q) sf*sum(q); else [lsfx,dlsfx] = feval(lsf{:},hyp_lsf,x); sfx = exp(lsfx); dsfx = @(q) dlsfx(q.*sfx); end if dg S = sfx.*sfx; sfz = sfx; dsfz = dsfx; else if xeqz sfz = sfx; dsfz = dsfx; else if scalar sfz = sf; dsfz = @(q) sf*sum(q); else [lsfz,dlsfz] = feval(lsf{:},hyp_lsf,z); sfz = exp(lsfz); dsfz = @(q) dlsfz(q.*sfz); end end S = sfx*sfz'; end K = S.*K0; % covariance if nargout > 1 % directional hyper derivative dK = @(Q) dirder(Q,S,K0,dK0,sfx,dsfx,sfz,dsfz,dg); end function [dhyp,dx] = dirder(Q,S,K0,dK0,sfx,dsfx,sfz,dsfz,dg) if nargout>1 [dhyp0,dx0] = dK0(Q.*S); dx = dx0; % sx contributions are missing else dhyp0 = dK0(Q.*S); end Q = Q.*K0; if dg qz = Q.*sfx; qx = Q.*sfz; else qz = sum(Q'*sfx,2); qx = sum(Q*sfz,2); end dhyp = [dhyp0; dsfx(qx)+dsfz(qz)];
github
kd383/GPML_SLD-master
covOU.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covOU.m
3,643
utf_8
02c3c9004d03310c02a3484a2c427480
function [K,dK] = covOU(i, hyp, x, z) % Ornstein-Uhlenbeck process covariance function, i times integrated. % % For i=0, this considers the stochastic differential equation % % ell * f'(x) + f(x) = N(0,sf^2), f(0) = N(f0,sf0^2), x>=0 % % where 1/ell>0 is the decay rate and sf, sf0 are noise levels. % N(m,v) is a Gaussian random variable with mean m and variance v. % % For i=0, this is the Ornstein-Uhlenbeck process covariance, for i=1, and % assuming sf=sf0, this is the integrated Ornstein-Uhlenbeck process. % % The covariance function -- given that x,z>=0 -- is specified as: % % i=0: k(x,z) = sf^2 * exp( -abs(x-z)/ell ) + (sf0^2-sf^2)*exp( -(x+z)/ell ) % i=1: k(x,z) = sf^2 * ell^2 * ( 2*min(x,z)/ell + r(x,z) ), % where r(x,z) = exp(-x/ell) + exp(-z/ell) - exp(-abs(x-z)/ell) - 1 % % The hyperparameters are: % % hyp = [ log(ell) % log(sf) % log(sf0) ] % % For more help on design of covariance functions, try "help covFunctions". % % See 10.2 of "Statistical Analysis of Stochastic Processes in Time", % by J. K. Lindsey, CUP 2004. % See "A Stochastic Model for Analysis of Longitudinal AIDS Data", % by Taylor, Cumberland and Sy, JASA 1994. % % Copyright (c) by Juan Pablo Carbajal and Hannes Nickisch, 2017-01-19. % % See also COVW.M, COVFUNCTIONS.M. if nargin<3, K = '3'; return; end % report number of parameters if nargin<4, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode [n,D] = size(x); if D~=1, error('Covariance is defined for 1d data only.'), end if any(x<0), error('Covariance is defined for nonnegative data only.'), end ell = exp(hyp(1)); sf = exp(hyp(2)); sf0 = exp(hyp(3)); % obtain hyperparameters ex = exp(-x/ell); ox = ones(size(x)); % precompute if dg % vector kxx M = x; G = 2-2*ex; dGa = -2*ex.*x/ell; E=[]; I=[]; ez=[]; oz=[]; D = zeros(n,1); S = 2*x; else if xeqz % symmetric matrix Kxx ez = ex; oz = ox; z = x; else % cross covariances Kxz ez = exp(-z/ell); oz = ones(size(z)); end D = bsxfun(@minus,x,z'); S = bsxfun(@plus,x,z'); M = ox*z'; T = x*oz'; I = bsxfun(@le,x,z'); M(I) = T(I); E = exp(-abs(D)/ell); G = 1+E-ex*oz'-ox*ez'; dGa = (E.*abs(D)-(ex.*x)*oz'-ox*(ez.*z)')/ell; end if i==0 eD = exp(-abs(D)/ell); eS = exp(-S/ell); K = sf^2*eD + (sf0^2-sf^2)*eS; dK = @(Q) dirder0(Q,D,S,eD,eS,ell,sf,sf0,dg,xeqz); else K = 2*ell*sf^2*( M - ell/2*G ); dK = @(Q) dirder1(Q,K,E,I,D,G,M,dGa,ex,ez,ox,oz,ell,sf,dg,xeqz); end function [dhyp,dx] = dirder0(Q,D,S,eD,eS,ell,sf,sf0,dg,xeqz) qes = Q(:)'*eS(:); qed = Q(:)'*eD(:); R = sf^2*eD.*abs(D) + (sf0^2-sf^2)*eS.*S; dhyp = [Q(:)'*R(:)/ell; 2*sf^2*(qed-qes); 2*sf0^2*qes]; if nargout > 1 if dg, dx = zeros(size(dpx)); else dx = (sf^2-sf0^2)*sum(Q .*eS,2) - sf^2*sum(Q .*eD.*sign(D),2); if xeqz dx = dx + (sf^2-sf0^2)*sum(Q'.*eS,2) - sf^2*sum(Q'.*eD.*sign(D),2); end end dx = dx/ell; end function [dhyp,dx] = dirder1(Q,K,E,I,D,G,M,dGa,ex,ez,ox,oz,a,sf,dg,xeqz) R = 2*a*M - a^2*(2*G+dGa); dhyp = [sf^2*(R(:)'*Q(:)); 2*(K(:)'*Q(:)); 0]; if dg dx = zeros(size(ex)); else dx = sum(Q.*I,2) + sum(Q.*(E.*sign(D)-ex*oz'),2)/2; % M+G if xeqz dx = dx + sum(Q.*(1-I),1)'; % M dx = dx + sum(Q.*(E.*sign(-D)-ox*ez'),1)'/2; % G end dx = 2*a*sf^2 * dx; end
github
kd383/GPML_SLD-master
covPeriodic.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covPeriodic.m
1,834
utf_8
fd8160a9f4eba0c658e2e84cf0077b87
function [K,dK] = covPeriodic(hyp, x, z) % Stationary covariance function for a smooth periodic function, with period p % in 1d (see covPERiso and covPERard for multivariate data): % % k(x,z) = sf^2 * exp( -2*sin^2( pi*(x-z)/p )/ell^2 ) % % where the hyperparameters are: % % hyp = [ log(ell) % log(p) % log(sf) ] % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-04-24. % % See also COVFUNCTIONS.M. if nargin<2, K = '3'; return; end % report number of parameters if nargin<3, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % 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)); % extract hyperparams % precompute deviations and exploit symmetry of sin^2 if dg % vector txx T = zeros(size(x,1),1); else if xeqz % symmetric matrix Txx T = pi/p*bsxfun(@plus,x,-x'); else % cross covariances Txz T = pi/p*bsxfun(@plus,x,-z'); end end S2 = (sin(T)/ell).^2; K = sf2*exp( -2*S2 ); % covariances if nargout>1 dK = @(Q) dirder(Q,K,S2,T,ell,xeqz,x,z,p); % directional hyper derivative end function [dhyp,dx] = dirder(Q,K,S2,T,ell,xeqz,x,z,p) Q = K.*Q; P = sin(2*T).*Q; dhyp = [4*(S2(:)'*Q(:)); 2/ell^2*(P(:)'*T(:)); 2*sum(Q(:))]; if nargout > 1 R = P./T; R(T==0) = 0; q2 = sum(R,2); q1 = sum(R,1)'; if xeqz y = bsxfun(@times,q1+q2,x) - (R+R')*x; else Rz = R*z; y = bsxfun(@times,q2,x) - Rz; end dx = -2*pi^2/(ell*p)^2 * y; end
github
kd383/GPML_SLD-master
covPref.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covPref.m
2,069
utf_8
7a68891ffcfb5214e9b185519e241b75
function [K,dK] = covPref(cov, hyp, x, z) % covPref - covariance function for preference learning. The covariance % function corresponds to a prior on f(x1) - f(x2). % % k(x,z) = k_0(x1,z1) + k_0(x2,z2) - k_0(x1,z2) - k_0(x2,z1). % % The hyperparameters are: % % hyp = [ hyp_k0 ] % % For more help on design of covariance functions, try "help covFunctions". % % See Collaborative Gaussian Processes for Preference Learning, NIPS 2014. % % Copyright (c) by Hannes Nickisch and Roman Garnett, 2016-04-17. % % See also COVFUNCTIONS.M. if nargin<3, K = strrep(feval(cov{:}),'D','D/2'); return; end % no of params if nargin<4, z = []; end % make sure, z exists xeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode x1 = x(:,1:end/2); x2 = x(:,1+end/2:end); if dg || xeqz z1 = x1; z2 = x2; else z1 = z(:,1:end/2); z2 = z(:,1+end/2:end); end if xeqz [K11,dK11] = feval(cov{:},hyp,x1); [K22,dK22] = feval(cov{:},hyp,x2); else if dg [K11,dK11] = feval(cov{:},hyp,x1,'diag'); [K22,dK22] = feval(cov{:},hyp,x2,'diag'); else [K11,dK11] = feval(cov{:},hyp,x1,z1); [K22,dK22] = feval(cov{:},hyp,x2,z2); end end [K12,dK12] = feval(cov{:},hyp,x1,z2); [K21,dK21] = feval(cov{:},hyp,x2,z1); if dg, K12 = diag(K12); K21 = diag(K21); end K = K11 + K22 - K12 - K21; dK = @(Q) dirder(Q,dK11,dK22,dK12,dK21,dg,xeqz); function [dhyp,dx] = dirder(Q,dK11,dK22,dK12,dK21,dg,xeqz) if nargout > 1 [dhyp11,dx11] = dK11(Q); [dhyp22,dx22] = dK22(Q); if dg [dhyp12,dx12] = dK12(diag(Q)); [dhyp21,dx21] = dK21(diag(Q)); else [dhyp12,dx12] = dK12(Q); [dhyp21,dx21] = dK21(Q); end if xeqz [junk,dx21t] = dK12(Q'); [junk,dx12t] = dK21(Q'); dx = [dx11-dx12-dx21t, dx22-dx21-dx12t]; else dx = [dx11-dx12, dx22-dx21]; end else dhyp11 = dK11(Q); dhyp22 = dK22(Q); if dg dhyp12 = dK12(diag(Q)); dhyp21 = dK21(diag(Q)); else dhyp12 = dK12(Q); dhyp21 = dK21(Q); end end dhyp = dhyp11 + dhyp22 - dhyp12 - dhyp21;
github
kd383/GPML_SLD-master
covSM.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/covSM.m
6,966
utf_8
53a540d4830180d0289d0d1f9d049c03
function [K,dK] = covSM(Q, hyp, x, z) % Gaussian Spectral Mixture covariance function. The covariance function % parametrization depends on the sign of Q. % % Let t(Dx1) be an offset vector in dataspace e.g. t = x-z. Then w(DxP) % are the weights and m(Dx|Q|) = 1/p, v(Dx|Q|) = (2*pi*ell)^-2 are spectral % means (frequencies) and variances, where p is the period and ell the length % scale of the Gabor function h(t2v,tm) given by the expression % h(t2v,tm) = exp(-2*pi^2*t2v).*cos(2*pi*tm) % % Then, the two covariances are obtained as follows: % % SM, spectral mixture: Q>0 => P = 1 % k(x,z) = w'*h((t.*t)'*v,t'*m), t = x-z % % SMP, spectral mixture product: Q<0 => P = D % k(x,z) = prod(w'*h(T*T*v,T*m)), T = diag(t), t = x-z % % Note that for D=1, the two modes +Q and -Q are exactly the same. % % The hyperparameters are: % % hyp = [ log(w(:)) % log(m(:)) % log(sqrt(v(:))) ] % % For more help on design of covariance functions, try "help covFunctions". % % Note that the spectral density H(s) = F[ h(t) ] of covGaboriso is given by % H(s) = N(s|m,v)/2 + N(s|-m,v)/2 where m=1/p is the mean and v=(2*pi*ell)^-2 % is the variance of a symmetric Gaussian mixture. Hence the covGaboriso % covariance forms a basis for the class of stationary covariances since a % weighted sum of covGaboriso covariances corresponds to an isotropic % location-scale mixture of a symmetric Gaussian mixture in the spectral domain. % % For more details, see % [1] SM: Gaussian Process Kernels for Pattern Discovery and Extrapolation, % ICML, 2013, by Andrew Gordon Wilson and Ryan Prescott Adams, % [2] SMP: GPatt: Fast Multidimensional Pattern Extrapolation with GPs, % arXiv 1310.5288, 2013, by Andrew Gordon Wilson, Elad Gilboa, % Arye Nehorai and John P. Cunningham, and % [3] Covariance kernels for fast automatic pattern discovery and extrapolation % with Gaussian processes, Andrew Gordon Wilson, PhD Thesis, January 2014. % http://www.cs.cmu.edu/~andrewgw/andrewgwthesis.pdf % [4] http://www.cs.cmu.edu/~andrewgw/pattern/. % % For Q>0, covSM corresponds to Eq. 4.7 in Ref [3]. % For Q<0, covSM corresponds to Eq. 14 in Ref [2] and Eq. 5.3 in Ref [3] but our % w here corresponds to w^2 in Eq. 14. % % Copyright (c) by Andrew Gordon Wilson and Hannes Nickisch, 2016-05-06. % % See also COVFUNCTIONS.M, COVGABORISO.M, COVGABORARD.M. if nargin<1, error('You need to provide Q.'), end smp = Q<0; Q = abs(Q); % switch between covSM and covSMP mode if nargin<3 % report no of parameters if smp, K = '3*D*'; else K = '(1+2*D)*'; end, K = [K,sprintf('%d',Q)]; return end if nargin<4, z = []; end % make sure, z exists % Note that we have two implementations covSMgabor and covSMfast. The former % constructs a weighted sum of products of covGabor covariances using covMask, % covProd, covScale and covSum while the latter is a standalone direct % implementation. The latter tends to be faster. if nargout > 1 if smp [K,dK] = covSMgabor(Q,hyp,x,z,smp); else [K,dK] = covSMfast(Q,hyp,x,z,smp); % faster direct alternative end else K = covSMfast(Q,hyp,x,z,smp); % faster direct alternative end function [K,dK] = covSMgabor(Q,hyp,x,z,smp) [n,D] = size(x); P = smp*D+(1-smp); % dimensionality, P=D or P=1 lw = reshape(hyp( 1:P*Q) ,P,Q); % log mixture weights lm = reshape(hyp(P*Q+ (1:D*Q)),D,Q); % log spectral means ls = reshape(hyp(P*Q+D*Q+(1:D*Q)),D,Q); % log spectral standard deviations if smp % 1) the product of weighted sums of 1d covGabor functions or fac = cell(1,D); for d=1:D add = cell(1,Q); % a) addends for weighted sum of 1d Gabor functions for q=1:Q, add{q} = {'covScale',{'covMask',{d,{'covGaboriso'}}}}; end fac{d} = {'covSum',add}; % b) combine addends into sum end fac{D+1} = 0; % disable cache to avoid memory problems cov = {'covProd',fac}; % c) combine factors into product else % 2) the weighted sum of multivariate covGaborard covariance functions. % weighted sum of multivariate Gabor functions add = cell(1,Q); for q=1:Q, add{q} = {'covScale',{'covGaborard'}}; end cov = {'covSum',add}; % combine into sum end if smp % assemble hyp; covGabor is parametrised using -ls-log(2*pi) and -lm hypgb = [-log(2*pi)-ls(:)'; -lm(:)'; lw(:)'/2]; else hypgb = [-log(2*pi)-ls; -lm; lw/2 ]; end if nargout>1 [K,dK] = feval(cov{:},hypgb(:),x,z); dK = @(R) dirder_gabor(R,dK,Q,x,smp); else K = feval(cov{:},hypgb(:),x,z); end function [dhyp,dx] = dirder_gabor(R,dK,Q,x,smp) if nargout > 1 [dhyp,dx] = dK(R); else dhyp = dK(R); end D = size(x,2); if smp dhyp = reshape(dhyp,3,D*Q); dls = -dhyp(1,:); dlm = -dhyp(2,:); dlw = 0.5*dhyp(3,:); else dhyp = reshape(dhyp,2*D+1,Q); dls = -dhyp(1:D,:); dlm = -dhyp(D+1:2*D,:); dlw = 0.5*dhyp(2*D+1,:); end dhyp = [dlw(:); dlm(:); dls(:)]; function [K,dK] = covSMfast(Q,hyp,x,z,smp) xeqz = isempty(z); dg = strcmp(z,'diag'); % sort out different types [n,D] = size(x); P = smp*D+(1-smp); % dimensionality, P=D or P=1 w = exp(reshape( hyp( 1:P*Q) ,P,Q)); % mixture weights m = exp(reshape( hyp(P*Q+ (1:D*Q)),D,Q)); % spectral means v = exp(reshape(2*hyp(P*Q+D*Q+(1:D*Q)),D,Q)); % spectral variances if dg T = zeros(n,1,D); else if xeqz T = 2*pi*bsxfun(@minus,reshape(x,n,1,D),reshape(x,1,n,D)); else T = 2*pi*bsxfun(@minus,reshape(x,n,1,D),reshape(z,1,[],D)); end end, T = reshape(T,[],D); if smp h = @(t2v,tm) exp(-0.5*t2v).*cos(tm); % Gabor function K = 1; w = reshape(w,Q,P)'; m = reshape(m,Q,D)'; v = reshape(v,Q,D)'; for d=1:D K = K .* ( h( (T(:,d).*T(:,d))*v(d,:), T(:,d)*m(d,:) )*w(d,:)' ); end K = reshape(K.*ones(size(T,1),1),n,[]); else E = exp(-0.5*(T.*T)*v); H = E.*cos(T*m); K = reshape(H*w',n,[]); if nargout>1 vec = @(x) x(:); dKdhyp = @(R) [ (H'*R(:)).*w'; -vec( ((E.*sin(T*m).*(R(:)*w))'* T )'.*m ); -vec( ((H.* (R(:)*w))'*(T.*T))'.*v ) ]; dK = @(R) dirder_fast(R,E,T,H,dKdhyp,x,z, m,v,w); end end function [dhyp,dx] = dirder_fast(R, E,T,H,dKdhyp,x,z, m,v,w) dhyp = dKdhyp(R); if nargout>1 xeqz = isempty(z); dg = strcmp(z,'diag'); [n,D] = size(x); if dg dx = zeros(size(x)); else A = reshape( (R(:)*w).*E.*sin(T*m)*m' + (((R(:)*w).*H)*v').*T, n, [], D); dx = -2*pi*squeeze(sum(A,2)); if xeqz, dx = dx + 2*pi*squeeze(sum(A,1)); end end end
github
kd383/GPML_SLD-master
apxGrid.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/cov/apxGrid.m
35,628
utf_8
f8130ac69ac6d56bec797472b95c15d0
function [K,Mx,xe] = apxGrid(cov, xg, hyp, x, z, b) % apxGrid - Covariance function approximation based on an inducing point grid. % % A grid covariance function k(x,z) is composed as a product % k(x,z) = k1(x(i1),z(i1)) * .. * kp(x(ip),z(ip)) of p covariance functions % operating on mutually disjoint components of the data x,z. % The resulting covariance matrix is given by the Kronecker product % K = kron(kron(kron(...,K3),K2),K1) = K_p x .. x K_2 x K_1. % % The function is designed to be used with infGaussLik and infLaplace. % % The covariance function grid contains p grid factors xg = {x1,..,xp} % so that for each of the factors xi a covariance function ki can be defined. % A factor xi is of size (ni,di) so that the Kronecker grid g has size % (n1,n2,..,np,D), where D=d1+d2+..+dp. Hence, the grid g contains N=n1*n2*..*np % data points overall. Note that the factors xi do neither need to % be sorted nor do they need to be 1d a priori. If a factor xi contains unevenly % spaced values, we require di=1. % % A factor xi can contain: % a) a univariate axis xi of size (ni,1), % b) a multivariate axis xi of size (ni,di), % where the values need to be equispaced, or % c) a stationary equispaced subgrid composed of di univariate equispaced axes % {xi_1,xi_2,xi_di}, where each axis xij is of size (nij,1) so that % ni=ni_1*..*ni_di intended to be used with stationary covariance functions % When a stationary equispaced subgrid is specified, we silently assume % the covariance function to be stationary. % % For fast computations, we exploit two kinds of structure: % 1) The Kronecker structure of the covariance matrix induced BY the p factors. % Hence, for p=1, there is nothing to gain here. % 2) The Toeplitz or BTTB (Block-Toeplitz with Toeplitz Blocks) WITHIN a factor % if a grid factor xi is equispaced (or multivariate and equispaced). % Note that empirically, only for matrices of sizes above 500x500, the % FFT-based MVMs are faster than dense matrix operations. % % Some examples with sizes and domain: % - a single factor with a univariate axis, case a) % xg = { 5*rand(150,1) } => N = 150, D = 1, dom = [0,5] % xg = { linspace(0,3,400)' } => N = 400, D = 1, dom = [0,3] % - a single factor with a multivariate axis (equispaced is mandatory), case b) % xg = { [linspace(0,3,100)',... % linspace(1,4,100)'] } => N = 100, D = 2, dom = [0,3]x[1,4] % - a single factor with a univariate equispaced&stationary subgrid, case c) % where we assume a stationary covariance and exploit Toeplitz structure % xg = { {linspace(0,10,175)'} } => N = 175, D = 1, dom = [0,10] % - a single factor with a bivariate equispaced&stationary subgrid, case c) % where we assume a stationary covariance and exploit BTTB structure % xg = { {linspace(0,3,20)',... % linspace(1,7,30)'} } => N = 600, D = 2, dom = [0,3]x[1,7] % - a two-factor grid of 2 univariate axes, case a) % xg = { 2*rand(40,1), 5*rand(20,1) } => N = 800, D = 2, dom = [0,2]x[0,5] % - a two-factor grid of 2 univariate equispaced and stationary axes, case c) % where we assume two stationary covariances and exploit Toeplitz structure % in both factors % xg = { {linspace(0,2,25)'}, ... % {linspace(1,3,25)'} } => N = 625, D = 2, dom = [0,2]x[1,3] % - a four-factor grid with a Toeplitz factor, two ordinary Kronecker % factors and a 2d BTTB factor % xg = { {linspace(0,1,50)'}, ... => N = 4e6, D = 5, dom = [0,1]^5 % rand(20,1), ... % linspace(0,1,40)', ... % {linspace(0,1,10)',linspace(0,1,10)'} } % % The apxGrid function can be used to expand the (nested) cell array xg into a % multivariate grid xe of size (N,D) via: % [xe,nx,Dx] = apxGrid('expand',xg); => mode 1) % The operation can be reverted (if no subgrids are used) by: % xg = apxGrid('factor',{xe,ng,Dg}); => mode 2) % % Given scattered data x of size (n,D), we can create a grid xg covering % the support of x using: % xg = apxGrid('create',x,eq,k); => mode 3) % The flag eq (default value 1) can be used to enforce an equispaced % grid. The integer k scalar or vector, indicates the number of grid points per % dimension. If k is a real number from (0,1], then the number of grid points % equals k*numel(unique(x(:,1))). % We require at least two different components per dimension. % % 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. % % Given a grid xg, the grid size can be obtained by: % [ng,Dg] = apxGrid('size',xg); => mode 4) % % An arbitrary data point x -- be it an index vector of size (n,1) or a data % point of size (n,D) -- is converted into a regular data point xx of % size (n,D) by: % [xx,ng,Dg] = apxGrid('idx2dat',xg,x); => mode 5) % If x is already of size (n,D), xx will simply equal x. % % Given a grid xg and given arbitrary data points x, the interpolation % matrix Mx can directly be computed without computing cross-covariances via: % [Mx,dMx] = apxGrid('interp',xg,x,deg); => mode 6) % For equispaced grids, deg can be used to set the degree of the interpolation % polynomial in all p axes. Here deg=0 means nearest neighbor, deg=1 means % linear interpolation, and deg=3 uses a cubic. % The cell array dMx contains the derivatives d Mx / d xi with respect to % the i=1..p grid components. % % Given a nested grid xg, we can compute a flattened grid xf by: % xf = apxGrid('flatten',xg); => mode 7) % without nesting and containing p axis elements. % % Given a covariance K, and a grid xg, and an integer embedding factor s, % we can compute the Kronecker eigen decomposition such that % K = V*diag(e)*V', where e = kron(ee,..). % [V,ee,e] = apxGrid('eigkron',K,xg,s); => mode 8) % Note that this holds only approximately for Toeplitz/BTTB due to the % circulant embedding. For details about s, see mode 9). % % Given a covariance function k where the call k(1:n) returns a vector of % length, an interger length n and an integer embedding factor s, we % construct a circulant embedding c (nx1). % [c,xg] = apxGrid('circ',k,n,s); => mode 9) % Here s is allowed to have the following values: % s=0 No embedding c = k. % s>0 Whittle embedding [1] as described by Guinness & Fuentes [2] in % equation (5) with N = |s|. % [1] Whittle, On stationary processes in the plane, Biometrika, 1954. % [2] Guinness & Fuentes, Circulant embedding of approximate covariances for % inference from Gaussian data on large lattices, 2014. % % Given a grid covariance K, a grid xg, an interpolation matrix Mx and % two sets of column vectors a and b, we can compute the directional derivative % d trace(a'*Mx*K*Mx'*b) / d hyp: % dhyp = apxGrid('dirder',K,xg,Mx,a,b); => mode 10) % % Multiplication with a matrix/operator A along dimension dim of the tensor B. % Note that tmul(A,B,1) = A*B if B is a matrix. % C = apxGrid('tmul',A,B,dim); => mode 11) % % Test grid for being equispaced along an axis i % eq = apxGrid('equi',xg,i); => mode 12) % % Return a descriptive string about the nature of Kg and Mx. % s = apxGrid('info',Kg,Mx,xg,deg); => mode 13) % % The hyperparameters are: % hyp = [ hyp_1 % hyp_2 % .. % hyp_p ], % % Copyright (c) by Hannes Nickisch and Andrew Wilson 2017-01-07. % % See also COVFUNCTIONS.M, APX.M, INFLAPLACE.M, INFGAUSSLIK.M. if nargin<2, error('Not enough parameters provided.'), end dense_max = 0; % 500 if larger grid we use FFT-algebra rather than dense algebra % mode 1) expand axes xg representation into full grid x if strcmp(cov,'expand') % call: [xe,nx,Dx] = apxGrid('expand',xg); [K,Mx,xe] = expandgrid(xg); return % mode 2) factor full x grid into axes representation xg elseif strcmp(cov,'factor') % call: xg = apxGrid('factor',{xe,ng,Dg}); K = factorgrid(xg{:}); return % mode 3) create axes representation xg from scattered data elseif strcmp(cov,'create') % call: xg = apxGrid('create',x,eq,k); if nargin<3, eq = 1; else eq = hyp; end % set default values if nargin<4, k = 1; else k = x; end, x = xg; % set input params K = creategrid(x,eq,k); return % mode 4) convert possible index vector into data space elseif strcmp(cov,'size') % call: [ng,Dg] = apxGrid('size',xg); [ng,Dg] = sizegrid(xg); K = ng; Mx = Dg; return % mode 5) convert possible index vector into data space elseif strcmp(cov,'idx2dat') % call: [xx,ng,Dg] = apxGrid('idx2dat',xg,x); [ng,Dg] = sizegrid(xg); N = prod(ng); if isidx(hyp,N), xe = expandgrid(xg); K = xe(hyp,:); else K = hyp; end Mx = ng; xe = Dg; return % mode 6) compute interpolation matrix elseif strcmp(cov,'interp') % call [Mx,dMx] = apxGrid('interp',xg,x,deg); if nargout>1, [K,Mx]=interpgrid(xg,hyp,x); else K=interpgrid(xg,hyp,x); end return % mode 7) provide flattened interpolation grid without nesting elseif strcmp(cov,'flatten') % call xf = apxGrid('flatten',xg); K = flattengrid(xg); return % mode 8) compute eigen-decomposition of Kronecker matrix elseif strcmp(cov,'eigkron') % call [V,ee,e] = apxGrid('eigkron',K,xg,s); [K,Mx,xe] = eigkron(xg,hyp,x); return % mode 9) compute a circulant embedding elseif strcmp(cov,'circ') % call [c,xg] = apxGrid('circ',k,n,s); [K,Mx] = circ(xg,hyp,x); return % mode 10) compute directional derivatives elseif strcmp(cov,'dirder') % call dhyp = apxGrid('dirder',K,xg,Mx,a,b); K = dirder(xg,hyp,x,z,b); return % mode 11) matrix multiplication along a tensor elseif strcmp(cov,'tmul') % call C = apxGrid('tmul',A,B,dim); K = tmul(xg,hyp,x); return % mode 12) test grid for being equispaced elseif strcmp(cov,'equi') % call eq = apxGrid('equi',xg,i); K = equi(xg,hyp); return % mode 13) report a descriptive status elseif strcmp(cov,'info') % call s = apxGrid('info',Kg,Mx,xg,deg); K = info(xg,hyp,x,z); return end % mode 0) regular covariance function computations p = numel(xg); [ng,Dg] = sizegrid(xg); % number of Kronecker factors if numel(cov)~=p, error('We require p factors.'), end for ii = 1:p % iterate over covariance functions 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 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 ~ix && size(x,2)~=D, error('Grid and data dimension are different.'), end if nargout>1 || ~(dg||xeqz||ix) % off-grid interpolation if nargin>5, Mx = interpgrid(xg,x,b); else Mx = interpgrid(xg,x); end end 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 ix, xii = xg{ii}; else xii = x(:,d); end % switch Kronecker/plain prod Kj = feval(f{:}, hyp(v==ii), xii, z); % plain Kronecker factor if ix, K = kron(K,Kj); else K = K.*Kj; end % switch Kronecker/plain prod end if ix, K = K(x); end, return end if isidx(z,N), iz = z; z = apxGrid('expand',xg); z = z(iz,:); end % expand z K = cell(p,1); dK = cell(p,1); sz = [1,1]; % cov Kronecker factors total size for ii = 1:p % 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 && iscell(xg{ii}) % Toeplitz/BTTB zd = []; else % symmetric matrix zd = z; end xii = xg{ii}; % grid factor if xeqz && iscell(xg{ii}) % Toeplitz/BTTB di = numel(xii); ni = sizegrid(xii); wi = zeros(di,1); for j=1:di, wi(j) = xii{j}(end)-xii{j}(1); end % width eqstat = true; for j=1:di, eqstat = eqstat & equi(xii,j); end if ~eqstat, error('Subgrid not equispaced.'), end % stop if problem if prod(ni)>dense_max % empirical thresh: FFT-based MVM with 1 rhs faster kii = @(n) feval(f{:},hyp(v==ii),(n-1)*diag(wi./(ni-1)), zeros(1,di)); xc = cell(di,1); % generic (Strang) circular embedding grid, kii = k(int) for j=1:di, n2 = floor(ni(j)-1/2)+1; xc{j} = [1:n2,n2-2*ni(j)+2:0]'; end ci = kii(apxGrid('expand',xc)); ci = reshape(ci,[2*ni(:)'-1,1]); dki = []; fi = real(fftn(ci)); % precompute FFT for circular filter mvmKi = @(x) bttbmvmsymfft(fi,x); % MVM with Toeplitz/BTTB matrix if di==1, s = 'toep'; else s = ['bttb',num2str(di)]; end ki = struct('descr',s, 'mvm',mvmKi, 'kii',kii, 'size',prod(ni)*[1,1]); else % simply evaluate covariance matrix if prod(ni) too small [ki,dki] = feval(f{:},hyp(v==ii),expandgrid(xii)); end K{ii} = ki; dK{ii} = dki; sz = sz.*K{ii}.size; else if iscell(xii), xii = expandgrid(xii); end [K{ii},dK{ii}] = feval(f{:}, hyp(v==ii), xii, zd); % plain Kronecker factor sz = sz.*size(K{ii}); end end if xeqz % create mvm and rest K = struct('mvm',@(a)kronmvm(K,a),'size',sz,'kronmvm',@kronmvm,... 'kron',struct('factor',K,'dfactor',dK)); else % expand cross terms Ks = K; K = Ks{1}; for ii = 2:p, K = kron1(Ks{ii},K); end if ix, if numel(x)~=N || max(abs(x-(1:N)'))>0, K = K(x,:); end else K = Mx*K; end end if nargout>2, xe = apxGrid('expand',xg); end % 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) if isnumeric(As{i}) As{i} = As{i}'; else As{i}.mvm = As{i}.mvmt; As{i}.size = [As{i}.size(2),As{i}.size(1)]; end end end m = zeros(numel(As),1); n = zeros(numel(As),1); % extract sizes for i=1:numel(n) if isnumeric(As{i}) [m(i),n(i)] = size(As{i}); else m(i) = As{i}.size(1); n(i) = As{i}.size(2); end end d = size(x,2); b = x; for i=1:numel(n) % apply As{i} to the 2nd dimension sa = [prod(m(1:i-1)), n(i), prod(n(i+1:end))*d]; % size a = reshape(permute(reshape(full(b),sa),[2,1,3]),n(i),[]); if isnumeric(As{i}), b = As{i}*a; else b = As{i}.mvm(a); end % do batch MVM b = permute(reshape(b,m(i),sa(1),sa(3)),[2,1,3]); end b = reshape(b,prod(m),d); % bring result in correct shape % Perform MVM b = T*a with a of size (n,m) with a BTTB (Block-Toeplitz with % Toeplitz-blocks) matrix T of size (n,n) by pointwise multiplication with the % Fourier-transformed filter f. All variables are assumed real valued. % Needs O(3*m*n*log(n)) time and O(n*m) space. function b = bttbmvmsymfft(f,a) ng = (size(f)+1)/2; p = numel(ng); Ng = prod(ng); % extract sizes if p==2 && ng(2)==1, p = 1; ng = ng(1); end % detect 1d and reduce p m = numel(a)/Ng; b = reshape(a,[ng,m]); for i=1:p, b = fft(b,2*ng(i)-1,i); end % emulate fftn with new shape b = bsxfun(@times,f,b); % pointwise multiplication for i=1:p, b = ifft(b,[],i); end % emulate ifft for i=1:p % only keep the relevant part of the result b = reshape(b,prod(ng(1:i-1)),2*ng(i)-1,prod(2*ng(i+1:p)-1)*m); b = b(:,1:ng(i),:); end b = real(reshape(b,[],m)); % 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 % mode 1 (expand) function [x,ng,Dg] = expandgrid(xg) % expand a Kronecker grid [ng,Dg] = sizegrid(xg); % original size if ~iscell(xg), x = xg; return, end % catch trivial case xg = flattengrid(xg); % remove nestedness p = numel(xg); x = xg{1}; % expanded grid data ngf = zeros(p,1); Dgf = zeros(p,1); [ngf(1),Dgf(1)] = size(xg{1}); for i=2:p szx = size(x); [ngf(i),Dgf(i)] = size(xg{i}); xold = repmat(reshape(x,[],1,szx(end)),[1,ngf(i),1]); xnew = repmat(reshape(xg{i},[1,ngf(i),Dgf(i)]),[size(xold,1),1,1]); x = reshape(cat(3,xold,xnew),[szx(1:end-1),ngf(i),szx(end)+Dgf(i)]); end x = reshape(x,[],size(x,ndims(x))); % mode 2 (factor) 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 % mode 3 (create) function xg = creategrid(x,eq,k) if nargin<2, eq = 1; end % set default values if nargin<3, k = 1; end % set input params p = size(x,2); xg = cell(p,1); % allocate result if numel(k)>0, k = ones(p,1).*k(:); end % enforce vector-valued k for j=1:p % iterate over dimensions u = sort(unique(x(:,j))); if numel(u)<2, error('Two few unique points.'),end if isempty(k) % determine number of grid points if eq ngj = ceil( (u(end)-u(1))/min(abs(diff(u))) ); % use minimum spacing else ngj = numel(u); end elseif 0<=k(j) && k(j)<=1 ngj = ceil(k(j)*numel(u)); else ngj = k(j); end du = (u(end)-u(1))/ngj; bu = [u(1)-5*du, u(end)+5*du]; if eq % equispaced grid xg{j} = linspace(bu(1),bu(2),max(ngj,5))'; % at least 5 grid points else % non-equispaced grid [idx,xgj] = kmeans(u,min(numel(u),ngj-2)); xgj = sort(xgj(:))'; % cluster nb = ngj-numel(xgj); nb1 = floor(nb/2); nb2 = nb - nb1; % size of boundary xg1 = linspace(bu(1),xgj(1),nb1+1); xg2 = linspace(xgj(end),bu(2),nb2+1); xg{j} = [xg1(1:nb1), xgj, xg2(1+(1:nb2))]'; end end % mode 4 (size) function [ng,Dg] = sizegrid(xg) % report the size of the p grid factors if ~iscell(xg), [ng,Dg] = size(xg); return, end % catch trivial case p = numel(xg); ng = zeros(p,1); Dg = zeros(p,1); % number of grid factors for i=1:p % iterate over grid factors x = xg{i}; if iscell(x) % stationary and equispace grid for j=1:numel(x) if j==1 [ng(i),Dg(i)] = size(x{j}); else ng(i) = ng(i)*size(x{j},1); Dg(i) = Dg(i)+size(x{j},2); end end else % arbitrary grid [ng(i),Dg(i)] = size(x); end end % mode 6 (interp) % deg, degree of equispaced interpolation polynomial, 0:nn, 1:lin, 3:cub function [Mx,dMx] = interpgrid(xg,x,deg) xg = flattengrid(xg); % remove nestedness p = numel(xg); Dg = zeros(p,1); ng = zeros(p,1); n = size(x,1); % dims .. for i=1:p, [ng(i),Dg(i)] = size(xg{i}); end, N = prod(ng); %.. and sizes ix = isidx(x,N); % determine whether x is an index or a data array if ix Mx = sparse(1:n,x,1,n,N); if nargout>1, dMx = repmat({sparse(n,N)},p,1); end else if nargin<3, deg = 3; end, deg = deg(:).*ones(p,1); % cubic is default s = 1; % initial stride for i=1:p % iterate over Toeplitz components d = sum(Dg(1:i-1))+(1:Dg(i)); % dimensions of interest xt = xg{i}; it = find(abs(xt(2,:)-xt(1,:))); % grid nonzero inc idx if equi(xg,i) % compute interpolation coefficients if nargout>1 % equispaced grid pts [Ji,Ci,dCi] = eqinterp(xt(:,it),x(:,d(it)),deg(i)); else [Ji,Ci] = eqinterp(xt(:,it),x(:,d(it)),deg(i)); end else if nargout>1 % non-equispaced grid pts, lin interp, inv dist weighting [Ji,Ci,dCi] = neqinterp(xt(:,it),x(:,d(it))); else [Ji,Ci] = neqinterp(xt(:,it),x(:,d(it))); end end nc = size(Ci,2); % number of interpolation coefficients along dimension if i==1 C = Ci; J = ones(n,1); if nargout>1, dC = repmat({Ci},p,1); dC{1} = dCi; end else C = repmat(C,[1,1,nc]) .* repmat(reshape(Ci,n,1,nc),[1,size(C,2),1]); C = reshape(C,n,[]); if nargout>1 for j=1:p if i==j, dCij = dCi; else dCij = Ci; end dC{j} = repmat(dC{j},[1,1,nc]) .* ... repmat(reshape(dCij,n,1,nc),[1,size(dC{j},2),1]); dC{j} = reshape(dC{j},n,[]); end end end J = repmat(J(:),[1,nc]) + s*repmat(Ji-1,[size(C,2)/nc,1]); % blow 2nd idx s = s*ng(i); % update stride end I = repmat((1:n)',[1,size(C,2)]); id = 0<J&J<=N;% first index and valid flag Mx = sparse(I(id),J(id),C(id),n,N); if nargout>1 dMx = cell(p,1); for i=1:p,dMx{i} = sparse(I(id),J(id),dC{i}(id),n,N); end end end % Compute interpolation coefficients C (nt,nc) and interpolation coefficient % indices J (nt,nc) from a source grid s (ns,1) to a target array t (nt,1). % The coefficient matrix C has rows summing up to 1. function [J,C,dC] = eqinterp(s,t,d) gp = false; switch d case 0, k = @(x) -0.5<x & x<=0.5; it=-1:0; dk = @(x) 0*x; case 1, k = @(x) max(1-abs(x),0); it=-1:0; dk = @(x) -(abs(x)<=1).*sign(x); case 3, k = @kcub; it=-2:1; dk = @dkcub; otherwise, ell = d/5; gp = true; % GP interpolation k = @(x) exp(-x.*x/(2*ell^2)); it=(0:d-1)-floor(d/2); dk = @(x) -k(x).*x/(ell^2); end ds = s(2)-s(1); ns = numel(s); nt = numel(t); nc = numel(it); if size(s,2)*size(t,2)~=1, error('Interpolation only possible for d==1.'), end if ns<nc, error('Interpolation only possible for ns>%d.',nc-1), end j = floor((t-s(1))/ds)+1; % index of closest smaller grid point w = (t-s(1))/ds-j+1; % relative distance to closest smaller grid point [0,1] j = j-it(nc); C = zeros(nt,nc); dC = zeros(nt,nc); for i=1:nc C(:,i) = k(w+it(nc+1-i)); if nargout>2, dC(:,i)=dk(w+it(nc+1-i))*(ns-1); end end if gp, kn = k(sqrt(sq_dist(1:d))); C = C/kn; dC = dC/kn; end v = 1; id = find(j<nc+it(1)); C(id,:) = 0; dC(id,:) = 0; % fix lower boundary D = abs(repmat(s(1:nc)',numel(id),1)-repmat(t(id),[1,nc])); [junk,jid] = min(D,[],2); % index of closest index in boundary region for i=1:numel(id), C(id(i),jid(i)) = 1; dC(id(i),jid(i)) = 0; end, j(id) = v; v = ns-nc+1; id = find(j>v); C(id,:) = 0; dC(id,:) = 0; % fix upper boundary D = abs(repmat(s(ns-nc+1:ns)',numel(id),1)-repmat(t(id),[1,nc])); [junk,jid] = min(D,[],2); % index of closest index in boundary region for i=1:numel(id), C(id(i),jid(i)) = 1; dC(id(i),jid(i)) = 0; end, j(id) = v; J = zeros(nt,nc); for i=1:nc, J(:,i) = j+i-1; end % construct index array J % Robert G. Keys, Cubic Convolution Interpolation for Digital Image Processing, % IEEE ASSP, 29:6, December 1981, p. 1153-1160. function y = kcub(x) y = zeros(size(x)); x = abs(x); q = x<=1; % Coefficients: 1.5, -2.5, 0, 1 y(q) = (( 1.5 * x(q) - 2.5) .* x(q) ) .* x(q) + 1; q = 1<x & x<=2; % Coefficients: -0.5, 2.5, -4, 2 y(q) = ((-0.5 * x(q) + 2.5) .* x(q) - 4) .* x(q) + 2; function y = dkcub(x) y = sign(x); x = abs(x); q = x<=1; % Coefficients: 1.5, -2.5, 0, 1 y(q) = y(q) .* ( 4.5 * x(q) - 5.0) .* x(q); q = 1<x & x<=2; % Coefficients: -0.5, 2.5, -4, 2 y(q) = y(q) .* ((-1.5 * x(q) + 5.0) .* x(q) - 4.0); y(x>2) = 0; % Perform piecewise linear interpolation using inverse distance weighting. % s (ns,1) source nodes, need neither be sorted nor equispaced % t (nt,1) target nodes % M (nt,ns) interpolation matrix, M = sparse((1:N)'*[1,1],J,C,nt,ns); % % z = M*y where y (ns,1) are source values and z (nt,1) are target values function [J,C,dC] = neqinterp(s,t) ns = size(s,1); nc = 2; % get dimensions if size(s,2)*size(t,2)~=1, error('Interpolation only possible for d==1.'), end if ns<nc, error('Interpolation only possible for ns>=nc.'), end [s,ord] = sort(s); ds = diff(s); if min(ds)<1e-10, error('Some source points are equal.'), end [junk,ii] = histc(t(:),[-inf;s(2:end-1);inf]); d0 = t(:)-s(ii); d1 = s(ii+1)-t(:); d0n = d0<0; d1n = d1<0; d0(d0n) = 0; d1(d1n) = 0; % boundary conditions J = [ord(ii),ord(ii+1)]; C = [d1./(d1+d0),d0./(d1+d0)]; nz = 1-(d1n|d0n); if nargout>2, dC = [-nz./(d1+d0),nz./(d1+d0)]; end % mode 7 (flatten) function xf = flattengrid(xg) % convert nested grid into flat grid if ~iscell(xg), xf = xg; return, end % catch trivial case xf = cell(1,0); for i=1:numel(xg) x = xg{i}; if iscell(x), xf = [xf,x]; else xf = [xf,{x}]; end end % mode 8 (eigkron) % Eigendecomposition of a Kronecker matrix K with dense, Toeplitz or BTTB % factors so that K = V*diag(e)*V', where e = kron(ee,..). Note that this holds % only approximately for Toeplitz/BTTB due to the circulant embedding. function [V,ee,e] = eigkron(K,xg,s) isbttb = @(Ki) isstruct(Ki) && (strcmp (Ki.descr,'toep') ... || strncmp(Ki.descr,'bttb',4)); % BTTB covariance p = numel(K.kron); V = cell(p,1); ee = cell(p,1); % sizes and allocate memory for j=1:p % compute eigenvalue diagonal matrix if isbttb(K.kron(j).factor) [xj,nj] = apxGrid('expand',xg{j}); % extract subgrid size ej = fftn(circ(K.kron(j).factor.kii,nj,s)); % circ embedded cov mat V{j}.mvm = @(v) Fmvm( v,nj); % V{j}' is Fourier matrix V{j}.mvmt = @(v) Fmvmt(v,nj); V{j}.size = numel(ej)*[1,1]; else Kj = K.kron(j).factor; Kj = (Kj+Kj')/2; % enforce symmetry [V{j},ej] = eig(Kj); % compute eigenvalues of non-Toeplitz matrix ej = diag(ej); V{j} = real(V{j}); % cosmetics end ee{j} = max(real(ej),0); % thresholding to ensure pd approximation end if nargout>2, e = 1; for j=1:p, e = kron(ee{j}(:),e); end, end function a = Fmvmt(b,nj) % fast Fourier transform transpose for multiple rhs Nj = prod(nj); sNj = sqrt(Nj); % scaling factor to make FFTN orthonormal nr = numel(b)/Nj; % number of right-hand-side arguments b = reshape(b,[nj(:)',nr]); for i=1:numel(nj), b = fft(b,[],i); end % emulate fftn a = reshape(b,Nj,[])/sNj; % perform rescaling function b = Fmvm(a,nj) % fast Fourier transform for multiple rhs Nj = prod(nj); sNj = sqrt(Nj); % scaling factor to make FFTN orthonormal nr = numel(a)/Nj; % number of right-hand-side arguments b = a; b = reshape(b,[nj(:)',nr]); % accumarray and target shape for i=1:numel(nj), b = ifft(b,[],i); end % emulate ifftn b = reshape(b,Nj,nr)*sNj; % perform rescaling % mode 9 (circ) % Construct a circular embedding c(nx1) from a covariance function k. % - k is a function and the call k(1:n) returns a vector of length n % - s is the setting for the embedding with values s={0,1,2,..}. % % s=0 No embedding c = k. % s>0 Whittle embedding [1] as described by Guinness & Fuentes [2] in % equation (5) with N = |s|. % % [1] Whittle, On stationary processes in the plane, Biometrika, 1954, 41(3/4). % [2] Guinness & Fuentes, Circulant embedding of approximate covariances for % inference from Gaussian data on large lattices, 2014, preprint, % http://www4.stat.ncsu.edu/~guinness/circembed.html. function [c,xg] = circ(k,n,s) p = numel(n); n = n(:)'; % dimensions and row vector if nargin<3, s = 2; end % default value if s==0 % no embedding at all xg = cell(p,1); for i=1:p, xg{i} = (1:n(i))'; end % standard grid c = reshape(k(apxGrid('expand',xg)),[n,1]); elseif s>0 % Whittle/Guinness aliasing xg = cell(p,1); for i=1:p, xg{i} = (1-s*n(i):s*n(i))'; end sz = [n; 2*s*ones(1,p)]; c = reshape(k(apxGrid('expand',xg)), sz(:)'); for i=1:p, c = sum(c,2*i); end, c = squeeze(c); end % mode 10 (dirder) % d trace(a'*Mx*Kg*Mx'*b) / d hyp function dhyp = dirder(Kg,xg,Mx,a,b) a = reshape(a,size(Mx,1),[]); % turn into column vectors if nargin<5, b = a; end % default input if b is missing b = reshape(b,size(Mx,1),[]); % turn into column vectors p = numel(Kg.kron); na = size(a,2); % number of Kronecker factors, vectors ng = [apxGrid('size',xg)',na]; % grid dimension Mta = Mx'*a; Mtb = Mx'*b; dhyp = []; % dhyp(i) = trace(a'*dKi*b) for i=1:p sz = [prod(ng(1:i-1)),ng(i),prod(ng(i+1:p)),na]; % bring arrays in vec shape shp = @(x) reshape(permute(reshape(x,sz),[2,1,3,4]),ng(i),[]); v = reshape(Mta,ng); for j=1:p, if i~=j, v = tmul(Kg.kron(j).factor,v,j); end, end if isnumeric(Kg.kron(i).factor) dhci = Kg.kron(i).dfactor( shp(v)*shp(Mtb)' ); else kii = Kg.kron(i).factor.kii; [junk,ni] = apxGrid('expand',xg{i}); di = numel(ni); xs = cell(di,1); % generic (Strang) circular embedding grid for j=1:di, n2 = floor(ni(j)-1/2)+1; xs{j} = [1:n2,n2-2*ni(j)+2:0]'; end [junk,dksi] = kii(apxGrid('expand',xs)); Fvb = fftn(sum(fftn2(shp(v),ni',1).*fftn2(shp(Mtb), ni'),di+1)); dhci = real(dksi(Fvb(:))); end dhyp = [dhyp; dhci(:)]; end function y = fftn2(x,n,t) % fftn on trailing dimensions with padding if nargin<3, t = 0; end % set a default value nx = numel(x)/prod(n); y = reshape(x,[n(:)',nx]); % #instances if t for i=1:numel(n), y = fft(y,2*n(i)-1,i); end % fftn on relevant dimensions else for i=1:numel(n), y = ifft(y,2*n(i)-1,i); end % ifftn on relevant dimensions end % mode 11 (tmul) % Multiplication with matrix/operator A along dimension dim of the tensor B. % Note that tmul(A,B,1) = A*B if B is a matrix. function C = tmul(A,B,dim) if isnumeric(A), sa = size(A); else sa = A.size; end sb = size(B); nb = ndims(B); assert(dim>0 && floor(dim)==dim && dim<=nb) assert(numel(sa)==2 && sb(dim)==sa(2)) if isnumeric(A), mvmA = @(x) A*x; else mvmA = A.mvm; end if dim==1 % along first dimension (save on permute) C = reshape(mvmA(reshape(B,sa(2),[])),[sa(1),sb(2:nb)]); elseif dim==nb % along last dimension (save on permute) C = reshape(mvmA(reshape(B,[],sa(2))')',[sb(1:nb-1),sa(1)]); else sb3 = [prod(sb(1:dim-1)),sa(2),prod(sb(dim+1:end))]; C = permute(reshape(B,sb3),[2,3,1]); C = reshape(mvmA(reshape(C,sa(2),[])),[sa(1),sb3(3),sb3(1)]); C = reshape(permute(C,[3,1,2]),[sb(1:dim-1),sa(1),sb(dim+1:end)]); end % mode 12 (equi) function eq = equi(xg,i) % grid along dim i is equispaced xi = xg{i}; if iscell(xi) eq = true; for j=1:numel(xi), eq = eq && equi(xi,j); end else ni = size(xi,1); if ni>1 % diagnose if data is linearly increasing dev = abs(diff(xi)-ones(ni-1,1)*(xi(2,:)-xi(1,:))); eq = max(dev(:))<1e-9; else eq = true; end end % mode 13 (info) function s = info(Kg,Mx,xg,deg) sk = 'K ='; Ks = Kg.kron; sk = [sk,' kron[ ']; p = numel(xg); for i=1:p if isnumeric(Ks(i).factor) si = sprintf('mat(%d)',size(Ks(i).factor,1)); else sz = num2str(size(xg{i}{1},1)); for j=2:numel(xg{i}), sz = [sz,'x',num2str(size(xg{i}{j},1))]; end si = sprintf('%s(%s)',Ks(i).factor.descr(1:4),sz); end if i<p, si = [si,' x ']; end sk = sprintf('%s%s',sk,si); end sk = sprintf('%s ]\n',sk); sm = 'M = '; xf = apxGrid('flatten',xg); deg = deg(:).*ones(numel(xf),1); id = 1; for i=1:p if apxGrid('equi',xg,i) si = sprintf('eq(d=%d',deg(id)); id = id+1; if iscell(xg{i}) for j=2:numel(xg{i}), si=sprintf('%s,d=%d',si,deg(id)); id = id+1; end end si = [si,')']; else si = 'neq(d=1)'; id = id+1; end if i<p, si = [si,' x ']; end sm = sprintf('%s%s',sm,si); end sm = sprintf('%s, nnz=%d\n',sm,nnz(Mx)); s = [sk,sm];
github
kd383/GPML_SLD-master
infMCMC.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/inf/infMCMC.m
11,425
utf_8
b9d0ffd6b56ddf12e1a81986654bca19
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 % - par.st spherical Gaussian width of the posterior KDE % Default values are sampler=hmc, Nsample=200, Nskip=40, Nburnin=10, Nais=3, % st=0.001*sqrt(sum(diag(K))/n). % % 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 2016-05-09. % % 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); st_def = 0.001*sqrt(sum(diag(K))/n); % default value if isfield(par,'st'), st =par.st; else st = st_def; end [cK,fail] = chol(K+st^2*eye(n)); % try an ordinary Cholesky decomposition if fail, error('Try increasing the par.st variable.'), end 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 strcmp(lik,'likGauss') [alpha,Na] = sample_gauss(K, m,y,hyp, N,Nb,Ns, varargin{:}); else 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 end %% sample from Gaussian posterior function [alpha,Na] = sample_gauss(K, m,y,hyp, N,Nb,Ns, taus) Na = (N+Nb)*Ns; sn2 = exp(2*hyp); n = size(K,1); if nargin<8 S = K + K*K/sn2; alpha = chol(S)\randn(n,N) + repmat(S\(K*(y-m)/sn2),1,N); else alpha = zeros(n,N); for t=1:N St = K + K*K*(taus(Nb+t)/sn2); alpha(:,t) = chol(St)\randn(n,1) + St\(K*(y-m)*taus(Nb+t)/sn2); end 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<8, 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
kd383/GPML_SLD-master
infGrid.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/inf/infGrid.m
9,908
utf_8
4d801508da434be163f9b59d8cbbf94d
function [post nlZ dnlZ] = infGrid(hyp, mean, cov, lik, x, y, opt) % Inference for a GP with grid-based approximate 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 covGrid* and likGauss. % % In case of equispaced data points, we use Toeplitz/BTTB algebra. We use a % circulant embedding approach to approximate the log determinant of the % covariance matrix. If any of the factors K_i, i=1..p has Toeplitz or more % general BTTB structure (which is indicated by K.kron.factor(i).descr being % equal to 'toep', 'bttb2', 'bttb3', etc.), we automatically use the circulant % determinant approximation. The grid specification needs to reflect this. % There are some examples to illustrate the doubly nested curly bracket % formalism. See also "help covGrid". % % There are a set of options available: % opt.pred_var, minimum value is 20 as suggested in the Papandreou paper % Instead of the data x, we can tell the engine to use x*hyp.P' to make grid % methods available to higher dimensional data. We offer two ways of % restricting the projection matrix hyp.P to either orthonormal matrices, % where hyp.P*hyp.P'=I or normalised projections diag(hyp.P*hyp.P')=1. % opt.proj = 'orth'; enforce orthonormal projections by working with % sqrtm(hyp.P*hyp.P')\hyp.P instead of hyp.P % opt.proj = 'norm'; enforce normal projections by working with % diag(1./sqrt(diag(hyp.P*hyp.P')))*hyp.P instead of hyp.P % % There are a number of options inherited from apx.m % The conjugate gradient-based linear system solver has two adjustable % parameters, the relative residual threshold for convergence opt.cg_tol and % the maximum number of MVMs opt.cg_maxit until the process stops. % opt.cg_tol, default is 1e-6 as in Matlab's pcg function % opt.cg_maxit, default is min(n,20) as in Matlab's pcg function % We can tell the inference engine to make functions post.fs2 and post.ys2 % available in order to compute the latent and predictive variance of an % unknown test data point. Precomputations for Perturb-and-MAP sampling are % required for these functions. % opt.stat = true returns a little bit of output summarising the exploited % structure of the covariance of the grid. % Please see cov/apxGrid.m for details. % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2016-10-14. if nargin<7, opt = []; end % make sure parameter exists xg = cov{3}; p = numel(xg); % extract underlying grid parameters [ng,Dg] = apxGrid('size',xg); N = prod(ng); D = sum(Dg); % dimensionality if isfield(opt,'proj'), proj = opt.proj; else proj = 'none'; end % projection hP = 1; % no projection at all if isfield(hyp,'proj') % apply transformation matrix if provided hP = hyp.proj; if strncmpi(proj,'orth',4) hP = sqrtm(hP*hP'+eps*eye(D))\hP; % orthonormal projector elseif strncmpi(proj,'norm',4) hP = diag(1./sqrt(diag(hP*hP')+eps))*hP; % normal projector end end if isfield(opt,'deg'), deg = opt.deg; else deg = 3; end % interpol. degree % no of samples for covariance hyperparameter sampling approximation, % see Po-Ru Loh et.al.: "Contrasting regional architectures of schizophrenia and % other complex diseases using fast variance components analysis, biorxiv.org if isfield(opt,'ndcovs'), ndcovs = max(opt.ndcovs,20); else ndcovs = 0; end [K,M] = feval(cov{:}, hyp.cov, x*hP'); % evaluate covariance mat constituents m = feval(mean{:}, hyp.mean, x*hP'); % evaluate mean vector if iscell(lik), lstr = lik{1}; else lstr = lik; end if isa(lstr,'function_handle'), lstr = func2str(lstr); end if isequal(lstr,'likGauss'), inf = @infGaussLik; else inf = @infLaplace; end if nargout>0 if nargout<3 [post nlZ] = inf(hyp, mean, cov, lik, x*hP', y, opt); else [post nlZ dnlZ] = inf(hyp, mean, cov, lik, x*hP', y, opt); if isfield(hyp,'proj') dnlZ.proj=deriv_proj(post.alpha,hP,K,covGrid('flatten',xg),m,mean,hyp,x); if strncmpi(proj,'orth',4), dnlZ.proj=chain_orth(hyp.proj,dnlZ.proj); elseif strncmpi(proj,'norm',4), dnlZ.proj=chain_norm(hyp.proj,dnlZ.proj); end end end else return, end % no of samples for perturb-and-MAP, see George Papandreou and Alan L. Yuille: % "Efficient Variational Inference in Large-Scale Bayesian Compressed Sensing" ns = 0; % do nothing per default, 20 is suggested in paper if isfield(opt,'pred_var'), ns = max(ceil(abs(opt.pred_var)),20); end if ndcovs>0 && nargout>2, ns = max(ns,ndcovs); end % possibly draw more samples Mtal = M'*post.alpha; % blow up alpha vector from n to N kronmvm = K.kronmvm; if ns>0 s = 3; % Whittle embedding overlap factor [V,ee,e] = apxGrid('eigkron',K,xg,s); % perform eigen-decomposition % explained variance on the grid vg=diag(Ku*M'*inv(C)*M*Ku), C=M*Ku*M'+inv(W) % relative accuracy r = std(vg_est)/vg_exact = sqrt(2/ns) A = sample(V,e,M,post.sW,ns,kronmvm); A = post.L(A); % a~N(0,inv(C)) z = K.mvm(M'*A); vg = sum(z.*z,2)/ns; % z ~ N(0,Ku*M'*inv(C)*M*Ku) if ndcovs>0 dnlZ.covs = - apxGrid('dirder',K,xg,M,post.alpha,post.alpha)/2; na = size(A,2); for i=1:na % compute (E[a'*dK*a] - a'*dK*a)/2 dnlZ.covs = dnlZ.covs + apxGrid('dirder',K,xg,M,A(:,i),A(:,i))/(2*na); end if isfield(hyp,'proj') % data projection matrix dPs = zeros(size(hyp.proj)); % allocate memory for result KMtal = K.mvm(Mtal); [M,dM]=covGrid('interp',xg,x*hP'); % precompute for i = 1:size(dPs,1) if equi(xg,i), wi = max(xg{i})-min(xg{i}); else wi = 1; end % scaling for j = 1:size(dPs,2) dMtal = dM{i}'*(x(:,j).*post.alpha/wi); dMtA = dM{i}'*(repmat(x(:,j),1,na).*A/wi); dPs(i,j) = sum(sum(dMtA.*z))/ndcovs - dMtal'*KMtal; end end if strncmpi(proj,'orth',4),dnlZ.projs = chain_orth(hyp.proj,dPs); elseif strncmpi(proj,'norm',4),dnlZ.projs = chain_norm(hyp.proj,dPs); else dnlZ.projs = dPs; end end end else vg = zeros(N,1); % no variance explained end % add fast predictions to post structure, f|y,mu|s2 post.predict = @(xs) predict(xs*hP',xg,K.mvm(Mtal),vg,hyp,mean,cov,lik,deg); % global mem, S = whos(); mem=0; for i=1:numel(S), mem=mem+S(i).bytes/1e6; end % Compute latent and predictive means and variances by grid interpolation. function [fmu,fs2,ymu,ys2] = predict(xs,xg,Kalpha,vg,hyp,mean,cov,lik,deg) Ms = apxGrid('interp',xg,xs,deg); % obtain interpolation matrix xs = apxGrid('idx2dat',xg,xs,deg); % deal with index vector ms = feval(mean{:},hyp.mean,xs); % evaluate prior mean fmu = ms + Ms*Kalpha; % combine and perform grid interpolation if nargout>1 if norm(vg,1)>1e-10, ve = Ms*vg; else ve = 0; end % interp grid var expl. ks = feval(cov{:},hyp.cov,xs,'diag'); % evaluate prior variance fs2 = max(ks-ve,0); % combine, perform grid interpolation, clip if nargout>2, [lp, ymu, ys2] = feval(lik{:},hyp.lik,[],fmu,fs2); end end % sample a~N(0,C), C = M*Ku*M'+inv(W), W=sW^2 function A = sample(V,e,M,sW,ns,kronmvm) [n,N] = size(M); A = randn(N,ns); % a~N(0,I) A = kronmvm(V,repmat(sqrt(e),1,ns).*kronmvm(V,A,1)); % a~N(0,Ku) A = M*A + bsxfun(@times,1./sW,randn(n,ns)); % compute derivative of neg log marginal likelihood w.r.t. projection matrix P function dP = deriv_proj(alpha,P,K,xg,m,mean,hyp,x) xP = x*P'; [M,dM] = covGrid('interp',xg,xP); % grid interp derivative matrices beta = K.mvm(M'*alpha); % dP(i,j) = -alpha'*dMij*beta dP = zeros(size(P)); h = 1e-4; % allocate result, num deriv step for i=1:size(P,1) if equi(xg,i), wi = max(xg{i})-min(xg{i}); else wi = 1; end % scaling factor xP(:,i) = xP(:,i)+h; % perturb ith component of projection matrix dmi = (feval(mean{:},hyp.mean,xP)-m)/h; % numerically estimate dm/dP(:,i) xP(:,i) = xP(:,i)-h; % undo perturbation betai = dmi + dM{i}*beta/wi; for j=1:size(P,2), dP(i,j) = -alpha'*(x(:,j).*betai); end end function eq = equi(xg,i) % grid along dim i is equispaced ni = size(xg{i},1); if ni>1 % diagnose if data is linearly increasing dev = abs(diff(xg{i})-ones(ni-1,1)*(xg{i}(2,:)-xg{i}(1,:))); eq = max(dev(:))<1e-9; else eq = true; end % chain rule for the function Q = sqrtm(P*P')\P; for d sqrtm(X) see the website function dQ = chain_orth(P,dP) % http://math.stackexchange.com/questions/540361 [V,F] = eig(P*P'); sf = sqrt(diag(F)); S = V*diag(sf)*V'; % eig-decomp H = dP'/S; G = H'*(P'/S); o = ones(size(dP,1),1); % chain rule dQ = (H - P'*V*((V'*(G+G')*V)./(sf*o'+o*sf'))*V')'; % chain rule for the function Q = diag(1./sqrt(diag(P*P')))*P; function dQ = chain_norm(P,dP) p = 1./sqrt(diag(P*P')); dQ = diag(p)*dP - diag(diag(dP*P').*p.^3)*P;
github
kd383/GPML_SLD-master
infEP.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/inf/infEP.m
16,241
utf_8
ab38eadd10971c020f090bf044c20e7c
function [post nlZ dnlZ] = infEP(hyp, mean, cov, lik, x, y, opt) % 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. % % Functions for apx.m % ep_init_{sp,ex} % ep_up_{sp,ex} % ep_marg_{sp,ex} % % Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch 2016-12-20. % % 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 if nargin<=6, opt = []; end % make opt variable available if isfield(opt,'s'), s = opt.s; else s = 1.0; end % default is EP inf = 'infEP'; n = size(x,1); if isstruct(cov), K = cov; % use provided covariance structure else K = apx(hyp,cov,x,opt); end % set up covariance approximation if isnumeric(mean), m = mean; % use provided mean vector else [m,dm] = feval(mean{:}, hyp.mean, x); end % mean vector and deriv % init and update drivers for Gaussian posterior approximation c1 = cov{1}; if isa(c1, 'function_handle'), c1 = func2str(c1); end sparse = strcmp(c1,'apxSparse') || strcmp(c1,'covFITC'); grid = strcmp(c1,'apxGrid') || strcmp(c1,'covGrid'); exact = ~grid && ~sparse; if s~=0 && s~=1, error('Only opt.s=1 (EP) and opt.s=0 (KL) are possible.'),end if exact ep_up = @ep_up_ex; ep_init = @ep_init_ex; ep_marg = @ep_marg_ex;%O(n ^{2,3,0}) elseif sparse ep_up = @ep_up_sp; ep_init = @ep_init_sp; ep_marg = @ep_marg_sp;%O(nu^{2,3,2}) elseif grid error('EP not implemented for grid covariances.') end % 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. ttau = zeros(n,1); tnu = zeros(n,1); % init to zero if no better guess [nlZ,post] = ep_init(K,y,ttau,tnu,lik,hyp,m,inf,s,cov,x); % init post approx if all(size(last_ttau)==[n,1]) % try the tilde values from previous call [last_nlZ,last_post] = ep_init(K,y,last_ttau,last_tnu,lik,hyp,m,inf,s,cov,x); if nlZ > last_nlZ % previous is better nlZ = last_nlZ; post = last_post; ttau = last_ttau; tnu = last_tnu; 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 [mui,sii] = ep_marg(post,i); % obtain marginal moments tau_ni = 1/sii-ttau(i); % first find the cavity distribution .. nu_ni = mui/sii-tnu(i); % .. params tau_ni and nu_ni if s==1 % 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); % new tilde params ttaui = max(ttaui,0); % enforce positivity i.e. lower bound ttau by zero tnui = ( dlZ - nu_ni/tau_ni*d2lZ )/(1+d2lZ/tau_ni); elseif s==0 [mi,svi] = klmin(lik, hyp.lik, y(i), nu_ni,tau_ni); % KL projection ttaui = 1/svi^2-tau_ni; % new tilde params ttaui = max(ttaui,0); % enforce positivity i.e. lower bound ttau by zero tnui = mi/svi^2-nu_ni; end post = ep_up(post, ttau(i),tnu(i),i,ttaui-ttau(i),tnui-tnu(i));% update post ttau(i) = ttaui; tnu(i) = tnui; % update the tilde parameters end % recompute since repeated rank-one updates can destroy numerical precision [nlZ,post,alpha,tau_n,nu_n,solveKiW,dhyp] = ... ep_init(K,y,ttau,tnu,lik,hyp,m,inf,s,cov,x); post.L = @(r)-K.P(solveKiW(K.Pt(r))); post.alpha = K.P(alpha); 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 if nargout>2 % do we want derivatives? if s==1 dnlZ = dhyp(alpha); % covariance-related hypers 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 hypers dnlZ.mean = -dm(dlZ); elseif s==0 dnlZ = dhyp(alpha); v = post.diagSigma; % covariance-related hypers dv = -ttau/2; % at convergence we have df = alpha and dv = -W/2 = -ttau/2 [junk,dK] = feval(cov{:}, hyp.cov, x); A = post.A; % not (yet) scalable dnlZ.cov = dnlZ.cov - dK( diag(dv)*A'*(A-A') ); for i = 1:numel(hyp.lik) % likelihood hypers dnlZ.lik(i) = -sum( likKL(v,lik,hyp.lik,y,K.mvm(post.alpha)+m,[],[],i) ); end dnlZ.mean = -dm(alpha); % mean hypers end end post = struct('alpha',post.alpha, 'L',post.L, 'sW',sqrt(ttau));% clean posterior function [post,alpha,tau_n,nu_n,ldB2,solveKiW,varargout] = ... ep_cavity(K,m,ttau,tnu,post) varargout = cell(nargout-6,1); % return as much as required [ldB2,solveKiW,dW,varargout{:}] = K.fun(ttau); % functions depending on W post.diagSigma = 2*dW; alpha = tnu-solveKiW(K.mvm(tnu)+m); post.mu = K.mvm(alpha)+m; tau_n = 1./post.diagSigma-ttau; nu_n = post.mu./post.diagSigma-tnu; % cavities function nlZ = ep_Z(post,alpha,tau_n,nu_n,ldB2,solveKiW,triB,... K,m,y,ttau,tnu,lik,hyp,s) if s==1 lZ = feval(lik{:}, hyp.lik, y, nu_n./tau_n, 1./tau_n, 'infEP'); p = tnu-m.*ttau; q = nu_n-m.*tau_n; r = K.mvm(p); % auxiliary vectors nlZ = ldB2-sum(lZ)-p'*r/2 +r'*solveKiW(r)/2 +(post.diagSigma'*p.^2)/2 ... -q'*((ttau./tau_n.*q-2*p).*post.diagSigma)/2-sum(log(1+ttau./tau_n))/2; else lp = likKL(post.diagSigma,lik,hyp.lik,y,post.mu); % evaluate likelihood nlZ = ldB2 -sum(lp) + (alpha'*(post.mu-m)+triB-numel(m))/2; % upper bound end % refresh the representation of the posterior from initial and site parameters % to prevent possible loss of numerical precision after many updates % effort is O(n*nu^2) provided that nu<n function [nlZ,post,alpha,tau_n,nu_n,solveKiW,dhyp] = ... ep_init_sp(K,y,ttau,tnu,lik,hyp,m,inf,s,cov,x) xu = cov{3}; nu = size(xu,1); chol_inv = @(A) rot90(rot90(chol(rot90(rot90(A)))'))\eye(nu); % chol(inv(A)) Kuu = feval(cov{2}{:}, hyp.cov, xu); % get the building blocks Ku = feval(cov{2}{:}, hyp.cov, xu, x); diagK = feval(cov{2}{:}, hyp.cov, x, 'diag'); snu2 = 1e-6*(trace(Kuu)/nu); % stabilise by 0.1% of signal std 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) post.m = m; post.d0 = d0; post.Ku = Ku; post.R0 = R0; if max(norm(tnu),norm(ttau))<1e-10 && nargout<3 post.diagSigma = diagK; nlZ = -sum(feval(lik{:}, hyp.lik, y, m, post.diagSigma, inf)); else [post,alpha,tau_n,nu_n,ldB2,solveKiW,dhyp,L,triB] = ... ep_cavity(K,m,ttau,tnu,post); nlZ = ep_Z(post,alpha,tau_n,nu_n,ldB2,solveKiW,triB,... K,m,y,ttau,tnu,lik,hyp,s); end if nargout>1 t = 1./(1+d0.*ttau); % temporary variable O(n) d = d0.*t; % O(n) P = repmat(t',nu,1).*Ku; % O(n*nu) T = repmat((ttau.*t)',nu,1).*V; % temporary variable O(n*nu^2) R = chol_inv(eye(nu)+V*T'); % O(n*nu^3) nn = d.*tnu; % O(n) gg = R0'*(R'*(R*(V*(t.*tnu)))); % O(n*nu) post.d = d; post.P = P; post.R = R; post.nn = nn; post.gg = gg; end % update the representation of the posterior to reflect modification of the site % parameters, effort is O(nu^2) % old site parameters for site i=1..n: ttaui, tnui % new site parameters for site i=1..n: ttaui+dttaui, tnui+dtnui function post = ep_up_sp(post, ttaui,tnui,i,dttaui,dtnui) hi = post.nn(i)+post.m(i) + post.P(:,i)'*post.gg; % post mean of site i O(nu) t = 1+dttaui*post.d(i); post.d(i) = post.d(i)/t; % O(1) post.nn(i) = post.d(i)*(tnui+dtnui); % O(1) r = 1+post.d0(i)*ttaui; r = r*r/dttaui + r*post.d0(i); v = post.R*(post.R0*post.Ku(:,i)); r = 1/(r+v'*v); if r>0 post.R = cholupdate(post.R,sqrt( r)*post.R'*v,'-'); else post.R = cholupdate(post.R,sqrt(-r)*post.R'*v,'+'); end T = post.R0'*(post.R'*(post.R*(post.R0*post.P(:,i)))); post.gg = post.gg + ((dtnui-dttaui*(hi-post.m(i)))/t)*T; % O(nu^2) post.P(:,i) = post.P(:,i)/t; % O(nu) % O(nu^2) function to compute marginal i of the Gaussian posterior function [mui,sii] = ep_marg_sp(post,i) pi = post.P(:,i); t = post.R*(post.R0*pi); % temporary variables sii = post.d(i) + t'*t; mui = post.nn(i) + pi'*post.gg; % posterior moments % O(n^3) function to compute the parameters of the Gaussian posterior % approximation, Sigma and mu, and the negative log marginal likelihood, nlZ, % from the current site parameters, ttau and tnu. function [nlZ,post,alpha,tau_n,nu_n,solveKiW,dhyp] = ... ep_init_ex(K,y,ttau,tnu,lik,hyp,m,inf,s,cov,x) n = numel(y); post = []; % number of inputs if max(norm(tnu),norm(ttau))<1e-10 && nargout<3 post.mu = m; post.Sigma = K.mvm(eye(n)); post.diagSigma = diag(post.Sigma); nlZ = -sum(feval(lik{:}, hyp.lik, y, m, post.diagSigma, inf)); else [post,alpha,tau_n,nu_n,ldB2,solveKiW,dhyp,L,triB] = ... ep_cavity(K,m,ttau,tnu,post); nlZ = ep_Z(post,alpha,tau_n,nu_n,ldB2,solveKiW,triB,... K,m,y,ttau,tnu,lik,hyp,s); Kd = K.mvm(eye(n)); post.A = eye(n)-solveKiW(Kd); post.Sigma = Kd*post.A; end % O(n^2) function to compute the parameters of the Gaussian posterior % approximation, Sigma and mu, from the current site parameters, % old site parameters for site i=1..n: ttaui, tnui % new site parameters for site i=1..n: ttaui+dttaui, tnui+dtnui function post = ep_up_ex(post, ttaui,tnui,i,dttaui,dtnui) si = post.Sigma(:,i); sii = si(i); ci = dttaui/(1+dttaui*sii); mui = post.mu(i); post.Sigma = post.Sigma - ci*(si*si'); % rank-1 update Sigma takes O(n^2) post.mu = post.mu - (ci*(mui+sii*dtnui)-dtnui)*si; % .. and recompute mu % O(1) function to obtain the marginal i of the Gaussian posterior function [mui,sii] = ep_marg_ex(post,i) sii = post.Sigma(i,i); mui = post.mu(i); % 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 % Gaussian smoothed likelihood function; instead of p(y|f)=lik(..,f,..) compute % log likKL(f) = int log lik(..,t,..) N(f|t,v) dt, 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) f = varargin{3}; % obtain location of evaluation sv = sqrt(v); % smoothing width lik_str = lik{1}; if ~ischar(lik_str), lik_str = func2str(lik_str); end if strcmp(lik_str,'likLaplace') % likLaplace can be done analytically b = exp(varargin{1})/sqrt(2); y = varargin{2}; 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); else N = 20; % number of quadrature points [t,w] = gauher(N); % location and weights for Gaussian-Hermite quadrature 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}); ll = ll + w(i)*lp; % value of the integral df = df + w(i)*dlp; % derivative wrt. mean d2f = d2f + w(i)*d2lp; % 2nd derivative wrt. mean ai = t(i)./(2*sv+eps); dvi = dlp.*ai; dv = dv+w(i)*dvi; % deriv wrt. var d2v = d2v + w(i)*(d2lp.*(t(i)^2/2)-dvi)./(v+eps)/2; % 2nd deriv wrt. var dfdv = dfdv + w(i)*(ai.*d2lp); % mixed second derivatives end end
github
kd383/GPML_SLD-master
infVB.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/inf/infVB.m
5,862
utf_8
2ce41c3e62d67935a0e8f13ae909137b
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 2016-10-21. % % See also INFMETHODS.M. n = size(x,1); if nargin<=6, opt = []; end % make opt variable available if isstruct(cov), K = cov; % use provided covariance structure else K = apx(hyp,cov,x,opt); end % set up covariance approximation if isnumeric(mean), m = mean; % use provided mean vector else [m,dm] = feval(mean{:}, hyp.mean, x); end % mean vector and deriv 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 [junk,junk,dW] = K.fun(sW.*sW); v = 2*dW; [post,junk,junk,alpha] = infLaplace(hyp, mean, K, {@likVB,v,lik}, x, y, opt); % post.sW is very different from the optimal sW for non Gaussian likelihoods sW_old = sW; f = K.mvm(alpha)+m; % posterior mean [lp,junk,junk,sW,b,z] = feval(@likVB,v,lik,hyp.lik,y,f); if max(abs(sW-sW_old))<out_tol, break, end % diagnose convergence end post.sW = sW; % posterior parameters [ldB2,solveKiW,dW,dhyp] = K.fun(sW.*sW); post.L = @(r) -K.P(solveKiW(K.Pt(r))); 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) t = b.*ga+z-m; nlZ = ldB2 + (sum(h)+t'*solveKiW(t)-(be.*be)'*ga )/2; % var bound if nargout>2 % do we want derivatives? dnlZ = dhyp(alpha); % covariance hypers dnlZ.lik = zeros(size(hyp.lik)); % allocate memory 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 sn2 = exp(2*hyp.lik); dnlZ.lik = -sn2*(alpha'*alpha) - 2*sum(dW)/sn2 + n; end dnlZ.mean = -dm(alpha); % mean hypers 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
kd383/GPML_SLD-master
infLaplace.m
.m
GPML_SLD-master/gpml-matlab-v4.1-2017-10-19/inf/infLaplace.m
5,348
utf_8
472d96f52dc0997f6629ce9ae7ae5c5b
function [post nlZ dnlZ alpha] = 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 2016-10-21. % % 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 inf = 'infLaplace'; n = size(x,1); if isstruct(cov), K = cov; % use provided covariance structure else K = apx(hyp,cov,x,opt); end % set up covariance approximation if isnumeric(mean), m = mean; % use provided mean vector else [m,dm] = feval(mean{:}, hyp.mean, x); end % mean vector and deriv 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.mvm,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.mvm(alpha)+m; % compute latent function values last_alpha = alpha; % remember for next call [lp,dlp,d2lp,d3lp] = likfun(f); W = -d2lp; [ldB2,solveKiW,dW,dhyp] = K.fun(W); % obtain functionality depending on W post.alpha = K.P(alpha); % return the posterior parameters post.sW = sqrt(abs(W)).*sign(W); % preserve sign in case of negative post.L = @(r) -K.P(solveKiW(K.Pt(r))); % 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 nlZ = alpha'*(f-m)/2 - sum(lp) + ldB2; % compute marginal likelihood if nargout>2 % do we want derivatives? dfhat = dW.*d3lp; % deriv. of nlZ wrt. fhat: dfhat=diag(inv(inv(K)+W)).*d3lp/2 dahat = dfhat - solveKiW(K.mvm(dfhat)); dnlZ = dhyp(alpha,dlp,dahat); dnlZ.lik = zeros(size(hyp.lik)); % allocate memory 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) = -dW'*d2lp_dhyp - sum(lp_dhyp); % explicit part b = K.mvm(dlp_dhyp); % b-K*(Z*b) = inv(eye(n)+K*diag(W))*b dnlZ.lik(i) = dnlZ.lik(i) - dfhat'*( b-K.mvm(solveKiW(b)) ); % implicit end dnlZ.mean = -dm(alpha+dahat); % explicit + implicit part 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,mvmK,likfun) f = mvmK(alpha)+m; [lp,dlp,d2lp] = likfun(f); W = -d2lp; psi = alpha'*(f-m)/2 - sum(lp); if nargout>1, dpsi = mvmK(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.mvm,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.mvm(alpha)+m; [lp,dlp,d2lp] = likfun(f); W = -d2lp; n = size(K,1); Psi_new = Psi(alpha,m,K.mvm,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 [ldB2,solveKiW] = K.fun(W); b = W.*(f-m) + dlp; dalpha = b - solveKiW(K.mvm(b)) - alpha; % Newton direction + line search [s_line,Psi_new,n_line,dPsi_new,f,alpha,dlp,W] = search_line(alpha,dalpha); end % end Newton's iterations
github
kd383/GPML_SLD-master
demo_sound.m
.m
GPML_SLD-master/demo/sound/demo_sound.m
3,971
utf_8
d2532d9afe9491656859f693775ca427
function demo_sound(method, ninterp, hyp) % % Natural Sound Recovery Experiment % Recover contiguous missing region in a waveform using different % Training points: 59306, Testing points: 691 % % method: Logdet Approximation Methods, {'Lanczos', 'Cheby', 'SKI', 'FITC'} % ninterp: Number of interpolation points, default: 3000 % if nargin < 1 || isempty(method), method = 'lancz'; end % Default method: Lanczos if nargin < 2 || isempty(ninterp), ninterp = 3000; end % Default Gridpts: 3000 % Loading Sound Data fprintf('---------Loading Data----------\n'); testVars = {'xfull','xtrain','ytrain','xtest','ytest','hypc'}; load('audio_data.mat',testVars{:}); Ntrain = length(xtrain); Nrun = numel(ninterp); % Initialize Error/Time MAE = zeros(Nrun,1); SMAE = zeros(Nrun,1); RMSE = zeros(Nrun,1); TRIVMAE = zeros(Nrun,1); TRECOVER = zeros(Nrun,1); TINFER = zeros(Nrun,1); TPRED = zeros(Nrun,1); meanfunc = {@meanZero}; fprintf('Using Method: %s\n\n', method); for i = 1:Nrun xg = covGrid('create',xfull,1,ninterp(i)); % Create grid points [inf, covg, opt] = build_inf(method, xg, Ntrain); % Load options based on method if strcmp(method, 'FITC'), hyp = hypc; end % No recovery using FITC if isempty(hyp) fprintf('----------Start Recovery----------\n'); tic; hyp = minimize(hypc,@gp,-50,inf,meanfunc,covg,'likGauss',... xtrain,ytrain); % Recover hyper-params fprintf('The recovered hyper-parameters are:\n'); fprintf('ell = %.4f,\t sf = %.4f,\t sigma = %.4f\n',... [exp(hyp.cov)',exp(hyp.lik)]); TRECOVER(i) = toc; fprintf('The recovered time is: %.4f [s]\n\n', TRECOVER(i)); end fprintf('----------Start Inference----------\n'); tic; if strcmp(method, 'FITC') [post, nlZ, dnlZ] = infFITC(hyp,meanfunc,covg,'likGauss',... xtrain,ytrain,opt); else [post, nlZ, dnlZ] = infGrid(hyp,meanfunc,covg,'likGauss',... xtrain,ytrain,opt); end TINFER(i) = toc; fprintf('The inference time is: %.4f [s]\n\n', TINFER(i)); fprintf('----------Start Prediction----------\n'); post.L = @(x) 0*x; % Fast prediction tic; ymug = gp(hyp,inf,meanfunc,covg,[],xtrain,post,xtest); TPRED(i) = toc; MAE(i) = sum(abs(ytest-ymug))/numel(ytest); RMSE(i) = sqrt(sum((ytest-ymug).^2)/numel(ytest)); TRIVMAE(i) = sum(abs(ytest-zeros(numel(ytest),1)))/numel(ytest); SMAE(i) = MAE(i)./TRIVMAE(i); fprintf(['MAE = %5.3e, TRIVMAE = %5.3e, SMAE = %5.3e,\n', ... 'RMSE = %5.3e, time = %5.3f [s]\n\n'], MAE(i), TRIVMAE(i), ... SMAE(i), RMSE(i), TPRED(i)); end end % Loading options into inference and covariance function function [inf, covg, opt] = build_inf(method, xg, Ntrain) opt.cg_maxit = 1e4; opt.cg_tol = 1e-2; % CG solver options switch method case 'lancz' opt.ldB2_method = 'lancz'; opt.ldB2_maxit = -25; % Lanczos steps opt.ldB2_hutch = sign(randn(Ntrain,5)); % Number of probe vectors inf = @(varargin) infGrid(varargin{:},opt); covg = {@covGrid,{@covSEiso},xg}; case 'cheby' opt.ldB2_method = 'cheby'; opt.ldB2_hutch = 5; % Number of probe vectors opt.ldB2_maxit = 1e3; % Number of iterations for eigs opt.ldB2_cheby_degree = 100; % Degree of Cheby polynomial inf = @(varargin) infGrid(varargin{:},opt); covg = {@covGrid,{@covSEiso},xg}; case 'ski' inf = @(varargin) infGrid(varargin{:},opt); covg = {@covGrid,{@covSEiso},xg}; case 'fitc' inf = @infFITC; covg = {@covFITC,{@covSEiso},xg{1}}; end end
github
kd383/GPML_SLD-master
spatiotemporal_spectral_init_poisson.m
.m
GPML_SLD-master/demo/crime/auxiliary/spatiotemporal_spectral_init_poisson.m
4,088
utf_8
9fa01d473f355c69b9c4fbd1df01811d
% Function to initialise SM kernel hyperparameters % If varargin{1} is specified, it is the number of optimisation iterations % to run for each random restart. Otherwise, we will just have % initialisations and no optimisation. % stdy should be on the log-scale function hyp = spatiotemporal_spectral_init(inf_method,hyp,meanf,lik,cov,covg,x,y,stdy,idx,nrestarts,varargin) % start with user inputed hypers hyp_best = hyp; try % compute nlml for user specified hyp bestlik = Inf; %gp(hyp, inf_method, meanf, covg, lik, idx, y); catch disp('Error with user specified hypers.'); disp('Attempting to proceed with automatic initialisation.'); bestlik = Inf; end disp(sprintf('Initialisation nlml 0: %.02f',bestlik)); if isnan(bestlik) bestlik = Inf; end % try 'nrestarts' number of initialisations for ri=1:nrestarts hyp.cov = []; % shouldn't overwrite yet for i=1:numel(cov) % call the initialisation script for two 1D spectral mixture % kernels % alert!: This assumes each % separable component has % the same Q! if strcmp(func2str(cov{i}{1}),'covSum') hyp.cov = [hyp.cov; hypinit1D(func2str(cov{i}{2}{2}{1}), cov{i}{2}{2}, x(:,i) ,stdy, covg{3}{i}(2) - covg{3}{i}(1))]; % want the true inputs x here else hyp.cov = [hyp.cov; hypinit1D(func2str(cov{i}{1}), cov{i}, x(:,i) ,stdy, covg{3}{i}(2) - covg{3}{i}(1))]; % want the true inputs x here end end hyp.cov = log(hyp.cov); % if desired, try iter_run optimization iterations for each initialisation if(~isempty(varargin)) iter_run = varargin{1}; hyp = minimize(hyp,@gp,-iter_run,inf_method,meanf,covg,lik,idx,y); end % see if nlml of new initialisation is better try l = gp(hyp, inf_method, meanf, covg, lik, idx, y); disp(sprintf('nlml %d: %.02f', ri, l)) if l < bestlik bestlik = l; hyp_best = hyp; save('best.mat') end catch disp('Error trying initialisation'); end end hyp = hyp_best; disp(sprintf('best likelihood found: %f', bestlik)) % initialise a 1D spectral mixture kernel function [hypout] = hypinit1D(covtype,cov,x,stdy,Fs) hypout = []; switch(covtype) case 'covSM' Q = cov{2}; % NOTE TO USER: SET FS= 1/[MIN GRID SPACING] FOR YOUR APPLICATION % Fs is the sampling rate % Fs = 1; % 1/[grid spacing]. % Deterministic weights (fraction of variance) % Set so that k(0,0) is close to the empirical variance of the data. wm = stdy; w0 = 1/sqrt(Q)*ones(Q,1); w0 = w0.^2; % parametrization for covSMfast hypout = [w0]; % Uniform random frequencies % Fs/2 will typically be the Nyquist frequency % mu = max(Fs/2*rand(Q,1),1e-8); mu = abs(Fs/2/4*randn(Q,1)); hypout = [hypout; mu]; % Truncated Gaussian for length-scales (1/Sigma) maxlen = max(x) - min(x); % max. distance between any two points in input dimension % was maxlen = length(unique(x)) sigmean = maxlen*sqrt(2*pi)/2; % hypout = [hypout; 1./(abs(maxlen*randn(Q,1)))]; case 'covMaterniso' %hypout = exp(randn(2,1)); maxlen = max(x) - min(x); % max. distance between any two points in input dimension % was maxlen=length(unique(x) a = sqrt(maxlen)*sqrt(pi/2); hypout = [abs(a*randn);stdy]; case 'covSEiso' %hypout = exp(randn(2,1)); maxlen = max(x) - min(x); % max. distance between any two points in input dimension % was maxlen=length(unique(x) a = sqrt(naxlen)*sqrt(pi/2); hypout = [abs(a*randn);stdy]; case 'covConstant' hypout = []; end % Todo: Add SE and MA kernels.
github
neurogeometry/BoutonAnalyzer-master
Optimize_Trace.m
.m
BoutonAnalyzer-master/Optimize_Trace.m
5,971
utf_8
7a405cf45f27f2b1d38acf3e566b401b
% This function works with AM, AMlbl for branches, or AMlbl for trees. % Trees are optimized separately. % Branch positions (r) are optimized, but calibers (R) remain fixed % Branch and end points can be fixed or optimized: % Optimize_bps = 1,0 optimize branch points. % Optimize_tps = 1,0 optimize terminal (start, end) points. % AMlbl in the output is labled for trees % This version of the code is normalized for pointsperpixel as in the paper function [AMlbl,r,I_F,count]=Optimize_Trace(Orig,AMlbl,r,Rtypical,Optimize_bps,Optimize_tps,pointsperum,MaxIterations,alpha_r,betta_r,adjustPPM,output) epsilon=1; % added for stability MinChange_I=10^-6; MinChange_L=betta_r*10^-6; % adjust vertex density if adjustPPM==1 [AM,r,~] = AdjustPPM(AMlbl,r,ones(size(r,1),1),pointsperum); AM=spones(AM); else AM=spones(AMlbl); end if output==1 disp('F1 trace optimization started.') format short g display([' Iteration ', 'I-cost ', ' L-cost ', ' Total Fitness']) end [it,jt]=find(triu(AM,1)); N=length(AM); B=sparse(diag(sum(AM,2))-AM); B3=2.*pointsperum.*blkdiag(alpha_r.*B,alpha_r.*B,alpha_r.*B); W=ceil(2.5*Rtypical)*2+1; NW=(W+1)/2; [xtemp,ytemp,ztemp]=ndgrid(-(NW-1):(NW-1),-(NW-1):(NW-1),-(NW-1):(NW-1)); sizeIm=size(Orig); if length(sizeIm)==2 sizeIm(3)=1; end Orig=double(Orig(:)); Orig=Orig./max(Orig); M=mean(Orig); tps=(sum(AM)==1); bps=(sum(AM)>2); move=true(N,1); if Optimize_tps==0 move(tps)=false; end if Optimize_bps==0 move(bps)=false; end neighb1=nan(N,1); neighb1(it)=jt; neighb1(isnan(neighb1))=find(isnan(neighb1)); neighb1(bps)=NaN; neighb2=nan(N,1); neighb2(jt)=it; neighb2(isnan(neighb2))=find(isnan(neighb2)); neighb2(bps)=NaN; del_r=zeros(size(r)); I_Q=zeros(N,1); I_Qx=zeros(N,1); I_Qy=zeros(N,1); I_Qz=zeros(N,1); I_Pxx=zeros(N,1); I_Pxy=zeros(N,1); I_Pxz=zeros(N,1); I_Pyy=zeros(N,1); I_Pyz=zeros(N,1); I_Pzz=zeros(N,1); I_F=zeros(N,1); temp3=1/(Rtypical^3*pi^1.5*pointsperum); temp4=1/(Rtypical^4*pi^1.5*pointsperum); temp5=1/(Rtypical^5*pi^1.5*pointsperum); count=1; exitflag=0; stepback=0; while exitflag==0 && count<=MaxIterations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Intensity cost, LoG filter for i=1:N xtemp1=xtemp(:)+round(r(i,1)); ytemp1=ytemp(:)+round(r(i,2)); ztemp1=ztemp(:)+round(r(i,3)); temp_ind=(xtemp1>=1 & xtemp1<=sizeIm(1) & ytemp1>=1 & ytemp1<=sizeIm(2) & ztemp1>=1 & ztemp1<=sizeIm(3)); indIm=xtemp1(temp_ind)+(ytemp1(temp_ind)-1).*sizeIm(1)+(ztemp1(temp_ind)-1).*(sizeIm(1)*sizeIm(2)); Itemp=ones(size(xtemp1)).*M; Itemp(temp_ind)=Orig(indIm); xR=(r(i,1)-xtemp1)./Rtypical; yR=(r(i,2)-ytemp1)./Rtypical; zR=(r(i,3)-ztemp1)./Rtypical; r2R2=(xR.^2+yR.^2+zR.^2); EXP=exp(-r2R2).*Itemp; Q=EXP.*(-10/3+(4/3).*r2R2); P=EXP.*(28/3-(8/3).*r2R2); I_Q(i)=sum(Q).*temp5; I_Qx(i)=sum(Q.*xR).*temp4; I_Qy(i)=sum(Q.*yR).*temp4; I_Qz(i)=sum(Q.*zR).*temp4; Px=P.*xR; Py=P.*yR; Pz=P.*zR; I_Pxx(i)=sum(Px.*xR).*temp5; I_Pxy(i)=sum(Px.*yR).*temp5; I_Pxz(i)=sum(Px.*zR).*temp5; I_Pyy(i)=sum(Py.*yR).*temp5; I_Pyz(i)=sum(Py.*zR).*temp5; I_Pzz(i)=sum(Pz.*zR).*temp5; I_F(i)=sum(EXP.*(1-(2/3).*r2R2))*temp3; end dFcostdrR=[I_Qx;I_Qy;I_Qz]-B3*r(:); d2IcostdRr2=[diag(sparse(I_Pxx+I_Q)),diag(sparse(I_Pxy)),diag(sparse(I_Pxz)); diag(sparse(I_Pxy)),diag(sparse(I_Pyy+I_Q)),diag(sparse(I_Pyz)); diag(sparse(I_Pxz)),diag(sparse(I_Pyz)),diag(sparse(I_Pzz+I_Q))]-B3-epsilon.*diag(sparse(ones(3*N,1))); Icost=sum(I_F); Lcost=sum(sum((r(it,:)-r(jt,:)).^2,2))*pointsperum; Fitness=Icost-alpha_r.*Lcost; if count>1 && stepback==0 ChangeIcost=abs((Icost-oldIcost)/oldIcost); ChangeLcost=abs((Lcost-oldLcost)/oldLcost); exitflag=~(ChangeIcost>MinChange_I || ChangeLcost>MinChange_L); if ChangeIcost>0.5 || ChangeLcost>0.5 warning('Trace may be unstable. Decrease Optimization Step Size and/or increase Trace Stiffness parameter.') end end if exitflag==0 if output==1 disp(full([count, Icost, Lcost, Fitness])) end count=count+1; stepback=0; oldIcost=Icost; oldLcost=Lcost; r_old=r; del_rR=d2IcostdRr2\dFcostdrR; del_r(:)=del_rR(1:3*N); l=r(neighb1,:)-r(neighb2,:); l=l./(sum(l.^2,2).^0.5*ones(1,3)); l(isnan(l))=0; del_r=del_r-(sum(del_r.*l,2)*ones(1,3)).*l; abs_del_r=sum(del_r.^2,2).^0.5; inst_ind=abs_del_r>0.1; del_r(inst_ind,:)=del_r(inst_ind,:)./(abs_del_r(inst_ind)*ones(1,3)).*0.1; r(move,:)=r(move,:)-betta_r.*del_r(move,:); % r ranges from 0.5 to sizeIm+0.5 in Matlab and [0 sizeIm] in Java and SWC r(r(:,1)<0.5,1)=0.5; r(r(:,1)>sizeIm(1)+0.5,1)=sizeIm(1)+0.5; r(r(:,2)<0.5,2)=0.5; r(r(:,2)>sizeIm(2)+0.5,2)=sizeIm(2)+0.5; r(r(:,3)<0.5,3)=0.5; r(r(:,3)>sizeIm(3)+0.5,3)=sizeIm(3)+0.5; else r=r_old; betta_r=betta_r./1.1; count=count-1; stepback=1; end end r=r_old; AMlbl = LabelTreesAM(AM); if output==1 disp('F1 trace optimization is complete.') if ChangeIcost>MinChange_I || ChangeLcost>MinChange_L disp('The algorithm did not converge to solution with default precision.') disp('Consider increasing Optimization Step Size and/or Maximum Number of Iterations.') end end
github
neurogeometry/BoutonAnalyzer-master
plotAM.m
.m
BoutonAnalyzer-master/plotAM.m
643
utf_8
ef459959fe9a0c21691aa0c19012211e
% This function plots the tree structure contained in AM. % The function works with labeled or not labeled AM. % AM can be directed or undirected. % The labels don't have to be consecutive. function h=plotAM(AM,r,col) if size(r,2)==2 r=[r,zeros(size(r,1),1)]; end AM = max(AM,AM'); AM = triu(AM); Labels=full(AM(AM(:)>0)); Labels=unique(Labels); L=numel(Labels); if isempty(col) cc=lines(L); else cc=col; end h=hggroup; for f=1:L [i,j]=find(AM==Labels(f)); X=[r(i,1),r(j,1)]'; Y=[r(i,2),r(j,2)]'; Z=[r(i,3),r(j,3)]'; line(Y,X,Z,'Color',cc(L,:),'LineWidth',1,'Parent',h); end
github
neurogeometry/BoutonAnalyzer-master
FastMarchingTube.m
.m
BoutonAnalyzer-master/FastMarchingTube.m
4,471
utf_8
5d4a3e0287fa79356f6c02a4dc0be28c
% This function the Eikonal equation by using the Fast Marching algorithm % of Sethian. T and D are the arival time and distance maps. % Max_Known_Dist is the distance at which re-initialization is performed % SVr contains positions of the seeds % unisotropy is the wave speed unisotropy in a uniform intensity image % Output is Logical KT==1; function [KT]=FastMarchingTube(sizeIM,SVr,Max_Known_Dist,unisotropy) output=false; pad=2; Max_Known_Time=inf; unisotropy(unisotropy<0)=0; if sum(unisotropy)==0 unisotropy=[1,1,1]; end unisotropy=unisotropy./sum(unisotropy.^2)^0.5; h2=[unisotropy(1),unisotropy(1),unisotropy(2),unisotropy(2),unisotropy(3),unisotropy(3)].^2; Orig=ones(sizeIM); sizeOrig=size(Orig); if length(sizeOrig)==2 sizeOrig=[sizeOrig,1]; end Im=zeros(sizeOrig+2*pad); Im(1+pad:end-pad,1+pad:end-pad,1+pad:end-pad)=Orig; clear Orig sizeIm=sizeOrig+2*pad; SVr=round(SVr);%Matlab IM pixel goes from 0.5 to 1.5 etc. SVr=SVr+pad; StartVoxel=sub2ind_ASfast(sizeIm,SVr(:,1),SVr(:,2),SVr(:,3)); StartVoxel=unique(StartVoxel); N6_ind=[-1;+1;-sizeIm(1);+sizeIm(1);-sizeIm(1)*sizeIm(2);+sizeIm(1)*sizeIm(2)]; T=inf(sizeIm,'single'); T(StartVoxel)=0; D=inf(sizeIm,'single'); D(StartVoxel)=0; KT=zeros(sizeIm,'uint8'); KT(StartVoxel)=1; % Known=1, Trial=2 KnownPoints=StartVoxel; NHood=[KnownPoints+N6_ind(1);KnownPoints+N6_ind(2);KnownPoints+N6_ind(3); ... KnownPoints+N6_ind(4);KnownPoints+N6_ind(5);KnownPoints+N6_ind(6)]; NHood(KT(NHood)==1)=[]; NHood(Im(NHood)==0)=[]; %For padding NHood=unique(NHood); TrialPoints=NHood(~isinf(T(NHood))); T_TrialPoints=T(TrialPoints); stop_cond=true; if isempty(NHood) stop_cond=false; exit_flag='end'; end NewKnownPoint=[]; iter=0; while stop_cond iter=iter+1; if mod(iter,1000)==0 && output display(['Current distance: ', num2str(D(NewKnownPoint))]); end if ~isempty(NHood) ind=[NHood+N6_ind(1),NHood+N6_ind(2),NHood+N6_ind(3),NHood+N6_ind(4),NHood+N6_ind(5),NHood+N6_ind(6)]; KT_1=(KT(ind)~=1); Tpm_xyz=T(ind); Tpm_xyz(KT_1)=inf; [Tpm_xyz,IX]=sort(Tpm_xyz,2); Dpm_xyz=D(ind); Dpm_xyz(KT_1)=inf; Dpm_xyz=sort(Dpm_xyz,2); %Calculate arrival time, T, and distance, D, for the trial %points------------------------------------------------------------ H=h2(IX); H_cum=cumsum(H,2); ct=1./Im(NHood).^2; Tpm_xyz_cum=cumsum(Tpm_xyz.*H,2); Tpm_xyz2_cum=cumsum(Tpm_xyz.^2.*H,2); nt=sum(((Tpm_xyz2_cum-Tpm_xyz_cum.^2./H_cum)<=ct*ones(1,size(Tpm_xyz,2))),2); if sum(h2==0)>0 nt(nt==0)=1; end ind_nt=(1:size(Tpm_xyz,1))'+(nt-1).*size(Tpm_xyz,1); ntH=H_cum(ind_nt); temp=Tpm_xyz_cum(ind_nt); T(NHood)=(temp+(ct.*ntH-(Tpm_xyz2_cum(ind_nt).*ntH-temp.^2)).^0.5)./ntH; N=ones(size(Tpm_xyz,1),1)*(1:size(Tpm_xyz,2)); Dpm_xyz_cum=cumsum(Dpm_xyz,2); Dpm_xyz2_cum=cumsum(Dpm_xyz.^2,2); nd=sum(((Dpm_xyz2_cum-Dpm_xyz_cum.^2./N)<=ones(size(Dpm_xyz))),2); ind_nd=(1:size(Dpm_xyz,1))'+(nd-1).*size(Dpm_xyz,1); temp=Dpm_xyz_cum(ind_nd); D(NHood)=(temp+(nd-(Dpm_xyz2_cum(ind_nd).*nd-temp.^2)).^0.5)./nd; %------------------------------------------------------------------ keep=NHood(KT(NHood)==0 & ~isinf(T(NHood))); KT(keep)=2; TrialPoints=[TrialPoints;keep]; T_TrialPoints=[T_TrialPoints;T(keep)]; end [min_T,min_ind]=min(T_TrialPoints); NewKnownPoint=TrialPoints(min_ind); if ~isempty(NewKnownPoint) && ~isinf(min_T) KT(NewKnownPoint)=1; T_TrialPoints(min_ind)=inf; NHood=NewKnownPoint+N6_ind; KnownPoints=[KnownPoints;NewKnownPoint]; NHood(KT(NHood)==1)=[]; NHood(Im(NHood)==0)=[]; %Remove points in padding if T(NewKnownPoint)>=Max_Known_Time stop_cond=false; exit_flag='time'; % maximum time reached end if D(NewKnownPoint)>=Max_Known_Dist; stop_cond=false; exit_flag='dist'; % maximum distance reached end else stop_cond=false; exit_flag='end'; % No place to propagate. end end KT=KT(1+pad:end-pad,1+pad:end-pad,1+pad:end-pad); KT=(KT==1); % D=D(1+pad:end-pad,1+pad:end-pad,1+pad:end-pad); % D(KT==0)=max(D(KT)); % D=double((max(D(:))-D)./max(D(:))); end
github
neurogeometry/BoutonAnalyzer-master
profilefilters.m
.m
BoutonAnalyzer-master/profilefilters.m
4,319
utf_8
dc109b321906ffba43afbcb7c0059c56
function [II, RR]= profilefilters (r,IM,filtertype,params) if strcmp(filtertype,'LoGxy') %LoGxy filter options LoGxy_R_min=params.filt.LoGxy_R_min; LoGxy_R_step=params.filt.LoGxy_R_step; LoGxy_R_max=params.filt.LoGxy_R_max; LoGxy_Rz=params.filt.LoGxy_Rz; [II,RR] = LoG_Filt_xy(IM,r,LoGxy_R_min,LoGxy_R_step,LoGxy_R_max,LoGxy_Rz); elseif strcmp(filtertype,'Gauss') %Gaussian filter Gauss_R=params.filt.Gauss_R; [II,RR]=Gauss_Filt(IM,r,Gauss_R,1,Gauss_R); else display('Filter ',filtertype, ' not found'); end end %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- function [I,Rxy] = LoG_Filt_xy(Orig,r,Rxy_min,Rxy_step,Rxy_max,Rz) if Rxy_min<0.1 Rxy_min=0.1; end s=(Rxy_min:Rxy_step:Rxy_max)'; if isempty(s) Rxy=zeros(size(r(:,1))); I=zeros(size(r(:,1)))'; else r=round(r); del=0.01*Rxy_min; N=size(r,1); sizeIm=size(Orig); if length(sizeIm)==2 sizeIm=[sizeIm,1]; end W=ceil(2*max([Rxy_max,Rz]))*2+1; HW=(W-1)/2; S=[W,W,W]; [xtemp,ytemp,ztemp]=ind2sub(S,1:prod(S)); Itemp=zeros(prod(S),N); for i=1:N, xtemp1=xtemp+r(i,1)-HW-1; ytemp1=ytemp+r(i,2)-HW-1; ztemp1=ztemp+r(i,3)-HW-1; temp_ind=(xtemp1>=1 & xtemp1<=sizeIm(1) & ytemp1>=1 & ytemp1<=sizeIm(2) & ztemp1>=1 & ztemp1<=sizeIm(3)); indIm=sub2ind_ASfast(sizeIm,xtemp1(temp_ind),ytemp1(temp_ind),ztemp1(temp_ind)); Im_S=zeros(S); Im_S(temp_ind)=double(Orig(indIm)); Itemp(:,i)=Im_S(:); end xy2=(HW+1-xtemp).^2+(HW+1-ytemp).^2; Gxym=exp(-(1./(s-del).^2)*xy2).*((1./(s-del).^2)*ones(1,prod(S))); Gxym=Gxym./(sum(Gxym,2)*ones(1,prod(S))); Gxyp=exp(-(1./(s+del).^2)*xy2).*((1./(s+del).^2)*ones(1,prod(S))); Gxyp=Gxyp./(sum(Gxyp,2)*ones(1,prod(S))); z2=(HW+1-ztemp).^2; Gz=exp(-(1./Rz.^2)*z2)./Rz; Gz=Gz./sum(Gz,2); LoG=(Gxym-Gxyp)./(2*del).*(s*ones(1,prod(S))).*(ones(length(s),1)*Gz); %correct up to a numerical factor I_LoG=LoG*Itemp; if length(s)>1 [I,ind]=max(I_LoG); Rxy=s(ind); else I=I_LoG; Rxy=s.*ones(size(r(:,1))); end end I=I(:); Rxy=Rxy(:); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [I,R] = Gauss_Filt(Orig,r,R_min,R_step,R_max) if R_min<0.1 R_min=0.1; end s=(R_min:R_step:R_max)'; if isempty(s) R=zeros(size(r(:,1))); I=zeros(size(r(:,1)))'; else r=round(r); N=size(r,1); sizeIm=size(Orig); if length(sizeIm)==2 sizeIm=[sizeIm,1]; end W=ceil(2*max(s))*2+1; HW=(W-1)/2; S=[W,W,W]; [xtemp,ytemp,ztemp]=ind2sub(S,1:prod(S)); Itemp=zeros(prod(S),N); for i=1:N, xtemp1=xtemp+r(i,1)-HW-1; ytemp1=ytemp+r(i,2)-HW-1; ztemp1=ztemp+r(i,3)-HW-1; temp_ind=(xtemp1>=1 & xtemp1<=sizeIm(1) & ytemp1>=1 & ytemp1<=sizeIm(2) & ztemp1>=1 & ztemp1<=sizeIm(3)); indIm=sub2ind_ASfast(sizeIm,xtemp1(temp_ind),ytemp1(temp_ind),ztemp1(temp_ind)); Im_S=zeros(S); Im_S(temp_ind)=double(Orig(indIm)); Itemp(:,i)=Im_S(:); end r2=(HW+1-xtemp).^2+(HW+1-ytemp).^2+(HW+1-ztemp).^2; Gp=exp(-(1./(s).^2)*r2).*((1./(s).^3)*ones(1,prod(S))); Gp=Gp./(sum(Gp,2)*ones(1,prod(S))); I_Gauss=Gp*Itemp; if length(s)>1 [I,ind]=max(I_Gauss); R=s(ind); else I=I_Gauss; R=s.*ones(size(r(:,1))); end end I=I(:); R=R(:); end %-------------------------------------------------------------------------- function [I_mean,I_median] = Simple_Filts(Orig,r,filt_size) r=round(r); sizeIM=size(Orig); HW=(filt_size-1); minx=round(max(1,(r(:,1)-round(HW(1)/2)))); maxx=round(min((r(:,1)+round(HW(1)/2)),sizeIM(1))); miny=round(max(1,(r(:,2)-round(HW(2)/2)))); maxy=round(min((r(:,2)+round(HW(2)/2)),sizeIM(2))); minz=round(max(1,(r(:,3)-round(HW(3)/2)))); maxz=round(min((r(:,3)+round(HW(3)/2)),sizeIM(3))); I_mean=nan(size(r,1),1); I_median=nan(size(r,1),1); for i=1:size(r,1) IMval=Orig(minx(i):maxx(i),miny(i):maxy(i),minz(i):maxz(i)); I_mean(i)=mean(IMval(:)); I_median(i)=median(IMval(:)); end end
github
neurogeometry/BoutonAnalyzer-master
AM2swc.m
.m
BoutonAnalyzer-master/AM2swc.m
3,317
utf_8
964b9a6ab8a971b47d17295439d0695f
% This function converts AMlbl r R format to swc. Reduction done during image % loading is inverted. AMlbl must not contain loops. function swc_all = AM2swc(AMlbl,r,R,reduction_x,reduction_y,reduction_z) rem_ind=(sum(AMlbl)==0); AMlbl(rem_ind,:)=[]; AMlbl(:,rem_ind)=[]; r(rem_ind,:)=[]; R(rem_ind)=[]; if isempty(AMlbl) swc_all=0; else swc_all=AM2swc_temp(AMlbl,r,R,reduction_x,reduction_y,reduction_z); end %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- function swc = AM2swc_temp(AMlbl,r,R,reduction_x,reduction_y,reduction_z) r=r-0.5; % r ranges from 0.5 to sizeIm+0.5 in Matlab and [0 sizeIm] in Java and SWC L=unique(AMlbl(AMlbl>0)); swc=zeros(sum(AMlbl(:)>0)/2+length(L),7); swc(:,1)=(1:length(swc(:,1))); swc(:,2)=10; Current_id=1; for i=1:length(L) AMtree=(AMlbl==L(i)); Current_vertex=find(sum(AMtree,1)==1,1); if ~isempty(Current_vertex) swc(Current_id,7)=-1; swc(Current_id,3:5)=r(Current_vertex,:); swc(Current_id,6)=R(Current_vertex); Active_Roots=[]; Active_Roots_pid=[]; while nnz(AMtree)>0 || ~isempty(Active_Roots) Current_id=Current_id+1; Next_verts=(AMtree(Current_vertex,:)); Neighb=sum(Next_verts); if Neighb==0 if ~isempty(Active_Roots) Next_vertex=Active_Roots(1); Current_vertex=Next_vertex; swc(Current_id,7)=Active_Roots_pid(1); swc(Current_id,3:5)=r(Current_vertex,:); swc(Current_id,6)=R(Current_vertex); Active_Roots(1)=[]; Active_Roots_pid(1)=[]; else Current_vertex=find(sum(AMtree,1)==1,1); swc(Current_id,7)=-1; swc(Current_id,3:5)=r(Current_vertex,:); swc(Current_id,6)=R(Current_vertex); end elseif Neighb==1 Next_vertex=find(Next_verts,1); AMtree(Current_vertex,Next_vertex)=0; AMtree(Next_vertex,Current_vertex)=0; Current_vertex=Next_vertex; swc(Current_id,7)=Current_id-1; swc(Current_id,3:5)=r(Current_vertex,:); swc(Current_id,6)=R(Current_vertex); else Next_vertex=find(Next_verts,1); AMtree(Current_vertex,Next_verts)=0; AMtree(Next_verts,Current_vertex)=0; Active_Roots=[Active_Roots,find(Next_verts,Neighb-1,'last')]; Active_Roots_pid=[Active_Roots_pid,(Current_id-1).*ones(1,Neighb-1)]; Current_vertex=Next_vertex; swc(Current_id,7)=Current_id-1; swc(Current_id,3:5)=r(Current_vertex,:); swc(Current_id,6)=R(Current_vertex); end end Current_id=Current_id+1; end end swc(:,3:4)=[swc(:,4),swc(:,3)]; swc(:,3)=swc(:,3).*reduction_y; swc(:,4)=swc(:,4).*reduction_y; swc(:,5)=swc(:,5).*reduction_z; swc(:,6)=swc(:,6).*(reduction_x*reduction_y*reduction_z).^(1/3);
github
neurogeometry/BoutonAnalyzer-master
updateProfile.m
.m
BoutonAnalyzer-master/updateProfile.m
3,418
utf_8
f56672094ce0bb36d08e9dde37ea8e44
function updateProfile(hf) %This function ensures that assigned fg.id are in a sorted order based on %distance along the trace. In addition, removal of peaks can require %re-labeling of existing matches, which is accomplished by the call to %addrempeaklbl UserData=hf.UserData;hf.UserData=[];%For speed reasons channel=UserData.inform.channel{1}; current_fgid=[]; relbl_fgid=[]; match_id=[]; Time=cell(numel(UserData.Profile),1); for ti=1:numel(UserData.Profile) Time{ti}.fg_id=UserData.Profile{ti}.fit.(channel).LoGxy.fg.id; Time{ti}.fg_manid=UserData.Profile{ti}.fit.(channel).LoGxy.fg.manid; Time{ti}.fg_ind=UserData.Profile{ti}.fit.(channel).LoGxy.fg.ind; end for ti=1:numel(UserData.Profile) current_fgid=cat(1,current_fgid,Time{ti}.fg_id(:)); match_id=cat(1,match_id,Time{ti}.fg_manid(:)); [~,si]=sort(Time{ti}.fg_ind(:));%Index, not id temp=nan(size(Time{ti}.fg_id(:))); temp(si)=min(Time{ti}.fg_id)+(1:numel(Time{ti}.fg_id(:)))-1; relbl_fgid=cat(1,relbl_fgid,temp(:)); end [~,new_match_id] = addrempeaklblAM (relbl_fgid,match_id); for ti=1:length(Time) [lia,~]=ismember(current_fgid,Time{ti}.fg_id); in_ti=find(lia); mu=nan(size(in_ti)); amp=nan(size(in_ti)); sig=nan(size(in_ti)); flg=nan(size(in_ti)); fgid=relbl_fgid(in_ti); old_fgid=current_fgid(in_ti); manid=new_match_id(in_ti); autoid=nan(size(in_ti)); ind=Time{ti}.fg_ind(:); for inlist=1:numel(fgid) inorig=find(UserData.Profile{ti}.fit.(channel).LoGxy.fg.id==old_fgid(inlist)); if ~isempty(inorig) mu(inlist)=UserData.Profile{ti}.fit.(channel).LoGxy.fg.mu(inorig); amp(inlist)=UserData.Profile{ti}.fit.(channel).LoGxy.fg.amp(inorig); sig(inlist)=UserData.Profile{ti}.fit.(channel).LoGxy.fg.sig(inorig); flg(inlist)=UserData.Profile{ti}.fit.(channel).LoGxy.fg.flag(inorig); end end UserData.Profile{ti}.fit.(channel).LoGxy.fg.ind=ind; UserData.Profile{ti}.fit.(channel).LoGxy.fg.mu=mu; UserData.Profile{ti}.fit.(channel).LoGxy.fg.sig=sig; UserData.Profile{ti}.fit.(channel).LoGxy.fg.amp=amp; UserData.Profile{ti}.fit.(channel).LoGxy.fg.id=fgid; UserData.Profile{ti}.fit.(channel).LoGxy.fg.manid=manid; UserData.Profile{ti}.fit.(channel).LoGxy.fg.autoid=autoid; UserData.Profile{ti}.fit.(channel).LoGxy.fg.flag=flg; [~,si]=sort(UserData.Profile{ti}.fit.(channel).LoGxy.fg.ind); fn=fieldnames(UserData.Profile{ti}.fit.(channel).LoGxy.fg); for f=1:numel(fn) UserData.Profile{ti}.fit.(channel).LoGxy.fg.(fn{f})=UserData.Profile{ti}.fit.(channel).LoGxy.fg.(fn{f})(si); end end hf.UserData=UserData; end %-------------------------------------------------------------------------- function [AM,matchidnew] = addrempeaklblAM (origid,matchid) %This function takes a list of unique bouton id and matched bouton id %to create an adjacency matrix. matchid is updated to reflect AM. This will %be used to ensure consistency after changing bouton labels. AM=zeros(size(origid,1)); matchidnew=nan(size(origid,1),1); mid=unique(matchid(~isnan(matchid))); for m=1:numel(mid) conid=sort(origid(matchid==mid(m))); matchidnew(matchid==mid(m))=conid(1); [~,AMind] = ismember(conid,origid); for i=1:(numel(AMind)-1) AM(AMind(i),AMind(i+1))=conid(1); AM(AMind(i+1),AMind(i))=conid(1); end end end
github
neurogeometry/BoutonAnalyzer-master
ImportStackJ.m
.m
BoutonAnalyzer-master/ImportStackJ.m
1,791
utf_8
066057b9ee6616481e3155413ab88b5c
% This function imports images into MatLab. RGB images are converted to % grayscale. Data format of Orig is preserved (uint8, uint16, etc). function [Orig,sizeOrig,classOrig]=ImportStackJ(pth,file_list) Orig=[]; sizeOrig=[]; classOrig=[]; N=length(file_list); info = imfinfo([pth,file_list{1}]); Npl=length(info); if N==0 disp('There are no images which pass the file selection criteria.') return elseif N==1 && Npl>1 %import a virtual stack (tif or LSM) temp = imread([pth,file_list{1}],'Index',1); classOrig=class(temp); formatOrig=size(temp,3); sizeOrig=fix([size(temp,1),size(temp,2),Npl]); Orig=zeros(sizeOrig,classOrig); for i=1:Npl temp = imread([pth,file_list{1}],'Index',i); if formatOrig==3 temp=rgb2gray(temp); end Orig(:,:,i) = temp; end elseif N>1 || (N==1 && Npl==1) %import a set of regular images if Npl>1 disp('Unable to load multiple virtual stacks.') return end temp = imread([pth,file_list{1}]); for i=2:N info = imfinfo([pth,file_list{i}]); if length(info)>1 disp('Unable to load multiple virtual stacks.') return end if info.Height~=size(temp,1) || info.Width~=size(temp,2) disp('Unable to load. Images have different dimensions.') return end end classOrig=class(temp); formatOrig=size(temp,3); sizeOrig=fix([size(temp,1),size(temp,2),N]); Orig=zeros(sizeOrig,classOrig); for i=1:N temp = imread([pth,file_list{i}]); if formatOrig==3 temp=rgb2gray(temp); end Orig(:,:,i) = temp; end end
github
neurogeometry/BoutonAnalyzer-master
LabelBranchesAM.m
.m
BoutonAnalyzer-master/LabelBranchesAM.m
1,097
utf_8
ea1bc5783fe1d5a6940da903652809ec
% This function labels individual branches in AM by using Depth First Search. % The function works even when there are several disconnected trees in the AM function AMlbl = LabelBranchesAM(AM) AM=spones(AM+AM'); AM=AM-diag(diag(AM)); Remaining=find(sum(AM,1)==1 | sum(AM,1)>2); AMlbl=AM; AMlbl(AMlbl==1)=NaN; CurrentLabel=1; while sum(isnan(AMlbl(:)))>0 if isempty(Remaining) Remaining=find(isnan(sum(AMlbl,1)),1); end BegVert=Remaining(1); NeighVert=find(isnan(AMlbl(BegVert,:)),1); AMlbl(BegVert,NeighVert)=CurrentLabel; AMlbl(NeighVert,BegVert)=CurrentLabel; if sum(isnan(AMlbl(Remaining(1),:)))==0 Remaining(1)=[]; end while sum(AM(NeighVert,:))==2 && isnan(sum(AMlbl(NeighVert,:))) BegVert=NeighVert; NeighVert=find(isnan(AMlbl(BegVert,:)),1); AMlbl(BegVert,NeighVert)=CurrentLabel; AMlbl(NeighVert,BegVert)=CurrentLabel; end if sum(isnan(AMlbl(NeighVert,:)))==0 Remaining(Remaining==NeighVert)=[]; end CurrentLabel=CurrentLabel+1; end
github
neurogeometry/BoutonAnalyzer-master
BoutonAnalyzer.m
.m
BoutonAnalyzer-master/BoutonAnalyzer.m
6,273
utf_8
87972725983ca960cac7bc42612f1e9e
function BoutonAnalyzer() temp=get(0); fi.H=400; fi.W=600; fi.L=temp.ScreenSize(3)/2-fi.W/2; fi.B=temp.ScreenSize(4)/2-fi.H/2; hf=figure; hf.Position=[fi.L,fi.B,fi.W,fi.H]; hf.MenuBar='none'; hf.NumberTitle='off'; hf.Name='Bouton Analyzer'; workingdir=pwd; cbfcn=['open(''',workingdir,filesep,'User Manual.pdf'')']; hfmenu=uimenu('Label','Help','Parent',hf); uimenu(hfmenu,'Label','User Manual','Callback',cbfcn); uimenu(hfmenu,'Label','Website','Callback','web(''http://www.northeastern.edu/neurogeometry/resources/bouton-analyzer/'')'); ha=axes('Parent',hf); %Initialize axis ha.Units='Normalized';ha.Position=[0 0.65 1 0.3]; ha.Color=[0.94 0.94 0.94];box(ha,'off'); ha.NextPlot='add'; %Plot projection [im,~,alpha] = imread('Icon.png'); f=imshow(im,'Parent',ha); set(f,'AlphaData',alpha); axis(ha,'off'); pathlist; h_viewpanel=uipanel('Parent',hf);h_viewpanel.Tag='Paths'; h_viewpanel.Units='pixels';h_viewpanel.Position=[10 100 580 160]; h_viewpanel.Title='Paths'; hf.UserData.Im=im_pth; hf.UserData.Trace=man_pth; hf.UserData.Profile=profile_pth; hf.UserData.Results=proc_pth; %Images-------------------------------------------------------------------- uicontrol('Style', 'text','Parent',h_viewpanel,... 'Units','normalized','Position', [0.02 0.7 0.15 0.15],... 'String','Images: '); him=uicontrol('Style','edit','Parent',h_viewpanel,'Tag','Impthtxt',... 'Units','normalized','Position',[0.20 0.7 0.6 0.15],... 'String',hf.UserData.Im,'Callback',@chkpth,'Enable','on'); uicontrol('Style','pushbutton','Parent',h_viewpanel,'Tag','Impthbtn',... 'Units','normalized','Position',[0.82 0.7 0.1 0.15],... 'String','Choose',... 'Callback',{@setpth,him}); %Traces-------------------------------------------------------------------- uicontrol('Style', 'text','Parent',h_viewpanel,... 'Units','normalized','Position', [0.02 0.5 0.15 0.15],... 'String','Traces: '); htr=uicontrol('Style','edit','Parent',h_viewpanel,'Tag','Tracepthtxt',... 'Units','normalized','Position',[0.20 0.5 0.6 0.15],... 'String',hf.UserData.Trace,'Callback',@chkpth,'Enable','on'); uicontrol('Style','pushbutton','Parent',h_viewpanel,'Tag','Tracepthbtn',... 'Units','normalized','Position',[0.82 0.5 0.1 0.15],... 'String','Choose',... 'Callback',{@setpth,htr}); %Profiles------------------------------------------------------------------ uicontrol('Style','text','Parent',h_viewpanel,... 'Units','normalized','Position', [0.02 0.3 0.15 0.15],... 'String','Profiles: '); hpr=uicontrol('Style','edit','Parent',h_viewpanel,'Tag','Profilepthtxt',... 'Units','normalized','Position',[0.20 0.3 0.6 0.15],... 'String',hf.UserData.Profile,'Callback',@chkpth,'Enable','on'); uicontrol('Style','pushbutton','Parent',h_viewpanel,'Tag','Profilepthbtn',... 'Units','normalized','Position',[0.82 0.3 0.1 0.15],... 'String','Choose',... 'Callback',{@setpth,hpr}); %Proc------------------------------------------------------------------ uicontrol('Style','text','Parent',h_viewpanel,... 'Units','normalized','Position', [0.02 0.1 0.15 0.15],... 'String','Results: '); hprc=uicontrol('Style','edit','Parent',h_viewpanel,'Tag','Procpthtxt',... 'Units','normalized','Position',[0.20 0.1 0.6 0.15],... 'String',hf.UserData.Results,'Callback',@chkpth,'Enable','on'); uicontrol('Style','pushbutton','Parent',h_viewpanel,'Tag','Procpthbtn',... 'Units','normalized','Position',[0.82 0.1 0.1 0.15],... 'String','Choose',... 'Callback',{@setpth,hprc}); %Launch GUi panel---------------------------------------------------------- h_viewpanel=uipanel('Parent',hf);h_viewpanel.Tag='Launch'; h_viewpanel.Units='pixels';h_viewpanel.Position=[10 10 580 80]; h_viewpanel.Title='Launch GUI'; uicontrol('Style','pushbutton','Parent',h_viewpanel,'Tag','Tracepthbtn',... 'Units','normalized','Position',[0.30 0.55 0.4 0.4],... 'String','Optimize Trace & Generate Profile',... 'Callback',{@launchgui,1}); uicontrol('Style','pushbutton','Parent',h_viewpanel,'Tag','Tracepthbtn',... 'Units','normalized','Position',[0.30 0.1 0.4 0.4],... 'String','Detect & Track Boutons',... 'Callback',{@launchgui,2}); end %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- function []=setpth(src,~,h) histfile=[pwd,filesep,'tmp',filesep,'paths.mat']; maindir=fileparts(pwd); temp=uigetdir(maindir); if temp %uigetdir returns 0 when cancelled h.String=[temp,filesep];%Update the text field if exist(histfile,'file') custompth=load(histfile); end end ht=findobj(src.Parent,'Tag','Impthtxt'); custompth.im_pth=ht.String; ht=findobj(src.Parent,'Tag','Tracepthtxt'); custompth.man_pth=ht.String; ht=findobj(src.Parent,'Tag','Profilepthtxt'); custompth.profile_pth=ht.String; ht=findobj(src.Parent,'Tag','Procpthtxt'); custompth.proc_pth=ht.String; save(histfile,'-struct','custompth'); end function []=launchgui(~,~,h) if h==1 gui_optimization(gcbf); elseif h==2 gui_alignment(gcbf); end end function []=chkpth(src,~) histfile=[pwd,filesep,'tmp',filesep,'paths.mat']; if exist(src.String,'dir') if ~strcmp(src.String(end),filesep) src.String=[src.String,filesep]; end if exist(histfile,'file') custompth=load(histfile); end disp(['Path set: ',src.String]); ht=findobj(src.Parent,'Tag','Impthtxt'); custompth.im_pth=ht.String; ht=findobj(src.Parent,'Tag','Tracepthtxt'); custompth.man_pth=ht.String; ht=findobj(src.Parent,'Tag','Profilepthtxt'); custompth.profile_pth=ht.String; ht=findobj(src.Parent,'Tag','Procpthtxt'); custompth.proc_pth=ht.String; save(histfile,'-struct','custompth'); else disp('Directory does not exist.'); pathlist; switch src.Tag case 'Impthtxt' src.String=im_pth; case 'Tracepthtxt' src.String=man_pth; case 'Profilepthtxt' src.String=profile_pth; case 'Procpthtxt' src.String=proc_pth; end end end
github
neurogeometry/BoutonAnalyzer-master
gui_alignment_defineframe.m
.m
BoutonAnalyzer-master/gui_alignment_defineframe.m
5,391
utf_8
347c2a1194dd679b003548d3c7a6c8e4
function [] = gui_alignment_defineframe(hf) gui_alignment_layout; %------------------------------Operation Panel----------------------------- h_operation=uipanel('Parent',hf);h_operation.Tag='Operation'; h_operation.Units='pixels';h_operation.Position=[panel_l,operationpanel_b,panel_w,operationpanel_h]; h_operation.Title=''; %Mode select h_mode = uibuttongroup('Tag','Mode','Parent',h_operation,... 'Units','pixels','Position',[0,operationpanel_mode_b,panel_w,operationpanel_mode_h],... 'SelectionChangedFcn',{@operationPanelController,hf},... 'Title','','BorderType','none'); modechoices={'Align Traces','Annotate Traces','Detect Peaks'}; nbtn=3; for n=1:nbtn mode_rb=uicontrol('Style','radiobutton','Parent',h_mode); mode_rb.Units='pixels';mode_rb.Position=[stdbuff_w,(nbtn-n)*(rbtn_h+minbuff_h)+stdbuff_h+1, element_w, rbtn_h]; mode_rb.String=modechoices{n}; mode_rb.Enable='off'; end %Object select h_object = uibuttongroup('Tag','Object','Parent',h_operation,... 'Units','pixels','Position',[0,operationpanel_object_b,panel_w,operationpanel_object_h],... 'SelectionChangedFcn',{@operationPanelController,hf},... 'Title','');%,'BorderType','none'); objectchoices={'Edit Peaks','Match Peaks'}; nbtn=numel(objectchoices); for n=1:nbtn obj_rb=uicontrol('Style','radiobutton','Parent',h_object); obj_rb.Units='pixels';obj_rb.Position=[stdbuff_w,(nbtn-n)*(rbtn_h+minbuff_h)+stdbuff_h+1, element_w, rbtn_h]; obj_rb.String=objectchoices{n}; obj_rb.Enable='off'; end %Save profile button uicontrol('Style', 'pushbutton','Tag','SaveProfile','Parent',h_operation,... 'Units','pixels','Position',[stdbuff_w, savebutton_b+1, element_w, pushbutton_h],... 'String', 'Save','Callback',{@saveProfile,hf},'Enable','off'); %New Axon button uicontrol('Style', 'pushbutton','Tag','LoadNextAxon','Parent',h_operation,... 'Units','pixels','Position',[stdbuff_w, newaxonbtn_b+1 element_w, pushbutton_h],... 'String', 'Load Next','Callback',{@loadnext,hf},'Enable','on'); %------------------------------View Panel---------------------------------- h_viewpanel=uipanel('Parent',hf);h_viewpanel.Tag='ViewPanel'; h_viewpanel.Units='pixels';h_viewpanel.Position=[panel_l,viewpanel_b,panel_w,viewpanel_h]; h_viewpanel.Title='View Options'; %Contrast setting uicontrol('Style', 'text','Parent',h_viewpanel,... 'Units','pixels','Position', [stdbuff_w, view_intrange_b+txtbx_h+minbuff_h, element_w, txt_h],... 'String','Intensity range'); uicontrol('Style','edit','Parent',h_viewpanel,'Tag','ContrastValue',... 'Units','pixels','Position',[stdbuff_w,view_intrange_b, element_w, txtbx_h],... 'Callback',{@viewPanelController,hf},... 'ToolTipString','e.g. 0, 100'); %Position setting uicontrol('Style', 'text','Parent',h_viewpanel,... 'Units','pixels','Position', [stdbuff_w, view_shift_b+txtbx_h+minbuff_h, element_w, txt_h],... 'String',sprintf('Shift: down, right (px)')); uicontrol('Style','edit','Tag','ShiftValue','Parent',h_viewpanel,... 'Units','pixels','Position',[stdbuff_w, view_shift_b, element_w, txtbx_h],... 'Callback',{@viewPanelController,hf},... 'ToolTipString','e.g. -10, 15'); %Toggle channel sel_ch = uibuttongroup('Tag','Channel','Parent',h_viewpanel,... 'Units','pixels','Position',[0, view_chnrb_b, panel_w, view_chnrb_h],... 'SelectionChangedFcn',{@viewPanelController,hf},... 'Title','Channel','BorderType','none'); nbtn=3; channel=fieldnames(hf.UserData.Profile{1}.proj); for n=1:nbtn ch_rb=uicontrol('Style','radiobutton','Parent',sel_ch); ch_rb.Units='pixels';ch_rb.Position=[stdbuff_w,(nbtn-n)*(rbtn_h+minbuff_h)+minbuff_h, element_w, rbtn_h]; if n<=numel(channel) ch_rb.String=channel{n}; ch_rb.Enable='on'; else ch_rb.String='-NA-'; ch_rb.Enable='off'; end end sel_ch.SelectedObject=findobj(sel_ch,'String',hf.UserData.inform.channel{1}); %Toggle normalized h_norm = uibuttongroup('Tag','RelativeIntensity','Parent',h_viewpanel,... 'Units','pixels','Position',[0,stdbuff_h,panel_w,view_relintrb_h],... 'SelectionChangedFcn',{@viewPanelController,hf},... 'Title','Image intensity','BorderType','none'); normchoices={'Raw','Normalized'}; nbtn=numel(normchoices); for n=1:nbtn norm_rb=uicontrol('Style','radiobutton','Parent',h_norm); norm_rb.Units='pixels';norm_rb.Position=[stdbuff_w,(nbtn-n)*(rbtn_h+minbuff_h)+minbuff_h, element_w, rbtn_h]; norm_rb.String=normchoices{n}; norm_rb.Enable='on'; end h_norm.SelectedObject=findobj(h_norm,'String','Raw'); %----------------------------Initialize axis------------------------------- h_axis=axes('Parent',hf);h_axis.Tag='Axis'; h_axis.Units='pixels';h_axis.Position=[2*buff.w+panel_w+buff.h,buff.h,xyaxis_w,xyaxis_w]; h_axis.YLabel.String='X axis, [pixels]';h_axis.XLabel.String='Y axis, [pixels]'; h_axis.XLim=[0 1000];h_axis.YLim=[0 1000]; h_axis.Color=[0.4 0.4 0.4];box(h_axis,'on'); h_axis.NextPlot='add'; %Initialize selected vertices group h_sv=hggroup('Parent',h_axis); h_sv.Tag='SelVerts'; end function [] = loadnext(~,~,hf) close(hf); if ~isvalid(hf) gui_alignment([]); else disp('Current axon was retained. Load new axon operation terminated.') end end
github
neurogeometry/BoutonAnalyzer-master
gui_alignment.m
.m
BoutonAnalyzer-master/gui_alignment.m
8,260
utf_8
89f47bb5669ce220107bc3f6689b9190
function gui_alignment(src) %Function allows %1. view projections of all traces simultaneously and align traces %2. annotate traces to exclude cross-overs etc %3. editing and matching of peaks (putative boutons) close(src); temp=get(0); fi.H=max([700,temp.ScreenSize(4)*0.8]); fi.W=max([875,fi.H*5/4]); fi.L=(fi.W.*0.1); fi.B=(fi.H.*0.1); hf=figure('Visible','off');clf(hf); hf.Name='BoutonAnalyzer: Detection & Tracking';hf.NumberTitle='off';hf.Tag='Main'; hf.Position=[fi.L,fi.B,fi.W,fi.H]; set(hf,'KeyPressFcn',@hotkeys); set(hf,'WindowScrollWheelFcn',@scroll2zoom); customizeMenus(hf); %Set data [~,Profile,~,inform,exitstatus] = gui_loaddata(0,1,0,'gui_alignment'); if exitstatus==1 set(hf,'CloseRequestFcn',@closereqf) hf.UserData.profilefig=figure('Visible','off'); set(hf,'DeleteFcn',{@closeProfileFig,hf}); hf.UserData.Profile=Profile;clear Profile; hf.UserData.inform=inform; %Set GUI related parameters hf.UserData.AnalysisStatus=1; hf.UserData.AlignVerts.ind=[]; hf.UserData.AlignVerts.t=[]; hf.UserData.relshiftx=[]; hf.UserData.relshifty=[]; hf.UserData.normfactor=[]; %Define the GUI frame with all buttons and axes gui_alignment_defineframe(hf); %Set initial state and clean profiles: getViewPanelProp(hf); [~,hf.UserData.AnalysisStatus]=setAnalysisStatus(hf.UserData); setGUIstate(hf); setinitGUIstate(hf); hf.UserData=cleanupProfiles(hf.UserData); updatePlots(hf,2); setViewPanelProp(hf); hf.Visible='on'; else close(hf); end end %This function adds nodes to an active list when an edge is selected function hotkeys(src,ed) %All the keyboard shortcuts are defined here hf=src; h_axis=findobj(hf.Children,'-depth',0,'Tag','Axis'); h_operationpanel=findobj(hf.Children,'flat','Tag','Operation'); h_mode=findobj(h_operationpanel.Children,'flat','Tag','Mode'); h_object=findobj(h_operationpanel.Children,'flat','Tag','Object'); h_sv=findobj(h_axis.Children,'-depth',0,'Tag','SelVerts'); panfact=0.03; if strcmp(ed.Key,'comma') || strcmp(ed.Key,'period') if ~isempty(h_sv) h_active=findobj(h_sv.Children,'-depth',0,'Tag','Active'); if ~isempty(h_active) && strcmp(h_active.UserData.type,'Trace') vert.t=h_active.UserData.t; vert.ind=h_active.UserData.ind; vert.type=h_active.UserData.type; if strcmp(ed.Key,'comma') vert.ind=min(vert.ind+1,numel(hf.UserData.Profile{vert.t}.d.optim)); elseif strcmp(ed.Key,'period') vert.ind=max(vert.ind-1,1); end xdat=hf.UserData.Profile{vert.t}.r.optim(vert.ind,1)+hf.UserData.shiftx(vert.t); ydat=hf.UserData.Profile{vert.t}.r.optim(vert.ind,2)+hf.UserData.shifty(vert.t); %Update active vertex h_active.XData=ydat; h_active.YData=xdat; set(h_active,'UserData',vert) end %If in edit & match mode, with trace object selected if strcmp(h_mode.SelectedObject.String,'Detect Peaks') && strcmp(h_object.SelectedObject.String,'Edit Peaks') drawProfile([],[],hf); end end elseif strcmp(ed.Key,'equal') h_axis=findobj(hf.Children,'flat','Tag','Axis'); h_axis.CLim(2)=h_axis.CLim(2)*0.9; setViewPanelProp(hf);%Update display getViewPanelProp(hf);%Update internal state using display elseif strcmp(ed.Key,'hyphen') h_axis=findobj(hf.Children,'flat','Tag','Axis'); h_axis.CLim(2)=h_axis.CLim(2)*1.1; setViewPanelProp(hf); getViewPanelProp(hf); elseif strcmp(ed.Key,'d') deselectVert([],[],hf); elseif strcmp(ed.Key,'z') %Activates zoom with a context menu to disable zoom mode hCMZ = uicontextmenu; uimenu('Parent',hCMZ,'Label','Switch to pan mode',... 'Callback','pan(gcbf,''on'')'); uimenu('Parent',hCMZ,'Label','Exit zoom mode',... 'Callback','zoom(gcbf,''off'')'); hZoom = zoom(gcbf); hZoom.UIContextMenu = hCMZ; zoom('on'); elseif strcmp(ed.Key,'x') %Activates pan with a context menu to disable pan mode hPanMZ = uicontextmenu; uimenu('Parent',hPanMZ,'Label','Switch to zoom mode',... 'Callback','zoom(gcbf,''on'')'); uimenu('Parent',hPanMZ,'Label','Exit pan mode',... 'Callback','pan(gcbf,''off'')'); hPan = pan(gcbf); hPan.UIContextMenu = hPanMZ; pan('on'); elseif strcmp(ed.Key,'a') || strcmp(ed.Key,'r') || strcmp(ed.Key,'f') h_operationpanel=findobj(hf.Children,'flat','Tag','Operation'); h_mode=findobj(h_operationpanel.Children,'flat','Tag','Mode'); h_object=findobj(h_operationpanel.Children,'flat','Tag','Object'); if strcmp(h_mode.SelectedObject.String,'Align Traces') h_axis=findobj(hf.Children,'flat','Tag','Axis'); h_sv=findobj(h_axis.Children,'flat','Tag','SelVerts'); if ~isempty(h_sv.Children) && strcmp(ed.Key,'a') addLandmark([],[],hf); end elseif strcmp(h_mode.SelectedObject.String,'Detect Peaks') && ... strcmp(h_object.SelectedObject.String,'Edit Peaks') h_axis=findobj(hf.Children,'flat','Tag','Axis'); h_sv=findobj(h_axis.Children,'flat','Tag','SelVerts'); if ~isempty(h_sv.Children) && strcmp(ed.Key,'a') addPeak([],[],hf); elseif ~isempty(h_sv.Children) && strcmp(ed.Key,'r') remPeak([],[],hf); end elseif strcmp(h_mode.SelectedObject.String,'Detect Peaks') && ... strcmp(h_object.SelectedObject.String,'Match Peaks') h_sv=findobj(h_axis.Children,'flat','Tag','SelVerts'); if numel(h_sv.Children)>1 && strcmp(ed.Key,'a') addEdges([],[],hf); elseif numel(h_sv.Children)>0 && strcmp(ed.Key,'f') editFlag([],[],hf); end end elseif strcmp(ed.Key,'v') h_elements=findobj(h_axis.Children,'flat','-not','Tag','Image','-not','Tag','SelVerts'); stateval=h_elements(1).Visible; if strcmp(stateval,'on') stateval='off'; else stateval='on'; end set(h_elements,'Visible',stateval); elseif strcmp(ed.Key,'z') %Activates zoom with a context menu to disable zoom mode switch2zoom([],[],hf); elseif strcmp(ed.Key,'x') %Activates pan with a context menu to disable pan mode switch2pan([],[],hf); elseif strcmp(ed.Key,'uparrow')%up h_axis.YLim=h_axis.YLim-cosd(h_axis.View(1))*diff(h_axis.XLim)*panfact; h_axis.XLim=h_axis.XLim-sind(h_axis.View(1))*diff(h_axis.YLim)*panfact; elseif strcmp(ed.Key,'downarrow')%down h_axis.YLim=h_axis.YLim+cosd(h_axis.View(1))*diff(h_axis.XLim)*panfact; h_axis.XLim=h_axis.XLim+sind(h_axis.View(1))*diff(h_axis.YLim)*panfact; elseif strcmp(ed.Key,'leftarrow')%left h_axis.XLim=h_axis.XLim-cosd(h_axis.View(1))*diff(h_axis.XLim)*panfact; h_axis.YLim=h_axis.YLim+sind(h_axis.View(1))*diff(h_axis.YLim)*panfact; elseif strcmp(ed.Key,'rightarrow')%right h_axis.XLim=h_axis.XLim+cosd(h_axis.View(1))*diff(h_axis.XLim)*panfact; h_axis.YLim=h_axis.YLim-sind(h_axis.View(1))*diff(h_axis.YLim)*panfact; end end function scroll2zoom(~,ed) %Callback for zooming in and out using scroll %h_axis=findobj(src.Children,'flat','Tag','Axis'); if ed.VerticalScrollCount<0 zoom(1.2); else zoom(1/1.2); end end function closereqf(~,~) % Close request function % to display a question dialog box selection = questdlg('All unsaved changes will be lost. Continue?',... 'Warning',... 'Yes','No','No'); switch selection case 'Yes' delete(gcbf) case 'No' return end end function switch2zoom(~,~,hf) hCMZ = uicontextmenu; uimenu('Parent',hCMZ,'Label','Switch to pan mode',... 'Callback',{@switch2pan,hf}); uimenu('Parent',hCMZ,'Label','Exit zoom mode',... 'Callback','zoom(gcbf,''off'')'); hZoom = zoom(hf); hZoom.UIContextMenu = hCMZ; zoom('on'); end function switch2pan(~,~,hf) hPanMZ = uicontextmenu; uimenu('Parent',hPanMZ,'Label','Switch to zoom mode',... 'Callback',{@switch2zoom,hf}); uimenu('Parent',hPanMZ,'Label','Exit pan mode',... 'Callback','pan(gcbf,''off'')'); hPan = pan(hf); hPan.UIContextMenu = hPanMZ; pan('on'); end
github
neurogeometry/BoutonAnalyzer-master
LabelTreesAM.m
.m
BoutonAnalyzer-master/LabelTreesAM.m
723
utf_8
3b17984d93020bca4d75064e73a9e1af
% This function finds trees in a directed or undirected AM and returns a % labeled AMlbl. function AMlbl = LabelTreesAM(AM) AM = spones(AM+AM'); AMlbl=double(AM); AV = find(sum(AM)); if ~isempty(AV) startV=AV(1); TreeLabel=1; end while ~isempty(AV) startVnew=find(sum(AM(startV,:),1)); if ~isempty(startVnew) AMlbl(startV,startVnew)=AM(startV,startVnew).*TreeLabel; AMlbl(startVnew,startV)=AM(startVnew,startV).*TreeLabel; AM(startV,startVnew)=0; AM(startVnew,startV)=0; startV=startVnew; else AV=find(sum(AM)); if ~isempty(AV) startV=AV(1); TreeLabel=TreeLabel+1; end end end
github
neurogeometry/BoutonAnalyzer-master
gui_optimization.m
.m
BoutonAnalyzer-master/gui_optimization.m
21,412
utf_8
700e399f68aa0ec77f44b54100f76dc5
function gui_optimization(src) close(src); %This section has sizes derived from screen resolution--------------------- temp=get(0); fi.H=max([700,temp.ScreenSize(4)*0.8]); fi.W=max([875,fi.H*5/4]); fi.L=(fi.W.*0.1); fi.B=(fi.H.*0.1); %-------------------------------------------------------------------------- hf=figure;clf(hf);hf.Visible='off'; hf.Name='BoutonAnalyzer: Optimize Trace & Generate Profile';hf.NumberTitle='off'; hf.Position=[fi.L,fi.B,fi.W,fi.H]; set(hf,'KeyPressFcn',@hotkeys); set(hf,'WindowScrollWheelFcn',@scroll2zoom); customizeMenus(hf); [hf.UserData.Im,Profile,Trace,hf.UserData.inform,exitstat]=gui_loaddata(1,1,1,'gui_optimization'); if exitstat==1 %All channels are assumed to have same dimensions, Trace and Profile are %cells; hf.UserData.Profile=Profile{1}; hf.CloseRequestFcn=@closereq; %Order trace for faster plotting: startt=find(sum(Trace{1}.AM,1)==1);startt=startt(1); [Trace{1}.AM,Trace{1}.r,~] = orderprofile(Trace{1}.AM,Trace{1}.r,false(size(Trace{1}.r,1),1),startt); hf.UserData.Trace=Trace{1}; clear Profile Trace; %Initialize profile if no trace in profile channel=hf.UserData.inform.channel; if ~isfield(hf.UserData.Profile,'AM') hf.UserData.Profile.AM.optim=[]; hf.UserData.Profile.r.optim=[]; hf.UserData.Profile.annotate.ignore=[]; for ch=1:numel(channel) hf.UserData.Profile.proj.(channel{ch}).xy.full=max(permute(hf.UserData.Im.(channel{ch}),[1,2,3]),[],3); hf.UserData.Profile.proj.(channel{ch}).zy.full=max(permute(hf.UserData.Im.(channel{ch}),[3,2,1]),[],3); hf.UserData.Profile.proj.(channel{ch}).xz.full=max(permute(hf.UserData.Im.(channel{ch}),[1,3,2]),[],3); hf.UserData.Profile.proj.(channel{ch}).xy.ax=[]; hf.UserData.Profile.proj.(channel{ch}).zy.ax=[]; hf.UserData.Profile.proj.(channel{ch}).xz.ax=[]; end hf.UserData.Opt.r=hf.UserData.Trace.r; hf.UserData.Opt.AM=hf.UserData.Trace.AM; hf.UserData.Opt.R=hf.UserData.Trace.R; else hf.UserData.Opt.r=hf.UserData.Profile.r.optim; hf.UserData.Opt.AM=hf.UserData.Profile.AM.optim; hf.UserData.Opt.R=zeros(size(hf.UserData.Profile.r.optim,1),1); end %Generate projections genproj(hf); gui_optimization_layout; %Initialize axis ha_xy=axes;ha_xy.Tag='ha_xy';ha_xy.Parent=hf; ha_xy.Units='pixels';ha_xy.Position=[panel_l+panel_w+buff.h+(1/3)*xyaxis_w+buff.h, buff.h, xyaxis_w, xyaxis_w]; ha_xy.YLabel.String='X axis, [pixels]';ha_xy.XLabel.String='Y axis, [pixels]'; ha_xy.XLim=[0 900];ha_xy.YLim=[0 900]; ha_xy.Color=[0.4 0.4 0.4];box(ha_xy,'on'); ha_xy.NextPlot='add'; %Plot projection hi_xy=imshow(hf.UserData.Profile.proj.(channel{1}).xy.full,[],'Parent',ha_xy);hold on; ha_xy.CLim=[0,mean(hf.UserData.Profile.proj.(channel{1}).xy.full(:))+5*std(hf.UserData.Profile.proj.(channel{1}).xy.full(:))]; hi_xy.Tag='hi_xy_full'; axis(ha_xy,'on'); %Initialize axis ha_zy=axes;ha_zy.Tag='ha_zy';ha_zy.Parent=hf; ha_zy.Units='pixels';ha_zy.Position=[panel_l+panel_w+buff.h+(1/3)*xyaxis_w+buff.h,xyaxis_w+2*buff.h,xyaxis_w,(1/3)*xyaxis_w]; ha_zy.YLabel.String='Z axis, [pixels]';ha_zy.XLabel.String='Y axis, [pixels]'; ha_zy.XLim=[0 900];ha_zy.YLim=[0 300]; ha_zy.Color=[0.4 0.4 0.4];box(ha_zy,'on'); ha_zy.NextPlot='add'; %Plot projection hi_zy=imshow(hf.UserData.Profile.proj.(channel{1}).zy.full,[],'Parent',ha_zy);hold on; ha_zy.CLim=ha_xy.CLim; hi_zy.Tag='hi_zy_full'; axis(ha_zy,'on'); %Initialize axis ha_xz=axes; ha_xz.Tag='ha_xz';ha_xz.Parent=hf; ha_xz.Units='pixels';ha_xz.Position=[panel_l+panel_w+buff.h, buff.h, (1/3)*xyaxis_w, xyaxis_w]; ha_xz.XLabel.String='Z axis, [pixels]';ha_xz.YLabel.String='X axis, [pixels]'; ha_xz.XLim=[0 300];ha_xz.YLim=[0 900]; ha_xz.Color=[0.4 0.4 0.4];box(ha_xz,'on'); ha_xz.NextPlot='add'; %Plot projection hi_xz=imshow(hf.UserData.Profile.proj.(channel{1}).xz.full,[],'Parent',ha_xz);hold on; hi_xz.Tag='hi_xz_full'; ha_xz.CLim=ha_xy.CLim; axis(ha_xz,'on'); %Initialize view panel------------------------------------------------- hv=uipanel('Parent',hf); hv.Units='pixels';hv.Position=[panel_l, buff.h, panel_w, viewpanel_h]; hv.Title='View Options'; hv.Tag='ViewControl'; %Intensity range setting uicontrol('Style', 'text','Parent',hv,... 'Units','pixels','Position', [stdbuff_w, view_intrange_b+txtbx_h+minbuff_h, element_w, txt_h],... 'String','Intensity range','Tag','IntensityRange'); uicontrol('Style','edit','Parent',hv,'Tag','IntensityRangeBox',... 'Units','pixels','Position',[stdbuff_w, view_intrange_b, element_w, txtbx_h],... 'Callback',@setintensityrange,... 'String',sprintf('%0.0f,%0.0f',ha_xz.CLim(1),ha_xz.CLim(2)),... 'ToolTipString','e.g. 0, 500'); %Toggle channel sel_ch = uibuttongroup('Tag','Channels','Parent',hv,... 'Units','pixels','Position',[0, view_chnrb_b, panel_w, view_chnrb_h],... 'SelectionChangedFcn',@drawim,... 'Title','Channel','BorderType','none'); nbtn=3; for n=1:nbtn ch_rb=uicontrol('Style','radiobutton','Parent',sel_ch); ch_rb.Units='pixels';ch_rb.Position=[stdbuff_w,(nbtn-n)*(rbtn_h+minbuff_h)+minbuff_h, element_w, rbtn_h]; if n<=numel(channel) ch_rb.String=channel{n}; else ch_rb.String='-NA-'; ch_rb.Enable='off'; end end sel_ch.SelectedObject=findobj(sel_ch,'String',channel{1}); %Toggle trace sel_tr = uibuttongroup('Title','Trace','Tag','Trace','Parent',hv,... 'Units','pixels','Position',[0, view_tracerb_b, panel_w, view_tracerb_h],... 'SelectionChangedFcn',{@drawtrace,hf},'BorderType','none'); nbtn=3; txtlist={'None','Initial','Optimized'}; if isempty(hf.UserData.Profile.AM.optim) choice.NewValue.String='Initial'; else choice.NewValue.String='Optimized'; end for n=1:nbtn tr_rb=uicontrol('Style','radiobutton','Parent',sel_tr); tr_rb.Units='pixels';tr_rb.Position=[stdbuff_w,(nbtn-n)*(rbtn_h+minbuff_h)+minbuff_h, element_w, rbtn_h]; tr_rb.String=txtlist{n}; if strcmp(txtlist{n},'Optimized') && isempty(hf.UserData.Profile.AM.optim) tr_rb.Enable='off'; end tr_rb.HandleVisibility='on'; end sel_tr.SelectedObject=findobj(sel_tr,'String',choice.NewValue.String); drawtrace([],choice,hf); %Toggle tube sel_tube = uibuttongroup('Title','Projection','Tag','Projection','Parent',hv,... 'Units','pixels','Position',[0, view_tuberb_b, panel_w, view_tuberb_h],... 'SelectionChangedFcn',@drawim,'BorderType','none'); nbtn=2; txtlist={'Full','Tube'}; for n=1:nbtn tube_rb=uicontrol('Style','radiobutton','Parent',sel_tube); tube_rb.Units='pixels';tube_rb.Position=[stdbuff_w,(nbtn-n)*(rbtn_h+minbuff_h)+minbuff_h, element_w, rbtn_h]; tube_rb.String=txtlist{n}; end sel_tube.SelectedObject=findobj(sel_tube,'String','Full'); %Operation panel------------------------------------------------------- hopt=uipanel('Parent',hf,'Tag','OptControl',... 'Units','pixels','Position',[panel_l,operationpanel_b,panel_w,operationpanel_h],... 'Title','','BorderType','none'); %Optimize push buttons uicontrol('Style', 'pushbutton','Tag','IsOptPresent','Parent',hopt,... 'Units','pixels','Position',[stdbuff_w, stdbuff_h+2*(pushbutton_h+minbuff_h), element_w, pushbutton_h],... 'String','Optimize Trace','Callback',@optim); uicontrol('Style', 'pushbutton','Tag','SaveProfile','Parent',hopt,... 'Units','pixels','Position',[stdbuff_w, stdbuff_h+pushbutton_h+minbuff_h, element_w, pushbutton_h],... 'String', 'Generate Profile & Save','Callback',@saveprofile,'Enable','on'); uicontrol('Style', 'pushbutton','Tag','NewAxon','Parent',hopt,... 'Units','pixels','Position',[stdbuff_w, stdbuff_h, element_w, pushbutton_h],... 'String', 'Load Next','Callback',@loadnew,'Enable','on'); hf.Visible='on'; else disp('Data files could not be loaded. Exiting GUI.') end end %-----------------------Functions------------------------------------------ %-------------------------------------------------------------------------- %-----------------------Create projections--------------------------------- function genproj(hf) UserData=hf.UserData; channel=fieldnames(UserData.Im); sizeIm=size(UserData.Im.(channel{1}));%Size of all channels is the same. pad=20; minr=min(UserData.Opt.r,[],1); maxr=max(UserData.Opt.r,[],1); minx=round(max(minr(1)-pad,1));maxx=round(min(maxr(1)+pad,sizeIm(1))); miny=round(max(minr(2)-pad,1));maxy=round(min(maxr(2)+pad,sizeIm(2))); minz=round(max(minr(3)-pad,1));maxz=round(min(maxr(3)+pad,sizeIm(3))); [~,SVr,~]=AdjustPPM(UserData.Opt.AM,UserData.Opt.r,UserData.Opt.R,1); disp('Updating projections...'); %Perform fast marching on restricted volume: paramset;%Parameters for FastMarching [KT]=FastMarchingTube([maxx-minx+1,maxy-miny+1,maxz-minz+1],[SVr(:,1)-minx+1,SVr(:,2)-miny+1,SVr(:,3)-minz+1],params.proj.fm_dist,[1 1 1]); Filter=false(sizeIm); Filter(minx:maxx,miny:maxy,minz:maxz)=KT; for ch=1:numel(fieldnames(UserData.Im)) Im_ax=zeros(size(UserData.Im.(channel{ch}))); Im_ax(Filter)=UserData.Im.(channel{ch})(Filter); UserData.Profile.proj.(channel{ch}).xy.ax=squeeze(max(Im_ax,[],3)); UserData.Profile.proj.(channel{ch}).zy.ax=squeeze(max(Im_ax,[],1))'; UserData.Profile.proj.(channel{ch}).xz.ax=squeeze(max(Im_ax,[],2)); end hf.UserData=[]; hf.UserData=UserData; disp('Projections updated.'); end %-----------------------Update traces-------------------------------------- function drawtrace(~,ed,hf) ht=findobj(hf,'-depth',3,'-regexp','Tag','(ht)*'); ha_xy=findobj(hf,'-depth',2,'Tag','ha_xy'); ha_zy=findobj(hf,'-depth',2,'Tag','ha_zy'); ha_xz=findobj(hf,'-depth',2,'Tag','ha_xz'); if ~isempty(ht) delete(ht); end switch ed.NewValue.String case 'None' %Do nothing case 'Initial' plot(hf.UserData.Trace.r(:,2),hf.UserData.Trace.r(:,1),'-','Color',[0.8 0 0],'Parent',ha_xy,'Tag','ht_xy_Manual'); plot(hf.UserData.Trace.r(:,2),hf.UserData.Trace.r(:,3),'-','Color',[0.8 0 0],'Parent',ha_zy,'Tag','ht_zy_Manual'); plot(hf.UserData.Trace.r(:,3),hf.UserData.Trace.r(:,1),'-','Color',[0.8 0 0],'Parent',ha_xz,'Tag','ht_xz_Manual'); case 'Optimized' if ~isempty(hf.UserData.Profile.AM.optim) plot(hf.UserData.Profile.r.optim(:,2),hf.UserData.Profile.r.optim(:,1),'-','Color',[0.1 0.7 0],'Parent',ha_xy,'Tag','ht_xy_Optimized'); plot(hf.UserData.Profile.r.optim(:,2),hf.UserData.Profile.r.optim(:,3),'-','Color',[0.1 0.7 0],'Parent',ha_zy,'Tag','ht_zy_Optimized'); plot(hf.UserData.Profile.r.optim(:,3),hf.UserData.Profile.r.optim(:,1),'-','Color',[0.1 0.7 0],'Parent',ha_xz,'Tag','ht_xz_Optimized'); else disp('No optimized trace present!') end end end %---------------Update projection on all plots----------------------------- function drawim(~,~) %drawim is called by two buttons, and within optimization code. Hence gcbf %always returns the correct figure hf=gcbf; h_dispcontrol=findobj(hf,'-depth',2,'Tag','ViewControl'); h_ch=findobj(h_dispcontrol,'-depth',2,'Tag','Projection'); if strcmp(h_ch.SelectedObject.String,'Full') projtype='full'; elseif strcmp(h_ch.SelectedObject.String,'Tube') projtype='ax'; end h_ch=findobj(h_dispcontrol,'-depth',2,'Tag','Channels'); channel=h_ch.SelectedObject.String; hi_xy=findobj(hf, '-depth',2,'-regexp','Tag','(hi_xy)*'); hi_zy=findobj(hf, '-depth',2,'-regexp','Tag','(hi_zy)*'); hi_xz=findobj(hf, '-depth',2,'-regexp','Tag','(hi_xz)*'); hi_xy.CData=hf.UserData.Profile.proj.(channel).xy.(projtype); hi_zy.CData=hf.UserData.Profile.proj.(channel).zy.(projtype); hi_xz.CData=hf.UserData.Profile.proj.(channel).xz.(projtype); end %-----------------------Perform optimization------------------------------- function optim(varargin) hf=gcbf; h_msg=msgbox('Please wait until optimization is completed. This may take a minute...','Trace Optimization'); UserData=hf.UserData; %hf.UserData=[]; channel=UserData.inform.channel{1}; paramset; [UserData.Profile.AM.optim,UserData.Profile.r.optim,~,~]=... Optimize_Trace(UserData.Im.(channel),UserData.Trace.AM,UserData.Trace.r,... params.opt.Rtypical,params.opt.Optimize_bps,params.opt.Optimize_tps,params.opt.pointspervoxel,params.opt.MaxIterations, ... params.opt.alpha_r,params.opt.betta_r,params.opt.isadjustpointdensity,params.opt.output); close(h_msg); %Subdividing trace [UserData.Profile.AM.optim,UserData.Profile.r.optim,~]=... AdjustPPM(UserData.Profile.AM.optim,UserData.Profile.r.optim,zeros(size(UserData.Profile.r.optim,1),1),params.profile.pointspervoxel); %Order trace for faster plotting: startt=find(sum(UserData.Profile.AM.optim,1)==1);startt=startt(1); [UserData.Profile.AM.optim,UserData.Profile.r.optim,~] = orderprofile(UserData.Profile.AM.optim,UserData.Profile.r.optim,false(size(UserData.Profile.r.optim,1),1),startt); %Replace the trace with which tube is calculated UserData.Opt.r=UserData.Profile.r.optim; UserData.Opt.AM=UserData.Profile.AM.optim; UserData.Opt.R=zeros(size(UserData.Profile.r.optim,1),1); hf.UserData=[]; hf.UserData=UserData; h_tr=findobj(hf,'-depth',2,'Tag','ViewControl'); h_tr=findobj(h_tr,'String','Optimized'); h_tr.Enable='on'; %Switch displayed trace to optimized trace sel_tr=h_tr.Parent; sel_tr.SelectedObject=h_tr; choice.NewValue.String=h_tr.String; drawtrace([],choice,hf); %Generate new projections genproj(hf); %Update projections and refresh trace disp('Updating plots...'); drawim([],[]); %Refresh trace h_tr=findobj(hf,'-depth',2,'Tag','ViewControl'); h_tr=findobj(h_tr,'Tag','Trace'); choice.NewValue.String=h_tr.SelectedObject.String; drawtrace([],choice,hf); disp('Updating plots completed.'); end %-----------------------Update contrast on all axes------------------------ function setintensityrange(~,~,~) hf=gcbf; ha_xy=findobj(hf,'-depth',2,'Tag','ha_xy'); ha_zy=findobj(hf,'-depth',2,'Tag','ha_zy'); ha_xz=findobj(hf,'-depth',2,'Tag','ha_xz'); hv=findobj(hf.Children,'flat','Tag','ViewControl'); hir=findobj(hv.Children,'Tag','IntensityRangeBox'); change=false; Cval=regexp(hir.String,',','split'); if numel(Cval)==2 CVal=[str2double(Cval{1}),str2double(Cval{2})]; if ~any(isnan(CVal)) ha_xy.CLim=CVal; ha_zy.CLim=CVal; ha_xz.CLim=CVal; change=true; end end if ~change CVal=ha_xy.CLim; hir.String=[num2str(CVal(1)),' , ',num2str(CVal(2))]; disp('Intensity range must be specified as comma separated numbers.') end end %-----------------------Generating profile--------------------------------- function genprofile(varargin) hf=gcbf; an=1;se=1; ax=1;ti=1; pathlist; Profile=hf.UserData.Profile; paramset; if isempty(Profile.r.optim) disp('Warning: Trace is not optimized. Profile generated using loaded trace.') Profile.AM.optim=hf.UserData.Trace.AM; Profile.r.optim=hf.UserData.Trace.r; %Subdividing trace [Profile.AM.optim,Profile.r.optim,~]=... AdjustPPM(Profile.AM.optim,Profile.r.optim,zeros(size(Profile.r.optim,1),1),params.profile.pointspervoxel); end %Re-order AM and r Profile.annotate.ignore=false(size(Profile.r.optim,1),1); startt=find(sum(Profile.AM.optim,1)==1); startt=startt(1); [Profile.AM.optim,Profile.r.optim,Profile.annotate.ignore]=... orderprofile(Profile.AM.optim,Profile.r.optim,Profile.annotate.ignore,startt); %Calculating path distance and filter intensity [Profile.d.optim]=vx2um(Profile.r.optim); Profile.d.aligned=Profile.d.optim; Profile.d.alignedxy=px2um(Profile.r.optim); channel=hf.UserData.inform.channel; for ch=1:numel(channel) for fi=1:numel(params.filt.types) [temp.I,temp.R]=profilefilters(Profile.r.optim,hf.UserData.Im.(channel{ch}),params.filt.types{fi},params); Profile.I.(channel{ch}).(params.filt.types{fi}).raw=temp.I; Profile.I.(channel{ch}).(params.filt.types{fi}).caliber=temp.R; Profile.I.(channel{ch}).(params.filt.types{fi}).norm=temp.I./mean(temp.I(~Profile.annotate.ignore)); disp([params.filt.types{fi},' profile generated for ',channel{ch},' Channel.']); end end %Create fit and id fields for ch=1:numel(channel) Profile.fit.(channel{ch})=struct(); end stack_id=[hf.UserData.inform.animal{an},hf.UserData.inform.timepoint{ti},hf.UserData.inform.section{se}]; Profile.id=[stack_id,'-',hf.UserData.inform.axon{ax}]; Profile=orderfields(Profile,{'AM','r','d','I','annotate','fit','proj','id'}); hf.UserData.Profile=Profile; end %-----------------------Saving profile------------------------------------- function saveprofile(varargin) hf=gcbf; an=1;se=1; ax=1;ti=1; pathlist; genprofile(); Profile=hf.UserData.Profile; if ~isempty(Profile) profile_id=hf.UserData.inform.axon{ax}; stack_id=[hf.UserData.inform.animal{an},hf.UserData.inform.timepoint{ti},hf.UserData.inform.section{se}]; fname=isunixispc([profile_pth,stack_id,filesep,profile_id,'.mat']); %Check directory if ~exist(isunixispc([profile_pth,stack_id]),'dir') mkdir(isunixispc(profile_pth),stack_id); display(['Creating directory: ', isunixispc([profile_pth,stack_id])]); end save(fname,'-struct','Profile'); disp(['Saved profile in ',fname]); else disp('No profile found. Generate profile before saving.'); end end %-----------------------Shortcuts profile---------------------------------- function hotkeys(src,ed) %All the keyboard shortcuts are defined here hf=src; h_axis=gca; panfact=0.03; if strcmp(ed.Key,'uparrow')%up h_axis.YLim=h_axis.YLim-cosd(h_axis.View(1))*diff(h_axis.XLim)*panfact; h_axis.XLim=h_axis.XLim-sind(h_axis.View(1))*diff(h_axis.YLim)*panfact; elseif strcmp(ed.Key,'downarrow')%down h_axis.YLim=h_axis.YLim+cosd(h_axis.View(1))*diff(h_axis.XLim)*panfact; h_axis.XLim=h_axis.XLim+sind(h_axis.View(1))*diff(h_axis.YLim)*panfact; elseif strcmp(ed.Key,'leftarrow')%left h_axis.XLim=h_axis.XLim-cosd(h_axis.View(1))*diff(h_axis.XLim)*panfact; h_axis.YLim=h_axis.YLim+sind(h_axis.View(1))*diff(h_axis.YLim)*panfact; elseif strcmp(ed.Key,'rightarrow')%right h_axis.XLim=h_axis.XLim+cosd(h_axis.View(1))*diff(h_axis.XLim)*panfact; h_axis.YLim=h_axis.YLim-sind(h_axis.View(1))*diff(h_axis.YLim)*panfact; elseif strcmp(ed.Key,'equal') hv=findobj(hf.Children,'flat','Tag','ViewControl'); hir=findobj(hv.Children,'Tag','IntensityRangeBox'); CVal=h_axis.CLim; CVal(2)=CVal(2)*0.9; hir.String=[num2str(CVal(1)),' , ',num2str(CVal(2))]; setintensityrange([],[],[]); elseif strcmp(ed.Key,'hyphen') hv=findobj(hf.Children,'flat','Tag','ViewControl'); hir=findobj(hv.Children,'Tag','IntensityRangeBox'); CVal=h_axis.CLim; CVal(2)=CVal(2)*1.1; hir.String=[num2str(CVal(1)),' , ',num2str(CVal(2))]; setintensityrange([],[],[]); elseif strcmp(ed.Key,'z') %Activates zoom with a context menu to disable zoom mode switch2zoom([],[],hf); elseif strcmp(ed.Key,'x') %Activates pan with a context menu to disable pan mode switch2pan([],[],hf); end end function scroll2zoom(~,ed) %Callback for zooming in and out using scroll %h_axis=findobj(src.Children,'flat','Tag','Axis'); gca; if ed.VerticalScrollCount<0 zoom(1.2); else zoom(1/1.2); end end function closereq(~,~) % Close request function % to display a question dialog box selection = questdlg('All unsaved changes will be lost. Continue?',... 'Warning',... 'Yes','No','No'); switch selection case 'Yes' delete(gcbf) case 'No' return end end function loadnew(~,~) hf=gcbf; close(hf); if ~isvalid(hf) gui_optimization([]); else disp('Current axon was retained. Load new axon operation terminated.') end end function switch2zoom(~,~,hf) hCMZ = uicontextmenu; uimenu('Parent',hCMZ,'Label','Switch to pan mode',... 'Callback',{@switch2pan,hf}); uimenu('Parent',hCMZ,'Label','Exit zoom mode',... 'Callback','zoom(gcbf,''off'')'); hZoom = zoom(hf); hZoom.UIContextMenu = hCMZ; zoom('on'); end function switch2pan(~,~,hf) hPanMZ = uicontextmenu; uimenu('Parent',hPanMZ,'Label','Switch to zoom mode',... 'Callback',{@switch2zoom,hf}); uimenu('Parent',hPanMZ,'Label','Exit pan mode',... 'Callback','pan(gcbf,''off'')'); hPan = pan(hf); hPan.UIContextMenu = hPanMZ; pan('on'); end
github
neurogeometry/BoutonAnalyzer-master
analysis_getmat.m
.m
BoutonAnalyzer-master/analysis_getmat.m
8,683
utf_8
e5d2bfae9a58fae36c925993965f1573
function [AxonMat] = analysis_getmat(An) %This function creates matrices for analysis from registered data. Input is %obtained from BoutonAnalyzer via saveProfile.m channel=fieldnames(An{1}.fit); remchannelind=false(numel(channel),1); for i=1:numel(channel) remchannelind(i)=isempty(fieldnames(An{1}.fit.(channel{i}))); end channel(remchannelind)=[]; fitshape='G'; %This should be the same as used in fitLoGxy.m and fitGauss.m if strcmp(fitshape,'G') Ff = @(x,A,mu,sigma) (ones(size(x))*A).*exp(-(x*ones(size(A))-ones(size(x))*mu).^2./(ones(size(x))*sigma.^2)./2); elseif strcmp(fitshape,'L') Ff = @(x,A,mu,sigma) (ones(size(x))*A)./((x*ones(size(A))-ones(size(x))*mu).^2./(ones(size(x))*sigma.^2)+1); end for ch=1:numel(channel) %1. Initializing matrices---------------------------------------------- n_times=numel(An); max_nbtns=0; for ti=1:n_times max_nbtns=max_nbtns+numel(An{ti}.fit.(channel{ch}).LoGxy.fg.ind); end AxonMat.btn_id=nan(1,max_nbtns); %(1 x btn)This is bouton lbl assigned during registration AxonMat.flag=nan(n_times,max_nbtns); %(time x btn) Flags are assigned during registration AxonMat.ind=nan(n_times,max_nbtns); %(time x btn) Index along corresponding profile AxonMat.d=nan(1,max_nbtns); %(1 x btn) 1d position along the aligned profile AxonMat.dorig=nan(n_times,max_nbtns); %(time x btn) 1d position along the original profile AxonMat.blen=nan(n_times,max_nbtns); %(time x btn) length associated with bouton AxonMat.rx=nan(n_times,max_nbtns); %(time x btn) 3d x-position of peak in each time point AxonMat.ry=nan(n_times,max_nbtns); %(time x btn) 3d y-position of peak in each time point AxonMat.rz=nan(n_times,max_nbtns); %(time x btn) 3d z-position of peak in each time point AxonMat.Iraw=nan(n_times,max_nbtns); %Non-normalized intensity at location on profile. AxonMat.Inorm=nan(n_times,max_nbtns); %Intensity at location on profile. Inorm is roughly Ifg+Ibg AxonMat.Ibg=nan(n_times,max_nbtns); %Intensity of background at given foreground peak location AxonMat.sig=nan(n_times,max_nbtns); %Peak width for every detected peak. nan otherwise AxonMat.amp=nan(n_times,max_nbtns); %Intensity of fitted foreground peak. nan otherwise AxonMat.w=nan(n_times,max_nbtns); %Normalized bouton weight AxonMat.P=nan(n_times,max_nbtns); %Probability using noise model %2. Populating matrices------------------------------------------------ dmin=-inf;dmax=inf; Ibg=cell(n_times,1); for ti=1:n_times Axon=An{ti}; dmin=max([(Axon.fit.(channel{ch}).LoGxy.d.man(1)),dmin]); dmax=min([(Axon.fit.(channel{ch}).LoGxy.d.man(end)),dmax]); nanind=isnan(Axon.fit.(channel{ch}).LoGxy.fg.manid); %Boutons not matched are assigned manid=fg.id. Axon.fit.(channel{ch}).LoGxy.fg.manid(nanind)=Axon.fit.(channel{ch}).LoGxy.fg.id(nanind); [~,matind]=ismember(Axon.fit.(channel{ch}).LoGxy.fg.manid,AxonMat.btn_id); startind=find(isnan(AxonMat.btn_id),1,'first'); endind=startind+sum(matind==0)-1; matind(matind==0)=startind:endind; AxonMat.btn_id(1,matind)=Axon.fit.(channel{ch}).LoGxy.fg.manid; AxonMat.flag(ti,matind)=Axon.fit.(channel{ch}).LoGxy.fg.flag; AxonMat.ind(ti,matind)=Axon.fit.(channel{ch}).LoGxy.fg.ind; AxonMat.d(1,matind)=Axon.fit.(channel{ch}).LoGxy.d.man(Axon.fit.(channel{ch}).LoGxy.fg.ind); AxonMat.dorig(ti,matind)=Axon.d.optim(Axon.fit.(channel{ch}).LoGxy.fg.ind); %Extra peaks are assumed as removed from dataset. temp=diff([dmin,AxonMat.d(1,matind),dmax]); blen=(temp(1:end-1)+temp(2:end))./2; blen(1)=blen(1)+temp(1)/2; blen(end)=blen(end)+temp(end)/2; AxonMat.blen(ti,matind)=blen; AxonMat.rx(ti,matind)=Axon.r.optim(Axon.fit.(channel{ch}).LoGxy.fg.ind,1); AxonMat.ry(ti,matind)=Axon.r.optim(Axon.fit.(channel{ch}).LoGxy.fg.ind,2); AxonMat.rz(ti,matind)=Axon.r.optim(Axon.fit.(channel{ch}).LoGxy.fg.ind,3); AxonMat.Iraw(ti,matind)=Axon.I.(channel{ch}).LoGxy.raw(Axon.fit.(channel{ch}).LoGxy.fg.ind); AxonMat.Inorm(ti,matind)=Axon.I.(channel{ch}).LoGxy.norm(Axon.fit.(channel{ch}).LoGxy.fg.ind); %If peaks were added manually, their intensity is nan after %operations by gui_alignment. Here those intensities are %replaced with intensity at the aligned profile location man_addedpeaks=find(isnan(Axon.fit.(channel{ch}).LoGxy.fg.amp)); if numel(man_addedpeaks)>0 Axon.fit.(channel{ch}).LoGxy.fg.amp(man_addedpeaks)=... Axon.I.(channel{ch}).LoGxy.norm(Axon.fit.(channel{ch}).LoGxy.fg.ind(man_addedpeaks)); end AxonMat.amp(ti,matind)=Axon.fit.(channel{ch}).LoGxy.fg.amp; AxonMat.sig(ti,matind)=Axon.fit.(channel{ch}).LoGxy.fg.sig; Ibg{ti}=zeros(size(Axon.d.optim)); for p=1:numel(Axon.fit.(channel{ch}).LoGxy.bg.ind) Ibg{ti}=Ibg{ti}+Ff(Axon.d.optim,Axon.fit.(channel{ch}).LoGxy.bg.amp(p),... Axon.fit.(channel{ch}).LoGxy.bg.mu(p),... Axon.fit.(channel{ch}).LoGxy.bg.sig(p)); end AxonMat.Ibg(ti,matind)=Ibg{ti}(Axon.fit.(channel{ch}).LoGxy.fg.ind); end %3. Removing boutons based on flag & overlap--------------------------- fldnm=fieldnames(AxonMat); %Remove extra columns from initialization remind=find(sum(isnan(AxonMat.ind),1)==size(AxonMat.ind,1)); remind=unique(remind); for f=1:numel(fldnm) AxonMat.(fldnm{f})(:,remind)=[]; end %Assign distances to each peak before removing based on %flags or non-overlapping axon region. %Convention for flags: %{ '0: No match provided (default) '1: Confirmed no match '2: Ignore, noisy intensity '3: Ignore, terminal bouton intensity '4: Ignore, cross-over %} temp=AxonMat.flag; temp(isnan(temp))=0;%because nan~=0 returns true; temp=temp~=0 & temp~=1; [~,remind1]=find(temp); remind2=find(AxonMat.d<dmin | AxonMat.d>dmax); remind=unique([remind1(:);remind2(:)]); for f=1:numel(fldnm) AxonMat.(fldnm{f})(:,remind)=[]; end %Sortind boutons in every axon by distance [~,sortind]=sort(AxonMat.d); for f=1:numel(fldnm) AxonMat.(fldnm{f})=AxonMat.(fldnm{f})(:,sortind); end %4. Replace nans with corresponding value on profile------------------- for ti=1:n_times Axon=An{ti}; nanind=find(isnan(AxonMat.ind(ti,:))); nanind=nanind(:)'; [~,minind]=min(abs(bsxfun(@minus,AxonMat.d(nanind),Axon.fit.(channel{ch}).LoGxy.d.man(:))),[],1); AxonMat.ind(ti,nanind)=minind; AxonMat.dorig(ti,nanind)=Axon.d.optim(minind); AxonMat.rx(ti,nanind)=Axon.r.optim(minind,1); AxonMat.ry(ti,nanind)=Axon.r.optim(minind,2); AxonMat.rz(ti,nanind)=Axon.r.optim(minind,3); AxonMat.Iraw(ti,nanind)=Axon.I.(channel{ch}).LoGxy.raw(minind); AxonMat.Inorm(ti,nanind)=Axon.I.(channel{ch}).LoGxy.norm(minind); AxonMat.Ibg(ti,nanind)=Ibg{ti}(minind); end %Related to normalization Norm=nan(n_times,1); for ti=1:n_times %Calculate normalization only based on current time: Gauss_bg=zeros(size(An{ti}.d.optim)); for i=1:numel(An{ti}.fit.(channel{ch}).Gauss.bg.ind) Gauss_bg=Gauss_bg+Ff(An{ti}.d.optim,... An{ti}.fit.(channel{ch}).Gauss.bg.amp(i),... An{ti}.fit.(channel{ch}).Gauss.bg.mu(i),... An{ti}.fit.(channel{ch}).Gauss.bg.sig(i)); end Norm(ti)=mean(Gauss_bg(~An{ti}.annotate.ignore)); end Norm=mean(Norm); AxonMat.w=AxonMat.amp; AxonMat.w(isnan(AxonMat.w))=AxonMat.Inorm(isnan(AxonMat.w)); AxonMat.w=AxonMat.w./Norm; AxonMat.w(AxonMat.w<0)=0; AxonMat.P=fP(AxonMat.w); end end function P=fP(varargin) alpha=0.2389; wthr=2; w=varargin{1}; if nargin==2 thr=varargin{2}; else thr=wthr; end P=nan(size(w)); w(w<eps)=abs(eps); P(:)=0.5*(1+erf((w(:)-thr)./((alpha*w(:)).^0.5))); end
github
neurogeometry/BoutonAnalyzer-master
AdjustPPM.m
.m
BoutonAnalyzer-master/AdjustPPM.m
4,361
utf_8
6916b925eb85d858d3b11a7f31944fe0
% This function adjusts the number of points per micrometer of the trace (ppm). % Input can be in the form of AM, AMlbl for branches, or AMlbl for trees % The output is always in the form of AMlbl for trees function [AMlbl,r,R] = AdjustPPM(AM,r,R,ppm) AM=spones(AM+AM'); AMlbl = LabelBranchesAM(AM); leng=size(AMlbl,1); L=unique(AMlbl(AMlbl>0)); Nvert=zeros(1,length(L)); for i=1:length(L) [e1,e2]=find(AMlbl==L(i)); lll=sum((r(e1,:)-r(e2,:)).^2,2).^0.5; Nvert(i)=ceil(sum(lll)/2*ppm)+1; end degree=sum(AM,1); N_new=sum(Nvert)-sum((degree-1).*(degree>2)); N_new_interm=N_new-sum(degree==1)-sum(degree>2); AMlbl(end+N_new_interm,end+N_new_interm)=0; r=[r;zeros(N_new_interm,3)]; R=[R;zeros(N_new_interm,1)]; for i=1:length(L) [e1, ~]=find(AMlbl==L(i)); if ~isempty(e1) e1=unique(e1); endp=e1(sum(AM(:,e1))==1 | sum(AM(:,e1))>=3); if isempty(endp) % isolated loop endp=e1(1); r_branch=zeros(length(e1)+1,3); r_branch(1,:)=r(endp(1),:); r_branch(end,:)=r(endp(1),:); R_branch=zeros(length(e1)+1,1); R_branch(1)=R(endp(1)); R_branch(end)=R(endp(1)); elseif length(endp)==1 % terminal loop r_branch=zeros(length(e1)+1,3); r_branch(1,:)=r(endp(1),:); r_branch(end,:)=r(endp(1),:); R_branch=zeros(length(e1)+1,1); R_branch(1)=R(endp(1)); R_branch(end)=R(endp(1)); else r_branch=zeros(length(e1),3); r_branch(1,:)=r(endp(1),:); r_branch(end,:)=r(endp(2),:); R_branch=zeros(length(e1),1); R_branch(1)=R(endp(1)); R_branch(end)=R(endp(2)); end startp=endp(1); if length(e1)>2 for j=2:length(e1)-length(endp)+1 nextp=find(AMlbl(startp,:)==L(i),1,'first'); r_branch(j,:)=r(nextp,:); R_branch(j)=R(nextp); AMlbl(nextp,startp)=0; AMlbl(startp,nextp)=0; startp=nextp; end if length(endp)==1 % terminal loop AMlbl(endp(1),startp)=0; AMlbl(startp,endp(1))=0; else AMlbl(endp(2),startp)=0; AMlbl(startp,endp(2))=0; end elseif length(e1)==2 AMlbl(endp(2),endp(1))=0; AMlbl(endp(1),endp(2))=0; end lll=sum((r_branch(2:end,:)-r_branch(1:end-1,:)).^2,2).^0.5; cumlll=cumsum(lll); N_interm=ceil(sum(lll)*ppm)-1; if N_interm==0 && length(endp)>1 % not a terminal or isolated loop AMlbl(endp(2),endp(1))=L(i); AMlbl(endp(1),endp(2))=L(i); elseif N_interm>=1 r_interm=zeros(N_interm,3); R_interm=zeros(N_interm,1); for j=1:N_interm temp_ind=find(cumlll>sum(lll)/(N_interm+1)*j,1,'first'); r_interm(j,:)=r_branch(temp_ind,:)+(r_branch(temp_ind+1,:)-r_branch(temp_ind,:)).*(1-(cumlll(temp_ind)-sum(lll)/(N_interm+1)*j)./lll(temp_ind)); R_interm(j)=R_branch(temp_ind)+(R_branch(temp_ind+1)-R_branch(temp_ind)).*(1-(cumlll(temp_ind)-sum(lll)/(N_interm+1)*j)./lll(temp_ind)); end if leng+N_interm>size(AMlbl,1) AMlbl(leng+N_interm,leng+N_interm)=0; end AMlbl=AMlbl+sparse(leng+[1:N_interm-1,2:N_interm],leng+[2:N_interm,1:N_interm-1],L(i),size(AMlbl,1),size(AMlbl,2)); AMlbl(leng+1,endp(1))=L(i); AMlbl(endp(1),leng+1)=L(i); if length(endp)==1 % terminal loop AMlbl(leng+N_interm,endp(1))=L(i); AMlbl(endp(1),leng+N_interm)=L(i); else AMlbl(leng+N_interm,endp(2))=L(i); AMlbl(endp(2),leng+N_interm)=L(i); end r(leng+1:leng+N_interm,:)=r_interm; R(leng+1:leng+N_interm)=R_interm; leng=leng+N_interm; end end end rem=(sum(AMlbl,1)==0); AMlbl(rem,:)=[]; AMlbl(:,rem)=[]; r(rem,:)=[]; R(rem)=[]; AMlbl=LabelTreesAM(AMlbl); %disp('Point density is adjusted.')
github
Hui-Ling/BeamformerSourceImaging-master
process_beamformer_con_speedup.m
.m
BeamformerSourceImaging-master/process_beamformer_con_speedup.m
84,804
utf_8
61b790c40d1f3c4f0a06d22c6268f587
function varargout = process_beamformer_con_speedup( varargin ) % PROCESS_BEAMFORMER_TEST: % @============================================================================= % This software is part of the Brainstorm software: % http://neuroimage.usc.edu/brainstorm % % Copyright (c)2000-2013 Brainstorm by the University of Southern California % This software is distributed under the terms of the GNU General Public License % as published by the Free Software Foundation. Further details on the GPL % license can be found at http://www.gnu.org/copyleft/gpl.html. % % FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE % UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY % WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY % LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE. % % For more information type "brainstorm license" at command prompt. % =============================================================================@ % % Authors: eval(macro_method) %macro_methodcall; end %% ===== GET DESCRIPTION ===== function sProcess = GetDescription() %#ok<DEFNU> % Description the process sProcess.Comment = 'Beamformer-based connectivity imaging'; sProcess.FileTag = ''; sProcess.Category = 'Custom'; sProcess.SubGroup = 'Connectivity'; sProcess.Index = 3005; % Definition of the input accepted by this process sProcess.InputTypes = {'data','matrix'}; sProcess.OutputTypes = {'results','results'}; sProcess.nInputs = 2; sProcess.nMinFiles = 1; %sProcess.options.sep.Type = 'label'; % % Definition of the options % sProcess.options.oriconstraint.Comment = {'Unconstrained', 'Cortical Constrained'}; % sProcess.options.oriconstraint.Type = 'radio'; % sProcess.options.oriconstraint.Value = 1; sProcess.options.result_comm.Comment = 'Comment: '; sProcess.options.result_comm.Type = 'text'; sProcess.options.result_comm.Value = ''; % === MEASURE === sProcess.options.measure.Comment = {'SILSC (Corr)', 'BIPAC (ESC)', 'Methods (Measures):'}; sProcess.options.measure.Type = 'radio_line'; sProcess.options.measure.Value = 1; % Options: Time-freq sProcess.options.labelC.Comment = '<HTML><B><U>Options for BIPAC (ESC)</U></B>:'; sProcess.options.labelC.Type = 'label'; % === NESTING FREQ sProcess.options.nesting.Comment = 'Nesting frequency band (low, data, Files A):'; sProcess.options.nesting.Type = 'range'; sProcess.options.nesting.Value = {[2, 30], 'Hz', 2}; % === NESTED FREQ sProcess.options.nested.Comment = 'Nested frequency band (high, ref, Files B):'; sProcess.options.nested.Type = 'range'; sProcess.options.nested.Value = {[40, 150], 'Hz', 2}; % Options: number of randomization test sProcess.options.nRand.Comment = 'Number of randomization (very time consuming)'; sProcess.options.nRand.Type = 'value'; sProcess.options.nRand.Value = {0, '', 0}; sProcess.options.nRand.Hidden = 1; % sProcess.options.ref_replicate_num.Comment = 'Number to replicate reference signals:'; % sProcess.options.ref_replicate_num.Type = 'value'; % sProcess.options.ref_replicate_num.Value = {1,'times',0}; % % sProcess.options.ref_replicate_interval.Comment = 'Interval of replicated reference signals:'; % sProcess.options.ref_replicate_interval.Type = 'value'; % sProcess.options.ref_replicate_interval.Value = {0.01,'ms',1}; % Separator sProcess.options.sep2.Type = 'separator'; sProcess.options.sep2.Comment = ' '; sProcess.options.labelB.Comment = '<HTML><B><U>Estimation options (Files A)</U></B>:'; sProcess.options.labelB.Type = 'label'; % sProcess.options.beamformertype.Comment = {'Vector-type beamformer', 'Scalar-type beamformer'}; % sProcess.options.beamformertype.Type = 'radio'; % sProcess.options.beamformertype.Value = 1; % === MINIMUM VARIANCE sProcess.options.minvar_time.Comment = 'Minimum variance time window: '; sProcess.options.minvar_time.Type = 'timewindow'; sProcess.options.minvar_time.Value = []; % === ACTIVE TIME RANGE sProcess.options.corr_range.Comment = 'Time range of interest: '; sProcess.options.corr_range.Type = 'timewindow'; sProcess.options.corr_range.Value = []; % === ACTIVE TIME WINDOW SIZE sProcess.options.active_window_size.Comment = 'Sliding window size: '; sProcess.options.active_window_size.Type = 'value'; sProcess.options.active_window_size.Value = {0.1, 'ms', 1}; % === ACTIVE TEMPORAL RESOLUTION sProcess.options.corr_tresolution.Comment = 'Temporal resolution: '; sProcess.options.corr_tresolution.Type = 'value'; sProcess.options.corr_tresolution.Value = {0.01, 'ms', 1}; % === REGULARIZATION sProcess.options.reg.Comment = 'Regularization parameter: '; sProcess.options.reg.Type = 'value'; sProcess.options.reg.Value = {0.1, '%', 4}; % === Sensor types sProcess.options.sensortypes.Comment = 'Sensor types or names (empty=all): '; sProcess.options.sensortypes.Type = 'text'; sProcess.options.sensortypes.Value = 'MEG, EEG'; % Separator sProcess.options.sep.Type = 'separator'; sProcess.options.sep.Comment = ' '; sProcess.options.labelA.Comment = '<HTML><B><U>Reference signal options (Files B)</U></B>:'; sProcess.options.labelA.Type = 'label'; % === REF TIME TYPE === sProcess.options.ref_range_type.Comment = {'Fixed time range (Absolute)', 'Range of time delay (Relative)', 'Time range type:'}; sProcess.options.ref_range_type.Type = 'radio_line'; sProcess.options.ref_range_type.Value = 1; % === TIME WINDOW === sProcess.options.ref_range.Comment = 'Time range to extract ref signal: '; sProcess.options.ref_range.Type = 'timewindow'; sProcess.options.ref_range.Value = []; sProcess.options.ref_replicate_tresolution.Comment = 'Temporal resolution to extract ref signal: '; sProcess.options.ref_replicate_tresolution.Type = 'value'; sProcess.options.ref_replicate_tresolution.Value = {0.01, 'ms', 1}; % === BASELINE TIME RANGE FOR Z STATISTICS CALCULATION sProcess.options.baseline_time.Comment = 'Baseline: '; sProcess.options.baseline_time.Type = 'baseline'; sProcess.options.baseline_time.Value = []; % Options: Hanning window sProcess.options.isHann.Comment = 'Apply hanning window'; sProcess.options.isHann.Type = 'checkbox'; sProcess.options.isHann.Value = 0; %sProcess.options.sep2.Type = 'label'; % % Options: Mirror % sProcess.options.mirror.Comment = 'Estimating in frequency domain'; % sProcess.options.mirror.Type = 'checkbox'; % sProcess.options.mirror.Value = 0; % sProcess.options.mirror.InputTypes = {'data'}; % % === Low bound % sProcess.options.highpassA.Comment = 'Lower cutoff frequency (Data):'; % sProcess.options.highpassA.Type = 'value'; % sProcess.options.highpassA.Value = {15,'Hz ',2}; % sProcess.options.highpassA.InputTypes = {'data'}; % % === High bound % sProcess.options.lowpassA.Comment = 'Upper cutoff frequency (Data):'; % sProcess.options.lowpassA.Type = 'value'; % sProcess.options.lowpassA.Value = {29,'Hz ',2}; % sProcess.options.lowpassA.InputTypes = {'data'}; % % === Low bound % sProcess.options.highpassB.Comment = 'Lower cutoff frequency (Ref):'; % sProcess.options.highpassB.Type = 'value'; % sProcess.options.highpassB.Value = {0,'Hz ',2}; % sProcess.options.highpassB.InputTypes = {'data'}; % % === High bound % sProcess.options.lowpassB.Comment = 'Upper cutoff frequency (Ref):'; % sProcess.options.lowpassB.Type = 'value'; % sProcess.options.lowpassB.Value = {0,'Hz ',2}; % sProcess.options.lowpassB.InputTypes = {'data'}; % % === TF METHOD === % sProcess.options.tfmethod.Comment = {'Hilbert', 'Wavelet', 'STFT', 'TF method:'}; % sProcess.options.tfmethod.Type = 'radio_line'; % sProcess.options.tfmethod.Value = 1; % % === Width % sProcess.options.width.Comment = 'Cycles of wavelet:'; % sProcess.options.width.Type = 'value'; % sProcess.options.width.Value = {7, 'Cycles', 0}; % % === WINDOW LENGTH % sProcess.options.winlength.Comment = 'Estimator window length: '; % sProcess.options.winlength.Type = 'value'; % sProcess.options.winlength.Value = {0.128, 'ms ', 1}; % sProcess.options.winlength.InputTypes = {'data'}; % % === Low bound % sProcess.options.winoverlap.Comment = 'Overlap percentage: '; % sProcess.options.winoverlap.Type = 'value'; % sProcess.options.winoverlap.Value = {0.75, '% ', 1}; % sProcess.options.winoverlap.InputTypes = {'data'}; % % === Freq band % sProcess.options.freqband.Comment = 'Frequency band of interested:'; % sProcess.options.freqband.Type = 'text'; % sProcess.options.freqband.Value = 'beta'; % sProcess.options.freqband.InputTypes = {'timefreq'}; % % === SCOUTS === % sProcess.options.scouts.Comment = 'Use scouts'; % sProcess.options.scouts.Type = 'scout'; % sProcess.options.scouts.Value = []; % % === Freq band % sProcess.options.DICStest.Comment = 'DICS test'; % sProcess.options.DICStest.Type = 'text'; % sProcess.options.DICStest.Value = '1'; % === CONNECT INPUT %sProcess = process_corr1n('DefineConnectOptions', sProcess, 1); end %% ===== DEFINE SCOUT OPTIONS ===== function sProcess = DefineConnectOptions(sProcess, isConnNN) %#ok<DEFNU> % === TIME WINDOW === sProcess.options.label1.Comment = '<HTML><B><U>Input options</U></B>:'; sProcess.options.label1.Type = 'label'; sProcess.options.timewindow.Comment = 'Time window:'; sProcess.options.timewindow.Type = 'timewindow'; sProcess.options.timewindow.Value = []; % === FROM: CONNECTIVITY [1xN] === if ~isConnNN % === FROM: REFERENCE CHANNELS === sProcess.options.src_channel.Comment = 'Source channel: '; sProcess.options.src_channel.Type = 'channelname'; sProcess.options.src_channel.Value = 'name'; sProcess.options.src_channel.InputTypes = {'data'}; % === FROM: ROW NAME === sProcess.options.src_rowname.Comment = 'Source rows (names or indices): '; sProcess.options.src_rowname.Type = 'text'; sProcess.options.src_rowname.Value = ''; sProcess.options.src_rowname.InputTypes = {'timefreq', 'matrix'}; end % === TO: SENSOR SELECTION === sProcess.options.dest_sensors.Comment = 'Sensor types or names (empty=all): '; sProcess.options.dest_sensors.Type = 'text'; sProcess.options.dest_sensors.Value = 'MEG, EEG'; sProcess.options.dest_sensors.InputTypes = {'data'}; % === SCOUTS === sProcess.options.scouts.Comment = 'Use scouts'; if isConnNN sProcess.options.scouts.Type = 'scout_confirm'; else sProcess.options.scouts.Type = 'scout'; end sProcess.options.scouts.Value = []; sProcess.options.scouts.InputTypes = {'results'}; % Atlas: surface/volume sProcess.options.isvolume.Comment = ''; sProcess.options.isvolume.Type = 'checkbox'; sProcess.options.isvolume.Value = 0; sProcess.options.isvolume.Hidden = 1; % === SCOUT FUNCTION === sProcess.options.scoutfunc.Comment = {'Mean', 'Max', 'PCA', 'Std', 'All', 'Scout function:'}; sProcess.options.scoutfunc.Type = 'radio_line'; sProcess.options.scoutfunc.Value = 2; sProcess.options.scoutfunc.InputTypes = {'results'}; % === SCOUT TIME === sProcess.options.scouttime.Comment = {'Before', 'After', 'When to apply the scout function:'}; sProcess.options.scouttime.Type = 'radio_line'; sProcess.options.scouttime.Value = 2; sProcess.options.scouttime.InputTypes = {'results'}; end %% ===== FORMAT COMMENT ===== function Comment = FormatComment(sProcess) %#ok<DEFNU> Comment = sProcess.Comment; end %% ===== RUN ===== function OutputFiles = Run(sProcess, sInputsA, sInputsB) %#ok<DEFNU> % Initialize returned list of files OutputFiles = {}; if isempty(sInputsA) || isempty(sInputsB) bst_report('Error', sProcess, sInputsA, 'No inputs'); return; end InputsData = sInputsA ; InputsRef = sInputsB ; % Get option values %isFreq = sProcess.options.mirror.Value; OPTIONS.isHann = sProcess.options.isHann.Value; OPTIONS.BeamformerType = 2;%sProcess.options.beamformertype.Value; %ActiveTime = sProcess.options.active_time.Value{1}; % Get option values OPTIONS.BaselineTime = sProcess.options.baseline_time.Value{1}; OPTIONS.MinVarTime = sProcess.options.minvar_time.Value{1}; %OPTIONS.RefTime = sProcess.options.ref_range.Value{1}; OPTIONS.CORRrange = sProcess.options.corr_range.Value{1}; OPTIONS.Reg = sProcess.options.reg.Value{1}; OPTIONS.SensorTypes = sProcess.options.sensortypes.Value; OPTIONS.CORRTResolu = sProcess.options.corr_tresolution.Value{1}; OPTIONS.WinSize = sProcess.options.active_window_size.Value{1}; % OPTIONS.BandBoundsData = sProcess.options.nesting.Value; % OPTIONS.BandBoundsRef = sProcess.options.nested.Value; % OPTIONS.WinOverlap = sProcess.options.winoverlap.Value{1}; % OPTIONS.SegmentLength = sProcess.options.winlength.Value{1}; % OPTIONS.Width = sProcess.options.width.Value{1}; % Get and check frequencies OPTIONS.BandBoundsData = sProcess.options.nesting.Value{1}; OPTIONS.BandBoundsRef = sProcess.options.nested.Value{1}; OPTIONS.RefRangeType = sProcess.options.ref_range_type.Value; OPTIONS.Width = 256; %OPTIONS.Target = sProcess.options.scouts.Value; OPTIONS.nRand = sProcess.options.nRand.Value{1}; OPTIONS.TFmethod = 'hilbert'; % switch (sProcess.options.tfmethod.Value) % case 1, OPTIONS.TFmethod = 'hilbert'; % case 2, OPTIONS.TFmethod = 'wavelet'; % case 3, OPTIONS.TFmethod = 'stft'; % end switch (sProcess.options.measure.Value) case 1, OPTIONS.measure = 'cor'; OPTIONS.method = 'SILSC'; case 2, OPTIONS.measure = 'esc'; OPTIONS.method = 'BIPAC'; end if strcmp(OPTIONS.measure,'esc') || strcmp(OPTIONS.measure,'cfc') if (min(OPTIONS.BandBoundsData) < 0) bst_report('Error', sProcess, [], 'This function cannot be used to estimate PAC for nesting frequencies below 0 Hz.'); return; end if (max(OPTIONS.BandBoundsData) > min(OPTIONS.BandBoundsRef)) && min(OPTIONS.BandBoundsRef)~=0 && max(OPTIONS.BandBoundsRef)~=0 bst_report('Error', sProcess, [], 'The low and high frequency band cannot overlap.'); return; end end OPTIONS.RepRefNum = 0;%sProcess.options.ref_replicate_num.Value{1}; OPTIONS.RepRefInterval = 0;%sProcess.options.ref_replicate_interval.Value{1}; OPTIONS.RefDelayInterval = sProcess.options.ref_replicate_tresolution.Value{1}; OPTIONS.RefDelayRange = sProcess.options.ref_range.Value{1}; result_comment = sProcess.options.result_comm.Value; if ~isempty(result_comment) result_comment = [result_comment ': ']; end % MinVarTime = OPTIONS.CORRrange; % ===== LOAD THE REFRENCE DATA ===== % Read the first file in the list, to initialize the loop RefMat = in_bst(InputsRef(1).FileName, [], 0); %nRefTrials = size(RefMat.Value,1); RefFs = 1/(RefMat.Time(2)-RefMat.Time(1)); % if RefMat.Time(1) > OPTIONS.RefTime(1) % bst_report('Warning', sProcess, InputsData, 'The start for time range of reference signal is reset to the first time point of data'); % OPTIONS.RefTime(1) = RefMat.Time(1); % end % if RefMat.Time(end) < OPTIONS.RefTime(2) % bst_report('Warning', sProcess, InputsData, 'The end for time range of reference signal is reset to the last time point of data'); % OPTIONS.RefTime(2) = RefMat.Time(end); % end % RefTimePoints= panel_time('GetTimeIndices', RefMat.Time, [OPTIONS.RefTime(1) OPTIONS.RefTime(2)]); % RefLength = length(RefTimePoints); % ===== LOAD THE DATA ===== % Read the first file in the list, to initialize the loop DataMat = in_bst(InputsData(1).FileName, [], 0); if strcmpi(InputsData(1).FileType,'data') nChannels = size(DataMat.F,1); else nChannels = size(DataMat.TF,1); end Time = DataMat.Time; nTime = length(Time); DataFs = 1/(DataMat.Time(2)-DataMat.Time(1)); CorrWindowSize = OPTIONS.WinSize;%.RefTime(end)-OPTIONS.RefTime(1);%RefLength; if CorrWindowSize <= 0 || OPTIONS.CORRTResolu <= 0 CorrWindowSize = OPTIONS.CORRrange(2)-OPTIONS.CORRrange(1); OPTIONS.CORRTResolu = 0; end if OPTIONS.RepRefNum > 0 && OPTIONS.RepRefInterval > 0 CorrWindowSize = CorrWindowSize + (OPTIONS.RepRefNum-1)*OPTIONS.RepRefInterval; end HalfCorrWindowSize = CorrWindowSize/2; % ===== PROCESS THE TIME WINDOWS ===== if round(RefFs) ~= round(DataFs) bst_report('Error', sProcess, InputsData, 'The sampling rates of FileA and FileB are different.'); else Fs = RefFs; end if OPTIONS.CORRrange(1) > OPTIONS.CORRrange(2) bst_report('Error', sProcess, InputsData, 'The setting of time range of interest is incorrect.'); end if OPTIONS.CORRrange(1) < Time(1) bst_report('Warning', sProcess, InputsData, 'The start for time range of interest is reset to the first time point of data'); OPTIONS.CORRrange(1) = Time(1); end if OPTIONS.CORRrange(2) > Time(end) bst_report('Warning', sProcess, InputsData, 'The end for time range of interest is reset to the end point of data'); OPTIONS.CORRrange(2) = Time(end); end if (OPTIONS.CORRrange(1)+CorrWindowSize) > OPTIONS.CORRrange(2) || OPTIONS.CORRTResolu <= 0; bst_report('Warning', sProcess, InputsData, 'The active window size is reset to the same as the time range of interest.'); CorrWindowSize = OPTIONS.CORRrange(2) - OPTIONS.CORRrange(1); OPTIONS.CORRTResolu = 0; end CorrRangePoints = panel_time('GetTimeIndices', Time, [OPTIONS.CORRrange(1)+CorrWindowSize OPTIONS.CORRrange(2)]); if length(CorrRangePoints)<=1 nCORR = 1; else nCORR = length((OPTIONS.CORRrange(1)+CorrWindowSize):OPTIONS.CORRTResolu:OPTIONS.CORRrange(2)); if nCORR == 0 bst_report('Error', sProcess, InputsData, 'No correlation windows.'); end end CorrTimeList= zeros(nCORR,2); for i=1:nCORR CorrTimeList(i,:) = OPTIONS.CORRrange(1) + OPTIONS.CORRTResolu*(i-1) + [0 CorrWindowSize] ; end MinVarRangePoint = panel_time('GetTimeIndices', Time, [OPTIONS.MinVarTime(1) OPTIONS.MinVarTime(2)]); % ===== LOAD CHANNEL FILE ===== % Load channel file ChannelMat = in_bst_channel(InputsData(1).ChannelFile); % Find the MEG channels iChannels = channel_find(ChannelMat.Channel, OPTIONS.SensorTypes); % ===== LOAD HEAD MODEL ===== % Get channel study [sChannelStudy, iChannelStudy] = bst_get('ChannelFile', InputsData(1).ChannelFile); % Load the default head model HeadModelFile = sChannelStudy.HeadModel(sChannelStudy.iHeadModel).FileName; sHeadModel = load(file_fullpath(HeadModelFile)); nCorrWindowPoints = length(panel_time('GetTimeIndices', Time, CorrTimeList(1,:))); for i=2:nCORR nCorrWindowPoints = min(nCorrWindowPoints,length(panel_time('GetTimeIndices', Time, CorrTimeList(i,:)))); end iCorrWindowTime = zeros(nCORR, nCorrWindowPoints); for i = 1:nCORR if CorrTimeList(i,1) < Time(1) || CorrTimeList(i,2) > Time(end) % Add an error message to the report bst_report('Error', sProcess, sInputsA, 'One correlation time window is not within the data time range.'); % Stop the process return; end single_iCorrWindow = panel_time('GetTimeIndices', Time, CorrTimeList(i,:)); if length(single_iCorrWindow) < nCorrWindowPoints bst_report('Error', sProcess, sInputsA, 'Wrong time range'); % Stop the process return; end iCorrWindowTime(i,:) = single_iCorrWindow(1:nCorrWindowPoints); end bst_progress('start', ['Applying process: ' OPTIONS.method], 'Loading reference...', 0, length(InputsRef)); nRef = 0; nOriRef = 0; nTrials = length(InputsData); AllRefData = cell(nCORR,1); RowName = {}; if OPTIONS.RefRangeType == 1 DelayList = ((OPTIONS.RefDelayRange(1)+CorrWindowSize):OPTIONS.RefDelayInterval:OPTIONS.RefDelayRange(2))-HalfCorrWindowSize; nDelay = length(DelayList); if nDelay==0; nDelay=1; DelayList=0; end elseif OPTIONS.RefRangeType == 2 DelayList = OPTIONS.RefDelayRange(1):OPTIONS.RefDelayInterval:OPTIONS.RefDelayRange(2); nDelay = length(DelayList); if nDelay==0; nDelay=1; DelayList=0; end end RefLength = nCorrWindowPoints; TargetList = {}; %AllRefData = zeros(nTrials, RefLength,length(InputsRef)); % Reading all the input files in a big matrix for i = 1:length(InputsRef) % Read the file #i RefMat = in_bst(InputsRef(i).FileName, [], 0); % Check the dimensions of the recordings matrix in this file if mod(size(RefMat.Value,1), nTrials)~=0 % Add an error message to the report bst_report('Error', sProcess, InputsData, 'One reference file has a different number of trials.'); % Stop the process return; else nRefSingleFile = (size(RefMat.Value,1) / nTrials); refData = RefMat.Value; end hw = hann(double(nCorrWindowPoints)); for j = 1:nRefSingleFile fileRefData = refData(j:nRefSingleFile:end,:); sRate = 1 / (RefMat.Time(2) - RefMat.Time(1)); if strcmp(OPTIONS.measure,'esc') || strcmp(OPTIONS.measure,'cfc') fileRefData = amp_vec(fileRefData,OPTIONS.BandBoundsRef,sRate,OPTIONS.Width,OPTIONS.TFmethod); if strcmp(OPTIONS.measure, 'cfc') fileRefData = (fileRefData / sRate).^2; end end for m=1:nDelay if strcmpi(InputsRef(i).FileType,'timefreq') RowName{nRef+m} = [RefMat.RowNames{j} ' (' DelayList(m) 'ms)']; else RowName{nRef+m} = [RefMat.Description{j} ' (' DelayList(m) 'ms)']; end end if isfield(RefMat,'Atlas') if ~isempty(RefMat.Atlas) TargetList{nOriRef+j}=RefMat.Atlas.Scouts(j); end end if OPTIONS.RefRangeType == 1 for m=1:nDelay refTime = OPTIONS.RefDelayRange(1) + OPTIONS.RefDelayInterval*(m-1) + [0 CorrWindowSize]; if (RefMat.Time(1) > refTime(1)) || (RefMat.Time(end) < refTime(2)) % Add an error message to the report bst_report('Error', sProcess, InputsData, 'The selected range for extracting reference signal is out of range.'); % Stop the process return; end iRefWindow = panel_time('GetTimeIndices', Time, refTime); iRefWindow = iRefWindow(1:nCorrWindowPoints); cRefData = fileRefData(:,iRefWindow); if OPTIONS.isHann for n = 1:nTrials cRefData(n,:) = cRefData(n,:).*hw'; end end %else % RefMat.Value = RefMat.Value(j:nRefSingleFile:end,RefTimePoints); % RefMatAvg = mean(RefMat.Value, 2); % fileRefData = bst_bsxfun(@minus, RefMat.Value, RefMatAvg); %end AllRefData{1} = cat(3,AllRefData{1}, cRefData); end elseif OPTIONS.RefRangeType == 2 for k=1:nCORR for m=1:nDelay refTime = CorrTimeList(k,:) + DelayList(m); if (RefMat.Time(1) > refTime(1)) || (RefMat.Time(end) < refTime(2)) % Add an error message to the report bst_report('Error', sProcess, InputsData, 'The selected range for extracting reference signal is out of range.'); % Stop the process return; end iRefWindow = panel_time('GetTimeIndices', Time, refTime); iRefWindow = iRefWindow(1:nCorrWindowPoints); cRefData = fileRefData(:,iRefWindow); if OPTIONS.isHann for n = 1:nTrials cRefData(n,:) = cRefData(n,:).*hw'; end end %else % RefMat.Value = RefMat.Value(j:nRefSingleFile:end,RefTimePoints); % RefMatAvg = mean(RefMat.Value, 2); % fileRefData = bst_bsxfun(@minus, RefMat.Value, RefMatAvg); %end AllRefData{k} = cat(3,AllRefData{k}, cRefData); end end end end nRef = nRef + nRefSingleFile*nDelay; nOriRef = nOriRef + nRefSingleFile; bst_progress('inc',1); end RepRefIntervalPoints = round(OPTIONS.RepRefInterval / (Time(2) - Time(1))); if OPTIONS.RepRefNum > 0 && RepRefIntervalPoints > 0 for k=1:nCORR % nRefTrials, RefLength, nRef RepRefData = zeros(nTrials,RefLength + (OPTIONS.RepRefNum-1)*RepRefIntervalPoints,nRef*OPTIONS.RepRefNum); % Relicate Reference Signal for i = 1:OPTIONS.RepRefNum RepRefData(:,(i-1)*RepRefIntervalPoints + (1:RefLength),(i-1)*nRef + (1:nRef)) = AllRefData{k}; end nRef = nRef*OPTIONS.RepRefNum; AllRefData{k} = RepRefData; end else OPTIONS.RepRefNum = 1; end for i=1:nCORR AllRefData{i} = permute(AllRefData{i},[2 3 1]); %RefLength, nRef, nRefTrials end AllCovRef = cell(nCORR,1); AllRefDataCell = AllRefData; AllRefDataCellorig = AllRefDataCell; clear AllRefData; for m=1:nCORR if OPTIONS.RefRangeType == 1 && m > 1 if nRef > 1 AllCovRef{m}.origcov = AllCovRef{1}.origcov; AllCovRef{m}.originv_cov=AllCovRef{1}.originv_cov; end AllCovRef{m}.cov = AllCovRef{1}.cov; AllCovRef{m}.inv_cov = AllCovRef{1}.inv_cov; AllRefDataCellorig{m} = AllRefDataCellorig{1}; AllRefDataCell{m} = AllRefDataCell{1}; continue; end AllRefData = AllRefDataCell{m}; covRef = zeros(nRef,nRef); for i = 1:nTrials singleRefTrial = squeeze(AllRefData(:,:,i))'; singleRefTrialAvg = mean(singleRefTrial, 2); AllRefData(:,:,i) = bst_bsxfun(@minus, singleRefTrial, singleRefTrialAvg)'; covRef = covRef + AllRefData(:,:,i)'*AllRefData(:,:,i); end AllRefDataCellorig{m}=AllRefData; if nRef > 1 origAllRefData = AllRefDataCell{m}; covRef = covRef/(nTrials*RefLength-1); [v,d]=eig(covRef); C=v*diag(diag(d).^(-0.5)); origcovRef = covRef; for i = 1:nTrials singleRefTrial = C'*squeeze(origAllRefData(:,:,i))'; singleRefTrialAvg = mean(singleRefTrial, 2); AllRefData(:,:,i) = bst_bsxfun(@minus, singleRefTrial, singleRefTrialAvg)'; covRef = covRef + AllRefData(:,:,i)'*AllRefData(:,:,i); end AllRefDataCell{m} = AllRefData; % figure; % subplot(2,1,1); % imagesc(origcovRef);colorbar; % subplot(2,1,2); % imagesc(covRef/(nTrials*RefLength-1));colorbar; AllCovRef{m}.origcov=origcovRef; % Calculate the inverse of covRef AllCovRef{m}.originv_cov=inv(AllCovRef{m}.origcov); end covRef = covRef / (nTrials*RefLength-1); AllCovRef{m}.cov=covRef; % Calculate the inverse of covRef AllCovRef{m}.inv_cov=inv(covRef); end % if nRef == 1 % covRef_inv = inv(covRef); % else % [U,S,V] = svd(covRef); % S = diag(S); % Covariance = Cm = U*S*U' % Si = diag(1 ./ (S + S(1) * Reg / 100)); % 1/(S^2 + lambda I) % covRef_inv = V*Si*U'; % U * 1/(S^2 + lambda I) * U' = Cm^(-1) % end % Find the indices for covariance calculation %iMinVarTime = panel_time('GetTimeIndices', Time, MinVarTime); % Initialize the covariance matrices MinVarCov = zeros(nChannels, nChannels); CorrCovOfNumerator = zeros(nChannels, nRef ,nCORR); CorrCovOfDenominator = zeros(nChannels, nChannels, nCORR); CorrCovOfNumeratorOrig = zeros(nChannels, nRef ,nCORR); nTotalMinVar = zeros(nChannels, nChannels, nCORR); nTotalCorrCovOfNumerator = zeros(nChannels, nRef, nCORR); nTotalCorrCovOfDenominator = zeros(nChannels, nChannels, nCORR); nTotalCorrCovOfNumeratorOrig = zeros(nChannels, nRef, nCORR); % Extract the covariance matrix of the used channels NoiseCovMat = load(file_fullpath(sChannelStudy.NoiseCov.FileName)); NoiseCov = NoiseCovMat.NoiseCov(iChannels,iChannels); bst_progress('start', ['Applying process: ' OPTIONS.method], 'Calculating covariance matrices...', 0, length(InputsData)*nCORR); if OPTIONS.BaselineTime(1)==OPTIONS.BaselineTime(2) iBaselineTime = []; else iBaselineTime = panel_time('GetTimeIndices', Time, OPTIONS.BaselineTime); end % Reading all the input files in a big matrix for i = 1:nTrials % Read the file #i DataMat = in_bst(InputsData(i).FileName, [], 0); % Check the dimensions of the recordings matrix in this file if (size(DataMat.F,1) ~= nChannels) || (size(DataMat.F,2) ~= nTime) % Add an error message to the report bst_report('Error', sProcess, InputsData, 'One file has a different number of channels or a different number of time samples.'); % Stop the process return; end if strcmp(OPTIONS.measure,'esc') && OPTIONS.BandBoundsData(1)~=0 && OPTIONS.BandBoundsData(2)~=0 DataMat.F = bp_vec(DataMat.F,OPTIONS.BandBoundsData,sRate,OPTIONS.Width,OPTIONS.TFmethod); end % Get good channels iGoodChan = find(DataMat.ChannelFlag == 1); %for j = 1:nCORR % j=1; if ~isempty(iBaselineTime) % Remove average FavgActive = mean(DataMat.F(iGoodChan,iBaselineTime), 2); DataMinVar = bst_bsxfun(@minus, DataMat.F(iGoodChan,MinVarRangePoint), FavgActive); else DataMinVar = DataMat.F(iGoodChan,MinVarRangePoint); end % % Average baseline values % FavgMinVar = mean(DataMat.F(iGoodChan,MinVarRangePoint), 2); % % Remove average % DataMinVar = bst_bsxfun(@minus, DataMat.F(iGoodChan,MinVarRangePoint), FavgMinVar); % Compute covariance for this file fileMinVarCov = DataMat.nAvg .* (DataMinVar * DataMinVar'); MinVarCov(iGoodChan,iGoodChan,j) = bst_bsxfun(@plus,MinVarCov(iGoodChan,iGoodChan), fileMinVarCov); nTotalMinVar(iGoodChan,iGoodChan,j) = nTotalMinVar(iGoodChan,iGoodChan) + RefLength*DataMat.nAvg; %end % end % if ~isFreq % % Average baseline values % FavgMinVar = mean(DataMat.F(iGoodChan,iMinVarTime), 2); % % Remove average % DataMinVar = bst_bsxfun(@minus, DataMat.F(iGoodChan,iMinVarTime), FavgMinVar); % % Compute covariance for this file % fileMinVarCov = DataMat.nAvg .* (DataMinVar * DataMinVar'); % else % [Cxy,freq] = crossSpectrum(DataMat.F(iGoodChan,iMinVarTime), DataMat.F(iGoodChan,iMinVarTime), Fs, SegmentLength, []); % fileMinVarCov = zeros(size(Cxy,1),size(Cxy,2)); % nCxy = 0; % for f = 1:length(freq) % if (freq(f) <= BandBounds(2)) && (freq(f) >= BandBounds(1)) % fileMinVarCov = fileMinVarCov + Cxy(:,:,f); % nCxy = nCxy + 1; % end % end % if nCxy > 0 % fileMinVarCov = DataMat.nAvg * fileMinVarCov / nCxy; % end % end % % %fileMinVarCov = DataMinVar * DataMinVar'; % % Add file covariance to accumulator % MinVarCov(iGoodChan,iGoodChan) = MinVarCov(iGoodChan,iGoodChan) + fileMinVarCov; % nTotalMinVar(iGoodChan,iGoodChan) = nTotalMinVar(iGoodChan,iGoodChan) + length(iMinVarTime)*DataMat.nAvg; for j = 1:nCORR AllRefData = AllRefDataCell{j}; if strcmp(OPTIONS.measure,'cfc') || strcmp(OPTIONS.measure,'coh') %if ~isCrossFreq [Cxy,freq,Cxx] = crossSpectrum(DataMat.F(iGoodChan,iCorrWindowTime(j,:)), AllRefData(:,:,i)', Fs, OPTIONS.SegmentLength, [], OPTIONS.WinOverlap); %else % [Cxy,freq,Cxx] = crossSpectrumCrossFreq(DataMat.F(iGoodChan,iCorrWindowTime(j,:)), AllRefData(:,:,i)', Fs, BandBoundsRef, SegmentLength, [], WinOverlapLength); %end fileDataInCorrWindowCovD = zeros(size(Cxx,1),size(Cxx,2)); fileDataInCorrWindowCovN = zeros(size(Cxy,1),size(Cxy,2)); nCxy = 0; for f = 1:length(freq) if (freq(f) <= OPTIONS.BandBoundsData(2)) && (freq(f) >= OPTIONS.BandBoundsData(1)) fileDataInCorrWindowCovD = fileDataInCorrWindowCovD + Cxx(:,:,f); fileDataInCorrWindowCovN = fileDataInCorrWindowCovN + Cxy(:,:,f); nCxy = nCxy + 1; end end if nCxy > 0 fileDataInCorrWindowCovN = fileDataInCorrWindowCovN / nCxy; fileDataInCorrWindowCovD = fileDataInCorrWindowCovD / nCxy; else bst_report('Error', sProcess, InputsData, 'Cannot find signal within this frequency range.'); end else % Average baseline values DataAvg = mean(DataMat.F(iGoodChan,iCorrWindowTime(j,:)), 2); % Remove average DataInCorrWindow = bst_bsxfun(@minus, DataMat.F(iGoodChan,iCorrWindowTime(j,:)), DataAvg); % Compute covariance for this file fileDataInCorrWindowCovN = (DataInCorrWindow * AllRefData(:,:,i)); fileDataInCorrWindowCovD = (DataInCorrWindow * DataInCorrWindow'); end if nRef > 1 fileDataInCorrWindowCovNorig = (DataInCorrWindow * AllRefDataCellorig{j}(:,:,i)); % Add file covariance to accumulator CorrCovOfNumeratorOrig(iGoodChan,:,j) = bst_bsxfun(@plus,CorrCovOfNumeratorOrig(iGoodChan,:,j), fileDataInCorrWindowCovNorig); nTotalCorrCovOfNumeratorOrig(iGoodChan,:,j) = nTotalCorrCovOfNumeratorOrig(iGoodChan,:,j) + RefLength; end % Add file covariance to accumulator CorrCovOfNumerator(iGoodChan,:,j) = bst_bsxfun(@plus, CorrCovOfNumerator(iGoodChan,:,j), fileDataInCorrWindowCovN); nTotalCorrCovOfNumerator(iGoodChan,:,j) = nTotalCorrCovOfNumerator(iGoodChan,:,j) + RefLength; % Add file covariance to accumulator CorrCovOfDenominator(iGoodChan,iGoodChan,j) = bst_bsxfun(@plus, CorrCovOfDenominator(iGoodChan,iGoodChan,j), fileDataInCorrWindowCovD); nTotalCorrCovOfDenominator(iGoodChan,iGoodChan,j) = nTotalCorrCovOfDenominator(iGoodChan,iGoodChan,j) + RefLength; bst_progress('inc',1); end end % Remove zeros from N matrix nTotalMinVar(nTotalMinVar <= 1) = 2; nTotalCorrCovOfNumerator(nTotalCorrCovOfNumerator <= 1) = 2; nTotalCorrCovOfDenominator(nTotalCorrCovOfDenominator <=1 ) = 2; nTotalCorrCovOfNumeratorOrig(nTotalCorrCovOfNumeratorOrig <= 1) = 2; % Divide final matrix by number of samples MinVarCov = MinVarCov ./ (nTotalMinVar-1); CorrCovOfNumerator = CorrCovOfNumerator ./ (nTotalCorrCovOfNumerator-1); CorrCovOfDenominator = CorrCovOfDenominator ./ (nTotalCorrCovOfDenominator-1); CorrCovOfNumeratorOrig = CorrCovOfNumeratorOrig ./ (nTotalCorrCovOfNumeratorOrig-1); CovCovOfNumerator = zeros(nChannels,nChannels,nCORR); for j = 1:nCORR CovCovOfNumerator(:,:,j) = CorrCovOfNumerator(:,:,j)*AllCovRef{j}.inv_cov*CorrCovOfNumerator(:,:,j)'; end % ===== PROCESS ===== % Processing iChannels %%%% TO EDIT %%%%% % Get Study % Extract the covariance matrix of the used channels %ActiveCov = ActiveCov(iChannels,iChannels); %NoiseCovMat = load(file_fullpath(sChannelStudy.NoiseCov.FileName)); %NoiseCov = NoiseCovMat.NoiseCov(iChannels,iChannels); MinVarCov = MinVarCov(iChannels,iChannels,:); CovCovOfNumerator = CovCovOfNumerator(iChannels,iChannels,:); CorrCovOfNumerator = CorrCovOfNumerator(iChannels,:,:); CorrCovOfDenominator = CorrCovOfDenominator(iChannels,iChannels,:); CorrCovOfNumeratorOrig = CorrCovOfNumeratorOrig(iChannels,:,:); % Normalize the regularization parameter % eigValues = eig(MinVarCov); % Reg_alpha = Reg * max(eigValues); % Calculate the inverse of (Cm+alpha*I) % if isFreq % if strcmpi(InputsData(1).FileType,'data') % MinVarCov = CorrCovOfDenominator; % MinVarCov_inv = CorrCovOfDenominator; % end % for j=1:nCORR MinVarCov_inv(:,:,1) = pInv(MinVarCov(:,:,1), OPTIONS.Reg); % end % else % tmp = pInv(MinVarCov, Reg); % MinVarCov_inv = zeros(length(iChannels),length(iChannels),nCORR); % for j=1:nCORR % MinVarCov_inv(:,:,j) = tmp; % end % end % Get forward field Kernel = sHeadModel.Gain(iChannels,:); %Kernel(abs(Kernel(:)) < eps) = eps; % Set zero elements to strictly non-zero [nChannels ,nSources] = size(Kernel); % size of Gain Matrix % ===== CALCULATE NEURAL ACTIVITY INDEX AND FILTERS ===== CorrMaps = zeros(nSources/3,nCORR); AmpMaps = zeros(nSources/3,nCORR); Ori = zeros(3,nSources/3,nCORR); spatialFilter = zeros(nSources/3, nChannels,nCORR); % calculate filter for outputs bst_progress('start', ['Applying process: ' OPTIONS.method], 'Calculating spatial filters...', 0, nCORR*nSources/3); %testNum = str2double(sProcess.options.DICStest.Value); if OPTIONS.BeamformerType == 1 for r = 1:3:nSources % calculate noise power for index r2 = (r+2)/3; Gr = Kernel(:,r:r+2); for j=1:nCORR W = pinv(Gr' * MinVarCov_inv * Gr)* Gr' * MinVarCov_inv; % [u,s,v] = svd(real(W * MinVarCov(:,:,j) * W')); [u,s,v] = svd( real(W * CovCovOfNumerator(:,:,j)* W')); if s(1) > 100*s(2) csd = s(1,1); %w = u(:,1); else csd = trace(s); %w = [1 1 1]/sqrt(3); end [u,s,v] = svd( real(W * CorrCovOfDenominator(:,:,j)* W')); if s(1) > 100*s(2) pow = s(1,1); else pow = trace(s); end %CorrMaps(r2,j) = sqrt((w*CovCovOfNumerator(:,:,j)*w')/(w*CorrCovOfDenominator(:,:,j)*w')); CorrMaps(r2,j) = sqrt(csd/pow); spatialFilter(r2,:,j) = w; bst_progress('inc',1); end end else usedKernel = mat2cell(Kernel,nChannels,3*ones(1,nSources/3)); Cmat = cellfun(@(x)MinVarCov_inv*x, usedKernel, 'UniformOutput', false); Dmat = cellfun(@(x,y)x'*y, usedKernel, Cmat, 'UniformOutput', false); for j=1:nCORR Pmat = cellfun(@(x) x'*CovCovOfNumerator(:,:,j)*x, Cmat, 'UniformOutput', false); Qmat = cellfun(@(x) x'*CorrCovOfDenominator(:,:,j)*x, Cmat, 'UniformOutput', false); invQmat = cellfun(@(x)pInv(x,0.0000000001),Qmat, 'UniformOutput', false); invQPmat = cellfun(@mtimes, invQmat, Pmat, 'UniformOutput', false); [eigVecmat, eigValmat] = cellfun(@eig, invQPmat, 'UniformOutput', false); if min(size(eigValmat{1,1}))>1 eigValmat = cellfun(@diag, eigValmat, 'UniformOutput', false); end [~, imaxmat] = cellfun(@max, eigValmat, 'UniformOutput', false); Orimat = cellfun(@(x,y)x(:,y), eigVecmat, imaxmat, 'UniformOutput', false); Ori(:,:,j) = cell2mat(Orimat); bst_progress('inc',nSources/6); tmpMat = cellfun(@(x,y)x'*y*x, Orimat, Dmat, 'UniformOutput', false); tmpMat2 = cellfun(@mtimes, Cmat, Orimat, 'UniformOutput', false); sfmat = cellfun(@mrdivide, tmpMat2, tmpMat, 'UniformOutput', false); vcMat = cellfun(@(x)x'*NoiseCov*x, sfmat,'UniformOutput', false); tmpMat = cellfun(@(x)x'*CovCovOfNumerator(:,:,j)*x, sfmat); tmpMat2 = cellfun(@(x)x'*CorrCovOfDenominator(:,:,j)*x, sfmat); CorrMat = bsxfun(@rdivide, tmpMat, tmpMat2); CorrMaps(:,j) = arrayfun(@sqrt, CorrMat); tmpMat = cell2mat(vcMat); AmpMat =bsxfun(@rdivide, tmpMat2, tmpMat); AmpMaps(:,j) = AmpMat;%arrayfun(@sqrt, AmpMat); vcMat = cellfun(@sqrt, vcMat, 'UniformOutput', false); ImagingKernel = cellfun(@mrdivide, sfmat, vcMat, 'UniformOutput', false); spatialFilter(:,:,j) = cell2mat(ImagingKernel)'; bst_progress('inc',nSources/6); end % Cr = MinVarCov_inv * Gr; % Dr = Gr' * Cr; % % Pr = Cr' * CovCovOfNumerator(:,:,j)* Cr; % Qr = Cr' * CorrCovOfDenominator(:,:,j)* Cr; % %Qr = Cr' * NoiseCov* Cr; % % % Regularize the matrix Q to avoid singular problem % invQr = pInv(Qr,0.0000000001); % % % Compute the dipole orientation % % (the eigenvector corresponding to maximum eigenvalue of inv(Q)*P) % [eigVectors,eigValues] = eig(invQr*Pr); % % check whether eigValues are saved as matrix or vector % if min(size(eigValues))==1 % [tmp, imax] = max(eigValues); % else % [tmp, imax] = max(diag(eigValues)); % end % DipoleOri = eigVectors(:,imax); % % Ori(:,r2,j) = DipoleOri; % w = Cr*DipoleOri/(DipoleOri'*Dr*DipoleOri); % spatialFilter(r2,:,j) = w'; % CorrMaps(r2,j) = sqrt((w'*CovCovOfNumerator(:,:,j)*w)/(w'*CorrCovOfDenominator(:,:,j)*w)); % AmpMaps(r2,j)=sqrt((w'*CorrCovOfDenominator(:,:,j)*w)/(w'*NoiseCov*w)); % % if imag(CorrMaps(r2,j))~=0 % % disp('ERROR'); % % end % % bst_progress('inc',1); end nSources = nSources/3 ; nRand = 0;%OPTIONS.nRand; %% Correction if nRand > 0 % Generate simulation sources bst_progress('start', ['Applying process: ' OPTIONS.method], 'Calculating Spurious Corr...', 0, nCORR*nSources); totalTimePoints = size(DataMat.F,2); simuSignalRef = randn(totalTimePoints,nRef/nDelay,nTrials); simuSignalTarget = randn(totalTimePoints,nTrials,nRand); CorrMapsRand = zeros(nSources,nRand,nCORR); for j=1:nCORR simuMeasurementsRef = zeros(nChannels,totalTimePoints,nTrials); for iRef = 1:nOriRef r = TargetList{iRef}.Seed; Gr = Kernel(:,(r-1)*3+(1:3))*Ori(:,r,j); w = squeeze(spatialFilter(r,:,j)); amps = sqrt(w*CorrCovOfDenominator(:,:,j)*w'); for i=1:nTrials powMat = repmat(amps*simuSignalRef(:,iRef,i)',nChannels,1); simuMeasurementsRef(:,:,i) = simuMeasurementsRef(:,:,i) + powMat.*repmat(Gr,1,totalTimePoints); end end for r=1:nSources Gr = Kernel(:,(r-1)*3+(1:3))*Ori(:,r,j); wr = squeeze(spatialFilter(r,:,j)); amps = sqrt(wr*CorrCovOfDenominator(:,:,j)*wr'); for n=1:nRand Cba = zeros(nRef,1); Cbb = zeros(nRef,nRef); Caa = 0; for i=1:nTrials powMat = repmat(amps*simuSignalTarget(:,i,n)',nChannels,1); simuMeasurementsAll = simuMeasurementsRef(:,:,i) + powMat.*repmat(Gr,1,totalTimePoints); ind = 1; refSignals = zeros(nRef,nCorrWindowPoints); for iRef = 1:nOriRef w = squeeze(spatialFilter(TargetList{iRef}.Seed,:,j)); tmp=w*simuMeasurementsAll; for m=1:nDelay refTime = CorrTimeList(j,:) + DelayList(m); iRefWindow = panel_time('GetTimeIndices', Time, refTime); refSignals(ind,:) = tmp(iRefWindow(1:nCorrWindowPoints)); ind = ind+1; if OPTIONS.isHann refSignals(ind,:) = refSignals(ind,:).*hw'; end end end tmp = wr*simuMeasurementsAll(:,iCorrWindowTime(j,:)); Cba = Cba + refSignals*tmp'; Cbb = Cbb + refSignals*refSignals'; Caa = Caa + tmp*tmp'; end Cba = Cba / (nTrials*nCorrWindowPoints-1); Cbb = Cbb / (nTrials*nCorrWindowPoints-1); Caa = Caa / (nTrials*nCorrWindowPoints-1); CorrMapsRand(r,n,j) = sqrt(Cba'*inv(Cbb)*Cba/Caa); end bst_progress('inc',1); end end end %% ===== Calculate weights ===== if nDelay > 1 bst_progress('start', ['Applying process: ' OPTIONS.method], 'Calculating weights ...', 0, nSources); CorrWeight = zeros(nSources,nCORR,nDelay,nRef/nDelay); CorrWeight2 = zeros(nSources,nCORR,nDelay,nRef/nDelay); for r = 1:1:nSources for j=1:nCORR w = squeeze(spatialFilter(r,:,j)); Cab = w*CorrCovOfNumeratorOrig(:,:,j); for k = 1:nRef f(k) = (w*squeeze(CorrCovOfNumeratorOrig(:,k,j)))/(sqrt(w*CorrCovOfDenominator(:,:,j)*w')*sqrt(AllCovRef{j}.origcov(k,k))); end f2 = Cab*AllCovRef{j}.originv_cov; f2 = f2/norm(f2)*CorrMaps(r,j); ind = 0; for k = 1:nDelay for i = 1:nRef/nDelay ind = ind + 1; CorrWeight(r,j,k,i) = f(ind); CorrWeight2(r,j,k,i) = f2(ind); %f(ind) = Cab(ind)/AllCovRef{j}.origcov(ind,ind); end end end bst_progress('inc',1); end %CorrWeight = CorrWeight/max(abs(CorrWeight(:))); end %% ===== ASSIGN MAPS AND KERNELS ===== bst_progress('start', ['Applying process: ' OPTIONS.method], 'Saving results...', 0, 3+nCORR*3); timestring = sprintf('%d_%d',round(OPTIONS.CORRrange(1)*1000),round(OPTIONS.CORRrange(2)*1000)); % == Save the spatial filter as ImagingKernel == % for i=1:nCORR % sp_window_time_string = sprintf('%.1f-%.1f', CorrTimeList(i,1)*1000, CorrTimeList(i,2)*1000); % sp_window_time_string = []; saveSF = 1; if saveSF == 1 % Create a new data file structure ResultsMat2 = db_template('resultsmat'); if nCORR > 1 [Cval,Ind]=max(CorrMaps'); clear Cval; for i=1:nSources spatialFilter(i,:,1) = spatialFilter(i,:,Ind(i)); Ori(:,i,1) = Ori(:,i,Ind(i)); end spatialFilter = squeeze(spatialFilter(:,:,1)); Ori = squeeze(Ori(:,:,1)); end ResultsMat2.ImagingKernel = spatialFilter; ResultsMat2.ImageGridAmp = []; ResultsMat2.EstimatedGridOrient = Ori'; ResultsMat2.nComponents = 1; if strcmp(OPTIONS.measure,'cfc') || strcmp(OPTIONS.measure,'coh') if ~isCrossFreq if BeamformerType == 1 ResultsMat2.Comment = [result_comment OPTIONS.method ': spatial filter |' timestring 'ms(' num2str(BandBoundsData(1)) '-' num2str(BandBoundsData(2)) 'Hz)' ]; else ResultsMat2.Comment = [result_comment OPTIONS.method ': spatial filter |' timestring 'ms(' num2str(BandBoundsData(1)) '-' num2str(BandBoundsData(2)) 'Hz)' ]; end else if BeamformerType == 1 ResultsMat2.Comment = [result_comment OPTIONS.method ': spatial filter |' timestring 'ms(' num2str(BandBoundsData(1)) '-' num2str(BandBoundsData(2)) ',' num2str(BandBoundsRef(1)) '-' num2str(BandBoundsRef(2)) 'Hz)' ]; else ResultsMat2.Comment = [result_comment OPTIONS.method ': spatial filter |' timestring 'ms(' num2str(BandBoundsData(1)) '-' num2str(BandBoundsData(2)) ',' num2str(BandBoundsRef(1)) '-' num2str(BandBoundsRef(2)) 'Hz)' ]; end end else if OPTIONS.BeamformerType == 1 ResultsMat2.Comment = [result_comment OPTIONS.method ': spatial filter |' timestring 'ms' ]; else ResultsMat2.Comment = [result_comment OPTIONS.method ': spatial filter |' timestring 'ms' ]; end end ResultsMat2.Function = 'SILSCspatialfilter'; ResultsMat2.Time = []; % Leave it empty if using ImagingKernel ResultsMat2.DataFile = []; ResultsMat2.HeadModelFile = HeadModelFile; ResultsMat2.HeadModelType = sHeadModel.HeadModelType; ResultsMat2.ChannelFlag = []; ResultsMat2.GoodChannel = iChannels; if strcmp(sHeadModel.HeadModelType,'volume') ResultsMat2.GridLoc = sHeadModel.GridLoc; ResultsMat2.SurfaceFile = sHeadModel.SurfaceFile; else ResultsMat2.SurfaceFile = sHeadModel.SurfaceFile; end %ResultsMat2.GridLoc = [];%sHeadModel.GridLoc; % === SHARED == % Get the output study (pick the one from the first file) iStudy = iChannelStudy; %nOutputFiles = length(OutputFiles); % Create a default output filename Outs = bst_process('GetNewFilename', fileparts(InputsData(1).ChannelFile), 'results_beam_KERNEL'); % Save on disk save(Outs, '-struct', 'ResultsMat2'); % bst_save(OutputFiles{nOutputFiles+1}, ResultsMat2,'v6'); % Register in database db_add_data(iStudy, Outs, ResultsMat2); bst_progress('inc',1); end % end if nCORR == 1 % CORRRangePoints = panel_time('GetTimeIndices', Time, CORRrange); % bst_progress('start', 'Applying process: SISSC', 'Interpolating correlation dynamics...', 0, length(CORRRangePoints)); % ImageGridAmp = zeros(nSources,nTime); % % for i = CORRRangePoints(1):CORRRangePoints(end) % ImageGridAmp(:,i) = CorrMaps(:,1); % bst_progress('inc',1); % end TFMat = db_template('timefreqmat'); % timestring2 = sprintf('(ws:%d%s)',round(CorrWindowSize*1000),'ms'); TFMat.Time = [OPTIONS.CORRrange(1), OPTIONS.CORRrange(end)]; %TFMat.TimeBands = {'corr',[num2str(CORRrange(1)) ',' num2str(CORRrange(end))], 'mean'}; % Leave it empty if using ImagingKernel TFMat.TF = [CorrMaps CorrMaps]; [mv, mr] = max(CorrMaps); sSubject = bst_get('Subject', 0); sMRI = load(file_fullpath(sSubject.Anatomy.FileName)); lc = cs_convert(sMRI, 'scs', 'mni', sHeadModel.GridLoc(mr,:))*1000; disp(['BIPAC> Maximum Peak Location: ' num2str(round(lc)) ]); disp(['BIPAC> Maximum Peak Value: ' num2str(mv) ]); else % Interpolate the correlation maps to have the same temporal resolution as the data bst_progress('start', ['Applying process: ' OPTIONS.method], ['Interpolating ' OPTIONS.measure ' dynamics...'], 0, nCORR+1); ImageGridAmpOriginal = CorrMaps; ImageGridAmp = zeros(nSources,nTime); for i=1:(nCORR-1) InterpolateTimeWindow = OPTIONS.CORRrange(1)+HalfCorrWindowSize+[(i-1)*OPTIONS.CORRTResolu i*OPTIONS.CORRTResolu]; iInterpolateTime = panel_time('GetTimeIndices', Time, InterpolateTimeWindow); nInterpolateTime = length(iInterpolateTime); ImageGridAmp(:,iInterpolateTime(1)) = ImageGridAmpOriginal(:,i); ImageGridAmp(:,iInterpolateTime(end)) = ImageGridAmpOriginal(:,i+1); for j=2:(nInterpolateTime-1) InterpolatePercentage = (j-1)/(nInterpolateTime-1); ImageGridAmp(:,iInterpolateTime(j)) = ImageGridAmpOriginal(:,i+1)*InterpolatePercentage + ImageGridAmpOriginal(:,i)*(1-InterpolatePercentage); end bst_progress('inc',1); end TFMat = db_template('timefreqmat'); % timestring2 = sprintf('(ws:%d%s,tr:%.1f%s)',round(CorrWindowSize*1000),'ms',OPTIONS.CORRTResolu*1000,'ms'); TFMat.Time = Time;%((OPTIONS.CORRrange(1)+HalfCorrWindowSize):OPTIONS.CORRTResolu:(OPTIONS.CORRrange(end)-HalfCorrWindowSize))-(OPTIONS.RefDelayRange(1)+HalfCorrWindowSize); %TFMat.Time = CorrTimeList(:,1); TFMat.TimeBands = {}; TFMat.TF = ImageGridAmp; [mv, mr] = max(max(ImageGridAmp')); [~, mt] = max(max(ImageGridAmp)); sSubject = bst_get('Subject', 0); sMRI = load(file_fullpath(sSubject.Anatomy.FileName)); lc = cs_convert(sMRI, 'scs', 'mni', sHeadModel.GridLoc(mr,:))*1000; disp(['BIPAC> Maximum Peak Location: ' num2str(round(lc)) ]); disp(['BIPAC> Maximum Peak Value: ' num2str(mv) ]); disp(['BIPAC> Maximum Peak Time: ' num2str(TFMat.Time(mt)) ]); end % if isFreq % if ~isCrossFreq % TFMat.Method = 'cohere'; % TFMat.Freqs = {'custum',[num2str(OPTIONS.BandBoundsData(1)) ',' num2str(OPTIONS.BandBoundsData(2))],'mean'}; % if BeamformerType == 1 % TFMat.Comment = [result_comment 'DICS: cohere|' timestring 'ms(' num2str(BandBoundsData(1)) '-' num2str(BandBoundsData(2)) 'Hz)' timestring2]; % else % TFMat.Comment = [result_comment 'SILSC: cohere|' timestring 'ms(' num2str(BandBoundsData(1)) '-' num2str(BandBoundsData(2)) 'Hz)' timestring2]; % end % else % TFMat.Method = 'crossfreq coupling'; % TFMat.Freqs = {'custum',[num2str(BandBoundsData(1)) ',' num2str(BandBoundsData(2))],'mean'}; % if BeamformerType == 1 % TFMat.Comment = [result_comment 'DICS: crxfreqcoup|' timestring 'ms(' num2str(BandBoundsData(1)) '-' num2str(BandBoundsData(2)) ',' num2str(BandBoundsRef(1)) '-' num2str(BandBoundsRef(2)) 'Hz)' timestring2]; % else % TFMat.Comment = [result_comment 'SILSC: crxfreqcoup|' timestring 'ms(' num2str(BandBoundsData(1)) '-' num2str(BandBoundsData(2)) ',' num2str(BandBoundsRef(1)) '-' num2str(BandBoundsRef(2)) 'Hz)' timestring2]; % end % end % else % % TFMat.Freqs = 0; % end TFMat.OPTIONS = OPTIONS; TFMat.Method = 'corr'; TFMat.TFMethod = OPTIONS.TFmethod; TFMat.Comment = [result_comment OPTIONS.method ': ' upper(OPTIONS.measure) '(' timestring 'ms)']; % TFMat.TF = CorrMaps; TFMat.DataFile = []; TFMat.DataType = 'results'; TFMat.Measure = 'other'; TFMat.RefRowNames = RowName; TFMat.RowNames = 1:nSources; % Leave it empty if using ImagingKernel TFMat.nAvg = length(InputsData); if strcmp(sHeadModel.HeadModelType,'volume') TFMat.GridLoc = sHeadModel.GridLoc; TFMat.SurfaceFile = sHeadModel.SurfaceFile; else TFMat.SurfaceFile = sHeadModel.SurfaceFile; end % TFMat.OPTIONS.EstimatedOri = Ori'; TFMat.OPTIONS.SpatialFilterFileName = Outs; TFMat.HeadModelFile = HeadModelFile; TFMat.HeadModelType = sHeadModel.HeadModelType; % === NOT SHARED === % Get the output study (pick the one from the first file) [StudyContent,iStudy]=bst_get('StudyWithCondition',fileparts(InputsData(1).FileName)); % Create a default output filename OutputFiles{1} = bst_process('GetNewFilename', fileparts(InputsData(1).FileName), 'timefreq_connect1_beam'); % Save on disk bst_save(OutputFiles{1}, TFMat,'v6'); % Register in database db_add_data(iStudy, OutputFiles{1}, TFMat); bst_progress('inc',1); clear TFMat; % == Save the baseline corr if nRand > 1 for i=1:nCORR timestring = sprintf('%d_%d',round(CorrTimeList(i,1)*1000),round(CorrTimeList(i,2)*1000)); TFMat = db_template('timefreqmat'); TFMat.Time = 1:nRand; TFMat.TF = CorrMapsRand(:,:,i); TFMat.OPTIONS = OPTIONS; TFMat.Method = OPTIONS.measure; TFMat.TFMethod = OPTIONS.TFmethod; TFMat.Comment = [result_comment OPTIONS.method ': ' upper(OPTIONS.measure) '(rand, ' timestring 'ms)']; TFMat.DataFile = []; TFMat.DataType = 'results'; TFMat.Measure = 'other'; TFMat.RefRowNames = RowName; TFMat.RowNames = 1:nSources; % Leave it empty if using ImagingKernel TFMat.nAvg = length(InputsData); if strcmp(sHeadModel.HeadModelType,'volume') TFMat.GridLoc = sHeadModel.GridLoc; TFMat.SurfaceFile = sHeadModel.SurfaceFile; else TFMat.SurfaceFile = sHeadModel.SurfaceFile; end % === NOT SHARED === % Get the output study (pick the one from the first file) [StudyContent,iStudy]=bst_get('StudyWithCondition',fileparts(sInputsData(1).FileName)); % Create a default output filename OutputFiles{i+1} = bst_process('GetNewFilename', fileparts(InputsData(1).FileName), 'timefreq_connect1_beam'); % Save on disk bst_save(OutputFiles{i+1}, TFMat,'v6'); % Register in database db_add_data(iStudy, OutputFiles{i+1}, TFMat); bst_progress('inc',1); clear TFMat end end % == Save the contrast timestring = sprintf('%d_%d',round(OPTIONS.CORRrange(1)*1000),round(OPTIONS.CORRrange(2)*1000)); if nCORR == 1 % CORRRangePoints = panel_time('GetTimeIndices', Time, CORRrange); % bst_progress('start', 'Applying process: SISSC', 'Interpolating correlation dynamics...', 0, length(CORRRangePoints)); % ImageGridAmp = zeros(nSources,nTime); % % for i = CORRRangePoints(1):CORRRangePoints(end) % ImageGridAmp(:,i) = CorrMaps(:,1); % bst_progress('inc',1); % end % ===== SAVE THE RESULTS ===== bst_progress('start', ['Applying process: ' OPTIONS.method], 'Saving results...', 0, 2); TFMat = db_template('timefreqmat'); % timestring2 = sprintf('(ws:%d%s)',round(CorrWindowSize*1000),'ms'); TFMat.Time = [OPTIONS.CORRrange(1), OPTIONS.CORRrange(end)]; %TFMat.TimeBands = {'corr',[num2str(CORRrange(1)) ',' num2str(CORRrange(end))], 'mean'}; % Leave it empty if using ImagingKernel TFMat.TF = AmpMaps; else % Interpolate the correlation maps to have the same temporal resolution as the data bst_progress('inc',1); % Create a new data file structure bst_progress('start', ['Applying process: ' OPTIONS.method], 'Saving results...', 0, 2); ImageGridAmpOriginal = AmpMaps; ImageGridAmp = zeros(nSources,nTime); for i=1:(nCORR-1) InterpolateTimeWindow = OPTIONS.CORRrange(1)+HalfCorrWindowSize+[(i-1)*OPTIONS.CORRTResolu i*OPTIONS.CORRTResolu]; iInterpolateTime = panel_time('GetTimeIndices', Time, InterpolateTimeWindow); nInterpolateTime = length(iInterpolateTime); ImageGridAmp(:,iInterpolateTime(1)) = ImageGridAmpOriginal(:,i); ImageGridAmp(:,iInterpolateTime(end)) = ImageGridAmpOriginal(:,i+1); for j=2:(nInterpolateTime-1) InterpolatePercentage = (j-1)/(nInterpolateTime-1); ImageGridAmp(:,iInterpolateTime(j)) = ImageGridAmpOriginal(:,i+1)*InterpolatePercentage + ImageGridAmpOriginal(:,i)*(1-InterpolatePercentage); end bst_progress('inc',1); end TFMat = db_template('timefreqmat'); % timestring2 = sprintf('(ws:%d%s,tr:%.1f%s)',round(CorrWindowSize*1000),'ms',OPTIONS.CORRTResolu*1000,'ms'); TFMat.Time = Time;%((OPTIONS.CORRrange(1)+HalfCorrWindowSize):OPTIONS.CORRTResolu:(OPTIONS.CORRrange(end)-HalfCorrWindowSize))-(OPTIONS.RefDelayRange(1)+HalfCorrWindowSize); TFMat.TimeBands = {}; TFMat.TF = ImageGridAmp; end %TFMat.TF = AmpMaps; TFMat.OPTIONS = OPTIONS; TFMat.Method = OPTIONS.measure; TFMat.TFMethod = OPTIONS.TFmethod; TFMat.Comment = [result_comment OPTIONS.method ': Fmap(' timestring 'ms)']; TFMat.DataFile = []; TFMat.DataType = 'results'; TFMat.Measure = 'other'; TFMat.RefRowNames = RowName; TFMat.RowNames = 1:nSources; % Leave it empty if using ImagingKernel TFMat.nAvg = length(InputsData); if strcmp(sHeadModel.HeadModelType,'volume') TFMat.GridLoc = sHeadModel.GridLoc; TFMat.SurfaceFile = sHeadModel.SurfaceFile; else TFMat.SurfaceFile = sHeadModel.SurfaceFile; end TFMat.HeadModelFile = HeadModelFile; TFMat.HeadModelType = sHeadModel.HeadModelType; % === NOT SHARED === % Get the output study (pick the one from the first file) nOutputFiles = length(OutputFiles); % Create a default output filename OutputFiles{nOutputFiles+1} = bst_process('GetNewFilename', fileparts(InputsData(1).FileName), 'timefreq_connect1_beam'); % Save on disk bst_save(OutputFiles{nOutputFiles+1}, TFMat,'v6'); % Register in database db_add_data(iStudy, OutputFiles{nOutputFiles+1}, TFMat); bst_progress('inc',1); clear TFMat; %=== save weight=== if nDelay > 1 cwcomment = 'weight'; for cw = 1:2 if cw==2 CorrWeight = CorrWeight2; cwcomment = 'normalizedweight'; end CorrWeight = permute(CorrWeight,[1 3 2 4]); nOutputFiles = length(OutputFiles); for k = 1:nCORR%nDelay timestring = sprintf('%d_%d',round(CorrTimeList(k,1)*1000),round(CorrTimeList(k,2)*1000)); SingleCorrWeight = CorrWeight(:,:,k,1); % TFMat.Time = DelayList; %timestring = sprintf('%d_%d',round(OPTIONS.CORRrange(1)*1000),round(OPTIONS.CORRrange(2)*1000)); % if nDelay == 1 % ===== SAVE THE RESULTS ===== bst_progress('start', ['Applying process: ' OPTIONS.method ], 'Saving results...', 0, 2); TFMat = db_template('timefreqmat'); % timestring2 = sprintf('(ws:%d%s)',round(CorrWindowSize*1000),'ms'); % TFMat.Time = [OPTIONS.CORRrange(1), OPTIONS.CORRrange(end)]; %TFMat.TimeBands = {'corr',[num2str(CORRrange(1)) ',' num2str(CORRrange(end))], 'mean'}; % Leave it empty if using ImagingKernel % else % Interpolate the correlation maps to have the same temporal resolution as the data % bst_progress('start', ['Applying process: ' OPTIONS.method ], 'Interpolating correlation dynamics...', 0, nCORR+1); % bst_progress('inc',1); % % Create a new data file structure % bst_progress('start', ['Applying process: ' OPTIONS.method ], 'Saving weights...', 0, 2); % % TFMat = db_template('timefreqmat'); % % timestring2 = sprintf('(ws:%d%s,tr:%.1f%s)',round(CorrWindowSize*1000),'ms',CORRTResolu*1000,'ms'); % % TFMat.Time = (OPTIONS.CORRrange(1)+HalfCorrWindowSize):CORRTResolu:(OPTIONS.CORRrange(end)-HalfCorrWindowSize); % end TFMat.Time = DelayList; if strcmp(OPTIONS.measure,'cfc') || strcmp(OPTIONS.measure,'coh') % TFMat.Freqs = 1:nDelay TFMat.Comment = [result_comment OPTIONS.method ':' cwcomment ' (' timestring 'ms,' num2str(BandBounds(1)) '-' num2str(BandBounds(2)) 'Hz)' ]; else TFMat.Comment = [result_comment OPTIONS.method ':' cwcomment ' (' timestring 'ms)' ]; end TFMat.TF = SingleCorrWeight; TFMat.DataFile = []; TFMat.Method = 'corr'; TFMat.DataType = 'results'; TFMat.Measure = 'other'; TFMat.RefRowNames = RowName; TFMat.RowNames = 1:nSources; % Leave it empty if using ImagingKernel TFMat.nAvg = length(InputsData); if strcmp(sHeadModel.HeadModelType,'volume') TFMat.GridLoc = sHeadModel.GridLoc; else TFMat.SurfaceFile = sHeadModel.SurfaceFile; end % === NOT SHARED === % Get the output study (pick the one from the first file) [StudyContent,iStudy]=bst_get('StudyWithCondition',fileparts(InputsData(1).FileName)); % Create a default output filename OutputFiles{nOutputFiles+k} = bst_process('GetNewFilename', fileparts(InputsData(1).FileName), 'timefreq_connect1_BeamWeight'); % Save on disk bst_save(OutputFiles{nOutputFiles+k}, TFMat,'v6'); % Register in database db_add_data(iStudy, OutputFiles{nOutputFiles+k}, TFMat); bst_progress('inc',1); clear TFMat end end end bst_progress('stop'); end %% ===== TRUNCATED PSEUDO-INVERSE ===== function X = pInv(A,Reg) % Inverse of 3x3 GCG' in unconstrained beamformers. % Since most head models have rank 2 at each vertex, we cut all the fat and % just take a rank 2 inverse of all the 3x3 matrices % [U,S,V] = svd(A); % Si = diag(1 ./ (S + S(1) * Reg / 100)); % 1/(S^2 + lambda I) % X = V*diag(Si)*U'; eigValues = eig(A); Reg_alpha = Reg / 100 * max(eigValues); X = inv(A+Reg_alpha*eye(size(A,1))); end function TF = hilberData(F,BandBounds) % Band-pass filter in one frequency band Fband = process_bandpass('Compute', F, Fs, BandBounds(1), BandBounds(2), [], 1); % Apply Hilbert transform TF = abs(hilbert(Fband')'); end function [spectra,freq,spectraX] = crossSpectrum(X, Y, Fs, segmentLengthTime, MaxFreqRes, WinOverlap) % Default options if (nargin < 5) || isempty(MaxFreqRes) MaxFreqRes = 1; end if (nargin < 4) || isempty(segmentLengthTime) segmentLengthTime = 128; end segmentLength = floor(segmentLengthTime * Fs); overlap = floor(WinOverlap * segmentLength); % Signal properties nX = size(X, 1); nY = size(Y, 1); nTimes = size(X, 2); % Segment indices - discard final timepoints overlapLength = floor(overlap * segmentLength); nSegments = floor((nTimes-overlapLength) / (segmentLength-overlapLength)); partialLength = segmentLength - overlapLength; segmentStart = partialLength * (0:(nSegments-1)) + 1; segmentEnd = segmentStart + (segmentLength-1); if (segmentEnd(end) > nTimes) segmentStart(end) = []; segmentEnd(end) = []; end segmentIndices = [segmentStart; segmentEnd]; % Maximum default resolution: 1 Hz if ~isempty(MaxFreqRes) && (nTimes > round(Fs / MaxFreqRes)) nFFT = 2^nextpow2( round(Fs / MaxFreqRes) ); % Use the default for FFT else nFFT = 2^nextpow2( nTimes ); end % Output frequencies freq = Fs/2*linspace(0, 1, nFFT/2 + 1)'; freq(end) = []; % Frequency smoother (represented as time-domain multiplication) smoother = window('parzenwin', segmentLength) .* tukeywin(segmentLength, 0); smoother = smoother / sqrt(sum(smoother.^2)); %% ===== VERSION 1: for loops, full matrix ===== isCalcAuto = isequal(X,Y); % Initialize variables spectra = zeros(nX, nY, length(freq)); % Cross-spectrum if ~isCalcAuto spectraX = zeros(nX, nX, length(freq)); % spectraY = zeros(nY, nY, length(freq)); for iSeg = 1:nSegments % Get time indices for this segment iTime = segmentIndices(1,iSeg):segmentIndices(2,iSeg); % Frequency domain spectrum after smoothing and tapering fourierX = abs(fft(bst_bsxfun(@times, X(:,iTime), smoother'), nFFT, 2)); fourierY = abs(fft(bst_bsxfun(@times, Y(:,iTime), smoother'), nFFT, 2)); % Calculate for each frequency: fourierX * fourierY' for f = 1:length(freq) spectra(:,:,f) = spectra(:,:,f) + fourierX(:,f) * fourierY(:,f)'; spectraX(:,:,f) = spectraX(:,:,f) + fourierX(:,f) * fourierX(:,f)'; % spectraY(:,:,f) = spectraY(:,:,f) + fourierY(:,f) * fourierY(:,f)'; end end spectraX = spectraX / (nSegments * Fs); else for iSeg = 1:nSegments % Get time indices for this segment iTime = segmentIndices(1,iSeg):segmentIndices(2,iSeg); % Frequency domain spectrum after smoothing and tapering fourierX = fft(bst_bsxfun(@times, X(:,iTime), smoother'), nFFT, 2); % Calculate for each frequency: fourierX * fourierY' for f = 1:length(freq) spectra(:,:,f) = spectra(:,:,f) + fourierX(:,f) * fourierX(:,f)'; end end end % Normalize for segments and sampling rate spectra = spectra / (nSegments * Fs); % [NxN]: Auto spectrum for X is contained within cross-spectral estimation % bst_progress('set', round(waitStart + 0.9 * waitMax)); end function [spectra,freq,spectraX] = crossSpectrumCrossFreq(X, Y, Fs, BandBoundsY, segmentLengthTime, MaxFreqRes, WinOverlapLength) % Default options if (nargin < 6) || isempty(MaxFreqRes) MaxFreqRes = 1; end if (nargin < 5) || isempty(segmentLengthTime) segmentLengthTime = 128; end segmentLength = floor(segmentLengthTime * Fs); %overlapLength = floor(WinOverlapLengthTime * Fs); overlap = WinOverlapLength; % Signal properties nX = size(X, 1); nY = size(Y, 1); nTimes = size(X, 2); % Segment indices - discard final timepoints overlapLength = floor(overlap * segmentLength); nSegments = floor((nTimes-overlapLength) / (segmentLength-overlapLength)); partialLength = segmentLength - overlapLength; segmentStart = partialLength * (0:(nSegments-1)) + 1; segmentEnd = segmentStart + (segmentLength-1); if (segmentEnd(end) > nTimes) segmentStart(end) = []; segmentEnd(end) = []; end segmentIndices = [segmentStart; segmentEnd]; % Maximum default resolution: 1 Hz if ~isempty(MaxFreqRes) && (nTimes > round(Fs / MaxFreqRes)) nFFT = 2^nextpow2( round(Fs / MaxFreqRes) ); % Use the default for FFT else nFFT = 2^nextpow2( nTimes ); end % Output frequencies freq = Fs/2*linspace(0, 1, nFFT/2 + 1)'; freq(end) = []; % Frequency smoother (represented as time-domain multiplication) smoother = window('parzenwin', segmentLength) .* tukeywin(segmentLength, 0); smoother = smoother / sqrt(sum(smoother.^2)); %% ===== VERSION 1: for loops, full matrix ===== isCalcAuto = isequal(X,Y); % Initialize variables spectra = zeros(nX, nY, length(freq)); % Cross-spectrum if ~isCalcAuto spectraX = zeros(nX, nX, length(freq)); %spectraY = zeros(nY, nY, length(freq)); for iSeg = 1:nSegments % Get time indices for this segment iTime = segmentIndices(1,iSeg):segmentIndices(2,iSeg); % Frequency domain spectrum after smoothing and tapering fourierX = fft(bst_bsxfun(@times, X(:,iTime), smoother'), nFFT, 2); fourierY = fft(bst_bsxfun(@times, Y(:,iTime), smoother'), nFFT, 2); % Calculate for each frequency: fourierX * fourierY' for f = 1:length(freq) spectraOne = zeros(nX, nY); nF = 0; for f1 = 1:length(freq) if freq(f1) >= BandBoundsY(1) && freq(f1) <= BandBoundsY(2) spectraOne = spectraOne + fourierX(:,f) * fourierY(:,f1)'; nF = nF + 1; end end if nF > 0 spectra(:,:,f) = spectra(:,:,f) + spectraOne / nF; end spectraX(:,:,f) = spectraX(:,:,f) + fourierX(:,f) * fourierX(:,f)'; %spectraY(:,:,f) = spectraY(:,:,f) + fourierY(:,f) * fourierY(:,f)'; end end spectraX = spectraX / (nSegments * Fs); %spectraY = spectraY / (nSegments * Fs); else for iSeg = 1:nSegments % Get time indices for this segment iTime = segmentIndices(1,iSeg):segmentIndices(2,iSeg); % Frequency domain spectrum after smoothing and tapering fourierX = fft(bst_bsxfun(@times, X(:,iTime), smoother'), nFFT, 2); % Calculate for each frequency: fourierX * fourierY' for f = 1:length(freq) spectra(:,:,f) = spectra(:,:,f) + fourierX(:,f) * fourierX(:,f)'; end end end % Normalize for segments and sampling rate spectra = spectra / (nSegments * Fs); % [NxN]: Auto spectrum for X is contained within cross-spectral estimation % bst_progress('set', round(waitStart + 0.9 * waitMax)); end % function TF = amp_vec(F,BandBounds,Fs,width) % lower_bin = BandBounds(1); % upper_bin = BandBounds(2); % N = size(F,1); % TF = []; % for i = 1:N % F1 = ampvec((lower_bin + floor((upper_bin- lower_bin)/2)),F(i,:)', Fs, width); % if isempty(TF) % TF = zeros(N,length(F1)); % end % TF(i,:) = F1'; % end % % % Band-pass filter in one frequency band % % Fband = process_bandpass('Compute', F, BandBounds(1), BandBounds(2), [], 1); % % % Apply Hilbert transform % % TF = abs(hilbert(Fband')'); % end % function TF = bp_vec(F,BandBounds,Fs,width) % lower_bin = BandBounds(1); % upper_bin = BandBounds(2); % N = size(F,1); % TF = []; % for i = 1:N % F1 = bpvec((lower_bin + floor((upper_bin- lower_bin)/2)),F(i,:)', Fs, width); % if isempty(TF) % TF = zeros(N,length(F1)); % end % TF(i,:) = F1'; % end % % % Band-pass filter in one frequency band % % Fband = process_bandpass('Compute', F, BandBounds(1), BandBounds(2), [], 1); % % end % function TF = ph_vec(F,BandBounds,Fs,width) % lower_bin = BandBounds(1); % upper_bin = BandBounds(2); % N = size(F,1); % TF = []; % for i = 1:N % F1 = phasevec((lower_bin + floor((upper_bin- lower_bin)/2)),F(i,:)', Fs, width); % if isempty(TF) % TF = zeros(N,length(F1)); % end % TF(i,:) = F1'; % end % % % Band-pass filter in one frequency band % % Fband = process_bandpass('Compute', F, BandBounds(1), BandBounds(2), [], 1); % % % Apply Hilbert transform % % TF = angle(hilbert(Fband')'); % end function TF = ana_vec(F,BandBounds,Fs,width,SegmentOverlap) lower_bin = BandBounds(1); upper_bin = BandBounds(2); N = size(F,1); TF = []; w = floor(width*Fs*(1/lower_bin)); ow = floor(w*SegmentOverlap); nF = length(lower_bin:upper_bin); for i = 1:N [S,fvec,tvec]=spectrogram([F(i,end:-1:1) F(i,:) F(i,end:-1:1)],w,ow,lower_bin:upper_bin,Fs); ind = (tvec > length(F)/Fs) & (tvec <= 2*length(F)/Fs); S = S(:,ind); if isempty(TF) TF = zeros(sum(ind),length(fvec),N); end TF(:,:,i) = S'; end end function TF = amp_vec(F,BandBounds,Fs,width,TFmethod) lower_bin = BandBounds(1); upper_bin = BandBounds(2); N = size(F,1); T = size(F,2); TF = []; cf = (lower_bin + floor((upper_bin- lower_bin)/2)); w = floor(width*Fs*(1/lower_bin)); for i = 1:N if strcmp(TFmethod,'wavelet') F1 = ampvec(cf, F(i,:)', Fs, width)'; elseif strcmp(TFmethod,'hilbert') % Band-pass filter in one frequency band if lower_bin ~= 0 && upper_bin ~= 0 Fband = process_bandpass('Compute', F(i,:), Fs, lower_bin, upper_bin, [], 1); else Fband = F(i,:); end % Fband = F(i,:); %Fband = Fband(T+(1:T)); % Apply Hilbert transform F1 = abs(hilbert(Fband')'); % F1 = F1(ceil(0.1*T)+(1:floor(0.8*T))-1); elseif strcmp(TFmethod,'stft') [S,fvec,tvec]=spectrogram([F(i,end:-1:1) F(i,:) F(i,end:-1:1)],w,w-1,lower_bin:upper_bin,Fs); ind = (tvec > length(F)/Fs) & (tvec <= 2*length(F)/Fs); F1 = mean(abs(S(:,ind))); end if isempty(TF) TF = zeros(N,length(F1)); end TF(i,:) = F1; end end function TF = bp_vec(F,BandBounds,Fs,width,TFmethod) % N = size(F,1); % T = size(F,2); % TF = []; lower_bin = BandBounds(1); upper_bin = BandBounds(2); Fcell = num2cell(F,2); % if N>1 if lower_bin ==0 && upper_bin==0 TF = F; else TFcell = cellfun(@(x)process_bandpass('Compute', x, Fs, lower_bin, upper_bin, [], 1), Fcell,'UniformOutput',false); TF = cell2mat(TFcell); end % else % for i = 1:N % if strcmp(TFmethod,'wavelet') % F1 = bpvec((lower_bin + floor((upper_bin- lower_bin)/2)),F(i,:)', Fs, width); % % elseif strcmp(TFmethod,'hilbert') || strcmp(TFmethod,'stft') % % F1 = process_bandpass('Compute', F(i,:), Fs, lower_bin, upper_bin, [], 1)'; % % if strcmp(TFmethod,'hilbert') % % F1 = F1(ceil(0.1*T)+(1:floor(0.8*T))-1); % % end % end % if isempty(TF) % TF = zeros(N,length(F1)); % end % TF(i,:) = F1'; % % end % end end % function TF = bp_vec(F,BandBounds,Fs,width,TFmethod) % N = size(F,1); % T = size(F,2); % TF = []; % lower_bin = BandBounds(1); % upper_bin = BandBounds(2); % % for i = 1:N % if strcmp(TFmethod,'wavelet') % F1 = bpvec((lower_bin + floor((upper_bin- lower_bin)/2)),F(i,:)', Fs, width); % % elseif strcmp(TFmethod,'hilbert') || strcmp(TFmethod,'stft') % F1 = process_bandpass('Compute', F(i,:), Fs, lower_bin, upper_bin, [], 1)'; % % if strcmp(TFmethod,'hilbert') % % F1 = F1(ceil(0.1*T)+(1:floor(0.8*T))-1); % % end % end % if isempty(TF) % TF = zeros(N,length(F1)); % end % TF(i,:) = F1'; % % end % % end function TF = ph_vec(F,BandBounds,Fs,width,TFmethod) lower_bin = BandBounds(1); upper_bin = BandBounds(2); N = size(F,1); T = size(F,2); TF = []; cf = (lower_bin + floor((upper_bin- lower_bin)/2)); w = floor(width*Fs*(1/lower_bin)); for i = 1:N if strcmp(TFmethod,'wavelet') F1 = phasevec(cf, F(i,:)', Fs, width)'; elseif strcmp(TFmethod,'hilbert') % Band-pass filter in one frequency band Fband = process_bandpass('Compute', F(i,:), Fs, lower_bin, upper_bin, [], 1); % Apply Hilbert transform F1 = angle(hilbert(Fband')'); % F1 = F1(ceil(0.1*T)+(1:floor(0.8*T))-1); elseif strcmp(TFmethod,'stft') [S,fvec,tvec]=spectrogram([F(i,end:-1:1) F(i,:) F(i,end:-1:1)],w,w-1,lower_bin:upper_bin,Fs); ind = (tvec > length(F)/Fs) & (tvec <= 2*length(F)/Fs); F1 = mean(angle(S(:,ind))); end if isempty(TF) TF = zeros(N,length(F1)); end TF(i,:) = F1; end end
github
Hui-Ling/BeamformerSourceImaging-master
process_beamformer_mcb_speedup.m
.m
BeamformerSourceImaging-master/process_beamformer_mcb_speedup.m
39,513
utf_8
9ce8310d95f5258ce3de7e5363f7b2ce
function varargout = process_beamformer_mcb_speedup( varargin ) % PROCESS_BEAMFORMER_MCB (2017.01.16): % USAGE: sInput = process_beamformer_mcb_speedup('GetDescription') % sOutput = process_beamformer_mcb_speedup('Run', sProcess, sInput, method=[]) % INPUT: % - Options % |- result_comm : The comment of output files % |- oriconstraint: If 1, unconstrained beamformer, if 0 uses normal to cortex as dipole orientation % |- minvar_range : [tStart, tStop]; range of time values used to compute minimum variance criteria % |- fmaps_range : [tStart, tStop]; range of time values used to compute f maps % |- fmap_size: length of sliding window for computing fmap % |- fmaps_tresolution : Step between each fmap % |- reg : regularization parameter % |- sensortypes: MEG, EEG, MEG GRAD, MEG MAG % |- savefilter : If 1, saves the result spatial filter, if 0 only saves f maps % @============================================================================= % This software is part of the Brainstorm software: % http://neuroimage.usc.edu/brainstorm % % Copyright (c)2000-2014 University of Southern California & McGill University % This software is distributed under the terms of the GNU General Public License % as published by the Free Software Foundation. Further details on the GPL % license can be found at http://www.gnu.org/copyleft/gpl.html. % % FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE % UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY % WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY % LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE. % % For more information type "brainstorm license" at command prompt. % =============================================================================@ % Authors: Hui-Ling Chan, Francois Tadel, Sylvain Baillet, 2014-2015 eval(macro_method); %macro_methodcall; end %% ===== GET DESCRIPTION ===== function sProcess = GetDescription() %#ok<DEFNU> % Description the process sProcess.Comment = 'Beamformer: Maximum Contrast (speedup)'; sProcess.FileTag = ''; sProcess.Category = 'Custom'; sProcess.SubGroup = 'Sources'; sProcess.Index = 330; % Definition of the input accepted by this process sProcess.InputTypes = {'data'}; sProcess.OutputTypes = {'results'}; sProcess.nInputs = 1; sProcess.nMinFiles = 1; sProcess.isSeparator = 1; % Definition of the options sProcess.options.result_comm.Comment = 'Comment: '; sProcess.options.result_comm.Type = 'text'; sProcess.options.result_comm.Value = ''; % === SENSOR TYPES sProcess.options.sensortypes.Comment = 'Sensor types or names (empty=all): '; sProcess.options.sensortypes.Type = 'text'; sProcess.options.sensortypes.Value = 'MEG GRAD'; % === CORTICAL CONSTRAINED ORIENTATION sProcess.options.label_o.Comment = '<HTML><BR><b><u>Options: Dipole orietation</u></b>'; sProcess.options.label_o.Type = 'label'; sProcess.options.oriconstraint.Comment = {'Unconstrained <FONT color="#777777"><I>(maximum contrast of active/noise) </I></FONT>', 'Constrained <FONT color="#777777"><I>(normal to cortex)</I></FONT>'}; sProcess.options.oriconstraint.Type = 'radio'; sProcess.options.oriconstraint.Value = 1; sProcess.options.ori_range.Comment = 'Time range (only for unconstr): '; sProcess.options.ori_range.Type = 'poststim'; sProcess.options.ori_range.Value = []; % % === BASELINE TIME RANGE % sProcess.options.baseline_time.Comment = 'Baseline (Set [0,0] if no baseline correction): '; % sProcess.options.baseline_time.Type = 'baseline'; % sProcess.options.baseline_time.Value = []; sProcess.options.label_sf.Comment = '<HTML><BR><b><u>Options: Spatial filter</u></b>'; sProcess.options.label_sf.Type = 'label'; % === SPATIAL FILTER TIME RANGE sProcess.options.minvar_range.Comment = 'Time range (for minimum variance): '; sProcess.options.minvar_range.Type = 'poststim'; sProcess.options.minvar_range.Value = []; % === REGULARIZATION sProcess.options.reg.Comment = 'Regularization parameter: '; sProcess.options.reg.Type = 'value'; sProcess.options.reg.Value = {0.3, '%', 4}; % === SAVE SPATIAL FILTER sProcess.options.savefilter.Comment = 'Save spatial filters'; sProcess.options.savefilter.Type = 'checkbox'; sProcess.options.savefilter.Value = 1; sProcess.options.label_f.Comment = '<HTML><BR><b><u>Options: Active state (for f-statistic map)</u></b>'; sProcess.options.label_f.Type = 'label'; % === F-MAP TIME RANGE sProcess.options.fmaps_range.Comment = 'Duration of interests (DOI): '; sProcess.options.fmaps_range.Type = 'poststim'; sProcess.options.fmaps_range.Value = []; % === F-MAP TIME WINDOW SIZE sProcess.options.fmap_size.Comment = 'Size of sliding window (0=whole DOI): '; sProcess.options.fmap_size.Type = 'value'; sProcess.options.fmap_size.Value = {0, 'ms', 1}; % === F-MAP TEMPORAL RESOLUTION sProcess.options.fmaps_tresolution.Comment = 'Step for sliding window: '; sProcess.options.fmaps_tresolution.Type = 'value'; sProcess.options.fmaps_tresolution.Value = {0, 'ms', 1}; sProcess.options.label_s.Comment = '<HTML><BR><b><u>Options: Scouts</u></b>'; sProcess.options.label_s.Type = 'label'; % === OPTIONS: COMPUTE IN SELECT SCOUTS sProcess.options.usescouts.Comment = 'Compute sources in scouts (uncheck=whole brain)'; sProcess.options.usescouts.Type = 'checkbox'; sProcess.options.usescouts.Value = 0; % === OPTIONS: SELECTED SCOUTS sProcess.options.scouts.Comment = 'Use scouts (no selection=all):'; sProcess.options.scouts.Type = 'scout'; sProcess.options.scouts.Value = []; end %% ===== FORMAT COMMENT ===== function Comment = FormatComment(sProcess) %#ok<DEFNU> Comment = sProcess.Comment; end %% ===== RUN ===== function OutputFiles = Run(sProcess, sInputs) %#ok<DEFNU> % Initialize returned list of files OutputFiles = {}; % Selected scouts sScouts = sProcess.options.scouts.Value; % Get option values BaselineTime = [0,0];%sProcess.options.baseline_time.Value{1}; FmapRange = sProcess.options.fmaps_range.Value{1}; Reg = sProcess.options.reg.Value{1}; SensorTypes = sProcess.options.sensortypes.Value; FmapSize = sProcess.options.fmap_size.Value{1}; FmapTResolu = sProcess.options.fmaps_tresolution.Value{1}; isSaveFilter = sProcess.options.savefilter.Value; %SFcriteriaType = sProcess.options.sfcriteria.Value; MinVarRange = sProcess.options.minvar_range.Value{1}; OriRange = sProcess.options.ori_range.Value{1}; isScout = sProcess.options.usescouts.Value; result_comment = sProcess.options.result_comm.Value; if ~isempty(result_comment) result_comment = [result_comment]; end % ===== LOAD THE DATA ===== % Read the first file in the list, to initialize the loop DataMat = in_bst(sInputs(1).FileName, [], 0); nChannels = size(DataMat.F,1); nTime = size(DataMat.F,2); Time = DataMat.Time; % ===== PROCESS THE TIME WINDOWS ===== if FmapRange(1) > FmapRange(2) bst_report('Error', sProcess, sInputs, 'The setting of time range of active state is incorrect.'); end if FmapRange(1) < Time(1) bst_report('Warning', sProcess, sInputs, 'The start for time range of active state is reset to the first time point of data'); FmapRange(1) = Time(1); end if FmapRange(2) > Time(end) bst_report('Warning', sProcess, sInputs, 'The end for time range of active state is reset to the end point of data'); FmapRange(2) = Time(end); end if (FmapRange(1)+FmapSize) > FmapRange(2) bst_report('Warning', sProcess, sInputs, 'The F statistic window size is too large and reset to the same as the time range of active state.'); FmapSize = FmapRange(2) - FmapRange(1); end MinVarTime = MinVarRange; ActiveTime = OriRange; %MinVarPoints = panel_time('GetTimeIndices', Time, MinVarRange); if FmapTResolu == 0 nFmaps = 1; FmapTResolu = 1; FmapSize = FmapRange(2) - FmapRange(1); if FmapRange(1)+FmapSize ~= FmapRange(2) bst_report('Warning', sProcess, sInputs, 'Temporal resolution should not be 0 ms. The F statistic window size is reset to the same as the time range of interest.'); end end FmapPoints = panel_time('GetTimeIndices', Time, [FmapRange(1)+FmapSize FmapRange(2)]); if length(FmapPoints)<=1 nFmaps = 1; else nFmaps = length((FmapRange(1)+FmapSize):FmapTResolu:FmapRange(2)); end HalfFmapSize= FmapSize/2; FmapTimeList= zeros(nFmaps,2); for i=1:nFmaps FmapTimeList(i,:) = FmapRange(1) + FmapTResolu*(i-1) + [0 FmapSize] ; end % ===== LOAD CHANNEL FILE ===== % Load channel file ChannelMat = in_bst_channel(sInputs(1).ChannelFile); % Find the MEG channels % iMEG = good_channel(ChannelMat.Channel, [], 'MEG'); % iEEG = good_channel(ChannelMat.Channel, [], 'EEG'); % iSEEG = good_channel(ChannelMat.Channel, [], 'SEEG'); % iECOG = good_channel(ChannelMat.Channel, [], 'ECOG'); iChannels = channel_find(ChannelMat.Channel, SensorTypes); % ===== LOAD HEAD MODEL ===== % Get channel study [sChannelStudy, iChannelStudy] = bst_get('ChannelFile', sInputs(1).ChannelFile); % Load the default head model HeadModelFile = sChannelStudy.HeadModel(sChannelStudy.iHeadModel).FileName; sHeadModel = load(file_fullpath(HeadModelFile)); % Get number of sources nSources = size(sHeadModel.GridLoc,1); if (sProcess.options.oriconstraint.Value == 2) && (isequal(sHeadModel.HeadModelType,'volume') || isempty(sHeadModel.GridOrient)) bst_report('Error', sProcess, sInputs, 'No dipole orientation for cortical constrained beamformer estimation.'); % Stop the process return; end % ===== LOAD SCOUTS ===== if isempty(sScouts) || (isScout==0) %isequal(sHeadModel.HeadModelType,'volume') || isScout = 0; nScoutVertex = nSources; sScoutVerticesList = 1:nSources; else isScout = 1; end if isScout sScoutsInfo = process_extract_scout('GetScoutsInfo', '@ Beamformer:MCB', [], sHeadModel.SurfaceFile, sScouts); sScoutVerticesList = unique([sScoutsInfo.Vertices]); nScoutVertex = length(sScoutVerticesList); if isequal(sHeadModel.HeadModelType,'volume') % sSurface = load(file_fullpath(sHeadModel.SurfaceFile)); % vSurf = sSurface.Vertices(sScoutVerticesList,:); newScoutVerticesList = []; for ns = 1:nScoutVertex SCS = sHeadModel.GridLoc(sScoutVerticesList(ns),:); dist = (sHeadModel.GridLoc(:,1) - SCS(1)) .^ 2 + (sHeadModel.GridLoc(:,2) - SCS(2)) .^ 2 + (sHeadModel.GridLoc(:,3) - SCS(3)) .^ 2; iVertex = find(sqrt(dist) < 0.01); % [~, iVertex] = min(dist); newScoutVerticesList = [newScoutVerticesList iVertex]; % sScoutVerticesList(ns) = iVertex; end sScoutVerticesList = unique(newScoutVerticesList); nScoutVertex = length(sScoutVerticesList); % iAtlas = find(arrayfun(@(x)strcmp(x.Name(1:6),'Volume'),sSurface.Atlas)); % for ns = 1:length(sScoutsInfo) % iScouts(ns) = find(arrayfun(@(x)strcmp(x.Label, sScoutsInfo(ns).Label),sSurface.Atlas(iAtlas).Scouts)); % end % GridAtlas = sSurface.Atlas(iAtlas); % GridAtlas.Scouts = GridAtlas.Scouts(unique(iScouts)); % % GridAtlas.Vert2Grid = cellfun(@(x)min_dist_index(x,sHeadModel.GridLoc),mat2cell(sSurface.Vertices,ones(size(sSurface.Vertices,1),1), 3)); % GridAtlas.Grid2Source = 1:nSources; % for ns = 1:length(GridAtlas.Scouts) % GridAtlas.Scouts(ns).Region(2) ='V'; % GridAtlas.Scouts(ns).Region(3) ='C'; % GridAtlas.Scouts(ns).GridRows = GridAtlas.Vert2Grid(GridAtlas.Scouts(ns).Seed); % end % % Remove the vertices that are outside the list of vertices in Vert2Grid % iVertices(iVertices > size(GridAtlas.Vert2Grid,2)) = []; % % Surface.Vertices => Results.GridLoc % iVertices = find(any(GridAtlas.Vert2Grid(:,iVertices), 2))'; % % % Get indices in the ImageGridAmp/ImagingKernel matrix % iSourceRows = find(any(GridAtlas.Grid2Source(:,iVertices), 2))'; % % Find over which regions this vertex selection spans % if (nargout >= 2) % iRegionScouts = find(~cellfun(@(c)isempty(intersect(c,iVertices)), {GridAtlas.Scouts.GridRows})); % end end end % ===== LOAD THE DATA ===== % Find the indices for covariance calculation iMinVarTime = panel_time('GetTimeIndices', Time, MinVarRange); iActiveTime = panel_time('GetTimeIndices', Time, OriRange); if BaselineTime(1)==BaselineTime(2) iBaselineTime = []; else iBaselineTime = panel_time('GetTimeIndices', Time, BaselineTime); end % Initialize the covariance matrices ActiveCov = zeros(nChannels, nChannels); nTotalActive = zeros(nChannels, nChannels); MinVarCov = zeros(nChannels, nChannels); nTotalMinVar = zeros(nChannels, nChannels); nFmapPoints = length(panel_time('GetTimeIndices', Time, FmapTimeList(1,:))); iFmapTime = zeros(nFmaps, nFmapPoints); for i = 1:nFmaps if FmapTimeList(i,1) < Time(1) || FmapTimeList(i,2) > Time(end) % Add an error message to the report bst_report('Error', sProcess, sInputs, 'One fmap time window is not within the data time range.'); % Stop the process return; end single_iFmap = panel_time('GetTimeIndices', Time, FmapTimeList(i,:)); % detect the round error caused by the non-interger sampling rate % -- added in 20141026 if nFmapPoints - length(single_iFmap) == 1 single_iFmap(nFmapPoints) = single_iFmap(end) + 1; end %%%%%%%% iFmapTime(i,:) = single_iFmap(1:nFmapPoints); end % Initialize the covariance matrices FmapActiveCov = zeros(nChannels, nChannels, nFmaps); nTotalFmapActive = zeros(nChannels, nChannels, nFmaps); bst_progress('start', 'Applying process: MCB', 'Calulating covariance matrix...', 0, length(sInputs)*nFmaps*4+2); AllData = []; % Reading all the input files in a big matrix for i = 1:length(sInputs) % Read the file #i DataMat = in_bst(sInputs(i).FileName, [], 0); % Check the dimensions of the recordings matrix in this file if (size(DataMat.F,1) ~= nChannels) || (size(DataMat.F,2) ~= nTime) % Add an error message to the report bst_report('Error', sProcess, sInputs, 'One file has a different number of channels or a different number of time samples.'); % Stop the process return; end % Get good channels iGoodChan = find(DataMat.ChannelFlag == 1); if ~isempty(iBaselineTime) % Average baseline values FavgActive = mean(DataMat.F(iGoodChan,iBaselineTime), 2); % Remove average DataActive = bst_bsxfun(@minus, DataMat.F(iGoodChan,iActiveTime), FavgActive); else DataActive = DataMat.F(iGoodChan,iActiveTime); end % Compute covariance for this file fileActiveCov = DataMat.nAvg .* (DataActive * DataActive'); % Add file covariance to accumulator ActiveCov(iGoodChan,iGoodChan) = ActiveCov(iGoodChan,iGoodChan) + fileActiveCov; nTotalActive(iGoodChan,iGoodChan) = nTotalActive(iGoodChan,iGoodChan) + length(iActiveTime); if ~isempty(iBaselineTime) % Remove average DataMinVar = bst_bsxfun(@minus, DataMat.F(iGoodChan,iMinVarTime), FavgActive); else DataMinVar = DataMat.F(iGoodChan,iMinVarTime); end % Compute covariance for this file fileMinVarCov = DataMat.nAvg .* (DataMinVar * DataMinVar'); % Add file covariance to accumulator MinVarCov(iGoodChan,iGoodChan) = MinVarCov(iGoodChan,iGoodChan) + fileMinVarCov; nTotalMinVar(iGoodChan,iGoodChan) = nTotalMinVar(iGoodChan,iGoodChan) + length(iMinVarTime); for j = 1:nFmaps % Average baseline values if isempty(iBaselineTime) FavgFmapActive = 0; else FavgFmapActive = mean(DataMat.F(iGoodChan,iBaselineTime), 2); end % Remove average DataFmapActive = bst_bsxfun(@minus, DataMat.F(iGoodChan,iFmapTime(j,:)), FavgFmapActive); %DataFmapActive = sym(DataFmapActive); %DataMatnAvgSym = sym(DataMat.nAvg); bst_progress('inc',1); % Compute covariance for this file fileFmapActiveCov = DataMat.nAvg .* (DataFmapActive * DataFmapActive'); bst_progress('inc',1); % Add file covariance to accumulator FmapActiveCov(iGoodChan,iGoodChan,j) = FmapActiveCov(iGoodChan,iGoodChan,j) + fileFmapActiveCov; %FmapActiveCov(iGoodChan,iGoodChan,j) = FmapActiveCov(iGoodChan,iGoodChan,j) + fileFmapActiveCov; bst_progress('inc',1); nTotalFmapActive(iGoodChan,iGoodChan,j) = nTotalFmapActive(iGoodChan,iGoodChan,j) + nFmapPoints; bst_progress('inc',1); end if isempty(AllData) AllData = zeros(nChannels, length(DataMat.Time), length(sInputs)); end AllData(:,:,i)=DataMat.F; end clear DataMat; % Remove bad channels - Added by Hui-Ling 20170113 - start iUnusedChannel = find(nTotalActive(1,:) < 1); if ~isempty(iUnusedChannel) for i=1:length(iUnusedChannel) iChannels(iChannels == iUnusedChannel(i)) = []; end end % Remove bad channels - Added by Hui-Ling 20170113 - end % Remove zeros from N matrix if sProcess.options.oriconstraint.Value == 1, nTotalActive(nTotalActive <= 1) = 2; nTotalMinVar(nTotalMinVar <= 1) = 2; end nTotalFmapActive(nTotalFmapActive <= 1) = 2; bst_progress('inc',1); % Divide final matrix by number of samples if sProcess.options.oriconstraint.Value == 1, ActiveCov = ActiveCov ./ (nTotalActive - 1); MinVarCov = MinVarCov ./ (nTotalMinVar - 1); end FmapActiveCov = FmapActiveCov ./ (nTotalFmapActive - 1); bst_progress('inc',1); bst_progress('stop'); % ===== PROCESS ===== % Number of channels used to compute sources nUsedChannels = length(iChannels); % Extract the covariance matrix of the used channels ActiveCov = ActiveCov(iChannels,iChannels); NoiseCovMat = load(file_fullpath(sChannelStudy.NoiseCov(1).FileName)); if isempty(NoiseCovMat) bst_report('Error', sProcess, sInputs, 'Cannot find noise covariance matrix.'); % Stop the process return; end NoiseCov = NoiseCovMat.NoiseCov(iChannels,iChannels); MinVarCov = MinVarCov(iChannels,iChannels); FmapActiveCov = FmapActiveCov(iChannels,iChannels,:); AllData = AllData(iChannels,:,:); %% Calculate the inverse of (C+alpha*I) % eigValues = eig(MinVarCov); % Reg_alpha = Reg / 100 * max(eigValues); % invMinVarCovI = inv(MinVarCov+Reg_alpha*eye(nUsedChannels)); [U,S,V] = svd(MinVarCov); S = diag(S); % Covariance = Cm = U*S*U' Si = diag(1 ./ (S + S(1) * Reg / 100)); % 1/(S + lambda I) invMinVarCovI = V*Si*U'; % V * 1/(S + lambda I) * U' = Cm^(-1) % Initilize the ImagingKernel (spatial filter) and ImageGridAmp (f value) ImagingKernel = zeros(nSources, nUsedChannels); ImageGridAmp = zeros(nSources, nFmaps); ImagingGridOri = zeros(nSources, 3); % Set the dipole positions for the computation of sources Loc = sHeadModel.GridLoc; % Get forward field if sProcess.options.oriconstraint.Value == 2; % anatomically constrained beamformer Kernel = bst_gain_orient(sHeadModel.Gain(iChannels,:), sHeadModel.GridOrient); % Loc = sHeadModel.GridLoc; else Kernel = sHeadModel.Gain(iChannels,:); % Loc = sHeadModel.GridLoc; end %Kernel(abs(Kernel(:)) < eps) = eps; % Set zero elements to strictly non-zero bst_progress('start', 'Applying process: MCB', 'Calculating spatial filters and f-statistic maps...', 0, 16+nFmaps); %% Compute the spatial filter and f value for each position if sProcess.options.oriconstraint.Value == 1; % Obtain gain matrix usedKernel = arrayfun(@(x)Kernel(:,[1 2 3]+3*(x-1)),sScoutVerticesList,'UniformOutput', false); % Compute A = inv(C+alpha*I)*Lr Amat = cellfun(@(x)invMinVarCovI*x, usedKernel, 'UniformOutput', false); bst_progress('inc',1); % == Compute orientation using maxium constrast criterion == % Compute P = A'*Ca*A Pmat = cellfun(@(x) x'*ActiveCov*x, Amat, 'UniformOutput', false); bst_progress('inc',1); % Compute Q = A'*Cc*A Qmat = cellfun(@(x) x'*NoiseCov*x, Amat, 'UniformOutput', false); bst_progress('inc',1); % Regularize the matrix Q to avoid singular problem invQmat = cellfun(@(x)pInv(x,0.0000000001),Qmat, 'UniformOutput', false); bst_progress('inc',1); invQPmat = cellfun(@mtimes, invQmat, Pmat, 'UniformOutput', false); bst_progress('inc',1); % Compute the dipole orientation % (the eigenvector corresponding to maximum eigenvalue of inv(Q)*P) [eigVecmat, eigValmat] = cellfun(@eig, invQPmat, 'UniformOutput', false); bst_progress('inc',1); % check whether eigValues are saved as matrix or vector if min(size(eigValmat{1,1}))>1 eigValmat = cellfun(@diag, eigValmat, 'UniformOutput', false); end [~, imaxmat] = cellfun(@max, eigValmat, 'UniformOutput', false); bst_progress('inc',1); Orimat = cellfun(@(x,y)x(:,y), eigVecmat, imaxmat, 'UniformOutput', false); bst_progress('inc',1); % Compute B = Lr'*A Bmat = cellfun(@(x,y)x'*y, usedKernel, Amat, 'UniformOutput', false); bst_progress('inc',1); % Compute the spatial filter tmpMat = cellfun(@(x,y)x'*y*x, Orimat, Bmat, 'UniformOutput', false); bst_progress('inc',1); tmpMat2 = cellfun(@mtimes, Amat, Orimat, 'UniformOutput', false); bst_progress('inc',1); sfmat = cellfun(@mrdivide, tmpMat2, tmpMat, 'UniformOutput', false); bst_progress('inc',1); % Compute the source power during control state vcMat = cellfun(@(x)x'*NoiseCov*x, sfmat,'UniformOutput', false); bst_progress('inc',1); for j = 1:nFmaps % Compute the source power during active state vaMat = cellfun(@(x)x'*FmapActiveCov(:,:,j)*x, sfmat,'UniformOutput', false); % Compute the f-statistic value by contrasting the power % during active and control states ImageGridAmp(sScoutVerticesList,j) = cellfun(@rdivide,vaMat,vcMat); bst_progress('inc',1); end % Normalize spatial filter using the amplitude of control state vcMat = cellfun(@sqrt, vcMat, 'UniformOutput', false); bst_progress('inc',1); tmp = cellfun(@mrdivide, sfmat, vcMat, 'UniformOutput', false); bst_progress('inc',1); if size(tmp{1},2) == 1 tmp = cellfun(@(x)x', tmp, 'UniformOutput', false); end if size(tmp,1) == 1 tmp = tmp'; end % Save the normalized spatial filter ImagingKernel(sScoutVerticesList,:) = cell2mat(tmp); ImagingGridOri(sScoutVerticesList,:) = cell2mat(Orimat)'; bst_progress('inc',1); % for iScoutVertex = 1:nScoutVertex % % i = sScoutVerticesList(iScoutVertex); % iGain = [1 2 3] + 3*(i-1); % if Loc(i,1) < 0.01 && Loc(i,1) > -0.01 && Loc(i,2) < 0.01 && Loc(i,2) > -0.01 && Loc(i,3) < 0.01 && Loc(i,3) > -0.01 % bst_progress('inc',2); % % continue; % else % % Compute A = inv(C+alpha*I)*Lr % A = invMinVarCovI * Kernel(:,iGain); % % % Compute B = Lr'*A % B = Kernel(:,iGain)' * A; % % % % == Compute orientation using maxium constrast criterion == % % Compute P = A'*Ca*A % P = A' * ActiveCov * A; % % Compute Q = A'*Cc*A % Q = A' * NoiseCov * A; % % % Regularize the matrix Q to avoid singular problem % [U,S,V] = svd(Q); % S = diag(S); % Covariance = Cm = V*S*U' % Si = diag(1 ./ (S + S(1) * 0.0000000001)); % 1/(S + lambda I) % invQ = V*Si*U'; % V * 1/(S + lambda I) * U' = Cm^(-1) % % % Compute the dipole orientation % % (the eigenvector corresponding to maximum eigenvalue of inv(Q)*P) % [eigVectors,eigValues] = eig(invQ*P); % % check whether eigValues are saved as matrix or vector % if(min(size(eigValues))==1) % [tmp, imax] = max(eigValues); % else % [tmp, imax] = max(diag(eigValues)); % end % DipoleOri = eigVectors(:,imax); % % % Compute the spatial filter % SpatialFilter = (A * DipoleOri) / (DipoleOri' * B * DipoleOri); % % varControl = SpatialFilter'* NoiseCov * SpatialFilter; % bst_progress('inc',1); % % % % for j = 1:nFmaps % % Compute the contrast of source power during active state and control state % varActive = SpatialFilter'*FmapActiveCov(:,:,j)*SpatialFilter; % % varActive = 0; % % for k = 1:length(sInputs) % % varActive = varActive + sum((SpatialFilter' * AllData(:,iFmapTime(j,:),k)).^2); % % end % % varActive = varActive / (length(sInputs)*nFmapPoints); % %varActive = mean((SpatialFilter' * AllData).^2); % ImageGridAmp(i,j) = varActive / varControl; % % bst_progress('inc',1); % end % % Save teh result % ImagingKernel(i,:) = SpatialFilter / sqrt(varControl); % % end % % end else for iScoutVertex = 1:nScoutVertex i = sScoutVerticesList(iScoutVertex); %iGain = [1 2 3] + 3*(i-1); if Loc(i,1) < 0.01 && Loc(i,1) > -0.01 && Loc(i,2) < 0.01 && Loc(i,2) > -0.01 && Loc(i,3) < 0.01 && Loc(i,3) > -0.01 bst_progress('inc',2); continue; end % Compute the spatial filter with cortical constrained dipole orientation % Compute A = inv(C+alpha*I)*Lr A = invMinVarCovI * Kernel(:,i); % Compute B = Lr'*A B = Kernel(:,i)'*A; % Compute the spatial filter SpatialFilter = A / B; % compute the variance of control state varControl = SpatialFilter'* NoiseCov * SpatialFilter; bst_progress('inc',1); for j = 1:nFmaps % Compute the contrast of source power during active state and control state varActive = SpatialFilter'*FmapActiveCov(:,:,j)*SpatialFilter; ImageGridAmp(i,j) = varActive / varControl; %ImageGridAmp(i,j) = Fvalue; bst_progress('inc',1); end % Save teh result ImagingKernel(i,:) = SpatialFilter / sqrt(varControl); end end bst_progress('stop'); bst_progress('start', 'Applying process: MCB', 'Interpolating results...', 0, 1); %bst_progress('text', ['Applying process: ' sProcess.Comment ' [Interpolating results]']); if nFmaps == 1 %%%%%%%%% ADDED BY HUI-LING May 10, 2016 -- start [mv, mr] = max(ImageGridAmp); % sSubject = bst_get('Subject', 0); [~, iSubject] = bst_get('SurfaceFile', sHeadModel.SurfaceFile); sMRI = bst_memory('LoadMri', iSubject); % sMRI = load(file_fullpath(sSubject.Anatomy.FileName)); lc = cs_convert(sMRI, 'scs', 'mni', Loc(mr,:))*1000; disp(['MCB> Maximum Peak Location (MNI coordinates): ' num2str(round(lc)) ]); disp(['MCB> Maximum Peak Value (f-statistic): ' num2str(mv) ]); %%%%%%%%% ADDED BY HUI-LING May 10, 2016 -- end FmapRangePoints = panel_time('GetTimeIndices', Time, FmapRange); ImageGridAmpOriginal = ImageGridAmp; ImageGridAmp = [ImageGridAmpOriginal, ImageGridAmpOriginal]; TimeIndex = [Time(1), Time(end)]; else % Interpolate the f maps to have the same temporal resolution as the data ImageGridAmpOriginal = ImageGridAmp; ImageGridAmp = zeros(nSources,nTime); for i=1:(nFmaps-1) InterpolateTimeWindow = FmapRange(1)+HalfFmapSize+[(i-1)*FmapTResolu i*FmapTResolu]; iInterpolateTime = panel_time('GetTimeIndices', Time, InterpolateTimeWindow); nInterpolateTime = length(iInterpolateTime); ImageGridAmp(:,iInterpolateTime(1)) = ImageGridAmpOriginal(:,i); ImageGridAmp(:,iInterpolateTime(end)) = ImageGridAmpOriginal(:,i+1); for j=2:(nInterpolateTime-1) InterpolatePercentage = (j-1)/(nInterpolateTime-1); ImageGridAmp(:,iInterpolateTime(j)) = ImageGridAmpOriginal(:,i+1)*InterpolatePercentage + ImageGridAmpOriginal(:,i)*(1-InterpolatePercentage); end end %%%%%%%%%%%% % InterpolateTimeWindow = FmapRange(1)+ [0 HalfFmapSize]; % iInterpolateTime = panel_time('GetTimeIndices', Time, InterpolateTimeWindow); % nInterpolateTime = length(iInterpolateTime); % % for j=1:(nInterpolateTime-1) % ImageGridAmp(:,iInterpolateTime(j)) = ImageGridAmpOriginal(:,1); % end % % InterpolateTimeWindow = FmapRange(1)+HalfFmapSize+(nFmaps-1)*FmapTResolu+[0 HalfFmapSize]; % iInterpolateTime = panel_time('GetTimeIndices', Time, InterpolateTimeWindow); % nInterpolateTime = length(iInterpolateTime); % % for j=2:nInterpolateTime % ImageGridAmp(:,iInterpolateTime(j)) = ImageGridAmpOriginal(:,end); % end % [mv, mr] = max(max(ImageGridAmp')); [~, mt] = max(max(ImageGridAmp)); sSubject = bst_get('Subject', 0); sMRI = load(file_fullpath(sSubject.Anatomy.FileName)); lc = cs_convert(sMRI, 'scs', 'mni', Loc(mr,:)*1000); disp(['MCB> Maximum Peak Location (MNI coordinates): ' num2str(round(lc)) ]); disp(['MCB> Maximum Peak Value (f-statistic): ' num2str(mv) ]); disp(['MCB> Maximum Peak Time: ' num2str(Time(mt)) ' seconds']); TimeIndex = Time; end bst_progress('inc',1); bst_progress('stop'); %bst_progress('text', ['Applying process: ' sProcess.Comment ' [Saving results]']); % ===== SAVE THE RESULTS ===== % Create a new data file structure ResultsMat = db_template('resultsmat'); ResultsMat.ImagingKernel = []; ResultsMat.ImageGridAmp = ImageGridAmp; % ResultsMat.nComponents = 1; % 1 or 3 if strcmp(sHeadModel.HeadModelType,'volume') ResultsMat.nComponents = 1; else ResultsMat.nComponents = 1; % 1 or 3 end % Comment Comment = []; if ~isempty(result_comment) Comment = [result_comment ': ']; end if ~isempty(iBaselineTime) strContrastType = 'bl'; else strContrastType = 'no bl'; end if sProcess.options.oriconstraint.Value == 1; ostr = 'Unconstr'; else ostr = 'Constr'; end if FmapRange(1) > 5 || FmapRange(2) > 5 || FmapSize > 5 timescale = 1; strTimeUnit = 's'; else timescale = 1000; strTimeUnit = 'ms'; end if (nFmaps == 1) Comment1 = sprintf('%sMCB/fmap (%s, %s, %d-%d%s)', Comment, ostr, strContrastType, round(FmapRange(1)*timescale), round(FmapRange(2)*timescale),strTimeUnit); else Comment1 = sprintf('%sMCB/fmap (%s, %s , %d-%d%s, ws:%d%s, tr:%d%s)', Comment, ostr, strContrastType, round((FmapRange(1)+FmapSize/2)*timescale), ... round((FmapRange(1) + FmapSize/2 + (nFmaps-1)*FmapTResolu)*timescale), strTimeUnit, round(FmapSize*timescale), strTimeUnit, round(FmapTResolu*timescale),strTimeUnit); end ResultsMat.Function = 'MaximumContrastBeamformerResult'; ResultsMat.Comment = Comment1; ResultsMat.Time = TimeIndex; % Leave it empty if using ImagingKernel ResultsMat.DataFile = []; ResultsMat.HeadModelFile = HeadModelFile; ResultsMat.HeadModelType = sHeadModel.HeadModelType; ResultsMat.ChannelFlag = []; ResultsMat.GoodChannel = iChannels; ResultsMat.SurfaceFile = sHeadModel.SurfaceFile; if strcmp(sHeadModel.HeadModelType,'volume') ResultsMat.GridLoc = Loc; % ResultsMat.GridAtlas = GridAtlas; end % === NOT SHARED === % Get the output study (pick the one from the first file) iStudy = sInputs(1).iStudy; % Create a default output filename OutputFiles{1} = bst_process('GetNewFilename', fileparts(sInputs(1).FileName), 'results_MCB_amp'); % Save on disk save(OutputFiles{1}, '-struct', 'ResultsMat'); % Register in database db_add_data(iStudy, OutputFiles{1}, ResultsMat); % ===== SPATIAL FILTER: SAVE FILE ===== if isSaveFilter % == Save the spatial filter as ImagingKernel == % Create a new data file structure ResultsMat2 = db_template('resultsmat'); ResultsMat2.ImagingKernel = ImagingKernel; ResultsMat2.ImageGridAmp = []; if strcmp(sHeadModel.HeadModelType,'volume') ResultsMat2.nComponents = 1; else ResultsMat2.nComponents = 1; % 1 or 3 end timestring = sprintf('%d_%d%s',round(ActiveTime(1)*timescale),round(ActiveTime(2)*timescale),strTimeUnit); if ~isempty(iBaselineTime) ResultsMat2.Comment = [Comment 'MCB/filter (' ostr ', bl, ' timestring ')']; else ResultsMat2.Comment = [Comment 'MCB/filter (' ostr ', no bl, ' timestring ')']; end ResultsMat2.Function = 'MaximumContrastBeamformerFilter'; ResultsMat2.Time = []; % Leave it empty if using ImagingKernel ResultsMat2.DataFile = []; ResultsMat2.HeadModelFile = HeadModelFile; ResultsMat2.HeadModelType = sHeadModel.HeadModelType; ResultsMat2.ChannelFlag = []; ResultsMat2.GoodChannel = iChannels; ResultsMat2.SurfaceFile = sHeadModel.SurfaceFile; if strcmp(sHeadModel.HeadModelType,'volume') ResultsMat2.GridLoc = Loc; % ResultsMat2.GridAtlas = GridAtlas; end if sProcess.options.oriconstraint.Value == 1 ResultsMat2.EstimatedGridOrient = ImagingGridOri; end % === SHARED == % Get the output study (pick the one from the first file) iStudy = iChannelStudy; % Create a default output filename OutputFiles{2} = bst_process('GetNewFilename', fileparts(sInputs(1).ChannelFile), 'results_MCB_KERNEL'); % Save on disk save(OutputFiles{2}, '-struct', 'ResultsMat2'); % Register in database db_add_data(iStudy, OutputFiles{2}, ResultsMat2); %%=========== end % % if (sProcess.options.oriconstraint.Value == 1) && (isempty(sHeadModel.GridOrient)==0) % % ===== SAVE THE RESULTS ===== % % Create a new data file structure % ResultsMat3 = db_template('resultsmat'); % ResultsMat3.ImagingKernel = []; % ResultsMat3.ImageGridAmp = [OriDifference OriDifference]; % ResultsMat3.nComponents = 1; % 1 or 3 % ResultsMat3.Comment = 'MCB: Orientation Difference(Unconstr)'; % ResultsMat3.Function = 'MaximumContrastBeamformerOriDiff'; % ResultsMat3.Time = [1 1]; % Leave it empty if using ImagingKernel % ResultsMat3.DataFile = []; % ResultsMat3.HeadModelFile = HeadModelFile; % ResultsMat3.HeadModelType = sHeadModel.HeadModelType; % ResultsMat3.ChannelFlag = []; % ResultsMat3.GoodChannel = iChannels; % ResultsMat3.SurfaceFile = sHeadModel.SurfaceFile; % ResultsMat3.GridLoc = GridLoc; % % % === NOT SHARED === % % Get the output study (pick the one from the first file) % iStudy = sInputs(1).iStudy; % % Create a default output filename % OutputFiles{3} = bst_process('GetNewFilename', fileparts(sInputs(1).FileName), 'results_MCB_oriDiff'); % % Save on disk % save(OutputFiles{3}, '-struct', 'ResultsMat3'); % % Register in database % db_add_data(iStudy, OutputFiles{3}, ResultsMat3); % end end function ind = min_dist_index(source,target) dist = (source(:,1) - target(1)) .^ 2 + (source(:,2) - target(2)) .^ 2 + (source(:,3) - target(3)) .^ 2; [~,ind] = min(dist); end function X = pInv(A,Reg) % Inverse of 3x3 GCG' in unconstrained beamformers. % Since most head models have rank 2 at each vertex, we cut all the fat and % just take a rank 2 inverse of all the 3x3 matrices % [U,S,V] = svd(A); % Si = diag(1 ./ (S + S(1) * Reg / 100)); % 1/(S^2 + lambda I) % X = V*diag(Si)*U'; eigValues = eig(A); Reg_alpha = Reg / 100 * max(eigValues); X = inv(A+Reg_alpha*eye(size(A,1))); end
github
harig00/MVHSlepian-master
slept2residBAD.m
.m
MVHSlepian-master/Fall17/slept2residBAD.m
21,124
utf_8
047d48a22b5d0885965d42125828a8f3
function varargout=slept2resid(slept,thedates,fitwhat,givenerrors,specialterms,CC,TH,N) % [ESTsignal,ESTresid,ftests,extravalues,total,alphavarall,totalparams, % totalparamerrors,totalfit,functionintegrals,alphavar] % =SLEPT2RESID(slept,thedates,fitwhat,givenerrors,specialterms,CC,TH) % % Takes a time series of Slepian coefficients and fits a desired % combination of functions (e.g. secular, annual, semiannual, etc.) to % each coefficient in order to separate "signal" from residual. % % You can choose to fit either a mean, linear, quadratic, or cubic fuction % as your "base" function to each Slepian coefficient, by using "fitwhat". % In these cases of higher functions, they are only used if they pass an % F-test for variance reduction. For example, a cubic term is only used if % it is significantly better than a quadratic function. % % If you also provide the Slepian functions (CC) and region (TH) for this % localization, then we assume that you want the fitting to the integrated % functions. i.e. If you have surface density, then using the integrated % Slepian function would give you total mass change in a region. In % addition, there will be a fitting of the combination (total) of the Slepian % functions up to the Shannon number for this localization. % % INPUT: % % slept The time series of Slepian coefficients. This % should be a two dimensional matrix (not a cell array), % where the first dimension is time, and the second dimension % are Slepian coefficients sorted by global eigenvalue. % thedates An array of dates corresponding to the slept timeseries. These % should be in Matlab's date format. (see DATENUM in units % of decimal days) % ***It is assumed that 'thedates' matches 'slept'. If 'thedates' % is longer than 'slept' then it is assumed that these are % extra dates that you would like ESTsignal to be evaluated at. % This is useful if you want to interpolate to one of the % GRACE missing months that is important, such as Jan 2011. % fitwhat The functions that you would like to fit to the time series % data. The format of this array is as follows: % [order periodic1 periodic2 periodic3 etc...] where % - order is either 0/1/2/3 to fit UP TO either a % mean/linear/quadratic/cubic function (if increasing % the power of the function reduces variance enough) % - periodic1 is the period in days of a function (i.e. 365.0) % Any # of desired periodic functions [days] can be included. % givenerrors These are given errors, if you have them. In this case a % weighted inversion is performed. givenerrors should be the % same dimensions of slept. % specialterms A cell array such as {2 'periodic' 1460}. At the moment % this is pretty specific to our needs, but could be % expanded later. % CC A cell array of the localization Slepian functions % TH The region (proper string or XY coordinates) that you did the % localization on (so we can integrate) % N The number of functions % % OUTPUT: % % ESTsignal The least-squares fitted function for each Slepian % coefficient evaluated at those months in the same format % ESTresid Residual time series for each Slepian coefficients, ordered % as they were given, presumably by eigenvalue % [nmonths x (Lwindow+1)^2] % ftests An matrix, such as [0 1 1] for each Slepian coefficient, % on whether the fits you % requested passed an F-test for significance. % extravalues These are the values of ESTsignal evaluated at your extra % dates which were tacked onto 'thedates' % total The time series of the combined mass change from N Slepian % functions (i.e. the combined data points) % alphavarall The time averaged variance on each data point (from error % propogation from each individual function). These values % are the same for every point. % % totalparams The parameters of the fits to the total. This is a 4-by-j % matrix where j are the fits you wanted. Zeros fill out % the unused parameters. For example, if % you want just a 2nd order polynomial, you will get % [intercept intercept; slope slope; 0 quadratic; 0 0] % totalparamerrors The 95% confidence value on this slope. This is computed % using the critical value for a t-distribution % At the moment, totalparams and totalparamerrors and just % the values for a linear fit. Sometime later maybe change % this to be potentially a quadratic fit as well. % % totalfit Datapoints for the best fit line, so you can plot it, and % datapoints for the confidence intervals of this linear fit, % so you can plot them. NOTE: To plot these you should use % totalfit(:,2)+totalfit(:,3) and totalfit(:,2)-totalfit(:,3) % % functionintegrals This is a vector of the integrals of the Slepian % functions, up to the Shannon number. With this we % can multiply by the data or ESTSignal to get the % changes in total mass over time for each function. % This also has the conversion from kg to Gt already % in it, so don't do that again. % % alphavar The variances on the individual alpha function time series (INTEGRALS). % This is calculated by making a covariance matrix from % ESTresid and then doing the matrix multiplication with the % eigenfunction integrals. % % SEE ALSO: % % Last modified by charig-at-princeton.edu 6/26/2012 defval('xver',0) %defval('specialterms',{2 'periodic' 1728.1}); defval('specialterms',{NaN}); defval('slept','grace2slept(''CSR'',''greenland'',0.5,60,[],[],[],[],''SD'')') defval('extravalues',[]); if isstr(slept) % Evaluate the specified expression [slept,~,thedates,TH,G,CC,V] = eval(slept); end % Initialize/Preallocate defval('givenerrors',ones(size(slept))); defval('fitwhat',[3 365.0]) % Handle the dates if length(thedates)==size(slept,1) % Do nothing extradates = []; moredates=0; elseif length(thedates) > size(slept,1) % There are extra dates, pull them off extradates = thedates((size(slept,1)+1):end); thedates = thedates(1:size(slept,1)); moredates=1; else error('Is thedates shorter than slept?') end % How many data? nmonths=length(thedates); % We will do a scaling to improve the solution mu1 = mean(thedates); % mean mu2 = std(thedates); % standard deviation % Make a new x-vector with this information xprime = (thedates - mu1)/mu2; extradatesprime = (extradates - mu1)/mu2; % The frequencies being fitted in [1/days] omega = 1./[fitwhat(2:end)]; % Rescale these to our new xprime omega = omega*mu2; [i,j] = size(slept); % Initialize the residuals ESTresid =zeros(size(slept)); % Initialize the evaluated fitted function set ESTsignal=zeros(size(slept)); % Figure out the orders and degrees of this setup % BUT orders and degrees have lost their meaning since slept should % be ordered by eigenvalue Ldata=addmoff(j,'r'); [dems,dels]=addmout(Ldata); % How many periodic components? lomega=length(omega); %%% % G matrix assembly %%% % We will have the same number of G matrices as order of polynomial fit. % These matrices are smallish, so make all 3 regardless of whether you want % them all. G1 = []; % For line fits G2 = []; % For quadratic fits G3 = []; % For cubic fits % Mean term if fitwhat(1) >= 0 G1 = [G1 ones(size(xprime'))]; G2 = [G2 ones(size(xprime'))]; G3 = [G3 ones(size(xprime'))]; end % Secular term if fitwhat(1) >= 1 G1 = [G1 (xprime)']; G2 = [G2 (xprime)']; G3 = [G3 (xprime)']; end % Quadratic term if fitwhat(1) >= 2 G2 = [G2 (xprime)'.^2]; G3 = [G3 (xprime)'.^2]; end % Cubic term if fitwhat(1) == 3 G3 = [G3 (xprime)'.^3]; end % Periodic terms if ~isempty(omega) % Angular frequency in radians/(rescaled day) of the periodic terms th_o= repmat(omega,nmonths,1)*2*pi.*repmat((xprime)',1,lomega); G1 = [G1 cos(th_o) sin(th_o)]; G2 = [G2 cos(th_o) sin(th_o)]; G3 = [G3 cos(th_o) sin(th_o)]; % Create our specialterms G if we have it. At the moment this is just % an additional periodic function, but in the future we could add something % else. if ~isnan(specialterms{1}) % Strip off the previous periodic terms here and REPLACE with omegaspec omegaspec = [omega mu2/specialterms{3}]; thspec= repmat(omegaspec,nmonths,1)*2*pi.*repmat((xprime)',1,length(omegaspec)); Gspec1 = [G1(:,1:end-2*lomega) cos(thspec) sin(thspec)]; Gspec2 = [G2(:,1:end-2*lomega) cos(thspec) sin(thspec)]; Gspec3 = [G3(:,1:end-2*lomega) cos(thspec) sin(thspec)]; end end % end periodic % Initilization Complete %%% % Solving %%% % Since each Slepian coefficient has different errors, each will have a % different weighting matrix. Thus we loop over the coefficients. for index=1:j % If we have a priori error information, create a weighting matrix, and % change the G and d matrices to reflect this. Since each coefficient % has its own weighting, we have to invert them separately. W = diag([1./givenerrors(:,index)]); d = slept(:,index); G1w = W*G1; G2w = W*G2; G3w = W*G3; dw = W*d; % This is in case you request a single special term to be looked at % in a special way if index == specialterms{1} Gspec1w = W*Gspec1; Gspec2w = W*Gspec2; Gspec3w = W*Gspec3; lomega = length(omegaspec); th=thspec; myomega=omegaspec; else lomega = length(omega); myomega=omega; th=th_o; end %%% % First order polynomial %%% % Do the fitting by minimizing least squares % First, the linear fit with periodics mL2_1 = (G1w'*G1w)\(G1w'*dw) ; % That was regular, but if there was a special one, substitute if index == specialterms{1} mL2_1 = (Gspec1w'*Gspec1w)\(Gspec1w'*dw) ; end % Use the model parameters to make the periodic amplitude in time startP = length(mL2_1) - 2*lomega + 1; amp1 = [mL2_1(startP:(startP+lomega-1)) mL2_1((startP+lomega):end)]; amp1 = sqrt(amp1(:,1).^2 + amp1(:,2).^2); % Use the model parameters to make the periodic phase in time phase1 = [mL2_1(startP:(startP+lomega-1)) mL2_1((startP+lomega):end)]; phase1 = atan2(phase1(:,1),phase1(:,2)); % Assemble the estimated signal function, evaluated at 'thedates' % Start adding things fitfn1 = mL2_1(1) + mL2_1(2)*(xprime); % Add the sum over all the periodic components periodics fitfn1 = fitfn1 + ... sum(repmat(amp1,1,nmonths).*sin(th'+repmat(phase1,1,nmonths)),1); % For the special time when you want the periodic stuff taken out % fitfn1_nosine = mL2_1(1) + mL2_1(2)*(xprime); % resid1_nosine = d'-sum(repmat(amp1,1,nmonths).*sin(th'+repmat(phase1,1,nmonths)),1); % Compute the residual time series for this coefficient resid1 = d - fitfn1'; % Here's the definition of the residual at lm vs time ESTresid(:,index) = resid1; % Here's the definition of the signal at lm vs time ESTsignal(:,index) = fitfn1'; % Do extra dates if you have them if moredates th_extras= repmat(myomega,length(extradatesprime),1)... *2*pi.*repmat((extradatesprime)',1,lomega); % Evaluate at the missing dates extravaluesfn1 = mL2_1(1) + mL2_1(2)*(extradatesprime) + ... sum(repmat(amp1,1,1).*sin(th_extras'+repmat(phase1,1,1)),1); extravalues(:,index) = extravaluesfn1'; end % Get the residual sum of squares for later F tests rss1 = sum(resid1.^2); %%% % Second order polynomial %%% % Now repeat that all again with second order polynomial, if we want P2ftest = 0; if fitwhat(1) >= 2 mL2_2 = (G2w'*G2w)\(G2w'*dw) ; if index == specialterms{1} mL2_2 = (Gspec2w'*Gspec2w)\(Gspec2w'*dw) ; end startP = length(mL2_2) - 2*lomega + 1; amp2 = [mL2_2(startP:(startP+lomega-1)) mL2_2((startP+lomega):end)]; amp2 = sqrt(amp2(:,1).^2 + amp2(:,2).^2); phase2 = [mL2_2(startP:(startP+lomega-1)) mL2_2((startP+lomega):end)]; phase2 = atan2(phase2(:,1),phase2(:,2)); fitfn2 = mL2_2(1) + mL2_2(2)*(xprime) + mL2_2(3)*(xprime).^2; fitfn2 = fitfn2 + ... sum(repmat(amp2,1,nmonths).*sin(th'+repmat(phase2,1,nmonths)),1); % For the special time when you want the periodic stuff taken out % fitfn2_nosine = mL2_1(1) + mL2_1(2)*(xprime) + mL2_2(3)*(xprime).^2; % resid2_nosine = d'-sum(repmat(amp1,1,nmonths).*sin(th'+repmat(phase1,1,nmonths)),1); % Compute the residual time series for this coefficient resid2 = d - fitfn2'; % Do extra dates if you have them if moredates th_extras= repmat(myomega,length(extradatesprime),1)... *2*pi.*repmat((extradatesprime)',1,lomega); extravaluesfn2 = mL2_2(1) + mL2_2(2)*(extradatesprime) +... mL2_2(3)*(extradatesprime).^2 +... sum(repmat(amp1,1,1).*sin(th_extras'+repmat(phase1,1,1)),1); end % Get the residual sum of squares rss2 = sum(resid2.^2); % Calculate an F-score for this new fit fratioP2 = (rss1 - rss2)/1/(rss2/(length(slept(:,index))-length(mL2_2))); fscore = finv(.95,1,length(slept(:,index))-length(mL2_2)); if fratioP2 > fscore P2ftest = 1; % We pass, so update the signal and residuals with this new fit ESTresid(:,index) = resid2; ESTsignal(:,index) = fitfn2'; if moredates; extravalues(:,index) = extravaluesfn2'; end end end %%% % Third order polynomial %%% % Now repeat that all again with third order polynomial, if we want P3ftest=0; if fitwhat(1) >= 3 mL2_3 = (G3w'*G3w)\(G3w'*dw) ; if index == specialterms{1} mL2_3 = (Gspec3w'*Gspec3w)\(Gspec3w'*dw) ; end startP = length(mL2_3) - 2*lomega + 1; amp3 = [mL2_3(startP:(startP+lomega-1)) mL2_3((startP+lomega):end)]; amp3 = sqrt(amp3(:,1).^2 + amp3(:,2).^2); phase3 = [mL2_3(startP:(startP+lomega-1)) mL2_3((startP+lomega):end)]; phase3 = atan2(phase3(:,1),phase3(:,2)); fitfn3 = mL2_3(1) + mL2_3(2)*(xprime) ... + mL2_3(3)*(xprime).^2 + mL2_3(4)*(xprime).^3; fitfn3 = fitfn3 + ... sum(repmat(amp3,1,nmonths).*sin(th'+repmat(phase3,1,nmonths)),1); resid3 = d - fitfn3'; % For the special time when you want the periodic stuff taken out % fitfn3_nosine = mL2_1(1) + mL2_1(2)*(xprime) +... % mL2_2(3)*(xprime).^2 + mL2_3(4)*(xprime).^3; % resid3_nosine = d'-sum(repmat(amp1,1,nmonths).*sin(th'+repmat(phase1,1,nmonths)),1); % Do extra dates if you have them if moredates th_extras= repmat(myomega,length(extradatesprime),1)... *2*pi.*repmat((extradatesprime)',1,lomega); extravaluesfn3 = mL2_3(1) + mL2_3(2)*(extradatesprime) +... mL2_3(3)*(extradatesprime).^2 + mL2_3(4)*(extradatesprime).^3 +... sum(repmat(amp1,1,1).*sin(th_extras'+repmat(phase1,1,1)),1); end % Get the residual sum of squares rss3 = sum(resid3.^2); % Calculate an F-score for this new fit fratioP3 = (rss1 - rss3)/2/(rss3/(length(slept(:,index))-length(mL2_3))); fscore = finv(.95,1,length(slept(:,index))-length(mL2_3)); if fratioP3 > fscore P3ftest = 1; % We pass, so update the signal and residuals with this new fit ESTresid(:,index) = resid3; ESTsignal(:,index) = fitfn3'; if moredates; extravalues(:,index) = extravaluesfn3'; end end end % Some extra plotting for excessive verification if xver==1 && index <= 30 % clf % subplot(211) % plot(thedates,d,'+') % hold on % plot(thedates,fitfn,'r'); % errorbar(thedates,d,givenerrors(:,1),'b-') % % axis tight % datetick('x',28) % title(sprintf('components at alpha = %i',index)) % legend('Data with given errors','Fitted signal') % % subplot(212) % DY=sqrt(mean(ESTresid(:,1).^2))*ones(size(fitfn))'; % fill([thedates' ; flipud(thedates')],... % [ESTresid(:,1)+DY ; flipud(ESTresid(:,1)-DY)],... % [0.7 0.7 0.7]); % %errorfill(thedates,ESTresid(:,1),sqrt(mean(ESTresid(:,1).^2))*ones(size(fitfn))) % %errorbar(thedates,ESTresid(:,1),sqrt(mean(ESTresid(:,1).^2))*ones(size(fitfn)),'r-') % hold on % DY=givenerrors(:,1); % fill([thedates' ; flipud(thedates')],... % [ESTresid(:,1)+DY ; flipud(ESTresid(:,1)-DY)],... % [0.9 0.9 0.9]); % %errorbar(thedates,ESTresid(:,1),givenerrors(:,1),'b-') % title(sprintf('Residuals with error bands at alpha = %i',index)) % legend('Estimated errors','Given errors') % axis tight % datetick('x',28) clf plot(thedates,d,'b-') hold on plot(thedates,ESTsignal(:,index),'r-') datetick('x',28) title(sprintf('alpha = %i',index)) keyboard end % Make the matrix ftests ftests(index,:) = [0 P2ftest P3ftest]; end % Collect output varns={ESTsignal,ESTresid,ftests,extravalues}; %%% % TOTAL COMBINED FITTING %%% % If we have the parameters for this localization, and we requested the % total fit, then let's do that. if nargout >= 5 && exist('CC') && exist('TH') % Get the residual covariance [Cab] = slepresid2cov(ESTresid); % Calculate the bandwdith for this basis L = sqrt(size(slept,2)) - 1; % This should be an integer if (floor(L)~=L); error('Something fishy about your L'); end if iscell(TH) % Something like {'greenland' 0.5} XY=eval(sprintf('%s(%i,%f)',TH{1},10,TH{2})); else % Coordinates or a string, either works XY=TH; end % Calculate the Shannon number for this basis % N=round((L+1)^2*spharea(XY)); <---------------------------------- defval('N',round((L+1)^2*spharea(XY))); % Make the coefficients with reference to some mean % If they already are, then this won't matter sleptdelta = slept(1:nmonths,:) - repmat(mean(slept(1:nmonths,:),1),nmonths,1); % COMBINE % We want to take the Slepian functions and combine them to get total mass. % For signal, this means integrating the functions and adding them. For % the error, this means using the error propogation equation, where we % compute (int)*(covar)*(int)'. Since the slepcoffs are constants that % just come forward, we can do the integration of the eigenfunctions % first (and once for each function), then multiply by slepcoffs to % get the monthly values. This is much faster. [eigfunINT] = integratebasis(CC,TH,N); % Since Int should have units of (fn * m^2), need to go from fractional % sphere area to real area. If the fn is surface density, this output is % in kilograms. Then change the units from kg to Gt in METRIC tons eigfunINT = eigfunINT*4*pi*6370000^2/10^3/10^9; functionintegrals = eigfunINT; % Now multiply by the appropriate slepcoffs to get the months % This becomes alpha by months %functimeseries=repmat(eigfunINT',1,nmonths).*sleptdelta(:,1:N)'; %functimeseries = sleptdelta(:,1:N)'; % Here do the total sum of the data total=eigfunINT*sleptdelta(:,1:N)'; % Get the error thevars = diag(Cab(1:N,1:N))'; alphavar = eigfunINT.^2.*thevars; % Now the combined error with covariance alphavarall = eigfunINT*Cab(1:N,1:N)*eigfunINT'; % FITTING % We have uniform estimated error, which will be different than the polyfit % estimated residuals because ours account for sinusoidal signals. So % pass the new error to our function for replacement, so % that the fitting confidence intervals reflect that [fit,delta,params,paramerrors] = timeseriesfit([thedates' total'],alphavarall,1,1); % Make a matrix for the line, and 95% confidence in the fit totalfit = [thedates' fit delta]; % Make the parameters and error valid for a year totalparams = params(2)*365; totalparamerrors = paramerrors*365; % Collect the expanded output varns={ESTsignal,ESTresid,ftests,extravalues,... total,alphavarall,totalparams,totalparamerrors,totalfit,... functionintegrals,alphavar}; end varargout=varns(1:nargout);
github
harig00/MVHSlepian-master
slept2resid.m
.m
MVHSlepian-master/Fall17/slept2resid.m
21,225
utf_8
0aa4fba4615ad4ae371dd2bec3a23cc1
function varargout=slept2resid(slept,thedates,fitwhat,givenerrors,specialterms,CC,TH,N) % [ESTsignal,ESTresid,ftests,extravalues,total,alphavarall,totalparams, % totalparamerrors,totalfit,functionintegrals,alphavar] % =SLEPT2RESID(slept,thedates,fitwhat,givenerrors,specialterms,CC,TH) % % Takes a time series of Slepian coefficients and fits a desired % combination of functions (e.g. secular, annual, semiannual, etc.) to % each coefficient in order to separate "signal" from residual. % % You can choose to fit either a mean, linear, quadratic, or cubic fuction % as your "base" function to each Slepian coefficient, by using "fitwhat". % In these cases of higher functions, they are only used if they pass an % F-test for variance reduction. For example, a cubic term is only used if % it is significantly better than a quadratic function. % % If you also provide the Slepian functions (CC) and region (TH) for this % localization, then we assume that you want the fitting to the integrated % functions. i.e. If you have surface density, then using the integrated % Slepian function would give you total mass change in a region. In % addition, there will be a fitting of the combination (total) of the Slepian % functions up to the Shannon number for this localization. % % INPUT: % % slept The time series of Slepian coefficients. This % should be a two dimensional matrix (not a cell array), % where the first dimension is time, and the second dimension % are Slepian coefficients sorted by global eigenvalue. % thedates An array of dates corresponding to the slept timeseries. These % should be in Matlab's date format. (see DATENUM in units % of decimal days) % ***It is assumed that 'thedates' matches 'slept'. If 'thedates' % is longer than 'slept' then it is assumed that these are % extra dates that you would like ESTsignal to be evaluated at. % This is useful if you want to interpolate to one of the % GRACE missing months that is important, such as Jan 2011. % fitwhat The functions that you would like to fit to the time series % data. The format of this array is as follows: % [order periodic1 periodic2 periodic3 etc...] where % - order is either 0/1/2/3 to fit UP TO either a % mean/linear/quadratic/cubic function (if increasing % the power of the function reduces variance enough) % - periodic1 is the period in days of a function (i.e. 365.0) % Any # of desired periodic functions [days] can be included. % givenerrors These are given errors, if you have them. In this case a % weighted inversion is performed. givenerrors should be the % same dimensions of slept. % specialterms A cell array such as {2 'periodic' 1460}. At the moment % this is pretty specific to our needs, but could be % expanded later. % CC A cell array of the localization Slepian functions % TH The region (proper string or XY coordinates) that you did the % localization on (so we can integrate) % N Number of largest eigenfunctions in which to expand. By default % rounds to the Shannon number. % % OUTPUT: % % ESTsignal The least-squares fitted function for each Slepian % coefficient evaluated at those months in the same format % ESTresid Residual time series for each Slepian coefficients, ordered % as they were given, presumably by eigenvalue % [nmonths x (Lwindow+1)^2] % ftests An matrix, such as [0 1 1] for each Slepian coefficient, % on whether the fits you % requested passed an F-test for significance. % extravalues These are the values of ESTsignal evaluated at your extra % dates which were tacked onto 'thedates' % total The time series of the combined mass change from N Slepian % functions (i.e. the combined data points) % alphavarall The time averaged variance on each data point (from error % propogation from each individual function). These values % are the same for every point. % % totalparams The parameters of the fits to the total. This is a 4-by-j % matrix where j are the fits you wanted. Zeros fill out % the unused parameters. For example, if % you want just a 2nd order polynomial, you will get % [intercept intercept; slope slope; 0 quadratic; 0 0] % totalparamerrors The 95% confidence value on this slope. This is computed % using the critical value for a t-distribution % At the moment, totalparams and totalparamerrors and just % the values for a linear fit. Sometime later maybe change % this to be potentially a quadratic fit as well. % % totalfit Datapoints for the best fit line, so you can plot it, and % datapoints for the confidence intervals of this linear fit, % so you can plot them. NOTE: To plot these you should use % totalfit(:,2)+totalfit(:,3) and totalfit(:,2)-totalfit(:,3) % % functionintegrals This is a vector of the integrals of the Slepian % functions, up to the Shannon number. With this we % can multiply by the data or ESTSignal to get the % changes in total mass over time for each function. % This also has the conversion from kg to Gt already % in it, so don't do that again. % % alphavar The variances on the individual alpha function time series (INTEGRALS). % This is calculated by making a covariance matrix from % ESTresid and then doing the matrix multiplication with the % eigenfunction integrals. % % SEE ALSO: % % Last modified by charig-at-princeton.edu 6/26/2012 defval('xver',0) %defval('specialterms',{2 'periodic' 1728.1}); defval('specialterms',{NaN}); defval('slept','grace2slept(''CSR'',''greenland'',0.5,60,[],[],[],[],''SD'')') defval('extravalues',[]); if isstr(slept) % Evaluate the specified expression [slept,~,thedates,TH,G,CC,V] = eval(slept); end % Initialize/Preallocate defval('givenerrors',ones(size(slept))); defval('fitwhat',[1 365.0]); defval('P2ftest',0); defval('P3ftest',0); % Handle the dates if length(thedates)==size(slept,1) % Do nothing extradates = []; moredates=0; elseif length(thedates) > size(slept,1) % There are extra dates, pull them off extradates = thedates((size(slept,1)+1):end); thedates = thedates(1:size(slept,1)); moredates=1; else error('Is thedates shorter than slept?') end % How many data? nmonths=length(thedates); % We will do a scaling to improve the solution mu1 = mean(thedates); % mean mu2 = std(thedates); % standard deviation % Make a new x-vector with this information xprime = (thedates - mu1)/mu2; extradatesprime = (extradates - mu1)/mu2; % The frequencies being fitted in [1/days] omega = 1./[fitwhat(2:end)]; % Rescale these to our new xprime omega = omega*mu2; [i,j] = size(slept); % Initialize the residuals ESTresid =zeros(size(slept)); % Initialize the evaluated fitted function set ESTsignal=zeros(size(slept)); % Figure out the orders and degrees of this setup % BUT orders and degrees have lost their meaning since slept should % be ordered by eigenvalue Ldata=addmoff(j,'r'); [dems,dels]=addmout(Ldata); % How many periodic components? lomega=length(omega); %%% % G matrix assembly %%% % We will have the same number of G matrices as order of polynomial fit. % These matrices are smallish, so make all 3 regardless of whether you want % them all. G1 = []; % For line fits G2 = []; % For quadratic fits G3 = []; % For cubic fits % Mean term if fitwhat(1) >= 0 G1 = [G1 ones(size(xprime'))]; G2 = [G2 ones(size(xprime'))]; G3 = [G3 ones(size(xprime'))]; end % Secular term if fitwhat(1) >= 1 G1 = [G1 (xprime)']; G2 = [G2 (xprime)']; G3 = [G3 (xprime)']; end % Quadratic term if fitwhat(1) >= 2 G2 = [G2 (xprime)'.^2]; G3 = [G3 (xprime)'.^2]; end % Cubic term if fitwhat(1) == 3 G3 = [G3 (xprime)'.^3]; end % Periodic terms if ~isempty(omega) % Angular frequency in radians/(rescaled day) of the periodic terms th_o= repmat(omega,nmonths,1)*2*pi.*repmat((xprime)',1,lomega); G1 = [G1 cos(th_o) sin(th_o)]; G2 = [G2 cos(th_o) sin(th_o)]; G3 = [G3 cos(th_o) sin(th_o)]; % Create our specialterms G if we have it. At the moment this is just % an additional periodic function, but in the future we could add something % else. if ~isnan(specialterms{1}) % Strip off the previous periodic terms here and REPLACE with omegaspec omegaspec = [omega mu2/specialterms{3}]; thspec= repmat(omegaspec,nmonths,1)*2*pi.*repmat((xprime)',1,length(omegaspec)); Gspec1 = [G1(:,1:end-2*lomega) cos(thspec) sin(thspec)]; Gspec2 = [G2(:,1:end-2*lomega) cos(thspec) sin(thspec)]; Gspec3 = [G3(:,1:end-2*lomega) cos(thspec) sin(thspec)]; end end % end periodic % Initilization Complete %%% % Solving %%% % Since each Slepian coefficient has different errors, each will have a % different weighting matrix. Thus we loop over the coefficients. for index=1:j % If we have a priori error information, create a weighting matrix, and % change the G and d matrices to reflect this. Since each coefficient % has its own weighting, we have to invert them separately. W = diag([1./givenerrors(:,index)]); d = slept(:,index); G1w = W*G1; G2w = W*G2; G3w = W*G3; dw = W*d; % This is in case you request a single special term to be looked at % in a special way if index == specialterms{1} Gspec1w = W*Gspec1; Gspec2w = W*Gspec2; Gspec3w = W*Gspec3; lomega = length(omegaspec); th=thspec; myomega=omegaspec; else lomega = length(omega); myomega=omega; th=th_o; end %%% % First order polynomial %%% % Do the fitting by minimizing least squares % First, the linear fit with periodics mL2_1 = (G1w'*G1w)\(G1w'*dw) ; % That was regular, but if there was a special one, substitute if index == specialterms{1} mL2_1 = (Gspec1w'*Gspec1w)\(Gspec1w'*dw) ; end % Use the model parameters to make the periodic amplitude in time startP = length(mL2_1) - 2*lomega + 1; amp1 = [mL2_1(startP:(startP+lomega-1)) mL2_1((startP+lomega):end)]; amp1 = sqrt(amp1(:,1).^2 + amp1(:,2).^2); % Use the model parameters to make the periodic phase in time phase1 = [mL2_1(startP:(startP+lomega-1)) mL2_1((startP+lomega):end)]; phase1 = atan2(phase1(:,1),phase1(:,2)); % Assemble the estimated signal function, evaluated at 'thedates' % Start adding things fitfn1 = mL2_1(1) + mL2_1(2)*(xprime); % Add the sum over all the periodic components periodics fitfn1 = fitfn1 + ... sum(repmat(amp1,1,nmonths).*sin(th'+repmat(phase1,1,nmonths)),1); % For the special time when you want the periodic stuff taken out % fitfn1_nosine = mL2_1(1) + mL2_1(2)*(xprime); % resid1_nosine = d'-sum(repmat(amp1,1,nmonths).*sin(th'+repmat(phase1,1,nmonths)),1); % Compute the residual time series for this coefficient resid1 = d - fitfn1'; % Here's the definition of the residual at lm vs time ESTresid(:,index) = resid1; % Here's the definition of the signal at lm vs time ESTsignal(:,index) = fitfn1'; % Do extra dates if you have them if moredates th_extras= repmat(myomega,length(extradatesprime),1)... *2*pi.*repmat((extradatesprime)',1,lomega); % Evaluate at the missing dates extravaluesfn1 = mL2_1(1) + mL2_1(2)*(extradatesprime) + ... sum(repmat(amp1,1,1).*sin(th_extras'+repmat(phase1,1,1)),1); extravalues(:,index) = extravaluesfn1'; end % Get the residual sum of squares for later F tests rss1 = sum(resid1.^2); %%% % Second order polynomial %%% % Now repeat that all again with second order polynomial, if we want if fitwhat(1) >= 2 mL2_2 = (G2w'*G2w)\(G2w'*dw) ; if index == specialterms{1} mL2_2 = (Gspec2w'*Gspec2w)\(Gspec2w'*dw) ; end startP = length(mL2_2) - 2*lomega + 1; amp2 = [mL2_2(startP:(startP+lomega-1)) mL2_2((startP+lomega):end)]; amp2 = sqrt(amp2(:,1).^2 + amp2(:,2).^2); phase2 = [mL2_2(startP:(startP+lomega-1)) mL2_2((startP+lomega):end)]; phase2 = atan2(phase2(:,1),phase2(:,2)); fitfn2 = mL2_2(1) + mL2_2(2)*(xprime) + mL2_2(3)*(xprime).^2; fitfn2 = fitfn2 + ... sum(repmat(amp2,1,nmonths).*sin(th'+repmat(phase2,1,nmonths)),1); % For the special time when you want the periodic stuff taken out % fitfn2_nosine = mL2_1(1) + mL2_1(2)*(xprime) + mL2_2(3)*(xprime).^2; % resid2_nosine = d'-sum(repmat(amp1,1,nmonths).*sin(th'+repmat(phase1,1,nmonths)),1); % Compute the residual time series for this coefficient resid2 = d - fitfn2'; % Do extra dates if you have them if moredates th_extras= repmat(myomega,length(extradatesprime),1)... *2*pi.*repmat((extradatesprime)',1,lomega); extravaluesfn2 = mL2_2(1) + mL2_2(2)*(extradatesprime) +... mL2_2(3)*(extradatesprime).^2 +... sum(repmat(amp1,1,1).*sin(th_extras'+repmat(phase1,1,1)),1); end % Get the residual sum of squares rss2 = sum(resid2.^2); % Calculate an F-score for this new fit fratioP2 = (rss1 - rss2)/1/(rss2/(length(slept(:,index))-length(mL2_2))); fscore = finv(.95,1,length(slept(:,index))-length(mL2_2)); if fratioP2 > fscore P2ftest = 1; % We pass, so update the signal and residuals with this new fit ESTresid(:,index) = resid2; ESTsignal(:,index) = fitfn2'; if moredates; extravalues(:,index) = extravaluesfn2'; end else P2ftest = 0; end end %%% % Third order polynomial %%% % Now repeat that all again with third order polynomial, if we want if fitwhat(1) >= 3 mL2_3 = (G3w'*G3w)\(G3w'*dw) ; if index == specialterms{1} mL2_3 = (Gspec3w'*Gspec3w)\(Gspec3w'*dw) ; end startP = length(mL2_3) - 2*lomega + 1; amp3 = [mL2_3(startP:(startP+lomega-1)) mL2_3((startP+lomega):end)]; amp3 = sqrt(amp3(:,1).^2 + amp3(:,2).^2); phase3 = [mL2_3(startP:(startP+lomega-1)) mL2_3((startP+lomega):end)]; phase3 = atan2(phase3(:,1),phase3(:,2)); fitfn3 = mL2_3(1) + mL2_3(2)*(xprime) ... + mL2_3(3)*(xprime).^2 + mL2_3(4)*(xprime).^3; fitfn3 = fitfn3 + ... sum(repmat(amp3,1,nmonths).*sin(th'+repmat(phase3,1,nmonths)),1); resid3 = d - fitfn3'; % For the special time when you want the periodic stuff taken out % fitfn3_nosine = mL2_1(1) + mL2_1(2)*(xprime) +... % mL2_2(3)*(xprime).^2 + mL2_3(4)*(xprime).^3; % resid3_nosine = d'-sum(repmat(amp1,1,nmonths).*sin(th'+repmat(phase1,1,nmonths)),1); % Do extra dates if you have them if moredates th_extras= repmat(myomega,length(extradatesprime),1)... *2*pi.*repmat((extradatesprime)',1,lomega); extravaluesfn3 = mL2_3(1) + mL2_3(2)*(extradatesprime) +... mL2_3(3)*(extradatesprime).^2 + mL2_3(4)*(extradatesprime).^3 +... sum(repmat(amp1,1,1).*sin(th_extras'+repmat(phase1,1,1)),1); end % Get the residual sum of squares rss3 = sum(resid3.^2); % Calculate an F-score for this new fit fratioP3 = (rss1 - rss3)/2/(rss3/(length(slept(:,index))-length(mL2_3))); fscore = finv(.95,1,length(slept(:,index))-length(mL2_3)); if fratioP3 > fscore P3ftest = 1; % We pass, so update the signal and residuals with this new fit ESTresid(:,index) = resid3; ESTsignal(:,index) = fitfn3'; if moredates; extravalues(:,index) = extravaluesfn3'; end else P3ftest = 0; end end % Some extra plotting for excessive verification if xver==1 && index <= 30 % clf % subplot(211) % plot(thedates,d,'+') % hold on % plot(thedates,fitfn,'r'); % errorbar(thedates,d,givenerrors(:,1),'b-') % % axis tight % datetick('x',28) % title(sprintf('components at alpha = %i',index)) % legend('Data with given errors','Fitted signal') % % subplot(212) % DY=sqrt(mean(ESTresid(:,1).^2))*ones(size(fitfn))'; % fill([thedates' ; flipud(thedates')],... % [ESTresid(:,1)+DY ; flipud(ESTresid(:,1)-DY)],... % [0.7 0.7 0.7]); % %errorfill(thedates,ESTresid(:,1),sqrt(mean(ESTresid(:,1).^2))*ones(size(fitfn))) % %errorbar(thedates,ESTresid(:,1),sqrt(mean(ESTresid(:,1).^2))*ones(size(fitfn)),'r-') % hold on % DY=givenerrors(:,1); % fill([thedates' ; flipud(thedates')],... % [ESTresid(:,1)+DY ; flipud(ESTresid(:,1)-DY)],... % [0.9 0.9 0.9]); % %errorbar(thedates,ESTresid(:,1),givenerrors(:,1),'b-') % title(sprintf('Residuals with error bands at alpha = %i',index)) % legend('Estimated errors','Given errors') % axis tight % datetick('x',28) clf plot(thedates,d,'b-') hold on plot(thedates,ESTsignal(:,index),'r-') datetick('x',28) title(sprintf('alpha = %i',index)) end % Make the matrix ftests ftests(index,:) = [0 P2ftest P3ftest]; end % Collect output varns={ESTsignal,ESTresid,ftests,extravalues}; %%% % TOTAL COMBINED FITTING %%% % If we have the parameters for this localization, and we requested the % total fit, then let's do that. if nargout >= 5 && exist('CC') && exist('TH') % Get the residual covariance [Cab] = slepresid2cov(ESTresid); % Calculate the bandwdith for this basis L = sqrt(size(slept,2)) - 1; % This should be an integer if (floor(L)~=L); error('Something fishy about your L'); end if iscell(TH) % Something like {'greenland' 0.5} XY=eval(sprintf('%s(%i,%f)',TH{1},10,TH{2})); else % Coordinates or a string, either works XY=TH; end % Calculate the Shannon number for this basis defval('N',round((L+1)^2*spharea(XY))); % Make the coefficients with reference to some mean % If they already are, then this won't matter sleptdelta = slept(1:nmonths,:) - repmat(mean(slept(1:nmonths,:),1),nmonths,1); % COMBINE % We want to take the Slepian functions and combine them to get total mass. % For signal, this means integrating the functions and adding them. For % the error, this means using the error propogation equation, where we % compute (int)*(covar)*(int)'. Since the slepcoffs are constants that % just come forward, we can do the integration of the eigenfunctions % first (and once for each function), then multiply by slepcoffs to % get the monthly values. This is much faster. [eigfunINT] = integratebasis(CC,TH,N); % Since Int should have units of (fn * m^2), need to go from fractional % sphere area to real area. If the fn is surface density, this output is % in kilograms. Then change the units from kg to Gt in METRIC tons eigfunINT = eigfunINT*4*pi*6370000^2/10^3/10^9; functionintegrals = eigfunINT; % Now multiply by the appropriate slepcoffs to get the months % This becomes alpha by months %functimeseries=repmat(eigfunINT',1,nmonths).*sleptdelta(:,1:N)'; %functimeseries = sleptdelta(:,1:N)'; % Here do the total sum of the data total=eigfunINT*sleptdelta(:,1:N)'; % Get the error thevars = diag(Cab(1:N,1:N))'; alphavar = eigfunINT.^2.*thevars; % Now the combined error with covariance alphavarall = eigfunINT*Cab(1:N,1:N)*eigfunINT'; % FITTING % We have uniform estimated error, which will be different than the polyfit % estimated residuals because ours account for sinusoidal signals. So % pass the new error to our function for replacement, so % that the fitting confidence intervals reflect that [fit,delta,totalparams,paramerrors] = timeseriesfit([thedates' total'],alphavarall,1,fitwhat(1)); % [fit,delta,params,paramerrors] = timeseriesfit([thedates' total'],alphavarall,1,1); % Make a matrix for the line, and 95% confidence in the fit totalfit = [thedates' fit delta]; totalparamerrors = paramerrors*365; % Collect the expanded output varns={ESTsignal,ESTresid,ftests,extravalues,... total,alphavarall,totalparams,totalparamerrors,totalfit,... functionintegrals,alphavar}; end varargout=varns(1:nargout);
github
harig00/MVHSlepian-master
intersection_reduce.m
.m
MVHSlepian-master/Spring18/utils/intersection_reduce.m
1,009
utf_8
11161e9a8e01992a62f4609a7efc9d1f
% Some code I'm working on to take as input a list of regions and return % a new list wherein all intersecting/overlapping regions from the original % have been unioned together. % Not currently working, or done. function [ reduced ] = intersectReduce(polys) % Any intersecting polys get unioned numPolys=numel(polys); for a=1:numPolys polyA=polys(a); evaldPolyA=eval(sprintf('%s(%i,%f)',polyA,res,b)); % Cast to euclidean in case we contain a pole [latfA,lonfA]=flatearthpoly(evaldPolyA); % Check for intersections for b=a+1:numPolys polyB=polys(b); evaldPolyB=eval(sprintf('%s(%i,%f)',polyB,res,b)); [latfB,lonfB]=flatearthpoly(evaldPolyB); [xi,yi]=polyxpoly(latfA,lonfA,latfB,lonfB); if numel([xi yi])~=0 % Union the two polys [xu,yu]=polybool('union',evaldPolyA,evaldPolyB); % Remove polyB newPolys=zeros(numel(polys)-1); % Replace polyA % Recurse! end end end reduced=polys; end
github
rossimattia/light-field-super-resolution-master
nlm.m
.m
light-field-super-resolution-master/nlm.m
5,739
utf_8
2dfeb4c385a2f7cb353ba02583afbe08
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function wei = nlm(A, B, patRad, intSigma, offset) % NLM computes the similarity weights between the pixels of an image A and % those of an image B. In graph terms, it computes the edge weights of a % graph were edges go from the pixels of image A to those of image B. The % weights are stored in a vector wei with three columns: the weight of the % edge from pixel wei(k,1) of image A to the pixel wei(k,2) of image B is % wei(k,3), with wei(k,1) and wei(k,2) linear coordinates. % % INPUT: % A - a gray scale image (double [0,1]). % B - a gray scale image (double [0,1]). % patRad - the size of the (patRad x patRad) patch used in the similarity computation. % intSigma - the standard deviation used in the similarity computation. % offSet - a struct defining the searching window (see below). % % OUTPUT: % wei - the similarity weights (aka the graph weights). % % Each pixel A(y,x) is compared with all the pixels B(y + offSet.Y(k),x + offSet.X(k)) % where k = 1, 2, ... , length(offSet.X). The comparison is carried out % between the (patRad x patRad) patches centered at the two considered pixels. % % For a matter of computational efficiency, some rows of wei are computed % but NOT valid. These rows are not valid because either wei(k,1) or wei(k,2) % does not correspond to a real pixel coordinate in A or B, respectively. % These rows are the only ones having wei(k,3) equal to ZERO, therefore % they can be easily recognized. % ========================================================================= tStart = tic; % ==== Global constants =================================================== QUIET = 1; % ==== Extract the images dimensions ====================================== height = size(A, 1); width = size(A, 2); N = height * width; % ==== Compute the weights ================================================ % Extract the comparison offsets. Y = offset.Y; X = offset.X; offsetsNum = length(X); % Compute the radius of the smallest window that contains the offsets. % The window will be ((2 * winRad + 1) x (2 * winRad + 1)) pixels. winRad = max( max(abs(Y)), max(abs(X)) ); % Pad images A and B. Apad = padarray(A, [patRad, patRad], 0.5, 'both'); Bpad = padarray(B, [winRad + patRad, winRad + patRad], 0.5, 'both'); % Allocate auxiliary variables. D = zeros(patRad + height + patRad, patRad + width + patRad); Dint = zeros(1 + size(D, 1), 1 + size(D, 2)); weiAux = zeros(N, 3); weiNum = N * length(X); wei = zeros(weiNum, 3); % Bpad(rows, cols) is Bpad without the winRad pixel frame. rows = (winRad + 1):(winRad + patRad + height + patRad); cols = (winRad + 1):(winRad + patRad + width + patRad); % Compute the linear coordinates of all the pixels in a image. z = (1:1:N)'; % Initialize the 1st column of "weiAux" with "z". weiAux(:, 1) = z; % Compute the (row,col) coordinates of all the pixels in "z". [y, x] = ind2sub([height, width], z); % Auxiliary indexes. rowSelect1 = (1 + patRad + (1 + patRad)):(1 + patRad + (height + patRad)); colSelect1 = (1 + patRad + (1 + patRad)):(1 + patRad + (width + patRad)); rowSelect2 = (1 + patRad + (1 + patRad)):(1 + patRad + (height + patRad)); colSelect2 = (1 + patRad + (1 - patRad - 1)):(1 + patRad + (width - patRad - 1)); rowSelect3 = (1 + patRad + (1 - patRad - 1)):(1 + patRad + (height - patRad - 1)); colSelect3 = (1 + patRad + (1 + patRad)):(1 + patRad + (width + patRad)); rowSelect4 = (1 + patRad + (1 - patRad - 1)):(1 + patRad + (height - patRad - 1)); colSelect4 = (1 + patRad + (1 - patRad - 1)):(1 + patRad + (width - patRad - 1)); % Each row of "wei" will contain, from left to right: % - the linear coordinate of a 1st pixel, % - the linear coordinate of a 2nd pixel, % - the energy of the difference between the two patches centered on the % 1st and 2nd pixel, respectively. for k = 1:1:offsetsNum % We want to compare the patch centered on pixels (y,x) with that at pixel (yp,xp). yp = y + Y(k); xp = x + X(k); % Compute the squared difference between Apad and the shifted Bpad. D(:, :) = ( Apad - Bpad(rows + Y(k), cols + X(k)) ).^2; % Compute the integral image of D. Dint(:, :) = integralImage(D, 'upright'); % V(y,x) will contain the weight between pixels (y,x) and (yp,xp). V = ... Dint(rowSelect1, colSelect1) ... - Dint(rowSelect2, colSelect2) ... - Dint(rowSelect3, colSelect3) ... + Dint(rowSelect4, colSelect4); % Detect those comparisons with pixels (yp,xp) outside image B. mask = (yp >= 1) & (yp <= height) & (xp >= 1) & (xp <= width); % Store the valid pixels (yp,xp) in linear form. weiAux(mask, 2) = sub2ind([height, width], yp(mask), xp(mask)); % Compute and store the Gaussian weights. weiAux(:, 3) = exp( - V(:) / (intSigma ^2) ); % Remove the non valid weights, i.e. those associated to pixels (yp,xp) outside B. weiAux(~mask, 3) = 0; % Add the weigths assocaited to the offset (Y(k),X(k)). wei( (((k - 1) * N) + 1):(k * N), : ) = weiAux; % Clean weiAux for the next iteration. weiAux(:, 2:3) = 0; end % ========================================================================= if ~QUIET tElapsed = toc(tStart); fprintf('\n>>> nlm <<< time: %f\n', tElapsed); end end
github
rossimattia/light-field-super-resolution-master
tukeywin.m
.m
light-field-super-resolution-master/tukeywin.m
1,096
utf_8
49da297950887fc13409ec7ed2385fff
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function W = tukeywin(N, alpha) % TUKEYWIN builds a 1D Tukey window. % % INPUT: % N - the window length. % alpha - the window parameter. % % OUTPUT: % W - the window. % ========================================================================= n = 0:1:(N-1); W = zeros(N, 1); mask = (n < ceil(alpha * (N-1) / 2)); W(mask) = (1/2) * ( 1 + cos( pi * ( ( (2 * n(mask)) / (alpha * (N-1)) ) - 1 ) ) ); mask = (n >= ceil(alpha * (N-1) / 2)) & (n <= floor((N-1) * (1 - (alpha/2)))); W(mask) = 1; mask = (n > floor((N-1) * (1 - (alpha/2)))); W(mask) = (1/2) * ( 1 + cos( pi * ( ( (2 * n(mask)) / (alpha * (N-1)) ) - (2/alpha) + 1 ) ) ); end
github
rossimattia/light-field-super-resolution-master
readhci.m
.m
light-field-super-resolution-master/readhci.m
2,868
utf_8
e577d16ba369b9221d054cfa67220b05
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function lf = readhci(filename) % READHCI stores the data inside the HDF5 file at the input into a struct % with the same fields. Views are arranged in a 2D cell array adopting the % reference system described in the README. % % INPUT: % filename - an HDF5 file name. % % OUTPUT: % lf - a struct with: % - the same fields of the HDF5 file, % - a 2D cell array storing the light field, % - a 2D cell array storing the light field depth maps. % ==== Extract the light field parameters ================================= lf.yRes = h5readatt(filename, '/', 'yRes'); lf.xRes = h5readatt(filename, '/', 'xRes'); lf.vRes = h5readatt(filename, '/', 'vRes'); lf.hRes = h5readatt(filename, '/', 'hRes'); lf.channels = h5readatt(filename, '/', 'channels'); lf.vSampling = h5readatt(filename, '/', 'vSampling'); lf.hSampling = h5readatt(filename, '/', 'hSampling'); lf.focalLength = h5readatt(filename, '/', 'focalLength'); lf.dV = h5readatt(filename, '/', 'dV'); lf.dH = h5readatt(filename, '/', 'dH'); lf.shift = h5readatt(filename, '/', 'shift'); % ==== Check the input light field ======================================== if (lf.channels ~= 3) error('Input views must be RGB !!!'); end % ==== Read the light field views ========================================= % Dataset '/LF' is a 5D array of size (channels x xRes x yRes x hRes x vRes). % Read the light field views. dataZ = h5read(filename, '/LF'); % Order dataLF as (yRes x xRes x channels x vRes x hRes). dataZ = permute(dataZ, [3 2 1 5 4]); % ==== Read the light field depth maps ==================================== % '/GT_DEPTH' is a 4D array of size (xRes x yRes x hRes x vRes). % Read the light field depth maps. dataW = h5read(filename, '/GT_DEPTH'); % Order dataW as (yRes x xRes x vRes x hRes). dataW = permute(dataW, [2 1 4 3]); % ==== Organize the views and depth maps into 2D cell arrays ============== % Allocate a 2D cell array for the light field views. lf.view = cell(lf.vRes, lf.hRes); % Allocate a 2D cell array for the light field depth maps. lf.depth = cell(lf.vRes, lf.hRes); for s = 1:1:lf.hRes for t = 1:1:lf.vRes % Extract view (t,s) and its depth map. auxZ = dataZ(:, :, :, t, lf.hRes - s + 1); auxW = dataW(:, :, t, lf.hRes - s + 1); % Store the view and its depth map. lf.view{t, s} = auxZ; lf.depth{t, s} = auxW; end end end