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
TUDelft-DataDrivenControl/Predictor-Based-Subspace-IDentification-toolbox-master
reggcv.m
.m
Predictor-Based-Subspace-IDentification-toolbox-master/extra/backwards/private/reggcv.m
4,183
utf_8
96e102b790fbfa5f01c26445d60a36fc
function reg_min=reggcv(Y,Vn,Sn,method,show) %REGGCV Compute regularization using generalized cross validation. % Determine the regularization parameter for ordkernel % using Generalized Cross-Validation (GCV). It plots the % GCV function as a function of the regularization % parameter and finds its minimum. % % Syntax: % reg=reggcv(Y,V,S) % reg=reggcv(Y,V,S,method,show) % % Input: % Y,V,S Data matrices from lpvkernel or bilkernel. % method Regularization method to be used. % 'Tikh' - Tikhonov regularization (default). % 'tsvd' - Truncated singular value decomposition. % show Display intermediate steps of the algorithm. % % Output: % reg Regularization paramater for the kernel % subspace identification method of ordkernel. % Written by Vincent Verdult, May 2004. % Based on Regularization Tools by P. C. Hansen % default method if nargin<4 method='Tikh'; end if nargin<5 show=0; end if size(Y,1)~=size(Vn,1) error('The number of rows in Y must equal the number of rows in V.') end if size(Vn,1)~=size(Vn,2) error('V must be a square matrix.') end if size(Sn,2)~=1 error('S must be a column vector.') end if size(Vn,1)~=size(Sn,1) error('The number of rows in S must equal the number of rows in V.') end % Initialization. N = size(Sn,1); beta = Vn'*Y; % Tikhonov regularization if (strncmp(method,'Tikh',4) || strncmp(method,'tikh',4)) npoints = 200; % Number of points on the curve. smin_ratio = 16*eps; % Smallest regularization parameter. reg_param = zeros(npoints,1); G = zeros(npoints,1); s = sqrt(Sn); reg_param(npoints) = max([s(N),s(1)*smin_ratio]); ratio = (s(1)/reg_param(npoints))^(1/(npoints-1)); for i=npoints-1:-1:1 reg_param(i) = ratio*reg_param(i+1); end if show==1 disp('Calculating GCV curve.') end % Vector of GCV-function values. for i=1:npoints G(i) = reggcvfun(reg_param(i),Sn,beta); end % Plot GCV function. if show==1 loglog(reg_param,G,'-'), xlabel('\lambda'), ylabel('G(\lambda)') title('GCV function') end % Find minimum if show==1 disp('Searching GCV minimum') OPT=optimset('Display','iter'); else OPT=optimset('Display','off'); end [minG,minGi] = min(G); % Initial guess. reg_min = fminbnd(@reggcvfun,... reg_param(min(minGi+1,npoints)),... reg_param(max(minGi-1,1)),OPT,Sn,beta); % Minimizer. minG = reggcvfun(reg_min,Sn,beta); % Minimum of GCV function. if show==1 ax = axis; HoldState = ishold; hold on; loglog(reg_min,minG,'*r',[reg_min,reg_min],[minG/1000,minG],':r') title(['GCV function, minimum at \lambda = ',num2str(reg_min)]) axis(ax) if (~HoldState) hold off end end % Truncated SVD elseif (strncmp(method,'tsvd',4) || strncmp(method,'TSVD',4)) rho=zeros(1,N-1); G=zeros(1,N-1); rho(N-1) = sum(beta(N,:).^2); G(N-1) = rho(N-1); for k=N-2:-1:1 rho(k) = rho(k+1) + sum(beta(k+1,:).^2); G(k) = rho(k)/((N - k)^2); end reg_param = (1:N-1)'; % Plot GCV function. if show==1 semilogy(reg_param,G,'o'), xlabel('k'), ylabel('G(k)') title('GCV function') end % Find minimum [minG,reg_min] = min(G); if show==1 ax = axis; HoldState = ishold; hold on; semilogy(reg_min,minG,'*r',[reg_min,reg_min],[minG/1000,minG],':r') title(['GCV function, minimum at k = ',num2str(reg_min)]) axis(ax); if (~HoldState) hold off end end else error('Illegal method.') end end function G=reggcvfun(lam,s2,beta) % reggcvfun Computes GCV function for reggcv. % Auxiliary function for reggcv. % % Written by Vincent Verdult, May 2004. % Based on Regularization Tools by P. C. Hansen f=lam^2./(s2+lam^2); G=norm((f*ones(1,size(beta,2))).*beta,'fro')^2/(sum(f)^2); end
github
TUDelft-DataDrivenControl/Predictor-Based-Subspace-IDentification-toolbox-master
exls_back.m
.m
Predictor-Based-Subspace-IDentification-toolbox-master/extra/backwards/private/exls_back.m
6,802
utf_8
17f72f64cc45a64fce83e4c308ef12ae
function [VARMAX,Z] = exls_back(Y,Z,p,r,method,tol,reg,opt,VARMAX0) %EXLS Extended Least Squares % [VARMAX,Z] = EXLS(Y,Z,P,R,METHOD,TOL,REG,OPT,VARMAX0) computes the % extended least squares regression for the VARMAX estimation problem % using recursive least squares. This function is intended for DORDVARMAX. % Ivo Houtzager % Delft Center of Systems and Control % Delft University of Technology % The Netherlands, 2010 % assign default values to unspecified parameters if (nargin < 8) || isempty(opt) opt = 'gcv'; end if (nargin < 7) || isempty(reg) reg = 'tikh'; end if (nargin < 6) || isempty(tol) tol = 1e-4; end if (nargin < 5) || isempty(method) method = 'els'; end % if strcmpi(method,'gradient') || strcmpi(method,'grad') % if ~strcmpi(reg,'none') % error('Gradient method does not support regularisation!') % end % end ireg = sqrt(tol); % determine size N = size(Y,2)+p; l = size(Y,1); m = r+2*l; % calculate initial VARMAX solution if nargin < 9 || isempty(VARMAX0) if ~strcmpi(reg,'none') if strcmpi(method,'gradient') || strcmpi(method,'grad') [VARMAX,reg_min] = regress(Y,Z,reg,opt); else VARMAX = zeros(l,size(Z,1)); end else VARMAX = zeros(l,size(Z,1)); end else if ~strcmpi(reg,'none') [~,reg_min] = regress(Y,Z,reg,opt,VARMAX0); end VARMAX = VARMAX0; end cost1 = 1e10; switch lower(method) case 'els' % do the VARMAX whitening iterations PS = ireg; if isscalar('opt') reg_min = opt; else reg_min = 0; end lambda = tol^(1/N); maxit = 10; ok = true; k = 1; PS0 = PS; while ok == true && k <= maxit if ~strcmpi(reg,'none') && ~isscalar('opt') Y1 = Y.*(ones(size(Y,1),1)*lambda.^(length(Y)-1:-1:0)); Z1 = Z.*(ones(size(Z,1),1)*lambda.^(length(Z)-1:-1:0)); [~,reg_min] = regress(Y1,Z1,reg,opt,VARMAX); end PS = PS0; for i = N-p:-1:1 if ~strcmpi(reg,'none') [VARMAX,PS] = rls_ew_track_reg(Z(:,i),Y(:,i),VARMAX,PS,lambda,reg_min); else [VARMAX,PS] = rls_ew_track(Z(:,i),Y(:,i),VARMAX,PS,lambda); end E = Y(:,i) - VARMAX*Z(:,i); if i ~= 1 for j = 1:l Z((l+r)+j,i) = E(j); Z((2:p)*(l+r)+(1:p-1)*l+j,i-1) = Z((1:p-1)*(l+r)+(0:p-2)*l+j,i); end end end % pre-allocate matrices E = Y - VARMAX*Z; % check residue cost = norm(E','fro')^2 + reg_min^2*norm(VARMAX,'fro')^2; if abs(cost1 - cost) <= tol^2*N ok = false; end % store the past and future vectors e = zeros(l,N); e(:,1:N-p) = E; for i = 1:p Z((p-i)*m+r+l+1:(p-i+1)*m,:) = e(:,i:N+i-p-1); end % recalculate forgetting factor k = k + 1; lambda = (lambda^N)^(1/(k*N)); % swap cost1 = cost; end otherwise disp('Unknown method.') end end function [theta,P] = rls_ew_track(z,y,theta,P,lambda) %RLS_EW_TRACK Exponentially Weighted RLS iteration % [THETA,P]=RLS_EW_TRACK(Z,Y,THETA,P,LAMBDA) applies one iteration of % exponentially weighted regularized least-squares problem. In recursive % least-squares, we deal with the issue of an inceasing amount of date Z % and Y. At each iteration, THETA is the solution. The scalar LAMBDA is % called the forgetting factor since past data are exponentially weighted % less heavily than more recent data. % Ivo Houtzager % Delft Center of Systems and Control % The Netherlands, 2010 % Assign default values to unspecified parameters mz = size(z,1); if (nargin < 5) || isempty(lambda) lambda = 1; end if (nargin < 4) || isempty(P) P = zeros(mz); elseif isscalar(P) P = (1/P).*eye(mz); end if (nargin < 3) || isempty(theta) theta = zeros(size(y,1),mz); end % Exponentially-Weighted, Tracking, Regularized, Least-Squares Iteration P = (1/lambda).*(P - P*(z*z')*P./(lambda + z'*P*z)); P = 0.5.*(P+P'); % force symmetric e = y - theta*z; theta = theta + e*z'*P; end % end of function RLS_EW_TRACK function [theta,P] = rls_ew_track_reg(z,y,theta,P,lambda,reg_min) %RLS_EW_TRACK_REG Exponentially Weighted and Regularized RLS iteration % [THETA,P]=RLS_EW_TRACK_REG(Z,Y,THETA,P,LAMBDA,REG) applies one iteration % of exponentially weighted regularized least-squares problem. In % recursive least-squares, we deal with the issue of an inceasing amount % of date Z and Y. At each iteration, THETA is the solution. The scalar % LAMBDA is called the forgetting factor since past data are exponentially % weighted less heavily than more recent data. % Ivo Houtzager % Delft Center of Systems and Control % The Netherlands, 2010 % Assign default values to unspecified parameters mz = size(z,1); if (nargin < 6) || isempty(reg_min) reg_min = 0; end if (nargin < 5) || isempty(lambda) lambda = 1; end if (nargin < 4) || isempty(P) P = zeros(mz); elseif isscalar(P) P = (1/P).*eye(mz); end if (nargin < 3) || isempty(theta) theta = zeros(size(y,1),mz); end % Exponentially-Weighted, Tracking, Regularized, Least-Squares Iteration P = (1/lambda).*(P - P*(z*z')*P./(lambda + z'*P*z)); P = 0.5.*(P+P'); % force symmetric if isscalar(reg_min) opts.SYM = true; opts.POSDEF = true; P1 = linsolve((eye(size(P)) + reg_min^2.*P),P,opts); e = y - theta*z; theta = theta + e*z'*P1; elseif strcmpi(reg_min,'tikh') [U,S,V] = svd(pinv(P)); s = diag(S); YP = (y-theta*z)'; if isscalar(opt) reg_min = opt; elseif strcmpi(opt,'lcurve') reg_min = reglcurve(YP,U,s); elseif strcmpi(opt,'gcv') reg_min = reggcv(YP,U,s); end theta = theta + (V*(diag(s./(s.^2 + reg_min^2)))*U'*YP)'; elseif strcmpi(reg_min,'tsvd') [U,S,V] = svd(pinv(P)); s = diag(S); YP = (y-theta*z)'; if isscalar(opt) k_min = opt; elseif strcmpi(opt,'lcurve') k_min = reglcurve(YP,U,s,'tsvd'); elseif strcmpi(opt,'gcv') k_min = reggcv(YP,U,s,'tsvd'); end theta = theta + (V(:,1:k_min)*diag(1./s(1:k_min))*U(:,1:k_min)'*YP)'; end end % end of function RLS_EW_TRACK
github
TUDelft-DataDrivenControl/Predictor-Based-Subspace-IDentification-toolbox-master
reglcurve.m
.m
Predictor-Based-Subspace-IDentification-toolbox-master/extra/backwards/private/reglcurve.m
9,669
utf_8
4ba1982fb3c44a326be1ff4bec03edef
function reg_c=reglcurve(Y,Vn,Sn,method,show) %REGLCURVE Compute regularization using L-curve criterion. % Determine the regularization parameter for ordkernel % using L-curve criterion. It plots the L-curve and % find its corner. If the regularization method is % 'tsvd' then the Spline Toolbox is needed to determine % the corner. If this toolbox is not available NaN is % returned. % % Syntax: % reg=reglcurve(Y,V,S) % reg=reglcurve(Y,V,S,method,show) % % Input: % Y,V,S Data matrices from lpvkernel or bilkernel. % method Regularization method to be used. % 'Tikh' - Tikhonov regularization (default). % 'tsvd' - Truncated singular value decomposition. % show Display intermediate steps of the algorithm. % % Output: % reg Regularization paramater for the kernel % subspace identification method of ordkernel. % Written by Vincent Verdult, May 2004. % Based on Regularization Tools by P. C. Hansen % default method if nargin<4 method='Tikh'; end if nargin<5 show=0; end if size(Y,1)~=size(Vn,1) error('The number of rows in Y must equal the number of rows in V.') end if size(Vn,1)~=size(Vn,2) error('V must be a square matrix.') end if size(Sn,2)~=1 error('S must be a column vector.') end if size(Vn,1)~=size(Sn,1) error('The number of rows in S must equal the number of rows in V.') end % Initialization. N = size(Sn,1); s=sqrt(Sn); beta = Vn'*Y; xi = diag(1./s)*beta; %%%%%%%%%%%%%%%% % Tikhonov regularization if (strncmp(method,'Tikh',4) || strncmp(method,'tikh',4)) SkipCorner=0; txt = 'Tikh.'; marker='-'; npoints = 200; % Number of points on the curve. smin_ratio = 16*eps; % Smallest regularization parameter. eta = zeros(npoints,1); rho = zeros(npoints,1); reg_param = zeros(npoints,1); reg_param(npoints) = max([s(N),s(1)*smin_ratio]); ratio = (s(1)/reg_param(npoints))^(1/(npoints-1)); if show==1 disp('Calculation points on L-curve') end for i=npoints-1:-1:1 reg_param(i) = ratio*reg_param(i+1); end n=size(xi,2); for i=1:npoints f = Sn./(Sn + reg_param(i)^2); eta(i) = norm((f*ones(1,n)).*xi,'fro'); rho(i) = norm(((1-f)*ones(1,n)).*beta,'fro'); end % locate corner if show==1 disp('Calculating curvature of L-curve') end % The L-curve is differentiable; computation of curvature in % log-log scale is easy. % Compute g = - curvature of L-curve. g = reglcfun(reg_param,Sn,beta,xi); % Locate the corner. If the curvature is negative everywhere, % then define the leftmost point of the L-curve as the corner. if show==1 disp('Searching for corner in L-curve') OPT=optimset('Display','iter'); else OPT=optimset('Display','off'); end [gmin,gi] = min(g); reg_c = fminbnd(@reglcfun,... reg_param(min(gi+1,length(g))),reg_param(max(gi-1,1)),... OPT,Sn,beta,xi); % Minimizer. kappa_max = - reglcfun(reg_c,Sn,beta,xi); % Maximum curvature. if (kappa_max < 0) lr = length(rho); reg_c = reg_param(lr); rho_c = rho(lr); eta_c = eta(lr); else f = Sn./(Sn + reg_c^2); eta_c = norm((f*ones(1,n)).*xi,'fro'); rho_c = norm(((1-f)*ones(1,n)).*beta,'fro'); end %%%%%%%%%%%%%%%% % Truncated SVD elseif (strncmp(method,'tsvd',4) || strncmp(method,'TSVD',4)) % spline toolbox needed for determination of the corner. SkipCorner = exist('splines','dir')~=7; txt = 'TSVD'; marker='o'; eta = zeros(N,1); rho = zeros(N,1); eta(1) = sum(xi(1,:).^2); for k=2:N eta(k) = eta(k-1) + sum(xi(k,:).^2); end eta = sqrt(eta); rho(N) = eps^2; for k=N-1:-1:1 rho(k) = rho(k+1) + sum(beta(k+1,:).^2); end rho = sqrt(rho); reg_param = (1:N)'; % Determine corner using Splines if (SkipCorner) reg_c = NaN; else % The L-curve is discrete and may include unwanted fine-grained % corners. Use local smoothing, followed by fitting a 2-D spline % curve to the smoothed discrete L-curve. % Set default parameters for treatment of discrete L-curve. deg = 2; % Degree of local smooting polynomial. q = 2; % Half-width of local smoothing interval. order = 4; % Order of fitting 2-D spline curve. % Neglect singular values less than s_thr. s_thr = eps; index = find(s > s_thr); rho_t = rho(index); eta_t = eta(index); reg_param_t = reg_param(index); % Convert to logarithms. lr = length(rho_t); lrho = log(rho_t); leta = log(eta_t); slrho = lrho; sleta = leta; % For all interior points k = q+1:length(rho)-q-1 on the discrete % L-curve, perform local smoothing with a polynomial of degree deg % to the points k-q:k+q. v = (-q:q)'; A = zeros(2*q+1,deg+1); A(:,1) = ones(length(v),1); for j = 2:deg+1 A(:,j) = A(:,j-1).*v; end for k = q+1:lr-q-1 cr = A\lrho(k+v); slrho(k) = cr(1); ce = A\leta(k+v); sleta(k) = ce(1); end % Fit a 2-D spline curve to the smoothed discrete L-curve. sp = spmak(1:lr+order,[slrho';sleta']); pp = ppbrk(sp2pp(sp),[4,lr+1]); % Extract abscissa and ordinate splines and differentiate them. % Compute as many function values as default in spleval. P = spleval(pp); dpp = fnder(pp); D = spleval(dpp); ddpp = fnder(pp,2); DD = spleval(ddpp); ppx = P(1,:); ppy = P(2,:); dppx = D(1,:); dppy = D(2,:); ddppx = DD(1,:); ddppy = DD(2,:); % Compute the corner of the discretized .spline curve via max. curvature. % No need to refine this corner, since the final regularization % parameter is discrete anyway. % Define curvature = 0 where both dppx and dppy are zero. k1 = dppx.*ddppy - ddppx.*dppy; k2 = (dppx.^2 + dppy.^2).^(1.5); I_nz = find(k2 ~= 0); kappa = zeros(1,length(dppx)); kappa(I_nz) = -k1(I_nz)./k2(I_nz); [kmax,ikmax] = max(kappa); x_corner = ppx(ikmax); y_corner = ppy(ikmax); % Locate the point on the discrete L-curve which is closest to the % corner of the spline curve. Prefer a point below and to the % left of the corner. If the curvature is negative everywhere, % then define the leftmost point of the L-curve as the corner. if (kmax < 0) reg_c = reg_param_t(lr); rho_c = rho_t(lr); eta_c = eta_t(lr); else index = find(lrho < x_corner & leta < y_corner); if ~isempty(index) [dummy,rpi] = min((lrho(index)-x_corner).^2 + (leta(index)-y_corner).^2); rpi = index(rpi); else [dummy,rpi] = min((lrho-x_corner).^2 + (leta-y_corner).^2); end reg_c = reg_param_t(rpi); rho_c = rho_t(rpi); eta_c = eta_t(rpi); end end else error('Illegal method') end %%%%%%%%%%%%%%%% % Plot if show==1 N=length(rho); loglog(rho(2:end-1),eta(2:end-1)) ax = axis; ni = round(N/10); if (max(eta)/min(eta) > 10 || max(rho)/min(rho) > 10) loglog(rho,eta,marker,rho(ni:ni:N),eta(ni:ni:N),'x') else plot(rho,eta,marker,rho(ni:ni:N),eta(ni:ni:N),'x') end HoldState = ishold; hold on; for k = ni:ni:N text(rho(k),eta(k),num2str(reg_param(k))); end if ~(SkipCorner) loglog([min(rho)/100,rho_c],[eta_c,eta_c],':r',... [rho_c,rho_c],[min(eta)/100,eta_c],':r') title(['L-curve, ',txt,' corner at ',num2str(reg_c)]); else title('L-curve') end axis(ax) if (~HoldState) hold off end xlabel('residual norm || A x - b ||_2') ylabel('solution norm || x ||_2') end end function g = reglcfun(lambda,Sn,beta,xi) % reglcfun Computes L-curve for reglcurve. % Auxiliary function for reglcurve. % % Written by Vincent Verdult, May 2004. % Based on Regularization Tools by P. C. Hansen % Initialization. L=size(lambda,1); n=size(xi,2); phi = zeros(L,1); dphi = zeros(L,1); psi = zeros(L,1); dpsi = zeros(L,1); eta = zeros(L,1); rho = zeros(L,1); % Compute some intermediate quantities. for i = 1:L f = Sn./(Sn + lambda(i)^2); cf = 1 - f; eta(i) = norm((f*ones(1,n)).*xi,'fro'); rho(i) = norm((cf*ones(1,n)).*beta,'fro'); f1 = -2*f.*cf/lambda(i); f2 = -f1.*(3-4*f)/lambda(i); phi(i) = sum(f.*f1.*sum(xi.^2,2)); psi(i) = sum(cf.*f1.*sum(beta.^2,2)); dphi(i) = sum((f1.^2 + f.*f2).*sum(xi.^2,2)); dpsi(i) = sum((-f1.^2 + cf.*f2).*sum(beta.^2,2)); end % Now compute the first and second derivatives of eta and rho % with respect to lambda; deta = phi./eta; drho = -psi./rho; ddeta = dphi./eta - deta.*(deta./eta); ddrho = -dpsi./rho - drho.*(drho./rho); % Convert to derivatives of log(eta) and log(rho). dlogeta = deta./eta; dlogrho = drho./rho; ddlogeta = ddeta./eta - (dlogeta).^2; ddlogrho = ddrho./rho - (dlogrho).^2; % Let g = curvature. g = - (dlogrho.*ddlogeta - ddlogrho.*dlogeta)./... (dlogrho.^2 + dlogeta.^2).^(1.5); end
github
TUDelft-DataDrivenControl/Predictor-Based-Subspace-IDentification-toolbox-master
reggcv.m
.m
Predictor-Based-Subspace-IDentification-toolbox-master/extra/greybox/private/reggcv.m
4,183
utf_8
96e102b790fbfa5f01c26445d60a36fc
function reg_min=reggcv(Y,Vn,Sn,method,show) %REGGCV Compute regularization using generalized cross validation. % Determine the regularization parameter for ordkernel % using Generalized Cross-Validation (GCV). It plots the % GCV function as a function of the regularization % parameter and finds its minimum. % % Syntax: % reg=reggcv(Y,V,S) % reg=reggcv(Y,V,S,method,show) % % Input: % Y,V,S Data matrices from lpvkernel or bilkernel. % method Regularization method to be used. % 'Tikh' - Tikhonov regularization (default). % 'tsvd' - Truncated singular value decomposition. % show Display intermediate steps of the algorithm. % % Output: % reg Regularization paramater for the kernel % subspace identification method of ordkernel. % Written by Vincent Verdult, May 2004. % Based on Regularization Tools by P. C. Hansen % default method if nargin<4 method='Tikh'; end if nargin<5 show=0; end if size(Y,1)~=size(Vn,1) error('The number of rows in Y must equal the number of rows in V.') end if size(Vn,1)~=size(Vn,2) error('V must be a square matrix.') end if size(Sn,2)~=1 error('S must be a column vector.') end if size(Vn,1)~=size(Sn,1) error('The number of rows in S must equal the number of rows in V.') end % Initialization. N = size(Sn,1); beta = Vn'*Y; % Tikhonov regularization if (strncmp(method,'Tikh',4) || strncmp(method,'tikh',4)) npoints = 200; % Number of points on the curve. smin_ratio = 16*eps; % Smallest regularization parameter. reg_param = zeros(npoints,1); G = zeros(npoints,1); s = sqrt(Sn); reg_param(npoints) = max([s(N),s(1)*smin_ratio]); ratio = (s(1)/reg_param(npoints))^(1/(npoints-1)); for i=npoints-1:-1:1 reg_param(i) = ratio*reg_param(i+1); end if show==1 disp('Calculating GCV curve.') end % Vector of GCV-function values. for i=1:npoints G(i) = reggcvfun(reg_param(i),Sn,beta); end % Plot GCV function. if show==1 loglog(reg_param,G,'-'), xlabel('\lambda'), ylabel('G(\lambda)') title('GCV function') end % Find minimum if show==1 disp('Searching GCV minimum') OPT=optimset('Display','iter'); else OPT=optimset('Display','off'); end [minG,minGi] = min(G); % Initial guess. reg_min = fminbnd(@reggcvfun,... reg_param(min(minGi+1,npoints)),... reg_param(max(minGi-1,1)),OPT,Sn,beta); % Minimizer. minG = reggcvfun(reg_min,Sn,beta); % Minimum of GCV function. if show==1 ax = axis; HoldState = ishold; hold on; loglog(reg_min,minG,'*r',[reg_min,reg_min],[minG/1000,minG],':r') title(['GCV function, minimum at \lambda = ',num2str(reg_min)]) axis(ax) if (~HoldState) hold off end end % Truncated SVD elseif (strncmp(method,'tsvd',4) || strncmp(method,'TSVD',4)) rho=zeros(1,N-1); G=zeros(1,N-1); rho(N-1) = sum(beta(N,:).^2); G(N-1) = rho(N-1); for k=N-2:-1:1 rho(k) = rho(k+1) + sum(beta(k+1,:).^2); G(k) = rho(k)/((N - k)^2); end reg_param = (1:N-1)'; % Plot GCV function. if show==1 semilogy(reg_param,G,'o'), xlabel('k'), ylabel('G(k)') title('GCV function') end % Find minimum [minG,reg_min] = min(G); if show==1 ax = axis; HoldState = ishold; hold on; semilogy(reg_min,minG,'*r',[reg_min,reg_min],[minG/1000,minG],':r') title(['GCV function, minimum at k = ',num2str(reg_min)]) axis(ax); if (~HoldState) hold off end end else error('Illegal method.') end end function G=reggcvfun(lam,s2,beta) % reggcvfun Computes GCV function for reggcv. % Auxiliary function for reggcv. % % Written by Vincent Verdult, May 2004. % Based on Regularization Tools by P. C. Hansen f=lam^2./(s2+lam^2); G=norm((f*ones(1,size(beta,2))).*beta,'fro')^2/(sum(f)^2); end
github
TUDelft-DataDrivenControl/Predictor-Based-Subspace-IDentification-toolbox-master
reglcurve.m
.m
Predictor-Based-Subspace-IDentification-toolbox-master/extra/greybox/private/reglcurve.m
9,669
utf_8
4ba1982fb3c44a326be1ff4bec03edef
function reg_c=reglcurve(Y,Vn,Sn,method,show) %REGLCURVE Compute regularization using L-curve criterion. % Determine the regularization parameter for ordkernel % using L-curve criterion. It plots the L-curve and % find its corner. If the regularization method is % 'tsvd' then the Spline Toolbox is needed to determine % the corner. If this toolbox is not available NaN is % returned. % % Syntax: % reg=reglcurve(Y,V,S) % reg=reglcurve(Y,V,S,method,show) % % Input: % Y,V,S Data matrices from lpvkernel or bilkernel. % method Regularization method to be used. % 'Tikh' - Tikhonov regularization (default). % 'tsvd' - Truncated singular value decomposition. % show Display intermediate steps of the algorithm. % % Output: % reg Regularization paramater for the kernel % subspace identification method of ordkernel. % Written by Vincent Verdult, May 2004. % Based on Regularization Tools by P. C. Hansen % default method if nargin<4 method='Tikh'; end if nargin<5 show=0; end if size(Y,1)~=size(Vn,1) error('The number of rows in Y must equal the number of rows in V.') end if size(Vn,1)~=size(Vn,2) error('V must be a square matrix.') end if size(Sn,2)~=1 error('S must be a column vector.') end if size(Vn,1)~=size(Sn,1) error('The number of rows in S must equal the number of rows in V.') end % Initialization. N = size(Sn,1); s=sqrt(Sn); beta = Vn'*Y; xi = diag(1./s)*beta; %%%%%%%%%%%%%%%% % Tikhonov regularization if (strncmp(method,'Tikh',4) || strncmp(method,'tikh',4)) SkipCorner=0; txt = 'Tikh.'; marker='-'; npoints = 200; % Number of points on the curve. smin_ratio = 16*eps; % Smallest regularization parameter. eta = zeros(npoints,1); rho = zeros(npoints,1); reg_param = zeros(npoints,1); reg_param(npoints) = max([s(N),s(1)*smin_ratio]); ratio = (s(1)/reg_param(npoints))^(1/(npoints-1)); if show==1 disp('Calculation points on L-curve') end for i=npoints-1:-1:1 reg_param(i) = ratio*reg_param(i+1); end n=size(xi,2); for i=1:npoints f = Sn./(Sn + reg_param(i)^2); eta(i) = norm((f*ones(1,n)).*xi,'fro'); rho(i) = norm(((1-f)*ones(1,n)).*beta,'fro'); end % locate corner if show==1 disp('Calculating curvature of L-curve') end % The L-curve is differentiable; computation of curvature in % log-log scale is easy. % Compute g = - curvature of L-curve. g = reglcfun(reg_param,Sn,beta,xi); % Locate the corner. If the curvature is negative everywhere, % then define the leftmost point of the L-curve as the corner. if show==1 disp('Searching for corner in L-curve') OPT=optimset('Display','iter'); else OPT=optimset('Display','off'); end [gmin,gi] = min(g); reg_c = fminbnd(@reglcfun,... reg_param(min(gi+1,length(g))),reg_param(max(gi-1,1)),... OPT,Sn,beta,xi); % Minimizer. kappa_max = - reglcfun(reg_c,Sn,beta,xi); % Maximum curvature. if (kappa_max < 0) lr = length(rho); reg_c = reg_param(lr); rho_c = rho(lr); eta_c = eta(lr); else f = Sn./(Sn + reg_c^2); eta_c = norm((f*ones(1,n)).*xi,'fro'); rho_c = norm(((1-f)*ones(1,n)).*beta,'fro'); end %%%%%%%%%%%%%%%% % Truncated SVD elseif (strncmp(method,'tsvd',4) || strncmp(method,'TSVD',4)) % spline toolbox needed for determination of the corner. SkipCorner = exist('splines','dir')~=7; txt = 'TSVD'; marker='o'; eta = zeros(N,1); rho = zeros(N,1); eta(1) = sum(xi(1,:).^2); for k=2:N eta(k) = eta(k-1) + sum(xi(k,:).^2); end eta = sqrt(eta); rho(N) = eps^2; for k=N-1:-1:1 rho(k) = rho(k+1) + sum(beta(k+1,:).^2); end rho = sqrt(rho); reg_param = (1:N)'; % Determine corner using Splines if (SkipCorner) reg_c = NaN; else % The L-curve is discrete and may include unwanted fine-grained % corners. Use local smoothing, followed by fitting a 2-D spline % curve to the smoothed discrete L-curve. % Set default parameters for treatment of discrete L-curve. deg = 2; % Degree of local smooting polynomial. q = 2; % Half-width of local smoothing interval. order = 4; % Order of fitting 2-D spline curve. % Neglect singular values less than s_thr. s_thr = eps; index = find(s > s_thr); rho_t = rho(index); eta_t = eta(index); reg_param_t = reg_param(index); % Convert to logarithms. lr = length(rho_t); lrho = log(rho_t); leta = log(eta_t); slrho = lrho; sleta = leta; % For all interior points k = q+1:length(rho)-q-1 on the discrete % L-curve, perform local smoothing with a polynomial of degree deg % to the points k-q:k+q. v = (-q:q)'; A = zeros(2*q+1,deg+1); A(:,1) = ones(length(v),1); for j = 2:deg+1 A(:,j) = A(:,j-1).*v; end for k = q+1:lr-q-1 cr = A\lrho(k+v); slrho(k) = cr(1); ce = A\leta(k+v); sleta(k) = ce(1); end % Fit a 2-D spline curve to the smoothed discrete L-curve. sp = spmak(1:lr+order,[slrho';sleta']); pp = ppbrk(sp2pp(sp),[4,lr+1]); % Extract abscissa and ordinate splines and differentiate them. % Compute as many function values as default in spleval. P = spleval(pp); dpp = fnder(pp); D = spleval(dpp); ddpp = fnder(pp,2); DD = spleval(ddpp); ppx = P(1,:); ppy = P(2,:); dppx = D(1,:); dppy = D(2,:); ddppx = DD(1,:); ddppy = DD(2,:); % Compute the corner of the discretized .spline curve via max. curvature. % No need to refine this corner, since the final regularization % parameter is discrete anyway. % Define curvature = 0 where both dppx and dppy are zero. k1 = dppx.*ddppy - ddppx.*dppy; k2 = (dppx.^2 + dppy.^2).^(1.5); I_nz = find(k2 ~= 0); kappa = zeros(1,length(dppx)); kappa(I_nz) = -k1(I_nz)./k2(I_nz); [kmax,ikmax] = max(kappa); x_corner = ppx(ikmax); y_corner = ppy(ikmax); % Locate the point on the discrete L-curve which is closest to the % corner of the spline curve. Prefer a point below and to the % left of the corner. If the curvature is negative everywhere, % then define the leftmost point of the L-curve as the corner. if (kmax < 0) reg_c = reg_param_t(lr); rho_c = rho_t(lr); eta_c = eta_t(lr); else index = find(lrho < x_corner & leta < y_corner); if ~isempty(index) [dummy,rpi] = min((lrho(index)-x_corner).^2 + (leta(index)-y_corner).^2); rpi = index(rpi); else [dummy,rpi] = min((lrho-x_corner).^2 + (leta-y_corner).^2); end reg_c = reg_param_t(rpi); rho_c = rho_t(rpi); eta_c = eta_t(rpi); end end else error('Illegal method') end %%%%%%%%%%%%%%%% % Plot if show==1 N=length(rho); loglog(rho(2:end-1),eta(2:end-1)) ax = axis; ni = round(N/10); if (max(eta)/min(eta) > 10 || max(rho)/min(rho) > 10) loglog(rho,eta,marker,rho(ni:ni:N),eta(ni:ni:N),'x') else plot(rho,eta,marker,rho(ni:ni:N),eta(ni:ni:N),'x') end HoldState = ishold; hold on; for k = ni:ni:N text(rho(k),eta(k),num2str(reg_param(k))); end if ~(SkipCorner) loglog([min(rho)/100,rho_c],[eta_c,eta_c],':r',... [rho_c,rho_c],[min(eta)/100,eta_c],':r') title(['L-curve, ',txt,' corner at ',num2str(reg_c)]); else title('L-curve') end axis(ax) if (~HoldState) hold off end xlabel('residual norm || A x - b ||_2') ylabel('solution norm || x ||_2') end end function g = reglcfun(lambda,Sn,beta,xi) % reglcfun Computes L-curve for reglcurve. % Auxiliary function for reglcurve. % % Written by Vincent Verdult, May 2004. % Based on Regularization Tools by P. C. Hansen % Initialization. L=size(lambda,1); n=size(xi,2); phi = zeros(L,1); dphi = zeros(L,1); psi = zeros(L,1); dpsi = zeros(L,1); eta = zeros(L,1); rho = zeros(L,1); % Compute some intermediate quantities. for i = 1:L f = Sn./(Sn + lambda(i)^2); cf = 1 - f; eta(i) = norm((f*ones(1,n)).*xi,'fro'); rho(i) = norm((cf*ones(1,n)).*beta,'fro'); f1 = -2*f.*cf/lambda(i); f2 = -f1.*(3-4*f)/lambda(i); phi(i) = sum(f.*f1.*sum(xi.^2,2)); psi(i) = sum(cf.*f1.*sum(beta.^2,2)); dphi(i) = sum((f1.^2 + f.*f2).*sum(xi.^2,2)); dpsi(i) = sum((-f1.^2 + cf.*f2).*sum(beta.^2,2)); end % Now compute the first and second derivatives of eta and rho % with respect to lambda; deta = phi./eta; drho = -psi./rho; ddeta = dphi./eta - deta.*(deta./eta); ddrho = -dpsi./rho - drho.*(drho./rho); % Convert to derivatives of log(eta) and log(rho). dlogeta = deta./eta; dlogrho = drho./rho; ddlogeta = ddeta./eta - (dlogeta).^2; ddlogrho = ddrho./rho - (dlogrho).^2; % Let g = curvature. g = - (dlogrho.*ddlogeta - ddlogrho.*dlogeta)./... (dlogrho.^2 + dlogeta.^2).^(1.5); end
github
TUDelft-DataDrivenControl/Predictor-Based-Subspace-IDentification-toolbox-master
sfun_xygraph.m
.m
Predictor-Based-Subspace-IDentification-toolbox-master/simulink/sfun_xygraph.m
13,103
utf_8
5cf0dd62ab47b4f64b3e2f897ecaee5d
function [sys, x0, str, ts, simStateCompliance] = sfunxy_new(t,x,u,flag,ax,varargin) %SFUNXY S-function that acts as an X-Y scope using MATLAB plotting functions. % This M-file is designed to be used in a Simulink S-function block. % It draws a line from the previous input point, which is stored using % discrete states, and the current point. It then stores the current % point for use in the next invocation. % % See also SFUNXYS, LORENZS. % Copyright 1990-2008 The MathWorks, Inc. % $Revision: 1.38.2.9 $ % Andrew Grace 5-30-91. % Revised Wes Wang 4-28-93, 8-17-93, 12-15-93 % Revised Craig Santos 10-28-96 % Store the block handle and check if it's valid blockHandle = gcbh; IsValidBlock(blockHandle, flag); switch flag %%%%%%%%%%%%%%%%%% % Initialization % %%%%%%%%%%%%%%%%%% case 0 [sys,x0,str,ts,simStateCompliance] = mdlInitializeSizes(ax,varargin{:}); SetBlockCallbacks(blockHandle); %%%%%%%%%% % Update % %%%%%%%%%% case 2 sys = mdlUpdate(t,x,u,flag,ax,blockHandle,varargin{:}); %%%%%%%%% % Start % %%%%%%%%% case 'Start' LocalBlockStartFcn(blockHandle) %%%%%%%% % Stop % %%%%%%%% case 'Stop' LocalBlockStopFcn(blockHandle) %%%%%%%%%%%%%% % NameChange % %%%%%%%%%%%%%% case 'NameChange' LocalBlockNameChangeFcn(blockHandle) %%%%%%%%%%%%%%%%%%%%%%%% % CopyBlock, LoadBlock % %%%%%%%%%%%%%%%%%%%%%%%% case { 'CopyBlock', 'LoadBlock' } LocalBlockLoadCopyFcn(blockHandle) %%%%%%%%%%%%%%% % DeleteBlock % %%%%%%%%%%%%%%% case 'DeleteBlock' LocalBlockDeleteFcn(blockHandle) %%%%%%%%%%%%%%%% % DeleteFigure % %%%%%%%%%%%%%%%% case 'DeleteFigure' LocalFigureDeleteFcn %%%%%%%%%%%%%%%% % Unused flags % %%%%%%%%%%%%%%%% case { 3, 9 } sys = []; %%%%%%%%%%%%%%%%%%%% % Unexpected flags % %%%%%%%%%%%%%%%%%%%% otherwise if ischar(flag), DAStudio.error('Simulink:blocks:unhandledFlag', flag); else DAStudio.error('Simulink:blocks:unhandledFlag', num2str(flag)); end end % end sfunxy % %============================================================================= % mdlInitializeSizes % Return the sizes, initial conditions, and sample times for the S-function. %============================================================================= % function [sys,x0,str,ts,simStateCompliance] = mdlInitializeSizes(ax,varargin) if length (ax)~=4 DAStudio.error('Simulink:blocks:axisLimitsMustBeDefined'); end sizes = simsizes; sizes.NumContStates = 0; sizes.NumDiscStates = 0; sizes.NumOutputs = 0; sizes.NumInputs = 3; sizes.DirFeedthrough = 0; sizes.NumSampleTimes = 1; sys = simsizes(sizes); x0 = []; str = []; % % initialize the array of sample times, note that in earlier % versions of this scope, a sample time was not one of the input % arguments, the varargs checks for this and if not present, assigns % the sample time to -1 (inherited) % if ~isempty(varargin) > 0 ts = [varargin{1} 0]; else ts = [-1 0]; end % specify that the simState for this s-function is same as the default simStateCompliance = 'DefaultSimState'; % end mdlInitializeSizes % %============================================================================= % mdlUpdate % Handle discrete state updates, sample time hits, and major time step % requirements. %============================================================================= % function sys=mdlUpdate(t,x,u,flag,ax,block,varargin)%#ok % % always return empty, there are no states... % sys = []; % % Locate the figure window associated with this block. If it's not a valid % handle (it may have been closed by the user), then return. % FigHandle=GetSfunXYFigure(block); if ~ishandle(FigHandle), return end % % Get UserData of the figure. % ud = get(FigHandle,'UserData'); persistent lastU3; reset = false; if isempty(lastU3) lastU3 = u(3); else if (u(3)-lastU3 > 0.5) reset = true; end lastU3 = u(3); end if reset LocalBlockStartFcn(gcbh) end if reset || isempty(ud.XData), x_data = [u(1) u(1)]; y_data = [u(2) u(2)]; else x_data = [ud.XData(end) u(1)]; y_data = [ud.YData(end) u(2)]; end % plot the input lines set(ud.XYAxes, ... 'Xlim', ax(1:2),... 'Ylim', ax(3:4)); set(ud.XYLine,... 'Xdata',x_data,... 'Ydata',y_data); set(ud.XYTitle,'String','X Y Plot'); set(FigHandle,'Color',get(FigHandle,'Color')); % % update the X/Y stored data points ud.XData(end+1) = u(1); ud.YData(end+1) = u(2); set(FigHandle,'UserData',ud); drawnow; % end mdlUpdate % %============================================================================= % LocalBlockStartFcn % Function that is called when the simulation starts. Initialize the % XY Graph scope figure. %============================================================================= % function LocalBlockStartFcn(block) % % get the figure associated with this block, create a figure if it doesn't % exist % FigHandle = GetSfunXYFigure(block); if ~ishandle(FigHandle), FigHandle = CreateSfunXYFigure(block); end ud = get(FigHandle,'UserData'); set(ud.XYLine,'Erasemode','normal'); set(ud.XYLine,'XData',[],'YData',[]); set(ud.XYLine,'XData',0,'YData',0,'Erasemode','none'); ud.XData = []; ud.YData = []; set(FigHandle,'UserData',ud); % end LocalBlockStartFcn % %============================================================================= % LocalBlockStopFcn % At the end of the simulation, set the line's X and Y data to contain % the complete set of points that were acquire during the simulation. % Recall that during the simulation, the lines are only small segments from % the last time step to the current one. %============================================================================= % function LocalBlockStopFcn(block) FigHandle=GetSfunXYFigure(block); if ishandle(FigHandle), % % Get UserData of the figure. % ud = get(FigHandle,'UserData'); set(ud.XYLine,... 'Xdata',ud.XData,... 'Ydata',ud.YData,... 'LineStyle','-'); end set(0,'ShowHiddenHandles','Off') % end LocalBlockStopFcn % %============================================================================= % LocalBlockNameChangeFcn % Function that handles name changes on the Graph scope block. %============================================================================= % function LocalBlockNameChangeFcn(block) % % get the figure associated with this block, if it's valid, change % the name of the figure % FigHandle = GetSfunXYFigure(block); if ishandle(FigHandle), set(FigHandle,'Name',BlockFigureTitle(block)); end % end LocalBlockNameChangeFcn % %============================================================================= % LocalBlockLoadCopyFcn % This is the XYGraph block's LoadFcn and CopyFcn. Initialize the block's % UserData such that a figure is not associated with the block. %============================================================================= % function LocalBlockLoadCopyFcn(block) SetSfunXYFigure(block,-1); % end LocalBlockLoadCopyFcn % %============================================================================= % LocalBlockDeleteFcn % This is the XY Graph block'DeleteFcn. Delete the block's figure window, % if present, upon deletion of the block. %============================================================================= % function LocalBlockDeleteFcn(block) % % Get the figure handle associated with the block, if it exists, delete % the figure. % FigHandle=GetSfunXYFigure(block); if ishandle(FigHandle), delete(FigHandle); SetSfunXYFigure(block,-1); end % end LocalBlockDeleteFcn % %============================================================================= % LocalFigureDeleteFcn % This is the XY Graph figure window's DeleteFcn. The figure window is % being deleted, update the XY Graph block's UserData to reflect the change. %============================================================================= % function LocalFigureDeleteFcn % % Get the block associated with this figure and set it's figure to -1 % ud=get(gcbf,'UserData'); SetSfunXYFigure(ud.Block,-1) % end LocalFigureDeleteFcn % %============================================================================= % GetSfunXYFigure % Retrieves the figure window associated with this S-function XY Graph block % from the block's parent subsystem's UserData. %============================================================================= % function FigHandle=GetSfunXYFigure(block) if strcmp(get_param(block,'BlockType'),'S-Function'), block=get_param(block,'Parent'); end FigHandle=get_param(block,'UserData'); if isempty(FigHandle), FigHandle=-1; end % end GetSfunXYFigure % %============================================================================= % SetSfunXYFigure % Stores the figure window associated with this S-function XY Graph block % in the block's parent subsystem's UserData. %============================================================================= % function SetSfunXYFigure(block,FigHandle) if strcmp(get_param(bdroot,'BlockDiagramType'),'model'), if strcmp(get_param(block,'BlockType'),'S-Function'), block=get_param(block,'Parent'); end set_param(block,'UserData',FigHandle); end % end SetSfunXYFigure % %============================================================================= % CreateSfunXYFigure % Creates the figure window associated with this S-function XY Graph block. %============================================================================= % function FigHandle=CreateSfunXYFigure(block) % % the figure doesn't exist, create one % screenLoc = get(0,'ScreenSize'); if screenLoc(1) < 0 left = -screenLoc(1) + 100; else left = 100; end if screenLoc(2) < 0 bottom = -screenLoc(2) + 100; else bottom = 100; end FigHandle = figure('Units', 'pixel',... 'Position', [left bottom 400 300],... 'Name', BlockFigureTitle(block),... 'Tag', 'SIMULINK_XYGRAPH_FIGURE',... 'NumberTitle', 'off',... 'IntegerHandle', 'off',... 'Toolbar', 'none',... 'Menubar', 'none',... 'DeleteFcn', 'sfunxy([],[],[],''DeleteFigure'')'); % % store the block's handle in the figure's UserData % ud.Block=block; % % create various objects in the figure % ud.XYAxes = axes; ud.XYLine = plot(0,0,'EraseMode','None'); ud.XYXlabel = xlabel('X Axis'); ud.XYYlabel = ylabel('Y Axis'); ud.XYTitle = get(ud.XYAxes,'Title'); ud.XData = []; ud.YData = []; % % Associate the figure with the block, and set the figure's UserData. % SetSfunXYFigure(block,FigHandle); set(FigHandle,'HandleVisibility','callback','UserData',ud); % end CreateSfunXYFigure % %============================================================================= % BlockFigureTitle % String to display for figure window title %============================================================================= % function title = BlockFigureTitle(block) iotype = get_param(block,'iotype'); if strcmp(iotype,'viewer') title = viewertitle(block,false); else title = get_param(block,'Name'); end %end BlockFigureTitle % %============================================================================= % IsValidBlock % Check if this is a valid block %============================================================================= % function IsValidBlock(block, flag) if strcmp(get_param(block,'BlockType'),'S-Function'), thisBlock = get_param(block,'Parent'); else thisBlock = block; end if(~strcmp(flag,'DeleteFigure')) if(~strcmp(get_param(thisBlock,'MaskType'), 'XY scope.')) DAStudio.error('Simulink:blocks:invalidBlock'); end end %end IsValidBlock % %============================================================================= % SetBlockCallbacks % This sets the callbacks of the block if it is not a reference. %============================================================================= % function SetBlockCallbacks(block) % % the actual source of the block is the parent subsystem % block=get_param(block,'Parent'); % % if the block isn't linked, issue a warning, and then set the callbacks % for the block so that it has the proper operation % if strcmp(get_param(block,'LinkStatus'),'none'), warnmsg=sprintf(['The XY Graph scope ''%s'' should be replaced with a ' ... 'new version from the Simulink block library'],... block); warning(warnmsg);%#ok callbacks={ 'CopyFcn', 'sfunxy([],[],[],''CopyBlock'')' ; 'DeleteFcn', 'sfunxy([],[],[],''DeleteBlock'')' ; 'LoadFcn', 'sfunxy([],[],[],''LoadBlock'')' ; 'StartFcn', 'sfunxy([],[],[],''Start'')' ; 'StopFcn' 'sfunxy([],[],[],''Stop'')' 'NameChangeFcn', 'sfunxy([],[],[],''NameChange'')' ; }; for i=1:length(callbacks), if ~strcmp(get_param(block,callbacks{i,1}),callbacks{i,2}), set_param(block,callbacks{i,1},callbacks{i,2}) end end end % end SetBlockCallbacks
github
misztal/GRIT-master
meshdemond.m
.m
GRIT-master/UTILITIES/meshing/distmesh/meshdemond.m
1,036
utf_8
1610b2dc0c78ee32ea73e9a715f3bb47
function meshdemond %MESHDEMOND distmeshnd examples. % Copyright (C) 2004-2012 Per-Olof Persson. See COPYRIGHT.TXT for details. rand('state',1); % Always the same results set(gcf,'rend','opengl'); disp('(9) 3-D Unit ball') fd=inline('sqrt(sum(p.^2,2))-1','p'); [p,t]=distmeshnd(fd,@huniform,0.2,[-1,-1,-1;1,1,1],[]); post(p,t) disp('(10) Cylinder with hole') [p,t]=distmeshnd(@fd10,@fh10,0.1,[-1,-1,-1;1,1,1],[]); post(p,t) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function post(p,t) disp(sprintf(' (press any key)')) disp(' ') pause %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function d=fd10(p) r=sqrt(p(:,1).^2+p(:,2).^2); z=p(:,3); d1=r-1; d2=z-1; d3=-z-1; d4=sqrt(d1.^2+d2.^2); d5=sqrt(d1.^2+d3.^2); d=dintersect(dintersect(d1,d2),d3); ix=d1>0 & d2>0; d(ix)=d4(ix); ix=d1>0 & d3>0; d(ix)=d5(ix); d=ddiff(d,dsphere(p,0,0,0,0.5)); function h=fh10(p) h1=4*sqrt(sum(p.^2,2))-1; h=min(h1,2);
github
cwkx/IGAC-master
objwrite.m
.m
IGAC-master/wrappers/matlab/lib/objwrite.m
7,931
utf_8
75fc005aa03085efb4f12d8879670ec6
function objwrite(OBJ,fullfilename) % Write objects to a Wavefront OBJ file % % write_wobj(OBJ,filename); % % OBJ struct containing: % % OBJ.vertices : Vertices coordinates % OBJ.vertices_texture: Texture coordinates % OBJ.vertices_normal : Normal vectors % OBJ.vertices_point : Vertice data used for points and lines % OBJ.material : Parameters from external .MTL file, will contain parameters like % newmtl, Ka, Kd, Ks, illum, Ns, map_Ka, map_Kd, map_Ks, % example of an entry from the material object: % OBJ.material(i).type = newmtl % OBJ.material(i).data = 'vase_tex' % OBJ.objects : Cell object with all objects in the OBJ file, % example of a mesh object: % OBJ.objects(i).type='f' % OBJ.objects(i).data.vertices: [n x 3 double] % OBJ.objects(i).data.texture: [n x 3 double] % OBJ.objects(i).data.normal: [n x 3 double] % % example reading/writing, % % OBJ=read_wobj('examples\example10.obj'); % write_wobj(OBJ,'test.obj'); % % example isosurface to obj-file, % % % Load MRI scan % load('mri','D'); D=smooth3(squeeze(D)); % % Make iso-surface (Mesh) of skin % FV=isosurface(D,1); % % Calculate Iso-Normals of the surface % N=isonormals(D,FV.vertices); % L=sqrt(N(:,1).^2+N(:,2).^2+N(:,3).^2)+eps; % N(:,1)=N(:,1)./L; N(:,2)=N(:,2)./L; N(:,3)=N(:,3)./L; % % Display the iso-surface % figure, patch(FV,'facecolor',[1 0 0],'edgecolor','none'); view(3);camlight % % Invert Face rotation % FV.faces=[FV.faces(:,3) FV.faces(:,2) FV.faces(:,1)]; % % % Make a material structure % material(1).type='newmtl'; % material(1).data='skin'; % material(2).type='Ka'; % material(2).data=[0.8 0.4 0.4]; % material(3).type='Kd'; % material(3).data=[0.8 0.4 0.4]; % material(4).type='Ks'; % material(4).data=[1 1 1]; % material(5).type='illum'; % material(5).data=2; % material(6).type='Ns'; % material(6).data=27; % % % Make OBJ structure % clear OBJ % OBJ.vertices = FV.vertices; % OBJ.vertices_normal = N; % OBJ.material = material; % OBJ.objects(1).type='g'; % OBJ.objects(1).data='skin'; % OBJ.objects(2).type='usemtl'; % OBJ.objects(2).data='skin'; % OBJ.objects(3).type='f'; % OBJ.objects(3).data.vertices=FV.faces; % OBJ.objects(3).data.normal=FV.faces; % write_wobj(OBJ,'skinMRI.obj'); % % Function is written by D.Kroon University of Twente (June 2010) if(exist('fullfilename','var')==0) [filename, filefolder] = uiputfile('*.obj', 'Write obj-file'); fullfilename = [filefolder filename]; end [filefolder,filename] = fileparts( fullfilename); comments=cell(1,4); comments{1}=' Produced by Matlab Write Wobj exporter '; comments{2}=''; fid = fopen(fullfilename,'w'); write_comment(fid,comments); if(isfield(OBJ,'material')&&~isempty(OBJ.material)) filename_mtl=fullfile(filefolder,[filename '.mtl']); fprintf(fid,'mtllib %s\n',filename_mtl); write_MTL_file(filename_mtl,OBJ.material) end if(isfield(OBJ,'vertices')&&~isempty(OBJ.vertices)) write_vertices(fid,OBJ.vertices,'v'); end if(isfield(OBJ,'vertices_point')&&~isempty(OBJ.vertices_point)) write_vertices(fid,OBJ.vertices_point,'vp'); end if(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal)) write_vertices(fid,OBJ.vertices_normal,'vn'); end if(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture)) write_vertices(fid,OBJ.vertices_texture,'vt'); end for i=1:length(OBJ.objects) type=OBJ.objects(i).type; data=OBJ.objects(i).data; switch(type) case 'usemtl' fprintf(fid,'usemtl %s\n',data); case 'f' check1=(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture)); check2=(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal)); if(check1&&check2) for j=1:size(data.vertices,1) fprintf(fid,'f %d/%d/%d',data.vertices(j,1),data.texture(j,1),data.normal(j,1)); fprintf(fid,' %d/%d/%d', data.vertices(j,2),data.texture(j,2),data.normal(j,2)); fprintf(fid,' %d/%d/%d\n', data.vertices(j,3),data.texture(j,3),data.normal(j,3)); end elseif(check1) for j=1:size(data.vertices,1) fprintf(fid,'f %d/%d',data.vertices(j,1),data.texture(j,1)); fprintf(fid,' %d/%d', data.vertices(j,2),data.texture(j,2)); fprintf(fid,' %d/%d\n', data.vertices(j,3),data.texture(j,3)); end elseif(check2) for j=1:size(data.vertices,1) fprintf(fid,'f %d//%d',data.vertices(j,1),data.normal(j,1)); fprintf(fid,' %d//%d', data.vertices(j,2),data.normal(j,2)); fprintf(fid,' %d//%d\n', data.vertices(j,3),data.normal(j,3)); end else for j=1:size(data.vertices,1) fprintf(fid,'f %d %d %d\n',data.vertices(j,1),data.vertices(j,2),data.vertices(j,3)); end end otherwise fprintf(fid,'%s ',type); if(iscell(data)) for j=1:length(data) if(ischar(data{j})) fprintf(fid,'%s ',data{j}); else fprintf(fid,'%0.5g ',data{j}); end end elseif(ischar(data)) fprintf(fid,'%s ',data); else for j=1:length(data) fprintf(fid,'%0.5g ',data(j)); end end fprintf(fid,'\n'); end end fclose(fid); function write_MTL_file(filename,material) fid = fopen(filename,'w'); comments=cell(1,2); comments{1}=' Produced by Matlab Write Wobj exporter '; comments{2}=''; write_comment(fid,comments); for i=1:length(material) type=material(i).type; data=material(i).data; switch(type) case('newmtl') fprintf(fid,'%s ',type); fprintf(fid,'%s\n',data); case{'Ka','Kd','Ks'} fprintf(fid,'%s ',type); fprintf(fid,'%5.5f %5.5f %5.5f\n',data); case('illum') fprintf(fid,'%s ',type); fprintf(fid,'%d\n',data); case {'Ns','Tr','d'} fprintf(fid,'%s ',type); fprintf(fid,'%5.5f\n',data); otherwise fprintf(fid,'%s ',type); if(iscell(data)) for j=1:length(data) if(ischar(data{j})) fprintf(fid,'%s ',data{j}); else fprintf(fid,'%0.5g ',data{j}); end end elseif(ischar(data)) fprintf(fid,'%s ',data); else for j=1:length(data) fprintf(fid,'%0.5g ',data(j)); end end fprintf(fid,'\n'); end end comments=cell(1,2); comments{1}=''; comments{2}=' EOF'; write_comment(fid,comments); fclose(fid); function write_comment(fid,comments) for i=1:length(comments), fprintf(fid,'# %s\n',comments{i}); end function write_vertices(fid,V,type) switch size(V,2) case 1 for i=1:size(V,1) fprintf(fid,'%s %5.5f\n', type, V(i,1)); end case 2 for i=1:size(V,1) fprintf(fid,'%s %5.5f %5.5f\n', type, V(i,1), V(i,2)); end case 3 for i=1:size(V,1) fprintf(fid,'%s %5.5f %5.5f %5.5f\n', type, V(i,1), V(i,2), V(i,3)); end otherwise end switch(type) case 'v' fprintf(fid,'# %d vertices \n', size(V,1)); case 'vt' fprintf(fid,'# %d texture verticies \n', size(V,1)); case 'vn' fprintf(fid,'# %d normals \n', size(V,1)); otherwise fprintf(fid,'# %d\n', size(V,1)); end
github
cwkx/IGAC-master
stlwrite.m
.m
IGAC-master/wrappers/matlab/lib/stlwrite.m
10,024
utf_8
501ff36176fdfe30bfa6352a0991d7c3
function stlwrite(filename, varargin) %STLWRITE Write STL file from patch or surface data. % % STLWRITE(FILE, FV) writes a stereolithography (STL) file to FILE for a % triangulated patch defined by FV (a structure with fields 'vertices' % and 'faces'). % % STLWRITE(FILE, FACES, VERTICES) takes faces and vertices separately, % rather than in an FV struct % % STLWRITE(FILE, X, Y, Z) creates an STL file from surface data in X, Y, % and Z. STLWRITE triangulates this gridded data into a triangulated % surface using triangulation options specified below. X, Y and Z can be % two-dimensional arrays with the same size. If X and Y are vectors with % length equal to SIZE(Z,2) and SIZE(Z,1), respectively, they are passed % through MESHGRID to create gridded data. If X or Y are scalar values, % they are used to specify the X and Y spacing between grid points. % % STLWRITE(...,'PropertyName',VALUE,'PropertyName',VALUE,...) writes an % STL file using the following property values: % % MODE - File is written using 'binary' (default) or 'ascii'. % % TITLE - Header text (max 80 chars) written to the STL file. % % TRIANGULATION - When used with gridded data, TRIANGULATION is either: % 'delaunay' - (default) Delaunay triangulation of X, Y % 'f' - Forward slash division of grid quads % 'b' - Back slash division of quadrilaterals % 'x' - Cross division of quadrilaterals % Note that 'f', 'b', or 't' triangulations now use an % inbuilt version of FEX entry 28327, "mesh2tri". % % FACECOLOR - Single colour (1-by-3) or one-colour-per-face (N-by-3) % vector of RGB colours, for face/vertex input. RGB range % is 5 bits (0:31), stored in VisCAM/SolidView format % (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL) % % Example 1: % % Write binary STL from face/vertex data % tmpvol = false(20,20,20); % Empty voxel volume % tmpvol(8:12,8:12,5:15) = 1; % Turn some voxels on % fv = isosurface(~tmpvol, 0.5); % Make patch w. faces "out" % stlwrite('test.stl',fv) % Save to binary .stl % % Example 2: % % Write ascii STL from gridded data % [X,Y] = deal(1:40); % Create grid reference % Z = peaks(40); % Create grid height % stlwrite('test.stl',X,Y,Z,'mode','ascii') % % Example 3: % % Write binary STL with coloured faces % cVals = fv.vertices(fv.faces(:,1),3); % Colour by Z height. % cLims = [min(cVals) max(cVals)]; % Transform height values % nCols = 255; cMap = jet(nCols); % onto an 8-bit colour map % fColsDbl = interp1(linspace(cLims(1),cLims(2),nCols),cMap,cVals); % fCols8bit = fColsDbl*255; % Pass cols in 8bit (0-255) RGB triplets % stlwrite('testCol.stl',fv,'FaceColor',fCols8bit) % Original idea adapted from surf2stl by Bill McDonald. Huge speed % improvements implemented by Oliver Woodford. Non-Delaunay triangulation % of quadrilateral surface courtesy of Kevin Moerman. FaceColor % implementation by Grant Lohsen. % % Author: Sven Holcombe, 11-24-11 % Check valid filename path path = fileparts(filename); if ~isempty(path) && ~exist(path,'dir') error('Directory "%s" does not exist.',path); end % Get faces, vertices, and user-defined options for writing [faces, vertices, options] = parseInputs(varargin{:}); asciiMode = strcmp( options.mode ,'ascii'); % Create the facets facets = single(vertices'); facets = reshape(facets(:,faces'), 3, 3, []); % Compute their normals V1 = squeeze(facets(:,2,:) - facets(:,1,:)); V2 = squeeze(facets(:,3,:) - facets(:,1,:)); normals = V1([2 3 1],:) .* V2([3 1 2],:) - V2([2 3 1],:) .* V1([3 1 2],:); clear V1 V2 normals = bsxfun(@times, normals, 1 ./ sqrt(sum(normals .* normals, 1))); facets = cat(2, reshape(normals, 3, 1, []), facets); clear normals % Open the file for writing permissions = {'w','wb+'}; fid = fopen(filename, permissions{asciiMode+1}); if (fid == -1) error('stlwrite:cannotWriteFile', 'Unable to write to %s', filename); end % Write the file contents if asciiMode % Write HEADER fprintf(fid,'solid %s\r\n',options.title); % Write DATA fprintf(fid,[... 'facet normal %.7E %.7E %.7E\r\n' ... 'outer loop\r\n' ... 'vertex %.7E %.7E %.7E\r\n' ... 'vertex %.7E %.7E %.7E\r\n' ... 'vertex %.7E %.7E %.7E\r\n' ... 'endloop\r\n' ... 'endfacet\r\n'], facets); % Write FOOTER fprintf(fid,'endsolid %s\r\n',options.title); else % BINARY % Write HEADER fprintf(fid, '%-80s', options.title); % Title fwrite(fid, size(facets, 3), 'uint32'); % Number of facets % Write DATA % Add one uint16(0) to the end of each facet using a typecasting trick facets = reshape(typecast(facets(:), 'uint16'), 12*2, []); % Set the last bit to 0 (default) or supplied RGB facets(end+1,:) = options.facecolor; fwrite(fid, facets, 'uint16'); end % Close the file fclose(fid); fprintf('Wrote %d facets\n',size(facets, 2)); %% Input handling subfunctions function [faces, vertices, options] = parseInputs(varargin) % Determine input type if isstruct(varargin{1}) % stlwrite('file', FVstruct, ...) if ~all(isfield(varargin{1},{'vertices','faces'})) error( 'Variable p must be a faces/vertices structure' ); end faces = varargin{1}.faces; vertices = varargin{1}.vertices; options = parseOptions(varargin{2:end}); elseif isnumeric(varargin{1}) firstNumInput = cellfun(@isnumeric,varargin); firstNumInput(find(~firstNumInput,1):end) = 0; % Only consider numerical input PRIOR to the first non-numeric numericInputCnt = nnz(firstNumInput); options = parseOptions(varargin{numericInputCnt+1:end}); switch numericInputCnt case 3 % stlwrite('file', X, Y, Z, ...) % Extract the matrix Z Z = varargin{3}; % Convert scalar XY to vectors ZsizeXY = fliplr(size(Z)); for i = 1:2 if isscalar(varargin{i}) varargin{i} = (0:ZsizeXY(i)-1) * varargin{i}; end end % Extract X and Y if isequal(size(Z), size(varargin{1}), size(varargin{2})) % X,Y,Z were all provided as matrices [X,Y] = varargin{1:2}; elseif numel(varargin{1})==ZsizeXY(1) && numel(varargin{2})==ZsizeXY(2) % Convert vector XY to meshgrid [X,Y] = meshgrid(varargin{1}, varargin{2}); else error('stlwrite:badinput', 'Unable to resolve X and Y variables'); end % Convert to faces/vertices if strcmp(options.triangulation,'delaunay') faces = delaunay(X,Y); vertices = [X(:) Y(:) Z(:)]; else if ~exist('mesh2tri','file') error('stlwrite:missing', '"mesh2tri" is required to convert X,Y,Z matrices to STL. It can be downloaded from:\n%s\n',... 'http://www.mathworks.com/matlabcentral/fileexchange/28327') end [faces, vertices] = mesh2tri(X, Y, Z, options.triangulation); end case 2 % stlwrite('file', FACES, VERTICES, ...) faces = varargin{1}; vertices = varargin{2}; otherwise error('stlwrite:badinput', 'Unable to resolve input types.'); end end if ~isempty(options.facecolor) % Handle colour preparation facecolor = uint16(options.facecolor); %Set the Valid Color bit (bit 15) c0 = bitshift(ones(size(faces,1),1,'uint16'),15); %Red color (10:15), Blue color (5:9), Green color (0:4) c0 = bitor(bitshift(bitand(2^6-1, facecolor(:,1)),10),c0); c0 = bitor(bitshift(bitand(2^11-1, facecolor(:,2)),5),c0); c0 = bitor(bitand(2^6-1, facecolor(:,3)),c0); options.facecolor = c0; else options.facecolor = 0; end function options = parseOptions(varargin) IP = inputParser; IP.addParameter('mode', 'binary', @ischar) IP.addParameter('title', sprintf('Durham University %s',datestr(now)), @ischar); IP.addParameter('triangulation', 'delaunay', @ischar); IP.addParameter('facecolor',[], @isnumeric) IP.addParameter('facecolour',[], @isnumeric) IP.parse(varargin{:}); options = IP.Results; if ~isempty(options.facecolour) options.facecolor = options.facecolour; end function [F,V]=mesh2tri(X,Y,Z,tri_type) % function [F,V]=mesh2tri(X,Y,Z,tri_type) % % Available from http://www.mathworks.com/matlabcentral/fileexchange/28327 % Included here for convenience. Many thanks to Kevin Mattheus Moerman % [email protected] % 15/07/2010 %------------------------------------------------------------------------ [J,I]=meshgrid(1:1:size(X,2)-1,1:1:size(X,1)-1); switch tri_type case 'f'%Forward slash TRI_I=[I(:),I(:)+1,I(:)+1; I(:),I(:),I(:)+1]; TRI_J=[J(:),J(:)+1,J(:); J(:),J(:)+1,J(:)+1]; F = sub2ind(size(X),TRI_I,TRI_J); case 'b'%Back slash TRI_I=[I(:),I(:)+1,I(:); I(:)+1,I(:)+1,I(:)]; TRI_J=[J(:)+1,J(:),J(:); J(:)+1,J(:),J(:)+1]; F = sub2ind(size(X),TRI_I,TRI_J); case 'x'%Cross TRI_I=[I(:)+1,I(:); I(:)+1,I(:)+1; I(:),I(:)+1; I(:),I(:)]; TRI_J=[J(:),J(:); J(:)+1,J(:); J(:)+1,J(:)+1; J(:),J(:)+1]; IND=((numel(X)+1):numel(X)+prod(size(X)-1))'; F = sub2ind(size(X),TRI_I,TRI_J); F(:,3)=repmat(IND,[4,1]); Fe_I=[I(:),I(:)+1,I(:)+1,I(:)]; Fe_J=[J(:),J(:),J(:)+1,J(:)+1]; Fe = sub2ind(size(X),Fe_I,Fe_J); Xe=mean(X(Fe),2); Ye=mean(Y(Fe),2); Ze=mean(Z(Fe),2); X=[X(:);Xe(:)]; Y=[Y(:);Ye(:)]; Z=[Z(:);Ze(:)]; end V=[X(:),Y(:),Z(:)];
github
cwkx/IGAC-master
myaa.m
.m
IGAC-master/wrappers/matlab/lib/myaa.m
11,141
utf_8
a66dd7fc188c3f6a1a0a0c07623cf831
function [varargout] = myaa(varargin) %MYAA Render figure with anti-aliasing. % MYAA % Anti-aliased rendering of the current figure. This makes graphics look % a lot better than in a standard matlab figure, which is useful for % publishing results on the web or to better see the fine details in a % complex and cluttered plot. Some simple keyboard commands allow % the user to set the rendering quality interactively, zoom in/out and % re-render when needed. % % Usage: % myaa: Renders an anti-aliased version of the current figure. % % myaa(K): Sets the supersampling factor to K. Using a % higher K yields better rendering but takes longer time. If K is % omitted, it defaults to 4. It may be useful to run e.g. myaa(2) to % make a low-quality rendering as a first try, because it is a lot % faster than the default. % % myaa([K D]): Sets supersampling factor to K but downsamples the % image by a factor of D. If D is larger than K, the rendered image % will be smaller than the original. If D is smaller than K, the % rendering will be bigger. % % myaa('publish'): An experimental parameter, useful for publishing % matlab programs (see example 3). Beware, it kills the current figure. % % Interactivity: % The anti-aliased figure can be updated with the following keyboard % commands: % % <space> Re-render image (to reflect changes in the figure) % + Zoom in (decrease downsampling factor) % - Zoom out (increase downsampling factor) % 1 ... 9 Change supersampling and downsampling factor to ... % q Quit, i.e. close the anti-aliased figure % % Myaa can also be called with up to 3 parameters. % FIG = MYAA(K,AAMETHOD,FIGMODE) % Parameters and output: % K Subsampling factor. If a vector is specified, [K D], then % the second element will describe the downsampling factor. % Default is K = 4 and D = 4. % AAMETHOD Downsampling method. Normally this is chosen automatically. % 'standard': convolution based filtering and downsampling % 'imresize': downsampling using the imresize command from % the image toolbox. % 'noshrink': used internally % FIGMODE Display mode % 'figure': the normal mode, a new figure is created % 'update': internally used for interactive sessions % 'publish': used internally % FIG A handle to the new anti-aliased figure % % Example 1: % spharm2; % myaa; % % Press '1', '2' or '4' and try '+' and '-' % % Press 'r' or <space> to update the anti-aliased rendering, e.g. % % after rotating the 3-D object in the original figure. % % Example 2: % line(randn(2500,2)',randn(2500,2)','color','black','linewidth',0.01) % myaa(8); % % Example 3: % xpklein; % myaa(2,'standard'); % % Example 3: % Put the following in test.m % %% My test publish % % Testing to publish some anti-aliased images % % % spharm2; % Produce some nice graphics % myaa('publish'); % Render an anti-aliased version % % Then run: % publish test.m; % showdemo test; % % % BUGS: % Dotted and dashed lines in plots are not rendered correctly. This is % probably due to a bug in Matlab and it will hopefully be fixed in a % future version. % The OpenGL renderer does not always manage to render an image large % enough. Try the zbuffer renderer if you have problems or decrease the % K factor. You can set the current renderer to zbuffer by running e.g. % set(gcf,'renderer','zbuffer'). % % See also PUBLISH, PRINT % % Version 1.1, 2008-08-21 % Version 1.0, 2008-08-05 % % Author: Anders Brun % [email protected] % %% Force drawing of graphics drawnow; %% Find out about the current DPI... screen_DPI = get(0,'ScreenPixelsPerInch'); %% Determine the best choice of convolver. % If IPPL is available, imfilter is much faster. Otherwise it does not % matter too much. try if ippl() myconv = @imfilter; else myconv = @conv2; end catch myconv = @conv2; end %% Set default options and interpret arguments if isempty(varargin) self.K = [4 4]; try imfilter(zeros(2,2),zeros(2,2)); self.aamethod = 'imresize'; catch self.aamethod = 'standard'; end self.figmode = 'figure'; elseif strcmp(varargin{1},'publish') self.K = [4 4]; self.aamethod = 'noshrink'; self.figmode = 'publish'; elseif strcmp(varargin{1},'update') self = get(gcf,'UserData'); figure(self.source_fig); drawnow; self.figmode = 'update'; elseif strcmp(varargin{1},'lazyupdate') self = get(gcf,'UserData'); self.figmode = 'lazyupdate'; elseif length(varargin) == 1 self.K = varargin{1}; if length(self.K) == 1 self.K = [self.K self.K]; end if self.K(1) > 16 error('To avoid excessive use of memory, K has been limited to max 16. Change the code to fix this on your own risk.'); end try imfilter(zeros(2,2),zeros(2,2)); self.aamethod = 'imresize'; catch self.aamethod = 'standard'; end self.figmode = 'figure'; elseif length(varargin) == 2 self.K = varargin{1}; self.aamethod = varargin{2}; self.figmode = 'figure'; elseif length(varargin) == 3 self.K = varargin{1}; self.aamethod = varargin{2}; self.figmode = varargin{3}; if strcmp(self.figmode,'publish') && ~strcmp(varargin{2},'noshrink') printf('\nThe AAMETHOD was not set to ''noshrink'': Fixed.\n\n'); self.aamethod = 'noshrink'; end else error('Wrong syntax, run: help myaa'); end if length(self.K) == 1 self.K = [self.K self.K]; end %% Capture current figure in high resolution if ~strcmp(self.figmode,'lazyupdate'); tempfile = 'myaa_temp_screendump.png'; self.source_fig = gcf; current_paperpositionmode = get(self.source_fig,'PaperPositionMode'); current_inverthardcopy = get(self.source_fig,'InvertHardcopy'); set(self.source_fig,'PaperPositionMode','auto'); set(self.source_fig,'InvertHardcopy','off'); print(self.source_fig,['-r',num2str(screen_DPI*self.K(1))], '-dpng', tempfile); set(self.source_fig,'InvertHardcopy',current_inverthardcopy); set(self.source_fig,'PaperPositionMode',current_paperpositionmode); self.raw_hires = imread(tempfile); delete(tempfile); end %% Start filtering to remove aliasing w = warning; warning off; if strcmp(self.aamethod,'standard') || strcmp(self.aamethod,'noshrink') % Subsample hires figure image with standard anti-aliasing using a % butterworth filter kk = lpfilter(self.K(2)*3,self.K(2)*0.9,2); mm = myconv(ones(size(self.raw_hires(:,:,1))),kk,'same'); a1 = max(min(myconv(single(self.raw_hires(:,:,1))/(256),kk,'same'),1),0)./mm; a2 = max(min(myconv(single(self.raw_hires(:,:,2))/(256),kk,'same'),1),0)./mm; a3 = max(min(myconv(single(self.raw_hires(:,:,3))/(256),kk,'same'),1),0)./mm; if strcmp(self.aamethod,'standard') if abs(1-self.K(2)) > 0.001 raw_lowres = double(cat(3,a1(2:self.K(2):end,2:self.K(2):end),a2(2:self.K(2):end,2:self.K(2):end),a3(2:self.K(2):end,2:self.K(2):end))); else raw_lowres = self.raw_hires; end else raw_lowres = double(cat(3,a1,a2,a3)); end elseif strcmp(self.aamethod,'imresize') % This is probably the fastest method available at this moment... raw_lowres = single(imresize(self.raw_hires,1/self.K(2),'bilinear'))/256; end warning(w); %% Place the anti-aliased image in some image on the screen ... if strcmp(self.figmode,'figure'); % Create a new figure at the same place as the previous % The content of this new image is just a bitmap... oldpos = get(gcf,'Position'); self.myaa_figure = figure; fig = self.myaa_figure; set(fig,'Menubar','none'); set(fig,'Resize','off'); sz = size(raw_lowres); set(fig,'Units','pixels'); pos = [oldpos(1:2) sz(2:-1:1)]; set(fig,'Position',pos); ax = axes; image(raw_lowres); set(ax,'Units','pixels'); set(ax,'Position',[1 1 sz(2) sz(1)]); axis off; elseif strcmp(self.figmode,'publish'); % Create a new figure at the same place as the previous % The content of this new image is just a bitmap... self.myaa_figure = figure; fig = self.myaa_figure; current_units = get(self.source_fig,'Units'); set(self.source_fig,'Units','pixels'); pos = get(self.source_fig,'Position'); set(self.source_fig,'Units',current_units); set(fig,'Position',[pos(1) pos(2) pos(3) pos(4)]); ax = axes; image(raw_lowres); set(ax,'Units','normalized'); set(ax,'Position',[0 0 1 1]); axis off; close(self.source_fig); elseif strcmp(self.figmode,'update'); fig = self.myaa_figure; figure(fig); clf; set(fig,'Menubar','none'); set(fig,'Resize','off'); sz = size(raw_lowres); set(fig,'Units','pixels'); pos = get(fig,'Position'); pos(3:4) = sz(2:-1:1); set(fig,'Position',pos); ax = axes; image(raw_lowres); set(ax,'Units','pixels'); set(ax,'Position',[1 1 sz(2) sz(1)]); axis off; elseif strcmp(self.figmode,'lazyupdate'); clf; fig = self.myaa_figure; sz = size(raw_lowres); pos = get(fig,'Position'); pos(3:4) = sz(2:-1:1); set(fig,'Position',pos); ax = axes; image(raw_lowres); set(ax,'Units','pixels'); set(ax,'Position',[1 1 sz(2) sz(1)]); axis off; end %% Store current state set(gcf,'userdata',self); set(gcf,'KeyPressFcn',@keypress); set(gcf,'Interruptible','off'); %% Avoid unnecessary console output if nargout == 1 varargout(1) = {fig}; end %% A simple lowpass filter kernel (Butterworth). % sz is the size of the filter % subsmp is the downsampling factor to be used later % n is the degree of the butterworth filter function kk = lpfilter(sz, subsmp, n) sz = 2*floor(sz/2)+1; % make sure the size of the filter is odd cut_frequency = 0.5 / subsmp; range = (-(sz-1)/2:(sz-1)/2)/(sz-1); [ii,jj] = ndgrid(range,range); rr = sqrt(ii.^2+jj.^2); kk = ifftshift(1./(1+(rr./cut_frequency).^(2*n))); kk = fftshift(real(ifft2(kk))); kk = kk./sum(kk(:)); function keypress(src,evnt) if isempty(evnt.Character) return end recognized = 0; self = get(gcf,'userdata'); if evnt.Character == '+' self.K(2) = max(self.K(2).*0.5^(1/2),1); recognized = 1; set(gcf,'userdata',self); myaa('lazyupdate'); elseif evnt.Character == '-' self.K(2) = min(self.K(2).*2^(1/2),16); recognized = 1; set(gcf,'userdata',self); myaa('lazyupdate'); elseif evnt.Character == ' ' || evnt.Character == 'r' || evnt.Character == 'R' set(gcf,'userdata',self); myaa('update'); elseif evnt.Character == 'q' close(gcf); elseif find('123456789' == evnt.Character) self.K = [str2double(evnt.Character) str2double(evnt.Character)]; set(gcf,'userdata',self); myaa('update'); end
github
yangyangHu/deblur-master
create_greenspan_settings.m
.m
deblur-master/code/create_greenspan_settings.m
2,527
utf_8
cfad68ce50fdb9d9dcc4b38e9b9c14fe
function S = create_greenspan_settings(varargin) % Author: Bryan Russell % Version: 1.0, distribution code. % Project: Removing Camera Shake from a Single Image, SIGGRAPH 2006 paper % Copyright 2006, Massachusetts Institute of Technology % CREATE_GREENSPAN_SETTINGS - Creates a data structure containing the % various parameter settings for the Greenspan nonlinear enhancement % algorithm. % % S = CREATE_GREENSPAN_SETTINGS creates the default settings and stores % them in S. % % S = CREATE_GREENSPAN_SETTINGS('P1',SET1,'P2',SET2,...) sets the % parameters P1 to be SET1, etc. The settings that can be changed are as % follows: % % 'lo_filt' - Lowpass filter, which can be any kernel or one of 'gauss' % or 'binomial5' (default 'binomial5') % 'c' - Clipping constant (default 0.4). You may also specify % 'derived', which sets it to be the derived value, 0.45. This % constant must be in [0,1]. This constant provides the % nonlinearity and augments the frequency content of the image. % 's' - Scaling constant (default 5). You may also specify 'derived' % which sets it to be the derived vaule, 3. This constant % provides the sharp slope, thus reducing the blurring effect, % yet augmenting the ringing side-effect. % 'bp' - Bandpass filtering flag, which can be either 0 or 1 (default % 1). % 'factor' - Zoom by a factor of 2^factor (default is 1). % % See also GREENSPAN. % % <[email protected]> S.lo_filt = binomialFilter(5); S.lo_filt = S.lo_filt*S.lo_filt'; S.c = 0.4; S.s = 5; S.bp = 1; S.factor = 1; S = parse_args(S,varargin{:}); function S = parse_args(S,varargin) n = length(varargin); for k = 1:2:n-1 param = varargin{k}; setting = varargin{k+1}; switch lower(param) case 'lo_filt' if ischar(setting) switch lower(setting) case 'gauss' S.lo_filt = fspecial('gauss',[3 3],1); case 'binomial5' S.lo_filt = binomialFilter(5); S.lo_filt = S.lo_filt*S.lo_filt'; otherwise error('Invalid setting of lo_filt'); end else S.lo_filt = setting; end case 'c' if ischar(setting) & strcmp(lower(setting),'derived') S.c = 0.45; else S.c = setting; end case 's' if ischar(setting) & strcmp(lower(setting),'derived') S.s = 3; else S.s = setting; end case 'bp' S.bp = setting; case 'factor' S.factor = setting; otherwise error('Invalid parameter'); end end
github
dmarcosg/RotEqNet-master
cnn_mnist_rot_dag.m
.m
RotEqNet-master/cnn_mnist_rot_dag.m
3,269
utf_8
097dc6b8c124ce44eaff65b75b03bd81
function [net, info] = cnn_mnist_rot_dag(varargin) %CNN_MNIST Demonstrates MatConvNet on MNIST run(fullfile(fileparts(mfilename('fullpath')),... '..', '..', 'matlab', 'vl_setupnn.m')) ; run(fullfile(fileparts(mfilename('fullpath')),... 'setup_mcnRotEqNet.m')) ; opts.batchNormalization = true ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.expDir = fullfile('models', ['mnist-rot_size5_12k']) ; [opts, varargin] = vl_argparse(opts, varargin) ; opts.dataDir = 'data'; opts.imdbPath = fullfile(opts.expDir, 'imdb.mat'); opts.train = struct() ; opts = vl_argparse(opts, varargin) ; if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end; % -------------------------------------------------------------------- % Prepare data % -------------------------------------------------------------------- net = netinit_mnist_dag() ; if exist(opts.imdbPath, 'file') imdb = load(opts.imdbPath) ; else imdb = getMnistImdb(opts) ; mkdir(opts.expDir) ; save(opts.imdbPath, '-struct', 'imdb') ; end net.meta.classes.name = arrayfun(@(x)sprintf('%d',x),1:10,'UniformOutput',false) ; % -------------------------------------------------------------------- % Train % -------------------------------------------------------------------- trainfn = @cnn_train_dag ; [net, info] = trainfn(net, imdb, getBatch(opts), ... 'expDir', opts.expDir, ... net.meta.trainOpts, ... opts.train, ... 'val', find(imdb.images.set == 3)); % -------------------------------------------------------------------- function fn = getBatch(opts) % -------------------------------------------------------------------- bopts = struct('numGpus', numel(opts.train.gpus)) ; fn = @(x,y) getDagNNBatch(bopts,x,y) ; function inputs = getDagNNBatch(opts, imdb, batch) % -------------------------------------------------------------------- images = imdb.images.data(:,:,:,batch) ; for i = 1:size(images,4) images(:,:,:,i) = imrotate(images(:,:,:,i),rand*360,'crop'); end labels = imdb.images.labels(1,batch) ; if opts.numGpus > 0 images = gpuArray(images) ; end inputs = {'input', images, 'label', labels} ; % -------------------------------------------------------------------- function imdb = getMnistImdb(opts) % -------------------------------------------------------------------- % Prepare the imdb structure, returns image data with mean image subtracted urlroot = 'http://www.iro.umontreal.ca/~lisa/icml2007data/'; files = {'mnist_rotation_new.zip'}; if ~exist(opts.dataDir, 'dir') mkdir(opts.dataDir) ; end if ~exist(fullfile(opts.dataDir, files{1}), 'file') url = sprintf([urlroot,files{1}]) ; fprintf('downloading %s\n', url) ; gunzip(url, opts.dataDir) ; unzip(fullfile(opts.dataDir,files{1}),opts.dataDir); end d = single(dlmread(fullfile(opts.dataDir,'mnist_all_rotation_normalized_float_train_valid.amat'))); data = reshape(d(:,1:end-1)',28,28,1,[]); set = [ones(1,size(data,4)-100) 3*ones(1,100)]; y = d(:,end)'; imdb.images.data = data ; imdb.images.labels = y + 1 ; imdb.images.set = set ; imdb.meta.sets = {'train', 'val', 'test'} ; imdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;
github
dmarcosg/RotEqNet-master
vl_nnpoolangle.m
.m
RotEqNet-master/matlab/vl_nnpoolangle.m
5,992
utf_8
41d89f1d4728b2ec44b115fb1382e485
function y = vl_nnpoolangle(x,varargin) dzdy = []; if nargin > 1 if ~ischar(varargin{1}) dzdy = varargin{1}; if numel(varargin) > 1 varargin = varargin(2:end); end end end opts.bins = 1; opts.angle_n = 8; opts.max_angle = 360; opts.output_relative_angles = false; opts.output_absolute_angles = false; opts.opts = {}; if isempty(varargin{end}) varargin = varargin(1:end-1); end opts = vl_argparse(opts, varargin); bins = opts.bins; angle_n = opts.angle_n; max_angle = opts.max_angle; rel_ang = opts.output_relative_angles; abs_ang = opts.output_absolute_angles; if bins == 0 output_mode = 2; bins = 1; rel_ang = false; abs_ang = false; else output_mode = 1; end if rel_ang || abs_ang bins = 1; end if nargin <= 3 || isempty(dzdy) % Forward x = permute(x,[1 2 4 3]); xs = stackSteeredFilters(x,angle_n); nearest_center = getNearestCenter(angle_n,bins,max_angle); if output_mode == 1 if abs_ang || rel_ang y = zeros(size(xs,1),size(xs,2),size(xs,3),... size(xs,4)*(1 + 2*abs_ang + 2*(size(xs,4)-1)*rel_ang),1,'like',xs); [y(:,:,:,1:size(xs,4)), y_ind] = max(xs,[],5); y_ind = y_ind*2*pi/angle_n; b = 1; if rel_ang for b = 1:size(xs,4)-1 dif_y = y_ind - circshift(y_ind,b,4); y(:,:,:,(2*b-1)*size(xs,4)+1:2*b*size(xs,4)) = cos(dif_y); y(:,:,:,2*b*size(xs,4)+1:(2*b+1)*size(xs,4)) = sin(dif_y); end b = b + 1; end if abs_ang y(:,:,:,(2*b-1)*size(xs,4)+1:2*b*size(xs,4)) = cos(y_ind); y(:,:,:,2*b*size(xs,4)+1:(2*b+1)*size(xs,4)) = sin(y_ind); end else y = zeros(size(xs,1),size(xs,2),size(xs,3),size(xs,4),bins,'like',xs); for i = 1:bins y(:,:,:,:,i) = max(xs(:,:,:,:,nearest_center==i),[],5); end end y = stackSteeredFilters(y,bins); y = permute(y,[1 2 4 3]); else % output_mode == 2 d_alpha = max_angle/angle_n; alphas = 0:d_alpha:max_angle; alphas(end) = []; p1 = cos(alphas*pi/180); p2 = sin(alphas*pi/180); [absy,inds] = max(xs,[],5); inds = reshape(inds,size(absy)); y1 = absy .* reshape(p1(inds),size(absy)); y2 = absy .* reshape(p2(inds),size(absy)); %y1 = stackSteeredFilters(y1,bins); y1 = permute(y1,[1 2 4 3]); %y2 = stackSteeredFilters(y2,bins); y2 = permute(y2,[1 2 4 3]); y = zeros([size(y1,1),size(y1,2),size(y1,3),size(y1,4),2],'like',x); y(:,:,:,:,1) = y1; y(:,:,:,:,2) = y2; %y = stackSteeredFilters(permute(y,[1 2 4 3 5]),2); %y = permute(y,[1 2 4 3]); end else % Backward if abs_ang || rel_ang dzdy = dzdy(:,:,1:size(x,3)/angle_n,:,:); end x = permute(x,[1 2 4 3]); xs = stackSteeredFilters(x,angle_n); nearest_center = getNearestCenter(angle_n,bins,max_angle); if output_mode == 2 %temp_dzdy = zeros(size(dzdy(:,:,:,:,1)),'like',dzdy); %for m = 1:2 % temp_dzdy = temp_dzdy + dzdy(:,:,:,:,m).^2; %end %dzdy = permute(dzdy,[1 2 4 3]); %dzdy = stackSteeredFilters(dzdy,2); %temp_dzdy = sqrt(sum(dzdy.^2,5)); d_alpha = opts.max_angle/angle_n; alphas = 0:d_alpha:opts.max_angle; alphas(end) = []; p1 = cos(alphas*pi/180); p2 = sin(alphas*pi/180); [absy,inds] = max(xs,[],5); inds = permute(inds,[1 2 4 3]); dzdy = dzdy(:,:,:,:,1).*reshape(p1(inds),size(inds)) + dzdy(:,:,:,:,2).*reshape(p2(inds),size(inds)) ; %dzdy = dzdy(:,:,:,:,1) + dzdy(:,:,:,:,2); %dzdy = (temp_dzdy).*sign(permute(absy,[1 2 4 3])); %inds = permute(inds,[1 2 4 3]); %dzdy = dzdy(:,:,:,:,1).*sign(p1(inds)) + dzdy(:,:,:,:,2).*sign(p2(inds)); end dzdy = permute(dzdy,[1 2 4 3]); dzdys = stackSteeredFilters(dzdy,bins); y = zeros(size(xs,1),size(xs,2),size(xs,3),size(xs,4),angle_n,'like',xs); inds = zeros(size(xs,1),size(xs,2),size(xs,3),size(xs,4),bins,'like',xs); inds_pre = zeros(size(xs,1),size(xs,2),size(xs,3),size(xs,4),bins,'like',xs); offset = 0; for i = 1:bins [~,inds(:,:,:,:,i)] = max(xs(:,:,:,:,nearest_center==i),[],5); inds_pre(:,:,:,:,i) = inds(:,:,:,:,i) + offset; offset = offset + sum(nearest_center==i); end for i = 1:bins new_y = zeros(size(y,1),size(y,2),size(y,3),size(y,4),sum(nearest_center==i),'like',y); for j = 1:sum(nearest_center==i) new_y(:,:,:,:,j) = dzdys(:,:,:,:,i).*(inds(:,:,:,:,i)==j); end y(:,:,:,:,nearest_center==i) = new_y; end y = stackSteeredFilters(y,angle_n); y = permute(y,[1 2 4 3]); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function nearest_center = getNearestCenter(angle_n,bins,max_angle) bin_centers = linspace(0,max_angle,bins+1); bin_centers = bin_centers(1:end-1); angles = linspace(0,max_angle,angle_n+1); angles = angles(1:end-1); dist_to_centers = pdist2(bin_centers',angles'); [~,nearest_center] = min(dist_to_centers,[],1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fs = stackSteeredFilters(f,angle_n) siz = [size(f),1,1]; if size(f,5) == 1 % it's a normal 4D filter bank filt_num = siz(4) / angle_n; fs = zeros([siz(1:3), filt_num, angle_n],'like',f); for i = 1:angle_n fs(:,:,:,:,i) = f(:,:,:,i:angle_n:filt_num*angle_n-angle_n + i); end else % it's a steered 5D filter bank angle_n = siz(5); filt_num = angle_n * siz(4); fs = zeros([siz(1:3), filt_num],'like',f); for i = 1:angle_n fs(:,:,:,i:angle_n:filt_num-angle_n + i) = f(:,:,:,:,i); end end end
github
dmarcosg/RotEqNet-master
vl_nnconvsteer.m
.m
RotEqNet-master/matlab/vl_nnconvsteer.m
3,965
utf_8
0164847c23a50e4cd3af8614cb0f6978
function [y,dzdf,dzdb] = vl_nnconvsteer(x,f,b,varargin) % Forward: y = vl_nnconvsteer(x,f,b) % Backward: [dzdx,dzdf,dzdb] = vl_nnconvsteer(x,f,b,dzdy) % Options: % 'angle_n': number of rotations to compute for each filter in f if isa(x,'gpuArray') f = gpuArray(f); b = gpuArray(b); end cudnn = 'CuDNN'; dzdy = []; if nargin > 3 if ~ischar(varargin{1}) dzdy = varargin{1}; if numel(varargin) > 1 varargin = varargin(2:end); else varargin = {}; end end if ~isempty(varargin) && ischar(varargin{end}) cudnn = varargin{end}; varargin = varargin(1:end-1); end end opts.pad = 0 ; opts.stride = 1 ; opts.angle_n = 8; opts.max_angle = 360; %opts. if ~isempty(varargin) opts = vl_argparse(opts, varargin); end if size(f,5) == 2 input_mode = 2; else input_mode = 1; end if opts.angle_n > 1 mask = fspecial('disk', size(f,1)/2); mask = imresize(mask,[size(f,1),size(f,2)]); mask = mask / max(mask(:)); mask = mask > 0.5; f = bsxfun(@times,f,mask); end if nargin <= 3 || isempty(dzdy) % Forward br = zeros(1,numel(b)*opts.angle_n,'like',b); for i = 1:numel(b) br((i-1)*opts.angle_n+1:i*opts.angle_n) = b(i); end % If each input pixel is a 2D vector, apply conv to each dimension % separately and add the result (scalar product) y = zeros(1,'like',b); fr = getSteeredFilters(f,opts.angle_n,opts.max_angle); for m = 1:input_mode tempy = vl_nnconv(x(:,:,:,:,m),fr(:,:,:,:,m),br,'pad',opts.pad,'stride',opts.stride,cudnn); y = y + tempy; end dzdf = []; dzdb = []; else % Backward % Multiplex the biases br = zeros(1,numel(b)*opts.angle_n,'like',b); for i = 1:numel(b) br((i-1)*opts.angle_n+1:i*opts.angle_n) = b(i); end b = br; dzdb_temp = {}; dzdx_temp = {}; % Get all steered filters fr = getSteeredFilters(f,opts.angle_n,opts.max_angle); dzdfr = zeros(size(fr),'like',fr); for m = 1:input_mode % Get gradients [dzdx_temp{m}, dzdfr(:,:,:,:,m), dzdb_temp{m}] = vl_nnconv(x(:,:,:,:,m),fr(:,:,:,:,m),b,dzdy,'pad',opts.pad,'stride',opts.stride,cudnn); % Demultiplex the bias gradients by averaging dzdbr = zeros(1,numel(dzdb_temp{m})/opts.angle_n,'like',dzdb_temp{m}); for i = 1:numel(dzdbr) dzdbr(i) = sum(dzdb_temp{m}((i-1)*opts.angle_n+1:i*opts.angle_n)); end dzdb_temp{m} = dzdbr; end % Un-steer the gradients by averaging dzdf = getSteeredFilters(dzdfr,-opts.angle_n,opts.max_angle); size_x = size(dzdx_temp{1}); size_x(5) = input_mode; size_x(size_x==0) = 1; dzdx = zeros(size_x,'like',x); dzdb = zeros(size(dzdb_temp{1}),'like',x); for m = 1:input_mode dzdx(:,:,:,:,m) = dzdx_temp{m}; dzdb = dzdb + dzdb_temp{m}; end y = dzdx;% / sqrt(opts.angle_n); dzdb = dzdb(:);% / sqrt(opts.angle_n);% / input_mode; if opts.angle_n > 1 dzdf = bsxfun(@times,dzdf,mask); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fr = getSteeredFilters(f,angle_n,max_angle) % wr = getRotatedFilters(w,alpha_n) % Get alpha_n rotated versions of filters w % f is a 4D array of 3D filters % alpha_n >=1 is an integer, the number of steered versions if angle_n < 0 angle_n = abs(angle_n); inverse = true; fr = zeros([size(f,1),size(f,2),size(f,3),size(f,4)/angle_n,size(f,5)],'like',f); else inverse = false; fr = zeros([size(f,1),size(f,2),size(f,3),size(f,4)*angle_n,size(f,5)],'like',f); end d_alpha = max_angle/angle_n; alphas = 0:d_alpha:max_angle; alphas(end) = []; for i = 1:numel(alphas) if inverse fr = fr + rotateVectorField(f(:,:,:,i:angle_n:end,:),-alphas(i)); else fr(:,:,:,i:angle_n:end,:) = rotateVectorField(f,alphas(i)); end end end
github
dmarcosg/RotEqNet-master
vl_nnpool_ext.m
.m
RotEqNet-master/matlab/vl_nnpool_ext.m
7,800
utf_8
c1face47f04b27495af521b42d58ec6e
function y = vl_nnpool_ext(x,ext,pool,varargin) % Check whether forward or backward dzdy = []; if nargin > 3 if ~ischar(varargin{1}) dzdy = varargin{1}; if numel(varargin) > 1 varargin = varargin(2:end); else varargin = []; end end end opts.pad = 0 ; %opts.stride = 1 ; if ~isempty(varargin) opts = vl_argparse(opts, varargin); end pad = opts.pad; if numel(pad) == 1 pad = [ceil(pad/2) floor(pad/2) ceil(pad/2) floor(pad/2)]; end if numel(pad) == 2 pad = [ceil(pad(1)/2) floor(pad(1)/2) ceil(pad(2)/2) floor(pad(2)/2)]; end if mod(size(x,1),pool) ~= 0 pad = pad + [ceil(mod(size(x,1),pool)/2), floor(mod(size(x,1),pool)/2),... ceil(mod(size(x,1),pool)/2), floor(mod(size(x,1),pool)/2)]; end ingpu = isa(x,'gpuArray'); if ingpu x = gather(x); ext = gather(ext); dzdy = gather(dzdy); end if nargin < 3 || isempty(dzdy) % Forward padded_ext = zeros(size(ext,1) + pad(1) + pad(2),size(ext,2) + pad(3) + pad(4),size(ext,3),size(ext,4),size(ext,5),'like',ext); padded_ext(pad(1)+1:end - pad(2), pad(3) + 1:end - pad(4),:,:,:,:) = ext; padded_x = zeros(size(x,1) + pad(1) + pad(2),size(x,2) + pad(3) + pad(4),size(x,3),size(x,4),size(x,5),'like',x); padded_x(pad(1)+1:end - pad(2), pad(3) + 1:end - pad(4),:,:,:,:) = x; [~,ind] = maxpool(padded_ext,pool); y = getmax(padded_x,pool,ind); %y = zeros(size(temp,1) + pad(1) + pad(2),size(temp,2) + pad(3) + pad(4),size(temp,3),size(temp,4),size(temp,5),'like',temp); %y(pad(1)+1:end - pad(2), pad(3) + 1:end - pad(4),:,:,:,:) = temp; else % Backward padded_ext = zeros(size(ext,1) + pad(1) + pad(2),size(ext,2) + pad(3) + pad(4),size(ext,3),size(ext,4),size(ext,5),'like',ext); padded_ext(pad(1)+1:end - pad(2), pad(3) + 1:end - pad(4),:,:,:,:) = ext; [~,ind] = maxpool(padded_ext,pool); y = maxpool_back(dzdy,pool,size(padded_ext),ind); y = y(pad(1)+1:end - pad(2), pad(3) + 1:end - pad(4),:,:,:,:); end if ingpu y = gpuArray(y); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [m,ind] = maxpool(x,pool) if numel(pool) == 1 pool = [pool pool]; end x_pad = -inf(ceil(size(x,1)/pool(1))*pool(1),ceil(size(x,2)/pool(2))*pool(2),size(x,3),size(x,4),'like',x); x_pad(1:size(x,1),1:size(x,2),:,:) = x; m = zeros((size(x_pad,1)/pool(1)),(size(x_pad,2)/pool(2)),size(x_pad,3),size(x_pad,4),'like',x_pad); ind = zeros(size(m),'like',m); col = my_im2col(x_pad,pool,'distinct'); [temp_m,temp_ind] = max(col); m = reshape(temp_m,size(m,1),size(m,2),size(x_pad,3),size(x_pad,4)); ind = reshape(temp_ind,size(m,1),size(m,2),size(x_pad,3),size(x_pad,4)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x = maxpool_back(m,pool,s,ind) if numel(pool) == 1 pool = [pool pool]; end col_size = prod(pool); num_cols = size(m,1)*size(m,2); col = zeros(col_size,num_cols,size(m,3),size(m,4),'like',m); offset = (0:numel(ind)-1)*prod(pool); %offset = reshape(offset,size(ind)); col(ind(:) + offset(:)) = m(:); x = my_col2im(col,pool,s,'distinct'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [m] = getmax(x,pool,ind) if numel(pool) == 1 pool = [pool pool]; end x_pad = -inf(ceil(size(x,1)/pool(1))*pool(1),ceil(size(x,2)/pool(2))*pool(2),size(x,3),size(x,4),'like',x); x_pad(1:size(x,1),1:size(x,2),:,:) = x; m = zeros((size(x_pad,1)/pool(1)),(size(x_pad,2)/pool(2)),size(x_pad,3),size(x_pad,4),'like',x_pad); col = my_im2col(x_pad,pool,'distinct'); offset = (0:numel(ind)-1)*prod(pool); offset = reshape(offset,size(ind)); m = reshape(col(ind+offset),size(ind)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function col = my_im2col(im,p,mode) s = size(im); if numel(s) == 3 s = [s 1]; end if numel(s) == 2 s = [s 1 1]; end col = zeros(prod(p),ceil(s(1)/p(1))*ceil(s(2)/p(2)),s(3),s(4),'like',im); init_patch = zeros(p(1),p(2),size(im,3),size(im,4),'like',im); count = 1; p1 = p(1); p2 = p(2); s1 = s(1); s2 = s(2); if isa(im,'gpuArray') s1 = gpuArray(s1); s2 = gpuArray(s2); p1 = gpuArray(p1); p2 = gpuArray(p2); count = gpuArray(1); one = gpuArray(1); else one = 1; end first_corners = repmat( (1:p(1):s(1))',1,s(2)/p(2)); first_corners = bsxfun(@plus,first_corners,0:p(2)*s(1):s(1)*s(2)-1); first_corners = first_corners(:); first_corners = bsxfun(@plus, first_corners, 0:s(1)*s(2):s(1)*s(2)*s(3)-1); first_corners = first_corners(:); first_corners = bsxfun(@plus, first_corners, 0:s(1)*s(2)*s(3):s(1)*s(2)*s(3)*s(4)-1); first_corners = first_corners(:); for j = 0:p(2)-1 for i = 0:p(1)-1 temp = im(first_corners + i + s(1)*j); temp = reshape(temp,1,size(col,2),size(col,3),size(col,4)); col(count,:,:,:) = temp; count = count + 1; end end % for j_start = one:p2:s2-one % for i_start = one:p1:s1-one % temp = init_patch; % temp2 = im(i_start:min(s1,i_start+p1-one),j_start:min(s2,j_start+p2-one),:,:); % temp(one:size(temp2,1),one:size(temp2,2),:,:) = temp2; % col(:,count,:,:) = reshape(temp,[],1,s(3),s(4)); % count = count + one; % end % end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function im = my_col2im(col,p,s,mode) if numel(s) == 3 s = [s size(col,4)]; end if numel(s) == 2 s = [s size(col,3) size(col,4)]; end im = zeros(s,'like',col); count = 1; if isa(im,'gpuArray') s = gpuArray(s); p = gpuArray(p); count = gpuArray(1); end first_corners = repmat( (1:p(1):s(1))',1,s(2)/p(2)); first_corners = bsxfun(@plus,first_corners,0:p(2)*s(1):s(1)*s(2)-1); first_corners = first_corners(:); first_corners = bsxfun(@plus, first_corners, 0:s(1)*s(2):s(1)*s(2)*s(3)-1); first_corners = first_corners(:); first_corners = bsxfun(@plus, first_corners, 0:s(1)*s(2)*s(3):s(1)*s(2)*s(3)*s(4)-1); first_corners = first_corners(:); for j = 0:p(2)-1 for i = 0:p(1)-1 temp = col(count,:,:,:); im(first_corners + i + s(1)*j) = temp(:); count = count + 1; end end % for j_start = 1:p(2):s(2)-1 % for i_start = 1:p(1):s(1)-1 % temp = col(:,count,:,:); % temp = reshape(temp,p(1),p(2),s(3),s(4)); % this_p = [min(s(1),i_start+p(1)-1)-i_start+1,min(s(2),j_start+p(2)-1)-j_start+1]; % im(i_start:min(s(1),i_start+p(1)-1),j_start:min(s(2),j_start+p(2)-1),:,:) = temp(1:this_p(1),1:this_p(2),:,:); % count = count + 1; % end % end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [m,ind] = maxpool2(x,pool) if numel(pool) == 1 pool = [pool pool]; end %x_pad = zeros(size(x,1)+2*pad,size(x,2)+2*pad,size(x,3),size(x,4),'like',x); m_temp = zeros(ceil(size(x,1)/pool(1)),size(x,2),size(x,3),size(x,4),'like',x); ind_temp = zeros(ceil(size(x,1)/pool(1)),size(x,2),size(x,3),size(x,4),'like',x); count = 1; for i_start = 1:pool(1):size(x,1)-1 i_end = min(i_start+pool(1),size(x,1)); [m_temp(count,:,:,:),ind_temp(count,:,:,:)] = max(x(i_start:i_end,:,:,:),[],1); ind_temp(count,:,:,:) = ind_temp(count,:,:,:) + i_start - 1; count = count + 1; end m = zeros(ceil(size(x,1)/pool(1)),ceil(size(x,2)/pool(2)),size(x,3),size(x,4),'like',x); ind1 = zeros(ceil(size(x,1)/pool(1)),ceil(size(x,2)/pool(2)),size(x,3),size(x,4),'like',x); ind2 = zeros(ceil(size(x,1)/pool(1)),ceil(size(x,2)/pool(2)),size(x,3),size(x,4),'like',x); count = 1; for j_start = 1:pool(1):size(x,1)-1 j_end = min(j_start+pool(2),size(x,2)); [m(:,count,:,:),ind2(:,count,:,:)] = max(m_temp(:,j_start:j_end,:,:),[],2); %ind2(:,count,:,:) = ind2(:,count,:,:) + j_start - 1; count = count + 1; end end
github
startcode/qp-oases-master
make.m
.m
qp-oases-master/interfaces/simulink/make.m
8,453
utf_8
b56fed5a0b41150b8af75373612324c7
function [] = make( varargin ) %MAKE Compiles the Simulink interface of qpOASES. % %Type make to compile all interfaces that % have been modified, %type make clean to delete all compiled interfaces, %type make clean all to first delete and then compile % all interfaces, %type make 'name' to compile only the interface with % the given name (if it has been modified), %type make 'opt' to compile all interfaces using the % given compiler options. % %Copyright (C) 2013-2017 by Hans Joachim Ferreau, Andreas Potschka, %Christian Kirches et al. All rights reserved. %% %% This file is part of qpOASES. %% %% qpOASES -- An Implementation of the Online Active Set Strategy. %% Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka, %% Christian Kirches et al. All rights reserved. %% %% qpOASES is free software; you can redistribute it and/or %% modify it under the terms of the GNU Lesser General Public %% License as published by the Free Software Foundation; either %% version 2.1 of the License, or (at your option) any later version. %% %% qpOASES is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. %% See the GNU Lesser General Public License for more details. %% %% You should have received a copy of the GNU Lesser General Public %% License along with qpOASES; if not, write to the Free Software %% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA %% %% %% Filename: interfaces/simulink/make.m %% Author: Hans Joachim Ferreau, Andreas Potschka, Christian Kirches %% Version: 3.2 %% Date: 2007-2017 %% %% consistency check if ( exist( [pwd, '/make.m'],'file' ) == 0 ) error( ['ERROR (',mfilename '.m): Run this make script directly within the directory ', ... '<qpOASES-inst-dir>/interfaces/simulink, please.'] ); end if ( nargin > 2 ) error( ['ERROR (',mfilename '.m): At most two make arguments supported!'] ); else [ doClean,fcnNames,userFlags ] = analyseMakeArguments( nargin,varargin ); end %% define compiler settings QPOASESPATH = '../../'; DEBUGFLAGS = ' '; %DEBUGFLAGS = ' -g CXXDEBUGFLAGS=''$CXXDEBUGFLAGS -Wall -pedantic -Wshadow'' '; IFLAGS = [ '-I. -I',QPOASESPATH,'include',' -I',QPOASESPATH,'src',' ' ]; CPPFLAGS = [ IFLAGS, DEBUGFLAGS, '-largeArrayDims -D__cpluplus -D__MATLAB__ -D__SINGLE_OBJECT__',' ' ]; defaultFlags = '-O '; %% -D__NO_COPYRIGHT__ -D__SUPPRESSANYOUTPUT__ if ( ispc == 0 ) CPPFLAGS = [ CPPFLAGS, '-DLINUX ',' ' ]; else CPPFLAGS = [ CPPFLAGS, '-DWIN32 ',' ' ]; end if ( isempty(userFlags) > 0 ) CPPFLAGS = [ CPPFLAGS, defaultFlags,' ' ]; else CPPFLAGS = [ CPPFLAGS, userFlags,' ' ]; end mexExt = eval('mexext'); %% ensure copyright notice is displayed if ~isempty( strfind( CPPFLAGS,'-D__NO_COPYRIGHT__' ) ) printCopyrightNotice( ); end %% clean if desired if ( doClean > 0 ) eval( 'delete *.o;' ); eval( ['delete *.',mexExt,'*;'] ); disp( [ 'INFO (',mfilename '.m): Cleaned all compiled files.'] ); pause( 0.2 ); end if ( ~isempty(userFlags) ) disp( [ 'INFO (',mfilename '.m): Compiling all files with user-defined compiler flags (''',userFlags,''')...'] ); end %% call mex compiler for ii=1:length(fcnNames) cmd = [ 'mex -output ', fcnNames{ii}, ' ', CPPFLAGS, [fcnNames{ii},'.cpp'] ]; if ( exist( [fcnNames{ii},'.',mexExt],'file' ) == 0 ) eval( cmd ); disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' successfully created.'] ); else % check modification time of source/Make files and compiled mex file cppFile = dir( [pwd,'/',fcnNames{ii},'.cpp'] ); cppFileTimestamp = getTimestamp( cppFile ); makeFile = dir( [pwd,'/make.m'] ); makeFileTimestamp = getTimestamp( makeFile ); mexFile = dir( [pwd,'/',fcnNames{ii},'.',mexExt] ); if ( isempty(mexFile) == 0 ) mexFileTimestamp = getTimestamp( mexFile ); else mexFileTimestamp = 0; end if ( ( cppFileTimestamp >= mexFileTimestamp ) || ... ( makeFileTimestamp >= mexFileTimestamp ) ) eval( cmd ); disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' successfully created.'] ); else disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' already exists.'] ); end end end %% add qpOASES directory to path path( path,pwd ); end function [ doClean,fcnNames,userIFlags ] = analyseMakeArguments( nArgs,args ) doClean = 0; fcnNames = []; userIFlags = []; switch ( nArgs ) case 1 if ( strcmp( args{1},'all' ) > 0 ) fcnNames = { 'qpOASES_QProblemB','qpOASES_QProblem','qpOASES_SQProblem' }; elseif ( strcmp( args{1},'qpOASES_QProblemB' ) > 0 ) fcnNames = { 'qpOASES_QProblemB' }; elseif ( strcmp( args{1},'qpOASES_QProblem' ) > 0 ) fcnNames = { 'qpOASES_QProblem' }; elseif ( strcmp( args{1},'qpOASES_SQProblem' ) > 0 ) fcnNames = { 'qpOASES_SQProblem' }; elseif ( strcmp( args{1},'clean' ) > 0 ) doClean = 1; elseif ( strcmp( args{1}(1),'-' ) > 0 ) % make clean all with user-specified compiler flags userIFlags = args{1}; doClean = 1; fcnNames = { 'qpOASES_QProblemB','qpOASES_QProblem','qpOASES_SQProblem' }; else error( ['ERROR (',mfilename '.m): Invalid first argument (''',args{1},''')!'] ); end case 2 if ( strcmp( args{1},'clean' ) > 0 ) doClean = 1; else error( ['ERROR (',mfilename '.m): First argument must be ''clean'' if two arguments are provided!'] ); end if ( strcmp( args{2},'all' ) > 0 ) fcnNames = { 'qpOASES_QProblemB','qpOASES_QProblem','qpOASES_SQProblem' }; elseif ( strcmp( args{2},'qpOASES_QProblemB' ) > 0 ) fcnNames = { 'qpOASES_QProblemB' }; elseif ( strcmp( args{2},'qpOASES_QProblem' ) > 0 ) fcnNames = { 'qpOASES_QProblem' }; elseif ( strcmp( args{2},'qpOASES_SQProblem' ) > 0 ) fcnNames = { 'qpOASES_SQProblem' }; else error( ['ERROR (',mfilename '.m): Invalid second argument (''',args{2},''')!'] ); end otherwise doClean = 0; fcnNames = { 'qpOASES_QProblemB','qpOASES_QProblem','qpOASES_SQProblem' }; userIFlags = []; end end function [ timestamp ] = getTimestamp( dateString ) try timestamp = dateString.datenum; catch timestamp = Inf; end end function [ ] = printCopyrightNotice( ) disp( ' ' ); disp( 'qpOASES -- An Implementation of the Online Active Set Strategy.' ); disp( 'Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,' ); disp( 'Christian Kirches et al. All rights reserved.' ); disp( ' ' ); disp( 'qpOASES is distributed under the terms of the' ); disp( 'GNU Lesser General Public License 2.1 in the hope that it will be' ); disp( 'useful, but WITHOUT ANY WARRANTY; without even the implied warranty' ); disp( 'of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.' ); disp( 'See the GNU Lesser General Public License for more details.' ); disp( ' ' ); disp( ' ' ); end %% %% end of file %%
github
startcode/qp-oases-master
qpOASES_options.m
.m
qp-oases-master/interfaces/octave/qpOASES_options.m
10,357
utf_8
719207ae527db13f4b22333e9550c579
%qpOASES -- An Implementation of the Online Active Set Strategy. %Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka, %Christian Kirches et al. All rights reserved. % %qpOASES is distributed under the terms of the %GNU Lesser General Public License 2.1 in the hope that it will be %useful, but WITHOUT ANY WARRANTY; without even the implied warranty %of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. %See the GNU Lesser General Public License for more details. % %--------------------------------------------------------------------------------- % %Returns a struct containing values for all options to be used within qpOASES. % %Call % options = qpOASES_options( 'default' ); % options = qpOASES_options( 'reliable' ); % options = qpOASES_options( 'MPC' ); %to obtain a set of default options or a pre-defined set of options tuned %for reliable or fast QP solution, respectively. % %Call % options = qpOASES_options( 'option1',value1,'option2',value2,... ) %to obtain a set of default options but with 'option1' set to value1 etc. % %Call % options = qpOASES_options( oldOptions,'option1',value1,... ) %to obtain a copy of the options struct oldOptions but with 'option1' set %to value1 etc. % %Call % options = qpOASES_options( 'default', 'option1',value1,... ) % options = qpOASES_options( 'reliable','option1',value1,... ) % options = qpOASES_options( 'MPC', 'option1',value1,... ) %to obtain a set of default options or a pre-defined set of options tuned %for reliable or fast QP solution, respectively, but with 'option1' set to %value1 etc. % % %qpOASES features the following options: % maxIter - Maximum number of iterations (if set % to -1, a value is chosen heuristically) % maxCpuTime - Maximum CPU time in seconds (if set % to -1, only iteration limit is used) % printLevel - 0: no printed output, % 1: only error messages are printed, % 2: iterations and error messages are printed, % 3: all available messages are printed. % % enableRamping - Enables (1) or disables (0) ramping. % enableFarBounds - Enables (1) or disables (0) the use of % far bounds. % enableFlippingBounds - Enables (1) or disables (0) the use of % flipping bounds. % enableRegularisation - Enables (1) or disables (0) automatic % Hessian regularisation. % enableFullLITests - Enables (1) or disables (0) condition-hardened % (but more expensive) LI test. % enableNZCTests - Enables (1) or disables (0) nonzero curvature % tests. % enableDriftCorrection - Specifies the frequency of drift corrections: % 0: turns them off, % 1: uses them at each iteration etc. % enableCholeskyRefactorisation - Specifies the frequency of a full re- % factorisation of projected Hessian matrix: % 0: turns them off, % 1: uses them at each iteration etc. % enableEqualities - Specifies whether equalities should be treated % as always active (1) or not (0) % % terminationTolerance - Relative termination tolerance to stop homotopy. % boundTolerance - If upper and lower bounds differ less than this % tolerance, they are regarded equal, i.e. as % equality constraint. % boundRelaxation - Initial relaxation of bounds to start homotopy % and initial value for far bounds. % epsNum - Numerator tolerance for ratio tests. % epsDen - Denominator tolerance for ratio tests. % maxPrimalJump - Maximum allowed jump in primal variables in % nonzero curvature tests. % maxDualJump - Maximum allowed jump in dual variables in % linear independence tests. % % initialRamping - Start value for ramping strategy. % finalRamping - Final value for ramping strategy. % initialFarBounds - Initial size for far bounds. % growFarBounds - Factor to grow far bounds. % initialStatusBounds - Initial status of bounds at first iteration: % 0: all bounds inactive, % -1: all bounds active at their lower bound, % +1: all bounds active at their upper bound. % epsFlipping - Tolerance of squared Cholesky diagonal factor % which triggers flipping bound. % numRegularisationSteps - Maximum number of successive regularisation steps. % epsRegularisation - Scaling factor of identity matrix used for % Hessian regularisation. % numRefinementSteps - Maximum number of iterative refinement steps. % epsIterRef - Early termination tolerance for iterative % refinement. % epsLITests - Tolerance for linear independence tests. % epsNZCTests - Tolerance for nonzero curvature tests. % % %See also QPOASES, QPOASES_SEQUENCE, QPOASES_AUXINPUT % % %For additional information see the qpOASES User's Manual or %visit http://www.qpOASES.org/. % %Please send remarks and questions to [email protected]! function [ options ] = qpOASES_options( varargin ) firstIsStructOrScheme = 0; if ( nargin == 0 ) options = qpOASES_default_options(); else if ( isstruct( varargin{1} ) ) if ( mod( nargin,2 ) ~= 1 ) error('ERROR (qpOASES_options): Options must be specified in pairs!'); end options = varargin{1}; firstIsStructOrScheme = 1; else if ( ischar( varargin{1} ) ) if ( mod( nargin,2 ) == 0 ) options = qpOASES_default_options(); else if ( ( nargin > 1 ) && ( ischar( varargin{nargin} ) ) ) error('ERROR (qpOASES_options): Options must be specified in pairs!'); end switch ( varargin{1} ) case 'default' options = qpOASES_default_options(); case 'reliable' options = qpOASES_reliable_options(); case {'MPC','mpc','fast'} options = qpOASES_MPC_options(); otherwise error( ['ERROR (qpOASES_options): Only the following option schemes are defined: ''default'', ''reliable'', ''MPC''!'] ); end firstIsStructOrScheme = 1; end else error('ERROR (qpOASES_options): First argument needs to be a string or an options struct!'); end end end % set options to user-defined values for i=(1+firstIsStructOrScheme):2:nargin argName = varargin{i}; argValue = varargin{i+1}; if ( ( isempty( argName ) ) || ( ~ischar( argName ) ) ) error('ERROR (qpOASES_options): Argmument no. %d has to be a non-empty string!',i ); end if ( ( ischar(argValue) ) || ( ~isscalar( argValue ) ) ) error('ERROR (qpOASES_options): Argmument no. %d has to be a scalar constant!',i+1 ); end if ( ~isfield( options,argName ) ) error('ERROR (qpOASES_options): Argmument no. %d is an invalid option!',i ); end eval( ['options.',argName,' = ',num2str(argValue),';'] ); end end function [ options ] = qpOASES_default_options( ) % setup options struct with default values options = struct( 'maxIter', -1, ... 'maxCpuTime', -1, ... 'printLevel', 1, ... ... 'enableRamping', 1, ... 'enableFarBounds', 1, ... 'enableFlippingBounds', 1, ... 'enableRegularisation', 0, ... 'enableFullLITests', 0, ... 'enableNZCTests', 1, ... 'enableDriftCorrection', 1, ... 'enableCholeskyRefactorisation', 0, ... 'enableEqualities', 0, ... ... 'terminationTolerance', 5.0e6*eps, ... 'boundTolerance', 1.0e6*eps, ... 'boundRelaxation', 1.0e4, ... 'epsNum', -1.0e3*eps, ... 'epsDen', 1.0e3*eps, ... 'maxPrimalJump', 1.0e8, ... 'maxDualJump', 1.0e8, ... ... 'initialRamping', 0.5, ... 'finalRamping', 1.0, ... 'initialFarBounds', 1.0e6, ... 'growFarBounds', 1.0e3, ... 'initialStatusBounds', -1, ... 'epsFlipping', 1.0e3*eps, ... 'numRegularisationSteps', 0, ... 'epsRegularisation', 1.0e3*eps, ... 'numRefinementSteps', 1, ... 'epsIterRef', 1.0e2*eps, ... 'epsLITests', 1.0e5*eps, ... 'epsNZCTests', 3.1e3*eps ); end function [ options ] = qpOASES_reliable_options( ) % setup options struct with values for most reliable QP solution options = qpOASES_default_options( ); options.enableFullLITests = 1; options.enableCholeskyRefactorisation = 1; options.numRefinementSteps = 2; end function [ options ] = qpOASES_MPC_options( ) % setup options struct with values for most reliable QP solution options = qpOASES_default_options( ); options.enableRamping = 0; options.enableFarBounds = 1; options.enableFlippingBounds = 0; options.enableRegularisation = 1; options.enableNZCTests = 0; options.enableDriftCorrection = 0; options.enableEqualities = 1; options.terminationTolerance = 1.0e9*eps; options.initialStatusBounds = 0; options.numRegularisationSteps = 1; options.numRefinementSteps = 0; end
github
startcode/qp-oases-master
make.m
.m
qp-oases-master/interfaces/octave/make.m
8,296
utf_8
2ab639ac67f632a68b41a91e0b666f74
function [] = make( varargin ) %MAKE Compiles the octave interface of qpOASES. % %Type make to compile all interfaces that % have been modified, %type make clean to delete all compiled interfaces, %type make clean all to first delete and then compile % all interfaces, %type make 'name' to compile only the interface with % the given name (if it has been modified), %type make 'opt' to compile all interfaces using the % given compiler options. % %Copyright (C) 2013-2017 by Hans Joachim Ferreau, Andreas Potschka, %Christian Kirches et al. All rights reserved. %% %% This file is part of qpOASES. %% %% qpOASES -- An Implementation of the Online Active Set Strategy. %% Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka, %% Christian Kirches et al. All rights reserved. %% %% qpOASES is free software; you can redistribute it and/or %% modify it under the terms of the GNU Lesser General Public %% License as published by the Free Software Foundation; either %% version 2.1 of the License, or (at your option) any later version. %% %% qpOASES is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. %% See the GNU Lesser General Public License for more details. %% %% You should have received a copy of the GNU Lesser General Public %% License along with qpOASES; if not, write to the Free Software %% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA %% %% %% Filename: interfaces/octave/make.m %% Author: Hans Joachim Ferreau, Andreas Potschka, Christian Kirches %% Version: 3.2 %% Date: 2007-2017 %% %% consistency check if ( exist( [pwd, '/make.m'],'file' ) == 0 ) error( ['ERROR (',mfilename '.m): Run this make script directly within the directory', ... '<qpOASES-inst-dir>/interfaces/octave, please.'] ); end if ( nargin > 2 ) error( ['ERROR (',mfilename '.m): At most two make arguments supported!'] ); else [ doClean,fcnNames,userFlags ] = analyseMakeArguments( nargin,varargin ); end %% define compiler settings QPOASESPATH = '../../'; DEBUGFLAGS = ' '; %DEBUGFLAGS = ' -g CXXDEBUGFLAGS=''$CXXDEBUGFLAGS -Wall -pedantic -Wshadow'' '; IFLAGS = [ '-I. -I',QPOASESPATH,'include',' -I',QPOASESPATH,'src',' ' ]; CPPFLAGS = [ IFLAGS, DEBUGFLAGS, '-D__cpluplus -D__SINGLE_OBJECT__',' ' ]; %%removed: -largeArrayDims defaultFlags = '-D__NO_COPYRIGHT__ '; %% -D__SUPPRESSANYOUTPUT__ %%removed: -O if ( ispc == 0 ) CPPFLAGS = [ CPPFLAGS, '-DLINUX ',' ' ]; else CPPFLAGS = [ CPPFLAGS, '-DWIN32 ',' ' ]; end if ( isempty(userFlags) > 0 ) CPPFLAGS = [ CPPFLAGS, defaultFlags,' ' ]; else CPPFLAGS = [ CPPFLAGS, userFlags,' ' ]; end mexExt = mexext(); %% ensure copyright notice is displayed if ~isempty( strfind( CPPFLAGS,'-D__NO_COPYRIGHT__' ) ) printCopyrightNotice( ); end %% clean if desired if ( doClean > 0 ) eval( 'delete *.o;' ); eval( ['delete *.',mexExt,'*;'] ); disp( [ 'INFO (',mfilename '.m): Cleaned all compiled files.'] ); pause( 0.2 ); end if ( ~isempty(userFlags) ) disp( [ 'INFO (',mfilename '.m): Compiling all files with user-defined compiler flags (''',userFlags,''')...'] ); end %% call mex compiler for ii=1:length(fcnNames) cmd = [ 'mkoctfile --mex --output ', fcnNames{ii}, '.', mexext(), ' ', CPPFLAGS, [fcnNames{ii},'.cpp'] ]; if ( exist( [fcnNames{ii},'.',mexExt],'file' ) == 0 ) eval( cmd ); disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' successfully created.'] ); else % check modification time of source/Make files and compiled mex file cppFile = dir( [pwd,'/',fcnNames{ii},'.cpp'] ); cppFileTimestamp = getTimestamp( cppFile.date ); utilsFile = dir( [pwd,'/qpOASES_octave_utils.cpp'] ); utilsFileTimestamp = getTimestamp( utilsFile.date ); makeFile = dir( [pwd,'/make.m'] ); makeFileTimestamp = getTimestamp( makeFile.date ); mexFile = dir( [pwd,'/',fcnNames{ii},'.',mexExt] ); if ( isempty(mexFile) == 0 ) mexFileTimestamp = getTimestamp( mexFile.date ); else mexFileTimestamp = 0; end if ( ( cppFileTimestamp >= mexFileTimestamp ) || ... ( utilsFileTimestamp >= mexFileTimestamp ) || ... ( makeFileTimestamp >= mexFileTimestamp ) ) eval( cmd ); disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' successfully created.'] ); else disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' already exists.'] ); end end end %% add qpOASES directory to path path( path,pwd ); end function [ doClean,fcnNames,userIFlags ] = analyseMakeArguments( nArgs,args ) doClean = 0; fcnNames = []; userIFlags = []; switch ( nArgs ) case 1 if ( strcmp( args{1},'all' ) > 0 ) fcnNames = { 'qpOASES','qpOASES_sequence' }; elseif ( strcmp( args{1},'qpOASES' ) > 0 ) fcnNames = { 'qpOASES' }; elseif ( strcmp( args{1},'qpOASES_sequence' ) > 0 ) fcnNames = { 'qpOASES_sequence' }; elseif ( strcmp( args{1},'clean' ) > 0 ) doClean = 1; elseif ( strcmp( args{1}(1),'-' ) > 0 ) % make clean all with user-specified compiler flags userIFlags = args{1}; doClean = 1; fcnNames = { 'qpOASES','qpOASES_sequence' }; else error( ['ERROR (',mfilename '.m): Invalid first argument (''',args{1},''')!'] ); end case 2 if ( strcmp( args{1},'clean' ) > 0 ) doClean = 1; else error( ['ERROR (',mfilename '.m): First argument must be ''clean'' if two arguments are provided!'] ); end if ( strcmp( args{2},'all' ) > 0 ) fcnNames = { 'qpOASES','qpOASES_sequence' }; elseif ( strcmp( args{2},'qpOASES' ) > 0 ) fcnNames = { 'qpOASES' }; elseif ( strcmp( args{2},'qpOASES_sequence' ) > 0 ) fcnNames = { 'qpOASES_sequence' }; else error( ['ERROR (',mfilename '.m): Invalid second argument (''',args{2},''')!'] ); end otherwise fcnNames = { 'qpOASES','qpOASES_sequence' }; end end function [ timestamp ] = getTimestamp( dateString ) try timestamp = datenum( dateString ); catch timestamp = Inf; end end function [ ] = printCopyrightNotice( ) disp( ' ' ); disp( 'qpOASES -- An Implementation of the Online Active Set Strategy.' ); disp( 'Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,' ); disp( 'Christian Kirches et al. All rights reserved.' ); disp( ' ' ); disp( 'qpOASES is distributed under the terms of the' ); disp( 'GNU Lesser General Public License 2.1 in the hope that it will be' ); disp( 'useful, but WITHOUT ANY WARRANTY; without even the implied warranty' ); disp( 'of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.' ); disp( 'See the GNU Lesser General Public License for more details.' ); disp( ' ' ); disp( ' ' ); end %% %% end of file %%
github
startcode/qp-oases-master
qpOASES_auxInput.m
.m
qp-oases-master/interfaces/octave/qpOASES_auxInput.m
4,436
utf_8
fcc9652ca47c9fe89d24f7dc500fcb49
%qpOASES -- An Implementation of the Online Active Set Strategy. %Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka, %Christian Kirches et al. All rights reserved. % %qpOASES is distributed under the terms of the %GNU Lesser General Public License 2.1 in the hope that it will be %useful, but WITHOUT ANY WARRANTY; without even the implied warranty %of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. %See the GNU Lesser General Public License for more details. % %--------------------------------------------------------------------------------- % %Returns a struct containing all possible auxiliary inputs to be passed %to qpOASES. % %Call % auxInput = qpOASES_auxInput(); %to obtain a struct with all auxiliary inputs empty. % %Call % auxInput = qpOASES_auxInput( 'input1',value1,'input2',value2,... ) %to obtain a struct with 'input1' set to value1 etc. and all remaining %auxiliary inputs empty. % %Call % auxInput = qpOASES_auxInput( oldInputs,'input1',value1,... ) %to obtain a copy of the options struct oldInputs but with 'input1' set to %value1 etc. % % %qpOASES features the following auxiliary inputs: % hessianType - Provide information on Hessian matrix: % 0: Hessian is zero matrix (i.e. LP formulation) % 1: Hessian is identity matrix % 2: Hessian is (strictly) positive definite % 3: Hessian is positive definite on null space % of active bounds/constraints % 4: Hessian is positive semi-definite. % 5: Hessian is indefinite % Leave hessianType empty if Hessian type is unknown. % x0 - Initial guess for optimal primal solution. % guessedWorkingSetB - Initial guess for working set of bounds at % optimal solution (nV elements or empty). % guessedWorkingSetC - Initial guess for working set of constraints at % optimal solution (nC elements or empty). % The working sets needs to be encoded as follows: % 1: bound/constraint at its upper bound % 0: bound/constraint not at any bound % -1: bound/constraint at its lower bound % R - Cholesky factor of Hessian matrix (upper-triangular); % only used if both guessedWorkingSets are empty % and option initialStatusBounds is set to 0. % % %See also QPOASES, QPOASES_SEQUENCE, QPOASES_OPTIONS % % %For additional information see the qpOASES User's Manual or %visit http://www.qpOASES.org/. % %Please send remarks and questions to [email protected]! function [ auxInput ] = qpOASES_auxInput( varargin ) firstIsStruct = 0; if ( nargin == 0 ) auxInput = qpOASES_emptyAuxInput(); else if ( isstruct( varargin{1} ) ) if ( mod( nargin,2 ) ~= 1 ) error('ERROR (qpOASES_auxInput): Auxiliary inputs must be specified in pairs!'); end auxInput = varargin{1}; firstIsStruct = 1; else if ( mod( nargin,2 ) ~= 0 ) error('ERROR (qpOASES_auxInput): Auxiliary inputs must be specified in pairs!'); end auxInput = qpOASES_emptyAuxInput(); end end % set options to user-defined values for i=(1+firstIsStruct):2:nargin argName = varargin{i}; argValue = varargin{i+1}; if ( ( isempty( argName ) ) || ( ~ischar( argName ) ) ) error('ERROR (qpOASES_auxInput): Argmument no. %d has to be a non-empty string!',i ); end if ( ( ischar(argValue) ) || ( ~isnumeric( argValue ) ) ) error('ERROR (qpOASES_auxInput): Argmument no. %d has to be a numerical constant!',i+1 ); end if ( ~isfield( auxInput,argName ) ) error('ERROR (qpOASES_auxInput): Argmument no. %d is not a valid auxiliary input!',i ); end eval( ['auxInput.',argName,' = argValue;'] ); end end function [ auxInput ] = qpOASES_emptyAuxInput( ) % setup auxiliary input struct with all entries empty auxInput = struct( 'hessianType', [], ... 'x0', [], ... 'guessedWorkingSetB', [], ... 'guessedWorkingSetC', [], ... 'R', [] ... ); end
github
startcode/qp-oases-master
qpOASES_options.m
.m
qp-oases-master/interfaces/matlab/qpOASES_options.m
10,357
utf_8
719207ae527db13f4b22333e9550c579
%qpOASES -- An Implementation of the Online Active Set Strategy. %Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka, %Christian Kirches et al. All rights reserved. % %qpOASES is distributed under the terms of the %GNU Lesser General Public License 2.1 in the hope that it will be %useful, but WITHOUT ANY WARRANTY; without even the implied warranty %of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. %See the GNU Lesser General Public License for more details. % %--------------------------------------------------------------------------------- % %Returns a struct containing values for all options to be used within qpOASES. % %Call % options = qpOASES_options( 'default' ); % options = qpOASES_options( 'reliable' ); % options = qpOASES_options( 'MPC' ); %to obtain a set of default options or a pre-defined set of options tuned %for reliable or fast QP solution, respectively. % %Call % options = qpOASES_options( 'option1',value1,'option2',value2,... ) %to obtain a set of default options but with 'option1' set to value1 etc. % %Call % options = qpOASES_options( oldOptions,'option1',value1,... ) %to obtain a copy of the options struct oldOptions but with 'option1' set %to value1 etc. % %Call % options = qpOASES_options( 'default', 'option1',value1,... ) % options = qpOASES_options( 'reliable','option1',value1,... ) % options = qpOASES_options( 'MPC', 'option1',value1,... ) %to obtain a set of default options or a pre-defined set of options tuned %for reliable or fast QP solution, respectively, but with 'option1' set to %value1 etc. % % %qpOASES features the following options: % maxIter - Maximum number of iterations (if set % to -1, a value is chosen heuristically) % maxCpuTime - Maximum CPU time in seconds (if set % to -1, only iteration limit is used) % printLevel - 0: no printed output, % 1: only error messages are printed, % 2: iterations and error messages are printed, % 3: all available messages are printed. % % enableRamping - Enables (1) or disables (0) ramping. % enableFarBounds - Enables (1) or disables (0) the use of % far bounds. % enableFlippingBounds - Enables (1) or disables (0) the use of % flipping bounds. % enableRegularisation - Enables (1) or disables (0) automatic % Hessian regularisation. % enableFullLITests - Enables (1) or disables (0) condition-hardened % (but more expensive) LI test. % enableNZCTests - Enables (1) or disables (0) nonzero curvature % tests. % enableDriftCorrection - Specifies the frequency of drift corrections: % 0: turns them off, % 1: uses them at each iteration etc. % enableCholeskyRefactorisation - Specifies the frequency of a full re- % factorisation of projected Hessian matrix: % 0: turns them off, % 1: uses them at each iteration etc. % enableEqualities - Specifies whether equalities should be treated % as always active (1) or not (0) % % terminationTolerance - Relative termination tolerance to stop homotopy. % boundTolerance - If upper and lower bounds differ less than this % tolerance, they are regarded equal, i.e. as % equality constraint. % boundRelaxation - Initial relaxation of bounds to start homotopy % and initial value for far bounds. % epsNum - Numerator tolerance for ratio tests. % epsDen - Denominator tolerance for ratio tests. % maxPrimalJump - Maximum allowed jump in primal variables in % nonzero curvature tests. % maxDualJump - Maximum allowed jump in dual variables in % linear independence tests. % % initialRamping - Start value for ramping strategy. % finalRamping - Final value for ramping strategy. % initialFarBounds - Initial size for far bounds. % growFarBounds - Factor to grow far bounds. % initialStatusBounds - Initial status of bounds at first iteration: % 0: all bounds inactive, % -1: all bounds active at their lower bound, % +1: all bounds active at their upper bound. % epsFlipping - Tolerance of squared Cholesky diagonal factor % which triggers flipping bound. % numRegularisationSteps - Maximum number of successive regularisation steps. % epsRegularisation - Scaling factor of identity matrix used for % Hessian regularisation. % numRefinementSteps - Maximum number of iterative refinement steps. % epsIterRef - Early termination tolerance for iterative % refinement. % epsLITests - Tolerance for linear independence tests. % epsNZCTests - Tolerance for nonzero curvature tests. % % %See also QPOASES, QPOASES_SEQUENCE, QPOASES_AUXINPUT % % %For additional information see the qpOASES User's Manual or %visit http://www.qpOASES.org/. % %Please send remarks and questions to [email protected]! function [ options ] = qpOASES_options( varargin ) firstIsStructOrScheme = 0; if ( nargin == 0 ) options = qpOASES_default_options(); else if ( isstruct( varargin{1} ) ) if ( mod( nargin,2 ) ~= 1 ) error('ERROR (qpOASES_options): Options must be specified in pairs!'); end options = varargin{1}; firstIsStructOrScheme = 1; else if ( ischar( varargin{1} ) ) if ( mod( nargin,2 ) == 0 ) options = qpOASES_default_options(); else if ( ( nargin > 1 ) && ( ischar( varargin{nargin} ) ) ) error('ERROR (qpOASES_options): Options must be specified in pairs!'); end switch ( varargin{1} ) case 'default' options = qpOASES_default_options(); case 'reliable' options = qpOASES_reliable_options(); case {'MPC','mpc','fast'} options = qpOASES_MPC_options(); otherwise error( ['ERROR (qpOASES_options): Only the following option schemes are defined: ''default'', ''reliable'', ''MPC''!'] ); end firstIsStructOrScheme = 1; end else error('ERROR (qpOASES_options): First argument needs to be a string or an options struct!'); end end end % set options to user-defined values for i=(1+firstIsStructOrScheme):2:nargin argName = varargin{i}; argValue = varargin{i+1}; if ( ( isempty( argName ) ) || ( ~ischar( argName ) ) ) error('ERROR (qpOASES_options): Argmument no. %d has to be a non-empty string!',i ); end if ( ( ischar(argValue) ) || ( ~isscalar( argValue ) ) ) error('ERROR (qpOASES_options): Argmument no. %d has to be a scalar constant!',i+1 ); end if ( ~isfield( options,argName ) ) error('ERROR (qpOASES_options): Argmument no. %d is an invalid option!',i ); end eval( ['options.',argName,' = ',num2str(argValue),';'] ); end end function [ options ] = qpOASES_default_options( ) % setup options struct with default values options = struct( 'maxIter', -1, ... 'maxCpuTime', -1, ... 'printLevel', 1, ... ... 'enableRamping', 1, ... 'enableFarBounds', 1, ... 'enableFlippingBounds', 1, ... 'enableRegularisation', 0, ... 'enableFullLITests', 0, ... 'enableNZCTests', 1, ... 'enableDriftCorrection', 1, ... 'enableCholeskyRefactorisation', 0, ... 'enableEqualities', 0, ... ... 'terminationTolerance', 5.0e6*eps, ... 'boundTolerance', 1.0e6*eps, ... 'boundRelaxation', 1.0e4, ... 'epsNum', -1.0e3*eps, ... 'epsDen', 1.0e3*eps, ... 'maxPrimalJump', 1.0e8, ... 'maxDualJump', 1.0e8, ... ... 'initialRamping', 0.5, ... 'finalRamping', 1.0, ... 'initialFarBounds', 1.0e6, ... 'growFarBounds', 1.0e3, ... 'initialStatusBounds', -1, ... 'epsFlipping', 1.0e3*eps, ... 'numRegularisationSteps', 0, ... 'epsRegularisation', 1.0e3*eps, ... 'numRefinementSteps', 1, ... 'epsIterRef', 1.0e2*eps, ... 'epsLITests', 1.0e5*eps, ... 'epsNZCTests', 3.1e3*eps ); end function [ options ] = qpOASES_reliable_options( ) % setup options struct with values for most reliable QP solution options = qpOASES_default_options( ); options.enableFullLITests = 1; options.enableCholeskyRefactorisation = 1; options.numRefinementSteps = 2; end function [ options ] = qpOASES_MPC_options( ) % setup options struct with values for most reliable QP solution options = qpOASES_default_options( ); options.enableRamping = 0; options.enableFarBounds = 1; options.enableFlippingBounds = 0; options.enableRegularisation = 1; options.enableNZCTests = 0; options.enableDriftCorrection = 0; options.enableEqualities = 1; options.terminationTolerance = 1.0e9*eps; options.initialStatusBounds = 0; options.numRegularisationSteps = 1; options.numRefinementSteps = 0; end
github
startcode/qp-oases-master
make.m
.m
qp-oases-master/interfaces/matlab/make.m
8,997
utf_8
55ce9b55d80b98c042742e61a7372014
function [] = make( varargin ) %MAKE Compiles the Matlab interface of qpOASES. % %Type make to compile all interfaces that % have been modified, %type make clean to delete all compiled interfaces, %type make clean all to first delete and then compile % all interfaces, %type make 'name' to compile only the interface with % the given name (if it has been modified), %type make 'opt' to compile all interfaces using the % given compiler options. % %Copyright (C) 2013-2017 by Hans Joachim Ferreau, Andreas Potschka, %Christian Kirches et al. All rights reserved. %% %% This file is part of qpOASES. %% %% qpOASES -- An Implementation of the Online Active Set Strategy. %% Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka, %% Christian Kirches et al. All rights reserved. %% %% qpOASES is free software; you can redistribute it and/or %% modify it under the terms of the GNU Lesser General Public %% License as published by the Free Software Foundation; either %% version 2.1 of the License, or (at your option) any later version. %% %% qpOASES is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. %% See the GNU Lesser General Public License for more details. %% %% You should have received a copy of the GNU Lesser General Public %% License along with qpOASES; if not, write to the Free Software %% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA %% %% %% Filename: interfaces/matlab/make.m %% Author: Hans Joachim Ferreau, Andreas Potschka, Christian Kirches %% Version: 3.2 %% Date: 2007-2017 %% %% consistency check if ( exist( [pwd, '/make.m'],'file' ) == 0 ) error( ['ERROR (',mfilename '.m): Run this make script directly within the directory ', ... '<qpOASES-inst-dir>/interfaces/matlab, please.'] ); end if ( nargin > 2 ) error( ['ERROR (',mfilename '.m): At most two make arguments supported!'] ); else [ doClean,fcnNames,userFlags ] = analyseMakeArguments( nargin,varargin ); end %% define compiler settings QPOASESPATH = '../../'; DEBUGFLAGS = ' '; %DEBUGFLAGS = ' -v -g CXXDEBUGFLAGS=''$CXXDEBUGFLAGS -Wall -pedantic -Wshadow'' '; IFLAGS = [ '-I. -I',QPOASESPATH,'include',' -I',QPOASESPATH,'src',' ' ]; CPPFLAGS = [ IFLAGS, DEBUGFLAGS, '-largeArrayDims -D__cpluplus -D__MATLAB__ -D__SINGLE_OBJECT__',' ' ]; defaultFlags = '-O -D__NO_COPYRIGHT__ '; %% -D__SUPPRESSANYOUTPUT__ if ( ispc() == 0 ) CPPFLAGS = [ CPPFLAGS, '-DLINUX -lmwblas',' ' ]; else CPPFLAGS = [ CPPFLAGS, '-DWIN32',' ' ]; end if ( isempty(userFlags) > 0 ) CPPFLAGS = [ CPPFLAGS, defaultFlags,' ' ]; else CPPFLAGS = [ CPPFLAGS, userFlags,' ' ]; end %% determine if MA57 is available for sparse linear algebra isoctave = exist('OCTAVE_VERSION', 'builtin') ~= 0; if isoctave warning('Sparse linear algebra is currently not available for qpOASES in Octave. Passing sparse matrices works but will likely be slow.') SPARSEFLAGS = ''; elseif verLessThan('matlab', '7.8') warning('Sparse linear algebra is currently available for qpOASES only for Matlab versions 7.8 and later. Passing sparse matrices works but will likely be slow.') SPARSEFLAGS = ''; else if ( ispc() == 0 ) SPARSEFLAGS = '-largeArrayDims -D__USE_LONG_INTEGERS__ -D__USE_LONG_FINTS__ -DSOLVER_MA57 -lmwma57 '; else SPARSEFLAGS = '-largeArrayDims -D__USE_LONG_INTEGERS__ -D__USE_LONG_FINTS__ '; end end mexExt = eval('mexext'); %% ensure copyright notice is displayed if ~isempty( strfind( CPPFLAGS,'-D__NO_COPYRIGHT__' ) ) printCopyrightNotice( ); end %% clean if desired if ( doClean > 0 ) eval( 'delete *.o;' ); eval( ['delete *.',mexExt,'*;'] ); disp( [ 'INFO (',mfilename '.m): Cleaned all compiled files.'] ); pause( 0.2 ); end if ( ~isempty(userFlags) ) disp( [ 'INFO (',mfilename '.m): Compiling all files with user-defined compiler flags (''',userFlags,''')...'] ); end %% call mex compiler for ii=1:length(fcnNames) cmd = [ 'mex -output ', fcnNames{ii}, ' ', CPPFLAGS, SPARSEFLAGS, [fcnNames{ii},'.cpp'] ]; if ( exist( [fcnNames{ii},'.',mexExt],'file' ) == 0 ) eval( cmd ); disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' successfully created.'] ); else % check modification time of source/Make files and compiled mex file cppFile = dir( [pwd,'/',fcnNames{ii},'.cpp'] ); cppFileTimestamp = getTimestamp( cppFile ); utilsFile = dir( [pwd,'/qpOASES_matlab_utils.cpp'] ); utilsFileTimestamp = getTimestamp( utilsFile ); makeFile = dir( [pwd,'/make.m'] ); makeFileTimestamp = getTimestamp( makeFile ); mexFile = dir( [pwd,'/',fcnNames{ii},'.',mexExt] ); if ( isempty(mexFile) == 0 ) mexFileTimestamp = getTimestamp( mexFile ); else mexFileTimestamp = 0; end if ( ( cppFileTimestamp >= mexFileTimestamp ) || ... ( utilsFileTimestamp >= mexFileTimestamp ) || ... ( makeFileTimestamp >= mexFileTimestamp ) ) eval( cmd ); disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' successfully created.'] ); else disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' already exists.'] ); end end end %% add qpOASES directory to path path( path,pwd ); end function [ doClean,fcnNames,userIFlags ] = analyseMakeArguments( nArgs,args ) doClean = 0; fcnNames = []; userIFlags = []; switch ( nArgs ) case 1 if ( strcmp( args{1},'all' ) > 0 ) fcnNames = { 'qpOASES','qpOASES_sequence' }; elseif ( strcmp( args{1},'qpOASES' ) > 0 ) fcnNames = { 'qpOASES' }; elseif ( strcmp( args{1},'qpOASES_sequence' ) > 0 ) fcnNames = { 'qpOASES_sequence' }; elseif ( strcmp( args{1},'clean' ) > 0 ) doClean = 1; elseif ( strcmp( args{1}(1),'-' ) > 0 ) % make clean all with user-specified compiler flags userIFlags = args{1}; doClean = 1; fcnNames = { 'qpOASES','qpOASES_sequence' }; else error( ['ERROR (',mfilename '.m): Invalid first argument (''',args{1},''')!'] ); end case 2 if ( strcmp( args{1},'clean' ) > 0 ) doClean = 1; else error( ['ERROR (',mfilename '.m): First argument must be ''clean'' if two arguments are provided!'] ); end if ( strcmp( args{2},'all' ) > 0 ) fcnNames = { 'qpOASES','qpOASES_sequence' }; elseif ( strcmp( args{2},'qpOASES' ) > 0 ) fcnNames = { 'qpOASES' }; elseif ( strcmp( args{2},'qpOASES_sequence' ) > 0 ) fcnNames = { 'qpOASES_sequence' }; else error( ['ERROR (',mfilename '.m): Invalid second argument (''',args{2},''')!'] ); end otherwise fcnNames = { 'qpOASES','qpOASES_sequence' }; end end function [ timestamp ] = getTimestamp( dateString ) try timestamp = dateString.datenum; catch timestamp = Inf; end end function [ ] = printCopyrightNotice( ) disp( ' ' ); disp( 'qpOASES -- An Implementation of the Online Active Set Strategy.' ); disp( 'Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,' ); disp( 'Christian Kirches et al. All rights reserved.' ); disp( ' ' ); disp( 'qpOASES is distributed under the terms of the' ); disp( 'GNU Lesser General Public License 2.1 in the hope that it will be' ); disp( 'useful, but WITHOUT ANY WARRANTY; without even the implied warranty' ); disp( 'of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.' ); disp( 'See the GNU Lesser General Public License for more details.' ); disp( ' ' ); disp( ' ' ); end %% %% end of file %%
github
startcode/qp-oases-master
qpOASES_auxInput.m
.m
qp-oases-master/interfaces/matlab/qpOASES_auxInput.m
4,436
utf_8
fcc9652ca47c9fe89d24f7dc500fcb49
%qpOASES -- An Implementation of the Online Active Set Strategy. %Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka, %Christian Kirches et al. All rights reserved. % %qpOASES is distributed under the terms of the %GNU Lesser General Public License 2.1 in the hope that it will be %useful, but WITHOUT ANY WARRANTY; without even the implied warranty %of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. %See the GNU Lesser General Public License for more details. % %--------------------------------------------------------------------------------- % %Returns a struct containing all possible auxiliary inputs to be passed %to qpOASES. % %Call % auxInput = qpOASES_auxInput(); %to obtain a struct with all auxiliary inputs empty. % %Call % auxInput = qpOASES_auxInput( 'input1',value1,'input2',value2,... ) %to obtain a struct with 'input1' set to value1 etc. and all remaining %auxiliary inputs empty. % %Call % auxInput = qpOASES_auxInput( oldInputs,'input1',value1,... ) %to obtain a copy of the options struct oldInputs but with 'input1' set to %value1 etc. % % %qpOASES features the following auxiliary inputs: % hessianType - Provide information on Hessian matrix: % 0: Hessian is zero matrix (i.e. LP formulation) % 1: Hessian is identity matrix % 2: Hessian is (strictly) positive definite % 3: Hessian is positive definite on null space % of active bounds/constraints % 4: Hessian is positive semi-definite. % 5: Hessian is indefinite % Leave hessianType empty if Hessian type is unknown. % x0 - Initial guess for optimal primal solution. % guessedWorkingSetB - Initial guess for working set of bounds at % optimal solution (nV elements or empty). % guessedWorkingSetC - Initial guess for working set of constraints at % optimal solution (nC elements or empty). % The working sets needs to be encoded as follows: % 1: bound/constraint at its upper bound % 0: bound/constraint not at any bound % -1: bound/constraint at its lower bound % R - Cholesky factor of Hessian matrix (upper-triangular); % only used if both guessedWorkingSets are empty % and option initialStatusBounds is set to 0. % % %See also QPOASES, QPOASES_SEQUENCE, QPOASES_OPTIONS % % %For additional information see the qpOASES User's Manual or %visit http://www.qpOASES.org/. % %Please send remarks and questions to [email protected]! function [ auxInput ] = qpOASES_auxInput( varargin ) firstIsStruct = 0; if ( nargin == 0 ) auxInput = qpOASES_emptyAuxInput(); else if ( isstruct( varargin{1} ) ) if ( mod( nargin,2 ) ~= 1 ) error('ERROR (qpOASES_auxInput): Auxiliary inputs must be specified in pairs!'); end auxInput = varargin{1}; firstIsStruct = 1; else if ( mod( nargin,2 ) ~= 0 ) error('ERROR (qpOASES_auxInput): Auxiliary inputs must be specified in pairs!'); end auxInput = qpOASES_emptyAuxInput(); end end % set options to user-defined values for i=(1+firstIsStruct):2:nargin argName = varargin{i}; argValue = varargin{i+1}; if ( ( isempty( argName ) ) || ( ~ischar( argName ) ) ) error('ERROR (qpOASES_auxInput): Argmument no. %d has to be a non-empty string!',i ); end if ( ( ischar(argValue) ) || ( ~isnumeric( argValue ) ) ) error('ERROR (qpOASES_auxInput): Argmument no. %d has to be a numerical constant!',i+1 ); end if ( ~isfield( auxInput,argName ) ) error('ERROR (qpOASES_auxInput): Argmument no. %d is not a valid auxiliary input!',i ); end eval( ['auxInput.',argName,' = argValue;'] ); end end function [ auxInput ] = qpOASES_emptyAuxInput( ) % setup auxiliary input struct with all entries empty auxInput = struct( 'hessianType', [], ... 'x0', [], ... 'guessedWorkingSetB', [], ... 'guessedWorkingSetC', [], ... 'R', [] ... ); end
github
startcode/qp-oases-master
runAllTests.m
.m
qp-oases-master/testing/matlab/runAllTests.m
5,548
utf_8
bdff35e75080becaee269cf4f487d115
function [ successFlag ] = runAllTests( doPrint ) if ( nargin < 1 ) doPrint = 0; end successFlag = 1; curWarnLevel = warning; warning('off'); % add sub-folders to Matlab path setupTestingPaths(); clc; %% run interface tests fprintf( 'Running qpOASES interface tests... ' ) successFlag = updateSuccessFlag( successFlag, runInterfaceTest( 10,20, doPrint,42 ) ); fprintf( 'Running qpOASES_sequence interface tests... ' ) successFlag = updateSuccessFlag( successFlag, runInterfaceSeqTest( 8,5, doPrint,42 ) ); %% run functional tests fprintf( 'Running tests with random QPs having identity Hessian... ' ) successFlag = updateSuccessFlag( successFlag, runRandomIdHessian( 12,12, doPrint,4242 ) ); fprintf( 'Running tests with random QPs having zero Hessian... ' ) successFlag = updateSuccessFlag( successFlag, runRandomZeroHessian( 11,41, doPrint,4242 ) ); fprintf( 'Running qpOASES passing an empty Hessian matrix argument... ' ) successFlag = updateSuccessFlag( successFlag, runEmptyHessianTests( doPrint ) ); fprintf( 'Running alternativeX0 test... ' ) successFlag = updateSuccessFlag( successFlag, runAlternativeX0Test( 50,300,doPrint,4242 ) ); fprintf( 'Running testAPrioriKnownSeq1... ' ) successFlag = updateSuccessFlag( successFlag, runTestAPrioriKnownSeq1( doPrint ) ); fprintf( 'Running testSeq... ' ) successFlag = updateSuccessFlag( successFlag, runTestSeq( doPrint ) ); fprintf( 'Running testSparse... ' ) successFlag = updateSuccessFlag( successFlag, runTestSparse( doPrint ) ); fprintf( 'Running testSparse2... ' ) successFlag = updateSuccessFlag( successFlag, runTestSparse2( doPrint ) ); fprintf( 'Running testSparse3... ' ) successFlag = updateSuccessFlag( successFlag, runTestSparse3( doPrint ) ); fprintf( 'Running testSparse4... ' ) successFlag = updateSuccessFlag( successFlag, runTestSparse4( doPrint ) ); fprintf( 'Running simpleSpringExample... ' ) successFlag = updateSuccessFlag( successFlag, runSimpleSpringExample( doPrint ) ); fprintf( 'Running vanBarelsUnboundedQP... ' ) successFlag = updateSuccessFlag( successFlag, runVanBarelsUnboundedQP( doPrint ) ); fprintf( 'Running alexInfeas1... ' ) successFlag = updateSuccessFlag( successFlag, runAlexInfeas1( doPrint ) ); %fprintf( 'Running alexInfeas2... ' ) %successFlag = updateSuccessFlag( successFlag, runAlexInfeas2( doPrint ) ); %fprintf( 'Running QAP8... ' ) %successFlag = updateSuccessFlag( successFlag, runQAP( doPrint ) ); fprintf( 'Running testWorkingSetLI... ' ) successFlag = updateSuccessFlag( successFlag, runTestWorkingSetLI( doPrint ) ); fprintf( 'Running runExternalCholeskyTests... ' ) successFlag = updateSuccessFlag( successFlag, runExternalCholeskyTests( doPrint ) ); fprintf( 'Running EXAMPEL1... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkEXAMPLE1( 10,doPrint ) ); fprintf( 'Running EXAMPLE1A... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkEXAMPLE1A( 10,doPrint ) ); fprintf( 'Running EXAMPLE1B... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkEXAMPLE1B( 10,doPrint ) ); fprintf( 'Running CHAIN1... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkCHAIN1( 20,doPrint ) ); fprintf( 'Running CHAIN1A... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkCHAIN1A( 20,doPrint ) ); fprintf( 'Running CRANE1... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkCRANE1( 100,doPrint ) ); fprintf( 'Running CRANE2... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkCRANE2( 100,doPrint ) ); fprintf( 'Running CRANE3... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkCRANE3( 100,doPrint ) ); fprintf( 'Running EQUALITY1... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkEQUALITY1( 100,doPrint ) ); fprintf( 'Running EQUALITY2... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkEQUALITY2( 3200,doPrint ) ); %fprintf( 'Running IDHESSIAN1... ' ); %successFlag = updateSuccessFlag( successFlag, runBenchmarkIDHESSIAN1( 1200,doPrint ) ); fprintf( 'Running DIESEL... ' ); successFlag = updateSuccessFlag( successFlag, runBenchmarkDIESEL( 230,doPrint ) ); fprintf( 'Running QSHARE1B... ' ) successFlag = updateSuccessFlag( successFlag, runQSHARE1B( doPrint ) ); %% display results disp( ' ' ); if ( successFlag == 0 ) disp( 'At least one test failed!' ); else disp( 'All available tests passed successfully!' ); end warning( curWarnLevel ); end function [ newSuccessFlag ] = updateSuccessFlag( curSuccessFlag,curResult ) switch ( curResult ) case 0 newSuccessFlag = 0; fprintf( 'failed!\n' ); case 1 newSuccessFlag = curSuccessFlag; fprintf( 'passed!\n' ); case -1 newSuccessFlag = curSuccessFlag; fprintf( 'problem data missing!\n' ); otherwise error( 'Unknown success flag!' ); end end
github
startcode/qp-oases-master
runInterfaceTest.m
.m
qp-oases-master/testing/matlab/tests/runInterfaceTest.m
16,774
utf_8
695fea461f4e440770b787dcafe361d2
function [ successFlag ] = runInterfaceTest( nV,nC, doPrint,seed ) if ( nargin < 4 ) seed = 42; if ( nargin < 3 ) doPrint = 1; if ( nargin < 2 ) nC = 10; if ( nargin < 1 ) nV = 5; end end end end successFlag = 1; for isSparseH=0:1 for isSparseA=0:1 successFlag = runSeveralInterfaceTests( successFlag, nV,nC,isSparseH,isSparseA, doPrint,seed ); end end end function [ successFLAG ] = runSeveralInterfaceTests( successFLAG, nV,nC, isSparseH,isSparseA, doPrint,seed ) %% test without or empty A matrix for hasA=0:1 for hasLowerB=0:1 for hasUpperB=0:1 for hasOptions=0:2 for hasX0=0:1 for hasWS=0:2 if ( ( hasWS ~= 2 ) || ( hasA ~= 0 ) || ( hasOptions == 1 ) || ( hasX0 ~= 0 ) ) curSuccessFLAG = runSingleInterfaceTest( nV,0,hasA,isSparseH,isSparseA, hasLowerB,hasUpperB,0,0,hasOptions,hasX0,hasWS, doPrint,seed ); successFLAG = min( successFLAG,curSuccessFLAG ); end end end end end end end %% test with non-empty A matrix for hasLowerB=0:1 for hasUpperB=0:1 for hasLowerC=0:1 for hasUpperC=0:1 for hasOptions=0:2 for hasX0=0:1 for hasWS=0:2 curSuccessFLAG = runSingleInterfaceTest( nV,nC,1,isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC,hasOptions,hasX0,hasWS, doPrint,seed ); successFLAG = min( successFLAG,curSuccessFLAG ); end end end end end end end end function [ successFLAG ] = runSingleInterfaceTest( nV,nC,hasA,isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC,hasOptions,hasX0,hasWS, doPrint,seed ) successFLAG = 0; qpData = generateExample( nV,nC, isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC, seed ); string = 'Testing qpOASES( H'; if ( isSparseH > 0 ) string = [string,'s,g']; else string = [string,'d,g']; end if ( nC > 0 ) if ( isSparseA > 0 ) string = [string,',As']; else string = [string,',Ad']; end else if ( hasA > 0 ) string = [string,',[]']; end end if ( hasLowerB > 0 ) string = [string,',lb']; else string = [string,',[]']; end if ( hasUpperB > 0 ) string = [string,',ub']; else string = [string,',[]']; end if ( hasLowerC > 0 ) string = [string,',lbA']; else if ( hasA > 0 ) string = [string,',[] ']; end end if ( hasUpperC > 0 ) string = [string,',ubA']; else if ( hasA > 0 ) string = [string,',[] ']; end end switch ( hasOptions ) case 1 string = [string,',opt']; case 2 string = [string,',[] ']; case 0 if ( ( hasX0 > 0 ) || ( hasWS > 0 ) ) string = [string,',[] ']; end end switch ( hasX0 ) case 1 string = [string,',{x0']; case 2 string = [string,',{[]']; case 0 if ( hasWS > 0 ) string = [string,',{[]']; end end switch ( hasWS ) case 1 string = [string,',WS}']; case 2 string = [string,',[]}']; end string = [string,' )... ']; if ( doPrint > 0 ) %disp( string ); end curSuccessFlag = callQpOases( qpData,hasA,hasOptions,hasX0,hasWS, 1 ); if ( curSuccessFlag > 0 ) string = [string,'pass!']; successFLAG = 1; else string = [string,'fail!']; end if ( doPrint > 0 ) disp( string ); if ( curSuccessFlag == 0 ) pause; end end end function [ successFLAG ] = callQpOases( qpData,hasA,hasOptions,hasX0,hasWS, doPrint ) if ( nargin < 6 ) doPrint = 1; end TOL = 1e-15; KKTTOL = 1e-6; successFLAG = 0; H = qpData.H; g = qpData.g; A = [qpData.Aeq;qpData.Ain]; lb = qpData.lb; ub = qpData.ub; lbA = [qpData.beq;qpData.lbA]; ubA = [qpData.beq;qpData.ubA]; [nV,dummy] = size(H); %#ok<NASGU> [nC,dummy] = size(A); %#ok<NASGU> if ( hasWS > 0 ) if ( hasWS == 1 ) wsB = 0 * ones( nV,1 ); wsC = 0 * ones( nC,1 ); else wsB = []; wsC = []; end if ( hasX0 > 0 ) if ( hasX0 == 1 ) x0 = -1e-3 * ones( nV,1 ); else x0 = []; end auxInput = qpOASES_auxInput( 'x0',x0,'guessedWorkingSetB',wsB,'guessedWorkingSetC',wsC ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ x1 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x2,f2 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); %#ok<NASGU> else [ x1 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x2,f2 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,lb,ub,options,auxInput ); %#ok<NASGU> end else if ( hasA > 0 ) [ x1 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x2,f2 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); %#ok<NASGU> else [ x1 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x2,f2 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,lb,ub,[],auxInput ); %#ok<NASGU> end end else % hasX0 == 0 %auxInput = qpOASES_auxInput( 'guessedWorkingSetB',wsB,'guessedWorkingSetC',wsC ); auxInput = qpOASES_auxInput( 'guessedWorkingSetC',wsC ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ x1 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x2,f2 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); %#ok<NASGU> else [ x1 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x2,f2 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,lb,ub,options,auxInput ); %#ok<NASGU> end else if ( hasA > 0 ) [ x1 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x2,f2 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); %#ok<NASGU> else [ x1 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x2,f2 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,lb,ub,[],auxInput ); %#ok<NASGU> end end end % hasX0 else % hasWS == 0 if ( hasX0 > 0 ) if ( hasX0 == 1 ) x0 = -1e-3 * ones( nV,1 ); else x0 = []; end auxInput = qpOASES_auxInput( 'x0',x0 ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ x1 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x2,f2 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options,auxInput ); %#ok<NASGU> else [ x1 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x2,f2 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,lb,ub,options,auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,lb,ub,options,auxInput ); %#ok<NASGU> end else if ( hasA > 0 ) [ x1 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x2,f2 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,[],auxInput ); %#ok<NASGU> else [ x1 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x2,f2 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x3,f3,e3 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x4,f4,e4,i4 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,lb,ub,[],auxInput ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,lb,ub,[],auxInput ); %#ok<NASGU> end end else % hasX0 == 0 if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ x1 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options ); [ x2,f2 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options ); [ x3,f3,e3 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options ); [ x4,f4,e4,i4 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,A,lb,ub,lbA,ubA,options ); %#ok<NASGU> else [ x1 ] = qpOASES( H,g,lb,ub,options ); [ x2,f2 ] = qpOASES( H,g,lb,ub,options ); [ x3,f3,e3 ] = qpOASES( H,g,lb,ub,options ); [ x4,f4,e4,i4 ] = qpOASES( H,g,lb,ub,options ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,lb,ub,options ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,lb,ub,options ); %#ok<NASGU> end else if ( hasA > 0 ) [ x1 ] = qpOASES( H,g,A,lb,ub,lbA,ubA ); [ x2,f2 ] = qpOASES( H,g,A,lb,ub,lbA,ubA ); [ x3,f3,e3 ] = qpOASES( H,g,A,lb,ub,lbA,ubA ); [ x4,f4,e4,i4 ] = qpOASES( H,g,A,lb,ub,lbA,ubA ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,A,lb,ub,lbA,ubA ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,A,lb,ub,lbA,ubA ); %#ok<NASGU> else [ x1 ] = qpOASES( H,g,lb,ub ); [ x2,f2 ] = qpOASES( H,g,lb,ub ); [ x3,f3,e3 ] = qpOASES( H,g,lb,ub ); [ x4,f4,e4,i4 ] = qpOASES( H,g,lb,ub ); [ x5,f5,e5,i5,l5 ] = qpOASES( H,g,lb,ub ); [ x6,f6,e6,i6,l6,w6 ] = qpOASES( H,g,lb,ub ); %#ok<NASGU> end end end % hasX0 end % hasWS % check whether all calls lead to same optimal solution % independent from output arguments if ( ( norm(x1-x2) > TOL ) || ... ( norm(x1-x3) > TOL ) || ... ( norm(x1-x4) > TOL ) || ... ( norm(x1-x5) > TOL ) || ... ( norm(x1-x6) > TOL ) ) if ( doPrint > 0 ) disp('diff in x') end return; end if ( ( norm(f2-f3) > TOL ) || ... ( norm(f2-f4) > TOL ) || ... ( norm(f2-f5) > TOL ) || ... ( norm(f2-f6) > TOL ) ) if ( doPrint > 0 ) disp('diff in fval') end return; end if ( ( norm(e3-e4) > TOL ) || ... ( norm(e3-e5) > TOL ) || ... ( norm(e3-e6) > TOL ) ) if ( doPrint > 0 ) disp('diff in exitflag') end return; end if ( ( norm(i4-i5) > TOL ) || ... ( norm(i4-i6) > TOL ) ) if ( doPrint > 0 ) disp('diff in iter') end return; end if ( norm(l5-l6) > TOL ) if ( doPrint > 0 ) disp('diff in lambda') end return; end kktTol = getKktResidual( H,g,A,lb,ub,lbA,ubA, x6,l6 ); if ( ( kktTol <= KKTTOL ) && ( e6 >= 0 ) ) successFLAG = 1; else if ( doPrint > 0 ) disp( ['kkt error: ',num2str(kktTol)] ) end end end
github
startcode/qp-oases-master
runRandomZeroHessian.m
.m
qp-oases-master/testing/matlab/tests/runRandomZeroHessian.m
14,399
utf_8
62c1efb1adf03ca9009d830d211f3ef8
function [ successFlag ] = runRandomZeroHessian( nV,nC, doPrint,seed ) if ( nargin < 4 ) seed = 42; if ( nargin < 3 ) doPrint = 1; if ( nargin < 2 ) nC = 10; if ( nargin < 1 ) nV = 5; end end end end successFlag = 1; for isSparseH=0:1 for isSparseA=0:1 successFlag = runSeveralIdSeqTests( successFlag, nV,nC,isSparseH,isSparseA, doPrint,seed ); end end end function [ successFlag ] = runSeveralIdSeqTests( successFlag, nV,nC, isSparseH,isSparseA, doPrint,seed ) %% test without or empty A matrix % { for hasA=0:1 for changeMat=0:hasA % cannot change matrices if QProblemB object is instantiated for hasOptions=1:1 for hasX0=0:2 for hasWS=0:2 curSuccessFLAG = runSingleIdSeqTest( nV,0,hasA,isSparseH,isSparseA, 1,1,0,0,hasOptions,hasX0,hasWS,changeMat, doPrint,seed ); successFlag = min( successFlag,curSuccessFLAG ); end end end end end %} %% test with non-empty A matrix for hasLowerC=0:1 for hasUpperC=0:1 for hasOptions=1:1 for hasX0=0:2 for hasWS=0:2 for changeMat=0:1 curSuccessFLAG = runSingleIdSeqTest( nV,nC,1,isSparseH,isSparseA, 1,1,hasLowerC,hasUpperC,hasOptions,hasX0,hasWS,changeMat, doPrint,seed ); successFlag = min( successFlag,curSuccessFLAG ); end end end end end end end function [ successFlag ] = runSingleIdSeqTest( nV,nC,hasA,isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC,hasOptions,hasX0,hasWS,changeMat, doPrint,seed ) successFlag = 0; qpFeatures = setupQpFeaturesStruct( ); qpFeatures.nV = nV; qpFeatures.nC = nC; qpFeatures.isSparseH = isSparseH; qpFeatures.isSparseA = isSparseA; qpFeatures.hasLowerB = hasLowerB; qpFeatures.hasUpperB = hasUpperB; qpFeatures.hasLowerC = hasLowerC; qpFeatures.hasUpperC = hasUpperC; qpFeatures.hessianType = 3; qpData1 = generateRandomQp( qpFeatures,seed ); qpData2 = generateRandomQp( qpFeatures,seed ); if ( changeMat == 0 ) string = 'Testing qpOASES_sequence( ''i/h/c'',0'; else string = 'Testing qpOASES_sequence( ''i/m/c'',0'; end if ( isSparseH > 0 ) string = [string,'s,g']; else string = [string,'d,g']; end if ( nC > 0 ) if ( isSparseA > 0 ) string = [string,',As']; else string = [string,',Ad']; end else if ( hasA > 0 ) string = [string,',[]']; end end if ( hasLowerB > 0 ) string = [string,',lb']; else string = [string,',[]']; end if ( hasUpperB > 0 ) string = [string,',ub']; else string = [string,',[]']; end if ( hasLowerC > 0 ) string = [string,',lbA']; else if ( hasA > 0 ) string = [string,',[] ']; end end if ( hasUpperC > 0 ) string = [string,',ubA']; else if ( hasA > 0 ) string = [string,',[] ']; end end switch ( hasOptions ) case 1 string = [string,',opt']; case 2 string = [string,',[] ']; case 0 if ( ( hasX0 > 0 ) || ( hasWS > 0 ) ) string = [string,',[] ']; end end switch ( hasX0 ) case 1 string = [string,',{x0']; case 2 string = [string,',{[]']; case 0 if ( hasWS > 0 ) string = [string,',{[]']; end end switch ( hasWS ) case 1 string = [string,',WS}']; case 2 string = [string,',[]}']; end string = [string,' )... ']; if ( doPrint > 0 ) %disp( string ); end %try curSuccessFlag = callQpOasesSeq( qpData1,qpData2,hasA,hasOptions,hasX0,hasWS,changeMat,doPrint ); %catch %curSuccessFlag = 0; %end if ( curSuccessFlag > 0 ) string = [string,'pass!']; successFlag = 1; else string = [string,'fail!']; end if ( doPrint > 0 ) disp( string ); if ( curSuccessFlag == 0 ) %pause; end end end function [ successFlag ] = callQpOasesSeq( qpData1,qpData2,hasA,hasOptions,hasX0,hasWS,changeMat, doPrint ) if ( nargin < 8 ) doPrint = 1; end TOL = 1e-15; KKTTOL = 1e-6; successFlag = 0; H1 = qpData1.H; g1 = qpData1.g; A1 = [qpData1.Aeq;qpData1.Ain]; lb1 = qpData1.lb; ub1 = qpData1.ub; lbA1 = [qpData1.beq;qpData1.lbA]; ubA1 = [qpData1.beq;qpData1.ubA]; H2 = qpData2.H; g2 = qpData2.g; A2 = [qpData2.Aeq;qpData2.Ain]; lb2 = qpData2.lb; ub2 = qpData2.ub; lbA2 = [qpData2.beq;qpData2.lbA]; ubA2 = [qpData2.beq;qpData2.ubA]; [nV,dummy] = size(H1); [nC,dummy] = size(A1); if ( hasWS > 0 ) if ( hasWS == 1 ) wsB = 0 * ones( nV,1 ); wsC = 0 * ones( nC,1 ); else wsB = []; wsC = []; end if ( hasX0 > 0 ) if ( hasX0 == 1 ) x0 = -1e-3 * ones( nV,1 ); else x0 = []; end auxInput = qpOASES_auxInput( 'x0',x0,'guessedWorkingSetB',wsB,'guessedWorkingSetC',wsC ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options( 'fast' ); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options,auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options,auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,[],auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2 ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2 ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,[],auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); qpOASES_sequence( 'c',QP ); end end else % hasX0 == 0 auxInput = qpOASES_auxInput( 'guessedWorkingSetB',wsB,'guessedWorkingSetC',wsC ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options( 'fast' ); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options,auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options,auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,[],auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,[] ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,[] ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,[],auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); qpOASES_sequence( 'c',QP ); end end end % hasX0 else % hasWS == 0 if ( hasX0 > 0 ) if ( hasX0 == 1 ) x0 = -1e-3 * ones( nV,1 ); else x0 = []; end auxInput = qpOASES_auxInput( 'x0',x0 ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options( 'fast' ); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options,auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options,auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,[],auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2 ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2 ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,[],auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); qpOASES_sequence( 'c',QP ); end end else % hasX0 == 0 if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options( 'fast' ); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1 ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2 ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2 ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1 ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); qpOASES_sequence( 'c',QP ); end end end % hasX0 end % hasWS kktTol1 = getKktResidual( H1,g1,A1,lb1,ub1,lbA1,ubA1, x1,l1 ); if ( changeMat > 0 ) kktTol2 = getKktResidual( H2,g2,A2,lb2,ub2,lbA2,ubA2, x2,l2 ); else kktTol2 = getKktResidual( H1,g2,A1,lb2,ub2,lbA2,ubA2, x2,l2 ); end if ( ( kktTol1 <= KKTTOL ) && ( e1 >= 0 ) && ( kktTol2 <= KKTTOL ) && ( e2 >= 0 ) ) successFlag = 1; else if ( doPrint > 0 ) disp( ['kkt error: ',num2str(kktTol1),'/',num2str(kktTol2)] ) end end end
github
startcode/qp-oases-master
runInterfaceSeqTest.m
.m
qp-oases-master/testing/matlab/tests/runInterfaceSeqTest.m
15,458
utf_8
7fd12067642b559d3dd08130be565119
function [ successFlag ] = runInterfaceSeqTest( nV,nC, doPrint,seed ) if ( nargin < 4 ) seed = 42; if ( nargin < 3 ) doPrint = 1; if ( nargin < 2 ) nC = 10; if ( nargin < 1 ) nV = 5; end end end end successFlag = 1; for isSparseH=0:1 for isSparseA=0:1 successFlag = runSeveralInterfaceSeqTests( successFlag, nV,nC,isSparseH,isSparseA, doPrint,seed ); end end end function [ successFlag ] = runSeveralInterfaceSeqTests( successFlag, nV,nC, isSparseH,isSparseA, doPrint,seed ) %% test without or empty A matrix for hasA=0:1 for changeMat=0:hasA % cannot change matrices if QProblemB object is instantiated for hasLowerB=0:1 for hasUpperB=0:1 for hasOptions=0:2 for hasX0=0:2 for hasWS=0:2 curSuccessFLAG = runSingleInterfaceSeqTest( nV,0,hasA,isSparseH,isSparseA, hasLowerB,hasUpperB,0,0,hasOptions,hasX0,hasWS,changeMat, doPrint,seed ); successFlag = min( successFlag,curSuccessFLAG ); end end end end end end end %% test with non-empty A matrix for hasLowerB=0:1 for hasUpperB=0:1 for hasLowerC=0:1 for hasUpperC=0:1 for hasOptions=0:2 for hasX0=0:2 for hasWS=0:2 for changeMat=0:1 curSuccessFLAG = runSingleInterfaceSeqTest( nV,nC,1,isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC,hasOptions,hasX0,hasWS,changeMat, doPrint,seed ); successFlag = min( successFlag,curSuccessFLAG ); end end end end end end end end end function [ successFlag ] = runSingleInterfaceSeqTest( nV,nC,hasA,isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC,hasOptions,hasX0,hasWS,changeMat, doPrint,seed ) successFlag = 0; qpData1 = generateExample( nV,nC, isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC, seed ); if ( changeMat > 0 ) qpData2 = generateExample( nV,nC, isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC, seed+1 ); else qpData2 = generateExample( nV,nC, isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC, seed+1,qpData1.H,qpData1.Ain ); end if ( changeMat == 0 ) string = 'Testing qpOASES_sequence( ''i/h/c'',H'; else string = 'Testing qpOASES_sequence( ''i/m/c'',H'; end if ( isSparseH > 0 ) string = [string,'s,g']; else string = [string,'d,g']; end if ( nC > 0 ) if ( isSparseA > 0 ) string = [string,',As']; else string = [string,',Ad']; end else if ( hasA > 0 ) string = [string,',[]']; end end if ( hasLowerB > 0 ) string = [string,',lb']; else string = [string,',[]']; end if ( hasUpperB > 0 ) string = [string,',ub']; else string = [string,',[]']; end if ( hasLowerC > 0 ) string = [string,',lbA']; else if ( hasA > 0 ) string = [string,',[] ']; end end if ( hasUpperC > 0 ) string = [string,',ubA']; else if ( hasA > 0 ) string = [string,',[] ']; end end switch ( hasOptions ) case 1 string = [string,',opt']; case 2 string = [string,',[] ']; case 0 if ( ( hasX0 > 0 ) || ( hasWS > 0 ) ) string = [string,',[] ']; end end switch ( hasX0 ) case 1 string = [string,',{x0']; case 2 string = [string,',{[]']; case 0 if ( hasWS > 0 ) string = [string,',{[]']; end end switch ( hasWS ) case 1 string = [string,',WS}']; case 2 string = [string,',[]}']; end string = [string,' )... ']; if ( doPrint > 0 ) disp( string ); end curSuccessFlag = callQpOasesSeq( qpData1,qpData2,hasA,hasOptions,hasX0,hasWS,changeMat ); if ( curSuccessFlag > 0 ) string = [string,'pass!']; successFlag = 1; else string = [string,'fail!']; end if ( doPrint > 0 ) disp( string ); if ( curSuccessFlag == 0 ) pause(0.1); end end end function [ successFlag ] = callQpOasesSeq( qpData1,qpData2,hasA,hasOptions,hasX0,hasWS,changeMat, doPrint ) if ( nargin < 8 ) doPrint = 1; end %TOL = 1e-15; KKTTOL = 1e-6; successFlag = 0; H1 = qpData1.H; g1 = qpData1.g; A1 = [qpData1.Aeq;qpData1.Ain]; lb1 = qpData1.lb; ub1 = qpData1.ub; lbA1 = [qpData1.beq;qpData1.lbA]; ubA1 = [qpData1.beq;qpData1.ubA]; if ( changeMat > 0 ) H2 = qpData2.H; else H2 = H1; end g2 = qpData2.g; if ( changeMat > 0 ) A2 = [qpData2.Aeq;qpData2.Ain]; else A2 = A1; end lb2 = qpData2.lb; ub2 = qpData2.ub; lbA2 = [qpData2.beq;qpData2.lbA]; ubA2 = [qpData2.beq;qpData2.ubA]; [nV,dummy] = size(H1); %#ok<NASGU> [nC,dummy] = size(A1); %#ok<NASGU> if ( hasWS > 0 ) if ( hasWS == 1 ) wsB = 0 * ones( nV,1 ); wsC = 0 * ones( nC,1 ); else wsB = []; wsC = []; end if ( hasX0 > 0 ) if ( hasX0 == 1 ) x0 = -1e-3 * ones( nV,1 ); else x0 = []; end auxInput = qpOASES_auxInput( 'x0',x0,'guessedWorkingSetB',wsB,'guessedWorkingSetC',wsC ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options,auxInput ); %#ok<NASGU> if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); %#ok<NASGU> else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); %#ok<NASGU> end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options,auxInput ); %#ok<NASGU> [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); %#ok<NASGU> qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,[],auxInput ); %#ok<NASGU> if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2 ); %#ok<NASGU> else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2 ); %#ok<NASGU> end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,[],auxInput ); %#ok<NASGU> [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); %#ok<NASGU> qpOASES_sequence( 'c',QP ); end end else % hasX0 == 0 %auxInput = qpOASES_auxInput( 'guessedWorkingSetB',wsB,'guessedWorkingSetC',wsC ); auxInput = qpOASES_auxInput( 'guessedWorkingSetB',wsB ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options,auxInput ); %#ok<NASGU> if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); %#ok<NASGU> else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); %#ok<NASGU> end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options,auxInput ); %#ok<NASGU> [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); %#ok<NASGU> qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,[],auxInput ); %#ok<NASGU> if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,[] ); %#ok<NASGU> else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,[] ); %#ok<NASGU> end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,[],auxInput ); %#ok<NASGU> [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); %#ok<NASGU> qpOASES_sequence( 'c',QP ); end end end % hasX0 else % hasWS == 0 if ( hasX0 > 0 ) if ( hasX0 == 1 ) x0 = -1e-3 * ones( nV,1 ); else x0 = []; end auxInput = qpOASES_auxInput( 'x0',x0 ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options,auxInput ); %#ok<NASGU> if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); %#ok<NASGU> else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); %#ok<NASGU> end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options,auxInput ); %#ok<NASGU> [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); %#ok<NASGU> qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,[],auxInput ); %#ok<NASGU> if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2 ); %#ok<NASGU> else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2 ); %#ok<NASGU> end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,[],auxInput ); %#ok<NASGU> [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); %#ok<NASGU> qpOASES_sequence( 'c',QP ); end end else % hasX0 == 0 if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options ); %#ok<NASGU> if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); %#ok<NASGU> else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); %#ok<NASGU> end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options ); %#ok<NASGU> [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); %#ok<NASGU> qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1 ); %#ok<NASGU> if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2 ); %#ok<NASGU> else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2 ); %#ok<NASGU> end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1 ); %#ok<NASGU> [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); %#ok<NASGU> qpOASES_sequence( 'c',QP ); end end end % hasX0 end % hasWS kktTol1 = getKktResidual( H1,g1,A1,lb1,ub1,lbA1,ubA1, x1,l1 ); if ( changeMat > 0 ) kktTol2 = getKktResidual( H2,g2,A2,lb2,ub2,lbA2,ubA2, x2,l2 ); else kktTol2 = getKktResidual( H1,g2,A1,lb2,ub2,lbA2,ubA2, x2,l2 ); end if ( ( kktTol1 <= KKTTOL ) && ( e1 >= 0 ) && ( kktTol2 <= KKTTOL ) && ( e2 >= 0 ) ) successFlag = 1; else if ( doPrint > 0 ) if ( ( kktTol1 > KKTTOL ) || ( kktTol2 > KKTTOL ) ) disp( ['kkt error: ',num2str(kktTol1),'/',num2str(kktTol2)] ) else disp('exitflag<0') end end end end
github
startcode/qp-oases-master
runRandomIdHessian.m
.m
qp-oases-master/testing/matlab/tests/runRandomIdHessian.m
14,687
utf_8
1bf0849e7175e73709bbae55057eeff5
function [ successFlag ] = runRandomIdHessian( nV,nC, doPrint,seed ) if ( nargin < 4 ) seed = 42; if ( nargin < 3 ) doPrint = 1; if ( nargin < 2 ) nC = 10; if ( nargin < 1 ) nV = 5; end end end end successFlag = 1; for isSparseH=0:1 for isSparseA=0:1 successFlag = runSeveralIdSeqTests( successFlag, nV,nC,isSparseH,isSparseA, doPrint,seed ); end end end function [ successFlag ] = runSeveralIdSeqTests( successFlag, nV,nC, isSparseH,isSparseA, doPrint,seed ) %% test without or empty A matrix for hasA=0:1 for changeMat=0:hasA % cannot change matrices if QProblemB object is instantiated for hasLowerB=0:1 for hasUpperB=0:1 for hasOptions=0:1 for hasX0=0:2 for hasWS=0:2 curSuccessFLAG = runSingleIdSeqTest( nV,0,hasA,isSparseH,isSparseA, hasLowerB,hasUpperB,0,0,hasOptions,hasX0,hasWS,changeMat, doPrint,seed ); successFlag = min( successFlag,curSuccessFLAG ); end end end end end end end %% test with non-empty A matrix for hasLowerB=0:1 for hasUpperB=0:1 for hasLowerC=0:1 for hasUpperC=0:1 for hasOptions=0:1 for hasX0=0:2 for hasWS=0:2 for changeMat=0:1 curSuccessFLAG = runSingleIdSeqTest( nV,nC,1,isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC,hasOptions,hasX0,hasWS,changeMat, doPrint,seed ); successFlag = min( successFlag,curSuccessFLAG ); end end end end end end end end end function [ successFlag ] = runSingleIdSeqTest( nV,nC,hasA,isSparseH,isSparseA, hasLowerB,hasUpperB,hasLowerC,hasUpperC,hasOptions,hasX0,hasWS,changeMat, doPrint,seed ) successFlag = 0; qpFeatures = setupQpFeaturesStruct( ); qpFeatures.nV = nV; qpFeatures.nC = nC; qpFeatures.isSparseH = isSparseH; qpFeatures.isSparseA = isSparseA; qpFeatures.hasLowerB = hasLowerB; qpFeatures.hasUpperB = hasUpperB; qpFeatures.hasLowerC = hasLowerC; qpFeatures.hasUpperC = hasUpperC; qpFeatures.hessianType = 2; qpData1 = generateRandomQp( qpFeatures,seed ); qpData2 = generateRandomQp( qpFeatures,seed ); if ( changeMat == 0 ) string = 'Testing qpOASES_sequence( ''i/h/c'',ID'; else string = 'Testing qpOASES_sequence( ''i/m/c'',ID'; end if ( isSparseH > 0 ) string = [string,'s,g']; else string = [string,'d,g']; end if ( nC > 0 ) if ( isSparseA > 0 ) string = [string,',As']; else string = [string,',Ad']; end else if ( hasA > 0 ) string = [string,',[]']; end end if ( hasLowerB > 0 ) string = [string,',lb']; else string = [string,',[]']; end if ( hasUpperB > 0 ) string = [string,',ub']; else string = [string,',[]']; end if ( hasLowerC > 0 ) string = [string,',lbA']; else if ( hasA > 0 ) string = [string,',[] ']; end end if ( hasUpperC > 0 ) string = [string,',ubA']; else if ( hasA > 0 ) string = [string,',[] ']; end end switch ( hasOptions ) case 1 string = [string,',opt']; case 2 string = [string,',[] ']; case 0 if ( ( hasX0 > 0 ) || ( hasWS > 0 ) ) string = [string,',[] ']; end end switch ( hasX0 ) case 1 string = [string,',{x0']; case 2 string = [string,',{[]']; case 0 if ( hasWS > 0 ) string = [string,',{[]']; end end switch ( hasWS ) case 1 string = [string,',WS}']; case 2 string = [string,',[]}']; end string = [string,' )... ']; if ( doPrint > 0 ) %disp( string ); end curSuccessFlag = callQpOasesSeq( qpData1,qpData2,hasA,hasOptions,hasX0,hasWS,changeMat,doPrint ); if ( curSuccessFlag > 0 ) string = [string,'pass!']; successFlag = 1; else string = [string,'fail!']; end if ( doPrint > 0 ) disp( string ); if ( curSuccessFlag == 0 ) pause; end end end function [ successFlag ] = callQpOasesSeq( qpData1,qpData2,hasA,hasOptions,hasX0,hasWS,changeMat, doPrint ) if ( nargin < 8 ) doPrint = 1; end TOL = 1e-15; KKTTOL = 1e-6; successFlag = 0; H1 = qpData1.H; g1 = qpData1.g; A1 = [qpData1.Aeq;qpData1.Ain]; lb1 = qpData1.lb; ub1 = qpData1.ub; lbA1 = [qpData1.beq;qpData1.lbA]; ubA1 = [qpData1.beq;qpData1.ubA]; H2 = qpData2.H; g2 = qpData2.g; A2 = [qpData2.Aeq;qpData2.Ain]; lb2 = qpData2.lb; ub2 = qpData2.ub; lbA2 = [qpData2.beq;qpData2.lbA]; ubA2 = [qpData2.beq;qpData2.ubA]; [nV,dummy] = size(H1); [nC,dummy] = size(A1); if ( hasWS > 0 ) if ( hasWS == 1 ) wsB = 0 * ones( nV,1 ); wsC = 0 * ones( nC,1 ); else wsB = []; wsC = []; end if ( hasX0 > 0 ) if ( hasX0 == 1 ) x0 = -1e-3 * ones( nV,1 ); else x0 = []; end auxInput = qpOASES_auxInput( 'x0',x0,'guessedWorkingSetB',wsB,'guessedWorkingSetC',wsC ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options,auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options,auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,[],auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2 ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2 ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,[],auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); qpOASES_sequence( 'c',QP ); end end else % hasX0 == 0 auxInput = qpOASES_auxInput( 'guessedWorkingSetB',wsB,'guessedWorkingSetC',wsC ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options,auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options,auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,[],auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,[] ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,[] ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,[],auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); qpOASES_sequence( 'c',QP ); end end end % hasX0 else % hasWS == 0 if ( hasX0 > 0 ) if ( hasX0 == 1 ) x0 = -1e-3 * ones( nV,1 ); else x0 = []; end auxInput = qpOASES_auxInput( 'x0',x0 ); if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options,auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options,auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,[],auxInput ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2 ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2 ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,[],auxInput ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); qpOASES_sequence( 'c',QP ); end end else % hasX0 == 0 if ( hasOptions > 0 ) if ( hasOptions == 1 ) options = qpOASES_options(); else options = []; end if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1,options ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2,options ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2,options ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1,options ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,options ); qpOASES_sequence( 'c',QP ); end else if ( hasA > 0 ) [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,A1,lb1,ub1,lbA1,ubA1 ); if ( changeMat > 0 ) [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'm',QP,H2,g2,A2,lb2,ub2,lbA2,ubA2 ); else [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2,lbA2,ubA2 ); end qpOASES_sequence( 'c',QP ); else [ QP,x1,f1,e1,i1,l1,w1 ] = qpOASES_sequence( 'i',H1,g1,lb1,ub1 ); [ x2,f2,e2,i2,l2,w2 ] = qpOASES_sequence( 'h',QP,g2,lb2,ub2 ); qpOASES_sequence( 'c',QP ); end end end % hasX0 end % hasWS kktTol1 = getKktResidual( H1,g1,A1,lb1,ub1,lbA1,ubA1, x1,l1 ); if ( changeMat > 0 ) kktTol2 = getKktResidual( H2,g2,A2,lb2,ub2,lbA2,ubA2, x2,l2 ); else kktTol2 = getKktResidual( H1,g2,A1,lb2,ub2,lbA2,ubA2, x2,l2 ); end if ( ( kktTol1 <= KKTTOL ) && ( e1 >= 0 ) && ( kktTol2 <= KKTTOL ) && ( e2 >= 0 ) ) successFlag = 1; else if ( doPrint > 0 ) disp( ['kkt error: ',num2str(kktTol1),'/',num2str(kktTol2)] ) end end end
github
startcode/qp-oases-master
isoctave.m
.m
qp-oases-master/testing/matlab/auxFiles/isoctave.m
508
utf_8
c857dec2b164c5835c0d5235cd7ad8f0
% ISOCTAVE True if the operating environment is octave. % Usage: t=isoctave(); % % Returns 1 if the operating environment is octave, otherwise % 0 (Matlab) % % --------------------------------------------------------------- function t=isoctave() %ISOCTAVE True if the operating environment is octave. % Usage: t=isoctave(); % % Returns 1 if the operating environment is octave, otherwise % 0 (Matlab) if exist('OCTAVE_VERSION') % Only Octave has this variable. t=1; else t=0; end;
github
c2jahnke/THB-Spline-FE-master
ImpointCurvePlot.m
.m
THB-Spline-FE-master/CurvePlot/ImpointCurvePlot.m
798
utf_8
eaab8eb10e3e833c1d6d4e8da4f5a4b5
function ImpointCurvePlot(n,sP,p,U,plotVector,Points) % function to plot a curve with control points C = zeros( sP , 2 ); for l = 1:sP C(l,:) = CurvePoint(n,p,U,Points,plotVector(l)); end plt_curve = plot(C(:,1),C(:,2),'k','LineWidth',1.2); hold on; xlabel('x'); ylabel('y'); Impoints = {}; for i = 1:n Impoints{i} = impoint(gca, Points(i,1) , Points(i,2) ); addNewPositionCallback( Impoints{i} , @(newpos) updateCurvePlot(i,newpos) ); end function updateCurvePlot( index , newpos ) Points(index,:) = newpos; for k = 1:sP C(k,:) = CurvePoint(n,p,U,Points,plotVector(k)); end plt_curve.XData = C(:,1); plt_curve.YData = C(:,2); drawnow; end end
github
hliangzhao/Mathematical-Model-Implementation-master
DeJong_f2.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/DeJong_f2.m
705
utf_8
f474c060e61ab63d089b22de5a3cdcd9
% DeJong_f2.m % De Jong's f2 function, also called a Rosenbrock Variant % This is a 2D only equation % % described by Clerc in ... % http://clerc.maurice.free.fr/pso/Semi-continuous_challenge/Semi-continuous_challenge.htm % % used to test optimization/global minimization problems % in Clerc's "Semi-continuous challenge" % % f(x,y) = 100*(x.^2 - y).^2 + (1-x).^2; % % input = 2 element row vector containing [x, y] % each row is processed independently, % you can feed in matrices of timeXN no prob % % example: cost = DeJong_f2([1,2;3,4;5,6]) % note minimum =0 @ (1,1) % Brian Birge % Rev 1.0 % 9/12/04 function [out]=DeJong_f2(in) x= in(:,1); y= in(:,2); out = 100*(x.^2 - y).^2 + (1-x).^2;
github
hliangzhao/Mathematical-Model-Implementation-master
ackley.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/ackley.m
839
utf_8
f53febad1b1241ed2b82eb51990c494a
% ackley.m % Ackley's function, from http://www.cs.vu.nl/~gusz/ecbook/slides/16 % and further shown at: % http://clerc.maurice.free.fr/pso/Semi-continuous_challenge/Semi-continuous_challenge.htm % % commonly used to test optimization/global minimization problems % % f(x)= [ 20 + e ... % -20*exp(-0.2*sqrt((1/n)*sum(x.^2,2))) ... % -exp((1/n)*sum(cos(2*pi*x),2))]; % % dimension n = # of columns of input, x1, x2, ..., xn % each row is processed independently, % you can feed in matrices of timeXdim no prob % % example: cost = ackley([1,2,3;4,5,6]) % Brian Birge % Rev 1.0 % 9/12/04 function [out]=ackley(in) % dimension is # of columns of input, x1, x2, ..., xn n=length(in(1,:)); x=in; e=exp(1); out = (20 + e ... -20*exp(-0.2*sqrt((1/n).*sum(x.^2,2))) ... -exp((1/n).*sum(cos(2*pi*x),2))); return
github
hliangzhao/Mathematical-Model-Implementation-master
f6_spiral_dyn.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/f6_spiral_dyn.m
842
utf_8
a68995830769a8c36f01a49a1b854227
% f6_spiral_dyn.m % Schaffer's F6 function % commonly used to test optimization/global minimization problems % % This version moves the minimum about a Fermat Spiral % according to the equation: r = a*(theta^2) % theta is a function of time and is checked internally (not an input) % x_center = r*cos(theta) % y_center = r*sin(theta) % % z = 0.5 ... % +(sin^2(sqrt((x-x_center)^2+(y-y_center)^2))-0.5) ... % /((1+0.01*((x-x_center)^2+(y-y_center)^2))^2) % Brian Birge % Rev 1.0 % 9/12/04 function [out]=f6_spiral_dyn(in) % parse input x = in(:,1); y = in(:,2); % find current minimum based on clock [x_center,y_center]=spiral_dyn(1,.1); % this is in 'hiddenutils' num = sin(sqrt((x-x_center).^2+(y-y_center).^2)).^2 - 0.5; den = (1.0+0.01*((x-x_center).^2+(y-y_center).^2)).^2; out = 0.5 + num./den; return
github
hliangzhao/Mathematical-Model-Implementation-master
f6_linear_dyn.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/f6_linear_dyn.m
593
utf_8
ff08de37e8934d90aaf0da2cd9be2020
% f6_linear_dyn.m % Schaffer's F6 function % commonly used to test optimization/global minimization problems % % This version moves the minimum linearly along a 45 deg angle in x,y space % Brian Birge % Rev 1.0 % 9/12/04 function [out]=f6_linear_dyn(in) % parse input x = in(:,1); y = in(:,2); % find current minimum based on clock offset = linear_dyn(.5); % this is in 'hiddenutils' x_center = offset; y_center = offset; num = sin(sqrt((x-x_center).^2+(y-y_center).^2)).^2 - 0.5; den = (1.0+0.01*((x-x_center).^2+(y-y_center).^2)).^2; out = 0.5 + num./den; return
github
hliangzhao/Mathematical-Model-Implementation-master
NDparabola.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/NDparabola.m
641
utf_8
85e34a0950db121bff8caeefcc737538
% NDparabola.m % ND Parabola function (also called a Sphere function and DeJong's f1), % described by Clerc... % http://clerc.maurice.free.fr/pso/Semi-continuous_challenge/Semi-continuous_challenge.htm % % used to test optimization/global minimization problems % in Clerc's "Semi-continuous challenge" % % f(x) = sum( x.^2 ) % % x = N element row vector containing [x0, x1, ..., xN] % each row is processed independently, % you can feed in matrices of timeXN no prob % % example: cost = NDparabola([1,2;5,6;0,-50]) % note: known minimum =0 @ all x = 0 % Brian Birge % Rev 1.0 % 9/12/04 function [out]=NDparabola(in) out = sum(in.^2, 2);
github
hliangzhao/Mathematical-Model-Implementation-master
spiral_dyn.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/spiral_dyn.m
805
utf_8
9ed110a6f7dc7937e4f689a5a3b912ee
% spiral_dyn.m % returns x,y position along an archimedean spiral of degree n % based on cputime, first time it is called is start time % % based on: r = a*(theta^n) % % usage: [x_cnt,y_cnt] = spiral_dyn(n,a) % i.e., % n = 2 (Fermat) % = 1 (Archimedes) % = -1 (Hyberbolic) % = -2 (Lituus) % Brian Birge % Rev 1.1 % 8/23/04 function [x_cnt,y_cnt] = spiral_dyn(n,a) % this keeps the same start time for each run of the calling function % this will reset when any calling prog is re-saved or workspace is % cleared persistent tnot iter % find starting time if ~exist('tnot') | length(tnot)==0 tnot = cputime; % iter = 0; end %iter = iter+10 ; theta = cputime-tnot; %theta = iter/10000; r = a*(theta.^n); x_cnt = r*cos(theta); y_cnt = r*sin(theta); return
github
hliangzhao/Mathematical-Model-Implementation-master
alpine.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/alpine.m
617
utf_8
350e9ce69d84cc997f59ab6d77b6c4e5
% alpine.m % ND Alpine function, described by Clerc... % http://clerc.maurice.free.fr/pso/Semi-continuous_challenge/Semi-continuous_challenge.htm % % used to test optimization/global minimization problems % in Clerc's "Semi-continuous challenge" % % f(x) = sum( abs(x.*sin(x) + 0.1.*x) ) % % x = N element row vector containing [x0, x1, ..., xN] % each row is processed independently, % you can feed in matrices of timeXN no prob % % example: cost = alpine([1,2;5,6;0,-50]) % note: known minimum =0 @ all x = 0 % Brian Birge % Rev 1.0 % 9/12/04 function [out]=alpine(in) out = sum(abs(in.*sin(in) + 0.1.*in),2);
github
hliangzhao/Mathematical-Model-Implementation-master
Griewank.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/Griewank.m
1,175
utf_8
1922426be7c11651ad663dd929a16606
% Griewank.m % Griewank function % described by Clerc in ... % http://clerc.maurice.free.fr/pso/Semi-continuous_challenge/Semi-continuous_challenge.htm % % used to test optimization/global minimization problems % in Clerc's "Semi-continuous challenge" % % f(x) = sum((x-100).^2,2)./4000 - ... % prod(cos((x-100)./(sqrt(repmat([1:N],length(x(:,1),1)))),2) ... % +1 % % x = N element row vector containing [x0, x1, ..., xN] % each row is processed independently, % you can feed in matrices of timeXN no prob % % example: cost = Griewank([1,2;5,6;0,-50]) % note: known minimum =0 @ all x = 100 % Brian Birge % Rev 1.0 % 9/12/04 function [out]=Griewank(in) persistent d D tlen sqrtd % this speeds routine up a lot, if called from PSO these won't change from % call to call Dx=length(in(1,:)); tlenx=length(in(:,1)); if isempty(D) | D~=Dx | tlen~=tlenx D=Dx; % dimension of prob tlen=tlenx; % how many separate states d=repmat([1:D],tlen,1); % needed to vectorize this sqrtd=sqrt(d); end % just follows from the referenced website/paper term1 = sum([(in-100).^2],2)./4000; term2 = prod( (cos( (in-100)./sqrtd )) ,2); out = term1 - term2 + 1;
github
hliangzhao/Mathematical-Model-Implementation-master
f6mod.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/f6mod.m
675
utf_8
35ebfbe0fff22261e101217b1604fe22
% f6mod.m % Schaffer's F6 function % commonly used to test optimization/global minimization problems % % This version is a modified form, just the sum of 5 f6 functions with % different centers to look at local minimum issues % normal f6= % z = 0.5+ (sin^2(sqrt(x^2+y^2))-0.5)/((1+0.01*(x^2+y^2))^2) function [out]=f6mod(in) x=in(:,1); y=in(:,2); a=ones(size(x)); b=20; xycntr=[0*a,0*a,-b*a,-b*a,-b*a,b*a,b*a,-b*a,b*a,b*a]; tmpout=0.*a; for i=1:5 num=sin(sqrt( (x-xycntr(:,2*i-1)).^2 + (y-xycntr(:,2*i)).^2) ).^2 - 0.5; den=(1.0+0.01*((x-xycntr(:,2*i-1)).^2+(y-xycntr(:,2*i)).^2)).^2; tmpout=[tmpout, 0.5*a +num./den]; end out=sum(tmpout,2)./5; return
github
hliangzhao/Mathematical-Model-Implementation-master
linear_dyn.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/linear_dyn.m
724
utf_8
c630c42d5de136b31ca954328cde13d2
% linear_dyn.m % returns an offset that can be added to data that increases linearly with % time, based on cputime, first time it is called is start time % % equation is: offset = (cputime - tnot)*scalefactor % where tnot = cputime at the first call % scalefactor = value that slows or speeds up linear movement % % usage: [offset] = linear_dyn(scalefactor) % Brian Birge % Rev 1.0 % 8/23/04 function out = linear_dyn(sf) % this keeps the same start time for each run of the calling function % this will reset when any calling prog is re-saved or workspace is % cleared persistent tnot % find starting time if ~exist('tnot') | length(tnot)==0 tnot = cputime; end out = (cputime-tnot)*sf; return
github
hliangzhao/Mathematical-Model-Implementation-master
Rastrigin.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/Rastrigin.m
500
utf_8
49633129edf0685033f0b4fc126a822c
% Rastrigin.m % Rastrigin function % % used to test optimization/global minimization problems % % f(x) = sum([x.^2-10*cos(2*pi*x) + 10], 2); % % x = N element row vector containing [x0, x1, ..., xN] % each row is processed independently, % you can feed in matrices of timeXN no prob % % example: cost = Rastrigin([1,2;5,6;0,-50]) % note: known minimum =0 @ all x = 0 % Brian Birge % Rev 1.0 % 9/12/04 function [out]=Rastrigin(in) cos_in = cos(2*pi*in); out = sum((in.^2-10*cos_in + 10), 2);
github
hliangzhao/Mathematical-Model-Implementation-master
f6.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/f6.m
299
utf_8
6e328b2ad0f76540e9c80d87b5ad06dc
% f6.m % Schaffer's F6 function % commonly used to test optimization/global minimization problems % % z = 0.5+ (sin^2(sqrt(x^2+y^2))-0.5)/((1+0.01*(x^2+y^2))^2) function [out]=f6(in) x=in(:,1); y=in(:,2); num=sin(sqrt(x.^2+y.^2)).^2 - 0.5; den=(1.0+0.01*(x.^2+y.^2)).^2; out=0.5 +num./den;
github
hliangzhao/Mathematical-Model-Implementation-master
f6_bubbles_dyn.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/f6_bubbles_dyn.m
1,458
utf_8
00614b7d2beaf3ea99b48c5ccdd00063
% f6_bubbles_dyn.m % 2 separate Schaffer's F6 functions, one with min at [-8,-8] and the % other with min at [8,8] % as time goes on, each bubbles magnitude cycles up and down, % they are 180 deg out of phase with each other % % commonly used to test optimization/global minimization problems function [out]=f6_bubbles_dyn(in) persistent tnot % find starting time if ~exist('tnot') | length(tnot)==0 tnot = cputime; end time = cputime/10 - tnot; % calculate offset for whole function %[xc,yc]=spiral_dyn(1,.1); xc = 0; yc = xc; % parse input x = in(:,1) +xc; y = in(:,2) +yc; % bubble centers x1 = -8; y1 = x1; x2 = 8; y2 = x2; % f6 #1 (bubble #1) num = sin(sqrt((x-x1).^2+(y-y1).^2)).^2 - 0.5; den = (1.0+0.01*((x-x1).^2+(y-y1).^2)).^2; f6_1 = (0.5 + num./den).*abs(sin(time+pi/2)); % bubble #1 offset num_ofs = sin(sqrt((10000-x1).^2+(10000-y1).^2)).^2 - 0.5; den_ofs = (1.0+0.01*((10000-x1).^2+(10000-y1).^2)).^2; f6_1_ofs = (0.5 + num_ofs./den_ofs).*abs(sin(time+pi/2)); % f6 #2 (bubble #2) num = sin(sqrt((x-x2).^2+(y-y2).^2)).^2 - 0.5; den = (1.0+0.01*((x-x2).^2+(y-y2).^2)).^2; f6_2 = (0.5 + num./den).*abs(sin(time)); % bubble #2 offset num_ofs = sin(sqrt((10000-x2).^2+(10000-y2).^2)).^2 - 0.5; den_ofs = (1.0+0.01*((10000-x2).^2+(10000-y2).^2)).^2; f6_2_ofs = (0.5 + num_ofs./den_ofs).*abs(sin(time)); % output & return out = 2*((f6_1 + f6_2) - (f6_1_ofs + f6_2_ofs)); return
github
hliangzhao/Mathematical-Model-Implementation-master
Rosenbrock.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/Rosenbrock.m
697
utf_8
9b342f29fa2367ba43883cb0b50432cb
% Rosenbrock.m % Rosenbrock function % % described by Clerc in ... % http://clerc.maurice.free.fr/pso/Semi-continuous_challenge/Semi-continuous_challenge.htm % % used to test optimization/global minimization problems % in Clerc's "Semi-continuous challenge" % % f(x) = sum([ 100*(x(i+1) - x(i)^2)^2 + (x(i) -1)^2]) % % x = N element row vector containing [x0, x1, ..., xN] % each row is processed independently, % you can feed in matrices of timeXN no prob % % example: cost = Rosenbrock([1,2;5,6;0,-50]) % note: known minimum =0 @ all x = 1 % Brian Birge % Rev 1.0 % 9/12/04 function [out]=Rosenbrock(in) x0=in(:,1:end-1); x1=in(:,2:end); out = sum( (100*(x1-x0.^2).^2 + (x0-1).^2) , 2);
github
hliangzhao/Mathematical-Model-Implementation-master
tripod.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/tripod.m
860
utf_8
9e3c6b8565897f712d6297c5e041ebef
% tripod.m % 2D tripod function, described by Clerc... % http://clerc.maurice.free.fr/pso/Semi-continuous_challenge/Semi-continuous_challenge.htm % % used to test optimization/global minimization problems % in Clerc's "Semi-continuous challenge" % % f(x)= [ p(x2)*(1+p(x1)) ... % + abs(x1 + 50*p(x2)*(1-2*p(x1)))... % + abs(x2 + 50*(1-2*p(x2))) ]; % % where p(u) = 1 for u >= 0 % = 0 else % % in = 2 element row vector containing [x1, x2] % each row is processed independently, % you can feed in matrices of timeX2 no prob % % example: cost = tripod([1,2;5,6;0,-50]) % note: known minimum =0 @ (0,-50) % Brian Birge % Rev 1.0 % 9/12/04 function [out]=tripod(in) x1=in(:,1); x2=in(:,2); px1=((x1) >= 0); px2=((x2) >= 0); out= ( px2.*(1+px1) ... + abs(x1 + 50*px2.*(1-2*px1))... + abs(x2 + 50*(1-2.*px2)) );
github
hliangzhao/Mathematical-Model-Implementation-master
Foxhole.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/Foxhole.m
1,232
utf_8
21a1c5dd5e44f43ef92759b2e174b59c
% Foxhole.m % Foxhole function, 2D multi-minima function % % from: http://www.cs.rpi.edu/~hornda/pres/node10.html % % f(x) = 0.002 + sum([1/(j + sum( [x(i) - a(i,j)].^6 ) )]) % % x = 2 element row vector containing [ x, y ] % each row is processed independently, % you can feed in matrices of timeX2 no prob % % example: cost = Foxhole([1,2;3,4]) % note: known minimum =0 @ (-32,-32) unless you change 'a' in the function % Brian Birge % Rev 1.0 % 9/12/04 function [out]=Foxhole(in) x=in(:,1); y=in(:,2); % location of foxholes, you can change this, these are what DeJong used % if you change 'em, a{1} and a{2} must each have same # of elements a{1} = [... -32 -16 0 16 32 ;... -32 -16 0 16 32 ;... -32 -16 0 16 32 ;... -32 -16 0 16 32 ;... -32 -16 0 16 32 ;... ]; a{2} = [... -32 -32 -32 -32 -32 ;... -16 -16 -16 -16 -16 ;... 0 0 0 0 0 ;... 16 16 16 16 16 ;... 32 32 32 32 32 ;... ]; term_sum=0; for j=1:prod(size((a{1}))) ax=a{1} (j); ay=a{2} (j); term_num = (x - ax).^6 + (y - ay).^6; term_sum=term_sum+ 1./(j+term_num); end out = .002 + term_sum;
github
hliangzhao/Mathematical-Model-Implementation-master
pso_Trelea_vectorized.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/pso_Trelea_vectorized.m
22,526
utf_8
83cd4e518a70437a5b760d6cb5ceaa82
% pso_Trelea_vectorized.m % a generic particle swarm optimizer % to find the minimum or maximum of any % MISO matlab function % % Implements Common, Trelea type 1 and 2, and Clerc's class 1". It will % also automatically try to track to a changing environment (with varied % success - BKB 3/18/05) % % This vectorized version removes the for loop associated with particle % number. It also *requires* that the cost function have a single input % that represents all dimensions of search (i.e., for a function that has 2 % inputs then make a wrapper that passes a matrix of ps x 2 as a single % variable) % % Usage: % [optOUT]=PSO(functname,D) % or: % [optOUT,tr,te]=... % PSO(functname,D,mv,VarRange,minmax,PSOparams,plotfcn,PSOseedValue) % % Inputs: % functname - string of matlab function to optimize % D - # of inputs to the function (dimension of problem) % % Optional Inputs: % mv - max particle velocity, either a scalar or a vector of length D % (this allows each component to have it's own max velocity), % default = 4, set if not input or input as NaN % % VarRange - matrix of ranges for each input variable, % default -100 to 100, of form: % [ min1 max1 % min2 max2 % ... % minD maxD ] % % minmax = 0, funct minimized (default) % = 1, funct maximized % = 2, funct is targeted to P(12) (minimizes distance to errgoal) % PSOparams - PSO parameters % P(1) - Epochs between updating display, default = 100. if 0, % no display % P(2) - Maximum number of iterations (epochs) to train, default = 2000. % P(3) - population size, default = 24 % % P(4) - acceleration const 1 (local best influence), default = 2 % P(5) - acceleration const 2 (global best influence), default = 2 % P(6) - Initial inertia weight, default = 0.9 % P(7) - Final inertia weight, default = 0.4 % P(8) - Epoch when inertial weight at final value, default = 1500 % P(9)- minimum global error gradient, % if abs(Gbest(i+1)-Gbest(i)) < gradient over % certain length of epochs, terminate run, default = 1e-25 % P(10)- epochs before error gradient criterion terminates run, % default = 150, if the SSE does not change over 250 epochs % then exit % P(11)- error goal, if NaN then unconstrained min or max, default=NaN % P(12)- type flag (which kind of PSO to use) % 0 = Common PSO w/intertia (default) % 1,2 = Trelea types 1,2 % 3 = Clerc's Constricted PSO, Type 1" % P(13)- PSOseed, default=0 % = 0 for initial positions all random % = 1 for initial particles as user input % % plotfcn - optional name of plotting function, default 'goplotpso', % make your own and put here % % PSOseedValue - initial particle position, depends on P(13), must be % set if P(13) is 1 or 2, not used for P(13)=0, needs to % be nXm where n<=ps, and m<=D % If n<ps and/or m<D then remaining values are set random % on Varrange % Outputs: % optOUT - optimal inputs and associated min/max output of function, of form: % [ bestin1 % bestin2 % ... % bestinD % bestOUT ] % % Optional Outputs: % tr - Gbest at every iteration, traces flight of swarm % te - epochs to train, returned as a vector 1:endepoch % % Example: out=pso_Trelea_vectorized('f6',2) % Brian Birge % Rev 3.3 % 2/18/06 function [OUT,varargout]=pso_Trelea_vectorized(functname,D,varargin) rand('state',sum(100*clock)); if nargin < 2 error('Not enough arguments.'); end % PSO PARAMETERS if nargin == 2 % only specified functname and D VRmin=ones(D,1)*-100; VRmax=ones(D,1)*100; VR=[VRmin,VRmax]; minmax = 0; P = []; mv = 4; plotfcn='goplotpso'; elseif nargin == 3 % specified functname, D, and mv VRmin=ones(D,1)*-100; VRmax=ones(D,1)*100; VR=[VRmin,VRmax]; minmax = 0; mv=varargin{1}; if isnan(mv) mv=4; end P = []; plotfcn='goplotpso'; elseif nargin == 4 % specified functname, D, mv, Varrange mv=varargin{1}; if isnan(mv) mv=4; end VR=varargin{2}; minmax = 0; P = []; plotfcn='goplotpso'; elseif nargin == 5 % Functname, D, mv, Varrange, and minmax mv=varargin{1}; if isnan(mv) mv=4; end VR=varargin{2}; minmax=varargin{3}; P = []; plotfcn='goplotpso'; elseif nargin == 6 % Functname, D, mv, Varrange, minmax, and psoparams mv=varargin{1}; if isnan(mv) mv=4; end VR=varargin{2}; minmax=varargin{3}; P = varargin{4}; % psoparams plotfcn='goplotpso'; elseif nargin == 7 % Functname, D, mv, Varrange, minmax, and psoparams, plotfcn mv=varargin{1}; if isnan(mv) mv=4; end VR=varargin{2}; minmax=varargin{3}; P = varargin{4}; % psoparams plotfcn = varargin{5}; elseif nargin == 8 % Functname, D, mv, Varrange, minmax, and psoparams, plotfcn, PSOseedValue mv=varargin{1}; if isnan(mv) mv=4; end VR=varargin{2}; minmax=varargin{3}; P = varargin{4}; % psoparams plotfcn = varargin{5}; PSOseedValue = varargin{6}; else error('Wrong # of input arguments.'); end % sets up default pso params Pdef = [100 2000 24 2 2 0.9 0.4 1500 1e-25 250 NaN 0 0]; Plen = length(P); P = [P,Pdef(Plen+1:end)]; df = P(1); me = P(2); ps = P(3); ac1 = P(4); ac2 = P(5); iw1 = P(6); iw2 = P(7); iwe = P(8); ergrd = P(9); ergrdep = P(10); errgoal = P(11); trelea = P(12); PSOseed = P(13); % used with trainpso, for neural net training if strcmp(functname,'pso_neteval') net = evalin('caller','net'); Pd = evalin('caller','Pd'); Tl = evalin('caller','Tl'); Ai = evalin('caller','Ai'); Q = evalin('caller','Q'); TS = evalin('caller','TS'); end % error checking if ((minmax==2) & isnan(errgoal)) error('minmax= 2, errgoal= NaN: choose an error goal or set minmax to 0 or 1'); end if ( (PSOseed==1) & ~exist('PSOseedValue') ) error('PSOseed flag set but no PSOseedValue was input'); end if exist('PSOseedValue') tmpsz=size(PSOseedValue); if D < tmpsz(2) error('PSOseedValue column size must be D or less'); end if ps < tmpsz(1) error('PSOseedValue row length must be # of particles or less'); end end % set plotting flag if (P(1))~=0 plotflg=1; else plotflg=0; end % preallocate variables for speed up tr = ones(1,me)*NaN; % take care of setting max velocity and position params here if length(mv)==1 velmaskmin = -mv*ones(ps,D); % min vel, psXD matrix velmaskmax = mv*ones(ps,D); % max vel elseif length(mv)==D velmaskmin = repmat(forcerow(-mv),ps,1); % min vel velmaskmax = repmat(forcerow( mv),ps,1); % max vel else error('Max vel must be either a scalar or same length as prob dimension D'); end posmaskmin = repmat(VR(1:D,1)',ps,1); % min pos, psXD matrix posmaskmax = repmat(VR(1:D,2)',ps,1); % max pos posmaskmeth = 3; % 3=bounce method (see comments below inside epoch loop) % PLOTTING message = sprintf('PSO: %%g/%g iterations, GBest = %%20.20g.\n',me); % INITIALIZE INITIALIZE INITIALIZE INITIALIZE INITIALIZE INITIALIZE % initialize population of particles and their velocities at time zero, % format of pos= (particle#, dimension) % construct random population positions bounded by VR pos(1:ps,1:D) = normmat(rand([ps,D]),VR',1); if PSOseed == 1 % initial positions user input, see comments above tmpsz = size(PSOseedValue); pos(1:tmpsz(1),1:tmpsz(2)) = PSOseedValue; end % construct initial random velocities between -mv,mv vel(1:ps,1:D) = normmat(rand([ps,D]),... [forcecol(-mv),forcecol(mv)]',1); % initial pbest positions vals pbest = pos; % VECTORIZE THIS, or at least vectorize cost funct call out = feval(functname,pos); % returns column of cost values (1 for each particle) %--------------------------- pbestval=out; % initially, pbest is same as pos % assign initial gbest here also (gbest and gbestval) if minmax==1 % this picks gbestval when we want to maximize the function [gbestval,idx1] = max(pbestval); elseif minmax==0 % this works for straight minimization [gbestval,idx1] = min(pbestval); elseif minmax==2 % this works when you know target but not direction you need to go % good for a cost function that returns distance to target that can be either % negative or positive (direction info) [temp,idx1] = min((pbestval-ones(size(pbestval))*errgoal).^2); gbestval = pbestval(idx1); end % preallocate a variable to keep track of gbest for all iters bestpos = zeros(me,D+1)*NaN; gbest = pbest(idx1,:); % this is gbest position % used with trainpso, for neural net training % assign gbest to net at each iteration, these interim assignments % are for plotting mostly if strcmp(functname,'pso_neteval') net=setx(net,gbest); end %tr(1) = gbestval; % save for output bestpos(1,1:D) = gbest; % this part used for implementing Carlisle and Dozier's APSO idea % slightly modified, this tracks the global best as the sentry whereas % their's chooses a different point to act as sentry % see "Tracking Changing Extremea with Adaptive Particle Swarm Optimizer", % part of the WAC 2002 Proceedings, June 9-13, http://wacong.com sentryval = gbestval; sentry = gbest; if (trelea == 3) % calculate Clerc's constriction coefficient chi to use in his form kappa = 1; % standard val = 1, change for more or less constriction if ( (ac1+ac2) <=4 ) chi = kappa; else psi = ac1 + ac2; chi_den = abs(2-psi-sqrt(psi^2 - 4*psi)); chi_num = 2*kappa; chi = chi_num/chi_den; end end % INITIALIZE END INITIALIZE END INITIALIZE END INITIALIZE END rstflg = 0; % for dynamic environment checking % start PSO iterative procedures cnt = 0; % counter used for updating display according to df in the options cnt2 = 0; % counter used for the stopping subroutine based on error convergence iwt(1) = iw1; for i=1:me % start epoch loop (iterations) out = feval(functname,[pos;gbest]); outbestval = out(end,:); out = out(1:end-1,:); tr(i+1) = gbestval; % keep track of global best val te = i; % returns epoch number to calling program when done bestpos(i,1:D+1) = [gbest,gbestval]; %assignin('base','bestpos',bestpos(i,1:D+1)); %------------------------------------------------------------------------ % this section does the plots during iterations if plotflg==1 if (rem(i,df) == 0 ) | (i==me) | (i==1) fprintf(message,i,gbestval); cnt = cnt+1; % count how many times we display (useful for movies) eval(plotfcn); % defined at top of script end % end update display every df if statement end % end plotflg if statement % check for an error space that changes wrt time/iter % threshold value that determines dynamic environment % sees if the value of gbest changes more than some threshold value % for the same location chkdyn = 1; rstflg = 0; % for dynamic environment checking if chkdyn==1 threshld = 0.05; % percent current best is allowed to change, .05 = 5% etc letiter = 5; % # of iterations before checking environment, leave at least 3 so PSO has time to converge outorng = abs( 1- (outbestval/gbestval) ) >= threshld; samepos = (max( sentry == gbest )); if (outorng & samepos) & rem(i,letiter)==0 rstflg=1; % disp('New Environment: reset pbest, gbest, and vel'); %% reset pbest and pbestval if warranted % outpbestval = feval( functname,[pbest] ); % Poutorng = abs( 1-(outpbestval./pbestval) ) > threshld; % pbestval = pbestval.*~Poutorng + outpbestval.*Poutorng; % pbest = pbest.*repmat(~Poutorng,1,D) + pos.*repmat(Poutorng,1,D); pbest = pos; % reset personal bests to current positions pbestval = out; vel = vel*10; % agitate particles a little (or a lot) % recalculate best vals if minmax == 1 [gbestval,idx1] = max(pbestval); elseif minmax==0 [gbestval,idx1] = min(pbestval); elseif minmax==2 % this section needs work [temp,idx1] = min((pbestval-ones(size(pbestval))*errgoal).^2); gbestval = pbestval(idx1); end gbest = pbest(idx1,:); % used with trainpso, for neural net training % assign gbest to net at each iteration, these interim assignments % are for plotting mostly if strcmp(functname,'pso_neteval') net=setx(net,gbest); end end % end if outorng sentryval = gbestval; sentry = gbest; end % end if chkdyn % find particles where we have new pbest, depending on minmax choice % then find gbest and gbestval %[size(out),size(pbestval)] if rstflg == 0 if minmax == 0 [tempi] = find(pbestval>=out); % new min pbestvals pbestval(tempi,1) = out(tempi); % update pbestvals pbest(tempi,:) = pos(tempi,:); % update pbest positions [iterbestval,idx1] = min(pbestval); if gbestval >= iterbestval gbestval = iterbestval; gbest = pbest(idx1,:); % used with trainpso, for neural net training % assign gbest to net at each iteration, these interim assignments % are for plotting mostly if strcmp(functname,'pso_neteval') net=setx(net,gbest); end end elseif minmax == 1 [tempi,dum] = find(pbestval<=out); % new max pbestvals pbestval(tempi,1) = out(tempi,1); % update pbestvals pbest(tempi,:) = pos(tempi,:); % update pbest positions [iterbestval,idx1] = max(pbestval); if gbestval <= iterbestval gbestval = iterbestval; gbest = pbest(idx1,:); % used with trainpso, for neural net training % assign gbest to net at each iteration, these interim assignments % are for plotting mostly if strcmp(functname,'pso_neteval') net=setx(net,gbest); end end elseif minmax == 2 % this won't work as it is, fix it later egones = errgoal*ones(ps,1); % vector of errgoals sqrerr2 = ((pbestval-egones).^2); sqrerr1 = ((out-egones).^2); [tempi,dum] = find(sqerr1 <= sqrerr2); % find particles closest to targ pbestval(tempi,1) = out(tempi,1); % update pbestvals pbest(tempi,:) = pos(tempi,:); % update pbest positions sqrerr = ((pbestval-egones).^2); % need to do this to reflect new pbests [temp,idx1] = min(sqrerr); iterbestval = pbestval(idx1); if (iterbestval-errgoal)^2 <= (gbestval-errgoal)^2 gbestval = iterbestval; gbest = pbest(idx1,:); % used with trainpso, for neural net training % assign gbest to net at each iteration, these interim assignments % are for plotting mostly if strcmp(functname,'pso_neteval') net=setx(net,gbest); end end end end % % build a simple predictor 10th order, for gbest trajectory % if i>500 % for dimcnt=1:D % pred_coef = polyfit(i-250:i,(bestpos(i-250:i,dimcnt))',20); % % pred_coef = polyfit(200:i,(bestpos(200:i,dimcnt))',20); % gbest_pred(i,dimcnt) = polyval(pred_coef,i+1); % end % else % gbest_pred(i,:) = zeros(size(gbest)); % end %gbest_pred(i,:)=gbest; %assignin('base','gbest_pred',gbest_pred); % % convert to non-inertial frame % gbestoffset = gbest - gbest_pred(i,:); % gbest = gbest - gbestoffset; % pos = pos + repmat(gbestoffset,ps,1); % pbest = pbest + repmat(gbestoffset,ps,1); %PSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSO % get new velocities, positions (this is the heart of the PSO algorithm) % each epoch get new set of random numbers rannum1 = rand([ps,D]); % for Trelea and Clerc types rannum2 = rand([ps,D]); if trelea == 2 % from Trelea's paper, parameter set 2 vel = 0.729.*vel... % prev vel +1.494.*rannum1.*(pbest-pos)... % independent +1.494.*rannum2.*(repmat(gbest,ps,1)-pos); % social elseif trelea == 1 % from Trelea's paper, parameter set 1 vel = 0.600.*vel... % prev vel +1.700.*rannum1.*(pbest-pos)... % independent +1.700.*rannum2.*(repmat(gbest,ps,1)-pos); % social elseif trelea ==3 % Clerc's Type 1" PSO vel = chi*(vel... % prev vel +ac1.*rannum1.*(pbest-pos)... % independent +ac2.*rannum2.*(repmat(gbest,ps,1)-pos)) ; % social else % common PSO algo with inertia wt % get inertia weight, just a linear funct w.r.t. epoch parameter iwe if i<=iwe iwt(i) = ((iw2-iw1)/(iwe-1))*(i-1)+iw1; else iwt(i) = iw2; end % random number including acceleration constants ac11 = rannum1.*ac1; % for common PSO w/inertia ac22 = rannum2.*ac2; vel = iwt(i).*vel... % prev vel +ac11.*(pbest-pos)... % independent +ac22.*(repmat(gbest,ps,1)-pos); % social end % limit velocities here using masking vel = ( (vel <= velmaskmin).*velmaskmin ) + ( (vel > velmaskmin).*vel ); vel = ( (vel >= velmaskmax).*velmaskmax ) + ( (vel < velmaskmax).*vel ); % update new position (PSO algo) pos = pos + vel; % position masking, limits positions to desired search space % method: 0) no position limiting, 1) saturation at limit, % 2) wraparound at limit , 3) bounce off limit minposmask_throwaway = pos <= posmaskmin; % these are psXD matrices minposmask_keep = pos > posmaskmin; maxposmask_throwaway = pos >= posmaskmax; maxposmask_keep = pos < posmaskmax; if posmaskmeth == 1 % this is the saturation method pos = ( minposmask_throwaway.*posmaskmin ) + ( minposmask_keep.*pos ); pos = ( maxposmask_throwaway.*posmaskmax ) + ( maxposmask_keep.*pos ); elseif posmaskmeth == 2 % this is the wraparound method pos = ( minposmask_throwaway.*posmaskmax ) + ( minposmask_keep.*pos ); pos = ( maxposmask_throwaway.*posmaskmin ) + ( maxposmask_keep.*pos ); elseif posmaskmeth == 3 % this is the bounce method, particles bounce off the boundaries with -vel pos = ( minposmask_throwaway.*posmaskmin ) + ( minposmask_keep.*pos ); pos = ( maxposmask_throwaway.*posmaskmax ) + ( maxposmask_keep.*pos ); vel = (vel.*minposmask_keep) + (-vel.*minposmask_throwaway); vel = (vel.*maxposmask_keep) + (-vel.*maxposmask_throwaway); else % no change, this is the original Eberhart, Kennedy method, % it lets the particles grow beyond bounds if psoparams (P) % especially Vmax, aren't set correctly, see the literature end %PSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSO % check for stopping criterion based on speed of convergence to desired % error tmp1 = abs(tr(i) - gbestval); if tmp1 > ergrd cnt2 = 0; elseif tmp1 <= ergrd cnt2 = cnt2+1; if cnt2 >= ergrdep if plotflg == 1 fprintf(message,i,gbestval); disp(' '); disp(['--> Solution likely, GBest hasn''t changed by at least ',... num2str(ergrd),' for ',... num2str(cnt2),' epochs.']); eval(plotfcn); end break end end % this stops if using constrained optimization and goal is reached if ~isnan(errgoal) if ((gbestval<=errgoal) & (minmax==0)) | ((gbestval>=errgoal) & (minmax==1)) if plotflg == 1 fprintf(message,i,gbestval); disp(' '); disp(['--> Error Goal reached, successful termination!']); eval(plotfcn); end break end % this is stopping criterion for constrained from both sides if minmax == 2 if ((tr(i)<errgoal) & (gbestval>=errgoal)) | ((tr(i)>errgoal) ... & (gbestval <= errgoal)) if plotflg == 1 fprintf(message,i,gbestval); disp(' '); disp(['--> Error Goal reached, successful termination!']); eval(plotfcn); end break end end % end if minmax==2 end % end ~isnan if % % convert back to inertial frame % pos = pos - repmat(gbestoffset,ps,1); % pbest = pbest - repmat(gbestoffset,ps,1); % gbest = gbest + gbestoffset; end % end epoch loop %% clear temp outputs % evalin('base','clear temp_pso_out temp_te temp_tr;'); % output & return OUT=[gbest';gbestval]; varargout{1}=[1:te]; varargout{2}=[tr(find(~isnan(tr)))]; return
github
hliangzhao/Mathematical-Model-Implementation-master
DeJong_f4.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/DeJong_f4.m
971
utf_8
9df4774e7545c69c3ded2336203917ac
% DeJong_f4.m % De Jong's f4 function, ND, no noise % % described by Clerc in ... % http://clerc.maurice.free.fr/pso/Semi-continuous_challenge/Semi-continuous_challenge.htm % % used to test optimization/global minimization problems % in Clerc's "Semi-continuous challenge" % % f(x) = sum( [1:N].*(in.^4), 2) % % x = N element row vector containing [ x0, x1,..., xN ] % each row is processed independently, % you can feed in matrices of timeXN no prob % % example: cost = DeJong_f4([1,2;3,4;5,6]) % note minimum =0 @ x= all zeros % Brian Birge % Rev 1.0 % 9/12/04 function [out]=DeJong_f4(in) persistent D tlen d % this speeds routine up a lot, if called from PSO these won't change from % call to call (repmat is a cpu hog) Dx=length(in(1,:)); tlenx=length(in(:,1)); if isempty(D) | D~=Dx | tlen~=tlenx D=Dx; % dimension of prob tlen=tlenx; % how many separate states d=repmat([1:D],tlen,1); % needed to vectorize this end out = sum( d.*(in.^4), 2);
github
hliangzhao/Mathematical-Model-Implementation-master
DeJong_f3.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/testfunctions/DeJong_f3.m
488
utf_8
60082b5c3e0231c66b32f383ab9aca68
% DeJong_f3.m % De Jong's f3 function, ND, also called STEP % from: http://www.cs.rpi.edu/~hornda/pres/node4.html % % f(x) = sum( floor(x) ) % % x = N element row vector containing [ x0, x1,..., xN ] % each row is processed independently, % you can feed in matrices of timeXN no prob % % example: cost = DeJong_f3([1,2;3,4;5,6]) % note minimum @ x= -Inf or whatever lower bound you've chosen % Brian Birge % Rev 1.0 % 9/12/04 function [out]=DeJong_f3(in) out = sum( floor(in) , 2);
github
hliangzhao/Mathematical-Model-Implementation-master
spiral_dyn.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/PSOt/spiral_dyn.m
805
utf_8
9ed110a6f7dc7937e4f689a5a3b912ee
% spiral_dyn.m % returns x,y position along an archimedean spiral of degree n % based on cputime, first time it is called is start time % % based on: r = a*(theta^n) % % usage: [x_cnt,y_cnt] = spiral_dyn(n,a) % i.e., % n = 2 (Fermat) % = 1 (Archimedes) % = -1 (Hyberbolic) % = -2 (Lituus) % Brian Birge % Rev 1.1 % 8/23/04 function [x_cnt,y_cnt] = spiral_dyn(n,a) % this keeps the same start time for each run of the calling function % this will reset when any calling prog is re-saved or workspace is % cleared persistent tnot iter % find starting time if ~exist('tnot') | length(tnot)==0 tnot = cputime; % iter = 0; end %iter = iter+10 ; theta = cputime-tnot; %theta = iter/10000; r = a*(theta.^n); x_cnt = r*cos(theta); y_cnt = r*sin(theta); return
github
hliangzhao/Mathematical-Model-Implementation-master
linear_dyn.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/PSOt/linear_dyn.m
724
utf_8
c630c42d5de136b31ca954328cde13d2
% linear_dyn.m % returns an offset that can be added to data that increases linearly with % time, based on cputime, first time it is called is start time % % equation is: offset = (cputime - tnot)*scalefactor % where tnot = cputime at the first call % scalefactor = value that slows or speeds up linear movement % % usage: [offset] = linear_dyn(scalefactor) % Brian Birge % Rev 1.0 % 8/23/04 function out = linear_dyn(sf) % this keeps the same start time for each run of the calling function % this will reset when any calling prog is re-saved or workspace is % cleared persistent tnot % find starting time if ~exist('tnot') | length(tnot)==0 tnot = cputime; end out = (cputime-tnot)*sf; return
github
hliangzhao/Mathematical-Model-Implementation-master
pso_Trelea_vectorized.m
.m
Mathematical-Model-Implementation-master/IntelligenceAlgorithm/chapter17 基于PSO工具箱的函数寻优算法/PSOt/pso_Trelea_vectorized.m
22,526
utf_8
83cd4e518a70437a5b760d6cb5ceaa82
% pso_Trelea_vectorized.m % a generic particle swarm optimizer % to find the minimum or maximum of any % MISO matlab function % % Implements Common, Trelea type 1 and 2, and Clerc's class 1". It will % also automatically try to track to a changing environment (with varied % success - BKB 3/18/05) % % This vectorized version removes the for loop associated with particle % number. It also *requires* that the cost function have a single input % that represents all dimensions of search (i.e., for a function that has 2 % inputs then make a wrapper that passes a matrix of ps x 2 as a single % variable) % % Usage: % [optOUT]=PSO(functname,D) % or: % [optOUT,tr,te]=... % PSO(functname,D,mv,VarRange,minmax,PSOparams,plotfcn,PSOseedValue) % % Inputs: % functname - string of matlab function to optimize % D - # of inputs to the function (dimension of problem) % % Optional Inputs: % mv - max particle velocity, either a scalar or a vector of length D % (this allows each component to have it's own max velocity), % default = 4, set if not input or input as NaN % % VarRange - matrix of ranges for each input variable, % default -100 to 100, of form: % [ min1 max1 % min2 max2 % ... % minD maxD ] % % minmax = 0, funct minimized (default) % = 1, funct maximized % = 2, funct is targeted to P(12) (minimizes distance to errgoal) % PSOparams - PSO parameters % P(1) - Epochs between updating display, default = 100. if 0, % no display % P(2) - Maximum number of iterations (epochs) to train, default = 2000. % P(3) - population size, default = 24 % % P(4) - acceleration const 1 (local best influence), default = 2 % P(5) - acceleration const 2 (global best influence), default = 2 % P(6) - Initial inertia weight, default = 0.9 % P(7) - Final inertia weight, default = 0.4 % P(8) - Epoch when inertial weight at final value, default = 1500 % P(9)- minimum global error gradient, % if abs(Gbest(i+1)-Gbest(i)) < gradient over % certain length of epochs, terminate run, default = 1e-25 % P(10)- epochs before error gradient criterion terminates run, % default = 150, if the SSE does not change over 250 epochs % then exit % P(11)- error goal, if NaN then unconstrained min or max, default=NaN % P(12)- type flag (which kind of PSO to use) % 0 = Common PSO w/intertia (default) % 1,2 = Trelea types 1,2 % 3 = Clerc's Constricted PSO, Type 1" % P(13)- PSOseed, default=0 % = 0 for initial positions all random % = 1 for initial particles as user input % % plotfcn - optional name of plotting function, default 'goplotpso', % make your own and put here % % PSOseedValue - initial particle position, depends on P(13), must be % set if P(13) is 1 or 2, not used for P(13)=0, needs to % be nXm where n<=ps, and m<=D % If n<ps and/or m<D then remaining values are set random % on Varrange % Outputs: % optOUT - optimal inputs and associated min/max output of function, of form: % [ bestin1 % bestin2 % ... % bestinD % bestOUT ] % % Optional Outputs: % tr - Gbest at every iteration, traces flight of swarm % te - epochs to train, returned as a vector 1:endepoch % % Example: out=pso_Trelea_vectorized('f6',2) % Brian Birge % Rev 3.3 % 2/18/06 function [OUT,varargout]=pso_Trelea_vectorized(functname,D,varargin) rand('state',sum(100*clock)); if nargin < 2 error('Not enough arguments.'); end % PSO PARAMETERS if nargin == 2 % only specified functname and D VRmin=ones(D,1)*-100; VRmax=ones(D,1)*100; VR=[VRmin,VRmax]; minmax = 0; P = []; mv = 4; plotfcn='goplotpso'; elseif nargin == 3 % specified functname, D, and mv VRmin=ones(D,1)*-100; VRmax=ones(D,1)*100; VR=[VRmin,VRmax]; minmax = 0; mv=varargin{1}; if isnan(mv) mv=4; end P = []; plotfcn='goplotpso'; elseif nargin == 4 % specified functname, D, mv, Varrange mv=varargin{1}; if isnan(mv) mv=4; end VR=varargin{2}; minmax = 0; P = []; plotfcn='goplotpso'; elseif nargin == 5 % Functname, D, mv, Varrange, and minmax mv=varargin{1}; if isnan(mv) mv=4; end VR=varargin{2}; minmax=varargin{3}; P = []; plotfcn='goplotpso'; elseif nargin == 6 % Functname, D, mv, Varrange, minmax, and psoparams mv=varargin{1}; if isnan(mv) mv=4; end VR=varargin{2}; minmax=varargin{3}; P = varargin{4}; % psoparams plotfcn='goplotpso'; elseif nargin == 7 % Functname, D, mv, Varrange, minmax, and psoparams, plotfcn mv=varargin{1}; if isnan(mv) mv=4; end VR=varargin{2}; minmax=varargin{3}; P = varargin{4}; % psoparams plotfcn = varargin{5}; elseif nargin == 8 % Functname, D, mv, Varrange, minmax, and psoparams, plotfcn, PSOseedValue mv=varargin{1}; if isnan(mv) mv=4; end VR=varargin{2}; minmax=varargin{3}; P = varargin{4}; % psoparams plotfcn = varargin{5}; PSOseedValue = varargin{6}; else error('Wrong # of input arguments.'); end % sets up default pso params Pdef = [100 2000 24 2 2 0.9 0.4 1500 1e-25 250 NaN 0 0]; Plen = length(P); P = [P,Pdef(Plen+1:end)]; df = P(1); me = P(2); ps = P(3); ac1 = P(4); ac2 = P(5); iw1 = P(6); iw2 = P(7); iwe = P(8); ergrd = P(9); ergrdep = P(10); errgoal = P(11); trelea = P(12); PSOseed = P(13); % used with trainpso, for neural net training if strcmp(functname,'pso_neteval') net = evalin('caller','net'); Pd = evalin('caller','Pd'); Tl = evalin('caller','Tl'); Ai = evalin('caller','Ai'); Q = evalin('caller','Q'); TS = evalin('caller','TS'); end % error checking if ((minmax==2) & isnan(errgoal)) error('minmax= 2, errgoal= NaN: choose an error goal or set minmax to 0 or 1'); end if ( (PSOseed==1) & ~exist('PSOseedValue') ) error('PSOseed flag set but no PSOseedValue was input'); end if exist('PSOseedValue') tmpsz=size(PSOseedValue); if D < tmpsz(2) error('PSOseedValue column size must be D or less'); end if ps < tmpsz(1) error('PSOseedValue row length must be # of particles or less'); end end % set plotting flag if (P(1))~=0 plotflg=1; else plotflg=0; end % preallocate variables for speed up tr = ones(1,me)*NaN; % take care of setting max velocity and position params here if length(mv)==1 velmaskmin = -mv*ones(ps,D); % min vel, psXD matrix velmaskmax = mv*ones(ps,D); % max vel elseif length(mv)==D velmaskmin = repmat(forcerow(-mv),ps,1); % min vel velmaskmax = repmat(forcerow( mv),ps,1); % max vel else error('Max vel must be either a scalar or same length as prob dimension D'); end posmaskmin = repmat(VR(1:D,1)',ps,1); % min pos, psXD matrix posmaskmax = repmat(VR(1:D,2)',ps,1); % max pos posmaskmeth = 3; % 3=bounce method (see comments below inside epoch loop) % PLOTTING message = sprintf('PSO: %%g/%g iterations, GBest = %%20.20g.\n',me); % INITIALIZE INITIALIZE INITIALIZE INITIALIZE INITIALIZE INITIALIZE % initialize population of particles and their velocities at time zero, % format of pos= (particle#, dimension) % construct random population positions bounded by VR pos(1:ps,1:D) = normmat(rand([ps,D]),VR',1); if PSOseed == 1 % initial positions user input, see comments above tmpsz = size(PSOseedValue); pos(1:tmpsz(1),1:tmpsz(2)) = PSOseedValue; end % construct initial random velocities between -mv,mv vel(1:ps,1:D) = normmat(rand([ps,D]),... [forcecol(-mv),forcecol(mv)]',1); % initial pbest positions vals pbest = pos; % VECTORIZE THIS, or at least vectorize cost funct call out = feval(functname,pos); % returns column of cost values (1 for each particle) %--------------------------- pbestval=out; % initially, pbest is same as pos % assign initial gbest here also (gbest and gbestval) if minmax==1 % this picks gbestval when we want to maximize the function [gbestval,idx1] = max(pbestval); elseif minmax==0 % this works for straight minimization [gbestval,idx1] = min(pbestval); elseif minmax==2 % this works when you know target but not direction you need to go % good for a cost function that returns distance to target that can be either % negative or positive (direction info) [temp,idx1] = min((pbestval-ones(size(pbestval))*errgoal).^2); gbestval = pbestval(idx1); end % preallocate a variable to keep track of gbest for all iters bestpos = zeros(me,D+1)*NaN; gbest = pbest(idx1,:); % this is gbest position % used with trainpso, for neural net training % assign gbest to net at each iteration, these interim assignments % are for plotting mostly if strcmp(functname,'pso_neteval') net=setx(net,gbest); end %tr(1) = gbestval; % save for output bestpos(1,1:D) = gbest; % this part used for implementing Carlisle and Dozier's APSO idea % slightly modified, this tracks the global best as the sentry whereas % their's chooses a different point to act as sentry % see "Tracking Changing Extremea with Adaptive Particle Swarm Optimizer", % part of the WAC 2002 Proceedings, June 9-13, http://wacong.com sentryval = gbestval; sentry = gbest; if (trelea == 3) % calculate Clerc's constriction coefficient chi to use in his form kappa = 1; % standard val = 1, change for more or less constriction if ( (ac1+ac2) <=4 ) chi = kappa; else psi = ac1 + ac2; chi_den = abs(2-psi-sqrt(psi^2 - 4*psi)); chi_num = 2*kappa; chi = chi_num/chi_den; end end % INITIALIZE END INITIALIZE END INITIALIZE END INITIALIZE END rstflg = 0; % for dynamic environment checking % start PSO iterative procedures cnt = 0; % counter used for updating display according to df in the options cnt2 = 0; % counter used for the stopping subroutine based on error convergence iwt(1) = iw1; for i=1:me % start epoch loop (iterations) out = feval(functname,[pos;gbest]); outbestval = out(end,:); out = out(1:end-1,:); tr(i+1) = gbestval; % keep track of global best val te = i; % returns epoch number to calling program when done bestpos(i,1:D+1) = [gbest,gbestval]; %assignin('base','bestpos',bestpos(i,1:D+1)); %------------------------------------------------------------------------ % this section does the plots during iterations if plotflg==1 if (rem(i,df) == 0 ) | (i==me) | (i==1) fprintf(message,i,gbestval); cnt = cnt+1; % count how many times we display (useful for movies) eval(plotfcn); % defined at top of script end % end update display every df if statement end % end plotflg if statement % check for an error space that changes wrt time/iter % threshold value that determines dynamic environment % sees if the value of gbest changes more than some threshold value % for the same location chkdyn = 1; rstflg = 0; % for dynamic environment checking if chkdyn==1 threshld = 0.05; % percent current best is allowed to change, .05 = 5% etc letiter = 5; % # of iterations before checking environment, leave at least 3 so PSO has time to converge outorng = abs( 1- (outbestval/gbestval) ) >= threshld; samepos = (max( sentry == gbest )); if (outorng & samepos) & rem(i,letiter)==0 rstflg=1; % disp('New Environment: reset pbest, gbest, and vel'); %% reset pbest and pbestval if warranted % outpbestval = feval( functname,[pbest] ); % Poutorng = abs( 1-(outpbestval./pbestval) ) > threshld; % pbestval = pbestval.*~Poutorng + outpbestval.*Poutorng; % pbest = pbest.*repmat(~Poutorng,1,D) + pos.*repmat(Poutorng,1,D); pbest = pos; % reset personal bests to current positions pbestval = out; vel = vel*10; % agitate particles a little (or a lot) % recalculate best vals if minmax == 1 [gbestval,idx1] = max(pbestval); elseif minmax==0 [gbestval,idx1] = min(pbestval); elseif minmax==2 % this section needs work [temp,idx1] = min((pbestval-ones(size(pbestval))*errgoal).^2); gbestval = pbestval(idx1); end gbest = pbest(idx1,:); % used with trainpso, for neural net training % assign gbest to net at each iteration, these interim assignments % are for plotting mostly if strcmp(functname,'pso_neteval') net=setx(net,gbest); end end % end if outorng sentryval = gbestval; sentry = gbest; end % end if chkdyn % find particles where we have new pbest, depending on minmax choice % then find gbest and gbestval %[size(out),size(pbestval)] if rstflg == 0 if minmax == 0 [tempi] = find(pbestval>=out); % new min pbestvals pbestval(tempi,1) = out(tempi); % update pbestvals pbest(tempi,:) = pos(tempi,:); % update pbest positions [iterbestval,idx1] = min(pbestval); if gbestval >= iterbestval gbestval = iterbestval; gbest = pbest(idx1,:); % used with trainpso, for neural net training % assign gbest to net at each iteration, these interim assignments % are for plotting mostly if strcmp(functname,'pso_neteval') net=setx(net,gbest); end end elseif minmax == 1 [tempi,dum] = find(pbestval<=out); % new max pbestvals pbestval(tempi,1) = out(tempi,1); % update pbestvals pbest(tempi,:) = pos(tempi,:); % update pbest positions [iterbestval,idx1] = max(pbestval); if gbestval <= iterbestval gbestval = iterbestval; gbest = pbest(idx1,:); % used with trainpso, for neural net training % assign gbest to net at each iteration, these interim assignments % are for plotting mostly if strcmp(functname,'pso_neteval') net=setx(net,gbest); end end elseif minmax == 2 % this won't work as it is, fix it later egones = errgoal*ones(ps,1); % vector of errgoals sqrerr2 = ((pbestval-egones).^2); sqrerr1 = ((out-egones).^2); [tempi,dum] = find(sqerr1 <= sqrerr2); % find particles closest to targ pbestval(tempi,1) = out(tempi,1); % update pbestvals pbest(tempi,:) = pos(tempi,:); % update pbest positions sqrerr = ((pbestval-egones).^2); % need to do this to reflect new pbests [temp,idx1] = min(sqrerr); iterbestval = pbestval(idx1); if (iterbestval-errgoal)^2 <= (gbestval-errgoal)^2 gbestval = iterbestval; gbest = pbest(idx1,:); % used with trainpso, for neural net training % assign gbest to net at each iteration, these interim assignments % are for plotting mostly if strcmp(functname,'pso_neteval') net=setx(net,gbest); end end end end % % build a simple predictor 10th order, for gbest trajectory % if i>500 % for dimcnt=1:D % pred_coef = polyfit(i-250:i,(bestpos(i-250:i,dimcnt))',20); % % pred_coef = polyfit(200:i,(bestpos(200:i,dimcnt))',20); % gbest_pred(i,dimcnt) = polyval(pred_coef,i+1); % end % else % gbest_pred(i,:) = zeros(size(gbest)); % end %gbest_pred(i,:)=gbest; %assignin('base','gbest_pred',gbest_pred); % % convert to non-inertial frame % gbestoffset = gbest - gbest_pred(i,:); % gbest = gbest - gbestoffset; % pos = pos + repmat(gbestoffset,ps,1); % pbest = pbest + repmat(gbestoffset,ps,1); %PSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSO % get new velocities, positions (this is the heart of the PSO algorithm) % each epoch get new set of random numbers rannum1 = rand([ps,D]); % for Trelea and Clerc types rannum2 = rand([ps,D]); if trelea == 2 % from Trelea's paper, parameter set 2 vel = 0.729.*vel... % prev vel +1.494.*rannum1.*(pbest-pos)... % independent +1.494.*rannum2.*(repmat(gbest,ps,1)-pos); % social elseif trelea == 1 % from Trelea's paper, parameter set 1 vel = 0.600.*vel... % prev vel +1.700.*rannum1.*(pbest-pos)... % independent +1.700.*rannum2.*(repmat(gbest,ps,1)-pos); % social elseif trelea ==3 % Clerc's Type 1" PSO vel = chi*(vel... % prev vel +ac1.*rannum1.*(pbest-pos)... % independent +ac2.*rannum2.*(repmat(gbest,ps,1)-pos)) ; % social else % common PSO algo with inertia wt % get inertia weight, just a linear funct w.r.t. epoch parameter iwe if i<=iwe iwt(i) = ((iw2-iw1)/(iwe-1))*(i-1)+iw1; else iwt(i) = iw2; end % random number including acceleration constants ac11 = rannum1.*ac1; % for common PSO w/inertia ac22 = rannum2.*ac2; vel = iwt(i).*vel... % prev vel +ac11.*(pbest-pos)... % independent +ac22.*(repmat(gbest,ps,1)-pos); % social end % limit velocities here using masking vel = ( (vel <= velmaskmin).*velmaskmin ) + ( (vel > velmaskmin).*vel ); vel = ( (vel >= velmaskmax).*velmaskmax ) + ( (vel < velmaskmax).*vel ); % update new position (PSO algo) pos = pos + vel; % position masking, limits positions to desired search space % method: 0) no position limiting, 1) saturation at limit, % 2) wraparound at limit , 3) bounce off limit minposmask_throwaway = pos <= posmaskmin; % these are psXD matrices minposmask_keep = pos > posmaskmin; maxposmask_throwaway = pos >= posmaskmax; maxposmask_keep = pos < posmaskmax; if posmaskmeth == 1 % this is the saturation method pos = ( minposmask_throwaway.*posmaskmin ) + ( minposmask_keep.*pos ); pos = ( maxposmask_throwaway.*posmaskmax ) + ( maxposmask_keep.*pos ); elseif posmaskmeth == 2 % this is the wraparound method pos = ( minposmask_throwaway.*posmaskmax ) + ( minposmask_keep.*pos ); pos = ( maxposmask_throwaway.*posmaskmin ) + ( maxposmask_keep.*pos ); elseif posmaskmeth == 3 % this is the bounce method, particles bounce off the boundaries with -vel pos = ( minposmask_throwaway.*posmaskmin ) + ( minposmask_keep.*pos ); pos = ( maxposmask_throwaway.*posmaskmax ) + ( maxposmask_keep.*pos ); vel = (vel.*minposmask_keep) + (-vel.*minposmask_throwaway); vel = (vel.*maxposmask_keep) + (-vel.*maxposmask_throwaway); else % no change, this is the original Eberhart, Kennedy method, % it lets the particles grow beyond bounds if psoparams (P) % especially Vmax, aren't set correctly, see the literature end %PSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSO % check for stopping criterion based on speed of convergence to desired % error tmp1 = abs(tr(i) - gbestval); if tmp1 > ergrd cnt2 = 0; elseif tmp1 <= ergrd cnt2 = cnt2+1; if cnt2 >= ergrdep if plotflg == 1 fprintf(message,i,gbestval); disp(' '); disp(['--> Solution likely, GBest hasn''t changed by at least ',... num2str(ergrd),' for ',... num2str(cnt2),' epochs.']); eval(plotfcn); end break end end % this stops if using constrained optimization and goal is reached if ~isnan(errgoal) if ((gbestval<=errgoal) & (minmax==0)) | ((gbestval>=errgoal) & (minmax==1)) if plotflg == 1 fprintf(message,i,gbestval); disp(' '); disp(['--> Error Goal reached, successful termination!']); eval(plotfcn); end break end % this is stopping criterion for constrained from both sides if minmax == 2 if ((tr(i)<errgoal) & (gbestval>=errgoal)) | ((tr(i)>errgoal) ... & (gbestval <= errgoal)) if plotflg == 1 fprintf(message,i,gbestval); disp(' '); disp(['--> Error Goal reached, successful termination!']); eval(plotfcn); end break end end % end if minmax==2 end % end ~isnan if % % convert back to inertial frame % pos = pos - repmat(gbestoffset,ps,1); % pbest = pbest - repmat(gbestoffset,ps,1); % gbest = gbest + gbestoffset; end % end epoch loop %% clear temp outputs % evalin('base','clear temp_pso_out temp_te temp_tr;'); % output & return OUT=[gbest';gbestval]; varargout{1}=[1:te]; varargout{2}=[tr(find(~isnan(tr)))]; return
github
hliangzhao/Mathematical-Model-Implementation-master
distancematrix.m
.m
Mathematical-Model-Implementation-master/HeuristicAlgorithm/遗传算法/TSP(GA)/distancematrix.m
883
utf_8
1e2d36405073bd86e4af83903a01299b
function dis = distancematrix(city) % DISTANCEMATRIX % dis = DISTANCEMATRIX(city) return the distance matrix, dis(i,j) is the % distance between city_i and city_j numberofcities = length(city); R = 6378.137; % The radius of the Earth for i = 1:numberofcities for j = i+1:numberofcities dis(i,j) = distance(city(i).lat, city(i).long, ... city(j).lat, city(j).long, R); dis(j,i) = dis(i,j); end end function d = distance(lat1, long1, lat2, long2, R) % DISTANCE % d = DISTANCE(lat1, long1, lat2, long2, R) compute distance between points % on sphere with radians R. % % Latitude/Longitude Distance Calculation: % http://www.mathforum.com/library/drmath/view/51711.html y1 = lat1/180*pi; x1 = long1/180*pi; y2 = lat2/180*pi; x2 = long2/180*pi; dy = y1-y2; dx = x1-x2; d = 2*R*asin(sqrt(sin(dy/2)^2+sin(dx/2)^2*cos(y1)*cos(y2)));
github
hliangzhao/Mathematical-Model-Implementation-master
distancematrix.m
.m
Mathematical-Model-Implementation-master/HeuristicAlgorithm/模拟退火算法/TSP(SA)/distancematrix.m
883
utf_8
1e2d36405073bd86e4af83903a01299b
function dis = distancematrix(city) % DISTANCEMATRIX % dis = DISTANCEMATRIX(city) return the distance matrix, dis(i,j) is the % distance between city_i and city_j numberofcities = length(city); R = 6378.137; % The radius of the Earth for i = 1:numberofcities for j = i+1:numberofcities dis(i,j) = distance(city(i).lat, city(i).long, ... city(j).lat, city(j).long, R); dis(j,i) = dis(i,j); end end function d = distance(lat1, long1, lat2, long2, R) % DISTANCE % d = DISTANCE(lat1, long1, lat2, long2, R) compute distance between points % on sphere with radians R. % % Latitude/Longitude Distance Calculation: % http://www.mathforum.com/library/drmath/view/51711.html y1 = lat1/180*pi; x1 = long1/180*pi; y2 = lat2/180*pi; x2 = long2/180*pi; dy = y1-y2; dx = x1-x2; d = 2*R*asin(sqrt(sin(dy/2)^2+sin(dx/2)^2*cos(y1)*cos(y2)));
github
hliangzhao/Mathematical-Model-Implementation-master
grMinSpanTree.m
.m
Mathematical-Model-Implementation-master/GraphTheory/basic/grMinSpanTree.m
2,112
utf_8
56d552b6d33551eda5bc8d5d1fe22a3d
function nMST=grMinSpanTree(E) % Function nMST=grMinSpanTree(E) solve % the minimal spanning tree problem for a connected graph. % Input parameter: % E(m,2) or (m,3) - the edges of graph and their weight; % 1st and 2nd elements of each row is numbers of vertexes; % 3rd elements of each row is weight of edge; % m - number of edges. % If we set the array E(m,2), then all weights is 1. % Output parameter: % nMST(n-1,1) - the list of the numbers of edges included % in the minimal (weighted) spanning tree in the including order. % Uses the greedy algorithm. % Author: Sergiy Iglin % e-mail: [email protected] % personal page: http://iglin.exponenta.ru % ============= Input data validation ================== if nargin<1, error('There are no input data!') end [m,n,E] = grValidation(E); % E data validation % ============= The data preparation ================== En=[(1:m)',E]; % we add the numbers En(:,2:3)=sort(En(:,2:3)')'; % edges on increase order ln=find(En(:,2)==En(:,3)); % the loops numbers En=En(setdiff([1:size(En,1)]',ln),:); % we delete the loops [w,iw]=sort(En(:,4)); % sort by weight Ens=En(iw,:); % sorted edges % === We build the minimal spanning tree by the greedy algorithm === Emst=Ens(1,:); % 1st edge include to minimal spanning tree Ens=Ens(2:end,:); % rested edges while (size(Emst,1)<n-1)&(~isempty(Ens)), Emst=[Emst;Ens(1,:)]; % we add next edge to spanning tree Ens=Ens(2:end,:); % rested edges if any((Emst(end,2)==Emst(1:end-1,2))&... (Emst(end,3)==Emst(1:end-1,3))) | ... IsCycle(Emst(:,2:3)), % the multiple edge or cycle Emst=Emst(1:end-1,:); % we delete the last added edge end end nMST=Emst(:,1); % numbers of edges return function ic=IsCycle(E); % true, if graph E have cycle n=max(max(E)); % number of vertexes A=zeros(n); A((E(:,1)-1)*n+E(:,2))=1; A=A+A'; % the connectivity matrix p=sum(A); % the vertexes power ic=false; while any(p<=1), % we delete all tails nc=find(p>1); % rested vertexes if isempty(nc), return end A=A(nc,nc); % new connectivity matrix p=sum(A); % new powers end ic=true; return
github
hliangzhao/Mathematical-Model-Implementation-master
grPlot.m
.m
Mathematical-Model-Implementation-master/GraphTheory/basic/grPlot.m
7,247
utf_8
f1fabec67aba7eda59ab08e1a77ffe2f
function h=grPlot(V,E,kind,vkind,ekind) % Function h=grPlot(V,E,kind,vkind,ekind) % draw the plot of the graph (digraph). % Input parameters: % V(n,2) or (n,3) - the coordinates of vertexes % (1st column - x, 2nd - y) and, maybe, 3rd - the weights; % n - number of vertexes. % If V(n,2), we write labels: numbers of vertexes, % if V(n,3), we write labels: the weights of vertexes. % If V=[], use regular n-angle. % E(m,2) or (m,3) - the edges of graph (arrows of digraph) % and their weight; 1st and 2nd elements of each row % is numbers of vertexes; % 3rd elements of each row is weight of arrow; % m - number of arrows. % If E(m,2), we write labels: numbers of edges (arrows); % if E(m,3), we write labels: weights of edges (arrows). % For disconnected graph use E=[] or h=PlotGraph(V). % kind - the kind of graph. % kind = 'g' (to draw the graph) or 'd' (to draw digraph); % (optional, 'g' default). % vkind - kind of labels for vertexes (optional). % ekind - kind of labels for edges or arrows (optional). % For vkind and ekind use the format of function FPRINTF, % for example, '%8.3f', '%14.10f' etc. Default value is '%d'. % Use '' (empty string) for don't draw labels. % Output parameter: % h - handle of figure (optional). % See also GPLOT. % Author: Sergiy Iglin % e-mail: [email protected] % personal page: http://iglin.exponenta.ru % Acknowledgements to Mr.Howard ([email protected]) % for testing of this algorithm. % ============= Input data validation ================== if nargin<1, error('There are no input data!') end if (nargin==1) & isempty(V), error('V is empty and E is not determined!') end if (nargin==2) & isempty(V) & isempty(E), error('V and E are empty!') end if ~isempty(V), if ~isnumeric(V), error('The array V must be numeric!') end sv=size(V); % size of array V if length(sv)~=2, error('The array V must be 2D!') end if (sv(2)<2), error('The array V must have 2 or 3 columns!'), end if nargin==1, % disconnected graph E=[]; end end if ~isempty(E), % for connected graph [m,n,newE]=grValidation(E); we=min(3,size(E,2)); % 3 for weighed edges E=newE; if isempty(V), % regular n-angle V=[cos(2*pi*[1:n]'/n) sin(2*pi*[1:n]'/n)]; sv=size(V); % size of array V end if n>sv(1), error('Several vertexes is not determined!'); end else m=0; end % ============= Other arguments ================== n=sv(1); % real number of vertexes wv=min(3,sv(2)); % 3 for weighted vertexes if nargin<3, % only 2 input parameters kind1='g'; else if isempty(kind), kind='g'; kind1='g'; end if ~ischar(kind), error('The argument kind must be a string!') else kind1=lower(kind(1)); end end if nargin<4, vkind1='%d'; else if ~ischar(vkind), error('The argument vkind must be a string!') else vkind1=lower(vkind); end end if nargin<5, ekind1='%d'; else if ~ischar(ekind), error('The argument ekind must be a string!') else ekind1=lower(ekind); end end md=inf; % the minimal distance between vertexes for k1=1:n-1, for k2=k1+1:n, md=min(md,sum((V(k1,:)-V(k2,:)).^2)^0.5); end end if md<eps, % identical vertexes error('The array V have identical rows!') else V(:,1:2)=V(:,1:2)/md; % normalization end r=0.1; % for multiple edges tr=linspace(pi/4,3*pi/4); xr=0.5-cos(tr)/2^0.5; yr=(sin(tr)-2^0.5/2)/(1-2^0.5/2); t=linspace(-pi/2,3*pi/2); % for loops xc=0.1*cos(t); yc=0.1*sin(t); % we sort the edges if ~isempty(E), E=[zeros(m,1),[1:m]',E]; % 1st column for change, 2nd column is edge number need2=find(E(:,4)<E(:,3)); % for replace v1<->v2 tmp=E(need2,3); E(need2,3)=E(need2,4); E(need2,4)=tmp; E(need2,1)=1; % 1, if v1<->v2 [e1,ie1]=sort(E(:,3)); % sort by 1st vertex E1=E(ie1,:); for k2=E1(1,3):E1(end,3), num2=find(E1(:,3)==k2); if ~isempty(num2), % sort by 2nd vertex E3=E1(num2,:); [e3,ie3]=sort(E3(:,4)); E4=E3(ie3,:); E1(num2,:)=E4; end end ip=find(E1(:,3)==E1(:,4)); % we find loops Ep=E1(ip,:); % loops E2=E1(setdiff([1:m],ip),:); % edges without loops end % we paint the graph hh=figure; hold on plot(V(:,1),V(:,2),'k.','MarkerSize',20) axis equal h1=get(gca); % handle of current figure if ~isempty(vkind1), % labels of vertexes for k=1:n, if wv==3, s=sprintf(vkind1,V(k,3)); else s=sprintf(vkind1,k); end hhh=text(V(k,1)+0.05,V(k,2)-0.07,s); % set(hhh,'FontName','Times New Roman Cyr','FontSize',18) end end % edges (arrows) if ~isempty(E), k=0; m2=size(E2,1); % number of edges without loops while k<m2, k=k+1; % current edge MyE=V(E2(k,3:4),1:2); % numbers of vertexes 1, 2 k1=1; % we find the multiple edges if k<m2, while all(E2(k,3:4)==E2(k+k1,3:4)), k1=k1+1; if k+k1>m2, break; end end end ry=r*[1:k1]; ry=ry-mean(ry); % radius l=norm(MyE(1,:)-MyE(2,:)); % lenght of line dx=MyE(2,1)-MyE(1,1); dy=MyE(2,2)-MyE(1,2); alpha=atan2(dy,dx); % angle of rotation cosa=cos(alpha); sina=sin(alpha); MyX=xr*l; for k2=1:k1, % we draw the edges (arrows) MyY=yr*ry(k2); MyXg=MyX*cosa-MyY*sina+MyE(1,1); MyYg=MyX*sina+MyY*cosa+MyE(1,2); plot(MyXg,MyYg,'k-'); if kind1=='d', % digraph with arrows if E2(k+k2-1,1)==1, [xa,ya]=CreateArrow(MyXg(1:2),MyYg(1:2)); fill(xa,ya,'k'); else [xa,ya]=CreateArrow(MyXg(end:-1:end-1),MyYg(end:-1:end-1)); fill(xa,ya,'k'); end end if ~isempty(ekind1), % labels of edges (arrows) if we==3, s=sprintf(ekind1,E2(k+k2-1,5)); else s=sprintf(ekind1,E2(k+k2-1,2)); end text(MyXg(length(MyXg)/2),MyYg(length(MyYg)/2),s); % set(hhh,'FontName','Times New Roman Cyr','FontSize',18) end end k=k+k1-1; end % we draw the loops k=0; ml=size(Ep,1); % number of loops while k<ml, k=k+1; % current loop MyV=V(Ep(k,3),1:2); % vertexes k1=1; % we find the multiple loops if k<ml, while all(Ep(k,3:4)==Ep(k+k1,3:4)), k1=k1+1; if k+k1>ml, break; end end end ry=[1:k1]+1; % radius for k2=1:k1, % we draw the loop MyX=xc*ry(k2)+MyV(1); MyY=(yc+r)*ry(k2)+MyV(2); plot(MyX,MyY,'k-'); if kind1=='d', [xa,ya]=CreateArrow(MyX([1 10]),MyY([1 10])); fill(xa,ya,'k'); end if ~isempty(ekind1), % labels of edges (arrows) if we==3, s=sprintf(ekind1,Ep(k+k2-1,5)); else s=sprintf(ekind1,Ep(k+k2-1,2)); end hhh=text(MyX(length(MyX)/2),MyY(length(MyY)/2),s); % set(hhh,'FontName','Times New Roman Cyr','FontSize',18) end end k=k+k1-1; end end hold off axis off if nargout==1, h=hh; end return function [xa,ya]=CreateArrow(x,y) % create arrow with length 0.1 with tip x(1), y(1) % and direction from x(2), y(2) xa1=[0 0.1 0.08 0.1 0]'; ya1=[0 0.03 0 -0.03 0]'; dx=diff(x); dy=diff(y); alpha=atan2(dy,dx); % angle of rotation cosa=cos(alpha); sina=sin(alpha); xa=xa1*cosa-ya1*sina+x(1); ya=xa1*sina+ya1*cosa+y(1); return
github
avst34/nlp-master
loadData.m
.m
nlp-master/datasets/pp_attachement/boknilev/code/loadData.m
3,566
utf_8
4df1832c9e035e29642054c26367c290
function data = loadData(model, params, pref, wordVectors, varargin) %%%% default values %%%% numvarargs = length(varargin); if numvarargs > 2 error('loadData:TooManyInputs', ... 'requires at most 2 optional input'); end if params.useExt && numvarargs ~= 2 error('loadData:TooFewInputs', ... 'if useExt=true, must have exactly 2 more inputs'); end % set defaults for optional inputs optargs = {'' ''}; % now put these defaults into the valuesToUse cell array, % and overwrite the ones specified in varargin. optargs(1:numvarargs) = varargin; % Place optional args in memorable variable names [vn wn] = optargs{:}; %%%%%%%%%%%%%%%%%%%%%%%%% if model == 6 prepsFilename = [pref '.' 'preps']; ppChildrenFilename = [pref '.' 'children']; headsFilePref = [pref '.' 'heads']; labelsFilename = [pref '.' 'labels']; nheadsFilename = [pref '.' 'nheads']; if params.useExt headsPosfilename = [headsFilePref '.' 'pos']; headsNextPosFilename = [headsFilePref '.' 'next.pos']; if ~isfield(params, 'pos2idx') % create map pos2idx if not created already data.pos2idx = loadPosMapFromFile(headsNextPosFilename); else data.pos2idx = params.pos2idx; end [heads, preps, ppChildren, labels, nheads, includeInd] = loadDataSingleWordPP(wordVectors, params.inputSize, params.maxNumHeads, ... [headsFilePref '.words'], [prepsFilename '.words'], [ppChildrenFilename '.words'], ... labelsFilename, nheadsFilename, params.scaleVectors, ... params.useExt, headsPosfilename, headsNextPosFilename, data.pos2idx, vn, wn, params.language); else [heads, preps, ppChildren, labels, nheads, includeInd] = loadDataSingleWordPP(wordVectors, params.inputSize, params.maxNumHeads, ... [headsFilePref '.words'], [prepsFilename '.words'], [ppChildrenFilename '.words'], ... labelsFilename, nheadsFilename, params.scaleVectors, params.useExt); end data.heads = heads; data.preps = preps; data.ppChildren = ppChildren; ... data.labels = labels; data.nheads = nheads; data.includeInd = includeInd; if params.updateWordVectors [wordVectorsMat, indHeadsToWordVectors, indPrepsToWordVectors, indChildrenToWordVectors, labels, nheads] = ... loadDataSingleWordPPIndices(wordVectors, params.inputSize, params.maxNumHeads, ... [headsFilePref '.words'], [prepsFilename '.words'], [ppChildrenFilename '.words'], ... labelsFilename, nheadsFilename, params.scaleVectors); data.indHeadsToWordVectors = indHeadsToWordVectors; data.indPrepsToWordVectors = indPrepsToWordVectors; data.indChildrenToWordVectors = indChildrenToWordVectors; data.labels = labels; data.nheads = nheads; data.wordVectorsMat = wordVectorsMat; end else error('Error', ['unknown model ' num2str(model) ' in loadData()']); end end function pos2idx = loadPosMapFromFile(headsNextPosFilename) % load a map from pos to idx from a file with the pos for words following % candidate heads headNextPosLines = loadLinesFromFile(headsNextPosFilename); pos2idx = containers.Map(); % map pos to idx for i = 1:size(headNextPosLines, 1) poses = regexp(headNextPosLines(i), '\s+', 'split'); poses = poses{1}; for j = 1:size(poses, 2) pos = poses{j}; if ~isKey(pos2idx, pos) pos2idx(pos) = pos2idx.Count+1; end end end end
github
avst34/nlp-master
saveParameters.m
.m
nlp-master/datasets/pp_attachement/boknilev/code/saveParameters.m
1,511
utf_8
b8d196562c783d006af5c5637a90fed3
function saveParameters(model, theta, params, saveFile) if model == 6 saveParametersHeadDist(theta, params, saveFile); else error('Error', ['Unknown model ' num2str(model) ' in saveParameters()']); end end function saveParametersHeadDist(theta, params, saveFile) numDistances = params.numDistances; inputSize = params.inputSize + params.extDim; % extDim = 0 if not used W = reshape(theta(1:2*inputSize*inputSize), inputSize, 2*inputSize); Wdists = reshape(theta(2*inputSize*inputSize+1:(numDistances+1)*2*inputSize*inputSize), numDistances*inputSize, 2*inputSize); b = theta((numDistances+1)*2*inputSize*inputSize+1:(numDistances+1)*2*inputSize*inputSize+inputSize); bdists = theta((numDistances+1)*2*inputSize*inputSize+inputSize+1:(numDistances+1)*2*inputSize*inputSize+(numDistances+1)*inputSize); w = theta((numDistances+1)*2*inputSize*inputSize+(numDistances+1)*inputSize+1:(numDistances+1)*2*inputSize*inputSize+(numDistances+1)*inputSize+inputSize); if params.updateExt ext = theta(end-params.extDim+1:end); save(saveFile, 'W', 'Wdists', 'b', 'bdists', 'w', 'ext'); elseif params.updateWordVectors wordVectorsVocabSize = params.vocabSize; disp('Warning: saving word vectors as params is not up-to-date!'); wordVectors = reshape(theta(end-params.inputSize*wordVectorsVocabSize+1:end), params.inputSize, wordVectorsVocabSize); save(saveFile, 'W', 'Wdists', 'b', 'bdists', 'w', 'wordVectors'); else save(saveFile, 'W', 'Wdists', 'b', 'bdists', 'w'); end end
github
avst34/nlp-master
functionCostGrad.m
.m
nlp-master/datasets/pp_attachement/boknilev/code/functionCostGrad.m
2,380
utf_8
42b121b38683ac9aa8f922d8886c5c81
function [cost, grad] = functionCostGrad(theta, model, params, data) if model == 6 [cost, grad] = SingleWordPPHeadDistCostDispatcher(theta, params, data); else error('Error', ['unknown model ' num2str(model) ' in functionCostGrad()']); end end function [cost, grad] = SingleWordPPHeadDistCostDispatcher(theta, params, data) if params.updateWordVectors if params.useExt prepsExt = data.preps(params.inputSize+1:end,:); ppChildrenExt = data.ppChildren(params.inputSize+1:end,:); headsExt = data.heads(params.inputSize+1:end,:,:); [cost, grad] = SingleWordPPHeadDistDropoutUpdateWordVectorsExtCost(theta, ... params.inputSize, params.extDim, params.beta, params.dropout, ... params.maxNumHeads, data.labels, data.nheads, params.scaleVectors, ... params.vocabSize, ... data.indPrepsToWordVectors, data.indHeadsToWordVectors, data.indChildrenToWordVectors, ... prepsExt, headsExt, ppChildrenExt); else [cost, grad] = SingleWordPPHeadDistDropoutUpdateWordVectorsCost(theta, ... params.inputSize, params.beta, params.dropout, ... params.maxNumHeads, data.labels, data.nheads, params.scaleVectors, ... params.vocabSize, ... data.indPrepsToWordVectors, data.indHeadsToWordVectors, data.indChildrenToWordVectors); end else if params.updateExt [cost, grad] = SingleWordPPHeadDistDropoutUpdateExtCost(theta, params.inputSize+params.extDim, params.extDim, ... params.beta, params.dropout, ... params.maxNumHeads, data.heads, data.preps, ... data.ppChildren, data.labels, data.nheads, params.scaleVectors); else [cost, grad] = SingleWordPPHeadDistDropoutCost(theta, params.inputSize+params.extDim, ... params.beta, params.dropout, ... params.maxNumHeads, data.heads, data.preps, ... data.ppChildren, data.labels, data.nheads, params.scaleVectors); end end end
github
avst34/nlp-master
applyNonLinearity.m
.m
nlp-master/datasets/pp_attachement/boknilev/code/applyNonLinearity.m
265
utf_8
a3ea8f80b368b381289a9c9009f02d57
function result = applyNonLinearity(x) % result = 1 ./ (1 + exp(-x)); % sigmoid result = tanh(x); % tanh end function invResult = applyInverseNonLinearity(x) % invResult = log(x) - log(1-x); % sigmoid case invResult = atanh(x); % tanh case end
github
avst34/nlp-master
loadVerbnetWordnet.m
.m
nlp-master/datasets/pp_attachement/boknilev/code/loadVerbnetWordnet.m
3,466
utf_8
dfdf794e13ef30fc292e9f1fb63a70b9
function [vn, wn] = loadVerbnetWordnet(vnDir, wnDir, language) % load Verbnet and Wordnet from disk (prepared by Python scripts) if strcmpi(language, 'english') [vn, wn] = loadEnglishVerbnetWordnet([vnDir '/' 'verb2prep.txt'], [vnDir '/' 'verbalnoun2prep.txt'], ... [vnDir '/' 'verb2class.txt'], [wnDir '/' 'word2tophypernym.txt']); elseif strcmpi(language, 'arabic') [vn, wn] = loadArabicVerbnetWordnet([vnDir '/' 'verb2prep.txt'], [vnDir '/' 'verb2class.txt'], ... [wnDir '/' 'verb2tophypernym.txt'], [wnDir '/' 'noun2tophypernym.txt']); else disp(['Error: unknown language ' language]); end end function [evn, ewn] = loadEnglishVerbnetWordnet(verbPrepFilename, verbClassFilename, ... verbTopHypernymFilename, nounTopHypernymFilename) % load English Verbnet and Wordnet % verbnet verbPrepLines = loadLinesFromFile(verbPrepFilename); evn.verb2prep = getMapFromLines(verbPrepLines); verbClassLines = loadLinesFromFile(verbClassFilename); evn.verb2class = getMapFromLines(verbClassLines); verbClasses = {}; values = evn.verb2class.values; for i = 1:size(values, 2) verbClasses = union(verbClasses, values{i}); end evn.verbclass2idx = containers.Map(verbClasses, [1:size(verbClasses, 2)]); % wordnet % noun nounTopHypernymLines = loadLinesFromFile(nounTopHypernymFilename); ewn.noun2tophypernym = getMapFromLines(nounTopHypernymLines); hypernyms = {}; values = ewn.noun2tophypernym.values; for i = 1:length(values) hypernyms = union(hypernyms, values{i}); end ewn.nounhypernym2idx = containers.Map(hypernyms, [1:length(hypernyms)]); % verb (not used for now) verbTopHypernymLines = loadLinesFromFile(verbTopHypernymFilename); ewn.verb2tophypernym = getMapFromLines(verbTopHypernymLines); hypernyms = {}; values = ewn.verb2tophypernym.values; for i = 1:size(values, 2) hypernyms = union(hypernyms, values{i}); end ewn.verbhypernym2idx = containers.Map(hypernyms, [1:size(hypernyms, 2)]); end function [avn, awn] = loadArabicVerbnetWordnet(verbPrepFilename, verbalnounPrepFilename, verbClassFilename, wordTopHypernymFilename) % load Arabic Verbnet and Wordnet % verbnet verbPrepLines = loadLinesFromFile(verbPrepFilename); avn.verb2prep = getMapFromLines(verbPrepLines); verbalnounPrepLines = loadLinesFromFile(verbalnounPrepFilename); avn.verbalnoun2prep = getMapFromLines(verbalnounPrepLines); % verb classes (not used for now) verbClassLines = loadLinesFromFile(verbClassFilename); avn.verb2class = getMapFromLines(verbClassLines); verbClasses = {}; values = avn.verb2class.values; for i = 1:size(values, 2) verbClasses = union(verbClasses, values{i}); end avn.verbclass2idx = containers.Map(verbClasses, [1:size(verbClasses, 2)]); % wordnet wordTopHypernymLines = loadLinesFromFile(wordTopHypernymFilename); awn.word2tophypernym = getMapFromLines(wordTopHypernymLines); hypernyms = {}; values = awn.word2tophypernym.values; for i = 1:size(values, 2) hypernyms = union(hypernyms, values{i}); end awn.hypernym2idx = containers.Map(hypernyms, [1:size(hypernyms, 2)]); end function m = getMapFromLines(lines) m = containers.Map(); for i = 1:size(lines) line = regexp(lines(i), '\s+', 'split'); line = line{1}; k = line{1}; if size(line, 2) > 1 vals = line(2:end); else vals = {}; end m(k) = vals; end end
github
avst34/nlp-master
loadDataSingleWordPP.m
.m
nlp-master/datasets/pp_attachement/boknilev/code/loadDataSingleWordPP.m
9,103
utf_8
f4d60f7b74808ed6aab5ce354b57df83
function [heads, preps, ppChildren, labels, nheads, includeInd] = loadDataSingleWordPP(wordVectors, ... inputSize, maxNumHeads, ... headWordsFilename, prepWordsFilename, ... ppChildWordsFilename, labelsFilename, ... nheadsFilename, scaleVectors, ... useExt, varargin) %%%% default values %%%% numvarargs = length(varargin); if numvarargs > 6 error('loadDataSingleWordPP:TooManyInputs', ... 'requires at most 6 optional input'); end if useExt && numvarargs ~= 6 error('loadDataSingleWordPP:TooFewInputs', ... 'if useExt=true, must have exactly 6 more inputs'); end % set defaults for optional inputs optargs = {'' '' '' '' '' ''}; % now put these defaults into the valuesToUse cell array, % and overwrite the ones specified in varargin. optargs(1:numvarargs) = varargin; % Place optional args in memorable variable names [headsPosFilename headsNextPosFilename pos2idx vn wn, language] = optargs{:}; %%%%%%%%%%%%%%%%%%%%%%%%% % wordVectors - Map of word string to vector % useExt - if true, load extended vector dimensions % pos2idx - map from pos to index (to be used in one-hot vector) % load data for the model assuming preposition has only a single child headLines = loadLinesFromFile(headWordsFilename); prepWords = loadLinesFromFile(prepWordsFilename); ppChildWords = loadLinesFromFile(ppChildWordsFilename); extDim = 0; if useExt headPosLines = loadLinesFromFile(headsPosFilename); headNextPosLines = loadLinesFromFile(headsNextPosFilename); % extDim = 1 + pos2idx.Count + 1 + 1 + avn.verbclass2idx.Count + awn.hypernym2idx.Count; % head pos, next pos, verb-prep, verbalnoun-prep, verbclass, word hypernym %%% TODO add dims % hypOffset = 1 + pos2idx.Count + 1 + 1 + avn.verbclass2idx.Count; if strcmpi(language, 'arabic') extDim = 2 + pos2idx.Count + 1 + 1 + wn.hypernym2idx.Count; % head pos, next pos, verb-prep, verbalnoun-prep, word hypernym hypOffset = 2 + pos2idx.Count + 1 + 1; elseif strcmpi(language, 'english') extDim = 2 + pos2idx.Count + 1 + wn.nounhypernym2idx.Count; % head pos, next pos, verb-prep, noun hypernym hypOffset = 2 + pos2idx.Count + 1; end end datasize = size(headLines, 1); if size(prepWords, 1) ~= datasize || size(ppChildWords, 1) ~= datasize disp('Error: incompatible sizes') end preps = zeros(inputSize+extDim, datasize); heads = zeros(inputSize+extDim, maxNumHeads, datasize); ppChildren = zeros(inputSize+extDim, datasize); includeInd = []; for i = 1:datasize prepWord = prepWords{i}; childWord = ppChildWords{i}; if isKey(wordVectors, prepWord) && isKey(wordVectors, childWord) % only consider examples which have word vectors headLine = headLines(i); curHeadWords = regexp(headLine, '\s+', 'split'); curHeadWords = curHeadWords{1}; curHeads = zeros(inputSize+extDim, maxNumHeads); numExistingHeads = size(curHeadWords,2); if useExt headPosLine = headPosLines(i); curHeadPos = regexp(headPosLine, '\s+', 'split'); curHeadPos = str2double(curHeadPos{1}); headNextPosLine = headNextPosLines(i); curHeadNextPos = regexp(headNextPosLine, '\s+', 'split'); curHeadNextPos = curHeadNextPos{1}; end missingHeadVector = false; for j = 1:numExistingHeads curHeadWord = curHeadWords{j}; if isKey(wordVectors, curHeadWord) curHead = wordVectors(curHeadWord); if useExt headExt = getHeadExt(j, curHeadPos, curHeadNextPos, ... pos2idx, vn, wn, curHeadWord, prepWord, language); if size(headExt, 2) < extDim headExt = [headExt zeros(1, extDim-size(headExt, 2))]; end curHead = [curHead headExt]; end curHeads(:,j) = curHead; else missingHeadVector = true; end end for j = numExistingHeads+1:maxNumHeads curHeads(:,j) = zeros(inputSize+extDim,1); end if ~missingHeadVector % all words (heads, preps, children) have vectors, so can add includeInd = [includeInd; i]; prep = wordVectors(prepWord); child = wordVectors(childWord); if useExt prepExt = getPrepExt(extDim); prep = [prep prepExt]; childExt = getChildExt(extDim, wn, childWord, hypOffset, language); child = [child childExt]; end preps(:, i) = prep; ppChildren(:, i) = child; heads(:,:,i) = curHeads; end end end labels = load(labelsFilename); nheads = load(nheadsFilename); % take only included instances labels = labels(includeInd); nheads = nheads(includeInd); preps = preps(:,includeInd); ppChildren = ppChildren(:,includeInd); heads = heads(:,:,includeInd); % scale preps = scaleVectors*preps; heads = scaleVectors*heads; ppChildren = scaleVectors*ppChildren; end function headExt = getHeadExt(j, curHeadPos, curHeadNextPos, pos2idx, vn, wn, curHeadWord, prepWord, language) % get extended dimensions for head headExt = []; % pos pos = curHeadPos(j); posVec = [0 0]; if pos == 1; posVec(1) = 1; else posVec(2) = 1; end headExt = [headExt posVec]; % next pos nextPosVec = zeros(1, pos2idx.Count); % one hot vector if j <= size(curHeadNextPos, 2) nextPos = curHeadNextPos{j}; if isKey(pos2idx, nextPos) nextPosVec(pos2idx(nextPos)) = 1; end end headExt = [headExt nextPosVec]; % verb-prep verbPrep = 0; if pos == 1 && isKey(vn.verb2prep, curHeadWord) if ismember(prepWord, vn.verb2prep(curHeadWord)) verbPrep = 1; % else % verbPrep = -1; end end headExt = [headExt verbPrep]; if strcmpi(language, 'arabic') % verbalnoun-prep verbalnounPrep = 0; if pos == -1 && isKey(vn.verbalnoun2prep, curHeadWord) if ismember(prepWord, vn.verbalnoun2prep(curHeadWord)) verbalnounPrep = 1; % else % verbalnounPrep = -1; end end headExt = [headExt verbalnounPrep]; end % % verb class % verbClassVec = zeros(1, vn.verbclass2idx.Count); % one-hot vector % if pos == 1 && isKey(vn.verb2class, curHeadWord) % curVerbClasses = vn.verb2class(curHeadWord); % for c = 1:size(curVerbClasses, 2) % verbClassVec(vn.verbclass2idx(curVerbClasses{c})) = 1; % end % end % curHead = [curHead verbClassVec]; % head top hypernym if strcmpi(language, 'arabic') hypernymVec = zeros(1, wn.hypernym2idx.Count); if isKey(wn.word2tophypernym, curHeadWord) curWordHypernyms = wn.word2tophypernym(curHeadWord); for h = 1:size(curWordHypernyms, 2) hypernymVec(wn.hypernym2idx(curWordHypernyms{h})) = 1; end end elseif strcmpi(language, 'english') hypernymVec = zeros(1, wn.nounhypernym2idx.Count); if pos == -1 && isKey(wn.noun2tophypernym, curHeadWord) % for now use only noun hypernyms curWordHypernyms = wn.noun2tophypernym(curHeadWord); for h = 1:size(curWordHypernyms, 2) hypernymVec(wn.nounhypernym2idx(curWordHypernyms{h})) = 1; end end end headExt = [headExt hypernymVec]; end function childExt = getChildExt(extDim, wn, childWord, hypOffset, language) childExt = zeros(1, extDim); if strcmpi(language, 'arabic') if isKey(wn.word2tophypernym, childWord) % child top hypernym curWordHypernyms = wn.word2tophypernym(childWord); for h = 1:size(curWordHypernyms, 2) childExt(hypOffset + wn.hypernym2idx(curWordHypernyms{h})) = 1; end end elseif strcmpi(language, 'english') if isKey(wn.noun2tophypernym, childWord) % child top hypernym curWordHypernyms = wn.noun2tophypernym(childWord); for h = 1:size(curWordHypernyms, 2) childExt(hypOffset + wn.nounhypernym2idx(curWordHypernyms{h})) = 1; end end end end function prepExt = getPrepExt(extDim) % for now prepExt is just a zero vector prepExt = zeros(1, extDim); end
github
avst34/nlp-master
filterWordVectors.m
.m
nlp-master/datasets/pp_attachement/boknilev/code/filterWordVectors.m
3,221
utf_8
9065ab66e8f71b6dcef413834b11a2a1
function filteredWordVectors = filterWordVectors(wordVectors, model, params, filenames) disp('filtering word vectors based on train/test data'); disp(['wordVectors size before filtering: ' num2str(wordVectors.Count)]); intrainWordVectors = filterWordVectorsFromData(wordVectors, model, params, filenames.trainFilePref); intestWordVectors = filterWordVectorsFromData(wordVectors, model, params, filenames.testFilePref); filteredWordVectors = mergeMaps(intrainWordVectors, intestWordVectors); disp(['wordVectors size after filtering: ' num2str(filteredWordVectors.Count)]); end function filteredWordVectors = filterWordVectorsFromData(wordVectors, model, params, pref) % store UNK vector before filtering if params.useUnk if ~isKey(wordVectors, 'UNK') disp('WARNING: cannot useUnk when no UNK vector exists, resorting to zeros'); unkVec = zeros(params.inputSize); else unkVec = wordVectors('UNK'); end end if model == 1 || model == 2 || model == 5 || model == 6 || model == 7 || model == 10 || model == 12 prepsFilename = [pref '.' 'preps']; ppChildrenFilename = [pref '.' 'children']; headsFilePref = [pref '.' 'heads']; filteredWordVectors = filterWordVectorsFromFile(wordVectors, [prepsFilename '.words']); filteredWordVectors = mergeMaps(filteredWordVectors, filterWordVectorsFromFile(wordVectors, [ppChildrenFilename '.words'])); filteredWordVectors = mergeMaps(filteredWordVectors, filterWordVectorsFromHeadFile(wordVectors, [headsFilePref '.words'])); if model == 10 || model == 12 headsNextWordsFilename = [pref '.' 'heads.next.words']; filteredWordVectors = mergeMaps(filteredWordVectors, filterWordVectorsFromHeadFile(wordVectors, headsNextWordsFilename)); end else disp(['Error: filtering word vectors not implemented for model ' num2str(model)]); return; end % add UNK vector if necessary if params.useUnk filteredWordVectors('UNK') = unkVec; end end function filteredWordVectors = filterWordVectorsFromFile(wordVectors, file) words = loadLinesFromFile(file); filteredWordVectors = containers.Map(); for i = 1:size(words, 1) word = words{i}; if isKey(wordVectors, word) && ~isKey(filteredWordVectors, word) filteredWordVectors(word) = wordVectors(word); end end end function filteredWordVectors = filterWordVectorsFromHeadFile(wordVectors, file) headLines = loadLinesFromFile(file); filteredWordVectors = containers.Map(); for i = 1:size(headLines, 1) headLine = headLines(i); curHeadWords = regexp(headLine, '\s+', 'split'); curHeadWords = curHeadWords{1}; numExistingHeads = size(curHeadWords,2); for j = 1:numExistingHeads curHeadWord = curHeadWords{j}; if isKey(wordVectors, curHeadWord) && ~isKey(filteredWordVectors, curHeadWord) filteredWordVectors(curHeadWord) = wordVectors(curHeadWord); end end end end function m = mergeMaps(m1, m2) m = m1; m2keys = m2.keys(); m2vals = m2.values(); for i = 1:m2.Count k = m2keys{i}; v = m2vals{i}; if ~isKey(m, k) m(k) = v; end end end
github
avst34/nlp-master
initializeParameters.m
.m
nlp-master/datasets/pp_attachement/boknilev/code/initializeParameters.m
1,892
utf_8
74b70c503762678519fc03716d5fa542
function theta = initializeParameters(params, model) inputSize = double(params.inputSize+params.extDim); % add extended dimensions scaleParam = params.scaleParam; if model == 6 theta = initializeParametersHeadDist(inputSize, params.numDistances, scaleParam); else disp(['Error: unknown model ' num2str(model)]); % TODO change end if params.updateExt ext = ones(params.extDim, 1); theta = [theta(:); ext]; end end function theta = initializeParametersHeadDist(inputSize, varargin) % Define different Ws for composing with heads at different distances, % and another W for other compositions %%%% default values %%%% numvarargs = length(varargin); if numvarargs > 2 error('initializeParametersHeadDist:TooManyInputs', ... 'requires at most 2 optional input'); end % set defaults for optional inputs optargs = {5 1}; % now put these defaults into the valuesToUse cell array, % and overwrite the ones specified in varargin. optargs(1:numvarargs) = varargin; % Place optional args in memorable variable names [numDistances scaleParam] = optargs{:}; %%%%%%%%%%%%%%%%%%%%%%%%% % r = sqrt(6/(2*inputSize + inputSize)); r = 1/sqrt(inputSize*100); % global W, b W = 0.5*[eye(inputSize) eye(inputSize)] + (-r + 2*r.*rand(inputSize, 2*inputSize)); % W = 0.5*[eye(inputSize) eye(inputSize)] + (0.001 + 0.002.*rand(inputSize, 2*inputSize)); % b = 0.001 + 0.002.*rand(inputSize,1); % b = 0.001*ones(inputSize, 1); b = zeros(inputSize, 1); Wdists = 0.5 * repmat(eye(inputSize), numDistances, 2) + (-r + 2*r.*rand(numDistances*inputSize, 2*inputSize)); bdists = zeros(numDistances*inputSize, 1); % w w = 0.5*(-1/sqrt(inputSize) + 2/sqrt(inputSize).*rand(inputSize,1)); %%% for now % w = ones(inputSize, 1) + 0.001 + 0.002 .* rand(inputSize,1); % w = 1e-3*rand(inputSize,1); theta = [W(:); Wdists(:); b(:); bdists(:); w(:)]; theta = theta*scaleParam; end
github
avst34/nlp-master
trainModel.m
.m
nlp-master/datasets/pp_attachement/boknilev/code/trainModel.m
5,365
utf_8
1b6fa3a315a9881cf0367c07b870d658
function opttheta = trainModel(theta, data, wordVectors, params, model, trainParams, filenames) opttheta = theta; datasize = size(data.heads, 3); batchsize = trainParams.batchsize; numBatches = floor(datasize/batchsize)+1; iters = trainParams.iters; % iterations per batch sumSquares = ones(size(theta)); if trainParams.usePretrainedSumSquares disp('using pretrained sumSquares'); s = load(filenames.sumSquaresFile); sumSquares = s.sumSquares; end % for updating with different learning rates paramsSize = length(opttheta); wordVectorsRange = (paramsSize-params.inputSize*wordVectors.Count+1:paramsSize); otherParamsRange = (1:paramsSize-params.inputSize*wordVectors.Count); bestTheta = opttheta; [bestCost, bestGrad] = functionCostGrad(opttheta, model, params, data); disp(['initial cost: ' num2str(bestCost)]); tic; for t = 1:trainParams.epochs if ~trainParams.quiet disp(['epoch ' num2str(t)]); end rp = randperm(datasize); data = getDataSubind(data, model, rp, params); for i = 1:numBatches % startIdx = mod((i-1) * batchsize, datasize) + 1; startIdx = (i-1)*batchsize + 1; if startIdx > datasize continue; end endIdx = min(startIdx + batchsize - 1, datasize); % disp(['minibatch start: ' num2str(startIdx) ' end: ' num2str(endIdx)]); curData = getDataSubind(data, model, startIdx:endIdx, params); if strcmpi(trainParams.trainingMethod, 'adagrad') for j = 1:iters learningRate = trainParams.initLearningRate; [cost, grad] = functionCostGrad(opttheta, model, params, curData); if params.updateWordVectors && params.updateWordVectorsRate > 1 % if word vectors should be updated based on a different rate % update other params sumSquares(otherParamsRange) = sumSquares(otherParamsRange) + ... grad(otherParamsRange).*grad(otherParamsRange); opttheta(otherParamsRange) = opttheta(otherParamsRange) - ... (learningRate * 1./sqrt(sumSquares(otherParamsRange)) .* grad(otherParamsRange)); % update word vectors sumSquares(wordVectorsRange) = sumSquares(wordVectorsRange) ... + grad(wordVectorsRange).*grad(wordVectorsRange); opttheta(wordVectorsRange) = opttheta(wordVectorsRange) - ... (learningRate/params.updateWordVectorsRate * 1./sqrt(sumSquares(wordVectorsRange)) .* grad(wordVectorsRange)); else % word vectors updated the same as other parameters sumSquares = sumSquares + grad.*grad; opttheta = opttheta - (learningRate * 1./sqrt(sumSquares) .* grad); end end else disp(['Error: unknown optimization method ' trainParams.trainingMethod]); disp('This version only supports adagrad optimization'); return; end % disp(['cost ' num2str(cost)]); end % end batch loop [totalCost, totalGrad] = functionCostGrad(opttheta, model, params, data); if ~trainParams.quiet disp(['total cost ' num2str(totalCost)]); end if totalCost < bestCost bestTheta = opttheta; bestCost = totalCost; bestGrad = totalGrad; end end % end epoch loop disp('training elapsed time:'); toc; if trainParams.backpocket opttheta = bestTheta; cost = bestCost; grad = bestGrad; end disp(['final cost ' num2str(cost)]); % save parameters saveParamsFile = filenames.saveParamsFile; saveParameters(model, opttheta, params, saveParamsFile); % add extended dimensions disp(['opt params saved to ' saveParamsFile]); if params.updateWordVectors vocabSize = wordVectors.Count; updatedWordVectorsMat = reshape(opttheta(end-(params.inputSize*vocabSize)+1:end), params.inputSize, vocabSize); updatedWordVectorsWords = wordVectors.keys; saveUpdatedWordVectorsFile = filenames.saveUpdatedWordVectorsFile; save(saveUpdatedWordVectorsFile, 'updatedWordVectorsWords', 'updatedWordVectorsMat'); disp(['word vectors saved to ' saveUpdatedWordVectorsFile]); end if strcmpi(trainParams.trainingMethod, 'adagrad') saveSumSquaresFile = filenames.saveSumSquaresFile; save(saveSumSquaresFile, 'sumSquares'); disp(['last sum of squares (adagrad) saved to ' saveSumSquaresFile]); end end function indData = getDataSubind(data, model, ind, params) % ind - index for subset of the data (can be all data with permuted indices) indData.heads = data.heads(:,:,ind); indData.labels = data.labels(ind); indData.nheads = data.nheads(ind); indData.includeInd = data.includeInd(ind); if model == 6 indData.preps = data.preps(:,ind); indData.ppChildren = data.ppChildren(:,ind); if params.updateWordVectors indData.indPrepsToWordVectors = data.indPrepsToWordVectors(:,ind); indData.indHeadsToWordVectors = data.indHeadsToWordVectors(:,:,ind); indData.indChildrenToWordVectors = data.indChildrenToWordVectors(:,ind); indData.wordVectorsMat = data.wordVectorsMat; end else % TODO change? error('Error', ['unknown model ' num2str(model) ' in trainModel.m']); end end
github
phuselab/DANTE-master
MaximumLikelihoodEstimator.m
.m
DANTE-master/matlab/MaximumLikelihoodEstimator.m
404
utf_8
1eed500aaf9d695e0a4f7e77f7fe090a
% Finding an optimal estimate of the true emotion based on k evaluators and % N speech samples tham minimizes the mean square error result in the % Maximum Likelyhood Estimator (MLE) function MLE = MaximumLikelihoodEstimator(matriceDati) MLE = sum(transpose(matriceDati))/size(matriceDati, 2); end % Each of the evaluators is equally weighted and no a prior knowledge is % taken into account.
github
phuselab/DANTE-master
main.m
.m
DANTE-master/matlab/main.m
1,510
utf_8
e69eadd07e2c434b046ab959016af967
dati1 = dlmread('../annotation/1/vid1_ogg/arousal.csv',';',1,4); dati2 = dlmread('../annotation/2/vid1_ogg/arousal.csv',';',1,4); dati3 = dlmread('../annotation/3/vid1_ogg/arousal.csv',';',1,4); dati4 = dlmread('../annotation/6/vid1_ogg/arousal.csv',';',1,4); dati5 = dlmread('../annotation/8/vid1_ogg/arousal.csv',';',1,4); maxRow = max([size(dati1, 1) size(dati2, 1) size(dati3, 1) size(dati4, 1) size(dati5, 1)]); dati1 = aggiustaDati(dati1, maxRow); dati2 = aggiustaDati(dati2, maxRow); dati3 = aggiustaDati(dati3, maxRow); dati4 = aggiustaDati(dati4, maxRow); dati5 = aggiustaDati(dati5, maxRow); samplesMatrix = [dati1 dati2 dati3 dati4 dati5]; [row, K] = size(samplesMatrix); % K -> # Annotators MLE = MaximumLikelihoodEstimator(samplesMatrix); % To measure the agreement among the avaluators, the standard SD deviaton can % be caluclated. WV = WeightedVoting(samplesMatrix); % Speech files with high SD value show low inter-evaluator agreement % whereas low SD values show high inter-evaluator agreement. EWE = EvaluatorWeightedEstimator(samplesMatrix, transpose(MLE)); subplot(4,1,1) plot(samplesMatrix), axis([1 row -1 1]) title('dati') subplot(4,1,2) plot(MLE), axis([1 row -1 1]) title('Maximum Likelihood Estimator') subplot(4,1,3) plot(WV), axis([1 row -1 1]) title('Mean Standard Deviation') subplot(4,1,4) plot(EWE) axis([1 row -1 1]) title('Evaluator Weighted Esitmator') function [dati]=aggiustaDati(dati, max) for i=size(dati, 1):max-1 dati = [dati; 0]; end end
github
EvgeniDubov/FEAST-master
FCBF.m
.m
FEAST-master/matlab/FCBF.m
1,521
utf_8
3264683aaf05a2b37369f50d37fed22b
function [selectedFeatures] = FCBF(featureMatrix,classColumn,threshold) %function [selectedFeatures] = FCBF(featureMatrix,classColumn,threshold) % %Performs feature selection using the FCBF measure by Yu and Liu 2004. % %Instead of selecting a fixed number of features it provides a relevancy threshold and selects all %features which score above that and are not redundant % % The license is in the LICENSE file. numFeatures = size(featureMatrix,2); classScore = zeros(numFeatures,1); for i = 1:numFeatures classScore(i) = SU(featureMatrix(:,i),classColumn); end [classScore indexScore] = sort(classScore,1,'descend'); indexScore = indexScore(classScore > threshold); classScore = classScore(classScore > threshold); if ~isempty(indexScore) curPosition = 1; else curPosition = 0; end while curPosition <= length(indexScore) j = curPosition + 1; curFeature = indexScore(curPosition); while j <= length(indexScore) scoreij = SU(featureMatrix(:,curFeature),featureMatrix(:,indexScore(j))); if scoreij > classScore(j) indexScore(j) = []; classScore(j) = []; else j = j + 1; end end curPosition = curPosition + 1; end selectedFeatures = indexScore; end function [score] = SU(firstVector,secondVector) %function [score] = SU(firstVector,secondVector) % %calculates SU = 2 * (I(X;Y)/(H(X) + H(Y))) hX = h(firstVector); hY = h(secondVector); iXY = mi(firstVector,secondVector); score = (2 * iXY) / (hX + hY); end
github
kasimp93/Image-Classification-using-ML-and-Artificial-Neural-Networks-master
Train_ANN.m
.m
Image-Classification-using-ML-and-Artificial-Neural-Networks-master/Final_Code/Train_ANN.m
2,652
utf_8
ee25a75d73d259bacea0b897899c1697
%Author: Iman Abdalla, April 2017. function [cost_vec,Weights,predicted_train,output]=Train_ANN_is(lambda,iterations,Data,OutputNodes,W,S,Sh,L,alpha,bias,labels,S_vec) Der=ones(size(W)); counter=2; m=size(Data,1); input=zeros(L,S+1); output=zeros(size(Data,1),OutputNodes); for ind2=1:iterations waitbar(ind2/iterations)%max(max(Der))>accuracy max(max(Der)) delta=zeros(S+1,L-1); Delta=zeros(size(W)); cost=0; counter=counter+1; for n=1:size(Data,1) %---------------------Forward Propagation-------------------------- input(1,:)=[bias Data(n,:)]; for l=2:L if l==L output(n,:)=logsig(W(end-OutputNodes+1:end,1:Sh+1)*input(L-1,1:S_vec(L-1)+1)')'; else input(l,1:S_vec(l)+1)=[bias logsig(W(sum(S_vec(2:l-1))+1:sum(S_vec(2:l)),1:S_vec(l-1)+1)*input(l-1,1:S_vec(l-1)+1)')']; end end %-------------------------Compute cost function-------------------- cost=cost-sum(log(output(n,:)).*labels(n,:)+log(1-output(n,:)).*(1-labels(n,:)))/m; %------------------------Back Propagation-------------------------- %delta for the last layer L deltaL= output(n,:)'-labels(n,:)'; Delta(end-OutputNodes+1:end,1:Sh+1)= Delta(end-OutputNodes+1:end,1:Sh+1)+(deltaL*input(L-1,1:S_vec(L-1)+1)); for back=L-1:-1:2 g=input(back,1:S_vec(back)+1).*(1-input(back,1:S_vec(back)+1)); if back==L-1 delta(1:S_vec(back)+1,back)=(W(end-OutputNodes+1:end,1:Sh+1)'*deltaL).*g'; else delta(1:S_vec(back)+1,back)=(W(sum(S_vec(2:back))+1:sum(S_vec(2:back+1)),1:S_vec(back+1)+1)'*delta(2:S_vec(back+1)+1,back+1)).*g'; end Delta(sum(S_vec(2:back-1))+1:sum(S_vec(2:back)),1:S_vec(back-1)+1)=Delta(sum(S_vec(2:back-1))+1:sum(S_vec(2:back)),1:S_vec(back-1)+1)+delta(2:S_vec(back)+1,back)*input(back-1,1:S_vec(back-1)+1); end end %------------------------Compute Dervative----------------------------- Der=Delta/m; Der(:,2:end)=Der(:,2:end)+lambda/m*W(:,2:end); %add regularization term % [grad_approx]=gradient_check2(Data,bias,W,S,L,eps,OutputNodes,labels,lambda,Sh,S_vec) cost=cost+lambda/2/m*norm(W(:,2:end),'fro')^2 %before gradient descent step cost_vec(counter)=cost; %-----------------------------Gradient Descent----------------------------- W_old=W; W=W_old-alpha*Der; end Weights=W; if OutputNodes>2 [~, predicted_train]=max(output,[],2); else predicted_train=round(output); end %[a predicted_train]=max(output,[],2);
github
kasimp93/Image-Classification-using-ML-and-Artificial-Neural-Networks-master
Test_ANN.m
.m
Image-Classification-using-ML-and-Artificial-Neural-Networks-master/Final_Code/Test_ANN.m
875
utf_8
3786fe2f638ae1cb2a172cd522ce10b1
%Author: Iman Abdalla, April 2017. function [Predictions,output]=Test_ANN(TestData,OutputNodes,W,S,L,bias,S_vec,Sh) input=zeros(L,S+1); output=zeros(size(TestData,1),OutputNodes); for n=1:size(TestData,1) % for n=1:10 %---------------------Forward Propagation-------------------------- %---------------------Forward Propagation-------------------------- input(1,:)=[bias TestData(n,:)]; for l=2:L if l==L output(n,:)=logsig(W(end-OutputNodes+1:end,1:Sh+1)*input(L-1,1:S_vec(L-1)+1)')'; else input(l,1:S_vec(l)+1)=[bias logsig(W(sum(S_vec(2:l-1))+1:sum(S_vec(2:l)),1:S_vec(l-1)+1)*input(l-1,1:S_vec(l-1)+1)')']; end end end if OutputNodes>2 [~, Predictions]=max(output,[],2); else Predictions=round(output); end %[a Predictions]=max(output,[],2);
github
kasimp93/Image-Classification-using-ML-and-Artificial-Neural-Networks-master
comp_combined_15class.m
.m
Image-Classification-using-ML-and-Artificial-Neural-Networks-master/Final_Code/comp_combined_15class.m
1,058
utf_8
0046c2449ffe6a860bb5546e4a5accb7
% For a test image, get combined feature vector. function featurevec = comp_combined_15class(img) %% load means of 2 class data % load('X_cent.mat') % load('X_gist.mat'); % % %% standardize features (subtract mean and div by variance) % disp('standardizing test examples'); % meanXggist = mean(X_gist) % stdXgist = std(X_gist) % meanXcent = mean(X_cent) % stdXcent = std(X_cent) % for i = 1:size(X_gist2,1) % X_gist2(i,:) = (X_gist2(i,:) - meanXggist)./stdXgist; % X_cent2(i,:) = (X_cent2(i,:) - meanXcent)./stdXcent; % end load('stats_15class.mat') %% Get image stuff: - from open source code clear param param.orientationsPerScale = [8 8 8 8]; % number of orientations per scale (from HF to LF) param.numberBlocks = 4; param.fc_prefilt = 4; % Computing gist: disp('gist...') [gistfeatures, param] = LMgist(img, '', param); disp('centrist...') centristfeatures = centrist(img); gistfeatures = (gistfeatures - meanXggist)./stdXgist; centristfeatures = (centristfeatures - meanXcent)./stdXcent; featurevec = [gistfeatures,centristfeatures]; end
github
kasimp93/Image-Classification-using-ML-and-Artificial-Neural-Networks-master
comp_combined_2class.m
.m
Image-Classification-using-ML-and-Artificial-Neural-Networks-master/Final_Code/comp_combined_2class.m
1,068
utf_8
8e17e094772b8e50ddf394d7d24c1cfd
% For a test image, get combined feature vector. function featurevec = comp_combined_2class(img) %% load means of 2 class data % load('X_cent2.mat'); % load('X_gist2.mat'); % % %% standardize features (subtract mean and div by variance) % disp('standardizing test examples'); % meanXggist = mean(X_gist2); % stdXgist = std(X_gist2); % meanXcent = mean(X_cent2); % stdXcent = std(X_cent2); % for i = 1:size(X_gist2,1) % X_gist2(i,:) = (X_gist2(i,:) - meanXggist)./stdXgist; % X_cent2(i,:) = (X_cent2(i,:) - meanXcent)./stdXcent; % end load('stats_2class.mat') %% Get image stuff: - from OPEN SOURCE CODE clear param param.orientationsPerScale = [8 8 8 8]; % number of orientations per scale (from HF to LF) param.numberBlocks = 4; param.fc_prefilt = 4; % Computing gist: disp('gist...') [gistfeatures, param] = LMgist(img, '', param); disp('centrist...') centristfeatures = centrist(img); gistfeatures = (gistfeatures - meanXggist)./stdXgist; centristfeatures = (centristfeatures - meanXcent)./stdXcent; featurevec = [gistfeatures,centristfeatures]; end
github
kasimp93/Image-Classification-using-ML-and-Artificial-Neural-Networks-master
flatten.m
.m
Image-Classification-using-ML-and-Artificial-Neural-Networks-master/Final_Code/feature extraction/centrist/flatten.m
441
utf_8
2fbf5d34ed9644b3610e990b009d71e0
% Flatten a nested cell array, taken from % http://groups.google.com/group/comp.soft-sys.matlab/browse_thread/thread/83e6ad0772bf68b8 function flatCell = flatten(cellArray) flatCell{1} = []; %#ok<*AGROW> for i=1:numel(cellArray) if iscell(cellArray{i}) currentCell = flatten(cellArray{i}); [flatCell{end+1:end+length(currentCell)}] = deal(currentCell{:}); else flatCell{end+1} = cellArray{i}; end end flatCell(1) = []; end
github
kasimp93/Image-Classification-using-ML-and-Artificial-Neural-Networks-master
searchGUI.m
.m
Image-Classification-using-ML-and-Artificial-Neural-Networks-master/Final_Code/feature extraction/centrist/searchGUI.m
3,547
utf_8
fa191382c94bd4fada86c548399b3381
function varargout = searchGUI(varargin) % SEARCHGUI MATLAB code for searchGUI.fig % SEARCHGUI, by itself, creates a new SEARCHGUI or raises the existing % singleton*. % % H = SEARCHGUI returns the handle to a new SEARCHGUI or the handle to % the existing singleton*. % % SEARCHGUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in SEARCHGUI.M with the given input arguments. % % SEARCHGUI('Property','Value',...) creates a new SEARCHGUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before searchGUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to searchGUI_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help searchGUI % Last Modified by GUIDE v2.5 24-Jun-2011 13:27:06 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @searchGUI_OpeningFcn, ... 'gui_OutputFcn', @searchGUI_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % suppress unused function and variable warnings %#ok<*DEFNU> %#ok<*INUSL> % --- Executes just before searchGUI is made visible. function searchGUI_OpeningFcn(hObject, eventdata, handles, varargin) % Choose default command line output for searchGUI handles.output = hObject; % Update handles structure guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = searchGUI_OutputFcn(hObject, eventdata, handles) varargout{1} = handles.output; % --- Executes on button press in findImagesButton. function findImagesButton_Callback(hObject, eventdata, handles) imagePath = getappdata(gcbf, 'imagePath'); directory = getappdata(gcbf, 'searchDir'); results = vertcat(imagePath, ... findSimilarImages(imread(imagePath), ... directory, ... 9)); scrollfig(results); % --- Executes on button press in loadImageButton. function loadImageButton_Callback(hObject, eventdata, handles) [fileName, filePath] = uigetfile({supportedImageFormats, 'Images'; ... '*', 'All files'}, ... 'Select an Image...'); if fileName ~= 0 imagePath = [filePath fileName]; setappdata(gcbf, 'imagePath', imagePath); imshow(imread(imagePath), 'Parent', handles.imageAxes); set(handles.findImagesButton, 'Enable', 'On'); end % --- Executes on button press in changeSearchDirButton. function changeSearchDirButton_Callback(hObject, eventdata, handles) searchDir = uigetdir(get(handles.searchDirPath, 'String')); if searchDir ~= 0 currentDir = pwd; shortPath = cell2mat(strrep({ searchDir }, [ currentDir '/'], '')); setappdata(gcbf, 'searchDir', searchDir); set(handles.searchDirPath, 'String', shortPath); end
github
kasimp93/Image-Classification-using-ML-and-Artificial-Neural-Networks-master
LMgist.m
.m
Image-Classification-using-ML-and-Artificial-Neural-Networks-master/Final_Code/feature extraction/gist/LMgist.m
8,240
utf_8
bfdf40d00f3439f3864ce453bfce69d6
function [gist, param] = LMgist(D, HOMEIMAGES, param, HOMEGIST) % % [gist, param] = LMgist(D, HOMEIMAGES, param); % [gist, param] = LMgist(filename, HOMEIMAGES, param); % [gist, param] = LMgist(filename, HOMEIMAGES, param, HOMEGIST); % % For a set of images: % gist = LMgist(img, [], param); % % When calling LMgist with a fourth argument it will store the gists in a % new folder structure mirroring the folder structure of the images. Then, % when called again, if the gist files already exist, it will just read % them without recomputing them: % % [gist, param] = LMgist(filename, HOMEIMAGES, param, HOMEGIST); % [gist, param] = LMgist(D, HOMEIMAGES, param, HOMEGIST); % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Modeling the shape of the scene: a holistic representation of the spatial envelope % Aude Oliva, Antonio Torralba % International Journal of Computer Vision, Vol. 42(3): 145-175, 2001. if nargin==4 precomputed = 1; % get list of folders and create non-existing ones %listoffolders = {D(:).annotation.folder}; %for i = 1:length(D); % f{i} = D(i).annotation.folder; %end %[categories,b,class] = unique(f); else precomputed = 0; HOMEGIST = ''; end % select type of input if isstruct(D) % [gist, param] = LMgist(D, HOMEIMAGES, param); Nscenes = length(D); typeD = 1; end if iscell(D) % [gist, param] = LMgist(filename, HOMEIMAGES, param); Nscenes = length(D); typeD = 2; end if isnumeric(D) % [gist, param] = LMgist(img, HOMEIMAGES, param); Nscenes = size(D,4); typeD = 3; if ~isfield(param, 'imageSize') param.imageSize = [size(D,1) size(D,2)]; end end param.boundaryExtension = 32; % number of pixels to pad if nargin<3 % Default parameters param.imageSize = 128; param.orientationsPerScale = [8 8 8 8]; param.numberBlocks = 4; param.fc_prefilt = 4; param.G = createGabor(param.orientationsPerScale, param.imageSize+2*param.boundaryExtension); else if ~isfield(param, 'G') param.G = createGabor(param.orientationsPerScale, param.imageSize+2*param.boundaryExtension); end end % Precompute filter transfert functions (only need to do this once, unless % image size is changes): Nfeatures = size(param.G,3)*param.numberBlocks^2; % Loop: Compute gist features for all scenes gist = zeros([Nscenes Nfeatures], 'single'); for n = 1:Nscenes g = []; todo = 1; % if gist has already been computed, just read the file if precomputed==1 filegist = fullfile(HOMEGIST, D(n).annotation.folder, [D(n).annotation.filename(1:end-4) '.mat']); if exist(filegist, 'file') load(filegist, 'g'); todo = 0; end end % otherwise compute gist if todo==1 if Nscenes>1 disp([n Nscenes]); end % load image try switch typeD case 1 img = LMimread(D, n, HOMEIMAGES); case 2 img = imread(fullfile(HOMEIMAGES, D{n})); case 3 img = D(:,:,:,n); end catch disp(D(n).annotation.folder) disp(D(n).annotation.filename) rethrow(lasterror) end % convert to gray scale img = single(mean(img,3)); % resize and crop image to make it square img = imresizecrop(img, param.imageSize, 'bilinear'); %img = imresize(img, param.imageSize, 'bilinear'); %jhhays % scale intensities to be in the range [0 255] img = img-min(img(:)); img = 255*img/max(img(:)); if Nscenes>1 imshow(uint8(img)) title(n) end % prefiltering: local contrast scaling output = prefilt(img, param.fc_prefilt); % get gist: g = gistGabor(output, param); % save gist if a HOMEGIST file is provided if precomputed mkdir(fullfile(HOMEGIST, D(n).annotation.folder)) save (filegist, 'g') end end gist(n,:) = g; drawnow end function output = prefilt(img, fc) % ima = prefilt(img, fc); % fc = 4 (default) % % Input images are double in the range [0, 255]; % You can also input a block of images [ncols nrows 3 Nimages] % % For color images, normalization is done by dividing by the local % luminance variance. if nargin == 1 fc = 4; % 4 cycles/image end w = 5; s1 = fc/sqrt(log(2)); % Pad images to reduce boundary artifacts img = log(img+1); img = padarray(img, [w w], 'symmetric'); [sn, sm, c, N] = size(img); n = max([sn sm]); n = n + mod(n,2); img = padarray(img, [n-sn n-sm], 'symmetric','post'); % Filter [fx, fy] = meshgrid(-n/2:n/2-1); gf = fftshift(exp(-(fx.^2+fy.^2)/(s1^2))); gf = repmat(gf, [1 1 c N]); % Whitening output = img - real(ifft2(fft2(img).*gf)); clear img % Local contrast normalization localstd = repmat(sqrt(abs(ifft2(fft2(mean(output,3).^2).*gf(:,:,1,:)))), [1 1 c 1]); output = output./(.2+localstd); % Crop output to have same size than the input output = output(w+1:sn-w, w+1:sm-w,:,:); function g = gistGabor(img, param) % % Input: % img = input image (it can be a block: [nrows, ncols, c, Nimages]) % param.w = number of windows (w*w) % param.G = precomputed transfer functions % % Output: % g: are the global features = [Nfeatures Nimages], % Nfeatures = w*w*Nfilters*c img = single(img); w = param.numberBlocks; G = param.G; be = param.boundaryExtension; if ndims(img)==2 c = 1; N = 1; [nrows ncols c] = size(img); end if ndims(img)==3 [nrows ncols c] = size(img); N = c; end if ndims(img)==4 [nrows ncols c N] = size(img); img = reshape(img, [nrows ncols c*N]); N = c*N; end [ny nx Nfilters] = size(G); W = w*w; g = zeros([W*Nfilters N]); % pad image img = padarray(img, [be be], 'symmetric'); img = single(fft2(img)); k=0; for n = 1:Nfilters ig = abs(ifft2(img.*repmat(G(:,:,n), [1 1 N]))); ig = ig(be+1:ny-be, be+1:nx-be, :); v = downN(ig, w); g(k+1:k+W,:) = reshape(v, [W N]); k = k + W; drawnow end if c == 3 % If the input was a color image, then reshape 'g' so that one column % is one images output: g = reshape(g, [size(g,1)*3 size(g,2)/3]); end function y=downN(x, N) % % averaging over non-overlapping square image blocks % % Input % x = [nrows ncols nchanels] % Output % y = [N N nchanels] nx = fix(linspace(0,size(x,1),N+1)); ny = fix(linspace(0,size(x,2),N+1)); y = zeros(N, N, size(x,3)); for xx=1:N for yy=1:N v=mean(mean(x(nx(xx)+1:nx(xx+1), ny(yy)+1:ny(yy+1),:),1),2); y(xx,yy,:)=v(:); end end function G = createGabor(or, n) % % G = createGabor(numberOfOrientationsPerScale, n); % % Precomputes filter transfer functions. All computations are done on the % Fourier domain. % % If you call this function without output arguments it will show the % tiling of the Fourier domain. % % Input % numberOfOrientationsPerScale = vector that contains the number of % orientations at each scale (from HF to BF) % n = imagesize = [nrows ncols] % % output % G = transfer functions for a jet of gabor filters Nscales = length(or); Nfilters = sum(or); if length(n) == 1 n = [n(1) n(1)]; end l=0; for i=1:Nscales for j=1:or(i) l=l+1; param(l,:)=[.35 .3/(1.85^(i-1)) 16*or(i)^2/32^2 pi/(or(i))*(j-1)]; end end % Frequencies: %[fx, fy] = meshgrid(-n/2:n/2-1); [fx, fy] = meshgrid(-n(2)/2:n(2)/2-1, -n(1)/2:n(1)/2-1); fr = fftshift(sqrt(fx.^2+fy.^2)); t = fftshift(angle(fx+sqrt(-1)*fy)); % Transfer functions: G=zeros([n(1) n(2) Nfilters]); for i=1:Nfilters tr=t+param(i,4); tr=tr+2*pi*(tr<-pi)-2*pi*(tr>pi); G(:,:,i)=exp(-10*param(i,1)*(fr/n(2)/param(i,2)-1).^2-2*param(i,3)*pi*tr.^2); end if nargout == 0 figure for i=1:Nfilters contour(fx, fy, fftshift(G(:,:,i)),[1 .7 .6],'r'); hold on end axis('on') axis('equal') axis([-n(2)/2 n(2)/2 -n(1)/2 n(1)/2]) axis('ij') xlabel('f_x (cycles per image)') ylabel('f_y (cycles per image)') grid on end
github
kasimp93/Image-Classification-using-ML-and-Artificial-Neural-Networks-master
showGist.m
.m
Image-Classification-using-ML-and-Artificial-Neural-Networks-master/Final_Code/feature extraction/gist/showGist.m
1,954
utf_8
926839f0ab3e7182c10a1b52d06e5e31
function showGist(gist, param) % % Visualization of the gist descriptor % showGist(gist, param) % % The plot is color coded, with one color per scale % % Example: % img = zeros(256,256); % img(64:128,64:128) = 255; % gist = LMgist(img, '', param); % showGist(gist, param) [Nimages, Ndim] = size(gist); nx = ceil(sqrt(Nimages)); ny = ceil(Nimages/nx); Nblocks = param.numberBlocks; Nfilters = sum(param.orientationsPerScale); Nscales = length(param.orientationsPerScale); C = hsv(Nscales); colors = []; for s = 1:Nscales colors = [colors; repmat(C(s,:), [param.orientationsPerScale(s) 1])]; end colors = colors'; [nrows ncols Nfilters] = size(param.G); Nfeatures = Nblocks^2*Nfilters; if Ndim~=Nfeatures error('Missmatch between gist descriptors and the parameters'); end G = param.G(1:2:end,1:2:end,:); [nrows ncols Nfilters] = size(G); G = G + flipdim(flipdim(G,1),2); G = reshape(G, [ncols*nrows Nfilters]); if Nimages>1 figure; end for j = 1:Nimages g = reshape(gist(j,:), [Nblocks Nblocks Nfilters]); g = permute(g,[2 1 3]); g = reshape(g, [Nblocks*Nblocks Nfilters]); for c = 1:3 mosaic(:,c,:) = G*(repmat(colors(c,:), [Nblocks^2 1]).*g)'; end mosaic = reshape(mosaic, [nrows ncols 3 Nblocks*Nblocks]); mosaic = fftshift(fftshift(mosaic,1),2); mosaic = uint8(mosaic/max(mosaic(:))*255); mosaic(1,:,:,:) = 255; mosaic(end,:,:,:) = 255; mosaic(:,1,:,:) = 255; mosaic(:,end,:,:) = 255; if Nimages>1 subplottight(ny,nx,j,0.01); end montage(mosaic, 'size', [Nblocks Nblocks]) end function h=subplottight(Ny, Nx, j, margin) % General utility function % % This function is like subplot but it removes the spacing between axes. % % subplottight(Ny, Nx, j) if nargin <4 margin = 0; end j = j-1; x = mod(j,Nx)/Nx; y = (Ny-fix(j/Nx)-1)/Ny; h=axes('position', [x+margin/Nx y+margin/Ny 1/Nx-2*margin/Nx 1/Ny-2*margin/Ny]);
github
GatorSense/MICI-master
evalFitness_softmax.m
.m
MICI-master/util/evalFitness_softmax.m
1,879
utf_8
6dd18d55aa4d0dbfa74fdaa03e96c2c2
function [fitness] = evalFitness_softmax(Labels, measure, nPntsBags, oneV, bag_row_ids, diffM,p) % Evaluate the fitness a measure, similar to evalFitness_minmax() for % classification but uses generalized mean (sometimes also named "softmax") model % % INPUT % Labels - 1xNumTrainBags double - Training labels for each bag % measure - measure to be evaluated after update % nPntsBags - 1xNumTrainBags double - number of points in each bag % bag_row_ids - the row indices of measure used for each bag % diffM - Precompute differences for each bag % % OUTPUT % fitness - the fitness value using min(sum(min((ci-d)^2))) for regression. % % Written by: X. Du 03/2018 % p1 = p(1); p2 = p(2); singletonLoc = (nPntsBags == 1); diffM_ns = diffM(~singletonLoc); bag_row_ids_ns = bag_row_ids(~singletonLoc); labels_ns = Labels(~singletonLoc); oneV = oneV(~singletonLoc); fitness = 0; if sum(singletonLoc) %if there are singleton bags diffM_s = vertcat(diffM{singletonLoc}); bag_row_ids_s = vertcat(bag_row_ids{singletonLoc}); labels_s = Labels(singletonLoc)'; %Compute CI for singleton bags ci = sum(diffM_s.*horzcat(measure(bag_row_ids_s),ones(sum(singletonLoc),1)),2); fitness_s = sum((ci - labels_s).^2); fitness = fitness - fitness_s; end %Compute CI for non-singleton bags for i = 1:length(diffM_ns) ci = sum(diffM_ns{i}.*horzcat(measure(bag_row_ids_ns{i}), oneV{i}),2); if(labels_ns(i) ~= 1) %negative bag label=0 fitness = fitness - (mean(ci.^(2*p1))).^(1/p1); else fitness = fitness - (mean((ci-1).^(2*p2))).^(1/p2); end end % sanity check if isinf(fitness) || ~isreal(fitness) fitness = real(fitness); if fitness == Inf fitness = -10000000; elseif fitness == -Inf fitness = -10000000; end end end
github
GatorSense/MICI-master
invcdf_TruncatedGaussian.m
.m
MICI-master/util/invcdf_TruncatedGaussian.m
1,199
utf_8
50a5c7959b4606c1f3d6d03e9a8d0f47
function [val] = invcdf_TruncatedGaussian(cdf,x_bar,sigma_bar,lowerBound,upperBound) %stats_TruncatedGaussian - stats for a truncated gaussian distribution % INPUT % - cdf: evaluated at the values at cdf % - x_bar,sigma_bar,lowerBound,upperBound: suppose X~N(mu,sigma^2) has a normal distribution and lies within % the interval lowerBound<X<upperBound % *The size of cdfTG and pdfTG is the common size of X, MU and SIGMA. A scalar input % functions as a constant matrix of the same size as the other inputs. % OUTPUT % - val: the x corresponding to the cdf TG value % Written by: X. Du 05/20/2015 term2 = (normcdf_my(upperBound,x_bar,sigma_bar) - normcdf_my(lowerBound,x_bar,sigma_bar)); const2 = cdf*term2 + normcdf_my(lowerBound,x_bar,sigma_bar); const3 = const2*2-1; inner_temp = erfinv(const3); val = inner_temp*sqrt(2)*sigma_bar + x_bar; end function [p] = normcdf_my(x,mu,sigma) % INOPUT % - x: the x to compute the cdf value % - mu: mean of the Gaussian distribution % - sigma: sigma of the Gaussian distribution % OUTPUT % - val: the x corresponding to the cdf value % based on MATLAB normcdf() function. z = (x-mu) ./ sigma; p = 0.5 * erfc(-z ./ sqrt(2)); end
github
GatorSense/MICI-master
evalInterval.m
.m
MICI-master/util/evalInterval.m
1,164
utf_8
036195d98abaadc9bc9fb2a9cec22289
function [subsetInterval] = evalInterval(measure,nSources,lowerindex,upperindex) % Evaluate the valid interval width of a measure, then sort in descending order. % % INPUT % measure - measure to be evaluated after update % nSources - number of sources % lowerindex - the cell that stores all the corresponding subsets (lower index) of measure elements % upperindex - the cell that stores all the corresponding supersets (upper index) of measure elements % OUTPUT % subsetInterval - the valid interval widths for the measure elements,before sorting by value % % Written by: X. Du 03/2018 % Nmeasure = 2^nSources-1 ; %total length of measure lb = zeros(1,Nmeasure-1); ub = zeros(1,Nmeasure-1); for j = 1:nSources %singleton lb(j) = 0; %lower bound ub(j) = min(measure(upperindex{j})); %upper bound end for j = (nSources+1) : (Nmeasure-nSources-1) lb(j) = max(measure(lowerindex{j})); %lower bound ub(j) = min(measure(upperindex{j})); %upper bound end for j = (Nmeasure-nSources):(Nmeasure-1) %(nSources-1)- tuple lb(j) = max(measure(lowerindex{j})); %lower bound ub(j) = 1;%upper bound end subsetInterval = ub - lb; end
github
GatorSense/MICI-master
quadLearnChoquetMeasure_3Source.m
.m
MICI-master/util/quadLearnChoquetMeasure_3Source.m
5,070
utf_8
5f6e52334705601a119498e6bf458adb
function g = quadLearnChoquetMeasure_3Source(H, Y) % g = quadLearnChoquetMeasure(H, Y) % This code only works with 3 sources % % Purpose: Learn the fuzzy measures of a choquet integral for fusing sources % of information. Learning the measures is framed as the % following quadratic programming problem: % % % argmin { 0.5*g'Dg+gamma'*g } % g % % s.t. 0 <= g <=1 and A*g <= b --> A*g - b <= 0 % % Input: H = [n_samp x n_sources] Matrix: Support info. [0 1]. % Each row of H (denoted h) is the confidence from each source % of the sample belonging to class 1. % Y = [n_samp x 1] Row Vector: Binary desired output (1 = class 1, 0 = class 0.) % % Output: g - [2^n_sources - 2 x 1] Row vector: Learned fuzzy measures. % %% % Extract Dimensions of the data. [n_samp, n_sources] = size(H); % Currently only designed for 3 sources... if(n_sources ~=3) error('This code is only meant for the fusion of three inputs'); end %================== Compute Coefficients ================================== % Z = [n_samp x 2^n_sources - 2] Matrix: Stores the change in % values from different sources - h(x_i*) - h(x_i+1*) % Each row (z) is a measure of the difference between each source % for each sample. gamma(j) in the text. Z = zeros(n_samp, 6); for j = 1:n_samp hx = H(j,:); % Pull a single sample's support info hx = [h{x1} h{x2} h{x3}] [h_xsorted, sort_inds] = sort(hx, 'descend'); % Sort h(x_i) s.t. h(x_1*) > h(x_2*> ... Z(j,sort_inds(1)) = h_xsorted(1) - h_xsorted(2); % Store h(x1*) - h(x2*) g2 = GElement2(sort_inds); % Figure out which set combination corresponds to h(x2*) Z(j,g2) = h_xsorted(2) - h_xsorted(3); % Store h(x2*) - h(x3*) end % D = [2^n_sources - 2 x 2^n_source - 2] Matrix: 2 * sum over all samples of z'*z, 2 is for scaling purposes. D = zeros(6,6); for j = 1:n_samp D = D + Z(j,:)'*Z(j,:); end D = D*2; % Compute Gamma over all samples. G = zeros(6, 1); for j = 1:n_samp G = G + 2*(min(H(j,:))-Y(j))*Z(j,:)'; % Gamma = [2^n_sources-2 x 1] column vector: sum(2*(h(x_1*) - y)*z) over all samples. end %============ Setup Costraint Matrix ====================================== % Contraints follow the form: % % A*g <= b % % Monotinicity Constraint on g: % g{xi} <= g{xi, xj} for any j, following from choquet set constraints. % % Compact binary representation of the following constraint. % Assume: g = [g{x1} g{x2] g{x3] g{x1,x2} g{x1,x3} g{x2,x3}] % % g{x1} - g{x1,x2} <= 0 --> g{x1} <= g{x1,x2} % g{x1} - g{x1,x3} <= 0 --> g{x1} <= g{x1,x3} % g{x2} - g{x1,x2} <= 0 --> g{x2} <= g{x1,x2} % g{x2} - g{x2,x3} <= 0 --> g{x2} <= g{x2,x3} % g{x3} - g{x1,x3} <= 0 --> g{x3} <= g{x1,x3} % g{x3} - g{x2,x3} <= 0 --> g{x3} <= g{x2,x3} % 0 + g{x1,x2} <= 1 --> g{x1,x2} <= 1 % 0 + g{x1,x3} <= 1 --> g{x1,x3} <= 1 % 0 + g{x2,x3} <= 1 --> g{x2,x3} <= 1 % Set A: % Singletons | Combinations % g{x1}+g{x2]+g{x3]+g{x1,x2}+g{x1,x3}+g{x2,x3} A = [1 0 0 -1 0 0; % g{x1} - g{x1,x2} 1 0 0 0 -1 0; % g{x1} - g{x1,x3} 0 1 0 -1 0 0; % g{x2} - g{x1,x2} 0 1 0 0 0 -1; % g{x2} - g{x2,x3} 0 0 1 0 -1 0; % g{x3} - g{x1,x3} 0 0 1 0 0 -1; % g{x3} - g{x2,x3} 0 0 0 1 0 0; % 0 + g{x1,x2} 0 0 0 0 1 0; % 0 + g{x1,x3} 0 0 0 0 0 1]; % 0 + g{x2,x3} % Set b: Refer to comments above. b = [0 0 0 0 0 0 1 1 1]'; % Use matlab built-in function for solving the quadratic problem. %options = optimset('Algorithm', 'active-set'); g = quadprog(D, G, A, b, [], [], zeros(2^n_sources-2,1),ones(2^n_sources-2,1), []); %add upper and lower bounds of [0,1] - X. Du 01/13/2016 end % Determine g{x2*} which density to use as the second weight. Can be thought of as % picking the density which coresponds to the combination of sets which % gives the most worth. function element = GElement2(sort_inds) if(sort_inds(1) == 1) if(sort_inds(2) == 2) element = 4; % Use g{x1, x2} else element = 5; % Use g{x1, x3} end elseif(sort_inds(1) == 2) if(sort_inds(2) == 1) element = 4; % Use g{x1, x2} else element = 6; % Use g{x2, x3} end elseif(sort_inds(1) == 3) if(sort_inds(2) == 1) element = 5; % Use g{x1, x3} else element = 6; % Use g{x2, x3} end end end
github
GatorSense/MICI-master
quadLearnChoquetMeasure_5Source.m
.m
MICI-master/util/quadLearnChoquetMeasure_5Source.m
18,196
utf_8
f359c41388a5f67c036650506d60fd61
function g = quadLearnChoquetMeasure_5Source(H, Y) % g = quadLearnChoquetMeasure(H, Y) for 5 sources % % Purpose: Learn the fuzzy measures of a choquet integral for fusing sources % of information. Learning the measures is framed as the % following quadratic programming problem: % % % argmin { 0.5*g'Dg+gamma'*g } % g % % s.t. 0 <= g <=1 and A*g <= b --> A*g - b <= 0 % % Input: H = [n_samp x nSources] Matrix: Support info. [0 1]. % Each row of H (denoted h) is the confidence from each source % of the sample belonging to class 1. % Y = [n_samp x 1] Row Vector: Binary desired output (1 = class 1, 0 = class 0.) % % Output: g - [2^nSources - 2 x 1] Row vector: Learned fuzzy measures. % Written by: X. Du 01/13/2016 %% % Extract Dimensions of the data. [nSample, nSources] = size(H); % Currently only designed for 3 sources... if(nSources ~=5) error('This code is only meant for the fusion of five inputs'); end %================== Compute Coefficients ================================== % Z = [nSample x 2^nSources - 2] Matrix: Stores the change in % values from different sources - h(x_i*) - h(x_i+1*) % Each row (z) is a measure of the difference between each source % for each sample. gamma(j) in the text. Z = zeros(nSample, 2^nSources - 2); for j = 1:nSample hx = H(j,:); % Pull a single sample's support info hx = [h{x1} h{x2} h{x3}] [h_xsorted, sort_inds] = sort(hx, 'descend'); % Sort h(x_i) s.t. h(x_1*) > h(x_2*> ... Z(j,sort_inds(1)) = h_xsorted(1) - h_xsorted(2); % Store h(x1*) - h(x2*) g2 = GElement2(sort_inds); % Figure out which set combination corresponds to h(x2*) Z(j,g2) = h_xsorted(2) - h_xsorted(3); % Store h(x2*) - h(x3*) g3 = GElement3(sort_inds); Z(j,g3) = h_xsorted(3) - h_xsorted(4); g4 = GElement4(sort_inds); Z(j,g4) = h_xsorted(4) - h_xsorted(5); end % D = [2^nSources - 2 x 2^n_source - 2] Matrix: 2 * sum over all samples of z'*z, 2 is for scaling purposes. D = zeros(2^nSources-2 ,2^nSources-2 ); for j = 1:nSample D = D + Z(j,:)'*Z(j,:); end D = D*2; % Compute Gamma over all samples. Gamma = zeros(2^nSources-2, 1); for j = 1:nSample Gamma = Gamma + 2*(min(H(j,:))-Y(j))*Z(j,:)'; % Gamma = [2^nSources-2 x 1] column vector: sum(2*(h(x_1*) - y)*z) over all samples. end %============ Setup Costraint Matrix ====================================== % Contraints follow the form: % % A*g <= b % % Monotinicity Constraint on g: % g{xi} <= g{xi, xj} for any j, following from choquet set constraints. % % Compact binary representation of the constraint. % A total of nSources*(2^(nSources-1)-1) constraints (ref: J.M.Keller book chapter) % Set A: A = zeros(nSources*(2^(nSources-1)-1), 2^nSources-2); numConstraints = size(A,1); numMeasureElems = size(A,2); %number of measure elements with constraints (excluding empty 0 and all 1 sets) %%%% last nSources rows, g_12..(n-1)<=1 constraints%%%%%%% count = 0; for i = (numConstraints-nSources+1) : numConstraints count = count+1; A(i,numMeasureElems-nSources+count) = 1; end %%%%# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ... A = [ 1 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_1<=g_12 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_1<=g_13 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_1<=g_14 1 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_1<=g_15 0 1 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_2<=g_12 0 1 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_2<=g_23 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_2<=g_24 0 1 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_2<=g_25 0 0 1 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_3<=g_13 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_3<=g_23 0 0 1 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_3<=g_34 0 0 1 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_3<=g_35 0 0 0 1 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_4<=g_14 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_4<=g_24 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_4<=g_34 0 0 0 1 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_4<=g_45 0 0 0 0 1 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_5<=g_15 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_5<=g_25 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_5<=g_35 0 0 0 0 1 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_5<=g_45 %%%%# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ... 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_12<=g_123 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_12<=g_124 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0; %g_12<=g_125 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_13<=g_123 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0; %g_13<=g_134 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0; %g_13<=g_135 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_14<=g_124 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0; %g_14<=g_134 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0; %g_14<=g_145 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0; %g_15<=g_125 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0; %g_15<=g_135 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0; %g_15<=g_145 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_23<=g_123 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0; %g_23<=g_234 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0; %g_23<=g_235 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0; %g_24<=g_124 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0; %g_24<=g_234 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0; %g_24<=g_245 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0; %g_25<=g_125 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0; %g_25<=g_235 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0; %g_25<=g_245 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0; %g_34<=g_134 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 0; %g_34<=g_234 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0; %g_34<=g_345 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0; %g_35<=g_135 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0 0; %g_35<=g_235 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0; %g_35<=g_345 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 0 0; %g_45<=g_145 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0 0 0; %g_45<=g_245 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 -1 0 0 0 0 0; %g_45<=g_345 %%%%# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ... 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 -1 0 0 0 0; %g_123<=g_1234 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 -1 0 0 0; %g_123<=g_1235 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0 0; %g_124<=g_1234 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 -1 0 0; %g_124<=g_1245 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0 0 0; %g_125<=g_1235 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 -1 0 0; %g_125<=g_1245 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0 0; %g_134<=g_1234 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 -1 0; %g_134<=g_1345 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 0; %g_135<=g_1235 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 -1 0; %g_135<=g_1345 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 0; %g_145<=g_1245 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 -1 0; %g_145<=g_1345 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 -1 0 0 0 0; %g_234<=g_1234 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 -1; %g_234<=g_2345 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 -1 0 0 0; %g_235<=g_1235 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 -1; %g_235<=g_2345 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 -1 0 0; %g_245<=g_1245 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 -1; %g_245<=g_2345 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 -1 0; %g_345<=g_1345 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 -1; %g_345<=g_2345 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0; %g_1234<=1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0; %g_1235<=1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0; %g_1245<=1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; %g_1345<=1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1; %g_2345<=1 ]; % Set b: Refer to comments above. b = zeros(nSources*(2^(nSources-1)-1),1); b([end-nSources+1:end]) = 1; % the last tier constraints <=1 % Use matlab built-in function for solving the quadratic problem. % options = optimset('Algorithm', 'active-set'); g = quadprog(D, Gamma, A, b, [], [], zeros(2^nSources-2,1),ones(2^nSources-2,1), []); % options = optimset('Algorithm', 'interior-point-convex'); % options = optimset('Algorithm', 'trust-region-reflective'); % g = quadprog(D, Gamma, A, b, [], [], [], [], []); end % Determine g{x2*} which density to use as the second weight. Can be thought of as % picking the density which coresponds to the combination of sets which % gives the most worth. function element = GElement2(sort_inds) if ismember(sort_inds([1:2]),perms([1 2]),'rows') == 1 element = 6; % Use g{x1, x2} end if ismember(sort_inds([1:2]),perms([1 3]),'rows') == 1 element = 7; % Use g{x1, x3} end if ismember(sort_inds([1:2]),perms([1 4]),'rows') == 1 element = 8; % Use g{x1, x4} end if ismember(sort_inds([1:2]),perms([1 5]),'rows') == 1 element = 9; % Use g{x1, x5} end if ismember(sort_inds([1:2]),perms([2 3]),'rows') == 1 element = 10; % Use g{x2, x3} end if ismember(sort_inds([1:2]),perms([2 4]),'rows') == 1 element = 11; % Use g{x2, x4} end if ismember(sort_inds([1:2]),perms([2 5]),'rows') == 1 element = 12; % Use g{x2, x5} end if ismember(sort_inds([1:2]),perms([3 4]),'rows') == 1 element = 13; % Use g{x3, x4} end if ismember(sort_inds([1:2]),perms([3 5]),'rows') == 1 element = 14; % Use g{x3, x5} end if ismember(sort_inds([1:2]),perms([4 5]),'rows') == 1 element = 15; % Use g{x4, x5} end end % Determine g{x2*} which density to use as the second weight. Can be thought of as % picking the density which coresponds to the combination of sets which % gives the most worth. function element = GElement3(sort_inds) if ismember(sort_inds([1:3]),perms([1 2 3]),'rows') == 1 element = 16; % Use g{x1, x2, x3} end if ismember(sort_inds([1:3]),perms([1 2 4]),'rows') == 1 element = 17; % Use g{x1, x2, x4} end if ismember(sort_inds([1:3]),perms([1 2 5]),'rows') == 1 element = 18; % Use g{x1, x2, x5} end if ismember(sort_inds([1:3]),perms([1 3 4]),'rows') == 1 element = 19; % Use g{x1, x3, x4} end if ismember(sort_inds([1:3]),perms([1 3 5]),'rows') == 1 element = 20; % Use g{x1, x3, x5} end if ismember(sort_inds([1:3]),perms([1 4 5]),'rows') == 1 element = 21; % Use g{x1, x4, x5} end if ismember(sort_inds([1:3]),perms([2 3 4]),'rows') == 1 element = 22; % Use g{x2, x3, x4} end if ismember(sort_inds([1:3]),perms([2 3 5]),'rows') == 1 element = 23; % Use g{x2, x3, x5} end if ismember(sort_inds([1:3]),perms([2 4 5]),'rows') == 1 element = 24; % Use g{x2, x4, x5} end if ismember(sort_inds([1:3]),perms([3 4 5]),'rows') == 1 element = 25; % Use g{x3, x4, x5} end end function element = GElement4(sort_inds) if ismember(sort_inds([1:4]),perms([1 2 3 4]),'rows') == 1 element = 26; % Use g{x1, x2, x3, x4} end if ismember(sort_inds([1:4]),perms([1 2 3 5]),'rows') == 1 element = 27; % Use g{x1, x2, x3, x5} end if ismember(sort_inds([1:4]),perms([1 2 4 5]),'rows') == 1 element = 28; % Use g{x1, x2, x4, x5} end if ismember(sort_inds([1:4]),perms([1 3 4 5]),'rows') == 1 element = 29; % Use g{x1, x3, x4, x5} end if ismember(sort_inds([1:4]),perms([2 3 4 5]),'rows') == 1 element = 30; % Use g{x2, x3, x4, x5} end end
github
GatorSense/MICI-master
quadLearnChoquetMeasure_4Source.m
.m
MICI-master/util/quadLearnChoquetMeasure_4Source.m
8,043
utf_8
e8c8141ac0b625ed7f9ec38f54b3186d
function g = quadLearnChoquetMeasure_4Source(H, Y) % g = quadLearnChoquetMeasure(H, Y) for 4 sources % % Purpose: Learn the fuzzy measures of a choquet integral for fusing sources % of information. Learning the measures is framed as the % following quadratic programming problem: % % % argmin { 0.5*g'Dg+gamma'*g } % g % % s.t. 0 <= g <=1 and A*g <= b --> A*g - b <= 0 % % Input: H = [n_samp x nSources] Matrix: Support info. [0 1]. % Each row of H (denoted h) is the confidence from each source % of the sample belonging to class 1. % Y = [n_samp x 1] Row Vector: Binary desired output (1 = class 1, 0 = class 0.) % % Output: g - [2^nSources - 2 x 1] Row vector: Learned fuzzy measures. % Written by: X. Du 01/13/2016 %% % Extract Dimensions of the data. [nSample, nSources] = size(H); % Currently only designed for 3 sources... if(nSources ~=4) error('This code is only meant for the fusion of four inputs'); end %================== Compute Coefficients ================================== % Z = [nSample x 2^nSources - 2] Matrix: Stores the change in % values from different sources - h(x_i*) - h(x_i+1*) % Each row (z) is a measure of the difference between each source % for each sample. gamma(j) in the text. Z = zeros(nSample, 2^nSources - 2); for j = 1:nSample hx = H(j,:); % Pull a single sample's support info hx = [h{x1} h{x2} h{x3}] [h_xsorted, sort_inds] = sort(hx, 'descend'); % Sort h(x_i) s.t. h(x_1*) > h(x_2*> ... Z(j,sort_inds(1)) = h_xsorted(1) - h_xsorted(2); % Store h(x1*) - h(x2*) g2 = GElement2(sort_inds); % Figure out which set combination corresponds to h(x2*) Z(j,g2) = h_xsorted(2) - h_xsorted(3); % Store h(x2*) - h(x3*) g3 = GElement3(sort_inds); Z(j,g3) = h_xsorted(3) - h_xsorted(4); end % D = [2^nSources - 2 x 2^n_source - 2] Matrix: 2 * sum over all samples of z'*z, 2 is for scaling purposes. D = zeros(2^nSources-2 ,2^nSources-2 ); for j = 1:nSample D = D + Z(j,:)'*Z(j,:); end D = D*2; % Compute Gamma over all samples. Gamma = zeros(2^nSources-2, 1); for j = 1:nSample Gamma = Gamma + 2*(min(H(j,:))-Y(j))*Z(j,:)'; % Gamma = [2^nSources-2 x 1] column vector: sum(2*(h(x_1*) - y)*z) over all samples. end %============ Setup Costraint Matrix ====================================== % Contraints follow the form: % % A*g <= b % % Monotinicity Constraint on g: % g{xi} <= g{xi, xj} for any j, following from choquet set constraints. % % Compact binary representation of the constraint. % A total of nSources*(2^(nSources-1)-1) constraints (ref: J.M.Keller book chapter) % Set A: A = zeros(nSources*(2^(nSources-1)-1), 2^nSources-2); numConstraints = size(A,1); numMeasureElems = size(A,2); %number of measure elements with constraints (excluding empty 0 and all 1 sets) %%%% last nSources rows, g_12..(n-1)<=1 constraints%%%%%%% count = 0; for i = (numConstraints-nSources+1) : numConstraints count = count+1; A(i,numMeasureElems-nSources+count) = 1; end %%%%# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ... A = [ 1 0 0 0 -1 0 0 0 0 0 0 0 0 0; %g_1<=g_12 1 0 0 0 0 -1 0 0 0 0 0 0 0 0 ; %g_1<=g_13 1 0 0 0 0 0 -1 0 0 0 0 0 0 0 ; %g_1<=g_14 0 1 0 0 -1 0 0 0 0 0 0 0 0 0 ; %g_2<=g_12 0 1 0 0 0 0 0 -1 0 0 0 0 0 0 ; %g_2<=g_23 0 1 0 0 0 0 0 0 -1 0 0 0 0 0 ; %g_2<=g_24 0 0 1 0 0 -1 0 0 0 0 0 0 0 0 ; %g_3<=g_13 0 0 1 0 0 0 0 -1 0 0 0 0 0 0 ; %g_3<=g_23 0 0 1 0 0 0 0 0 0 -1 0 0 0 0 ; %g_3<=g_34 0 0 0 1 0 0 -1 0 0 0 0 0 0 0 ; %g_4<=g_14 0 0 0 1 0 0 0 0 -1 0 0 0 0 0 ; %g_4<=g_24 0 0 0 1 0 0 0 0 0 -1 0 0 0 0 ; %g_4<=g_34 0 0 0 0 1 0 0 0 0 0 -1 0 0 0 ; %g_12<=g_123 0 0 0 0 1 0 0 0 0 0 0 -1 0 0 ; %g_12<=g_124 0 0 0 0 0 1 0 0 0 0 -1 0 0 0 ; %g_13<=g_123 0 0 0 0 0 1 0 0 0 0 0 0 -1 0 ; %g_13<=g_134 0 0 0 0 0 0 1 0 0 0 0 -1 0 0 ; %g_14<=g_124 0 0 0 0 0 0 1 0 0 0 0 0 -1 0 ; %g_14<=g_134 0 0 0 0 0 0 0 1 0 0 -1 0 0 0 ; %g_23<=g_123 0 0 0 0 0 0 0 1 0 0 0 0 0 -1 ; %g_23<=g_234 0 0 0 0 0 0 0 0 1 0 0 -1 0 0 ; %g_24<=g_124 0 0 0 0 0 0 0 0 1 0 0 0 0 -1 ; %g_24<=g_234 0 0 0 0 0 0 0 0 0 1 0 0 -1 0 ; %g_34<=g_134 0 0 0 0 0 0 0 0 0 1 0 0 0 -1 ; %g_34<=g_234 0 0 0 0 0 0 0 0 0 0 1 0 0 0 ; %g_123<=1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 ; %g_124<=1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 ; %g_134<=1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ; %g_234<=1 ]; % Set b: Refer to comments above. b = zeros(nSources*(2^(nSources-1)-1),1); b([end-nSources+1:end]) = 1; % the last tier constraints <=1 % Use matlab built-in function for solving the quadratic problem. % options = optimset('Algorithm', 'active-set'); g = quadprog(D, Gamma, A, b, [], [], zeros(2^nSources-2,1),ones(2^nSources-2,1), []); % options = optimset('Algorithm', 'interior-point-convex'); % options = optimset('Algorithm', 'trust-region-reflective'); % g = quadprog(D, Gamma, A, b, [], [], [], [], []); end % Determine g{x2*} which density to use as the second weight. Can be thought of as % picking the density which coresponds to the combination of sets which % gives the most worth. function element = GElement2(sort_inds) if(sort_inds(1) == 1) if(sort_inds(2) == 2) element = 5; % Use g{x1, x2} elseif(sort_inds(2) == 3) element = 6; % Use g{x1, x3} elseif(sort_inds(2) == 4) element = 7; % Use g{x1, x4} end elseif(sort_inds(1) == 2) if(sort_inds(2) == 1) element = 5; % Use g{x1, x2} elseif(sort_inds(2) == 3) element = 8; % Use g{x2, x3} elseif(sort_inds(2) == 4) element = 9; % Use g{x2, x4} end elseif(sort_inds(1) == 3) if(sort_inds(2) == 1) element = 6; % Use g{x1, x3} elseif(sort_inds(2) == 2) element = 8; % Use g{x2, x3} elseif(sort_inds(2) == 4) element = 10; % Use g{x3, x4} end elseif(sort_inds(1) == 4) if(sort_inds(2) == 1) element = 7; % Use g{x1, x4} elseif(sort_inds(2) == 2) element = 9; % Use g{x2, x4} elseif(sort_inds(2) == 3) element = 10; % Use g{x3, x4} end end end % Determine g{x2*} which density to use as the second weight. Can be thought of as % picking the density which coresponds to the combination of sets which % gives the most worth. function element = GElement3(sort_inds) if ismember(sort_inds([1:3]),perms([1 2 3]),'rows') == 1 element = 11; % Use g{x1, x2, x3} end if ismember(sort_inds([1:3]),perms([1 2 4]),'rows') == 1 element = 12; % Use g{x1, x2, x4} end if ismember(sort_inds([1:3]),perms([1 3 4]),'rows') == 1 element = 13; % Use g{x1, x3, x4} end if ismember(sort_inds([1:3]),perms([2 3 4]),'rows') == 1 element = 14; % Use g{x2, x3, x4} end end
github
GatorSense/MICI-master
evalFitness_minmax.m
.m
MICI-master/util/evalFitness_minmax.m
1,791
utf_8
458a4f32ed7c7c5cd2103d2f52d35897
function [fitness] = evalFitness_minmax(Labels, measure, nPntsBags, oneV, bag_row_ids, diffM) % Evaluate the fitness a measure, using min( sum(max((ci-0)^2)) + sum(min(ci-1)^2) ) for classification. % min-max model % % INPUT % Labels - 1xNumTrainBags double - Training labels for each bag % measure - measure to be evaluated after update % nPntsBags - 1xNumTrainBags double - number of points in each bag % bag_row_ids - the row indices of measure used for each bag % diffM - Precompute differences for each bag % % OUTPUT % fitness - the fitness value using min(sum(min((ci-d)^2))) for regression. % % Written by: X. Du 03/2018 % singletonLoc = (nPntsBags == 1); diffM_ns = diffM(~singletonLoc); bag_row_ids_ns = bag_row_ids(~singletonLoc); labels_ns = Labels(~singletonLoc); oneV = oneV(~singletonLoc); fitness = 0; if sum(singletonLoc) %if there are singleton bags diffM_s = vertcat(diffM{singletonLoc}); bag_row_ids_s = vertcat(bag_row_ids{singletonLoc}); labels_s = Labels(singletonLoc)'; %Compute CI for singleton bags ci = sum(diffM_s.*horzcat(measure(bag_row_ids_s),ones(sum(singletonLoc),1)),2); fitness_s = sum((ci - labels_s).^2); fitness = fitness - fitness_s; end %Compute CI for non-singleton bags for i = 1:length(diffM_ns) ci = sum(diffM_ns{i}.*horzcat(measure(bag_row_ids_ns{i}), oneV{i}),2); if(labels_ns(i) ~= 1) %negative bag label=0 fitness = fitness - max(ci.^2); else fitness = fitness - min((ci-1).^2); end end % sanity check if isinf(fitness) || ~isreal(fitness) fitness = real(fitness); if fitness == Inf fitness = -10000000; elseif fitness == -Inf fitness = -10000000; end end end
github
GatorSense/MICI-master
evalFitness_reg.m
.m
MICI-master/util/evalFitness_reg.m
1,700
utf_8
1d2c493a725df54f1f82c58428fd5a6a
function [fitness] = evalFitness_reg(Labels, measure, nPntsBags, oneV, bag_row_ids, diffM) % Evaluate the fitness a measure, using min(sum(min((ci-d)^2))) for regression. % % INPUT % Labels - 1xNumTrainBags double - Training labels for each bag % measure - measure to be evaluated after update % nPntsBags - 1xNumTrainBags double - number of points in each bag % oneV - - marks where singletons are % bag_row_ids - the row indices of measure used for each bag % diffM - Precompute differences for each bag % % OUTPUT % fitness - the fitness value using min(sum(min((ci-d)^2))) for regression. % % Written by: X. Du 03/2018 % singletonLoc = (nPntsBags == 1); fitness = 0; if sum(singletonLoc) %if there are singleton bags diffM_s = vertcat(diffM{singletonLoc}); bag_row_ids_s = vertcat(bag_row_ids{singletonLoc}); labels_s = Labels(singletonLoc)'; %Compute CI for singleton bags ci = sum(diffM_s.*horzcat(measure(bag_row_ids_s),ones(sum(singletonLoc),1)),2); fitness_s = sum((ci - labels_s).^2); fitness = fitness - fitness_s; end diffM_ns = diffM(~singletonLoc); bag_row_ids_ns = bag_row_ids(~singletonLoc); labels_ns = Labels(~singletonLoc); oneV = oneV(~singletonLoc); %Compute CI for non-singleton bags for i = 1:length(diffM_ns) ci = sum(diffM_ns{i}.*horzcat(measure(bag_row_ids_ns{i}), oneV{i}),2); fitness = fitness - min((ci-labels_ns(i)).^2); end % sanity check if isinf(fitness) || ~isreal(fitness) fitness = real(fitness); if fitness == Inf fitness = -10000000; elseif fitness == -Inf fitness = -10000000; end end end
github
amoudgl/mosse-tracker-master
window2.m
.m
mosse-tracker-master/src/window2.m
1,476
utf_8
5d8ce11dc20f5afbafd1fb2bf2957add
% This function creates a 2 dimentional window for a sample image, it takes % the dimension of the window and applies the 1D window function % This is does NOT using a rotational symmetric method to generate a 2 window % % Disi A ---- May,16, 2013 % [N,M]=size(imgage); % --------------------------------------------------------------------- % w_type is defined by the following % @bartlett - Bartlett window. % @barthannwin - Modified Bartlett-Hanning window. % @blackman - Blackman window. % @blackmanharris - Minimum 4-term Blackman-Harris window. % @bohmanwin - Bohman window. % @chebwin - Chebyshev window. % @flattopwin - Flat Top window. % @gausswin - Gaussian window. % @hamming - Hamming window. % @hann - Hann window. % @kaiser - Kaiser window. % @nuttallwin - Nuttall defined minimum 4-term Blackman-Harris window. % @parzenwin - Parzen (de la Valle-Poussin) window. % @rectwin - Rectangular window. % @taylorwin - Taylor window. % @tukeywin - Tukey window. % @triang - Triangular window. % % Example: % To compute windowed 2D fFT % [r,c]=size(img); % w=window2(r,c,@hamming); % fft2(img.*w); function w=window2(N,M,w_func) wc=window(w_func,N); wr=window(w_func,M); [maskr,maskc]=meshgrid(wr,wc); %maskc=repmat(wc,1,M); Old version %maskr=repmat(wr',N,1); w=maskr.*maskc; end
github
Davonter/openairinterface5g-master
gen_7_5_kHz.m
.m
openairinterface5g-master/openair1/PHY/MODULATION/gen_7_5_kHz.m
3,298
utf_8
a08e730b234a112cbf6aac5b44c3af8b
function [] = gen_7_5_kHz() [s6_n2, s6_e2] = gen_sig(6); [s15_n2, s15_e2] = gen_sig(15); [s25_n2, s25_e2] = gen_sig(25); [s50_n2, s50_e2] = gen_sig(50); [s75_n2, s75_e2] = gen_sig(75); [s100_n2, s100_e2] = gen_sig(100); fd=fopen("kHz_7_5.h","w"); fprintf(fd,"s16 s6n_kHz_7_5[%d]__attribute__((aligned(16))) = {",length(s6_n2)); fprintf(fd,"%d,",s6_n2(1:(end-1))); fprintf(fd,"%d};\n\n",s6_n2(end)); fprintf(fd,"s16 s6e_kHz_7_5[%d]__attribute__((aligned(16))) = {",length(s6_e2)); fprintf(fd,"%d,",s6_e2(1:(end-1))); fprintf(fd,"%d};\n\n",s6_e2(end)); fprintf(fd,"s16 s15n_kHz_7_5[%d]__attribute__((aligned(16))) = {",length(s15_n2)); fprintf(fd,"%d,",s15_n2(1:(end-1))); fprintf(fd,"%d};\n\n",s15_n2(end)); fprintf(fd,"s16 s15e_kHz_7_5[%d]__attribute__((aligned(16))) = {",length(s15_e2)); fprintf(fd,"%d,",s15_e2(1:(end-1))); fprintf(fd,"%d};\n\n",s15_e2(end)); fprintf(fd,"s16 s25n_kHz_7_5[%d]__attribute__((aligned(16))) = {",length(s25_n2)); fprintf(fd,"%d,",s25_n2(1:(end-1))); fprintf(fd,"%d};\n\n",s25_n2(end)); fprintf(fd,"s16 s25e_kHz_7_5[%d]__attribute__((aligned(16))) = {",length(s25_e2)); fprintf(fd,"%d,",s25_e2(1:(end-1))); fprintf(fd,"%d};\n\n",s25_e2(end)); fprintf(fd,"s16 s50n_kHz_7_5[%d]__attribute__((aligned(16))) = {",length(s50_n2)); fprintf(fd,"%d,",s50_n2(1:(end-1))); fprintf(fd,"%d};\n\n",s50_n2(end)); fprintf(fd,"s16 s50e_kHz_7_5[%d]__attribute__((aligned(16))) = {",length(s50_e2)); fprintf(fd,"%d,",s50_e2(1:(end-1))); fprintf(fd,"%d};\n\n",s50_e2(end)); fprintf(fd,"s16 s75n_kHz_7_5[%d]__attribute__((aligned(16))) = {",length(s75_n2)); fprintf(fd,"%d,",s75_n2(1:(end-1))); fprintf(fd,"%d};\n\n",s75_n2(end)); fprintf(fd,"s16 s75e_kHz_7_5[%d]__attribute__((aligned(16))) = {",length(s75_e2)); fprintf(fd,"%d,",s75_e2(1:(end-1))); fprintf(fd,"%d};\n\n",s75_e2(end)); fprintf(fd,"s16 s100n_kHz_7_5[%d]__attribute__((aligned(16)))= {",length(s100_n2)); fprintf(fd,"%d,",s100_n2(1:(end-1))); fprintf(fd,"%d};\n\n",s100_n2(end)); fprintf(fd,"s16 s100e_kHz_7_5[%d]__attribute__((aligned(16)))= {",length(s100_n2)); fprintf(fd,"%d,",s100_e2(1:(end-1))); fprintf(fd,"%d};\n\n",s100_e2(end)); fclose(fd); end function [s_n2, s_e2] = gen_sig(RB) % 20MHz BW cp0 = 160; cp = 144; cpe = 512; samplerate = 30.72e6; ofdm_size = 2048; len = 15360; switch(RB) case 6 ratio = 1/16; case 15 ratio = 1/8; case 25 ratio = 1/4; case 50 ratio = 1/2; case 75 ratio = 3/4; case 100 ratio = 1; otherwise disp("Wrong Number of RB"); end cp0 = cp0*ratio; cp = cp*ratio; cpe = cpe*ratio; samplerate = samplerate*ratio; ofdm_size = ofdm_size*ratio; len = len*ratio; s_n0 = floor(32767*exp(-sqrt(-1)*2*pi*(-cp0:ofdm_size-1)*7.5e3/samplerate)); s_n1 = floor(32767*exp(-sqrt(-1)*2*pi*(-cp:ofdm_size-1)*7.5e3/samplerate)); s_n = [s_n0 s_n1 s_n1 s_n1 s_n1 s_n1 s_n1]; s_n2 = zeros(1, 2*len); s_n2(1:2:end) = real(s_n); s_n2(2:2:end) = imag(s_n); s_e = floor(32767*exp(-sqrt(-1)*2*pi*(-cpe:ofdm_size-1)*7.5e3/samplerate)); s_e = [s_e s_e s_e s_e s_e s_e]; s_e2 = zeros(1, 2*len); s_e2(1:2:end) = real(s_e); s_e2(2:2:end) = imag(s_e); end
github
Davonter/openairinterface5g-master
f_tls_diag.m
.m
openairinterface5g-master/targets/PROJECTS/TDDREC/f_tls_diag.m
1,272
utf_8
443132469284a3d4d0b38bd5fb7d0522
% % PURPOSE : TLS solution for AX = B based on SVD assuming X is diagonal % % ARGUMENTS : % % A : observation of A % B : observation of B % % OUTPUTS : % % X : TLS solution for X (Diagonal) % %********************************************************************************************** % EURECOM - All rights reserved % % AUTHOR : Xiwen JIANG, Florian Kaltenberger % % DEVELOPMENT HISTORY : % % Date Name(s) Version Description % ----------- ------------- ------- ------------------------------------------------------ % Apr-30-2014 X. JIANG 0.1 creation of code % % REFERENCES/NOTES/COMMENTS : % % - I. Markovsky and S. V. Huffel, “Overview of total least-squares methods,” Signal Processing, vol. 87, pp. % 2283–2302, 2007 % %********************************************************************************************** function [X_est A_est B_est] = f_tls_diag(A,B) d_N = size(A,2); X_est = zeros(d_N); A_est = zeros(size(A)); B_est = zeros(size(B)); err_est = zeros(d_N); for d_n = 1:d_N [X_est(d_n,d_n) A_est(:,d_n) B_est(:,d_n)] = f_tls_svd(A(:,d_n),B(:,d_n)); end %method 2: LS solution % for d_n = 1:d_N % X_est(d_n,d_n) = (A(:,d_n).'*A(:,d_n))\A(:,d_n).'*B(:,d_n); % end
github
Davonter/openairinterface5g-master
f_tls_ap.m
.m
openairinterface5g-master/targets/PROJECTS/TDDREC/f_tls_ap.m
1,368
utf_8
223603e551ebede67ff13452e95097b1
% % PURPOSE : TLS solution for AX = B based on alternative projection % % ARGUMENTS : % % A : observation of A % B : observation of B % % OUTPUTS : % % X : TLS solution for X % %********************************************************************************************** % EURECOM - All rights reserved % % AUTHOR : Xiwen JIANG, Florian Kaltenberger % % DEVELOPMENT HISTORY : % % Date Name(s) Version Description % ----------- ------------- ------- ------------------------------------------------------ % Mai-05-2014 X. JIANG 0.1 creation of code % % REFERENCES/NOTES/COMMENTS : % % - none. % %********************************************************************************************** function [X_est A_est B_est] = f_tls_ap(A,B) %** initlisation ** e_new = 0; e_old = 1e14; e_thr = 1e-5; %error threshold: what if the error cannot fall down under the error threshold X_est = eye(size(A,2)); A_est = A; %** alternative projection ** while(abs(e_new-e_old)>e_thr) e_old = e_new; % optimise X_est X_est = (A_est'*A_est)\A_est'*B; %optimise A_est A_est = B*X_est'/(X_est*X_est'); e_new = norm(A_est*X_est-B)^2+norm(A_est-A)^2; end B_est = A_est*X_est; end
github
Davonter/openairinterface5g-master
f_ofdm_rx.m
.m
openairinterface5g-master/targets/PROJECTS/TDDREC/f_ofdm_rx.m
1,545
utf_8
ade01596524abbe660fc84064cbb4724
% % PURPOSE : OFDM Receiver % % ARGUMENTS : % % m_sig_R : received signal with dimension ((d_N_FFT+d_N_CP)*d_N_ofdm) x d_N % d_N_FFT : total carrier number % d_N_CP : extented cyclic prefix % d_N_OFDM : OFDM symbol number per frame % v_active_rf : active RF antenna indicator % % OUTPUTS : % % m_sym_R : transmitted signal before IFFT with dimension d_N_f x d_N_ofdm x d_N_ant_act % %********************************************************************************************** % EURECOM - All rights reserved % % AUTHOR : Xiwen JIANG, Florian Kaltenberger % % DEVELOPMENT HISTORY : % % Date Name(s) Version Description % ----------- ------------- ------- ------------------------------------------------------ % Apr-29-2014 X. JIANG 0.1 creation of code % % REFERENCES/NOTES/COMMENTS : % % - Based on the function "genrandpskseq" created by Mirsad Cirkic, Florian Kaltenberger. % %********************************************************************************************** function m_sym_R = f_ofdm_rx(m_sig_R, d_N_FFT, d_N_CP, d_N_OFDM, v_active_rf) d_N_ant_act = sum(v_active_rf); m_sig_R_eff = m_sig_R(:,find(v_active_rf)); m_sig_R_f = reshape(m_sig_R_eff,(d_N_FFT+d_N_CP),d_N_OFDM,d_N_ant_act); %** delete the CP ** m_sig_R_noCP = m_sig_R_f(d_N_CP+1:end,:,:); %** fft ** m_sym_R_fft = 1/sqrt(d_N_FFT)*fft(m_sig_R_noCP,d_N_FFT,1); %m_sym_R_fft = fft(m_sig_R_noCP,d_N_FFT,1); m_sym_R = m_sym_R_fft([2:151 362:512],:,:); end
github
Davonter/openairinterface5g-master
f_ch_est.m
.m
openairinterface5g-master/targets/PROJECTS/TDDREC/f_ch_est.m
1,711
utf_8
f583032bb1c37167a7ff2a029a629de9
% % PURPOSE : channel estimation using least square method % % ARGUMENTS : % % m_sym_T : transmitted symbol, d_N_f x d_N_ofdm x d_N_ant_act x d_N_meas % m_sym_R : received symbol, d_N_f x d_N_ofdm x d_N_ant_act x d_N_meas % d_N_meas : number of measurements % % OUTPUTS : % % m_H_est : estimation of sub-channels, d_N_antR x d_N_antT x d_N_f x d_N_meas % %********************************************************************************************** % EURECOM - All rights reserved % % AUTHOR : Xiwen JIANG, Florian Kaltenberger % % DEVELOPMENT HISTORY : % % Date Name(s) Version Description % ----------- ------------- ------- ------------------------------------------------------ % Apr-29-2014 X. JIANG 0.1 creation of code % % REFERENCES/NOTES/COMMENTS : % % - Based on the function "runmeas_full_duplex" created by Mirsad Cirkic, Florian Kaltenberger. % %********************************************************************************************** function m_H_est = f_ch_est(m_sym_T, m_sym_R) %% ** initialisation ** [d_N_f,d_N_OFDM,d_N_antT,d_N_meas] = size(m_sym_T); d_N_antR = size(m_sym_R,3); m_H_est = zeros(d_N_antR,d_N_antT,d_N_f,d_N_meas); %% ** estimate the subband channel for each measurement and antenna ** for d_n_meas = 1:d_N_meas for d_n_f = 1:d_N_f m_y = reshape(m_sym_R(d_n_f,:,:,d_n_meas),d_N_OFDM,d_N_antR).'; % squeeze: problem for antenna number = 1 case m_s = reshape(m_sym_T(d_n_f,:,:,d_n_meas),d_N_OFDM,d_N_antT).'; m_H_est(:,:,d_n_f,d_n_meas) = m_y*m_s'/(m_s*m_s'); % LS channel estimation end end end
github
Davonter/openairinterface5g-master
f_ofdm_tx.m
.m
openairinterface5g-master/targets/PROJECTS/TDDREC/f_ofdm_tx.m
1,997
utf_8
042917cd72b493f1384cbc5fa2fa2de5
% % PURPOSE : OFDM Transmitter % % ARGUMENTS : % % d_M : modulation order % d_N_f : carrier number carrying data % d_N_FFT : total carrier number % d_N_CP : extented cyclic prefix % d_N_OFDM : OFDM symbol number per frame % v_active_rf : active RF antenna indicator % d_amp : amplitude % % OUTPUTS : % % m_sym_T : transmitted signal before IFFT with dimension d_N_f x d_N_OFDM x d_N_ant_act % m_sig_T : OFDM signal with dimension ((d_N_FFT+d_N_CP)*d_N_OFDM) x d_N_ant % %********************************************************************************************** % EURECOM - All rights reserved % % AUTHOR : Xiwen JIANG, Florian Kaltenberger % % DEVELOPMENT HISTORY : % % Date Name(s) Version Description % ----------- ------------- ------- ------------------------------------------------------ % Apr-29-2014 X. JIANG 0.1 creation of code % % REFERENCES/NOTES/COMMENTS : % % - Based on the function "genrandpskseq" created by Mirsad Cirkic, Florian Kaltenberger. % %********************************************************************************************** function [m_sym_T, m_sig_T] = f_ofdm_tx(d_M, d_N_f, d_N_FFT, d_N_CP, d_N_OFDM, v_active_rf, d_amp) d_N_ant_act = sum(v_active_rf); %** constellation table ** v_MPSK = exp(sqrt(-1)*([1:d_M]*2*pi/d_M+pi/d_M)); %** transmitted symbol ** %v_state = [1;2;3;4]; %rand("state",v_state); m_sym_T = v_MPSK(ceil(rand(d_N_f, d_N_OFDM, d_N_ant_act)*d_M)); %** mapping useful data to favorable carriers ** m_sym_T_ext = zeros(d_N_FFT,d_N_OFDM,d_N_ant_act); m_sym_T_ext(2:151,:,:) = m_sym_T(1:150,:,:); m_sym_T_ext(362:512,:,:) = m_sym_T(151:301,:,:); %** ifft ** m_sig_T_ = sqrt(d_N_FFT)*ifft(m_sym_T_ext,d_N_FFT,1); %** add cyclic prefix ** m_sig_T_ = [m_sig_T_(end-d_N_CP+1:end,:,:); m_sig_T_]; d_L = (d_N_FFT+d_N_CP)*d_N_OFDM; m_sig_T = floor(reshape(m_sig_T_,d_L,d_N_ant_act)*d_amp); end
github
Davonter/openairinterface5g-master
f_ofdm_rx.m
.m
openairinterface5g-master/targets/PROJECTS/TDDREC/v4_CH_EST/f_ofdm_rx.m
1,545
utf_8
798a54f027b266189ab1fdc57569dac1
% % PURPOSE : OFDM Receiver % % ARGUMENTS : % % m_sig_R : received signal with dimension ((d_N_FFT+d_N_CP)*d_N_ofdm) x d_N % d_N_FFT : total carrier number % d_N_CP : extented cyclic prefix % d_N_OFDM : OFDM symbol number per frame % v_active_rf : active RF antenna indicator % % OUTPUTS : % % m_sym_R : transmitted signal before IFFT with dimension d_N_f x d_N_ofdm x d_N_ant_act % %********************************************************************************************** % EURECOM - All rights reserved % % AUTHOR : Xiwen JIANG, Florian Kaltenberger % % DEVELOPMENT HISTORY : % % Date Name(s) Version Description % ----------- ------------- ------- ------------------------------------------------------ % Apr-29-2014 X. JIANG 0.1 creation of code % % REFERENCES/NOTES/COMMENTS : % % - Based on the function "genrandpskseq" created by Mirsad Cirkic, Florian Kaltenberger. % %********************************************************************************************** function m_sym_R = f_ofdm_rx(m_sig_R, d_N_FFT, d_N_CP, d_N_OFDM, v_active_rf) d_N_ant_act = sum(v_active_rf); m_sig_R_eff = m_sig_R(:,find(v_active_rf)); m_sig_R_f = reshape(m_sig_R_eff,(d_N_FFT+d_N_CP),d_N_OFDM,d_N_ant_act); %** delete the CP ** m_sig_R_noCP = m_sig_R_f(d_N_CP+1:end,:,:); %** fft ** m_sym_R_fft = 1/sqrt(d_N_FFT)*fft(m_sig_R_noCP,d_N_FFT,1); %m_sym_R_fft = fft(m_sig_R_noCP,d_N_FFT,1); m_sym_R = m_sym_R_fft([363:512 2:151],:,:); end
github
Davonter/openairinterface5g-master
f_ch_est.m
.m
openairinterface5g-master/targets/PROJECTS/TDDREC/v4_CH_EST/f_ch_est.m
1,708
utf_8
ad1741afb57ea0bbc0da1f1f0d410ce6
% PURPOSE : channel estimation using least square method %% ARGUMENTS : % % m_sym_T : transmitted symbol, d_N_f x d_N_ofdm x d_N_ant_act x d_N_meas % m_sym_R : received symbol, d_N_f x d_N_ofdm x d_N_ant_act x d_N_meas % d_N_meas : number of measurements % % OUTPUTS : % % m_H_est : estimation of sub-channels, d_N_antR x d_N_antT x d_N_f x d_N_meas % %********************************************************************************************** % EURECOM - All rights reserved % % AUTHOR : Xiwen JIANG, Florian Kaltenberger % % DEVELOPMENT HISTORY : % % Date Name(s) Version Description % ----------- ------------- ------- ------------------------------------------------------ % Apr-29-2014 X. JIANG 0.1 creation of code % % REFERENCES/NOTES/COMMENTS : % % - Based on the function "runmeas_full_duplex" created by Mirsad Cirkic, Florian Kaltenberger. % %********************************************************************************************** function m_H_est = f_ch_est(m_sym_T, m_sym_R) %% ** initialisation ** [d_N_f,d_N_OFDM,d_N_antT,d_N_meas] = size(m_sym_T); d_N_antR = size(m_sym_R,3); m_H_est = zeros(d_N_antR,d_N_antT,d_N_f,d_N_meas); %% ** estimate the subband channel for each measurement and antenna ** for d_n_meas = 1:d_N_meas for d_n_f = 1:d_N_f m_y = reshape(m_sym_R(d_n_f,:,:,d_n_meas),d_N_OFDM,d_N_antR).'; % squeeze: problem for antenna number = 1 case m_s = reshape(m_sym_T(d_n_f,:,:,d_n_meas),d_N_OFDM,d_N_antT).'; m_H_est(:,:,d_n_f,d_n_meas) = m_y*m_s'/(m_s*m_s'); % LS channel estimation end end end
github
Davonter/openairinterface5g-master
f_ofdm_tx.m
.m
openairinterface5g-master/targets/PROJECTS/TDDREC/v4_CH_EST/f_ofdm_tx.m
1,997
utf_8
52b00cfe39a99e4f6d079fcc3cdad1f8
% % PURPOSE : OFDM Transmitter % % ARGUMENTS : % % d_M : modulation order % d_N_f : carrier number carrying data % d_N_FFT : total carrier number % d_N_CP : extented cyclic prefix % d_N_OFDM : OFDM symbol number per frame % v_active_rf : active RF antenna indicator % d_amp : amplitude % % OUTPUTS : % % m_sym_T : transmitted signal before IFFT with dimension d_N_f x d_N_OFDM x d_N_ant_act % m_sig_T : OFDM signal with dimension ((d_N_FFT+d_N_CP)*d_N_OFDM) x d_N_ant % %********************************************************************************************** % EURECOM - All rights reserved % % AUTHOR : Xiwen JIANG, Florian Kaltenberger % % DEVELOPMENT HISTORY : % % Date Name(s) Version Description % ----------- ------------- ------- ------------------------------------------------------ % Apr-29-2014 X. JIANG 0.1 creation of code % % REFERENCES/NOTES/COMMENTS : % % - Based on the function "genrandpskseq" created by Mirsad Cirkic, Florian Kaltenberger. % %********************************************************************************************** function [m_sym_T, m_sig_T] = f_ofdm_tx(d_M, d_N_f, d_N_FFT, d_N_CP, d_N_OFDM, v_active_rf, d_amp) d_N_ant_act = sum(v_active_rf); %** constellation table ** v_MPSK = exp(sqrt(-1)*([1:d_M]*2*pi/d_M+pi/d_M)); %** transmitted symbol ** %v_state = [1;2;3;4]; %rand("state",v_state); m_sym_T = v_MPSK(ceil(rand(d_N_f, d_N_OFDM, d_N_ant_act)*d_M)); %** mapping useful data to favorable carriers ** m_sym_T_ext = zeros(d_N_FFT,d_N_OFDM,d_N_ant_act); m_sym_T_ext(2:151,:,:) = m_sym_T(151:300,:,:); m_sym_T_ext(363:512,:,:) = m_sym_T(1:150,:,:); %** ifft ** m_sig_T_ = sqrt(d_N_FFT)*ifft(m_sym_T_ext,d_N_FFT,1); %** add cyclic prefix ** m_sig_T_ = [m_sig_T_(end-d_N_CP+1:end,:,:); m_sig_T_]; d_L = (d_N_FFT+d_N_CP)*d_N_OFDM; m_sig_T = floor(reshape(m_sig_T_,d_L,d_N_ant_act)*d_amp); end
github
Davonter/openairinterface5g-master
genorthqpskseq.m
.m
openairinterface5g-master/targets/PROJECTS/TDDREC/v0/genorthqpskseq.m
1,143
utf_8
330b0dc2a723aa7a373d8a0cd01fcabb
# % Author: Mirsad Cirkic # % Organisation: Eurecom (and Linkoping University) # % E-mail: [email protected] function [carrierdata, s]=genorthqpskseq(Ns,N,amp) if(N!=512*150) error('The sequence length must be 76800.'); endif s = zeros(N,Ns); H=1; for k=1:log2(128) H=[H H; H -H]; end; H=H(:,1:120); i=1; while(i<size(H,1)) h=H(i,:); inds=find(h*H'!=0); H(inds,:)=[]; H=[h; H]; i=i+1; end Hc=H+sqrt(-1)*H; if(sum(Hc*Hc'-240*eye(8))>0) error("The code is not orhtogonal\n"); endif carrierdata=zeros(120,Ns*301); inds=1:8; ind=8; for i=1:301 for k=1:Ns carrierdata(:,i+(k-1)*301)=Hc(inds(ind),:)'; inds(ind)=[]; ind=ind-1; if(ind==0) inds=1:8; ind=8; endif endfor endfor for k=1:Ns frstgroup=(k-1)*301+[1:150]; # The first group of OFDM carriers sndgroup=(k-1)*301+[151:301]; # The second group of OFDM carriers for i=0:119 fblock=[0 carrierdata(i+1,frstgroup) zeros(1,210) carrierdata(i+1,sndgroup)]; ifblock=ifft(fblock,512)*sqrt(512); block = [ifblock(end-127:end) ifblock]; # Cycl. prefix s([1:640]+i*640,k)=floor(amp*block); endfor endfor endfunction
github
Davonter/openairinterface5g-master
genrandpskseq.m
.m
openairinterface5g-master/targets/PROJECTS/TDDREC/v0/genrandpskseq.m
776
utf_8
5cb33d8e20311847ffaa652cf70a4865
% Author: Mirsad Cirkic % Organisation: Eurecom (and Linkoping University) % E-mail: [email protected] function [carrierdata, s]=genrandpskseq(N,M,amp) if(mod(N,640)~=0) error('The sequence length must be divisible with 640.'); end s = zeros(N,1); MPSK=exp(sqrt(-1)*([1:M]*2*pi/M+pi/M)); % OFDM sequence with 512 FFT using randomly % generated 4-QAM and 128 cyclic prefix carrierdata=zeros(120,301); for i=0:(N/640-1) datablock=MPSK(ceil(rand(301,1)*M)); for j=1:301 carrierdata(i+1,j)=datablock(j); end fblock=[0 datablock(1:150) zeros(1,210) datablock(151:301)]; ifblock=ifft(fblock,512)*sqrt(512);; % Adding cycl. prefix making the block of 640 elements block = [ifblock(end-127:end) ifblock]; s([1:640]+i*640)=floor(amp*block); end end
github
Davonter/openairinterface5g-master
rfldec.m
.m
openairinterface5g-master/targets/ARCH/EXMIMO/USERSPACE/OCTAVE/rfldec.m
363
utf_8
24448e69682b1f6a6ea652c2426b08f7
## Decodes rf_local values: [ txi, txq, rxi, rxq ] = rfldec(rflocal) ## Author: Matthias Ihmig <ihmig@solstice> ## Created: 2012-12-05 function [ txi, txq, rxi, rxq ] = rfldec(rflocal) txi = mod(floor( rflocal /1 ), 64) txq = mod(floor( rflocal /64), 64) rxi = mod(floor( rflocal /4096), 64) rxq = mod(floor( rflocal /262144), 64) endfunction
github
Davonter/openairinterface5g-master
rfl.m
.m
openairinterface5g-master/targets/ARCH/EXMIMO/USERSPACE/OCTAVE/rfl.m
225
utf_8
9ad201a94d01db3e65ecedb02252ca19
## Composes rf_local values: rfl(txi, txq, rxi, rxq) ## Author: Matthias Ihmig <ihmig@solstice> ## Created: 2012-12-05 function [ ret ] = rfl(txi, txq, rxi, rxq) ret = txi + txq*2^6 + rxi*2^12 + rxq*2^18; endfunction
github
metocean/pysmc-master
create_grid_smcbase.m
.m
pysmc-master/SMCPy/matlab/create_grid_smcbase.m
11,589
utf_8
aa1c3bf7514af29170217dbe658c50c0
% THIS IS AN EXAMPLE SCRIPT FOR GENERATING A GRID AND CAN BE USED % AS A TEMPLATE FOR DESIGNING GRIDS function []=create_grid_smcbase(id,latmin,latmax,lonmin,lonmax,dlat,dlon,ref_grid,boundary,IS_GLOBAL,LAKE_TOL,out_dir,testmode,fname_poly, shift_userpolys) % 0. Initialization % 0.a Path to directories bin_dir = '/source/gridgen/noaa/bin'; % matlab scripts location ref_dir = '/source/gridgen/noaa/reference_data'; % reference data location % out_dir = './out/'; % output directory % 0.b Design grid parameters % fname_poly = '/source/gridgen/tests/glob05v5/user_polygons.flag'; % A file with switches for using user % defined polygons. An example file % has been provided with the reference % data for an existing user defined % polygon database. A switch of 0 % ignores the polygon while 1 % accounts for the polygon. fname = id; % file name prefix % Grid Definition % Gridgen is designed to work with curvilinear and/or rectilinear grids. In % both cases it expects a 2D array defining the Longititudes (x values) and % Lattitudes (y values). For curvilinear grids the user will have to use % alternative software to determine these arrays. For rectilinear grids % these are determined by the grid domain and desired resolution as shown % below % NOTE : In gridgen we always define the longitudes in the 0 to 365 range as the % boundary polygons have been defined in that range. It is fairly trivial to % rearrange the grids to -180 to 180 range after they have been generated. dx = str2num(dlon); dy = str2num(dlat); x1 = str2num(lonmin); x2 = str2num(lonmax); y1 = str2num(latmin); y2 = str2num(latmax); LAKE_TOL = str2num(LAKE_TOL); IS_GLOBAL = str2num(IS_GLOBAL); lon1d = [x1:dx:x2]; lat1d = [y1:dy:y2]; [lon,lat] = meshgrid(lon1d,lat1d); %ref_grid = 'etopo1'; % reference grid source % % etopo1 = Etopo1 grid % % etopo2 = Etopo2 grid %boundary = 'full'; % Option to determine which GSHHS % % .mat file to load % % full = full resolution % % high = 0.2 km % % inter = 1 lm % % low = 5 km % % coarse = 25 km % 0.c Setting the paths for subroutines addpath(bin_dir,'-END'); % 0.d Reading Input data read_boundary = 1; % flag to determine if input boundary % information needs to be read boundary % data files can be significantly large % and needs to be read only the first % time. So when making multiple grids % the flag can be set to 0 for subsequent % grids. (Note : If the workspace is % cleared the boundary data will have to % be read again) opt_poly = 0; % flag for reading the optional user % defined polygons. Set to 0 if you do % not wish to use this opt if (~strcmp(fname_poly, '0') & (fname_poly ~= 0)) opt_poly = 1; end; %if (fname_poly ~= 0) %opt_poly = 1; %end; obstr_scale = 100; depth_scale = 1000; if (nargin == 14) shift_userpolys = 0 end; testmode = str2num(testmode); if (testmode == 1) fprintf(1,'.........RUNNING IN TEST MODE..................\n'); fprintf(1,'.........(ignoring coastal polygons)..................\n'); end; if (read_boundary == 1) fprintf(1,'.........Reading Boundaries..................\n'); load([ref_dir,'/coastal_bound_',boundary,'.mat']); N = length(bound); Nu = 0; if (opt_poly == 1) [bound_user,Nu] = optional_bound(ref_dir,fname_poly, shift_userpolys); end; if (Nu == 0) opt_poly = 0; end; end; % 0.d Parameter values used in the software DRY_VAL = 999999; % Depth value for dry cells (can change as desired) MSL_LEV = 0.0; % Bathymetry level indicating wet / dry cells % all bathymetry values below this level are % considered wet CUT_OFF = 0.1; % Proportion of base bathymetry cells that need to be % wet for the target cell to be considered wet. % NOTE : If you have accurate boundary polygons then it is better to have a low value for % CUT_OFF which will make the target bathymetry cell wet even when there are only few % wet cells in the base bathymetry. This will then be cleaned up by the polygons in % the mask cleanup section. If on the other hand you do not inttend to use the % polygons to define the coastal domains then you are better off using CUT_OFF = 0.5 LIM_VAL = 0.5; % Fraction of cell that has to be inside a polygon for % cell to be marked dry; OFFSET = max([dx dy]); % Additional buffer around the boundary to check if cell % is crossing boundary. Should be set to largest grid res. % LAKE_TOL = -1; % See documentation on remove_lake routine for possible % values. % IS_GLOBAL = 0; % Set to 1 for global grids OBSTR_OFFSET = 1; % See documentation for create_obstr for details % 1. Generate the grid fprintf(1,'.........Creating Bathymetry..................\n'); depth = generate_grid(lon,lat,ref_dir,ref_grid,CUT_OFF,MSL_LEV,DRY_VAL); if (testmode == 1) fprintf(1,'.........Running in test mode, ignoring coastal polygons..................\n'); m = ones(size(depth)); m(depth == DRY_VAL) = 0; if (opt_poly == 1) lon_start = min(min(lon))-dx; lon_end = max(max(lon))+dx; lat_start = min(min(lat))-dy; lat_end = max(max(lat))+dy; coord = [lat_start lon_start lat_end lon_end]; [b_opt,N2] = compute_boundary(coord,bound_user); if (N2 ~= 0) fprintf(1,'...Applying user defined polygons..................\n'); m2 = clean_mask(lon,lat,m,b_opt,LIM_VAL,OFFSET); else m2 = m; end; end; fprintf(1,'.........Separating Water Bodies..................\n'); fprintf(1,'Lake_tol being passed to remove_lake: %d\n', LAKE_TOL); [m4,mask_map] = remove_lake(m2,LAKE_TOL,IS_GLOBAL); sx1 = zeros(size(depth)); sy1 = zeros(size(depth)); write_ww3file([out_dir,'/',fname,'.mask_map_before_user'],m); write_ww3file([out_dir,'/',fname,'.mask_map'],m2); write_ww3file([out_dir,'/',fname,'.before_remove_lakes'],m); write_ww3file([out_dir,'/',fname,'.after_remove_lakes'],m4); else % 2. Computing boundaries within the domain fprintf(1,'.........Computing Boundaries..................\n'); % 2.a Set the domain big enough to include the cells along the edges of the grid lon_start = min(min(lon))-dx; lon_end = max(max(lon))+dx; lat_start = min(min(lat))-dy; lat_end = max(max(lat))+dy; % 2.b Extract the boundaries from the GSHHS and the optional databases % the subset of polygons within the grid domain are stored in b and b_opt % for GSHHS and user defined polygons respectively coord = [lat_start lon_start lat_end lon_end]; [b,N1] = compute_boundary(coord,bound); if (opt_poly == 1) fprintf(1,'...Applying user defined polygons..................\n'); [b_opt,N2] = compute_boundary(coord,bound_user); end; % 3. Set up Land - Sea Mask % 3.a Set up initial land sea mask. The cells can either all be set to wet % or to make the code more efficient the cells marked as dry in % 'generate_grid' can be marked as dry cells m = ones(size(depth)); m(depth == DRY_VAL) = 0; % 3.b Split the larger GSHHS polygons for efficient computation of the % land sea mask. This is an optional step but recomended as it % significantly speeds up the computational time. Rule of thumb is to % set the limit for splitting the polygons at least 4-5 times dx,dy fprintf(1,'.........Splitting Boundaries..................\n'); if isstruct(b) b_split = split_boundary(b,5*max([dx dy])); % 3.c Get a better estimate of the land sea mask using the polygon data sets. % (NOTE : This part will have to be commented out if cells above the % MSL are being marked as wet, like in inundation studies) fprintf(1,'.........Cleaning Mask..................\n'); % GSHHS Polygons. If 'split_boundary' routine is not used then replace % b_split with b m2 = clean_mask(lon,lat,m,b_split,LIM_VAL,OFFSET); % Masking out regions defined by optional polygons if (opt_poly == 1 && N2 ~= 0) m3 = clean_mask(lon,lat,m2,b_opt,LIM_VAL,OFFSET); else m3 = m2; end; % 3.d Remove lakes and other minor water bodies fprintf(1,'.........Separating Water Bodies..................\n'); [m4,mask_map] = remove_lake(m3,LAKE_TOL,IS_GLOBAL); % 4. Generate sub - grid obstruction sets in x and y direction, based on % the final land/sea mask and the coastal boundaries fprintf(1,'.........Creating Obstructions..................\n'); [sx1,sy1] = create_obstr(lon,lat,b,m4,OBSTR_OFFSET,OBSTR_OFFSET); % 5. Output to ascii files for WAVEWATCH III else fprintf(1,'.......No boundaries in domain..............\n'); m4 = m; sx1 = zeros(size(depth)); sy1 = zeros(size(depth)); end; end; % testmode check d = round((depth)*depth_scale); d1 = round((sx1)*obstr_scale); d2 = round((sy1)*obstr_scale); dlon=dx; dlat=dy; save([out_dir,'/',fname '.mat'], 'dlon', 'dlat', 'lon', 'lat', 'depth', 'm3', 'm4',... 'mask_map', 'sx1', 'sy1'); % 6. Vizualization (this part can be commented out if resources are limited) %figure(1); %clf; %loc = find(m4 == 0); %d2 = depth; %d2(loc) = NaN; %pcolor(lon,lat,d2); %shading interp; %colorbar; %title(['Bathymetry for ',fname],'fontsize',14); %set(gca,'fontsize',14); %clear d2; %figure(2); %clf; %d2 = mask_map; %loc2 = find(mask_map == -1); %d2(loc2) = NaN; %pcolor(lon,lat,d2); %shading flat; %colorbar; %title(['Different water bodies for ',fname],'fontsize',14); %set(gca,'fontsize',14); %clear d2; % %figure(3); %clf; %pcolor(lon,lat,m4); %shading flat; %colorbar; %title(['Final Land-Sea Mask ',fname],'fontsize',14); %set(gca,'fontsize',14); %figure(4); %clf; %d2 = sx1; %d2(loc) = NaN; %pcolor(lon,lat,d2); %shading flat; %colorbar; %title(['Sx obstruction for ',fname],'fontsize',14); %set(gca,'fontsize',14); %clear d2; %figure(5); %clf; %d2 = sy1; %d2(loc) = NaN; %pcolor(lon,lat,d2); %shading flat; %colorbar; %title(['Sy obstruction for ',fname],'fontsize',14); %set(gca,'fontsize',14); %clear d2; exit end % END OF SCRIPT
github
sophont01/fStackIID-master
smooth_d.m
.m
fStackIID-master/utils/smooth_d.m
688
utf_8
f82b36cb85b140dae43358166f5681b9
%smooth the depth map to eliminate outliers function x=smooth_d(im,tmp,mask) [m n d]=size(im); depth=reshape(tmp,[],1); feature=reshape(im,[],d)'; c=20; lambda=0.02; row=[1:m*(n-1);m+1:m*n]; [a b]=ndgrid(1:m-1,1:n); tmp=sub2ind([m n],reshape(a,1,[]),reshape(b,1,[])); row=[row [tmp;tmp+1]]; value=exp(-c*sum(abs(feature(:,row(1,:))-feature(:,row(2,:)))))+1e-6; if(exist('mask','var')==1) mask=reshape(1-double(mask),[],1); value(find(mask(row(1,:))|mask(row(2,:))))=1e-3; end A=sparse(row(1,:),row(2,:),value,m*n,m*n); A=A+A'; D=spdiags(sum(A,2),0,m*n,m*n); L=D-A; M=spdiags(double(depth>=0.00001),0,m*n,m*n); x=(L+lambda*M)\(lambda*M*depth); x=reshape(x,m,n); end
github
sophont01/fStackIID-master
getVectors.m
.m
fStackIID-master/utils/getVectors.m
305
utf_8
3c948da1c7970d6eaf018498e9d38436
%compute the view vector at each pixel function p=getVectors(m,n,fov) if(~exist('fov','var')) fov=60; end x=((1:n)-(n+1)/2)/(n/2)*tan(fov/2/180*pi); y=-((1:m)-(m+1)/2)/(m/2)*tan(fov/2/180*pi)*(m/n); p=zeros(m,n,3); for i=1:m p(i,:,2)=y(i); end for i=1:n p(:,i,1)=x(i); end p(:,:,3)=-1; end