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
anantsrivastava30/SUVR-PET-ADNI-master
linsysolvefun.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/linsysolvefun.m
1,276
utf_8
7ca4a2896ad33a210a95d53138f0676f
%%************************************************************************* %% linsysolvefun: Solve H*x = b %% %% x = linsysolvefun(L,b) %% where L contains the triangular factors of H. %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%************************************************************************* function x = linsysolvefun(L,b) x = zeros(size(b)); for k=1:size(b,2) if strcmp(L.matfct_options,'chol') x(L.perm,k) = mextriang(L.R, mextriang(L.R,b(L.perm,k),2) ,1); %% x(L.perm,k) = L.R \ (b(L.perm,k)' / L.R)'; elseif strcmp(L.matfct_options,'spchol') x(L.perm,k) = mextriangsp(L.Rt,mextriangsp(L.R,b(L.perm,k),2),1); elseif strcmp(L.matfct_options,'ldl') x(L.p,k) = ((L.D\ (L.L \ b(L.p,k)))' / L.L)'; elseif strcmp(L.matfct_options,'spldl') btmp = b(:,k).*L.s; xtmp(L.p,1) = L.Lt\ (L.D\ (L.L \ btmp(L.p))); %#ok x(:,k) = xtmp.*L.s; elseif strcmp(L.matfct_options,'lu') x(:,k) = L.U \ (L.L \ b(L.p,k)); elseif strcmp(L.matfct_options,'splu') btmp = b(:,k)./L.s; x(L.q,k) = L.U \ (L.L \ (btmp(L.p))); end end %%*************************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
sqlpdemo.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/sqlpdemo.m
6,011
utf_8
793deabad8688259781993ce346cea24
%%***************************************************************** %% Examples of SQLP. %% %% this is an illustration on how to use our SQLP solvers %% coded in sqlp.m %% %% feas = 1 if want feasible initial iterate %% = 0 otherwise %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%***************************************************************** function sqlpdemo randn('seed',0); rand('seed',0); %#ok feas = input('using feasible starting point? [yes = 1, no = 0] '); if (feas) fprintf('\n using feasible starting point\n\n'); else fprintf('\n using infeasible starting point\n\n'); end pause(1); ntrials = 1; % iterm = zeros(2,6); infom = zeros(2,6); timem = zeros(2,6); sqlparameters; for trials = 1:ntrials for eg = 1:6 if (eg == 1); disp('******** random sdp **********') n = 10; m = 10; [blk,At,C,b,X0,y0,Z0] = randsdp(n,[],[],m,feas); text = 'random SDP'; elseif (eg == 2); disp('******** Norm minimization problem. **********') n = 10; m = 5; B = []; for k = 1:m+1; B{k} = randn(n); end; %#ok [blk,At,C,b,X0,y0,Z0] = norm_min(B,feas); text = 'Norm min. pbm'; elseif (eg == 3); disp('******** Max-cut *********'); N = 10; B = graph(N); [blk,At,C,b,X0,y0,Z0] = maxcut(B,feas); text = 'Maxcut'; elseif (eg == 4); disp('********* ETP ***********') N = 10; B = randn(N); B = B*B'; [blk,At,C,b,X0,y0,Z0] = etp(B,feas); text = 'ETP'; elseif (eg == 5); disp('**** Lovasz theta function ****') N = 10; B = graph(N); [blk,At,C,b,X0,y0,Z0] = thetaproblem(B,feas); text = 'Lovasz theta fn.'; elseif (eg == 6); disp('**** Logarithmic Chebyshev approx. pbm. ****') N = 20; m = 5; B = rand(N,m); f = rand(N,1); [blk,At,C,b,X0,y0,Z0] = logcheby(B,f,feas); text = 'Log. Chebyshev approx. pbm'; end; %% % m = length(b); nn = 0; for p = 1:size(blk,1), nn = nn + sum(blk{p,2}); end %% Gap = []; Feas = []; legendtext = {}; for vers = [1 2]; OPTIONS.vers = vers; [obj,X,y,Z,infoall,runhist] = ... sqlp(blk,At,C,b,OPTIONS,X0,y0,Z0); %#ok gaphist = runhist.gap; infeashist = max([runhist.pinfeas; runhist.dinfeas]); Gap(vers,1:length(gaphist)) = gaphist; %#ok Feas(vers,1:length(infeashist)) = infeashist; %#ok if (vers==1); legendtext{end+1} = 'HKM'; %#ok elseif (vers==2); legendtext{end+1} = 'NT'; %#ok end; end; h = plotgap(Gap,Feas); xlabel(text); legend(h(h~=0),legendtext{:}); fprintf('\n**** press enter to continue ****\n'); pause end end %% %%====================================================================== %% plotgap: plot the convergence curve of %% duality gap and infeasibility measure. %% %% h = plotgap(Gap,Feas); %% %% Input: Gap = each row of Gap corresponds to a convergence curve %% of the duality gap for an SDP. %% Feas = each row of Feas corresponds to a convergence curve %% of the infeasibility measure for an SDP. %% %% Output: h = figure handle. %% %% SDPT3: version 3.0 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last modified: 7 Jul 99 %%******************************************************************** function h = plotgap(Gap,Feas) clf; set(0,'defaultaxesfontsize',12); set(0,'defaultlinemarkersize',2); set(0,'defaulttextfontsize',12); %% %% get axis scale for plotting duality gap %% tmp = []; for k = 1:size(Gap,1); g = Gap(k,:); if ~isempty(g); g = g(g > 5*eps); tmp = [tmp abs(g)]; %#ok iter(k) = length(g); %#ok else iter(k) = 0; %#ok end end; ymax = exp(log(10)*(round(log10(max(tmp)))+0.5)); ymin = exp(log(10)*min(floor(log10(tmp)))-0.5); xmax = 5*ceil(max(iter)/5); %% %% plot duality gap %% color = '-r --b--m-c '; if nargin == 2; subplot('position',[0.05 0.3 0.45 0.45]); end; for k = 1:size(Gap,1); g = Gap(k,:); if ~isempty(g); idx = find(g > 5*eps); if ~isempty(idx); g = g(idx); len = length(g); semilogy(len-1,g(len),'.b','markersize',12); hold on; h(k) = semilogy(idx-1,g,color([3*(k-1)+1:3*k]),'linewidth',2); %#ok end; end; end; title('duality gap'); axis('square'); if nargin == 1; axis([0 xmax ymin ymax]); end; hold off; %% %% get axis scale for plotting infeasibility %% if nargin == 2; tmp = []; for k = 1:size(Feas,1); f = Feas(k,:); if ~isempty(f); f = f(f>0); tmp = [tmp abs(f)]; %#ok iter(k) = length(f); %#ok else iter(k) = 0; %#ok end end; fymax = exp(log(10)*(round(log10(max(tmp)))+0.5)); fymin = exp(log(10)*(min(floor(log10(tmp)))-0.5)); ymax = max(ymax,fymax); ymin = min(ymin,fymin); xmax = 5*ceil(max(iter)/5); axis([0 xmax ymin ymax]); %% %% plot infeasibility %% subplot('position',[0.5 0.3 0.45 0.45]); for k = 1:size(Feas,1); f = Feas(k,:); f(1) = max(f(1),eps); if ~isempty(f); idx = find(f > 1e-20); if ~isempty(idx); f = f(idx); len = length(f); semilogy(len-1,f(len),'.b','markersize',12); hold on; h(k) = semilogy(idx-1,f,color([3*(k-1)+1:3*k]),'linewidth',2); %#ok end; end; end; title('infeasibility measure'); axis('square'); axis([0 xmax ymin max(1,ymax)]); hold off; end; %%====================================================================
github
anantsrivastava30/SUVR-PET-ADNI-master
gpcomp.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/gpcomp.m
5,095
utf_8
7e23e98588f834156a9f13545f77cb3b
%%********************************************************************* %% gpcomp: Compute tp=1/gp in Proposition 2 of the paper: %% %% R.M. Freund, F. Ordonez, and K.C. Toh, %% Behavioral measures and their correlation with IPM iteration counts %% on semi-definite programming problems, %% Mathematical Programming, 109 (2007), pp. 445--475. %% %% [gp,info,Xfeas,blk2,At2,C2,b2] = gpcomp(blk,At,C,b,OPTIONS,solveyes); %% %% Xfeas = a feasible X for the primal problem if gp is finite. %% That is, %% norm(b-AXfun(blk,At,[],Xfeas)) %% should be small %%********************************************************************* function [gp,info,Xfeas,blk2,At2,C2,b2] = gpcomp(blk,At,C,b,OPTIONS,solveyes) if (nargin < 6); solveyes = 1; end if (nargin < 5) OPTIONS = sqlparameters; OPTIONS.vers = 1; OPTIONS.gaptol = 1e-10; OPTIONS.printlevel = 3; end if isempty(OPTIONS); OPTIONS = sqlparameters; end if ~isfield(OPTIONS,'solver'); OPTIONS.solver = 'sqlp'; end if ~isfield(OPTIONS,'printlevel'); OPTIONS.printlevel = 3; end if ~iscell(C); tmp = C; clear C; C{1} = tmp; end %% %% convert ublk to lblk %% % exist_ublk = 0; for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'u'); % exist_ublk = 1; fprintf('\n converting ublk into the difference of two non-negative vectors'); blk{p,1} = 'l'; blk{p,2} = 2*sum(blk{p,2}); At{p} = [At{p}; -At{p}]; C{p} = [C{p}; -C{p}]; end end %% m = length(b); blk2 = blk; At2 = At; C2 = cell(size(blk,1),1); b2 = zeros(m,1); %% %% %% dd = ones(1,m); ee = zeros(1,m); EE = cell(size(blk,1),1); % exist_ublk = 0; nn = zeros(size(blk,1),1); for p = 1:size(blk,1) pblk = blk(p,:); n = sum(pblk{2}); if strcmp(pblk{1},'s') ee = ee + svec(pblk,speye(n),1)'*At{p}; C2{p,1} = sparse(n,n); EE{p} = speye(n); nn(p) = n; elseif strcmp(pblk{1},'q') eq = zeros(n,1); idx1 = 1+[0,cumsum(pblk{2})]; idx1 = idx1(1:length(idx1)-1); eq(idx1) = ones(length(idx1),1); ee = ee + 2*eq'*At{p}; C2{p,1} = zeros(n,1); EE{p} = eq; nn(p) = length(pblk{2}); elseif strcmp(pblk{1},'l') ee = ee + ones(1,n)*At{p}; C2{p,1} = zeros(n,1); EE{p} = ones(n,1); nn(p) = n; elseif strcmp(pblk{1},'u') C2{p,1} = zeros(n,1); % exist_ublk = 1; EE{p} = sparse(n,1); nn(p) = n; end dd = dd + sqrt(sum(At{p}.*At{p})); end dd = 1./min(1e4,max(1,dd)); ee = ee.*dd; b = b.*dd'; %% %% scale data %% D = spdiags(dd',0,m,m); for p = 1:size(blk,1) % pblk = blk(p,:); At2{p} = At2{p}*D; end %% %% New variables in primal problem: %% [x; tt; theta]. %% numblk = size(blk,1); blk2{numblk+1,1} = 'l'; blk2{numblk+1,2} = 2; At2{numblk+1,1} = [ee; -b']; C2{numblk+1,1} = [-1; 0]; %% %% 3 additional inequality constraints in primal problem. %% ss = 0; for p = 1:size(blk,1) pblk = blk(p,:); n = sum(pblk{2}); if strcmp(pblk{1},'s') n2 = sum(pblk{2}.*(pblk{2}+1))/2; At2{p} = [At2{p}, svec(pblk,speye(n,n),1), sparse(n2,2)]; ss = ss + n; elseif strcmp(pblk{1},'q') eq = zeros(n,1); idx1 = 1+[0,cumsum(pblk{2})]; idx1 = idx1(1:length(idx1)-1); eq(idx1) = ones(length(idx1),1); At2{p} = [At2{p}, sparse(eq), sparse(n,2)]; ss = ss + 2*length(pblk{2}); elseif strcmp(pblk{1},'l') At2{p} = [At2{p}, sparse(ones(n,1)), sparse(n,2)]; ss = ss + n; elseif strcmp(pblk{1},'u') At2{p} = [At2{p}, sparse(n,3)]; end end At2{numblk+1} = sparse([At2{numblk+1}, [ss;0], [0;1], [1;-1]]); b2 = [b2; 1; 1; 0]; %% %% Add in the linear block corresponding to the 3 slack variables. %% blk2{numblk+2,1} = 'l'; blk2{numblk+2,2} = 3; At2{numblk+2,1} = [sparse(3,m), speye(3,3)]; C2{numblk+2,1} = zeros(3,1); %% %% Solve SDP %% gp = []; info = []; Xfeas = []; if (solveyes) if strcmp(OPTIONS.solver,'sqlp') [X0,y0,Z0] = infeaspt(blk2,At2,C2,b2,2,100); [obj,X,y,Z,info] = sqlp(blk2,At2,C2,b2,OPTIONS,X0,y0,Z0); %#ok elseif strcmp(OPTIONS.solver,'HSDsqlp') [obj,X,y,Z,info] = HSDsqlp(blk2,At2,C2,b2,OPTIONS); %#ok else [obj,X,y,Z,info] = sdpt3(blk2,At2,C2,b2,OPTIONS); %#ok end obj = -obj; tt = X{numblk+1}(1); theta = X{numblk+1}(2); Xfeas = ops(ops(X(1:numblk),'+',EE(1:numblk),tt),'/',theta); %% if (obj(1) > 0) || (abs(obj(1)) < 1e-8) gp = 1/abs(obj(1)); elseif (obj(2) > 0) gp = 1/obj(2); else gp = 1/exp(mean(log(abs(obj)))); end err = max(info.dimacs([1,3,6])); if (OPTIONS.printlevel) fprintf('\n ******** gp = %3.2e, err = %3.1e\n',gp,err); if (err > 1e-6); fprintf('\n----------------------------------------------------') fprintf('\n gp problem is not solved to sufficient accuracy'); fprintf('\n----------------------------------------------------\n') end end end %%*********************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
sqlparameters.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/sqlparameters.m
5,137
utf_8
76bbd09e284250f7770836baabcc95e5
%%************************************************************************* %% parameters.m: set OPTIONS structure to specify default %% parameters for sqlp.m %% %% OPTIONS.vers : version of direction to use. %% 1 for HKM direction %% 2 for NT direction %% 0 for the default (which uses the HKM direction if %% semidefinite blocks exist; and NT direction of SOCP problms) %% OPTIONS.gam : step-length parameter, %% OPTIONS.predcorr : whether to use Mehrotra predictor-corrector. %% OPTIONS.expon : exponent in decrease of centering parameter sigma. %% OPTIONS.gaptol : tolerance for duality gap as a fraction of the %% value of the objective functions. %% OPTIONS.inftol : tolerance for stopping due to suspicion of %% infeasibility. %% OPTIONS.steptol : toloerance for stopping due to small steps. %% OPTIONS.maxit : maximum number of iteration allowed %% OPTIONS.printlevel : 3, if want to display result in each iteration, %% 2, if want to display only summary, %% 1, if want to display warning message, %% 0, no display at all. %% OPTIONS.stoplevel : 2, if want to automatically detect termination; %% 1, if want to automatically detect termination, but %% restart automatically with a new iterate %% when the algorithm stagnants because of tiny step-lengths. %% 0, if want the algorithm to continue forever except for %% successful completion, maximum number of iterations, or %% numerical failures. Note, do not change this field unless %% you very sure. %% OPTIONS.scale_data : 1, if want to scale the data before solving the problem, %% else = 0 %% OPTIONS.rmdepconstr : 1, if want to remove nearly dependent constraints, %% else = 0. %% OPTIONS.smallblkdim : block-size threshold determining what method to compute the %% schur complement matrix corresponding to semidefintie block. %% NOTE: this number should be small, say less than 20. %% OPTIONS.parbarrier : parameter values of the log-barrier terms in the SQLP problem. %% Default = [], meaning that the parameter values are all 0. %% OPTIONS.schurfun : [], if no user supplied routine to compute the Schur matrix, %% else, it is a cell array where each cell is either [], %% or contains a string that is the file name where the Schur matrix %% of the associated block data is computed. %% For example, if the SQLP data has the block structure %% blk{1,1} = '1'; blk{1,2} = 10; %% blk{2,1} = 's'; blk{2,2} = 50; %% and %% OPTIONS.schurfun{1} = []; %% OPTIONS.schurfun{2} = 'myownschur', where %% 'myownschur' is a function with the calling sequence: %% function schur = myownschur(X2,Z2inv,schurfun_par(2,:)); %% This means that for the first block, the Schur %% matrix is computed by the default method in SDPT3, %% and for the second block, the user supplies the %% routine to compute the associated Schur matrix. %% OPTIONS.schurfun_par: [], if no user supplied routine to compute the Schur matrix, %% else, it is a cell array where the p-th row is either [], %% or is a cell array containing the parameters needed in %% the user supplied Schur routine OPTIONS.schurfun{p}. %% For example, for the block structure described %% above, we may have: %% OPTIONS.schurfun_par{1} = []; %% OPTIONS.schurfun_par{2,1} = par1; %% OPTIONS.schurfun_par{2,2} = par2; %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%************************************************************************* function OPTIONS = sqlparameters OPTIONS.vers = 0; OPTIONS.gam = 0; OPTIONS.predcorr = 1; OPTIONS.expon = 1; OPTIONS.gaptol = 1e-8; OPTIONS.inftol = 1e-8; OPTIONS.steptol = 1e-6; OPTIONS.maxit = 100; OPTIONS.printlevel = 3; OPTIONS.stoplevel = 1; %% do not change this field unless you very sure. OPTIONS.scale_data = 0; OPTIONS.spdensity = 0.4; OPTIONS.rmdepconstr = 0; OPTIONS.smallblkdim = 50; OPTIONS.parbarrier = []; OPTIONS.schurfun = []; OPTIONS.schurfun_par = []; %%*************************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
convertcmpsdp.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/convertcmpsdp.m
3,465
utf_8
6bd9a62cfb0249da5d75665cfb26063b
%%********************************************************* %% convertcmpsdp: convert SDP with complex data into one %% with real data by converting %% %% C - sum_{k=1}^m yk*Ak psd %% to %% [CR,-CI] - sum ykR*[AkR,-AkI] psd %% [CI, CR] [AkI, AkR] %% %% ykI = 0 for k = 1:m %% %% [bblk,AAt,CC,bb] = convertcmpsdp(blk,A,C,b); %% %%********************************************************* function [bblk,AAt,CC,bb,iscmp] = convertcmpsdp(blk,A,C,b) m = length(b); pp = size(A,1); if (pp ~= size(blk,1)) error('blk and A not compatible'); end numblk = size(blk,1); iscmp = zeros(numblk,m+1); for p = 1:size(blk,1) len = size(A(p),2); for k = 1:len if ~isempty(A{p,k}) iscmp(p,k) = 1-isreal(A{p,k}); end end iscmp(p,m+1) = 1-isreal(C{p}); end iscmp = norm(iscmp,'fro'); %% if (iscmp == 0) %% data is real bblk = blk; AAt = A; CC = C; bb = b; return; end %% bb = real(b); bblk = cell(size(blk,1),2); for p = 1:size(blk,1) pblk = blk(p,:); if (size(pblk{2},1) > size(pblk{2},2)) pblk{2} = pblk{2}'; end if strcmp(pblk{1},'s') ss = [0,cumsum(pblk{2})]; ss2 = [0,cumsum(2*pblk{2})]; n = sum(pblk{2}); n2 = sum(pblk{2}.*(pblk{2}+1))/2; AR = cell(1,m); Ctmp = sparse(2*n,2*n); if (size(A{p},1)==n2 && size(A{p},2)==m); Atype = 1; elseif (size(A(p),1)==1 && size(A(p),2)==1); Atype = 2; else error('convertcmp: At is not properly coded'); end for k = 0:m if (k == 0) Ak = C{p}; else if (Atype == 1) Ak = smat(pblk,A{p}(:,k),1); elseif (Atype == 2) Ak = A{p,k}; end end Atmp = sparse(2*n,2*n); if (length(pblk{2}) == 1) tmp = [real(Ak),-imag(Ak); imag(Ak), real(Ak)]; if (k==0) Ctmp = tmp; else Atmp = tmp; end else for j = 1:length(pblk{2}) idx = ss(j)+1: ss(j+1); Akj = Ak(idx,idx); tmp = [real(Akj),-imag(Akj); imag(Akj), real(Akj)]; idx2 = ss2(j)+1: ss2(j+1); if (k==0) Ctmp(idx2,idx2) = tmp; %#ok else Atmp(idx2,idx2) = tmp; %#ok end end end if (k==0); CC{p,1} = Ctmp; %#ok else AR{k} = Atmp; end end bblk{p,1} = 's'; bblk{p,2} = 2*pblk{2}; AAt(p,1) = svec(bblk(p,:),AR); %#ok elseif strcmp(pblk{1},'q'); error('SOCP block with complex data is currently not allowed'); elseif strcmp(pblk{1},'l'); if isreal(A{p}) && isreal(C{p}) bblk(p,:) = blk(p,:); AAt{p,1} = A{p}; CC{p,1} = C{p}; %#ok else error('data for linear block must be real'); end elseif strcmp(pblk{1},'u'); if isreal(A{p}) && isreal(C{p}) bblk(p,:) = blk(p,:); AAt{p,1} = A{p}; CC{p,1} = C{p}; %#ok else error('data for unrestricted block must be real'); end end end %%*********************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
sqlpsummary.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/sqlpsummary.m
4,047
utf_8
78361a4e3dfeaeb73a7102b08ad30733
%%***************************************************************************** %% sqlpsummary: print summary %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%***************************************************************************** function sqlpsummary(info,ttime,infeas_org,printlevel) iter = info.iter; obj = info.obj; gap = info.gap; relgap = info.relgap; prim_infeas = info.pinfeas; dual_infeas = info.dinfeas; termcode = info.termcode; reldist = info.reldist; resid = info.resid; dimacs = info.dimacs; totaltime = info.cputime; %% preproctime = ttime.preproc; pcholtime = ttime.pchol; dcholtime = ttime.dchol; predtime = ttime.pred; pstep_predtime = ttime.pred_pstep; dstep_predtime = ttime.pred_pstep; corrtime = ttime.corr; pstep_corrtime = ttime.corr_pstep; dstep_corrtime = ttime.corr_dstep; misctime = ttime.misc; %% if (printlevel >= 2) fprintf('\n------------------------------------------------'); fprintf('-------------------\n'); fprintf(' number of iterations = %2.0f\n',iter); end if (termcode <= 0) if (printlevel >=2) fprintf(' primal objective value = %- 9.8e\n',obj(1)); fprintf(' dual objective value = %- 9.8e\n',obj(2)); fprintf(' gap := trace(XZ) = %3.2e\n',gap); fprintf(' relative gap = %3.2e\n',relgap); fprintf(' actual relative gap = %3.2e\n',-diff(obj)/(1+sum(abs(obj)))); if ~isempty(infeas_org) fprintf(' rel. primal infeas (scaled problem) = %3.2e\n',prim_infeas); fprintf(' rel. dual " " " = %3.2e\n',dual_infeas); fprintf(' rel. primal infeas (unscaled problem) = %3.2e\n',infeas_org(1)); fprintf(' rel. dual " " " = %3.2e\n',infeas_org(2)); else fprintf(' rel. primal infeas = %3.2e\n',prim_infeas); fprintf(' rel. dual infeas = %3.2e\n',dual_infeas); end fprintf(' norm(X), norm(y), norm(Z) = %3.1e, %3.1e, %3.1e\n',... info.normX,info.normy,info.normZ); fprintf(' norm(A), norm(b), norm(C) = %3.1e, %3.1e, %3.1e\n',... info.normA,info.normb,info.normC); end elseif (termcode == 1) if (printlevel >=2) fprintf(' residual of primal infeasibility \n') fprintf(' certificate (y,Z) = %3.2e\n',resid); fprintf(' reldist to infeas. <= %3.2e\n',reldist); end elseif (termcode == 2) if (printlevel >=2) fprintf(' residual of dual infeasibility \n') fprintf(' certificate X = %3.2e\n',resid); fprintf(' reldist to infeas. <= %3.2e\n',reldist); end end if (printlevel >=2) fprintf(' Total CPU time (secs) = %3.2f \n',totaltime); fprintf(' CPU time per iteration = %3.2f \n',totaltime/iter); fprintf(' termination code = %2.0f\n',termcode); fprintf(' DIMACS: %.1e %.1e %.1e %.1e %.1e %.1e\n',dimacs); fprintf('------------------------------------------------'); fprintf('-------------------\n'); if (printlevel > 3) fprintf(' Percentage of CPU time spent in various parts \n'); fprintf('------------------------------------------------'); fprintf('-------------------\n'); fprintf(' preproc Xchol Zchol pred pred_steplen corr corr_steplen misc\n') tt = [preproctime, pcholtime, dcholtime, predtime, pstep_predtime, dstep_predtime]; tt = [tt, corrtime, pstep_corrtime, dstep_corrtime, misctime]; tt = tt/sum(tt)*100; fprintf(' %3.1f %3.1f %3.1f %3.1f %3.1f %3.1f ',... tt(1),tt(2),tt(3),tt(4),tt(5),tt(6)); fprintf(' %3.1f %3.1f %3.1f %3.1f\n',tt(7),tt(8),tt(9),tt(10)); fprintf('------------------------------------------------'); fprintf('-------------------\n'); end end %%*****************************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
checkdepconstr.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/checkdepconstr.m
6,926
utf_8
186362786fef9d7d3328ab9e5a9e117c
%%***************************************************************************** %% checkdepconst: compute AAt to determine if the %% constraint matrices Ak are linearly independent. %% %% [At,b,y,idxB,neardepconstr,feasible,AAt] = checkdepconstr(blk,At,b,y,rmdepconstr); %% %% rmdepconstr = 1, if want to remove dependent columns in At %% = 0, otherwise. %% %% idxB = indices of linearly independent columns of original At. %% neardepconstr = 1 if there is nearly dependent columns in At %% = 0, otherwise. %% Note: the definition of "nearly dependent" is dependent on the %% threshold used to determine the small diagonal elements in %% the LDLt factorization of A*At. %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%***************************************************************************** function [At,b,y,idxB,neardepconstr,feasible,AAt] = ... checkdepconstr(blk,At,b,y,rmdepconstr) global existlowrank printlevel global nnzmatold %% %% compute AAt %% m = length(b); AAt = sparse(m,m); numdencol = 0; UU = []; for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'s'); m1 = size(At{p,1},2); m2 = m - m1; if (m2 > 0) if (m2 > 0.3*m); AAt = full(AAt); end dd = At{p,3}; lenn = size(dd,1); idxD = [0; find(diff(dd(:,1))); lenn]; ss = [0, cumsum(pblk{3})]; if (existlowrank) AAt(1:m1,1:m1) = AAt(1:m1,1:m1) + At{p,1}'*At{p,1}; %#ok for k = 1:m2 idx = ss(k)+1 : ss(k+1); idx2 = idxD(k)+1: idxD(k+1); ii = dd(idx2,2)-ss(k); %% undo cumulative indexing jj = dd(idx2,3)-ss(k); len = pblk{3}(k); Dk = spconvert([ii,jj,dd(idx2,4); len,len,0]); tmp = svec(pblk,At{p,2}(:,idx)*Dk*At{p,2}(:,idx)'); tmp2 = AAt(1:m1,m1+k) + (tmp'*At{p,1})'; AAt(1:m1,m1+k) = tmp2; %#ok AAt(m1+k,1:m1) = tmp2'; %#ok end end DD = spconvert([dd(:,2:4); sum(pblk{3}),sum(pblk{3}),0]); VtVD = (At{p,2}'*At{p,2})*DD; VtVD2 = VtVD'.*VtVD; for k = 1:m2 idx0 = ss(k)+1 : ss(k+1); %%tmp = VtVD(idx0,:)' .* VtVD(:,idx0); tmp = VtVD2(:,idx0); tmp = tmp*ones(length(idx0),1); tmp3 = AAt(m1+1:m1+m2,m1+k) + mexqops(pblk{3},tmp,ones(length(tmp),1),1); AAt(m1+1:m1+m2,m1+k) = tmp3; %#ok end else AAt = AAt + abs(At{p,1})'*abs(At{p,1}); end else decolidx = checkdense(At{p,1}'); if ~isempty(decolidx); n2 = size(At{p,1},1); dd = ones(n2,1); len= length(decolidx); dd(decolidx) = zeros(len,1); AAt = AAt + (abs(At{p,1})' *spdiags(dd,0,n2,n2)) *abs(At{p,1}); tmp = At{p,1}(decolidx,:)'; UU = [UU, tmp]; %#ok numdencol = numdencol + len; else AAt = AAt + abs(At{p,1})'*abs(At{p,1}); end end end if (numdencol > 0) && (printlevel) fprintf('\n number of dense column in A = %d',numdencol); end numdencol = size(UU,2); %% %% %% feasible = 1; neardepconstr = 0; if ~issparse(AAt); AAt = sparse(AAt); end nnzmatold = mexnnz(AAt); rho = 1e-15; diagAAt = diag(AAt); mexschurfun(AAt,rho*max(diagAAt,1)); [L.R,indef,L.perm] = chol(AAt,'vector'); L.d = full(diag(L.R)).^2; if (indef) msg = 'AAt is not pos. def.'; idxB = 1:m; neardepconstr = 1; if (printlevel); fprintf('\n checkdepconstr: %s',msg); end return; end %% %% find independent rows of A %% dd = zeros(m,1); idxB = (1:m)'; dd(L.perm) = abs(L.d); idxN = find(dd < 1e-13*mean(L.d)); ddB = dd(setdiff(1:m,idxN)); ddN = dd(idxN); if ~isempty(ddN) && ~isempty(ddB) && (min(ddB)/max(ddN) < 10) %% no clear separation of elements in dd %% do not label constraints as dependent idxN = []; end if ~isempty(idxN) neardepconstr = 1; if (printlevel) fprintf('\n number of nearly dependent constraints = %1.0d',length(idxN)); end if (numdencol==0) if (rmdepconstr) idxB = setdiff((1:m)',idxN); if (printlevel) fprintf('\n checkdepconstr: removing dependent constraints...'); end [W,resnorm] = findcoeffsub(blk,At,idxB,idxN); tol = 1e-8; if (resnorm > sqrt(tol)) idxB = (1:m)'; neardepconstr = 0; if (printlevel) fprintf('\n checkdepconstr: basis rows cannot be reliably identified,'); fprintf(' abort removing nearly dependent constraints'); end return; end tmp = W'*b(idxB) - b(idxN); nnorm = norm(tmp)/max(1,norm(b)); if (nnorm > tol) feasible = 0; if (printlevel) fprintf('\n checkdepconstr: inconsistent constraints exist,'); fprintf(' problem is infeasible.'); end else feasible = 1; for p = 1:size(blk,1) At{p,1} = At{p,1}(:,idxB); end b = b(idxB); y = y(idxB); AAt = AAt(idxB,idxB); end else if (printlevel) fprintf('\n To remove these constraints,'); fprintf(' re-run sqlp.m with OPTIONS.rmdepconstr = 1.'); end end else if (printlevel) fprintf('\n warning: the sparse part of AAt may be nearly singular.'); end end end %%***************************************************************************** %% findcoeffsub: %% %% [W,resnorm] = findcoeffsub(blk,At,idXB,idXN); %% %% idXB = indices of independent columns of At. %% idxN = indices of dependent columns of At. %% %% AB = At(:,idxB); AN = At(:,idxN) = AB*W %% %% SDPT3: version 3.0 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last modified: 2 Feb 01 %%***************************************************************************** function [W,resnorm] = findcoeffsub(blk,At,idxB,idxN) AB = []; AN = []; for p = 1:size(blk,1) AB = [AB; At{p,1}(:,idxB)]; %#ok AN = [AN; At{p,1}(:,idxN)]; %#ok end n = size(AB,2); %% %%----------------------------------------- %% find W so that AN = AB*W %%----------------------------------------- %% [L,U,P,Q] = lu(sparse(AB)); rhs = P*AN; Lhat = L(1:n,:); W = Q*( U \ (Lhat \ rhs(1:n,:))); resnorm = norm(AN-AB*W,'fro')/max(1,norm(AN,'fro')); %%*****************************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
convertRcone.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/convertRcone.m
948
utf_8
afa3b210699dbf796a257cb53e92ef0d
%%*************************************************************** %% convertRcone: convert rotated cone to socp cone %% %% [blk,At,C,b,T] = convertRcone(blk,At,C,b); %% %%*************************************************************** function [blk,At,C,b,T] = convertRcone(blk,At,C,b) T = cell(size(blk,1),1); for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'r') if (min(pblk{2}) < 3) error('rotated cones must be at least 3-dimensional'); end n = sum(pblk{2}); len = length(pblk{2}); ss = [0,cumsum(pblk{2})]; idx = 1+ss(1:len)'; ir2 = 1/sqrt(2)*ones(len,1); dd = [idx,idx,ir2-1; idx,idx+1,ir2; idx+1,idx,ir2; idx+1,idx+1,-ir2-1]; T{p} = speye(n,n) + spconvert([dd; n,n,0]); blk{p,1} = 'q'; At{p,1} = T{p}*At{p,1}; C{p,1} = T{p}*C{p,1}; end end %%***************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
qops.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/qops.m
1,421
utf_8
bddd4e93643ef0eb5b6868ef41d2bec7
%%******************************************************** %% qops: Fu = qops(pblk,w,f,options,u); %% %% options = 1, Fu(i) = <wi,fi> %% = 2, Fu(i) = 2*wi(1)*fi(1)-<wi,fi> %% = 3, Fui = w(i)*fi %% = 4, Fui = w(i)*fi, Fui(1) = -Fui(1). %% options = 5, Fu = w [ f'*u ; ub + fb*alp ], where %% alp = (f'*u + u0)/(1+f0); %% options = 6, compute Finv*u. %% %% Note F = w [f0 fb'; fb I+ fb*fb'/(1+f0) ], where %% f0*f0 - fb*fb' = 1. %% Finv = (1/w) [f0 -fb'; -fb I+ fb*fb'/(1+f0) ]. %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%******************************************************** function Fu = qops(pblk,w,f,options,u) if (options >= 1 && options <= 4) Fu = mexqops(pblk{2},w,f,options); elseif (options == 5) s = 1 + [0 cumsum(pblk{2})]; idx1 = s(1:length(pblk{2})); inprod = mexqops(pblk{2},f,u,1); tmp = (u(idx1)+inprod)./(1+f(idx1)); Fu = u + mexqops(pblk{2},tmp,f,3); Fu(idx1) = inprod; Fu = mexqops(pblk{2},w,Fu,3); elseif (options == 6) s = 1 + [0 cumsum(pblk{2})]; idx1 = s(1:length(pblk{2})); gamprod = mexqops(pblk{2},f,u,2); tmp = (u(idx1)+gamprod)./(1+f(idx1)); Fu = u - mexqops(pblk{2},tmp,f,3); Fu(idx1) = gamprod; Fu = mexqops(pblk{2},1./w,Fu,3); end %%********************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
HKMdirfun.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/HKMdirfun.m
1,703
utf_8
2e90b8de8daed6f5a9a6894232dbff6a
%%******************************************************************* %% HKMdirfun: compute (dX,dZ), given dy, for the HKM direction. %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%******************************************************************* function [dX,dy,dZ] = HKMdirfun(blk,At,par,Rd,EinvRc,X,xx,m) global solve_ok dX = cell(size(blk,1),1); dZ = cell(size(blk,1),1); dy = []; if (any(isnan(xx)) || any(isinf(xx))) solve_ok = 0; fprintf('\n linsysolve: solution contains NaN or inf'); return; end %% dy = xx(1:m); count = m; %% for p=1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'l') %%dZ{p} = Rd{p} - At{p}*dy; dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy)); dX{p} = EinvRc{p} - par.dd{p}.*dZ{p}; elseif strcmp(pblk{1},'q') %%dZ{p} = Rd{p} - At{p}*dy; dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy)); tmp = par.dd{p}.*dZ{p} ... + qops(pblk,qops(pblk,dZ{p},par.Zinv{p},1),X{p},3) ... + qops(pblk,qops(pblk,dZ{p},X{p},1),par.Zinv{p},3); dX{p} = EinvRc{p} - tmp; elseif strcmp(pblk{1},'s') %%dZ{p} = Rd{p} -smat(pblk,At{p}*dy(par.permA(p,:)),par.isspAy(p)); dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),par.permA(p,:),par.isspAy(p),dy)); tmp = Prod3(pblk,X{p},dZ{p},par.Zinv{p},0); tmp = 0.5*(tmp+tmp'); dX{p} = EinvRc{p}-tmp; elseif strcmp(pblk{1},'u'); n = sum(pblk{2}); dZ{p} = zeros(n,1); dX{p} = xx(count+1:count+n); count = count + n; end end %%*******************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
symqmr.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/symqmr.m
3,957
utf_8
bf28cb72305cb0378a7b572d42f39ff6
%%************************************************************************* %% symqmr: symmetric QMR with left (symmetric) preconditioner. %% The preconditioner used is based on the analytical %% expression of inv(A). %% %% [x,resnrm,solve_ok] = symqmr(A,b,L,tol,maxit) %% %% child function: linsysolvefun.m %% %% A = [mat11 mat12; mat12' mat22]. %% b = rhs vector. %% if matfct_options = 'chol' or 'spchol' %% L = Cholesky factorization of (1,1) block. %% M = Cholesky factorization of %% Schur complement of A ( = mat12'*inv(mat11)*mat12-mat22). %% else %% L = triangular factors of A. %% M = not relevant. %% end %% resnrm = norm of qmr-generated residual vector b-Ax. %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%************************************************************************* function [xx,resnrm,solve_ok] = symqmr(A,b,L,tol,maxit,printlevel) N = length(b); if (nargin < 6); printlevel = 1; end if (nargin < 5) || isempty(maxit); maxit = max(30,length(A.mat22)); end; if (nargin < 4) || isempty(tol); tol = 1e-10; end; tolb = min(1e-4,tol*norm(b)); solve_ok = 1; x = zeros(N,1); if (norm(x)) if isstruct(A); Aq = matvec(A,x); else Aq=A*x; end; r = b-Aq; else r = b; end err = norm(r); resnrm(1) = err; minres = err; xx = x; if (err < 1e-3*tolb); return; end q = precond(A,L,r); tau_old = norm(q); rho_old = r'*q; theta_old = 0; d = zeros(N,1); res = r; Ad = zeros(N,1); %% %% main loop %% tiny = 1e-30; for iter = 1:maxit if isstruct(A); Aq = matvec(A,q); else Aq=A*q; end; sigma = q'*Aq; if (abs(sigma) < tiny) solve_ok = 2; if (printlevel); fprintf('*'); end; break; else alpha = rho_old/sigma; r = r - alpha*Aq; end u = precond(A,L,r); theta = norm(u)/tau_old; c = 1/sqrt(1+theta^2); tau = tau_old*theta*c; gam = (c^2*theta_old^2); eta = (c^2*alpha); d = gam*d + eta*q; x = x + d; %% Ad = gam*Ad + eta*Aq; res = res - Ad; err = norm(res); resnrm(iter+1) = err; %#ok if (err < minres); xx = x; minres = err; end if (err < tolb); break; end if (iter > 10) if (err > 0.98*mean(resnrm(iter-10:iter))) solve_ok = 0.5; break; end end %% if (abs(rho_old) < tiny) solve_ok = 2; if (printlevel); fprintf('*'); end; break; else rho = r'*u; beta = rho/rho_old; q = u + beta*q; end rho_old = rho; tau_old = tau; theta_old = theta; end if (iter == maxit); solve_ok = 0.3; end; %% %%************************************************************************* %% precond: %%************************************************************************* function Mx = precond(A,L,x) m = L.matdim; m2 = length(x)-m; Mx = zeros(length(x),1); for iter = 1:1 if norm(Mx); r = full(x - matvec(A,Mx)); else r = full(x); end r1 = r(1:m); if (m2 > 0) r2 = r(m+1:m+m2); w = linsysolvefun(L,r1); z = mexMatvec(A.mat12,w,1) - r2; z = L.Mu \ (L.Ml \ (L.Mp*z)); r1 = r1 - mexMatvec(A.mat12,z); end d = linsysolvefun(L,r1); if (m2 > 0) d = [d; z]; %#ok end Mx = Mx + d; end %%************************************************************************* %% matvec: matrix-vector multiply. %% matrix = [A.mat11, A.mat12; A.mat12', A.mat22] %%************************************************************************* function Ax = matvec(A,x) m = length(A.mat11); m2 = length(x)-m; if issparse(x); x = full(x); end if (m2 > 0) x1 = x(1:m); else x1 = x; end Ax = mexMatvec(A.mat11,x1); if (m2 > 0) x2 = x(m+1:m+m2); Ax = Ax + mexMatvec(A.mat12,x2); Ax2 = mexMatvec(A.mat12,x1,1) + mexMatvec(A.mat22,x2); Ax = [full(Ax); full(Ax2)]; end %%*************************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
validate_startpoint.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/validate_startpoint.m
3,067
utf_8
572146bf8639c3d5066b6a790bca3ba8
%%*********************************************************************** %% validate_startpoint: validate_startpoint starting point X0,y0,Z0 %% %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%*********************************************************************** function [X0,Z0] = validate_startpoint(blk,X0,Z0,spdensity,iscmp) if (nargin < 5); iscmp = 0; end if (nargin < 4); spdensity = 0.4; end %% if ~iscell(X0) || ~iscell(Z0); error('validate_startpoint: X0, Z0 must be cell arrays'); end if (min(size(X0))~=1 || min(size(Z0))~=1); error('validate_startpoint: cell array X, Z can only have 1 column or row'); end if (size(X0,2) > size(X0,1)); X0 = X0'; end; if (size(Z0,2) > size(Z0,1)); Z0 = Z0'; end; for p = 1:size(blk,1) pblk = blk(p,:); n = sum(pblk{2}); n2 = sum(pblk{2}.*pblk{2}); numblk = length(pblk{2}); if strcmp(pblk{1},'s'); if (iscmp) X0{p} = [real(X0{p}),-imag(X0{p}); imag(X0{p}), real(X0{p})]; Z0{p} = [real(Z0{p}),-imag(Z0{p}); imag(Z0{p}), real(Z0{p})]; end if ~all(size(X0{p}) == n) || ~all(size(Z0{p}) == n); error('validate_startpoint: blk and X0,Z0 are not compatible'); end if (norm([X0{p}-X0{p}' Z0{p}-Z0{p}'],inf) > 2e-13); error('validate_startpoint: X0,Z0 not symmetric'); end if (nnz(X0{p}) < spdensity*n2) || (numblk > 1) ; if ~issparse(X0{p}); X0{p} = sparse(X0{p}); end; else if issparse(X0{p}); X0{p} = full(X0{p}); end; end if (nnz(Z0{p}) < spdensity*n2) || (numblk > 1); if ~issparse(Z0{p}); Z0{p} = sparse(Z0{p}); end; else if issparse(Z0{p}); Z0{p} = full(Z0{p}); end; end elseif strcmp(pblk{1},'q') || strcmp(pblk{1},'l') || strcmp(pblk{1},'u'); if ~all([size(X0{p},2) size(Z0{p},2)]==1); error(['validate_startpoint: ',num2str(p),... '-th block of X0,Z0 must be column vectors']); end if ~all([size(X0{p},1) size(Z0{p},1)]==n); error('validate_startpoint: blk, and X0,Z0, are not compatible'); end if (nnz(X0{p}) < spdensity*n); if ~issparse(X0{p}); X0{p} = sparse(X0{p}); end; else if issparse(X0{p}); X0{p} = full(X0{p}); end; end if (nnz(Z0{p}) < spdensity*n); if ~issparse(Z0{p}); Z0{p} = sparse(Z0{p}); end; else if issparse(Z0{p}); Z0{p} = full(Z0{p}); end; end if strcmp(pblk{1},'l') && (any(X0{p} < 1e-12) || any(Z0{p} < 1e-12)) error('X0 or Z0 is not in nonnegative cone'); end if strcmp(pblk{1},'q'); s = 1+[0, cumsum(pblk{2})]; len = length(pblk{2}); if any(X0{p}(s(1:len)) < 1e-12) || any(Z0{p}(s(1:len)) < 1e-12) error('X0 or Z0 is not in socp cone'); end end end end %%***********************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
Atyfun.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/Atyfun.m
1,471
utf_8
5af173811d5528ab49ca2a48bd4748ce
%%********************************************************* %% Atyfun: compute sum_{k=1}^m yk*Ak. %% %% Q = Atyfun(blk,At,permA,isspAy,y); %% %% Note: permA and isspAy may be set to []. %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%********************************************************** function Q = Atyfun(blk,At,permA,isspAy,y) if isempty(permA); ismtpermA = 1; else ismtpermA = 0; end Q = cell(size(blk,1),1); if isempty(isspAy); isspAy = ones(size(blk,1),1); end for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'s') n = sum(pblk{2}); m1 = size(At{p,1},2); if (~isempty(At{p,1})) if (ismtpermA) tmp = At{p,1}*y(1:m1); else tmp = At{p,1}*y(permA(p,1:m1),1); end Q{p} = smat(pblk,tmp,isspAy(p)); else Q{p} = sparse(n,n); end if (length(pblk) > 2) %% for low rank constraints len = sum(pblk{3}); m2 = length(pblk{3}); y2 = y(m1+1:m1+m2); dd = At{p,3}; idxD = [0; find(diff(dd(:,1))); size(dd,1)]; yy2 = mexexpand(diff(idxD),y2); DD = spconvert([dd(:,2:3),dd(:,4).*yy2; len,len,0]); Q{p} = Q{p} + At{p,2}*DD*At{p,2}'; end else Q{p} = At{p,1}*y; end end %%*********************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
blkcholfun.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/blkcholfun.m
1,247
utf_8
6d78842d748fad818d79a003e1238916
%%****************************************************************** %% blkcholfun: compute Cholesky factorization of X. %% %% [Xchol,indef] = blkcholfun(blk,X,permX); %% %% X = Xchol'*Xchol; %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%****************************************************************** function [Xchol,indef] = blkcholfun(blk,X,permX) if (nargin == 2); permX = []; end; if ~iscell(X); indef = 0; if strcmp(blk{1},'s'); if isempty(permX) || ~issparse(X); [Xchol,indef] = chol(X); else [tmp,indef] = chol(X(permX,permX)); Xchol(:,permX) = tmp; end elseif strcmp(blk{1},'q') gamx = qops(blk,X,X,2); if any(gamx <= 0) indef = 1; end Xchol = []; elseif strcmp(blk{1},'l'); if any(X <= 0) indef = 1; end Xchol = []; elseif strcmp(blk{1},'u') Xchol = []; end else Xchol = cell(size(X)); for p = 1:size(blk,1) [Xchol{p},indef(p)] = blkcholfun(blk(p,:),X{p}); %#ok end indef = max(indef); end %%=================================================================
github
anantsrivastava30/SUVR-PET-ADNI-master
smat.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/smat.m
880
utf_8
184f4081013cebeae6150a22b224ebf9
%%********************************************************* %% smat: compute the matrix smat(x). %% %% M = smat(blk,x,isspM); %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%********************************************************** function M = smat(blk,xvec,isspM) if (nargin < 3); isspM = zeros(size(blk,1),1); end %% if ~iscell(xvec) if strcmp(blk{1},'s') M = mexsmat(blk,xvec,isspM); else M = xvec; end else M = cell(size(blk,1),1); if (length(isspM)==1) isspM = isspM*ones(size(blk,1),1); end for p=1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'s'); M{p} = mexsmat(pblk,xvec{p},isspM(p)); else M{p} = xvec{p}; end end end %%*********************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
sqlpcheckconvg.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/sqlpcheckconvg.m
8,298
utf_8
6acb41aefb05d5a53dbd501dabab2b33
%%***************************************************************************** %% sqlpcheckconvg: check convergence. %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%***************************************************************************** function [param,breakyes,restart,msg] = sqlpcheckconvg(param,runhist) termcode = param.termcode; iter = param.iter; obj = param.obj; relgap = param.relgap; gap = param.gap; prim_infeas = param.prim_infeas; dual_infeas = param.dual_infeas; mu = param.mu; % homrp = param.homrp; % homRd = param.homRd; prim_infeas_bad = param.prim_infeas_bad; dual_infeas_bad = param.dual_infeas_bad; if (iter > 15) prim_infeas_min = min(param.prim_infeas_min, max(prim_infeas,1e-10)); dual_infeas_min = min(param.dual_infeas_min, max(dual_infeas,1e-10)); else prim_infeas_min = inf; dual_infeas_min = inf; end printlevel = param.printlevel; stoplevel = param.stoplevel; ublksize = param.ublksize; use_LU = param.use_LU; numpertdiagschur = param.numpertdiagschur; infeas = max(prim_infeas,dual_infeas); restart = 0; breakyes = 0; msg = []; %% if (param.normX > 1e15*param.normX0 || param.normZ > 1e15*param.normZ0) termcode = 3; breakyes = 1; end err = max(infeas,relgap); idx = max(2,iter-9): iter+1; pratio = (1-runhist.pinfeas(idx)./runhist.pinfeas(idx-1))./runhist.pstep(idx); dratio = (1-runhist.dinfeas(idx)./runhist.dinfeas(idx-1))./runhist.dstep(idx); if (param.homRd < 0.1*sqrt(err*max(param.inftol,1e-13))) ... && (iter > 30 || termcode==3) && (mean(abs(dratio-1)) > 0.5) termcode = 1; breakyes = 1; end if (param.homrp < 0.1*sqrt(err*max(param.inftol,1e-13))) ... && (iter > 30 || termcode==3) && (mean(abs(pratio-1)) > 0.5) termcode = 2; breakyes = 1; end if (stoplevel) && (iter > 2) && (~breakyes) prim_infeas_bad = ... + (prim_infeas > max(1e-10,1e2*prim_infeas_min) && (prim_infeas_min < 1e-2)) ... + (prim_infeas > prod(1.5-runhist.step(iter+1:iter-1))*runhist.pinfeas(iter-2)); dual_infeas_bad = ... + (dual_infeas > max(1e-8,1e3*dual_infeas_min) && (dual_infeas_min < 1e-2)); if (mu < 1e-8) || (use_LU) idx = max(1,iter-1): iter; elseif (mu < 1e-4); idx = max(1,iter-2): iter; else idx = max(1,iter-3): iter; end gap_progress_bad = (infeas < 1e-4) && (relgap < 5e-3) ... && (gap > 0.9*exp(mean(log(runhist.gap(idx))))); gap_progress_bad2 = (infeas < 1e-4) && (relgap < 1) ... && (gap > 0.95*exp(mean(log(runhist.gap(idx))))); gap_ratio = runhist.gap(idx+1)./runhist.gap(idx); idxtmp = max(1,iter-4): iter; gap_ratio_tmp = runhist.gap(idxtmp+1)./runhist.gap(idxtmp); gap_slowrate = min(0.8,max(0.6,2*mean(gap_ratio_tmp))); idx2 = max(1,iter-10): iter; gap_ratio2 = runhist.gap(idx2+1)./runhist.gap(idx2); gap_slow = all(gap_ratio > gap_slowrate); gap_slow2 = all(gap_ratio2 > gap_slowrate); if (iter > 20) && (infeas < 1e-4 || prim_infeas_bad) ... && (max(infeas,relgap) < 1) ... && ~(min(runhist.step(idx)) > 0.2 && ublksize) if (gap_slow && prim_infeas_bad && (relgap < 1e-3)) ... || (gap_slow2 && prim_infeas_bad && ublksize && (runhist.step(iter+1) > 0.2)) msg = 'stop: progress is too slow'; if (printlevel); fprintf('\n %s',msg); end termcode = -5; breakyes = 1; elseif (max(infeas,relgap) < 1e-2) && (prim_infeas_bad) if (relgap < max(0.2*prim_infeas,1e-2*dual_infeas)) msg = 'stop: relative gap < infeasibility'; if (printlevel); fprintf('\n %s',msg); end termcode = -1; breakyes = 1; end end end if (iter > 20) && (gap_progress_bad) ... && (prim_infeas_bad || any(runhist.step(idx) > 0.5)) msg = 'stop: progress is bad'; if (printlevel); fprintf('\n %s',msg); end termcode = -5; breakyes = 1; end if (iter > 20) && (gap_progress_bad2) ... && (numpertdiagschur > 10); msg = 'stop: progress is bad'; if (printlevel); fprintf('\n %s',msg); end termcode = -5; breakyes = 1; end if (iter > 30) && (prim_infeas_bad) && (gap_slow) && (relgap < 1e-3) ... && (dual_infeas < 1e-5) && ~(min(runhist.step(idx)) > 0.2 && ublksize) msg = 'stop: progress is bad*'; if (printlevel); fprintf('\n %s',msg); end termcode = -5; breakyes = 1; end if (iter > 30) && (dual_infeas_bad) && (relgap < 1e-3) ... && (dual_infeas < 1e-5) ... && ~(min(runhist.step(idx)) > 0.2 && ublksize) %#ok msg = 'stop: dual infeas has deteriorated too much'; if (printlevel); fprintf('\n %s',msg); end termcode = -5; breakyes = 1; end if (iter > 50) && (prim_infeas/runhist.pinfeas(1) < 1e-6) ... && (dual_infeas/runhist.dinfeas(1) > 1e-3) ... && (runhist.step(iter+1) > 0.2) && (relgap > 1e-3) msg = 'stop: lack of progress in dual infeas'; if (printlevel); fprintf('\n %s, homrp=%2.1e',msg,param.homrp); end termcode = -5; breakyes = 1; end if (iter > 50) && (dual_infeas/runhist.dinfeas(1) < 1e-6) ... && (prim_infeas/runhist.pinfeas(1) > 1e-3) ... && (runhist.step(iter+1) > 0.2) && (relgap > 1e-3) msg = 'stop: lack of progress in primal infeas'; if (printlevel); fprintf('\n %s, homRd=%2.1e',msg,param.homRd); end termcode = -5; breakyes = 1; end if (min(runhist.infeas) < 1e-4 || (prim_infeas_bad && iter > 10)) ... && (max(runhist.infeas) > 1e-5) || (iter > 20) relgap2 = abs(diff(obj))/(1+sum(abs(obj))); if (relgap2 < 1e-3); step_short = all(runhist.step(iter:iter+1) < 0.05) ; elseif (relgap2 < 1) || (use_LU) idx = max(1,iter-3): iter+1; step_short = all(runhist.step(idx) < 0.03); else step_short = 0; end if (step_short) && (relgap2 < 1e-2) msg = 'stop: steps too short consecutively'; if (printlevel); fprintf('\n %s',msg); end termcode = -5; breakyes = 1; end end if (iter > 3 && iter < 20) && (infeas > 1) ... && (min(param.homrp,param.homRd) > min(1e-8,param.inftol)) ... && (max(runhist.step(max(1,iter-3):iter+1)) < 1e-3) if (stoplevel == 2) msg = 'stop: steps too short consecutively*'; if (printlevel) fprintf('\n *** Too many tiny steps, advisable to restart'); fprintf(' with the following iterate.') fprintf('\n *** Suggestion: [X0,y0,Z0] = infeaspt(blk,At,C,b,2,1e5);'); fprintf('\n %s',msg); end termcode = -5; breakyes = 1; elseif (stoplevel == 3) msg = 'stop: steps too short consecutively*'; if (printlevel) fprintf('\n *** Too many tiny steps even') fprintf(' after restarting'); fprintf('\n %s',msg); end termcode = -5; breakyes = 1; else if (printlevel) fprintf('\n *** Too many tiny steps:') fprintf(' restarting with the following iterate.') fprintf('\n *** [X,y,Z] = infeaspt(blk,At,C,b,2,1e5);'); end prim_infeas_min = 1e20; prim_infeas_bad = 0; restart = 1; end end end if (max(relgap,infeas) < param.gaptol) msg = sprintf('stop: max(relative gap, infeasibilities) < %3.2e',param.gaptol); if (printlevel); fprintf('\n %s',msg); end termcode = 0; breakyes = 1; end %% param.prim_infeas_bad = prim_infeas_bad; param.prim_infeas_min = prim_infeas_min; param.dual_infeas_bad = dual_infeas_bad; param.dual_infeas_min = dual_infeas_min; param.termcode = termcode; %%**************************************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
SDPT3soln_SEDUMIsoln.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/SDPT3soln_SEDUMIsoln.m
2,743
utf_8
1f7236a38116d782e7084afc40e90a10
%%********************************************************** %% SDPT3soln_SEDUMIsoln: convert SQLP solution in SDPT3 format to %% SeDuMi format %% %% [xx,yy,zz] = SDPT3soln_SEDUMIsoln(blk,X,y,Z,perm); %% %% usage: load SEDUMI_data_file (containing say, A,b,c,K) %% [blk,At,C,b,perm] = read_sedumi(A,b,c,K); %% [obj,X,y,Z] = sdpt3(blk,At,C,b); %% [xx,yy,zz] = SDPT3soln_SEDUMIsoln(blk,X,y,Z,perm); %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%********************************************************** function [xx,yy,zz] = SDPT3soln_SEDUMIsoln(blk,X,y,Z,perm) yy = y; xx = []; zz = []; %% %% extract unrestricted blk %% for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'u') xx = [xx; X{p,1}]; %#ok zz = [zz; Z{p,1}]; %#ok end end %% %% extract linear blk %% for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'l') xx = [xx; X{p,1}]; %#ok zz = [zz; Z{p,1}]; %#ok end end %% %% extract second order cone blk %% for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'q') xx = [xx; X{p,1}]; %#ok zz = [zz; Z{p,1}]; %#ok end end %% %% extract rotated cone blk %% for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'r') xx = [xx; X{p,1}]; %#ok zz = [zz; Z{p,1}]; %#ok end end %% %% extract semidefinite cone blk %% per = []; len = 0; for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'s') sblk(p) = length(pblk{2}); %#ok per = [per, perm{p}]; %#ok len = len + sum(pblk{2}.*pblk{2}); end end sblk = sum(sblk); cnt = 1; Xsblk = cell(sblk,1); Zsblk = cell(sblk,1); for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'s') ss = [0,cumsum(pblk{2})]; numblk = length(pblk{2}); Xp = X{p,1}; Zp = Z{p,1}; for tt = 1:numblk if (numblk > 1) idx = ss(tt)+1: ss(tt+1); Xsblk{cnt} = full(Xp(idx,idx)); Zsblk{cnt} = full(Zp(idx,idx)); else Xsblk{cnt} = Xp; Zsblk{cnt} = Zp; end cnt = cnt + 1; end end end if ~isempty(per) Xsblk(per) = Xsblk; Zsblk(per) = Zsblk; xtmp = zeros(len,1); ztmp = zeros(len,1); cnt = 0; for p = 1:sblk if strcmp(pblk{1},'s') idx = 1:length(Xsblk{p})^2; xtmp(cnt+idx) = Xsblk{p}(:); ztmp(cnt+idx) = Zsblk{p}(:); cnt = cnt + length(idx); end end xx = [xx; xtmp]; zz = [zz; ztmp]; end %%**********************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
detect_ublk.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/detect_ublk.m
2,815
utf_8
819f087d73a97e1717b952ca2f3a407d
%%******************************************************************* %% detect_ublk: search for implied free variables in linear %% block. %% [blk2,At2,C2,ublkinfo] = detect_ublk(blk,At,C); %% %% i1,i2: indices corresponding to splitting of unrestricted varaibles %% i3 : remaining indices in the linear block %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%******************************************************************* function [blk2,At2,C2,ublkinfo,parbarrier2,X2,Z2] = ... detect_ublk(blk,At,C,parbarrier,X,Z,printlevel) if (nargin < 7); printlevel = 1; end blk2 = blk; At2 = At; C2 = C; if (nargin >= 6) parbarrier2 = parbarrier; X2 = X; Z2 = Z; else X2 = []; Z2 = []; end numblk = size(blk,1); ublkinfo = cell(size(blk,1),3); tol = 1e-14; %% numblknew = numblk; %% for p = 1:numblk pblk = blk(p,:); m = size(At{p},2); if strcmp(pblk{1},'l') r = randmat(1,m,0,'n'); % stime = cputime; Ap = At{p}'; Cp = C{p}; ApTr = (r*Ap)'; [sApTr,perm] = sort(abs(ApTr)); idx0 = find(abs(diff(sApTr)) < tol); if ~isempty(idx0) n = pblk{2}; i1 = perm(idx0); i2 = perm(idx0+1); Api1 = Ap(:,i1); Api2 = Ap(:,i2); Cpi1 = Cp(i1)'; Cpi2 = Cp(i2)'; idxzr = abs(Cpi1+Cpi2) < tol & sum(abs(Api1+Api2),1) < tol; if any(idxzr) i1 = i1(idxzr'); i2 = i2(idxzr'); blk2{p,1} = 'u'; blk2{p,2} = length(i1); At2{p} = Ap(:,i1)'; C2{p} = Cp(i1); if (printlevel) fprintf('\n %1.0d linear variables from unrestricted variable.\n',... 2*length(i1)); end if (nargin >= 6) parbarrier2{p} = parbarrier{p}(i1); X2{p} = X{p}(i1)-X{p}(i2); Z2{p} = zeros(length(i1),1); end i3 = setdiff(1:n,union(i1,i2)); if ~isempty(i3) numblknew = numblknew + 1; blk2{numblknew,1} = 'l'; blk2{numblknew,2} = length(i3); At2{numblknew,1} = Ap(:,i3)'; C2{numblknew,1} = Cp(i3); if (nargin >= 6) parbarrier2{numblknew,1} = parbarrier{p}(i3); X2{numblknew,1} = X{p}(i3); Z2{numblknew,1} = Z{p}(i3); end end ublkinfo{p,1} = i1; ublkinfo{p,2} = i2; ublkinfo{p,3} = i3; end end end end %%*******************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
combine_blk.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/combine_blk.m
2,358
utf_8
205279faec8f7b11c04bc75707a6eb77
%%******************************************************************* %% combine_blk: combine small SDP blocks together, %% combine all SOCP blocks together, etc %% %% [blk2,At2,C2,blkinfo] = combine_blk(blk,At,C); %% %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%******************************************************************* function [blk2,At2,C2,blkinfo] = combine_blk(blk,At,C) blkinfo = zeros(size(blk,1),1); for p = 1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'s') if (sum(pblk{2}) < 100) blkinfo(p) = 1; end elseif strcmp(pblk{1},'q') blkinfo(p) = 2; elseif strcmp(pblk{1},'r') blkinfo(p) = 3; elseif strcmp(pblk{1},'l') blkinfo(p) = 4; elseif strcmp(pblk{1},'u') blkinfo(p) = 5; end end numblk0 = length(find(blkinfo == 0)); numblk = numblk0 + length(union(blkinfo(blkinfo > 0),[])); blk2 = cell(numblk,2); At2 = cell(numblk,1); C2 = cell(numblk,1); cnt = 0; idx = find(blkinfo==0); %% larger SDP blocks if ~isempty(idx) len = length(idx); blk2(1:len,:) = blk(idx,:); At2(1:len) = At(idx); C2(1:len) = C(idx); cnt = len; end idx = find(blkinfo==1); %% smaller SDP blocks Ctmp = []; idxstart = 0; if ~isempty(idx) cnt = cnt + 1; blk2{cnt,1} = 's'; blk2{cnt,2} = []; len = length(idx); for k = 1:len blk2{cnt,2} = [blk2{cnt,2}, blk{idx(k),2}]; At2{cnt} = [At2{cnt}; At{idx(k)}]; [ii,jj,vv] = find(C{idx(k)}); Ctmp = [Ctmp; [idxstart+ii,idxstart+jj,vv]]; %#ok idxstart = idxstart + sum(blk{idx(k),2}); end end n = sum(blk2{cnt,2}); C2{cnt} = spconvert([Ctmp; n,n,0]); %% for L = 2:5 idx = find(blkinfo==L); if ~isempty(idx) cnt = cnt + 1; if (L==2) blk2{cnt,1} = 'q'; elseif (L==3) blk2{cnt,1} = 'r'; elseif (L==4) blk2{cnt,1} = 'l'; elseif (L==5) blk2{cnt,1} = 'u'; end blk2{cnt,2} = []; len = length(idx); for k = 1:len blk2{cnt,2} = [blk2{cnt,2}, blk{idx(k),2}]; At2{cnt} = [At2{cnt}; At{idx(k)}]; C2{cnt} = [C2{cnt}; C{idx(k)}]; end end end %%*******************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
Prod2.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/Prod2.m
1,882
utf_8
b291dcf07608872ed75bd82e48ff0b54
%%******************************************************************* %% Prod2: compute the block diagonal matrix A*B %% %% C = Prod2(blk,A,B,options); %% %% INPUT: blk = a cell array describing the block structure of A and B %% A,B = square matrices or column vectors. %% %% options = 0 if no special structure %% 1 if C is symmetric %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%******************************************************************* function C = Prod2(blk,A,B,options) global spdensity if (nargin == 3); options = 0; end; iscellA = iscell(A); iscellB = iscell(B); %% if (~iscellA && ~iscellB) if (size(blk,1) > 1); error('Prod2: blk and A,B are not compatible'); end; if strcmp(blk{1},'s') numblk = length(blk{2}); isspA = issparse(A); isspB = issparse(B); if (numblk > 1) if ~isspA; A=sparse(A); isspA=1; end if ~isspB; B=sparse(B); isspB=1; end end %%use_matlab = (options==0 && ~isspA && ~isspB) || (isspA && isspB); use_matlab = (~isspA && ~isspB) || (isspA && isspB); if (use_matlab) C = A*B; if (options==1); C = 0.5*(C+C'); end; else C = mexProd2(blk,A,B,options); end checksparse = (numblk==1) && (isspA || isspB); if (checksparse) n2 = sum(blk{2}.*blk{2}); if (mexnnz(C) <= spdensity*n2); if ~issparse(C); C = sparse(C); end; else if issparse(C); C = full(C); end; end end elseif (strcmp(blk{1},'q') || strcmp(blk{1},'l') || strcmp(blk{1},'u')) C = A.*B; end else error('Prod2: A,B must be matrices'); end %%*******************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
NTdirfun.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sdpt3/Solver/NTdirfun.m
1,614
utf_8
a236e4d45e59db8824375b14ed6090a1
%%******************************************************************* %% NTdirfun: compute (dX,dZ), given dy, for the NT direction. %% %% SDPT3: version 3.1 %% Copyright (c) 1997 by %% K.C. Toh, M.J. Todd, R.H. Tutuncu %% Last Modified: 16 Sep 2004 %%******************************************************************* function [dX,dy,dZ] = NTdirfun(blk,At,par,Rd,EinvRc,xx,m) global solve_ok dX = cell(size(blk,1),1); dZ = cell(size(blk,1),1); dy = []; if (any(isnan(xx)) || any(isinf(xx))) solve_ok = 0; fprintf('\n linsysolve: solution contains NaN or inf.'); return; end %% dy = xx(1:m); count = m; %% for p=1:size(blk,1) pblk = blk(p,:); if strcmp(pblk{1},'l') %%dZ{p} = Rd{p} - At{p}*dy; dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy)); tmp = par.dd{p}.*dZ{p}; dX{p} = EinvRc{p} - tmp; elseif strcmp(pblk{1},'q') %%dZ{p} = Rd{p} - At{p}*dy; dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),[],[],dy)); tmp = par.dd{p}.*dZ{p} + qops(pblk,qops(pblk,dZ{p},par.ee{p},1),par.ee{p},3); dX{p} = EinvRc{p} - tmp; elseif strcmp(pblk{1},'s') %%dZ{p} = Rd{p} - smat(pblk,At{p}*dy(par.permA(p,:)),par.isspAy(p)); dZ(p) = ops(Rd(p),'-',Atyfun(pblk,At(p,:),par.permA(p,:),par.isspAy(p),dy)); tmp = Prod3(pblk,par.W{p},dZ{p},par.W{p},1); dX{p} = EinvRc{p}-tmp; elseif strcmp(pblk{1},'u'); n = sum(pblk{2}); dZ{p} = zeros(n,1); dX{p} = xx(count+1:count+n); count = count + n; end end %%*******************************************************************
github
anantsrivastava30/SUVR-PET-ADNI-master
make.m
.m
SUVR-PET-ADNI-master/scripts/cvx/examples/make.m
23,079
utf_8
8b04233b872cb2ab50851644ae0e486a
function make( varargin ) % % Determine the base path % odir = pwd; base = mfilename('fullpath'); base = fileparts( base ); % % Check the force and runonly flags % args = varargin; is_octave = exist( 'OCTAVE_VERSION', 'builtin' ); if is_octave, force = true; runonly = true; indexonly = false; page_output_immediately(true); else temp = strcmp( args, '-force' ); force = any( temp ); if force, args(temp) = []; end temp = strcmp( args, '-runonly' ); runonly = any( temp ); if runonly, args(temp) = []; end temp = strcmp( args, '-indexonly' ); indexonly = any( temp ); if indexonly, args(temp) = []; end if ~runonly, close all; fclose all; end end if isempty( args ), args = { base }; end % % Process the arguments % for k = 1 : length( args ), file = args{k}; if any( file == '*' ), files = dir( file ); files = { files.name }; else files = { file }; end for j = 1 : length( files ); % % Check the validity of the file or directory % file = files{j}; switch exist( file, 'file' ), case 0, error( 'Cannot find file or directory: %s', file ); case 2, file = which( file ); if isempty( file ), file = files{j}; if file(1) ~= filesep, file = [ base, filesep, file ]; end end [ mpath, file, ext ] = fileparts( file ); file = [ file, ext ]; if ~strcmp( ext, '.m' ), error( 'Must be an m-file: %s' ); elseif strcmp( file, 'Contents.m' ) && length( files ) > 1, continue; elseif strcmp( file, 'make.m' ) && strcmp( mpath, base ), continue; end case 7, cd( file ); mpath = pwd; cd( odir ); file = ''; otherwise, error( 'Invalid file: %s', file ); end if length( mpath ) < length( base ) || strncmpi( mpath, base, length( base ) ) == 0, error( 'Not a valid a subdirectory of cvx/examples/: %s', mpath ); end % % Process the file or directory % if ~runonly && isempty( file ) && strcmp( mpath, base ), [ fidr, message ] = fopen( 'index.html', 'r' ); if fidr < 0, error( 'Cannot open index.html\n %s', message ); end [ fidw, message ] = fopen( 'index.html.new', 'w+' ); if fidw < 0, error( 'Cannot open index.html.new\n %s', message ); end while ~feof( fidr ), temp = fgetl( fidr ); fprintf( fidw, '%s\n', temp ); if strcmp(temp,'<ul class="mktree" id="tree1">'), while ~feof( fidr ), temp = fgetl( fidr ); if strcmp(temp,'</ul>'), break; end end break; end end else fidw = -1; end if isempty( file ), generate_directory( mpath, '', force, runonly, indexonly, fidw, base, 0, is_octave ); else cd( mpath ); generate_file( file, '', force, runonly, indexonly, is_octave ); end cd( odir ); if fidw >= 0, fprintf( fidw, '</ul>\n' ); while ~feof( fidr ), fprintf( fidw, '%s\n', fgetl( fidr ) ); end fclose( fidr ); fclose( fidw ); cd( mpath ) compare_and_replace( '', 'index.html' ); end end end function [ title, files ] = generate_directory( mpath, prefix, force, runonly, indexonly, fidc, base, depth, is_octave ) fprintf( 1, '%sDirectory: %s\n', prefix, mpath ); prefix = [ prefix, ' ' ]; cd( mpath ); mpath = pwd; % % Open Contents.m file and retrieve title and comments % title = ''; if ~runonly, comments = {}; fcomments = {}; [ fidr, message ] = fopen( 'Contents.m', 'r' ); if fidr >= 0, temp = fgetl( fidr ); if length( temp ) > 2 && temp( 1 ) == '%' && temp( 2 ) == ' ' && temp( 3 ) ~= ' ', title = temp( min( find( temp ~= '%' & temp ~= ' ' ) ) : end ); while ~feof( fidr ), temp = fgetl( fidr ); if isempty(temp) || temp( 1 ) ~= '%' || ~any( temp ~= '%' & temp ~= ' ' ), break; end temp = temp( min( find( temp ~= '%' & temp ~= ' ' ) ) : end ); if strcmp(title(end-2:end),'...'), title = [ title(1:end-3), temp ]; else if ~isempty(fcomments) && strcmp( fcomments{end}(end-2:end),'...' ), fcomments{end} = [ fcomments{end}(1:end-3), temp ]; else fcomments{end+1} = temp; end comments{end+1} = temp; end end end fclose( fidr ); elseif ~isempty( dir( 'Contents.m' ) ), error( 'Cannot open Contents.m for reading\n %s', message ); end end if isempty(title), title = '(no title)'; end % % Read the entries, and process the scripts and functions % dd = dir; mlen = 0; files = struct( 'name', {}, 'title', {}, 'type', {} ); for k = 1 : length( dd ), name = dd(k).name; if dd(k).isdir, if name(1) == '.' || strcmp( name, 'eqs' ) || strcmp( name, 'html' ), continue; end name(end+1) = '/'; files( end + 1 ) = struct( 'name', name, 'title', '', 'type', 'dir' ); elseif length( name ) > 2, ndx = max(find(name=='.')); if isempty( ndx ), continue; end switch name(ndx+1:end), case 'm', if strcmp( name, 'Contents.m' ) || strcmp( name, 'make.m' ) || name(end-2) == '_', continue; end [ temp, isfunc ] = generate_file( name, prefix, force, runonly, indexonly, is_octave ); if isfunc, type = 'func'; else type = 'script'; end files( end + 1 ) = struct( 'name', name, 'title', temp, 'type', type ); case 'tex', temp = generate_doc( name, prefix, force ); files( end + 1 ) = struct( 'name', name, 'title', temp, 'type', 'tex' ); case { 'pdf', 'ps' }, if any( strcmp( { dd.name }, [name(1:ndx+1),'tex'] ) ), continue; end files( end + 1 ) = struct( 'name', name, 'title', '', 'type', 'doc' ); case { 'dat', 'mat', 'txt' }, if strcmp( name, 'index.dat' ), continue; end files( end + 1 ) = struct( 'name', name, 'title', '', 'type', 'dat' ); otherwise, continue; end end mlen = max( mlen, length(name) ); end % % Sort the files % if ~isempty( files ), [ fnames, ndxs ] = sort( { files.title } ); files = files(ndxs); ftypes = { files.type }; tdir = strcmp( ftypes, 'dir' ); tfun = strcmp( ftypes, 'func' ); tdoc = strcmp( ftypes, 'doc' ) | strcmp( ftypes, 'tex' ); tdat = strcmp( ftypes, 'dat' ); tscr = ~( tdir | tfun | tdoc | tdat ); t1 = strncmp( fnames, 'Exercise', 8 ) & tscr; t2 = strncmp( fnames, 'Example', 7 ) & tscr; t3 = strncmp( fnames, 'Section', 7 ) & tscr; t4 = strncmp( fnames, 'Figure', 6 ) & tscr; t5 = ~( t1 | t2 | t3 | t4 ) & tscr; tdir = find(tdir(:)); tscr = [ find(t3(:)); find(t4(:)); find(t2(:)); find(t5(:)); find(t1(:)); ]; tfun = find(tfun(:)); tdoc = find(tdoc(:)); tdat = find(tdat(:)); files = files( [ tdoc ; tdir ; tscr ; tfun ; tdat ] ); tdoc = [ 1, length(tdoc) ]; tdir = tdoc(end) + [ 1, length(tdir) ]; tscr = tdir(end) + [ 1, length(tscr) ]; tfun = tscr(end) + [ 1, length(tfun) ]; tdat = tfun(end) + [ 1, length(tdat) ]; end % % Fill out the index.jemdoc file % if fidc >= 0, dots = sprintf('\t'); dots = dots(ones(1,depth+1)); dpath = mpath( length(base) + 2 : end ); dpath(dpath=='\') = '/'; if ~isempty(dpath), dpath(end+1) = '/'; end % Directory title---skip for the top level if depth, title = regexprep(title,'</?b>',''); title = regexprep(title,' target="_blank"',''); title2 = regexprep(title,'<a ([^>]*>)','</b><a target="_blank" $1<b>'); title2 = regexprep(title2,'</a>','</b></a><b>'); title2 = regexprep(['<b>',title2,'</b>'],'<b></b>',''); fprintf( fidc, '%s<li>%s<ul>\n', dots(1:end-1), title2 ); end if tdoc(2) >= tdoc(1) || ~isempty( fcomments ), for k = tdoc(1) : tdoc(2), name = files( k ).name; if strcmp( files(k).type, 'tex' ), name = [ name(1:end-4), 'pdf' ]; end temp = files( k ).title; if isempty( temp ), fprintf( fidc, '%s<li>Reference: <a href="%s%s" target="_blank">%s</a></li>\n', dots, dpath, name, name ); else fprintf( fidc, '%s<li>Reference: <a href="%s%s" target="_blank">%s (%s)</a></li>\n', dots, dpath, name, temp, name ); end end for k = 1 : length(fcomments), fprintf( fidc, '%s<li>Reference: %s</li>\n', dots, regexprep(fcomments{k},'<a href=','<a target="_blank" href=')); end end for k = tdir(1) : tdir(2), files(k).title = generate_directory( files(k).name(1:end-1), prefix, force, runonly, indexonly, fidc, base, depth+1, is_octave ); cd(mpath); end if tscr(2) >= tscr(1), if ~depth, fprintf( fidc, '%s<li><b>Miscellaneous examples</b>\n', dots ); dots(end+1) = dots(end); fprintf( fidc, '%s<ul>\n', dots ); end for k = tscr(1) : tscr(2), name = files( k ).name; temp = files( k ).title; if isempty( temp ), fprintf( fidc, '%s<li><a href="%s%s">%s</a></li>\n', dots, dpath, name, name ); else fprintf( fidc, '%s<li><a href="%shtml/%shtml">%s</a> (<a href="%s%s">%s</a>)</li>\n', dots, dpath, name(1:end-1), temp, dpath, name, name ); end end if ~depth, fprintf( fidc, '%s</ul>\n', dots ); dots(end) = []; fprintf( fidc, '%s</li>\n', dots ); end end if tfun(2) >= tfun(1), pref = 'Utility: '; for k = tfun(1) : tfun(2), name = files( k ).name; temp = files( k ).title; if isempty( temp ), fprintf( fidc, '%s<li>Utility: <a href="%s%s">%s</a></li>\n', dots, dpath, name, name ); else fprintf( fidc, '%s<li>Utility: <a href="%shtml/%shtml">%s</a> (<a href="%s%s">%s</a>)</li>\n', dots, dpath, name(1:end-1), temp, dpath, name, name ); end end end if tdat(2) >= tdat(1), pref = '- Data: '; for k = tdat(1) : tdat(2), name = files( k ).name; temp = files( k ).title; if isempty( temp ), fprintf( fidc, '%s<li>Data: <a href="%s%s">%s</a></li>\n', dots, dpath, name, name ); else fprintf( fidc, '%s<li>Data: <a href="%s%s">%s (%s)</a></li>\n', dots, dpath, name, temp, name ); end end end if depth, fprintf( fidc, '%s</ul></li>\n', dots(1:end-1) ); end elseif any( tdir ), for k = 1 : length( files ), if strcmp( files(k).type, 'dir' ), files(k).title = generate_directory( files(k).name(1:end-1), prefix, force, runonly, indexonly, fidc, base, depth+1, is_octave ); cd(mpath); end end end % % Create Contents.m.new % if ~runonly, [ fidw, message ] = fopen( 'Contents.m.new', 'w+' ); if fidw < 0, if fidr >= 0, fclose( fidr ); end error( 'Cannot open Contents.m.new\n %s', message ); elseif ~isempty( title ), fprintf( fidw, '%% %s\n', title ); for k = 1 : length( comments ), fprintf( fidw, '%% %s\n', comments{k} ); end fprintf( fidw, '%%\n' ); end for k = 1 : length( files ), tfile = files(k); tfile.name(end+1:mlen) = ' '; if isempty( tfile.title ), fprintf( fidw, '%% %s - (no title)\n', tfile.name ); else fprintf( fidw, '%% %s - %s\n', tfile.name, tfile.title ); end end fprintf( fidw, 'help Contents\n' ); fclose( fidw ); else fidw = -1; end % % Compare Contents.m and Contents.m.new and update if necessary % cd( mpath ) if fidw >= 0, compare_and_replace( prefix, 'Contents.m' ); end function [ title, isfunc ] = generate_file( name, prefix, force, runonly, indexonly, is_octave ) if length( name ) < 2 || ~strcmp( name(end-1:end), '.m' ), error( 'Not an m-file.' ); elseif strcmp( name, 'Contents.m' ), error( 'To generate the Contents.m file, you must run this function on the entire directory.' ); else fprintf( 1, '%s%s: ', prefix, name ); end dd = dir( name ); ndate = date_convert( dd.date ); [ fidr, message ] = fopen( name, 'r' ); if fidr < 0, error( 'Cannot open the source file\n %s', message ); end title = ''; isfunc = false; lasttitle = false; founddata = false; prefixes = {}; while ~feof( fidr ) && ( ~founddata || isempty( title ) || lasttitle ), temp1 = fgetl( fidr ); if isempty( temp1 ), if lasttitle, continue; end else temp2 = find( temp1 ~= ' ' ); if isempty( temp2 ), if lasttitle, continue; end elseif temp1(temp2(1)) == '%', temp2 = temp1(temp2(1):temp2(end)); temp3 = find( temp2 ~= '%' ); if isempty( temp3 ), if lasttitle, continue; end else temp3 = temp2( temp3(1) : end ); temp4 = find( temp3 ~= ' ' ); if isempty( temp4 ), if lasttitle, continue; end elseif isempty( title ), title = temp3(temp4(1):temp4(end)); lasttitle = true; continue; else lasttitle = false; end end else lasttitle = false; founddata = true; temp2 = temp1(temp2(1):temp2(end)); if strncmp( temp2, 'function', 8 ) && ( length( temp2 ) == 8 || ~isvarname( temp2( 1 : 9 ) ) ), isfunc = true; end end end prefixes{end+1} = temp1; end if runonly, fclose( fidr ); if isfunc, return; end end hfile = [ name(1:end-1), 'html' ]; odir = pwd; hdir = 'html'; hdate = 0; if exist( hdir, 'dir' ), cd( hdir ); df = dir( hfile ); if length( df ) == 1, hdate = date_convert( df.date ); end cd( odir ); end if indexonly, fprintf( 1, 'done.\n' ); elseif force || hdate <= ndate, if runonly, fprintf( 1, 'running %s ...', name ); elseif hdate == 0, fprintf( 1, 'creating %s ...', hfile ); else fprintf( 1, 'updating %s ...', hfile ); end name = name(1:end-2); if ~runonly, [ fidw, message ] = fopen( [ name, '_.m' ], 'w+' ); if fidw < 0, error( 'Cannot open the temporary file\n %s', message ); end if isempty( title ), fprintf( fidw, '%%%% %s\n\n', name ); else fprintf( fidw, '%%%% %s\n\n', title ); end fprintf( fidw, '%s\n', prefixes{:} ); fwrite( fidw, fread( fidr, Inf, 'uint8' ), 'uint8' ); fclose( fidw ); fclose( fidr ); end evalin( 'base', 'clear' ); cvx_clear; cvx_quiet( false ); cvx_precision default; success = true; try out___ = []; if is_octave, run_clean_octave( name ); elseif runonly, out___ = run_clean( name ); fprintf( 1, ' done.\n' ); else opts.format = 'html'; opts.useNewFigure = false; opts.createThumbnail = false; opts.evalCode = ~isfunc; opts.showCode = true; opts.catchError = false; publish( [ name, '_' ], opts ); prefixes = { '<style', '<!--', '<p class="footer"', '<meta name=', '<link rel=' }; suffixes = { '</style>', '-->', '</p>', '>', '>' }; suffix = ''; f_in = fopen( [ 'html', filesep, name, '_.html' ], 'r' ); data = fread( f_in, Inf, 'uint8=>char' )'; fclose( f_in ); backpath = ''; for k = 1 : 10, if exist( [ backpath, filesep, 'examples.css' ], 'file' ), break; end backpath = [ '..', filesep, backpath ]; end backpath = [ '..', filesep, backpath ]; canon = [regexprep(pwd,'.*/cvx/examples','http://cvxr.com/cvx/examples'),'/html/',hfile]; data = regexprep( data, '<!--.*?-->|<link rel=.*?>|<style.*?</style>|<meta name=.*?>|<p class="footer".*?</p>', '' ); data = regexprep( data, '</head>', sprintf( '\n<link rel="canonical" href="%s"/>\n<link rel="stylesheet" href="%sexamples.css" type="text/css"/>\n</head>', canon, backpath ) ); data = regexprep( data, '<div class="content"><h1>(.*?)</h1>','<div id="header">\n<h1>$1</h1>\n<!--control--></div><div id="content">' ); data = regexprep( data, '<pre class="codeinput">\n?', '\n<a id="source"></a><pre class="codeinput">\n' ); if ~isempty( regexp( data, '<pre class="codeoutput">' ) ), control_o = '<a href="#output">Text output</a>\n'; data = regexprep( data, '<pre class="codeoutput">\n?', '\n<a id="output"></a><pre class="codeoutput">\n' ); else control_o = 'Text output\n'; end if ~isempty( regexp( data, '</pre>\s*<img', 'once' ) ), control_p = '<a href="#plots">Plots</a>\n'; data = regexprep( data, '</pre>\s*<img', '</pre>\n<a id="plots"></a><div id="plotoutput">\n<img' ); data = regexprep( data, '</div>\s*</body>', '</div></div></body>' ); else control_p = 'Plots\n'; end control = sprintf( 'Jump to:&nbsp;&nbsp;&nbsp;&nbsp;\n<a href="#source">Source code</a>&nbsp;&nbsp;&nbsp;&nbsp;\n%s&nbsp;&nbsp;&nbsp;&nbsp;\n%s&nbsp;&nbsp;&nbsp;&nbsp;<a href="%sindex.html">Library index</a>', control_o, control_p, backpath ); data = regexprep( data, '<!--control-->', control ); data = regexprep( data, '<html>', '<html>\n' ); data = regexprep( data, '(<div|<pre|</div>|<body>|</body>|</html>)', '\n$1' ); data = regexprep( data, '^\s*<!DOCTYPE.*?>','<!DOCTYPE HTML>' ); data = regexprep( data, '<meta http-equiv.*?>', '<meta charset="UTF-8">' ); data = regexprep( data, '\s*((v|h)space=\S*)', '' ); data = regexprep( data, '\s*(<meta|<title)','\n$1' ); data = regexprep( data, '/>', '>' ); f_out = fopen( [ 'html', filesep, name, '.html' ], 'w' ); fwrite( f_out, data ); fclose( f_out ); delete( [ 'html', filesep, name, '_.html' ] ); fprintf( 1, ' done.\n' ); end catch err = lasterror; fprintf( 1, ' aborted.\n' ); cd( odir ); fprintf( 1, '===> ERROR: %s\n', err.message ); success = false; end if runonly, disp( out___ ); else delete( [ name, '_.m' ] ); end cd( odir ); if ~success && ~runonly && exist( hdir, 'dir' ), cd( hdir ); df = dir( hfile ); if length( df ) == 1, delete( hfile ); end cd( odir ); end close all else fprintf( 1, 'up to date.\n' ); end function title = generate_doc( name, prefix, force ) if length( name ) < 5 || ~strcmp( name(end-3:end), '.tex' ), error( 'Not an valid TeX file.' ); else fprintf( 1, '%s%s: ', prefix, name ); end dd = dir( name ); ndate = date_convert( dd.date ); [ fidr, message ] = fopen( name, 'r' ); if fidr < 0, error( 'Cannot open the source file\n %s', message ); end title = ''; while ~feof( fidr ), temp = strtrim( fgetl( fidr ) ); kndx = strfind( temp, '\title{' ); if isempty( kndx ), continue; end knd2 = strfind( temp(kndx(1):end), '}' ); if isempty( knd2 ), continue; end title = strtrim(temp(kndx(1)+7:kndx(1)+kndx(2)-2)); break; end pdffile = [ name(1:end-3), 'pdf' ]; hdate = 0; df = dir( pdffile ); if length( df ) == 1, hdate = date_convert( df.date ); end if force || hdate < ndate, if hdate == 0, fprintf( 1, 'creating %s:', hfile ); else fprintf( 1, 'updating %s:', hfile ); end name2 = name(1:end-4); eval( sprintf( '!latex %s', name2 ) ); eval( sprintf( '!latex %s', name2 ) ); eval( sprintf( '!bibtex %s', name2 ) ); eval( sprintf( '!latex %s', name2 ) ); eval( sprintf( '!latex %s', name2 ) ); eval( sprintf( '!latex %s', name2 ) ); eval( sprintf( '!dvips %s', name2 ) ); eval( sprintf( '!ps2pdf %s.ps', name2 ) ); end function dnum = date_convert( dstr ) persistent mstrs if isempty( mstrs ), mstrs = { 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' }; end % DD-MMM-YY HH:MM:SS S = sscanf( dstr, '%d-%3s-%d %d:%d:%d' ); S = [ S(5), find(strcmp(char(S(2:4)'),mstrs)), S(1), S(6), S(7), S(8) ]; dnum = S(6) + 100 * ( S(5) + 100 * ( S(4) + 100 * ( S(3) + 100 * ( S(2) + 100 * S(1) ) ) ) ); function compare_and_replace( prefix, oldname ) names = { oldname, [ oldname, '.new' ] }; fprintf( 1, '%s%s ... ', prefix, oldname ); fids = []; c = {}; for k = 1 : 2, [ fids(k), message ] = fopen( names{k}, 'r' ); if fids(k) < 0 && ~isempty( dir( names{k} ) ), error( 'Cannot open file %s for reading:\n %s', names{k}, message ); end c{k} = fread( fids(k), Inf, 'uint8' ); fclose( fids(k) ); end if isempty( c{2} ), if fids(k) >= 0, fprintf( 1, ' removed.\n' ); delete( oldname ); end delete( names{2} ); elseif length( c{1} ) ~= length( c{2} ) || any( c{1} ~= c{2} ), [ success, message ] = movefile( names{2}, names{1}, 'f' ); if ~success, error( 'Cannot move %s into place\n %s', names{2}, message ); delete( names{2} ) end if ~isempty( c{1} ), fprintf( 1, ' updated.\n' ); else fprintf( 1, ' created.\n' ); end else delete( names{2} ) fprintf( 1, ' up to date.\n' ); end function run_clean_octave( name ) feval( name ); function out___ = run_clean( name ) out___ = evalc( name );
github
anantsrivastava30/SUVR-PET-ADNI-master
cantilever_beam_plot.m
.m
SUVR-PET-ADNI-master/scripts/cvx/examples/cvxbook/Ch04_cvx_opt_probs/cantilever_beam_plot.m
1,050
utf_8
e8c8c9e1b601e4102f96e0436649d132
% Plots a cantilever beam as a 3D figure. % This is a helper function for the optimal cantilever beam example. % % Inputs: % values: an array of heights and widths of each segment % [h1 h2 ... hN w1 w2 ... wN] % % Almir Mutapcic 01/25/06 function cantilever_beam_plot(values) N = length(values)/2; for k = 0:N-1 [X Y Z] = data_rect3(values(2*N-k),values(N-k),k); plot3(X,Y,Z); hold on; end hold off; xlabel('width') ylabel('height') zlabel('length') return; %**************************************************************** function [X, Y, Z] = data_rect3(w,h,d) %**************************************************************** % back face X = [-w/2 w/2 w/2 -w/2 -w/2]; Y = [-h/2 -h/2 h/2 h/2 -h/2]; Z = [d d d d d]; % side face X = [X -w/2 -w/2 -w/2 -w/2 -w/2]; Y = [Y -h/2 -h/2 h/2 h/2 -h/2]; Z = [Z d d+1 d+1 d d]; % front face X = [X -w/2 w/2 w/2 -w/2 -w/2]; Y = [Y -h/2 -h/2 h/2 h/2 -h/2]; Z = [Z d+1 d+1 d+1 d+1 d+1]; % back side face X = [X w/2 w/2 w/2 w/2 w/2]; Y = [Y -h/2 h/2 h/2 -h/2 -h/2]; Z = [Z d+1 d+1 d d d+1];
github
anantsrivastava30/SUVR-PET-ADNI-master
simple_step.m
.m
SUVR-PET-ADNI-master/scripts/cvx/examples/circuit_design/simple_step.m
235
utf_8
b8043326fe5966f9432b69b584891e0f
% Computes the step response of a linear system function X = simple_step(A,B,DT,N) n = size(A,1); Ad = expm( full( A * DT ) ); Bd = ( Ad - eye(n) ) * B; Bd = A \ Bd; X = zeros(n,N); for k = 2 : N, X(:,k) = Ad*X(:,k-1)+Bd; end
github
anantsrivastava30/SUVR-PET-ADNI-master
spectral_fact.m
.m
SUVR-PET-ADNI-master/scripts/cvx/examples/filter_design/spectral_fact.m
1,292
utf_8
014eebfa2dfbbd038c1383ff2ef97b0e
% Spectral factorization using Kolmogorov 1939 approach. % (code follows pp. 232-233, Signal Analysis, by A. Papoulis) % % Computes the minimum-phase impulse response which satisfies % given auto-correlation. % % Input: % r: top-half of the auto-correlation coefficients % starts from 0th element to end of the auto-corelation % should be passed in as a column vector % Output % h: impulse response that gives the desired auto-correlation function h = spectral_fact(r) % length of the impulse response sequence n = length(r); % over-sampling factor mult_factor = 100; % should have mult_factor*(n) >> n m = mult_factor*n; % computation method: % H(exp(jTw)) = alpha(w) + j*phi(w) % where alpha(w) = 1/2*ln(R(w)) and phi(w) = Hilbert_trans(alpha(w)) % compute 1/2*ln(R(w)) w = 2*pi*[0:m-1]/m; R = [ ones(m,1) 2*cos(kron(w',[1:n-1])) ]*r; alpha = 1/2*log(R); % find the Hilbert transform alphatmp = fft(alpha); alphatmp(floor(m/2)+1:m) = -alphatmp(floor(m/2)+1:m); alphatmp(1) = 0; alphatmp(floor(m/2)+1) = 0; phi = real(ifft(j*alphatmp)); % now retrieve the original sampling index = find(rem([0:m-1],mult_factor)==0); alpha1 = alpha(index); phi1 = phi(index); % compute the impulse response (inverse Fourier transform) h = real(ifft(exp(alpha1+j*phi1),n));
github
anantsrivastava30/SUVR-PET-ADNI-master
polar_plot_ant.m
.m
SUVR-PET-ADNI-master/scripts/cvx/examples/antenna_array_design/polar_plot_ant.m
1,149
utf_8
34a08a3bc75c474d61e01ea58b16e54e
% Plot a polar plot of an antenna array sensitivity % with lines denoting the target direction and beamwidth. % This is a helper function used in the broadband antenna examples. % % Inputs: % X: an array of abs(y(theta)) where y is the antenna array pattern % theta0: target direction % bw: total beamwidth % label: a string displayed as the plot legend % % Original code by Lieven Vandenberghe % Updated for CVX by Almir Mutapcic 02/17/06 function polar_plot_ant(X,theta0,bw,label) % polar plot numpoints = length(X); thetas2 = linspace(1,360,numpoints)'; plot(X.*cos(pi*thetas2/180), X.*sin(pi*thetas2/180), '-'); plot(X.*cos(pi*thetas2/180), X.*sin(pi*thetas2/180), '-'); hold on; axis('equal'); plot(cos(pi*[thetas2;1]/180), sin(pi*[thetas2;1]/180), '--'); text(1.1,0,'1'); plot([0 cos(pi*theta0/180)], [0 sin(pi*theta0/180)], '--'); sl1 = find(thetas2-theta0 > bw/2); sl2 = find(thetas2-theta0 < -bw/2); Gsl = max(max(X(sl1)), max(X(sl2))); plot(Gsl*cos(pi*thetas2(sl1)/180), Gsl*sin(pi*thetas2(sl1)/180), '--'); plot(Gsl*cos(pi*thetas2(sl2)/180), Gsl*sin(pi*thetas2(sl2)/180), '--'); text(-1,1.1,label); axis off;
github
anantsrivastava30/SUVR-PET-ADNI-master
spectral_fact.m
.m
SUVR-PET-ADNI-master/scripts/cvx/examples/antenna_array_design/spectral_fact.m
1,385
utf_8
570e7ae2165d19abd477494c52e609f8
% Spectral factorization using Kolmogorov 1939 approach % (code follows pp. 232-233, Signal Analysis, by A. Papoulis) % % Computes the minimum-phase impulse response which satisfies % given auto-correlation. % % Input: % r: top-half of the auto-correlation coefficients % starts from 0th element to end of the auto-corelation % should be passed in as a column vector % Output % h: impulse response that gives the desired auto-correlation function h = spectral_fact(r) % length of the impulse response sequence nr = length(r); n = (nr+1)/2; % over-sampling factor mult_factor = 30; % should have mult_factor*(n) >> n m = mult_factor*n; % computation method: % H(exp(jTw)) = alpha(w) + j*phi(w) % where alpha(w) = 1/2*ln(R(w)) and phi(w) = Hilbert_trans(alpha(w)) % compute 1/2*ln(R(w)) w = 2*pi*[0:m-1]/m; R = exp( -j*kron(w',[-(n-1):n-1]) )*r; R = abs(real(R)); % remove numerical noise from the imaginary part figure; plot(20*log10(R)); alpha = 1/2*log(R); % find the Hilbert transform alphatmp = fft(alpha); alphatmp(floor(m/2)+1:m) = -alphatmp(floor(m/2)+1:m); alphatmp(1) = 0; alphatmp(floor(m/2)+1) = 0; phi = real(ifft(j*alphatmp)); % now retrieve the original sampling index = find(rem([0:m-1],mult_factor)==0); alpha1 = alpha(index); phi1 = phi(index); % compute the impulse response (inverse Fourier transform) h = ifft(exp(alpha1+j*phi1),n);
github
anantsrivastava30/SUVR-PET-ADNI-master
plotgraph.m
.m
SUVR-PET-ADNI-master/scripts/cvx/examples/graph_laplacian/plotgraph.m
3,172
utf_8
a46b1d761798c492e96a5b9504aea9aa
function plotgraph(A,xy,weights) % Plots a graph with each edge width proportional to its weight. % % Edges with positive weights are drawn in blue; negative weights in red. % % Input parameters: % A --- incidence matrix of the graph (size is n x m) % (n is the number of nodes and m is the number of edges) % xy --- horizontal and vertical positions of the nodes (n x 2 matrix) % weights --- m vector giving edge weights % % Original by Lin Xiao % Modified by Almir Mutapcic % graph size [n,m]= size(A); % set the graph scale and normalize the coordinates to lay in [-1,1] square R = max(max(abs(xy))); % maximum abs value of the xy coordinates x = xy(:,1)/R; y = xy(:,2)/R; % normalize weight vector to range between +1 and -1 weights = weights/max(abs(weights)); % internal parameters (tune these parameters to make the plot look pretty) % (note that the graph coordinates and the weights have been rescaled % to a common unity scale) %rNode = 0.005; % radius of the node circles rNode = 0; % set the node radius to zero if you do not want the nodes wNode = 2; % line width of the node circles PWColor = [0 0 1]; % color of the edges with positive weights NWColor = [1 0 0]; % color of the edges with negative weights Wmin = 0.0001; % minimum weight value for which we draw an edge max_width = 0.05; % drawn width of edge with maximum absolute weight % first draw the edges with patch widths proportional to the weights for i=1:m if ( abs(weights(i)) > Wmin ) Isrc = find( sign(weights(i))*A(:,i)>0 ); Idst = find( sign(weights(i))*A(:,i)<0 ); else Isrc = find( A(:,i)>0 ); Idst = find( A(:,i)<0 ); end % obtain edge patch coordinates xdelta = x(Idst) - x(Isrc); ydelta = y(Idst) - y(Isrc); RotAgl = atan2( ydelta, xdelta ); xstart = x(Isrc) + rNode*cos(RotAgl); ystart = y(Isrc) + rNode*sin(RotAgl); xend = x(Idst) - rNode*cos(RotAgl); yend = y(Idst) - rNode*sin(RotAgl); L = sqrt( xdelta^2 + ydelta^2 ) - 2*rNode; if ( weights(i) > Wmin ) W = abs(weights(i))*max_width; drawedge(xstart, ystart, RotAgl, L, W, PWColor); hold on; elseif ( weights(i) < -Wmin ) W = abs(weights(i))*max_width; drawedge(xstart, ystart, RotAgl, L, W, NWColor); hold on; else plot([xstart xend],[ystart yend],'k:','LineWidth',2.5); end end % the circle to draw around each node angle = linspace(0,2*pi,100); xbd = rNode*cos(angle); ybd = rNode*sin(angle); % draw the nodes for i=1:n plot( x(i)+xbd, y(i)+ybd, 'k', 'LineWidth', wNode ); end; axis equal; set(gca,'Visible','off'); hold off; %******************************************************************** % helper function to draw edges in the graph %******************************************************************** function drawedge( x0, y0, RotAngle, L, W, color ) xp = [ 0 L L L L L 0 0 ]; yp = [-0.5*W -0.5*W -0.5*W 0 0.5*W 0.5*W 0.5*W -0.5*W]; RotMat = [cos(RotAngle) -sin(RotAngle); sin(RotAngle) cos(RotAngle)]; DrawCoordinates = RotMat*[ xp; yp ]; xd = x0 + DrawCoordinates(1,:); yd = y0 + DrawCoordinates(2,:); % draw the edge patch( xd, yd, color );
github
anantsrivastava30/SUVR-PET-ADNI-master
disp.m
.m
SUVR-PET-ADNI-master/scripts/cvx/lib/@cvxprob/disp.m
5,405
utf_8
c8f4506efcff564b81f1f3cc1dbb8a9c
function disp( prob, prefix ) if nargin < 2, prefix = ''; end global cvx___ p = cvx___.problems( prob.index_ ); if isempty( p.variables ), nvars = 0; else nvars = length( fieldnames( p.variables ) ); end if isempty( p.duals ), nduls = 0; else nduls = length( fieldnames( p.duals ) ); end neqns = ( length( cvx___.equalities ) - p.n_equality ) + ... ( length( cvx___.linforms ) - p.n_linform ) + ... ( length( cvx___.uniforms ) - p.n_uniform ); nineqs = nnz( cvx___.needslack( p.n_equality + 1 : end ) ) + ... nnz( cvx_vexity( cvx___.linrepls( p.n_linform + 1 : end ) ) ) + ... nnz( cvx_vexity( cvx___.unirepls( p.n_uniform + 1 : end ) ) ); neqns = neqns - nineqs; if isempty( p.name ) || strcmp( p.name, 'cvx_' ), nm = ''; else nm = [ p.name, ': ' ]; end rsv = cvx___.reserved; nt = length( rsv ); fv = length( p.t_variable ); qv = fv + 1 : nt; tt = p.t_variable; ni = nnz( tt ) - 1; ndup = sum( rsv ) - nnz( rsv ); neqns = neqns + ndup; nv = nt - fv + ni + ndup; tt( qv ) = true; gfound = nnz( cvx___.logarithm( tt ) ); cfound = false; for k = 1 : length( cvx___.cones ), if any( any( tt( cvx___.cones( k ).indices ) ) ), cfound = true; break; end end if all( [ numel( p.objective ), nv, nvars, nduls, neqns, nineqs, cfound, gfound ] == 0 ), disp( [ prefix, nm, 'cvx problem object' ] ); else if ( p.gp ), ptype =' geometric '; elseif ( p.sdp ), ptype = ' semidefinite '; else ptype = ' '; end if isempty( p.objective ), tp = 'feasibility'; else switch p.direction, case 'minimize', tp = 'minimization'; case 'epigraph', tp = 'epigraph minimization'; case 'hypograph', tp = 'hypograph maximization'; case 'maximize', tp = 'maximization'; end if numel( p.objective ) > 1, sz = sprintf( '%dx', size( p.objective ) ); tp = [ sz(1:end-1), '-objective ', tp ]; end end disp( [ prefix, nm, 'cvx', ptype, tp, ' problem' ] ); if nvars > 0, disp( [ prefix, 'variables: ' ] ); [ vnam, vsiz ] = dispvar( p.variables, '' ); vnam = strvcat( vnam ); %#ok vsiz = strvcat( vsiz ); %#ok for k = 1 : size( vnam ), disp( [ prefix, ' ', vnam( k, : ), ' ', vsiz( k, : ) ] ); end end if nduls > 0, disp( [ prefix, 'dual variables: ' ] ); [ vnam, vsiz ] = dispvar( p.duals, '' ); vnam = strvcat( vnam ); %#ok vsiz = strvcat( vsiz ); %#ok for k = 1 : size( vnam ), disp( [ prefix, ' ', vnam( k, : ), ' ', vsiz( k, : ) ] ); end end if neqns > 0 || nineqs > 0, disp( [ prefix, 'linear constraints:' ] ); if neqns > 0, if neqns > 1, plural = 'ies'; else plural = 'y'; end fprintf( 1, '%s %d equalit%s\n', prefix, neqns, plural ); end if nineqs > 0, if nineqs > 1, plural = 'ies'; else plural = 'y'; end fprintf( 1, '%s %d inequalit%s\n', prefix, nineqs, plural ); end end if cfound || gfound, disp( [ prefix, 'nonlinearities:' ] ); if gfound > 0, if gfound > 1, plural = 's'; else plural = ''; end fprintf( 1, '%s %d exponential pair%s\n', prefix, gfound, plural ); end if cfound, for k = 1 : length( cvx___.cones ), ndxs = cvx___.cones( k ).indices; ndxs = ndxs( :, any( reshape( tt( ndxs ), size( ndxs ) ), 1 ) ); if ~isempty( ndxs ), if isequal( cvx___.cones( k ).type, 'nonnegative' ), ncones = 1; csize = numel( ndxs ); else [ csize, ncones ] = size( ndxs ); end if ncones == 1, plural = ''; else plural = 's'; end fprintf( 1, '%s %d order-%d %s cone%s\n', prefix, ncones, csize, cvx___.cones( k ).type, plural ); end end end end end function [ names, sizes ] = dispvar( v, name ) switch class( v ), case 'struct', fn = fieldnames( v ); if ~isempty( name ), name( end + 1 ) = '.'; end names = {}; sizes = {}; for k = 1 : length( fn ), [ name2, size2 ] = dispvar( subsref(v,struct('type','.','subs',fn{k})), [ name, fn{k} ] ); names( end + 1 : end + length( name2 ) ) = name2; sizes( end + 1 : end + length( size2 ) ) = size2; if k == 1 && ~isempty( name ), name( 1 : end - 1 ) = ' '; end end case 'cell', names = {}; sizes = {}; for k = 1 : length( v ), [ name2, size2 ] = dispvar( v{k}, sprintf( '%s{%d}', name, k ) ); names( end + 1 : end + length( name2 ) ) = name2; sizes( end + 1 : end + length( size2 ) ) = size2; if k == 1, name( 1 : end ) = ' '; end end case 'double', names = { name }; sizes = { '(constant)' }; otherwise, names = { name }; sizes = { [ '(', type( v, true ), ')' ] }; end % Copyright 2005-2016 CVX Research, Inc. % See the file LICENSE.txt for full copyright information. % The command 'cvx_where' will show where this file is located.
github
anantsrivastava30/SUVR-PET-ADNI-master
apply.m
.m
SUVR-PET-ADNI-master/scripts/cvx/lib/@cvxtuple/apply.m
505
utf_8
f59f25021974462a358e5189ea5415e8
function y = apply( func, x ) y = do_apply( func, x.value_ ); function y = do_apply( func, x ) switch class( x ), case 'struct', y = cell2struct( do_apply( func, struct2cell( x ) ), fieldnames( x ), 1 ); case 'cell', y = cellfun( func, x, 'UniformOutput', false ); otherwise, y = feval( func, x ); end % Copyright 2005-2016 CVX Research, Inc. % See the file LICENSE.txt for full copyright information. % The command 'cvx_where' will show where this file is located.
github
anantsrivastava30/SUVR-PET-ADNI-master
cvx_setdual.m
.m
SUVR-PET-ADNI-master/scripts/cvx/lib/@cvxtuple/cvx_setdual.m
954
utf_8
b6deb370985cc299023b091bbba5dfd6
function x = setdual( x, y ) x.dual_ = y; x.value_ = do_setdual( x.value_, y ); function x = do_setdual( x, y ) switch class( x ), case 'struct', nx = numel( x ); if nx > 1, error( 'Dual variables may not be attached to struct arrays.' ); end f = fieldnames(x); y(end+1).type = '{}'; for k = 1 : length(f), y(end).subs = {1,k}; x.(f{k}) = do_setdual( x.(f{k}), y ); end case 'cell', y(end+1).type = '{}'; y(end+1).subs = cell(1,ndims(x)); for k = 1 : numel(nx), [ y(end).subs{:} ] = { 1, k }; x{k} = do_setdual( x{k}, y ); end case 'cvx', x = setdual( x, y ); case 'double', x = setdual( cvx( x ), y ); end % Copyright 2005-2016 CVX Research, Inc. % See the file LICENSE.txt for full copyright information. % The command 'cvx_where' will show where this file is located.
github
anantsrivastava30/SUVR-PET-ADNI-master
testall.m
.m
SUVR-PET-ADNI-master/scripts/cvx/lib/@cvxtuple/testall.m
452
utf_8
be9d0553e0e560f2c73fdb02a37b08b6
function y = testall( func, x ) y = do_test( func, x.value_ ); function y = do_test( func, x ) switch class( x ), case 'struct', y = do_test( func, struct2cell( x ) ); case 'cell', y = all( cellfun( func, x ) ); otherwise, y = feval( func, x ); end % Copyright 2005-2016 CVX Research, Inc. % See the file LICENSE.txt for full copyright information. % The command 'cvx_where' will show where this file is located.
github
anantsrivastava30/SUVR-PET-ADNI-master
disp.m
.m
SUVR-PET-ADNI-master/scripts/cvx/lib/@cvxtuple/disp.m
1,366
utf_8
ed9c53cbe23c1f5ab4440b5d9a10cbfd
function disp( x, prefix ) if nargin < 2, prefix = ''; end disp( [ prefix, 'cvx tuple object: ' ] ); prefix = [ prefix, ' ' ]; do_disp( x.value_, {}, prefix, prefix, '' ); if ~isempty( x.dual_ ), dn = cvx_subs2str( x.dual_ ); disp( [ prefix, 'dual variable: ', dn(2:end) ] ); end function do_disp( x, f, fprefix, prefix, suffix ) switch class( x ), case 'struct', do_disp( struct2cell(x), fieldnames(x), fprefix, prefix, suffix ); case 'cell', fprefix = [ fprefix, '{ ' ]; prefix = [ prefix, ' ' ]; nsuffix = ''; kend = numel( x ); for k = 1 : kend, if k == kend, nsuffix = [ ' }', suffix ]; end if ~isempty( f ), fprefix = sprintf( '%s%s: ', fprefix, f{k} ); end do_disp( x{k}, {}, fprefix, prefix, nsuffix ); fprefix = prefix; end case 'cvx', dual = cvx_getdual( x ); if ~isempty( dual ), suffix = sprintf( ' (dual: %s)%s', dual, suffix ); end disp( [ fprefix, cvx_class( x, true, true ), ' ', type( x ), suffix ] ); case 'double', fprintf( 1, '%s%g%s\n', fprefix, x, suffix ); end % Copyright 2005-2016 CVX Research, Inc. % See the file LICENSE.txt for full copyright information. % The command 'cvx_where' will show where this file is located.
github
anantsrivastava30/SUVR-PET-ADNI-master
sparsify.m
.m
SUVR-PET-ADNI-master/scripts/cvx/lib/@cvx/sparsify.m
4,013
utf_8
2eda31274fafa84387d3aad5be748107
function x = sparsify( x, mode ) global cvx___ narginchk(2,2); persistent remap % % Check mode argument % if ~ischar( mode ) || size( mode, 1 ) ~= 1, error( 'Second arugment must be a string.' ); end isobj = strcmp( mode, 'objective' ); pr = cvx___.problems( end ); touch( pr.self, x ); bz = x.basis_ ~= 0; bs = sum( bz, 1 ); bc = bz( 1, : ); tt = bs > bc + 1; at = any( tt ); if at, % % Replace posynomials with log-convex monomials --- that is, unless % we are taking the exponential of one. (Not that I know why we % would do that!) In that case, we should just use a standard % linear replacement and leave it at that. % if ~isequal( mode, 'exponential' ), if isempty( remap ), remap = cvx_remap( 'posynomial' ); end t2 = remap( cvx_classify( x ) ); if any( t2 ), if all( t2 ), x = exp( log( x ) ); else x = cvx_subsasgn( x, t2, exp( log( cvx_subsref( x, t2 ) ) ) ); end bc( t2 ) = 0; tt = tt & ~t2; at = any( tt ); end end % % Replace other multivariable forms with single-variable forms % if at, abc = any( bc( :, tt ) ); if abc, xc = cvx_constant( x ); x = x - xc; end forms = cvx___.linforms; repls = cvx___.linrepls; [ x, forms, repls ] = replcols( x, tt, 'full', forms, repls, isobj ); cvx___.linforms = forms; cvx___.linrepls = repls; if abc, x = x + xc; end end end % % Arguments: no constraints on coefficients or constant values % Objectives: all replaced with coefficient > 0, constant terms preserved % Exponentiation: coefficient == 1, constant terms perserved % Logarithm: coefficient > 0, constant terms eliminated % switch mode, case { 'argument', 'constraint' }, tt = false; case 'objective', tt = ~tt | sum( x.basis_, 1 ) < x.basis_( 1, : ); usexc = true; case 'logarithm', tt = sum( x.basis_, 1 ) < x.basis_( 1, : ); usexc = false; case 'exponential'; tt = sum( x.basis_, 1 ) ~= x.basis_( 1, : ) + 1; usexc = true; otherwise, error( [ 'Invalid normalization mode: ', mode ] ); end if any( tt ), if usexc, abc = any( bc ); if abc, xc = cvx_constant( x ); x = x - xc; end else abc = false; end forms = cvx___.uniforms; repls = cvx___.unirepls; [ x, forms, repls ] = replcols( x, tt, 'none', forms, repls, isobj ); cvx___.uniforms = forms; cvx___.unirepls = repls; if abc, x = x + xc; end end function [ x, forms, repls ] = replcols( x, tt, mode, forms, repls, isobj ) % % Sift through the forms, removing duplicates % global cvx___ bN = vec( cvx_subsref( x, tt ) ); nO = length( forms ); nN = length( bN ); if nO ~= 0, bN = [ forms ; bN ]; end [ bNR, bN ] = bcompress( bN, mode, nO ); bNR = bNR( :, nO + 1 : end ); nB = length( bN ) - nO; % % Create the replacement variables % if nB ~= 0, forms = bN; bN = cvx_subsref( bN, nO + 1 : nO + nB, 1 ); newrepl = newvar( cvx___.problems( end ).self, '', nB ); [ ndxs, temp ] = find( newrepl.basis_ ); %#ok repls = [ repls ; newrepl ]; bV = cvx_vexity( bN ); cvx___.vexity( ndxs ) = bV; cvx___.readonly( ndxs ) = vec( cvx_readlevel( bN ) ); if ~isobj, ss = bV == 0; if any( ss ), temp = cvx_basis( bN ); temp = any( temp( :, ss ), 2 ); temp( ndxs( ss ) ) = true; cvx___.canslack( temp ) = false; end end end % % Re-expand the structure % x = cvx_subsasgn( x, tt, buncompress( bNR, repls, nN ) ); % Copyright 2005-2016 CVX Research, Inc. % See the file LICENSE.txt for full copyright information. % The command 'cvx_where' will show where this file is located.
github
anantsrivastava30/SUVR-PET-ADNI-master
prelp.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sedumi/conversion/prelp.m
3,887
utf_8
4d1e23d094e3f1b35ec666df11a34003
% PRELP Loads and preprocesses LP from an MPS file. % % > [A,b,c,lenx,lbounds] = PRELP('problemname') % The above command results in an LP in standard form, % - Instead of specifying the problemname, you can also use PRELP([]), to % get the problem from the file /tmp/default.mat. % - Also, you may type PRELP without any input arguments, and get prompted % for a name. % % MINIMIZE c'*x SUCH THAT A*x = b AND x>= 0. % % So, you can solve it with SeDuMi: % > [x,y,info] = SEDUMI(A,b,c); % % After solving, post-process it with % > [x,objp] = POSTPROCESS(x(1:lenx),lbounds). % % REMARK x(lenx+1:length(x)) will contain upper-bound slacks. % % IMPORTANT works only if LIPSOL is installed on your system. % % See also sedumi, getproblem, postprocess (LIPSOL), frompack, lipsol. function [A,b,c,lenx,lbounds,times] = prelp(pname) % % This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko % Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1) % % Copyright (C) 2001 Jos F. Sturm (up to 1.05R5) % Dept. Econometrics & O.R., Tilburg University, the Netherlands. % Supported by the Netherlands Organization for Scientific Research (NWO). % % Affiliation SeDuMi 1.03 and 1.04Beta (2000): % Dept. Quantitative Economics, Maastricht University, the Netherlands. % % Affiliations up to SeDuMi 1.02 (AUG1998): % CRL, McMaster University, Canada. % Supported by the Netherlands Organization for Scientific Research (NWO). % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA % 02110-1301, USA% global OUTFID global Ubounds_exist if ~exist('loadata','file') || ~exist('preprocess','file') if ~exist('loadata','file') | ~exist('preprocess','file') error('To use PRELP, you need to have LIPSOL installed.') end %-------------------------------------------------- % LOAD LP PROBLEM INTO MEMORY %-------------------------------------------------- if (nargin == 0) pname = input('Enter problem name: ','s'); end [A,b,c,lbounds,ubounds,BIG] = loadata(pname); t0 = cputime; [A,b,c,lbounds,ubounds,BIG,NAME] = loadata(pname); times(1) = cputime - t0; %-------------------------------------------------- % PREPROCESS LP PROBLEM % NB: Y.Zhang's preprocess returns lbounds for post- % processing; the pre-processed problem has x>=0. %-------------------------------------------------- t0 = cputime; [A,b,c,lbounds,ubounds,FEASIBLE] = ... preprocess(A,b,c,lbounds,ubounds,BIG); if ~FEASIBLE fprintf('\n'); if isempty(OUTFID) return; end; msginf = 'Infeasibility detected in preprocessing'; fprintf(OUTFID, [pname ' 0 ' msginf '\n']); return; end; %[A,b,c,ubounds] = scaling(A,b,c,ubounds); %-------------------------------------------------- % INSERT UBOUND- CONSTRAINTS IN THE A-MATRIX %-------------------------------------------------- b = full(b); c = full(c); [m,lenx] = size(A); if Ubounds_exist nub = nnz(ubounds); A= [ A sparse(m,nub); sparse(1:nub,find(ubounds),1,nub,lenx) speye(nub) ]; b = [b; nonzeros(ubounds)]; c = [c; zeros(nub,1)]; else ubounds = []; end %-------------------------------------------------- % LOCATE DENSE COLUMNS %-------------------------------------------------- %checkdense(A); times(2) = cputime - t0;
github
anantsrivastava30/SUVR-PET-ADNI-master
feasreal.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sedumi/conversion/feasreal.m
4,144
utf_8
454dcb6c42c0642ed5c5a524e84bec58
% FEASREAL Generates a random sparse optimization problem with % linear, quadratic and semi-definite constraints. Output % can be used by SEDUMI. All data will be real-valued. % % The following two lines are typical: % > [AT,B,C,K] = FEASREAL; % > [X,Y,INFO] = SEDUMI(AT,B,C,K); % % An extended version is: % > [AT,B,C,K] = FEASREAL(m,lpN,lorL,rconeL,sdpL,denfac) % % SEE ALSO sedumi AND feascpx. function [At,b,c,K] = feasreal(m,nLP,qL,rL,nL,denfac) % % This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko % Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1) % % Copyright (C) 2001 Jos F. Sturm (up to 1.05R5) % Dept. Econometrics & O.R., Tilburg University, the Netherlands. % Supported by the Netherlands Organization for Scientific Research (NWO). % % Affiliation SeDuMi 1.03 and 1.04Beta (2000): % Dept. Quantitative Economics, Maastricht University, the Netherlands. % % Affiliations up to SeDuMi 1.02 (AUG1998): % CRL, McMaster University, Canada. % Supported by the Netherlands Organization for Scientific Research (NWO). % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA % 02110-1301, USA% if nargin < 6 denfac = 0.1; if nargin < 5 nL = 1+ round(7*rand(1,5)); fprintf('Choosing random SDP-product cone K.s.\n') if nargin < 4 rL = 3 + round(4*rand(1,5)); fprintf('Choosing random LORENTZ R-product cone K.r.\n') if nargin < 3 qL = 3 + round(4*rand(1,5)); fprintf('Choosing random LORENTZ-product cone K.q.\n') if(nargin < 2) nLP = 10; fprintf('Choosing default K.l=%3.0f.\n',nLP) if nargin < 1 m=10; fprintf('Choosing default m=%3.0f.\n',m) end end end end end end if isempty(nLP) nLP = 0; end nblk = length(nL) + length(rL) + length(qL) + nLP; denfac = min(1, max(denfac,2/nblk)); fprintf('Choosing block density denfac=%6.4f per row\n',denfac) Apattern=sparse(m,nblk); for j=1:m pati = sprandn(1,nblk,denfac); Apattern(j,:) = (pati~= 0); end sumnLsqr = sum(nL.^2); x = zeros(nLP+sum(qL)+sum(rL)+sumnLsqr,1); x(1:nLP) = rand(nLP,1); At = sparse(length(x),m); At(1:nLP,:) = sprandn(Apattern(:,1:nLP)'); firstk = nLP+1; %[nA, mA] = size(At); % LORENTZ: for k=1:length(qL) nk = qL(k); lastk = firstk + nk - 1; x(firstk) = rand; for j=1:m if Apattern(j,nLP+k)==1 At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk)); end end firstk = lastk + 1; end % RCONE (Rotated Lorentz): for k=1:length(rL) nk = rL(k); lastk = firstk + nk - 1; x(firstk) = rand; x(firstk+1) = rand; for j=1:m if Apattern(j,nLP+length(qL)+k)==1 At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk)); end end firstk = lastk + 1; end % SDP: for k=1:length(nL) nk = nL(k); lastk = firstk + nk*nk - 1; Xk = diag(rand(nk,1)); % diagonal, to keep sparsity structure x(firstk:lastk) = Xk; %although symmetric, store nk^2 elts. for j=1:m if Apattern(j,nLP+length(qL)+length(rL)+k)==1 Aik = sprandsym(nk,1/nk); %on average 1 nonzero per row At(firstk:lastk,j) = vec( (Aik+Aik') ); end end firstk = lastk + 1; end b = full(At'*x); y = rand(m,1)-0.5; c = sparse(At*y)+x; K.l = nLP; K.q = qL; K.r = rL; K.s = nL;
github
anantsrivastava30/SUVR-PET-ADNI-master
sdpa2vec.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sedumi/conversion/sdpa2vec.m
2,352
utf_8
f055b4df357f6cf3b426ce27869bc738
% x = sdpavec(E,K) % Takes an SDPA type sparse data description E, i.e. % E(1,:) = block, E(2,:) = row, E(3,:) = column, E(4,:) = entry, % and transforms it into a "long" vector, with vectorized matrices for % each block stacked under each other. The size of each matrix block % is given in the field K.s. % ********** INTERNAL FUNCTION OF SEDUMI ********** function x = sdpa2vec(E,K,invperm) % % This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko % Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1) % % Copyright (C) 2001 Jos F. Sturm (up to 1.05R5) % Dept. Econometrics & O.R., Tilburg University, the Netherlands. % Supported by the Netherlands Organization for Scientific Research (NWO). % % Affiliation SeDuMi 1.03 and 1.04Beta (2000): % Dept. Quantitative Economics, Maastricht University, the Netherlands. % % Affiliations up to SeDuMi 1.02 (AUG1998): % CRL, McMaster University, Canada. % Supported by the Netherlands Organization for Scientific Research (NWO). % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA % 02110-1301, USA % % ------------------------------------------------------------ % Split E into blocks E[1], E[2], ..., E[length(K.s)] % ------------------------------------------------------------ [xir,xjc] = sdpasplit(E(1,:),length(K.s)); x = sparse([],[],[],0,0,2*size(E,2)); for knz = 1:length(xir) permk = xir(knz); k = invperm(permk); if k > K.l k = k - K.l; % matrix nk = K.s(k); Ek = E(2:4,xjc(knz):xjc(knz+1)-1); Xk = sparse(Ek(1,:),Ek(2,:),Ek(3,:),nk,nk); Xk = Xk + triu(Xk,1)'; x=[x;Xk(:)]; else x=[x;E(4,xjc(knz))]; end end
github
anantsrivastava30/SUVR-PET-ADNI-master
blk2vec.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sedumi/conversion/blk2vec.m
1,653
utf_8
0d48b96f66e746fce480e7a3e9c271a5
% x = blk2vec(X,nL) % % Converts a block diagonal matrix into a vector. % % ********** INTERNAL FUNCTION OF FROMPACK ********** function x = blk2vec(X,nL) % % This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko % Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1) % % Copyright (C) 2001 Jos F. Sturm (up to 1.05R5) % Dept. Econometrics & O.R., Tilburg University, the Netherlands. % Supported by the Netherlands Organization for Scientific Research (NWO). % % Affiliation SeDuMi 1.03 and 1.04Beta (2000): % Dept. Quantitative Economics, Maastricht University, the Netherlands. % % Affiliations up to SeDuMi 1.02 (AUG1998): % CRL, McMaster University, Canada. % Supported by the Netherlands Organization for Scientific Research (NWO). % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA % 02110-1301, USA % nblk = length(nL); sumnk = 0; x = []; for k = 1:nblk nk = nL(k); x = [x; vec(X(sumnk+1:sumnk + nk,sumnk+1:sumnk + nk))] ; sumnk = sumnk + nk; end
github
anantsrivastava30/SUVR-PET-ADNI-master
writesdp.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sedumi/conversion/writesdp.m
4,708
utf_8
31f196bca4c11b9610c98de8e4d7b107
% This function takes a problem in SeDuMi MATLAB format and writes it out % in SDPpack format. % % Usage: % % writesdp(fname,A,b,c,K) % % fname Name of SDPpack file, in quotes % A,b,c,K Problem in SeDuMi form % % Notes: % % Problems with complex data are not allowed. % % Rotated cone constraints are not supported. % % Nonsymmetric A.s and C.s matrices are symmetrized with A=(A+A')/2 % a warning is given when this happens. % % Floating point numbers are written out with 18 decimal digits for % accuracy. % % Please contact the author (Brian Borchers, [email protected]) with any % questions or bug reports. % function writesdp(fname,A,b,c,K) %From: Brian Borchers[SMTP:[email protected]] %Sent: Wednesday, December 08, 1999 12:33 PM %To: [email protected] % %Here's a MATLAB routine that will take a problem in SeDuMi's MATLAB format %and write it out in SDPpack format. % % First, check for complex numbers in A, b, or c. % if (isreal(A) ~= 1), disp('A is not real!'); return; end; if (isreal(b) ~= 1), disp('b is not real!'); return; end; if (isreal(c) ~= 1), disp('c is not real!'); return; end; % % Check for any rotated cone constraints. % if (isfield(K,'r') && (~isempty(K.r)) && (K.r ~= 0)), disp('rotated cone constraints are not yet supported.'); return; end; % % Get the size data. % if (isfield(K,'l')), nlin=K.l; sizelin=nlin; if (isempty(sizelin)), sizelin=0; nlin=0; end; else nlin=0; sizelin=0; end; if (isfield(K,'s')), nsdpblocks=length(K.s); %sizesdp=sum((K.s).^2); %if (isempty(sizesdp)), %sizesdp=0; %nsdpblocks=0; %end; else %sizesdp=0; nsdpblocks=0; end; if (isfield(K,'q')), nqblocks=length(K.q); sizeq=sum(K.q); if (isempty(sizeq)), sizeq=0; nqblocks=0; end; else nqblocks=0; sizeq=0; end; m=length(b); % % Open up the file for writing. % fid=fopen(fname,'w'); % % Print out m, the number of constraints. % fprintf(fid,'%d \n',m); % % Next, b, with one entry per line. % fprintf(fid,'%.18e\n',full(b)); % % Next, the semidefinite part. % if (nsdpblocks == 0), fprintf(fid,'0\n'); else % % Print out the number of semidefinite blocks. % fprintf(fid,'%d\n',nsdpblocks); % % For each block, print out its size. % fprintf(fid,'%d\n',full(K.s)); % % Next, the cost matrix C.s. % % % First, calculate where in c things start. % base=sizelin+sizeq+1; % % Next, work through the blocks. % for i=1:nsdpblocks, fprintf(fid,'1\n'); work=c(base:base+K.s(i)^2-1); if nnz(work ~= work'), if (work ~= work'), disp('Non symmetric C.s matrix!'); work=(work+work')/2; end; work=triu(work); [II,JJ,V]=find(work); cnt=length(II); fprintf(fid,'%d\n',cnt); if (cnt ~= 0), fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]'); end; % % Next, update to the next base. % base=base+K.s(i)^2; end; % % Now, loop through the constraints, one at a time. % for cn=1:m, % % Print out the SDP part of constraint cn. % base=sizelin+sizeq+1; for i=1:nsdpblocks, fprintf(fid,'1\n'); if nnz(work ~= work'), work=reshape(work,K.s(i),K.s(i)); if (work ~= work'), disp('Non symmetric A.s matrix!'); work=(work+work')/2; end; work=triu(work); [II,JJ,V]=find(work); cnt=length(II); fprintf(fid,'%d\n',cnt); if (cnt ~= 0), fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]'); end; % % Next, update to the next base. % base=base+K.s(i)^2; end; % % Done with constraint cn % end; % % Done with SDP part. % end; % % Next, handle the Quadratic part. % % % Describe the Q blocks. % if (nqblocks == 0), fprintf(fid,'0\n'); else fprintf(fid,'%d\n',nqblocks); fprintf(fid,'%d\n',full(K.q)); % % Find C.q. % base=sizelin+1; cq=c(base:base+sizeq-1); % % Print out the C.q coefficients. % fprintf(fid,'%.18e\n',full(cq)); % % Next, the constraint matrix A.q. % Aq=A(:,base:base+sizeq-1); % % Print out the count of nonzeros. % [II,JJ,V]=find(Aq); cnt=length(II); fprintf(fid,'1\n'); fprintf(fid,'%d\n',cnt); if (cnt ~= 0), fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]'); end; % % End of handling quadratic part. % end; % % % Finally, handle the linear part. % if (nlin == 0), fprintf(fid,'0\n'); else % % Print out the number of linear variables. % fprintf(fid,'%d\n',nlin); % % Print out C.l % fprintf(fid,'%.18e\n',full(c(1:nlin))); % % Print out the A matrix. % Al=A(:,1:nlin); [II,JJ,V]=find(Al); cnt=length(II); fprintf(fid,'1\n'); fprintf(fid,'%d\n',cnt); if (cnt ~= 0), fprintf(fid,'%d\n%d\n%.18e\n',[II JJ V]'); end; end;
github
anantsrivastava30/SUVR-PET-ADNI-master
frompack.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sedumi/conversion/frompack.m
2,509
utf_8
a4730dcb4ec069944953dce753da973d
% FROMPACK Converts a cone problem in SDPPACK format to SEDUMI format. % % [At,c] = frompack(A,b,C,blk) Given a problem (A,b,C,blk) in the % SDPPACK-0.9-beta format, this produces At and c for use with % SeDuMi. This lets you execute % % [x,y,info] = SEDUMI(At,b,c,blk); % % IMPORTANT: this function assumes that the SDPPACK function `smat' % exists in your search path. % % SEE ALSO sedumi. function [At,c] = frompack(A,b,C,blk) % % This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko % Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1) % % Copyright (C) 2001 Jos F. Sturm (up to 1.05R5) % Dept. Econometrics & O.R., Tilburg University, the Netherlands. % Supported by the Netherlands Organization for Scientific Research (NWO). % % Affiliation SeDuMi 1.03 and 1.04Beta (2000): % Dept. Quantitative Economics, Maastricht University, the Netherlands. % % Affiliations up to SeDuMi 1.02 (AUG1998): % CRL, McMaster University, Canada. % Supported by the Netherlands Organization for Scientific Research (NWO). % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA % 02110-1301, USA% m = length(b); % ---------------------------------------- % In SDPPACK, 0s are sometimes used as emptyset and vice versa. % ---------------------------------------- if blk.l == 0 A.l = []; C.l = []; end if isempty(blk.q) A.q = []; C.q = []; end if isempty(blk.s) A.s = []; C.s = []; end % ---------------------------------------- % SDP: % ---------------------------------------- Asdp = []; if sum(blk.s) == 0 csdp = []; else for i=1:m Asdp = [Asdp blk2vec( smat(sparse(A.s(i,:)),blk.s), blk.s ) ]; end csdp = blk2vec(C.s,blk.s); end % ---------------------------------------- % Assemble LP, LORENTZ and SDP. %---------------------------------------- At = [A.l'; A.q'; Asdp]; c = [C.l; C.q; csdp];
github
anantsrivastava30/SUVR-PET-ADNI-master
feascpx.m
.m
SUVR-PET-ADNI-master/scripts/cvx/sedumi/conversion/feascpx.m
4,385
utf_8
c48c6cf336cdb94ad12b04e1efd2417b
% FEASCPX Generates a random sparse optimization problem with % linear, quadratic and semi-definite constraints. Output % can be used by SEDUMI. Includes complex-valued data. % % The following two lines are typical: % > [AT,B,C,K] = FEASCPX; % > [X,Y,INFO] = SEDUMI(AT,B,C,K); % % An extended version is: % > [AT,B,C,K] = FEASCPX(m,lpN,lorL,rconeL,sdpL,denfac) % % SEE ALSO sedumi AND feasreal. function [At,b,c,K] = feascpx(m,nLP,qL,rL,nL,denfac) % % This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko % Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1) % % Copyright (C) 2001 Jos F. Sturm (up to 1.05R5) % Dept. Econometrics & O.R., Tilburg University, the Netherlands. % Supported by the Netherlands Organization for Scientific Research (NWO). % % Affiliation SeDuMi 1.03 and 1.04Beta (2000): % Dept. Quantitative Economics, Maastricht University, the Netherlands. % % Affiliations up to SeDuMi 1.02 (AUG1998): % CRL, McMaster University, Canada. % Supported by the Netherlands Organization for Scientific Research (NWO). % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA % 02110-1301, USA% if nargin < 6 denfac = 0.1; if nargin < 5 nL = 1+ round(7*rand(1,5)); fprintf('Choosing random SDP-product cone K.s.\n') if nargin < 4 rL = 3 + round(4*rand(1,5)); fprintf('Choosing random LORENTZ R-product cone K.r.\n') if nargin < 3 qL = 3 + round(4*rand(1,5)); fprintf('Choosing random LORENTZ-product cone K.q.\n') if(nargin < 2) nLP = 10; fprintf('Choosing default K.l=%3.0f.\n',nLP) if nargin < 1 m=10; fprintf('Choosing default m=%3.0f.\n',m) end end end end end end if isempty(nLP) nLP = 0; end nblk = length(nL) + length(rL) + length(qL) + nLP; denfac = min(1, max(denfac,2/nblk)); fprintf('Choosing block density denfac=%6.4f per row\n',denfac) Apattern=sparse(m,nblk); for j=1:m pati = sprandn(1,nblk,denfac); Apattern(j,:) = (pati~= 0); end sumnLsqr = sum(nL.^2); x = zeros(nLP+sum(qL)+sum(rL)+sumnLsqr,1); x(1:nLP) = rand(nLP,1); At = sparse(length(x),m); At(1:nLP,:) = sprandn(Apattern(:,1:nLP)'); firstk = nLP+1; %[nA, mA] = size(At); % LORENTZ: for k=1:length(qL) nk = qL(k); lastk = firstk + nk - 1; x(firstk) = rand; for j=1:m if Apattern(j,nLP+k)==1 At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk)) + sqrt(-1) * ... sparse([0;sprand(nk-1,1,1/sqrt(nk))]); end end firstk = lastk + 1; end % RCONE (Rotated Lorentz): for k=1:length(rL) nk = rL(k); lastk = firstk + nk - 1; x(firstk) = rand; x(firstk+1) = rand; for j=1:m if Apattern(j,nLP+length(qL)+k)==1 At(firstk:lastk,j) = sprand(nk,1,1/sqrt(nk)) + sqrt(-1) * ... sparse([0;0;sprand(nk-2,1,1/sqrt(nk-1))]); end end firstk = lastk + 1; end % SDP: for k=1:length(nL) nk = nL(k); lastk = firstk + nk*nk - 1; Xk = diag(rand(nk,1)); % diagonal, to keep sparsity structure x(firstk:lastk) = Xk; %although symmetric, store nk^2 elts. for j=1:m if Apattern(j,nLP+length(qL)+length(rL)+k)==1 rAik = sprandsym(nk,1/nk); %on average 1 nonzero per row iAik = sprand(nk,nk,1/nk); %on average 1 nonzero per row At(firstk:lastk,j) = vec(rAik + sqrt(-1)*(iAik-iAik')); end end firstk = lastk + 1; end b = real(full(At'*x)); y = rand(m,1)-0.5; c = sparse(At*y)+x; K.l = nLP; K.q = qL; K.r = rL; K.s = nL;
github
anantsrivastava30/SUVR-PET-ADNI-master
cvx_glpk.m
.m
SUVR-PET-ADNI-master/scripts/cvx/shims/cvx_glpk.m
4,344
utf_8
fc695a24b6757c72ebcc0c9422e98dca
function shim = cvx_glpk( shim ) % CVX_SOLVER_SHIM GLPK interface for CVX. % This procedure returns a 'shim': a structure containing the necessary % information CVX needs to use this solver in its modeling framework. if ~isempty( shim.solve ), return end if isempty( shim.name ), fname = 'glpk.m'; ps = pathsep; shim.name = 'GLPK'; shim.dualize = true; flen = length(fname); fpaths = which( fname, '-all' ); if ~iscell(fpaths), fpaths = { fpaths }; end old_dir = pwd; oshim = shim; shim = []; for k = 1 : length(fpaths), fpath = fpaths{k}; if ~exist( fpath, 'file' ) || any( strcmp( fpath, fpaths(1:k-1) ) ), continue end new_dir = fpath(1:end-flen-1); cd( new_dir ); tshim = oshim; tshim.fullpath = fpath; tshim.version = 'unknown'; tshim.location = new_dir; if isempty( tshim.error ), tshim.check = @check; tshim.solve = @solve; tshim.eargs = {}; if k ~= 1, tshim.path = [ new_dir, ps ]; end end shim = [ shim, tshim ]; %#ok end cd( old_dir ); if isempty( shim ), shim = oshim; shim.error = 'Could not find a GLPK installation.'; end else shim.check = @check; shim.solve = @solve; end function found_bad = check( nonls ) %#ok found_bad = false; function [ x, status, tol, iters, y, z ] = solve( At, b, c, nonls, quiet, prec, settings ) n = length( c ); m = length( b ); lb = -Inf(n,1); ub = +Inf(n,1); vtype = 'C'; vtype = vtype(ones(n,1)); ctype = 'S'; ctype = ctype(ones(m,1)); rr = zeros(0,1); cc = rr; vv = rr; zinv = rr; is_ip = false; for k = 1 : length( nonls ), temp = nonls( k ).indices; nn = size( temp, 1 ); nv = size( temp, 2 ); tt = nonls( k ).type; if strncmp( tt, 'i_', 2 ), is_ip = true; vartype(temp) = 'I'; if strcmp(tt,'i_binary'), lb(temp) = 0; ub(temp) = 1; end elseif nn == 1 || isequal( tt, 'nonnegative' ), lb(temp) = 0; elseif isequal( tt, 'lorentz' ), if nn == 2, rr2 = [ temp ; temp ]; cc2 = reshape( floor( 1 : 0.5 : 2 * nv + 0.5 ), 4, nv ); vv2 = [1;1;-1;1]; vv = vv(:,ones(1,nv)); rr = [ rr ; rr(:) ]; cc = [ cc ; cc(:) ]; vv = [ vv ; vv(:) ]; zinv = [ zinv ; temp(:) ]; else error('GLPK does not support nonlinear constraints.' ); end else error('GLPK does not support nonlinear constraints.' ); end end if ~isempty(rr), znorm = [1:n]'; znorm(zinv) = []; rr = [ rr ; znorm ]; cc = [ cc ; znorm ]; vv = [ vv ; ones(size(znorm)) ]; reord = sparse( rr, cc, vv, n, n ); At = reord' * At; c = reord' * c; end if quiet, param.msglev = 0; else param.msglev = 2; end param.scale = 128; param.tolbnd = prec(1); param.toldj = prec(1); param.tolobj = prec(1); [ xx, fmin, errnum, extra ] = cvx_run_solver( @glpk, c, At', b, lb, ub, ctype, vtype, 1, param, 'xx', 'fmin', 'errnum', 'extra', settings, 9 ); tol = []; iters = []; x = full( xx ); y = full( extra.lambda ); z = full( extra.redcosts ); if ~isempty( rr ), x = reord * x; z = reord * z; z(zinv) = z(zinv) * 0.5; end status = 'Failed'; switch errnum, case 0, switch extra.status, case 2, if is_ip, status = 'Suboptimal'; elseif errnumn == 0, status = 'Solved'; else status = 'Inaccurate/Solved'; end case {3,4}, status = 'Infeasible'; case 5, status = 'Solved'; case 6, status = 'Unbounded'; end case 10, status = 'Infeasible'; case 11, status = 'Unbounded'; case {5,17,15,19} status = 'Failed'; case {6,7,8,9,13,14}, switch extra.status, case {2,5} if is_ip, status = 'Suboptimal'; else status = 'Inaccurate/Solved'; end case { 3,4 }, status = 'Inaccurate/Infeasible'; case 6, status = 'Inaccurate/Unbounded'; end end if strcmp(status,'Failed'), tol = Inf; elseif strncmp(status,'Inaccurate/',11), tol = prec(3); else tol = prec(2); end % Copyright 2005-2016 CVX Research, Inc. % See the file LICENSE.txt for full copyright information. % The command 'cvx_where' will show where this file is located.
github
anantsrivastava30/SUVR-PET-ADNI-master
cvx_sedumi.m
.m
SUVR-PET-ADNI-master/scripts/cvx/shims/cvx_sedumi.m
10,740
utf_8
42324556d877c6a43224d410f1a12290
function shim = cvx_sedumi( shim ) % CVX_SOLVER_SHIM SeDuMi interface for CVX. % This procedure returns a 'shim': a structure containing the necessary % information CVX needs to use this solver in its modeling framework. global cvx___ if ~isempty( shim.solve ), return end if isempty( shim.name ), fname = 'sedumi.m'; fs = cvx___.fs; ps = cvx___.ps; int_path = [ cvx___.where, fs ]; int_plen = length( int_path ); shim.name = 'SeDuMi'; shim.dualize = true; flen = length(fname); fpaths = { [ int_path, 'sedumi', fs, fname ] }; fpaths = [ fpaths ; which( fname, '-all' ) ]; old_dir = pwd; oshim = shim; shim = []; for k = 1 : length(fpaths), fpath = fpaths{k}; if ~exist( fpath, 'file' ) || any( strcmp( fpath, fpaths(1:k-1) ) ), continue end new_dir = fpath(1:end-flen-1); cd( new_dir ); tshim = oshim; tshim.fullpath = fpath; tshim.version = 'unknown'; is_internal = strncmp( new_dir, int_path, int_plen ); if is_internal, tshim.location = [ '{cvx}', new_dir(int_plen:end) ]; else tshim.location = new_dir; end try fid = fopen(fname); otp = fread(fid,Inf,'uint8=>char')'; fclose(fid); catch errmsg tshim.error = sprintf( 'Unexpected error:\n%s\n', errmsg.message ); end if isempty( tshim.error ), otp = regexp( otp, 'SeDuMi \d\S+', 'match' ); if ~isempty(otp), tshim.version = otp{end}(8:end); end vnum = str2double( tshim.version ); tshim.check = @check; tshim.solve = @solve; tshim.eargs = { vnum >= 1.3 && vnum < 1.32 }; if k ~= 2, tshim.path = [ new_dir, ps ]; if ~isempty(cvx___.msub) && exist([new_dir,fs,cvx___.msub],'dir'), tshim.path = [ new_dir, fs, cvx___.msub, ps, tshim.path ]; end end end shim = [ shim, tshim ]; %#ok end cd( old_dir ); if isempty( shim ), shim = oshim; shim.error = 'Could not find a SeDuMi installation.'; end else shim.check = @check; shim.solve = @solve; vnum = str2double( shim.version ); shim.eargs = { vnum >= 1.3 && vnum < 1.32 }; end function found_bad = check( nonls ) %#ok found_bad = false; function [ x, status, tol, iters, y, z ] = solve( At, b, c, nonls, quiet, prec, settings, nocplx ) n = length( c ); m = length( b ); K = struct( 'f', 0, 'l', 0, 'q', [], 'r', [], 's', [], 'scomplex', [], 'ycomplex', [] ); reord = struct( 'n', 0, 'r', [], 'c', [], 'v', [] ); reord = struct( 'f', reord, 'l', reord, 'a', reord, 'q', reord, 'r', reord, 's', reord, 'h', reord ); reord.f.n = n; zinv = []; for k = 1 : length( nonls ), temp = nonls( k ).indices; nn = size( temp, 1 ); nv = size( temp, 2 ); nnv = nn * nv; tt = nonls( k ).type; reord.f.n = reord.f.n - nnv; if strncmp( tt, 'i_', 2 ), error( 'SeDuMi does not support integer variables.' ); elseif nn == 1 || isequal( tt, 'nonnegative' ), reord.l.r = [ reord.l.r ; temp(:) ]; reord.l.c = [ reord.l.c ; reord.l.n + ( 1 : nnv )' ]; reord.l.v = [ reord.l.v ; ones( nnv, 1 ) ]; reord.l.n = reord.l.n + nnv; elseif isequal( tt, 'lorentz' ), if nn == 2, rr = [ temp ; temp ]; cc = reshape( floor( 1 : 0.5 : 2 * nv + 0.5 ), 4, nv ); vv = [1;1;-1;1]; vv = vv(:,ones(1,nv)); reord.a.r = [ reord.a.r ; rr(:) ]; reord.a.c = [ reord.a.c ; cc(:) + reord.a.n ]; reord.a.v = [ reord.a.v ; vv(:) ]; reord.a.n = reord.a.n + nnv; zinv = [ zinv ; temp(:) ]; %#ok else temp = temp( [ end, 1 : end - 1 ], : ); reord.q.r = [ reord.q.r ; temp(:) ]; reord.q.c = [ reord.q.c ; reord.q.n + ( 1 : nnv )' ]; reord.q.v = [ reord.q.v ; ones(nnv,1) ]; reord.q.n = reord.q.n + nnv; K.q = [ K.q, nn * ones( 1, nv ) ]; end elseif isequal( tt, 'semidefinite' ), if nn == 3, temp = temp( [1,3,2], : ); tempv = [sqrt(2);sqrt(2);1] * ones(1,nv); reord.r.r = [ reord.r.r ; temp(:) ]; reord.r.c = [ reord.r.c ; reord.r.n + ( 1 : nnv )' ]; reord.r.v = [ reord.r.v ; tempv(:) ]; reord.r.n = reord.r.n + nnv; K.r = [ K.r, 3 * ones( 1, nv ) ]; temp = temp(1:2,:); zinv = [ zinv ; temp(:) ]; %#ok else nn = 0.5 * ( sqrt( 8 * nn + 1 ) - 1 ); str = cvx_create_structure( [ nn, nn, nv ], 'symmetric' ); K.s = [ K.s, nn * ones( 1, nv ) ]; [ cc, rr, vv ] = find( cvx_invert_structure( str, 'compact' ) ); rr = temp( rr ); reord.s.r = [ reord.s.r; rr( : ) ]; reord.s.c = [ reord.s.c; cc( : ) + reord.s.n ]; reord.s.v = [ reord.s.v; vv( : ) ]; reord.s.n = reord.s.n + nn * nn * nv; reord.s.z = reord.s.v; end elseif isequal( tt, 'hermitian-semidefinite' ), if nn == 4, temp = temp( [1,4,2,3], : ); tempv = [sqrt(2);sqrt(2);1;1] * ones(1,nv); reord.r.r = [ reord.r.r ; temp(:) ]; reord.r.c = [ reord.r.c ; reord.r.n + ( 1 : nnv )' ]; reord.r.v = [ reord.r.v ; tempv(:) ]; reord.r.n = reord.r.n + nnv; reord.r.z = reord.r.v; K.r = [ K.r, 4 * ones( 1, nv ) ]; temp = temp(1:2,:); zinv = [ zinv ; temp(:) ]; %#ok elseif nocplx, % SeDuMi's complex SDP support was broken with the 1.3 update. So % we must use the following complex-to-real SDP conversion to work % around it, at a modest cost of problem size. % X >= 0 <==> exists [ Y1, Y2^T ; Y2, Y3 ] >= 0 s.t. % Y1 + Y3 == real(X), Y2 - Y2^T == imag(X) nsq = nn; nn = sqrt( nn ); str = cvx_create_structure( [ nn, nn, nv ], 'hermitian' ); [ cc, rr, vv ] = find( cvx_invert_structure( str, 'compact' ) ); cc = cc - 1; mm = floor( cc / nsq ); cc = cc - mm * nsq; jj = floor( cc / nn ); ii = cc - jj * nn + 1; jj = jj + 1; mm = mm + 1; vr = real( vv ); vi = imag( vv ); ii = [ ii + nn * ~vr ; ii + nn * ~vi ]; jj = [ jj ; jj + nn ]; %#ok vv = sqrt( 0.5 ) * [ vr + vi ; vr - vi ]; rr = [ rr ; rr ]; %#ok mm = [ mm ; mm ]; %#ok [ jj, ii ] = deal( min( ii, jj ), max( ii, jj ) ); cc = ii + ( jj - 1 ) * ( 2 * nn ) + ( mm - 1 ) * ( 4 * nsq ); K.s = [ K.s, 2 * nn * ones( 1, nv ) ]; rr = temp( rr ); reord.s.r = [ reord.s.r; rr( : ) ]; reord.s.c = [ reord.s.c; cc( : ) + reord.s.n ]; reord.s.v = [ reord.s.v; vv( : ) ]; reord.s.n = reord.s.n + 4 * nsq * nv; reord.s.z = reord.s.v; else % SeDuMi's complex SDP support was restored in v1.33. K.scomplex = [ K.scomplex, length( K.s ) + ( 1 : nv ) ]; nn = sqrt( nn ); str = cvx_create_structure( [ nn, nn, nv ], 'hermitian' ); K.s = [ K.s, nn * ones( 1, nv ) ]; stri = cvx_invert_structure( str, 'compact' )'; [ rr, cc, vv ] = find( stri ); rr = temp( rr ); reord.s.r = [ reord.s.r; rr( : ) ]; reord.s.c = [ reord.s.c; cc( : ) + reord.s.n ]; reord.s.v = [ reord.s.v; vv( : ) ]; reord.s.n = reord.s.n + size( stri, 2 ); reord.s.z = reord.s.v; end else error( 'Unsupported nonlinearity: %s', tt ); end end if reord.f.n > 0, reord.f.r = ( 1 : n )'; reord.f.r( [ reord.l.r ; reord.a.r ; reord.q.r ; reord.r.r ; reord.s.r ] ) = []; reord.f.c = ( 1 : reord.f.n )'; reord.f.v = ones(reord.f.n,1); end n_d = max( m - n - reord.f.n + 1, isempty( At ) ); if n_d, reord.l.n = reord.l.n + n_d; end K.f = reord.f.n; K.l = reord.l.n + reord.a.n; n_out = reord.f.n; reord.l.c = reord.l.c + n_out; n_out = n_out + reord.l.n; reord.a.c = reord.a.c + n_out; n_out = n_out + reord.a.n; reord.q.c = reord.q.c + n_out; n_out = n_out + reord.q.n; reord.r.c = reord.r.c + n_out; n_out = n_out + reord.r.n; reord.s.c = reord.s.c + n_out; n_out = n_out + reord.s.n; reord = sparse( ... [ reord.f.r ; reord.l.r ; reord.a.r ; reord.q.r ; reord.r.r ; reord.s.r ], ... [ reord.f.c ; reord.l.c ; reord.a.c ; reord.q.c ; reord.r.c ; reord.s.c ], ... [ reord.f.v ; reord.l.v ; reord.a.v ; reord.q.v ; reord.r.v ; reord.s.v ], ... n, n_out ); At = reord' * At; c = reord' * c; pars.free = K.f > 1 && nnz( K.q ); pars.eps = prec(1); pars.bigeps = prec(3); if quiet, pars.fid = 0; end add_row = isempty( At ); if add_row, K.f = K.f + 1; At = sparse( 1, 1, 1, n_out + 1, 1 ); b = 1; c = [ 0 ; c ]; end [ xx, yy, info ] = cvx_run_solver( @sedumi, At, b, c, K, pars, 'xx', 'yy', 'info', settings, 5 ); if add_row, xx = xx(2:end); yy = zeros(0,1); At = zeros(n_out,0); % b = zeros(0,1); c = c(2:end); end if ~isfield( info, 'r0' ) && info.pinf, info.r0 = 0; info.iter = 0; info.numerr = 0; end tol = info.r0; iters = info.iter; xx = full( xx ); yy = full( yy ); status = ''; if info.pinf ~= 0, status = 'Infeasible'; x = NaN * ones( n, 1 ); y = yy; z = - real( reord * ( At * yy ) ); if add_row, y = zeros( 0, 1 ); end elseif info.dinf ~= 0 status = 'Unbounded'; y = NaN * ones( m, 1 ); z = NaN * ones( n, 1 ); x = real( reord * xx ); else x = real( reord * xx ); y = yy; z = real( reord * ( c - At * yy ) ); if add_row, y = zeros( 0, 1 ); end end if ~isempty(zinv), z(zinv) = z(zinv) * 0.5; end if info.numerr == 2, status = 'Failed'; if any( K.q == 2 ), warning( 'CVX:SeDuMi', cvx_error_format( 'This solver failure may possibly be due to a known bug in the SeDuMi solver. Try switching to SDPT3 by inserting "cvx_solver sdpt3" into your model.', ... [66,75], false, '' ) ); end else if isempty( status ), status = 'Solved'; end if info.numerr == 1 && info.r0 > prec(2), status = [ 'Inaccurate/', status ]; end end % Copyright 2005-2016 CVX Research, Inc. % See the file LICENSE.txt for full copyright information. % The command 'cvx_where' will show where this file is located.
github
anantsrivastava30/SUVR-PET-ADNI-master
cvx_sdpt3.m
.m
SUVR-PET-ADNI-master/scripts/cvx/shims/cvx_sdpt3.m
12,657
utf_8
b42871a1a82cd274121bc52919caa778
function shim = cvx_sdpt3( shim ) % CVX_SOLVER_SHIM SDPT3 interface for CVX. % This procedure returns a 'shim': a structure containing the necessary % information CVX needs to use this solver in its modeling framework. global cvx___ if ~isempty( shim.solve ), return end if isempty( shim.name ), fname = 'sdpt3.m'; ps = cvx___.ps; fs = cvx___.fs; int_path = [ cvx___.where, fs ]; int_plen = length( int_path ); shim.name = 'SDPT3'; shim.dualize = true; flen = length(fname); fpaths = { [ int_path, 'sdpt3', fs, fname ] }; fpaths = [ fpaths ; which( fname, '-all' ) ]; old_dir = pwd; oshim = shim; shim = []; for k = 1 : length(fpaths), fpath = fpaths{k}; if ~exist( fpath, 'file' ) || any( strcmp( fpath, fpaths(1:k-1) ) ), continue end new_dir = fpath(1:end-flen-1); cd( new_dir ); tshim = oshim; tshim.fullpath = fpath; tshim.version = 'unknown'; is_internal = strncmp( new_dir, int_path, int_plen ); if is_internal, tshim.location = [ '{cvx}', new_dir(int_plen:end) ]; else tshim.location = new_dir; end try fid = fopen(fname); otp = fread(fid,Inf,'uint8=>char')'; fclose(fid); catch errmsg tshim.error = sprintf( 'Unexpected error:\n%s\n', errmsg.message ); end if isempty( tshim.error ), otp = regexp( otp, 'SDPT3: version \d+\.\d+', 'match' ); if ~isempty(otp), tshim.version = otp{1}(16:end); end if k ~= 2, tpath = { new_dir, [ new_dir, fs, 'Solver' ], [ new_dir, fs, 'HSDSolver' ], [ new_dir, fs, 'Solver', fs, 'Mexfun' ] }; if ~isempty(cvx___.msub) && exist( [ tpath{end}, fs, cvx___.msub ], 'dir' ), tpath{end} = [ tpath{end}, fs, cvx___.msub ]; end tpath = sprintf( [ '%s', ps ], tpath{:} ) ; tshim.path = tpath; end tshim.check = @check; tshim.solve = @solve; tshim.eargs = {}; end shim = [ shim, tshim ]; %#ok end cd( old_dir ); if isempty( shim ), shim = oshim; shim.error = 'Could not find a SDPT3 installation.'; end else shim.check = @check; shim.solve = @solve; shim.eargs = {}; end function found_bad = check( nonls ) %#ok found_bad = false; function [ x, status, tol, iters, y, z ] = solve( At, b, c, nonls, quiet, prec, settings ) [n,m] = size(At); % SDPT3 cannot handle empty equality constraints or square systems. So % add an extra row or column, as needed, to rectify this problem. mzero = m == 0 | isempty( nonls ) | m == n; if mzero, n = n + 1; c = [ c ; 0 ]; if m == 0, azero = true; At = sparse( n, 1, 1 ); b = 1; m = 1; elseif m + 1 < n, azero = true; At(end+1,end+1) = 1; b(end+1) = 1; m = m + 1; else At(end+1,end) = 0; azero = false; end nonls(end+1).type = 'nonnegative'; nonls(end).indices = n; else azero = false; end types = { nonls.type }; indices = { nonls.indices }; found = false(1,length(types)); used = false(1,n); blk = cell( 0, 2 ); Avec = cell( 0, 1 ); Cvec = cell( 0, 1 ); xvec = cell( 0, 1 ); tvec = cell( 0, 1 ); if nargout > 3, need_z = true; zvec = cell( 0, 1 ); else need_z = false; end % % Reject integer variables % if any( strncmp( types, 'i_', 2 ) ), error( 'SDTP3 does not support integer variables.' ); end % % Nonnegative variables preserved as-is % tt = find( strcmp( types, 'nonnegative' ) ); if ~isempty( tt ), for k = tt, ti = indices{k}; indices{k} = reshape(ti,1,numel(ti)); end ti = cat( 2, indices{tt} ); ni = length(ti); blk {end+1,1} = 'l'; blk {end, 2} = ni; Avec{end+1,1} = At(ti,:); Cvec{end+1,1} = c(ti); tvec{end+1,1} = ti; xvec{end+1,1} = 1; if need_z, zvec{end+1,1} = 1; end found(tt) = true; used(ti) = true; end % % SDTP3 places the epigraph variable of an SOC { (x,y) | ||x||<=y } % at the beginning of the vector; CVX places it at the end. So we must % reverse our ordering here. % tt = find( strcmp( types, 'lorentz' ) ); if ~isempty( tt ), blk{end+1,1} = 'q'; blk{end,2} = zeros(1,0); for k = tt, ti = indices{k}; ti = ti([end,1:end-1],:); blk{end,2} = [ blk{end,2}, size(ti,1) * ones(1,size(ti,2)) ]; indices{k} = reshape(ti,1,numel(ti)); end ti = cat( 2, indices{tt} ); Avec{end+1,1} = At(ti,:); Cvec{end+1,1} = c(ti); tvec{end+1,1} = ti; xvec{end+1,1} = 1; if need_z, zvec{end+1,1} = 1; end found(tt) = true; used(ti) = true; end tt = find( strcmp( types, 'semidefinite' ) | strcmp( types, 'hermitian-semidefinite' ) ); if ~isempty( tt ), blk{end+1,1} = 's'; blk{end,2} = {}; Avec{end+1,1} = {}; Cvec{end+1,1} = {}; tvec{end+1,1} = {}; xvec{end+1,1} = {}; if need_z, zvec{end+1,1} = {}; end nnn = 0; for k = tt, ti = indices{k}; [nt,nv] = size(ti); if types{k}(1) == 's', nn = 0.5*(sqrt(8*nt+1)-1); else nn = 2*sqrt(nt); end nnn = nnn + nn*nv; end for k = tt, ti = indices{k}; [nt,nv] = size(ti); if types{k}(1) == 's', nn = 0.5 * ( sqrt(8*nt+1) - 1 ); nt2 = nt; n2 = nn; else nn = sqrt(nt); n2 = 2 * nn; nt2 = 0.5 * n2 * ( n2 + 1 ); end blk{end,2}{end+1} = n2 * ones(1,nv); tvec{end}{end+1} = ti(:); if types{k}(1) == 's', % % CVX stores symmetric matrix variables in packed lower triangle % form; and str_1 is the adjoint of the mapping from packed form to % unpacked form. That is, if x is an n(n+1)/2 by 1 vector, then % str_1' * x is the n x n symmetric matrix. To preserve inner % products we need the inverse operator as well: % <a,x> = <a,str_2'*str_1'*x> = <str_2*a,str_1'*x> % str_1 = cvx_create_structure( [nn,nn], 'symmetric' ); else % % SDPT3 does not do complex SDP natively. To convert to real SDPs % there are two approaches; % X >= 0 <==> [ real(X), -imag(X) ; imag(X), real(X) ] >= 0 % X >= 0 <==> exists [ Y1, Y2^T ; Y2, Y3 ] >= 0 s.t. % Y1 + Y3 == real(X), Y2 - Y2^T == imag(X) % For primal standard form, this second form is the best choice, % and what we end up using here. % str_1 = cvx_create_structure( [nn,nn], 'hermitian' ); [rr,cr,vr] = find(real(str_1)); cr = cr + floor((cr-1)/nn)*nn; [ri,ci,vi] = find(imag(str_1)); ci = ci + floor((ci-1)/nn)*nn; str_1 = sparse( [rr;ri;ri;rr], [cr;ci+nn;ci+n2*nn;cr+nn*(n2+1)], [vr;vi;-vi;vr], nt, n2^2 ); end str_2 = cvx_invert_structure( str_1 ); % % SDPT3, on the other hand, stores symmetric matrix variables in % packed upper triangle format, with off-diagonal elements scaled % by sqrt(2) to preserve inner products. The operator is unitary: % <str_2*a,str_1'*x> = <str_3*str_2*a,str_3*str_1'*x> % str_3 = sqrt(0.5) * ones(nt2,1); str_3(cumsum(1:n2)) = 1; str_3 = spdiags( str_3, 0, nt2, nt2 ) * cvx_s_symmetric_ut( n2, n2, true ); Avec{end}{end+1} = reshape( ( str_3 * str_2 ) * reshape( At(ti,:), nt, nv * m ), nt2 * nv, m ); % % SDPT3 expects C to be in the form of a symmetric matrix, so we % only need to do half the work. % <c,x> == <str_2*c,str_1'*x> % cc = reshape( str_2 * reshape( c(ti,:), nt, nv ), n2, n2 * nv ); if nv > 1, % For multiple matrices, SDPT3 expects the blocks to be stacked % along the diagonal, but our calculation above stacks them into % a single row. A simple row offset fixes this. [ rr, cc, vv ] = find( cc ); cc = sparse( rr + floor((cc-1)/n2)*n2, cc, vv, n2 * nv, n2 * nv ); end Cvec{end}{end+1} = cc; % % SDPT3 presents X in symmetric form. We must extract the lower % triangle for CVX. No scaling is needed. For multiple blocks we % must add row offsets to handle the block diagonal form. % [ rr, cc, vv ] = find( str_2' ); cc = cc + floor((cc-1)/n2)*(nnn-n2); if nv > 1, ov = ones(1,nv); sv = 0:nv-1; or = ones(length(rr),1); rr = rr(:,ov) + or*(sv*nt); cc = cc(:,ov) + or*(sv*(n2*(nnn+1))); vv = vv(:,ov); end xvec{end}{end+1} = sparse( cc, rr, vv, n2*nv*(nnn+1), nt*nv ); if need_z, [ rr, cc, vv ] = find( str_1 ); cc = cc + floor((cc-1)/n2)*(nnn-n2); if nv > 1, ov = ones(1,nv); sv = 0:nv-1; or = ones(length(rr),1); rr = rr(:,ov) + or*(sv*nt); cc = cc(:,ov) + or*(sv*(n2*(nnn+1))); vv = vv(:,ov); end zvec{end}{end+1} = sparse( cc, rr, vv, n2*nv*(nnn+1), nt*nv ); end used(ti) = true; end blk{end,2} = horzcat( blk{end,2}{:} ); Avec{end} = vertcat( Avec{end}{:} ); Cvec{end} = cvx_blkdiag( Cvec{end}{:} ); tvec{end} = vertcat( tvec{end}{:} ); xvec{end} = cvx_blkdiag( xvec{end}{:} ); xvec{end}(nnn*nnn+1:end,:) = []; if need_z, zvec{end} = cvx_blkdiag( zvec{end}{:} ); zvec{end}(nnn*nnn+1:end,:) = []; end found(tt) = true; end ti = find(~found); if ~isempty(ti), types = unique( types(ti) ); types = sprintf( ' %s', types{:} ); error( 'One or more unsupported nonlinearities detected: %s', types ); end ti = find(~used); if ~isempty(ti), ni = numel(ti); ti = reshape( ti, 1, ni ); blk {end+1,1} = 'u'; blk {end, 2} = ni; Avec{end+1,1} = At(ti,:); Cvec{end+1,1} = c(ti); tvec{end+1,1} = ti; xvec{end+1,1} = 1; if need_z, zvec{end+1,1} = 1; end % found(tt) = true; % used(ti) = true; end % % Call SDPT3 % b = full(b); OPTIONS = sqlparameters; OPTIONS.gaptol = prec(1); OPTIONS.printlevel = 3 * ~quiet; warn_save = warning; [ obj, xx, y, zz, info ] = cvx_run_solver( @sqlp, blk, Avec, Cvec, b, OPTIONS, 'obj', 'x', 'y', 'z', 'info', settings, 5 ); %#ok warning( warn_save ); tol = max( [ info.relgap, info.pinfeas, info.dinfeas ] ); if ~quiet, disp(' '); end % % Interpret status codes % x_good = true; y_good = true; switch info.termcode, case 0, status = 'Solved'; tol = min( prec(2), tol ); case 1, status = 'Infeasible'; x_good = false; tol = min( info.dinfeas, prec(2) ); case 2, status = 'Unbounded'; y_good = false; tol = min( info.pinfeas, prec(2) ); otherwise, if isnan(tol), tol = Inf; status = 'Failed'; elseif tol > prec(3), status = 'Failed'; elseif tol <= prec(2), status = 'Solved'; info.termcode = 0; else status = 'Inaccurate/Solved'; info.termcode = 0; end end % Primal point if x_good, x = zeros(1,n); for k = 1 : length(xx), x(1,tvec{k}) = x(1,tvec{k}) + xx{k}(:)' * xvec{k}; end end if x_good && all(isfinite(x)), x = full( x )'; else x = NaN * ones(n,1); end if mzero, x(end) = []; end % Lagrange multipliers if y_good, y = full(y); end if ~y_good || ~all(isfinite(y)), y = NaN * ones(m,1); end if azero, y(end,:) = []; end % Iteration count iters = info.iter; % Dual cone if need_z, if y_good, z = zeros(1,n); for k = 1 : length(zz), z(1,tvec{k}) = z(1,tvec{k}) + zz{k}(:)' * zvec{k}; end end if y_good && all(isfinite(z)), z = full( z )'; else z = NaN * ones(n,1); end if mzero, z(end) = []; end end % Copyright 2005-2016 CVX Research, Inc. % See the file LICENSE.txt for full copyright information. % The command 'cvx_where' will show where this file is located.
github
dipankarsk/Feature-Selection-Hybrid-master
LoadData.m
.m
Feature-Selection-Hybrid-master/LoadData.m
226
utf_8
78032a391706c39e86c1fa384a530fe1
function data=LoadData() dataset=load('bodyfat_data3'); data.x=dataset.input; data.t=dataset.target; data.nx=size(data.x,1); data.nt=size(data.t,1); data.nSample=size(data.x,2); end
github
dipankarsk/Feature-Selection-Hybrid-master
SinglePointCrossover.m
.m
Feature-Selection-Hybrid-master/SinglePointCrossover.m
179
utf_8
bd27bb61610d49f21b6958bf5537fc87
function [y1, y2]=SinglePointCrossover(x1,x2) nVar=numel(x1); c=randi([1 nVar-1]); y1=[x1(1:c) x2(c+1:end)]; y2=[x2(1:c) x1(c+1:end)]; end
github
dipankarsk/Feature-Selection-Hybrid-master
UniformCrossover.m
.m
Feature-Selection-Hybrid-master/UniformCrossover.m
164
utf_8
5bb55be5ce6a3ead7481905bc412d7b5
function [y1, y2]=UniformCrossover(x1,x2) alpha=randi([0 1],size(x1)); y1=alpha.*x1+(1-alpha).*x2; y2=alpha.*x2+(1-alpha).*x1; end
github
dipankarsk/Feature-Selection-Hybrid-master
Crossover.m
.m
Feature-Selection-Hybrid-master/Crossover.m
491
utf_8
b77ebcbddbbe391a41c9e2712e2b38c5
function [y1, y2]=Crossover(x1,x2) pSinglePoint=0.1; pDoublePoint=0.2; pUniform=1-pSinglePoint-pDoublePoint; METHOD=RouletteWheelSelection([pSinglePoint pDoublePoint pUniform]); switch METHOD case 1 [y1, y2]=SinglePointCrossover(x1,x2); case 2 [y1, y2]=DoublePointCrossover(x1,x2); case 3 [y1, y2]=UniformCrossover(x1,x2); end end
github
dipankarsk/Feature-Selection-Hybrid-master
FeatureSelectionCost.m
.m
Feature-Selection-Hybrid-master/FeatureSelectionCost.m
1,054
utf_8
db056076415b1d99276adc81424f91fb
function [z, out]=FeatureSelectionCost(s,data) % Read Data Elements x=data.x; t=data.t; % Selected Features S=find(s~=0); % Number of Selected Features nf=numel(S); % Ratio of Selected Features rf=nf/numel(s); % Selecting Features xs=x(S,:); % Weights of Train and Test Errors wTrain=0.8; wTest=1-wTrain; % Number of Runs nRun=1; EE=zeros(1,nRun); for r=1:nRun % Create and Train ANN results=CreateAndTrainANN(xs,t); % Calculate Overall Error EE(r) = wTrain*results.TrainData.E + wTest*results.TestData.E; end E=mean(EE); %if isinf(E) % E=1e10; %end % Calculate Final Cost beta=0.5; z=E*(1+beta*rf); % Set Outputs out.S=S; out.nf=nf; out.rf=rf; out.E=E; out.z=z; %out.net=results.net; %out.Data=results.Data; %out.TrainData=results.TrainData; %out.TestData=results.TestData; end
github
dipankarsk/Feature-Selection-Hybrid-master
RouletteWheelSelection.m
.m
Feature-Selection-Hybrid-master/RouletteWheelSelection.m
121
utf_8
57f6bdead1494c070c43bc21d455f517
function i=RouletteWheelSelection(P) r=rand; c=cumsum(P); i=find(r<=c,1,'first'); end
github
dipankarsk/Feature-Selection-Hybrid-master
DoublePointCrossover.m
.m
Feature-Selection-Hybrid-master/DoublePointCrossover.m
245
utf_8
db8e17565fbfda7bc414bf2a0f3f8382
function [y1, y2]=DoublePointCrossover(x1,x2) nVar=numel(x1); cc=randsample(nVar-1,2); c1=min(cc); c2=max(cc); y1=[x1(1:c1) x2(c1+1:c2) x1(c2+1:end)]; y2=[x2(1:c1) x1(c1+1:c2) x2(c2+1:end)]; end
github
dipankarsk/Feature-Selection-Hybrid-master
Mutate.m
.m
Feature-Selection-Hybrid-master/Mutate.m
155
utf_8
c1f0095051ac33990eaad85e0ba0be8c
function y=Mutate(x,mu) nVar=numel(x); nmu=ceil(mu*nVar); j=randsample(nVar,nmu); y=x; y(j)=1-x(j); end
github
dipankarsk/Feature-Selection-Hybrid-master
CreateAndTrainANN.m
.m
Feature-Selection-Hybrid-master/CreateAndTrainANN.m
2,118
utf_8
068f56c52d912b04ba16da76e575b2bd
function results=CreateAndTrainANN(x,t) if ~isempty(x) hiddenLayerSize = 5; net = fitnet(hiddenLayerSize,trainFcn); net.input.processFcns = {'removeconstantrows','mapminmax'}; net.output.processFcns = {'removeconstantrows','mapminmax'}; net.divideFcn = 'dividerand'; % Divide data randomly net.divideMode = 'sample'; % Divide up every sample net.divideParam.trainRatio = 70/100; net.divideParam.valRatio = 15/100; net.divideParam.testRatio = 15/100; net.performFcn = 'mse'; % Mean squared error net.plotFcns = {}; net.trainParam.showWindow=false; net.trainParam.epochs=5; % Train the Network [net,tr] = train(net,x,t); % Test the Network y = net(x); e = gsubtract(t,y); E = perform(net,t,y); else y=inf(size(t)); e=inf(size(t)); E=inf; tr.trainInd=[]; tr.valInd=[]; tr.testInd=[]; end % All Data Data.x=x; Data.t=t; Data.y=y; Data.e=e; Data.E=E; % Train Data TrainData.x=x(:,tr.trainInd); TrainData.t=t(:,tr.trainInd); TrainData.y=y(:,tr.trainInd); TrainData.e=e(:,tr.trainInd); if ~isempty(x) TrainData.E=perform(net,TrainData.t,TrainData.y); else TrainData.E=inf; end % Validation and Test Data TestData.x=x(:,[tr.testInd tr.valInd]); TestData.t=t(:,[tr.testInd tr.valInd]); TestData.y=y(:,[tr.testInd tr.valInd]); TestData.e=e(:,[tr.testInd tr.valInd]); if ~isempty(x) TestData.E=perform(net,TestData.t,TestData.y); else TestData.E=inf; end % Export Results if ~isempty(x) results.net=net; else results.net=[]; end results.Data=Data; results.TrainData=TrainData; % results.ValidationData=ValidationData; results.TestData=TestData; end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
uniquepots.m
.m
bayesian-reasoning-machine-learning-master/src/uniquepots.m
1,370
utf_8
01144806ae1fd2ada3aaeeaa4a6c90ad
function [newpot A] = uniquepots(pot,varargin) %UNIQUEPOTS Eliminate redundant potentials (those contained wholly within another) by multiplying redundant potentials % [newpot A]= uniquepots(pot,<tables>) % if tables=0 then just merge the variables % The matrix has A(j,i)=1 if pot(i) is contained within pot(j) tables=1; if nargin==2; tables=varargin{1}; end % Find a tree of cliques by identifying a single parent clique j that contains clique i. C=length(pot); r=zeros(1,C); for i=1:C; r(i)=isempty(pot(i).variables); end pot=pot(~r);C=length(pot); A=sparse(C,C); for i=1:C j=1; while j<=C A(j,i)=ischildpot(pot,i,j); if A(j,i);break;end j=j+1; end end newpot=pot; % Now merge from bottom up [tree elimset sched]=istree(A); remove=zeros(1,C); if tables for s=1:size(sched,1) ch=sched(s,1); pa=sched(s,2); if ch~=pa newpot(pa)=multpots(newpot([pa ch])); remove(ch)=1; end end else for s=1:size(sched,1) ch=sched(s,2); pa=sched(s,1); if ch~=pa newpot(pa).variables=union(newpot(ch).variables,newpot(pa).variables); remove(ch)=1; end end end newpot=newpot(remove==0); function m = ischildpot(pot,i,j) if i==j; m=0; return; end m=all(ismember(pot(i).variables,pot(j).variables));
github
cosmicBboy/bayesian-reasoning-machine-learning-master
subsetsum.m
.m
bayesian-reasoning-machine-learning-master/src/subsetsum.m
2,689
utf_8
f8d7d15173c2e31dec9a155c9cc80873
function [q st]=subsetsum(x) %SUBSETSUM Solve the zero subset sum problem. % Input: x - a vector of integers % Outputs: q=1 if there is a binary 0/1 vector st such that % sum_i x(i).*st(i) = =0 % The method used is either dynamic programming or explicit enumeration, % depending on the number of variables and the precision of the integers. % The wikipedia dynamic programming method has complexity O(n*(P-N)), % where n is the number of variables, P the sum of positive x and N the sum of negative x. % This algorithmn is therefore practical only when the precision (number of % bits required to specify the elements of x is small. Otherwise, for small % n, and larger precision, one can just enumerate all 2^n binary states, % which would be more efficient. n=length(x); N=sum(x(x<0)); P=sum(x(x>0)); if n*log(2)> (log(n)+log(P-N)); do_dynamic_programming=1; else do_dynamic_programming=0; end if do_dynamic_programming offset=-min(N-x)+1; % offset ensures no negative indices Q=zeros(max(P-x+offset)); for s=N:P Q(1,s+offset)= (x(1)==s); end for i=2:n for s=N:P Q(i,s+offset)=Q(i-1,s+offset)| (x(i)==s) | Q(i-1,s-x(i)+offset); end end q=Q(n,0+offset); % q=1 if there is a solution st=zeros(1,n); % initialise solution if q % there is a solution, so find by backtracking: % idea is to start from the last point x(n). If there is a solution in % which the sum of a subset up to and including n-1 equals -x(n), then we % can include x(n) in the solution. We then add x(n) to the total, and move % on to x(n-1): tot=0; for i=n:-1:2 if tot+x(i)==0 st(i)=1; break; end if Q(i-1,offset-tot-x(i)) st(i)=1; tot=tot+x(i); if tot==0; break; end end end if sum(st(1:n).*x(1:n))~=0 st(1)=1; end end else % explicit enumeration of all 2^n states: st=ind2subv(2*ones(1,n),1:2^n)-1; vals=st*x(:); ind=find(vals==0); if isempty(ind) q=0; st=zeros(1,n); else q=1; st=vals(ind(1)); end end function out = ind2subv(siz,ndx) % out = ind2subv(siz,ndx) % % index to state : return a state vector of the linear index ndx, based on an array of size siz % For vector ndx, returns a matrix with each row containing the corresponding state vector k = [1 cumprod(siz(1:end-1))]; for i = length(siz):-1:1; vi = rem(ndx-1, k(i)) + 1; vj = (ndx - vi)./k(i) + 1;out(:,i) = vj;ndx = vi; end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
cliquedecomp.m
.m
bayesian-reasoning-machine-learning-master/src/cliquedecomp.m
4,181
utf_8
eb0a06cc65d47f1b7a21215da7603bc7
function[z zbest]=cliquedecomp(A,C,varargin) %CLIQUEDECOMP Clique matrix decomposition % A: adjacency matrix % C: maximum number of clusters required % opts.zloops: innerloop for a fixed number of cliques % opts.aloops: outerloop to find optimal number of clusters % opts.beta: inverse temperature % opts.burnin: set to 1 to do some initial burn in % opts.burninbeta: burn in beta value % opts.a_beta: Beta distribution a parameter % opts.b_beta: Beta distribution b parameter % see demoCliqueDecomp.m and cliquedecomp.c V=size(A,1); opts=[]; if nargin==3; opts=varargin{1}; end opts=setfields(opts,'zloops',ceil(V/10),'aloops',5,'beta',10,'a_beta',1,'b_beta',10,'plotprogress',1,'burnin',0);% default options beta=opts.beta; a_beta=opts.a_beta; b_beta=opts.b_beta; A=A-diag(diag(A)); A=A+eye(size(A,1)); % include self connections % Mean Field approximation of p(z_i=1|A) zm=real(rand(V,C)>0.0); % random initialisation ma=ones(1,C); zma=zm.*repmat(ma,V,1); errors=-1; olderror=10e100; zold=zm; zbest=zm; besterror=olderror; for loopa=1:opts.aloops if opts.burnin & loopa==1 thisbeta=opts.burninbeta; else thisbeta=beta; end for loopz=1:opts.zloops Mold = zma*zma'; for c=randperm(C) zc=zma(:,c); for k=randperm(V) Mk = Mold(:,k)-zc(:)*zc(k)+zma(:,c)*zma(k,c); logfn1=0;logfn0=0; for j=1:V mnfield0= Mk(j)-zma(j,c)*zma(k,c)-0.5; mnfield1= zma(j,c) + mnfield0; mnfield0=thisbeta*mnfield0; mnfield1=thisbeta*mnfield1; if A(j,k) logfn1=logfn1 + logsigma(mnfield1); logfn0=logfn0 + logsigma(mnfield0); else logfn1=logfn1 + logsigma(-mnfield1); logfn0=logfn0 + logsigma(-mnfield0); end % end if end % end for j zm(k,c) = 1/(1+exp(2*cap(logfn0-logfn1,100))); zma(k,c)=zm(k,c)*ma(c); end % end for k Mold = Mold-zc*zc'+zma(:,c)*zma(:,c)'; end % end for c z=zma>0.49; % threshold dz=double(z); AA= (dz*dz' > 0); AA = AA-diag(diag(AA)); AA = AA+diag(ones(1,V)); newerror= 0.5*sum(sum(AA~=A)); if newerror<besterror zbest=z; besterror=newerror; else z=zbest; newerror=besterror; end errors(loopz) = newerror; fprintf(1,'number of cliques=%d (after %d updates) | vertex loop %d| errors %d| best error %d| beta %f\n',... [C (loopa-1) loopz newerror besterror thisbeta]); if opts.plotprogress subplot(1,4,1);imagesc(A);colormap('bone');title('original');subplot(1,4,2);imagesc(AA); colormap('bone');title('approx');subplot(1,4,3); imagesc(z);colormap('bone');title('Z');subplot(1,4,4);plot(errors);drawnow; end end % end zloop %sum(z) %pause % update the number of cliques: if opts.aloops>1 zmatmp=zma; for c=1:C zmat=zmatmp; zmat(:,c)=zm(:,c); loglik1=cliqueloglikfn(zmat,A,thisbeta); zmat(:,c)=zeros(V,1); loglik0=cliqueloglikfn(zmat,A,thisbeta); atmp=ma; atmp(c)=1; T1=sum(atmp); T0=C-T1; logprior1 = betalog(a_beta+T1,b_beta+T0); atmp(c)=0; T1=sum(atmp); T0=C-T1; logprior0 = betalog(a_beta+T1,b_beta+T0); logpost1=logprior1+loglik1; logpost0=logprior0+loglik0; ma(c)=1/(1+exp(logpost0-logpost1)); end % end aloop zma=zma(:,ma>0.5); C=size(zma,2); % update the number of clusters ma=ma(:,ma>0.5); end keyboard end % end aloop function loglik=cliqueloglikfn(z,A,beta) V=size(A,1); loglik=0; for i=1:V for j=1:V if A(i,j) % if connection between i and j loglik=loglik+logsigma(beta*(sum(z(i,:).*z(j,:))-0.5)); else loglik=loglik+logsigma(-beta*(sum(z(i,:).*z(j,:))-0.5)); end end end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
hinton.m
.m
bayesian-reasoning-machine-learning-master/src/hinton.m
1,287
utf_8
c2796065ccb0df313df10b48a18ce866
function hinton(M,varargin) %HINTON Plot a Hinton diagram % hinton(M,opts) % Plot a Hinton diagram for matrix M. Positive is Green, and negative Red % use hinton(M,1) to turn on the grid % opts.grid = 1/0 % opts.coloursRGB: 2 x 4 matrix of RGB colours for the patches. First row is the RGB for % the positive and the second row for the negative entries. Default is % green and red. opts=[];if nargin==2; opts=varargin{1}; end opts=setfields(opts,'grid',1,'coloursRGB',[0 1 0; 1 0 0]);% default options [x, y, col]=makepatch(flipud(M)); cla for count=1:size(x,1); if col(count)==1 c=opts.coloursRGB(1,:); else c=opts.coloursRGB(2,:); end patch(y(count,:),x(count,:),c); end [I J]=size(M); set(gca,'xtick',[1:J]) set(gca,'xticklabel',[1:J]) set(gca,'ytick',[1:I]) set(gca,'yticklabel',[I:-1:1]) set(gca,'box','on') axis([0 J+1 0 I+1]); if opts.grid grid on else grid off end function [x, y, col]=makepatch(M) MM=max(max(abs(M))); M2=M./MM; M2=abs(M2); count=0; for i=1:size(M,1) for j=1:size(M,2) count=count+1; xx = i + M2(i,j)*0.45*[-1 -1 1 1]; yy = j + M2(i,j)*0.45*[-1 1 1 -1]; x(count,:)=xx; y(count,:)=yy; col(count)=sign(M(i,j)); end end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
mix2mix.m
.m
bayesian-reasoning-machine-learning-master/src/mix2mix.m
1,590
utf_8
366a4c119d7a19c2b93a6e136e5503c3
function [newcoeff, newmean, newcov] = mix2mix(coeff, mean, cov, I) %MIX2MIX Fit a mixture of Gaussians with another mixture of Gaussians % (but with a smaller number of components I) by retaining the % I-1 most probable coeffs, and merging the rest. % % Inputs: % coeff(:) : coefficients of the mixtures % mean(:,coeff) : the corresponding means % cov(:,:,coeff) : corresponding covariance matrices % I : desired number of smaller mixtures % % Outputs: % newcoeff(:) : new mixture coefficients % newmean(:,:) : new means % newcov(:,:,:) : new covariance matrices % See also SLDSforward.m, SLDSbackward.m newcoeff = coeff; newmean = mean; newcov = cov; L = length(newcoeff); if L > I [val,ind] = sort(coeff); tomerge = ind(1:L-I+1); notmerged = setdiff(1:L,tomerge); sump = sum(coeff(tomerge)); if sump ~= 0 condp = coeff(tomerge) ./ sump; else n = length(tomerge); condp = ones(1,n) / n; end [mergedmean, mergedcov] = matmixtosingle(condp, mean(:,tomerge), cov(:,:,tomerge)); newcoeff(tomerge) = []; newmean(:,tomerge) = []; newcov(:,:,tomerge) = []; newcoeff(I) = sump; newmean(:,I) = mergedmean; newcov(:,:,I) = mergedcov; end function [m, S] = matmixtosingle(coeff, means, cov) % fit a mixture of Gaussians with a single Gaussian, so that the first and second moments % of the fitted Gaussian match the mixture first and second moments. n=size(means,2); m=zeros(size(means,1),1); S=zeros(size(means,1)); for i=1:n m=m+coeff(i)*means(:,i); S=S+coeff(i)*(cov(:,:,i)+means(:,i)*means(:,i)'); end S=S-m*m';
github
cosmicBboy/bayesian-reasoning-machine-learning-master
mygamrnd.m
.m
bayesian-reasoning-machine-learning-master/src/mygamrnd.m
1,780
utf_8
a2f65264ce7e91b85cc3d4f99a8af08e
% % % Gamma random variate generator % Simon Rogers, 30/01/2007 % -------------------------------------------- % function g = mygamrnd(k,theta,N,varargin) % generates N random variates from a Gamma(k,theta) pdf % defined as % p(g|k,theta) = g^{k-1} \frac{e^{-g/theta}}{\theta^k \Gamma(k)} % % Uses an acceptance-rejection method as described at % http://en.wikipedia.org/wiki/Gamma_distribution % % varargin holds extra options, currently limited to % 'verbose' {0,1} - 0 is silent (default), 1 prints some diagnostics % e.g. g = mygamrnd(1,1,10,'verbose',1) % generates 10 variates from a Gamma(1,1) distribution and displays info % % function g = mygamrnd(alpha,theta,N,varargin) verbose = 0; for i = 1:2:length(varargin)-1 switch lower(varargin{i}) case 'verbose' verbose = varargin{i+1}; end end k = floor(alpha); delta = alpha-k; g = zeros(N,1); left = repmat(1,N,1); if verbose fprintf('\n\nGamma Variate Generator'); fprintf('\nSee http://en.wikipedia.org/wiki/Gamma_distribution'); fprintf('\n[k]=%g, delta=%g, theta=%g, N=%g',k,delta,theta,N); end it = 0; if delta>0 nu = exp(1)/(exp(1)+delta); for n = 1:N while 1 it = it + 1; V = rand(1,2); if V(1)<=nu xi = (V(1)/nu)^(1/delta); eta = V(2)*xi^(delta-1); else xi = 1 - log((V(1)-nu)/(1-nu)); eta = V(2)*exp(-xi); end if eta <= xi^(delta-1) * exp(-xi) break end end g(n) = xi; end end un = rand(N,k); g = (theta)*(g - sum(log(un),2)); if verbose fprintf('\nFinished, avg number of its: %g\n\n',it/N); end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
singleparenttree.m
.m
bayesian-reasoning-machine-learning-master/src/singleparenttree.m
1,274
utf_8
9880861b5dbb90b5d6b0d7017ad8724b
function [spTree elimseq]=singleparenttree(Atree,varargin) %SINGLEPARENTTREE From an undirected tree, form a directed tree with at most one parent %[spTree elimseq]=singleparenttree(Atree,<orient away from this node>) % Get an elimination elimseq such that each eliminated node has at most 1 parent: % By default consistently orients away from node 1. Atree=(Atree+Atree')>0; if isempty(varargin); start=1; % orient edges away from node 1 else start=varargin{1}; % orient away from specified node end comps=connectedComponents(Atree); Ncomps=max(comps); elimseq=[]; for c=1:Ncomps % loop over connected components compvars=find(comps==c); if start>length(compvars); compstart=1; else compstart=start; end [spTree(compvars,compvars) compelimseq]=singleparentConnectedtree(Atree(compvars,compvars),compstart); elimseq=[elimseq compvars(compelimseq)]; end function [spTree elimseq]=singleparentConnectedtree(Atree,start) elimseq=start; N=size(Atree,1); spTree=Atree; v=zeros(N,1); v(start)=1; A=Atree+eye(N); kids=children(spTree,elimseq); spTree(kids,elimseq)=0; while prod(v)~=1 v=real((A*v)>0); nodes=setdiff(find(v),elimseq); elimseq=[elimseq nodes(:)']; kids=children(spTree,nodes); spTree(kids,nodes)=0; end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
SVMtrain.m
.m
bayesian-reasoning-machine-learning-master/src/SVMtrain.m
2,022
utf_8
a7a5dadc2f12e2d3b37c2775d6a74631
function [A,G] = SVMtrain(Q,y,C) %SVMTRAIN train a Support vector Machine % compute the SMO decomposition algorithm from Fan et al JMLR 2005 % % Inputs: % Q_ij - y_i y_j K_ij (Where K is the kernel) % y - labels % C - C parameter % % Outputs: % A - alpha values % G - Gradient % written by Zakria Hussain, UCL, Jul 2008 eps = 1e-3; tau = 1e-12; len = length(y); A = zeros(len,1); G = -ones(len,1); while(1) [i,j] = selectB(Q,G,A,y,C,tau,eps); if j == -1; break; end % working set is (i,j) a = Q(i,i)+Q(j,j)-2*y(i)*y(j)*Q(i,j); if a <= 0; a = tau; end b = (-y(i)*G(i))+(y(j)*G(j)); % update alpha oldAi = A(i); oldAj = A(j); A(i) = A(i) + (y(i)*b/a); A(j) = A(j) - (y(j)*b/a); % project alpha back to the feasible region sum = (y(i)*oldAi) + (y(j)*oldAj); if A(i) > C; A(i) = C; end if A(i) < 0; A(i) = 0; end A(j) = y(j)*(sum-y(i)*A(i)); if A(j) > C; A(j) = C; end if A(j) < 0; A(j) = 0; end A(i) = y(i)*(sum-y(j)*A(j)); % update gradient deltaAi = A(i) - oldAi; deltaAj = A(j) - oldAj; G(:) = G(:) + (Q(:,i)*deltaAi) + (Q(:,j)*deltaAj); end function [i,j] = selectB(Q,G,A,y,C,tau,eps) len = length(A); i = -1; Gmax = -inf; Gmin = inf; for t=1:len if (y(t)==1 && A(t)<C) || (y(t)==-1 && A(t)>0) if -y(t)*G(t) >= Gmax i = t; Gmax = -y(t)*G(t); end end end j = -1; obj_min = inf; for t=1:len if (y(t)==1 && A(t)>0) || (y(t)==-1 && A(t)<C) b = Gmax + (y(t)*G(t)); if -y(t)*G(t) <= Gmin ; Gmin = -y(t)*G(t); end if b>0 a = Q(i,i)+Q(t,t)-2*y(i)*y(t)*Q(i,t); if a<=0; a = tau; end if -(b*b)/a <= obj_min j=t; obj_min = -(b*b)/a; end end end end if Gmax-Gmin < eps i = -1; j = -1; end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
uniquepots.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/uniquepots.m
1,370
utf_8
01144806ae1fd2ada3aaeeaa4a6c90ad
function [newpot A] = uniquepots(pot,varargin) %UNIQUEPOTS Eliminate redundant potentials (those contained wholly within another) by multiplying redundant potentials % [newpot A]= uniquepots(pot,<tables>) % if tables=0 then just merge the variables % The matrix has A(j,i)=1 if pot(i) is contained within pot(j) tables=1; if nargin==2; tables=varargin{1}; end % Find a tree of cliques by identifying a single parent clique j that contains clique i. C=length(pot); r=zeros(1,C); for i=1:C; r(i)=isempty(pot(i).variables); end pot=pot(~r);C=length(pot); A=sparse(C,C); for i=1:C j=1; while j<=C A(j,i)=ischildpot(pot,i,j); if A(j,i);break;end j=j+1; end end newpot=pot; % Now merge from bottom up [tree elimset sched]=istree(A); remove=zeros(1,C); if tables for s=1:size(sched,1) ch=sched(s,1); pa=sched(s,2); if ch~=pa newpot(pa)=multpots(newpot([pa ch])); remove(ch)=1; end end else for s=1:size(sched,1) ch=sched(s,2); pa=sched(s,1); if ch~=pa newpot(pa).variables=union(newpot(ch).variables,newpot(pa).variables); remove(ch)=1; end end end newpot=newpot(remove==0); function m = ischildpot(pot,i,j) if i==j; m=0; return; end m=all(ismember(pot(i).variables,pot(j).variables));
github
cosmicBboy/bayesian-reasoning-machine-learning-master
subsetsum.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/subsetsum.m
2,689
utf_8
f8d7d15173c2e31dec9a155c9cc80873
function [q st]=subsetsum(x) %SUBSETSUM Solve the zero subset sum problem. % Input: x - a vector of integers % Outputs: q=1 if there is a binary 0/1 vector st such that % sum_i x(i).*st(i) = =0 % The method used is either dynamic programming or explicit enumeration, % depending on the number of variables and the precision of the integers. % The wikipedia dynamic programming method has complexity O(n*(P-N)), % where n is the number of variables, P the sum of positive x and N the sum of negative x. % This algorithmn is therefore practical only when the precision (number of % bits required to specify the elements of x is small. Otherwise, for small % n, and larger precision, one can just enumerate all 2^n binary states, % which would be more efficient. n=length(x); N=sum(x(x<0)); P=sum(x(x>0)); if n*log(2)> (log(n)+log(P-N)); do_dynamic_programming=1; else do_dynamic_programming=0; end if do_dynamic_programming offset=-min(N-x)+1; % offset ensures no negative indices Q=zeros(max(P-x+offset)); for s=N:P Q(1,s+offset)= (x(1)==s); end for i=2:n for s=N:P Q(i,s+offset)=Q(i-1,s+offset)| (x(i)==s) | Q(i-1,s-x(i)+offset); end end q=Q(n,0+offset); % q=1 if there is a solution st=zeros(1,n); % initialise solution if q % there is a solution, so find by backtracking: % idea is to start from the last point x(n). If there is a solution in % which the sum of a subset up to and including n-1 equals -x(n), then we % can include x(n) in the solution. We then add x(n) to the total, and move % on to x(n-1): tot=0; for i=n:-1:2 if tot+x(i)==0 st(i)=1; break; end if Q(i-1,offset-tot-x(i)) st(i)=1; tot=tot+x(i); if tot==0; break; end end end if sum(st(1:n).*x(1:n))~=0 st(1)=1; end end else % explicit enumeration of all 2^n states: st=ind2subv(2*ones(1,n),1:2^n)-1; vals=st*x(:); ind=find(vals==0); if isempty(ind) q=0; st=zeros(1,n); else q=1; st=vals(ind(1)); end end function out = ind2subv(siz,ndx) % out = ind2subv(siz,ndx) % % index to state : return a state vector of the linear index ndx, based on an array of size siz % For vector ndx, returns a matrix with each row containing the corresponding state vector k = [1 cumprod(siz(1:end-1))]; for i = length(siz):-1:1; vi = rem(ndx-1, k(i)) + 1; vj = (ndx - vi)./k(i) + 1;out(:,i) = vj;ndx = vi; end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
cliquedecomp.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/cliquedecomp.m
4,181
utf_8
eb0a06cc65d47f1b7a21215da7603bc7
function[z zbest]=cliquedecomp(A,C,varargin) %CLIQUEDECOMP Clique matrix decomposition % A: adjacency matrix % C: maximum number of clusters required % opts.zloops: innerloop for a fixed number of cliques % opts.aloops: outerloop to find optimal number of clusters % opts.beta: inverse temperature % opts.burnin: set to 1 to do some initial burn in % opts.burninbeta: burn in beta value % opts.a_beta: Beta distribution a parameter % opts.b_beta: Beta distribution b parameter % see demoCliqueDecomp.m and cliquedecomp.c V=size(A,1); opts=[]; if nargin==3; opts=varargin{1}; end opts=setfields(opts,'zloops',ceil(V/10),'aloops',5,'beta',10,'a_beta',1,'b_beta',10,'plotprogress',1,'burnin',0);% default options beta=opts.beta; a_beta=opts.a_beta; b_beta=opts.b_beta; A=A-diag(diag(A)); A=A+eye(size(A,1)); % include self connections % Mean Field approximation of p(z_i=1|A) zm=real(rand(V,C)>0.0); % random initialisation ma=ones(1,C); zma=zm.*repmat(ma,V,1); errors=-1; olderror=10e100; zold=zm; zbest=zm; besterror=olderror; for loopa=1:opts.aloops if opts.burnin & loopa==1 thisbeta=opts.burninbeta; else thisbeta=beta; end for loopz=1:opts.zloops Mold = zma*zma'; for c=randperm(C) zc=zma(:,c); for k=randperm(V) Mk = Mold(:,k)-zc(:)*zc(k)+zma(:,c)*zma(k,c); logfn1=0;logfn0=0; for j=1:V mnfield0= Mk(j)-zma(j,c)*zma(k,c)-0.5; mnfield1= zma(j,c) + mnfield0; mnfield0=thisbeta*mnfield0; mnfield1=thisbeta*mnfield1; if A(j,k) logfn1=logfn1 + logsigma(mnfield1); logfn0=logfn0 + logsigma(mnfield0); else logfn1=logfn1 + logsigma(-mnfield1); logfn0=logfn0 + logsigma(-mnfield0); end % end if end % end for j zm(k,c) = 1/(1+exp(2*cap(logfn0-logfn1,100))); zma(k,c)=zm(k,c)*ma(c); end % end for k Mold = Mold-zc*zc'+zma(:,c)*zma(:,c)'; end % end for c z=zma>0.49; % threshold dz=double(z); AA= (dz*dz' > 0); AA = AA-diag(diag(AA)); AA = AA+diag(ones(1,V)); newerror= 0.5*sum(sum(AA~=A)); if newerror<besterror zbest=z; besterror=newerror; else z=zbest; newerror=besterror; end errors(loopz) = newerror; fprintf(1,'number of cliques=%d (after %d updates) | vertex loop %d| errors %d| best error %d| beta %f\n',... [C (loopa-1) loopz newerror besterror thisbeta]); if opts.plotprogress subplot(1,4,1);imagesc(A);colormap('bone');title('original');subplot(1,4,2);imagesc(AA); colormap('bone');title('approx');subplot(1,4,3); imagesc(z);colormap('bone');title('Z');subplot(1,4,4);plot(errors);drawnow; end end % end zloop %sum(z) %pause % update the number of cliques: if opts.aloops>1 zmatmp=zma; for c=1:C zmat=zmatmp; zmat(:,c)=zm(:,c); loglik1=cliqueloglikfn(zmat,A,thisbeta); zmat(:,c)=zeros(V,1); loglik0=cliqueloglikfn(zmat,A,thisbeta); atmp=ma; atmp(c)=1; T1=sum(atmp); T0=C-T1; logprior1 = betalog(a_beta+T1,b_beta+T0); atmp(c)=0; T1=sum(atmp); T0=C-T1; logprior0 = betalog(a_beta+T1,b_beta+T0); logpost1=logprior1+loglik1; logpost0=logprior0+loglik0; ma(c)=1/(1+exp(logpost0-logpost1)); end % end aloop zma=zma(:,ma>0.5); C=size(zma,2); % update the number of clusters ma=ma(:,ma>0.5); end keyboard end % end aloop function loglik=cliqueloglikfn(z,A,beta) V=size(A,1); loglik=0; for i=1:V for j=1:V if A(i,j) % if connection between i and j loglik=loglik+logsigma(beta*(sum(z(i,:).*z(j,:))-0.5)); else loglik=loglik+logsigma(-beta*(sum(z(i,:).*z(j,:))-0.5)); end end end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
hinton.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/hinton.m
1,287
utf_8
c2796065ccb0df313df10b48a18ce866
function hinton(M,varargin) %HINTON Plot a Hinton diagram % hinton(M,opts) % Plot a Hinton diagram for matrix M. Positive is Green, and negative Red % use hinton(M,1) to turn on the grid % opts.grid = 1/0 % opts.coloursRGB: 2 x 4 matrix of RGB colours for the patches. First row is the RGB for % the positive and the second row for the negative entries. Default is % green and red. opts=[];if nargin==2; opts=varargin{1}; end opts=setfields(opts,'grid',1,'coloursRGB',[0 1 0; 1 0 0]);% default options [x, y, col]=makepatch(flipud(M)); cla for count=1:size(x,1); if col(count)==1 c=opts.coloursRGB(1,:); else c=opts.coloursRGB(2,:); end patch(y(count,:),x(count,:),c); end [I J]=size(M); set(gca,'xtick',[1:J]) set(gca,'xticklabel',[1:J]) set(gca,'ytick',[1:I]) set(gca,'yticklabel',[I:-1:1]) set(gca,'box','on') axis([0 J+1 0 I+1]); if opts.grid grid on else grid off end function [x, y, col]=makepatch(M) MM=max(max(abs(M))); M2=M./MM; M2=abs(M2); count=0; for i=1:size(M,1) for j=1:size(M,2) count=count+1; xx = i + M2(i,j)*0.45*[-1 -1 1 1]; yy = j + M2(i,j)*0.45*[-1 1 1 -1]; x(count,:)=xx; y(count,:)=yy; col(count)=sign(M(i,j)); end end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
mix2mix.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/mix2mix.m
1,590
utf_8
366a4c119d7a19c2b93a6e136e5503c3
function [newcoeff, newmean, newcov] = mix2mix(coeff, mean, cov, I) %MIX2MIX Fit a mixture of Gaussians with another mixture of Gaussians % (but with a smaller number of components I) by retaining the % I-1 most probable coeffs, and merging the rest. % % Inputs: % coeff(:) : coefficients of the mixtures % mean(:,coeff) : the corresponding means % cov(:,:,coeff) : corresponding covariance matrices % I : desired number of smaller mixtures % % Outputs: % newcoeff(:) : new mixture coefficients % newmean(:,:) : new means % newcov(:,:,:) : new covariance matrices % See also SLDSforward.m, SLDSbackward.m newcoeff = coeff; newmean = mean; newcov = cov; L = length(newcoeff); if L > I [val,ind] = sort(coeff); tomerge = ind(1:L-I+1); notmerged = setdiff(1:L,tomerge); sump = sum(coeff(tomerge)); if sump ~= 0 condp = coeff(tomerge) ./ sump; else n = length(tomerge); condp = ones(1,n) / n; end [mergedmean, mergedcov] = matmixtosingle(condp, mean(:,tomerge), cov(:,:,tomerge)); newcoeff(tomerge) = []; newmean(:,tomerge) = []; newcov(:,:,tomerge) = []; newcoeff(I) = sump; newmean(:,I) = mergedmean; newcov(:,:,I) = mergedcov; end function [m, S] = matmixtosingle(coeff, means, cov) % fit a mixture of Gaussians with a single Gaussian, so that the first and second moments % of the fitted Gaussian match the mixture first and second moments. n=size(means,2); m=zeros(size(means,1),1); S=zeros(size(means,1)); for i=1:n m=m+coeff(i)*means(:,i); S=S+coeff(i)*(cov(:,:,i)+means(:,i)*means(:,i)'); end S=S-m*m';
github
cosmicBboy/bayesian-reasoning-machine-learning-master
mygamrnd.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/mygamrnd.m
1,780
utf_8
a2f65264ce7e91b85cc3d4f99a8af08e
% % % Gamma random variate generator % Simon Rogers, 30/01/2007 % -------------------------------------------- % function g = mygamrnd(k,theta,N,varargin) % generates N random variates from a Gamma(k,theta) pdf % defined as % p(g|k,theta) = g^{k-1} \frac{e^{-g/theta}}{\theta^k \Gamma(k)} % % Uses an acceptance-rejection method as described at % http://en.wikipedia.org/wiki/Gamma_distribution % % varargin holds extra options, currently limited to % 'verbose' {0,1} - 0 is silent (default), 1 prints some diagnostics % e.g. g = mygamrnd(1,1,10,'verbose',1) % generates 10 variates from a Gamma(1,1) distribution and displays info % % function g = mygamrnd(alpha,theta,N,varargin) verbose = 0; for i = 1:2:length(varargin)-1 switch lower(varargin{i}) case 'verbose' verbose = varargin{i+1}; end end k = floor(alpha); delta = alpha-k; g = zeros(N,1); left = repmat(1,N,1); if verbose fprintf('\n\nGamma Variate Generator'); fprintf('\nSee http://en.wikipedia.org/wiki/Gamma_distribution'); fprintf('\n[k]=%g, delta=%g, theta=%g, N=%g',k,delta,theta,N); end it = 0; if delta>0 nu = exp(1)/(exp(1)+delta); for n = 1:N while 1 it = it + 1; V = rand(1,2); if V(1)<=nu xi = (V(1)/nu)^(1/delta); eta = V(2)*xi^(delta-1); else xi = 1 - log((V(1)-nu)/(1-nu)); eta = V(2)*exp(-xi); end if eta <= xi^(delta-1) * exp(-xi) break end end g(n) = xi; end end un = rand(N,k); g = (theta)*(g - sum(log(un),2)); if verbose fprintf('\nFinished, avg number of its: %g\n\n',it/N); end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
singleparenttree.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/singleparenttree.m
1,274
utf_8
9880861b5dbb90b5d6b0d7017ad8724b
function [spTree elimseq]=singleparenttree(Atree,varargin) %SINGLEPARENTTREE From an undirected tree, form a directed tree with at most one parent %[spTree elimseq]=singleparenttree(Atree,<orient away from this node>) % Get an elimination elimseq such that each eliminated node has at most 1 parent: % By default consistently orients away from node 1. Atree=(Atree+Atree')>0; if isempty(varargin); start=1; % orient edges away from node 1 else start=varargin{1}; % orient away from specified node end comps=connectedComponents(Atree); Ncomps=max(comps); elimseq=[]; for c=1:Ncomps % loop over connected components compvars=find(comps==c); if start>length(compvars); compstart=1; else compstart=start; end [spTree(compvars,compvars) compelimseq]=singleparentConnectedtree(Atree(compvars,compvars),compstart); elimseq=[elimseq compvars(compelimseq)]; end function [spTree elimseq]=singleparentConnectedtree(Atree,start) elimseq=start; N=size(Atree,1); spTree=Atree; v=zeros(N,1); v(start)=1; A=Atree+eye(N); kids=children(spTree,elimseq); spTree(kids,elimseq)=0; while prod(v)~=1 v=real((A*v)>0); nodes=setdiff(find(v),elimseq); elimseq=[elimseq nodes(:)']; kids=children(spTree,nodes); spTree(kids,nodes)=0; end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
SVMtrain.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/SVMtrain.m
2,022
utf_8
a7a5dadc2f12e2d3b37c2775d6a74631
function [A,G] = SVMtrain(Q,y,C) %SVMTRAIN train a Support vector Machine % compute the SMO decomposition algorithm from Fan et al JMLR 2005 % % Inputs: % Q_ij - y_i y_j K_ij (Where K is the kernel) % y - labels % C - C parameter % % Outputs: % A - alpha values % G - Gradient % written by Zakria Hussain, UCL, Jul 2008 eps = 1e-3; tau = 1e-12; len = length(y); A = zeros(len,1); G = -ones(len,1); while(1) [i,j] = selectB(Q,G,A,y,C,tau,eps); if j == -1; break; end % working set is (i,j) a = Q(i,i)+Q(j,j)-2*y(i)*y(j)*Q(i,j); if a <= 0; a = tau; end b = (-y(i)*G(i))+(y(j)*G(j)); % update alpha oldAi = A(i); oldAj = A(j); A(i) = A(i) + (y(i)*b/a); A(j) = A(j) - (y(j)*b/a); % project alpha back to the feasible region sum = (y(i)*oldAi) + (y(j)*oldAj); if A(i) > C; A(i) = C; end if A(i) < 0; A(i) = 0; end A(j) = y(j)*(sum-y(i)*A(i)); if A(j) > C; A(j) = C; end if A(j) < 0; A(j) = 0; end A(i) = y(i)*(sum-y(j)*A(j)); % update gradient deltaAi = A(i) - oldAi; deltaAj = A(j) - oldAj; G(:) = G(:) + (Q(:,i)*deltaAi) + (Q(:,j)*deltaAj); end function [i,j] = selectB(Q,G,A,y,C,tau,eps) len = length(A); i = -1; Gmax = -inf; Gmin = inf; for t=1:len if (y(t)==1 && A(t)<C) || (y(t)==-1 && A(t)>0) if -y(t)*G(t) >= Gmax i = t; Gmax = -y(t)*G(t); end end end j = -1; obj_min = inf; for t=1:len if (y(t)==1 && A(t)>0) || (y(t)==-1 && A(t)<C) b = Gmax + (y(t)*G(t)); if -y(t)*G(t) <= Gmin ; Gmin = -y(t)*G(t); end if b>0 a = Q(i,i)+Q(t,t)-2*y(i)*y(t)*Q(i,t); if a<=0; a = tau; end if -(b*b)/a <= obj_min j=t; obj_min = -(b*b)/a; end end end end if Gmax-Gmin < eps i = -1; j = -1; end
github
cosmicBboy/bayesian-reasoning-machine-learning-master
textoval.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/graphlayout/textoval.m
2,151
utf_8
654d6f5117ff68685aac2921423cb76d
function [t, wd] = textoval(x, y, str) % TEXTOVAL Draws an oval around text objects % % [T, WIDTH] = TEXTOVAL(X, Y, STR) % [..] = TEXTOVAL(STR) % Interactive % % Inputs : % X, Y : Coordinates % TXT : Strings % % Outputs : % T : Object Handles % WIDTH : x and y Width of ovals % % Usage Example : [t] = textoval('Visit to Asia?'); % % % Note : % See also TEXTBOX % Uses : % Change History : % Date Time Prog Note % 15-Jun-1998 10:36 AM ATC Created under MATLAB 5.1.0.421 % ATC = Ali Taylan Cemgil, % SNN - University of Nijmegen, Department of Medical Physics and Biophysics % e-mail : [email protected] temp = []; switch nargin, case 1, str = x; if ~isa(str,'cell') str=cellstr(str); end; N = length(str); wd = zeros(N,2); for i=1:N, [x, y] = ginput(1); tx = text(x,y,str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); [ptc wx wy] = draw_oval(tx, x, y); wd(i,:) = [wx wy]; delete(tx); tx = text(x,y,str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); temp = [temp ; tx ptc]; end; case 3, if ~isa(str,'cell') str=cellstr(str); end; N = length(str); wd = zeros(N,2); for i=1:N, tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); [ptc wx wy] = draw_oval(tx, x(i), y(i)); wd(i,:) = [wx wy]; delete(tx); tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); temp = [temp; tx ptc]; end; otherwise, end; if nargout>0, t = temp; end; function [ptc, wx, wy] = draw_oval(tx, x, y) % Draws an oval box around a tex object if isoctave pos=get(gcf,'Position'); xl=pos(3); yl=pos(4); l = length(get(tx,'string')); % octave workaround: db sz = [1 1 0.011*(4+l)*560/xl 0.012*(4)*420/yl]; else sz = get(tx,'Extent'); % octave doesn't understand this end wy = sz(4); wx = max(2/3*sz(3), wy); ptc = ellipse(x, y, wx, wy); set(ptc, 'FaceColor','w');
github
cosmicBboy/bayesian-reasoning-machine-learning-master
textbox.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/graphlayout/textbox.m
2,118
utf_8
f7750958b5bdcd1839e4800abdeb9c21
function [t, wd] = textbox(x,y,str) % TEXTBOX Draws A Box around the text % % [T, WIDTH] = TEXTBOX(X, Y, STR) % [..] = TEXTBOX(STR) % % Inputs : % X, Y : Coordinates % TXT : Strings % % Outputs : % T : Object Handles % WIDTH : x and y Width of boxes %% % Usage Example : t = textbox({'Ali','Veli','49','50'}); % % % Note : % See also TEXTOVAL % Uses : % Change History : % Date Time Prog Note % 09-Jun-1998 11:43 AM ATC Created under MATLAB 5.1.0.421 % ATC = Ali Taylan Cemgil, % SNN - University of Nijmegen, Department of Medical Physics and Biophysics % e-mail : [email protected] % See temp = []; switch nargin, case 1, str = x; if ~isa(str,'cell') str=cellstr(str); end; N = length(str); wd = zeros(N,2); for i=1:N, [x, y] = ginput(1); tx = text(x,y,str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); [ptc wx wy] = draw_box(tx, x, y); wd(i,:) = [wx wy]; delete(tx); tx = text(x,y,str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); temp = [temp; tx ptc]; end; case 3, if ~isa(str,'cell') str=cellstr(str); end; N = length(str); for i=1:N, tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); [ptc wx wy] = draw_box(tx, x(i), y(i)); wd(i,:) = [wx wy]; delete(tx); tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); temp = [temp; tx ptc]; end; otherwise, end; if nargout>0, t = temp; end; function [ptc, wx, wy] = draw_box(tx, x, y) % Draws a box around a tex object if isoctave pos=get(gcf,'Position'); xl=pos(3); yl=pos(4); l = length(get(tx,'string')); % octave workaround: db sz = [1 1 0.01*(4+l)*560/xl 0.01*(4)*420/yl]; else sz = get(tx,'Extent'); end wy = 2/3*sz(4); wx = max(2/3*sz(3), wy); ptc = patch([x-wx x+wx x+wx x-wx], [y+wy y+wy y-wy y-wy],'w'); set(ptc, 'FaceColor','w');
github
cosmicBboy/bayesian-reasoning-machine-learning-master
arrow.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/graphlayout/private/arrow.m
56,774
utf_8
2dc514962f607a6855ee3f8bfbee74c4
function [h,yy,zz] = arrow(varargin) % ARROW Draw a line with an arrowhead. % % ARROW(Start,Stop) draws a line with an arrow from Start to Stop (points % should be vectors of length 2 or 3, or matrices with 2 or 3 % columns), and returns the graphics handle of the arrow(s). % % ARROW uses the mouse (click-drag) to create an arrow. % % ARROW DEMO & ARROW DEMO2 show 3-D & 2-D demos of the capabilities of ARROW. % % ARROW may be called with a normal argument list or a property-based list. % ARROW(Start,Stop,Length,BaseAngle,TipAngle,Width,Page,CrossDir) is % the full normal argument list, where all but the Start and Stop % points are optional. If you need to specify a later argument (e.g., % Page) but want default values of earlier ones (e.g., TipAngle), % pass an empty matrix for the earlier ones (e.g., TipAngle=[]). % % ARROW('Property1',PropVal1,'Property2',PropVal2,...) creates arrows with the % given properties, using default values for any unspecified or given as % 'default' or NaN. Some properties used for line and patch objects are % used in a modified fashion, others are passed directly to LINE, PATCH, % or SET. For a detailed properties explanation, call ARROW PROPERTIES. % % Start The starting points. B % Stop The end points. /|\ ^ % Length Length of the arrowhead in pixels. /|||\ | % BaseAngle Base angle in degrees (ADE). //|||\\ L| % TipAngle Tip angle in degrees (ABC). ///|||\\\ e| % Width Width of the base in pixels. ////|||\\\\ n| % Page Use hardcopy proportions. /////|D|\\\\\ g| % CrossDir Vector || to arrowhead plane. //// ||| \\\\ t| % NormalDir Vector out of arrowhead plane. /// ||| \\\ h| % Ends Which end has an arrowhead. //<----->|| \\ | % ObjectHandles Vector of handles to update. / base ||| \ V % E angle||<-------->C % ARROW(H,'Prop1',PropVal1,...), where H is a |||tipangle % vector of handles to previously-created arrows ||| % and/or line objects, will update the previously- ||| % created arrows according to the current view -->|A|<-- width % and any specified properties, and will convert % two-point line objects to corresponding arrows. ARROW(H) will update % the arrows if the current view has changed. Root, figure, or axes % handles included in H are replaced by all descendant Arrow objects. % % A property list can follow any specified normal argument list, e.g., % ARROW([1 2 3],[0 0 0],36,'BaseAngle',60) creates an arrow from (1,2,3) to % the origin, with an arrowhead of length 36 pixels and 60-degree base angle. % % The basic arguments or properties can generally be vectorized to create % multiple arrows with the same call. This is done by passing a property % with one row per arrow, or, if all arrows are to have the same property % value, just one row may be specified. % % You may want to execute AXIS(AXIS) before calling ARROW so it doesn't change % the axes on you; ARROW determines the sizes of arrow components BEFORE the % arrow is plotted, so if ARROW changes axis limits, arrows may be malformed. % % This version of ARROW uses features of MATLAB 6.x and is incompatible with % earlier MATLAB versions (ARROW for MATLAB 4.2c is available separately); % some problems with perspective plots still exist. % Copyright (c)1995-2009, Dr. Erik A. Johnson <[email protected]>, 5/20/2009 % http://www.usc.edu/civil_eng/johnsone/ % Revision history: % 5/20/09 EAJ Fix view direction in (3D) demo. % 6/26/08 EAJ Replace eval('trycmd','catchcmd') with try, trycmd; catch, % catchcmd; end; -- break's MATLAB 5 compatibility. % 8/26/03 EAJ Eliminate OpenGL attempted fix since it didn't fix anyway. % 11/15/02 EAJ Accomodate how MATLAB 6.5 handles NaN and logicals % 7/28/02 EAJ Tried (but failed) work-around for MATLAB 6.x / OpenGL bug % if zero 'Width' or not double-ended % 11/10/99 EAJ Add logical() to eliminate zero index problem in MATLAB 5.3. % 11/10/99 EAJ Corrected warning if axis limits changed on multiple axes. % 11/10/99 EAJ Update e-mail address. % 2/10/99 EAJ Some documentation updating. % 2/24/98 EAJ Fixed bug if Start~=Stop but both colinear with viewpoint. % 8/14/97 EAJ Added workaround for MATLAB 5.1 scalar logical transpose bug. % 7/21/97 EAJ Fixed a few misc bugs. % 7/14/97 EAJ Make arrow([],'Prop',...) do nothing (no old handles) % 6/23/97 EAJ MATLAB 5 compatible version, release. % 5/27/97 EAJ Added Line Arrows back in. Corrected a few bugs. % 5/26/97 EAJ Changed missing Start/Stop to mouse-selected arrows. % 5/19/97 EAJ MATLAB 5 compatible version, beta. % 4/13/97 EAJ MATLAB 5 compatible version, alpha. % 1/31/97 EAJ Fixed bug with multiple arrows and unspecified Z coords. % 12/05/96 EAJ Fixed one more bug with log plots and NormalDir specified % 10/24/96 EAJ Fixed bug with log plots and NormalDir specified % 11/13/95 EAJ Corrected handling for 'reverse' axis directions % 10/06/95 EAJ Corrected occasional conflict with SUBPLOT % 4/24/95 EAJ A major rewrite. % Fall 94 EAJ Original code. % Things to be done: % - in the arrow_clicks section, prompt by printing to the screen so that % the user knows what's going on; also make sure the figure is brought % to the front. % - segment parsing, computing, and plotting into separate subfunctions % - change computing from Xform to Camera paradigms % + this will help especially with 3-D perspective plots % + if the WarpToFill section works right, remove warning code % + when perpsective works properly, remove perspective warning code % - add cell property values and struct property name/values (like get/set) % - get rid of NaN as the "default" data label % + perhaps change userdata to a struct and don't include (or leave % empty) the values specified as default; or use a cell containing % an empty matrix for a default value % - add functionality of GET to retrieve current values of ARROW properties % Many thanks to Keith Rogers <[email protected]> for his many excellent % suggestions and beta testing. Check out his shareware package MATDRAW % (at ftp://ftp.mathworks.com/pub/contrib/v5/graphics/matdraw/) -- he has % permission to distribute ARROW with MATDRAW. % Permission is granted to distribute ARROW with the toolboxes for the book % "Solving Solid Mechanics Problems with MATLAB 5", by F. Golnaraghi et al. % (Prentice Hall, 1999). % Permission is granted to Dr. Josef Bigun to distribute ARROW with his % software to reproduce the figures in his image analysis text. if isoctave myarrow(varargin{1},varargin{2}); return end % global variable initialization global ARROW_PERSP_WARN ARROW_STRETCH_WARN ARROW_AXLIMITS if isempty(ARROW_PERSP_WARN ), ARROW_PERSP_WARN =1; end; if isempty(ARROW_STRETCH_WARN), ARROW_STRETCH_WARN=1; end; % Handle callbacks if (nargin>0 & isstr(varargin{1}) & strcmp(lower(varargin{1}),'callback')), arrow_callback(varargin{2:end}); return; end; % Are we doing the demo? c = sprintf('\n'); if (nargin==1 & isstr(varargin{1})), arg1 = lower(varargin{1}); if strncmp(arg1,'prop',4), arrow_props; elseif strncmp(arg1,'demo',4) clf reset demo_info = arrow_demo; if ~strncmp(arg1,'demo2',5), hh=arrow_demo3(demo_info); else, hh=arrow_demo2(demo_info); end; if (nargout>=1), h=hh; end; elseif strncmp(arg1,'fixlimits',3), arrow_fixlimits(ARROW_AXLIMITS); ARROW_AXLIMITS=[]; elseif strncmp(arg1,'help',4), disp(help(mfilename)); else, error([upper(mfilename) ' got an unknown single-argument string ''' deblank(arg1) '''.']); end; return; end; % Check # of arguments if (nargout>3), error([upper(mfilename) ' produces at most 3 output arguments.']); end; % find first property number firstprop = nargin+1; for k=1:length(varargin), if ~isnumeric(varargin{k}), firstprop=k; break; end; end; lastnumeric = firstprop-1; % check property list if (firstprop<=nargin), for k=firstprop:2:nargin, curarg = varargin{k}; if ~isstr(curarg) | sum(size(curarg)>1)>1, error([upper(mfilename) ' requires that a property name be a single string.']); end; end; if (rem(nargin-firstprop,2)~=1), error([upper(mfilename) ' requires that the property ''' ... varargin{nargin} ''' be paired with a property value.']); end; end; % default output if (nargout>0), h=[]; end; if (nargout>1), yy=[]; end; if (nargout>2), zz=[]; end; % set values to empty matrices start = []; stop = []; len = []; baseangle = []; tipangle = []; wid = []; page = []; crossdir = []; ends = []; ax = []; oldh = []; ispatch = []; defstart = [NaN NaN NaN]; defstop = [NaN NaN NaN]; deflen = 16; defbaseangle = 90; deftipangle = 16; defwid = 0; defpage = 0; defcrossdir = [NaN NaN NaN]; defends = 1; defoldh = []; defispatch = 1; % The 'Tag' we'll put on our arrows ArrowTag = 'Arrow'; % check for oldstyle arguments if (firstprop==2), % assume arg1 is a set of handles oldh = varargin{1}(:); if isempty(oldh), return; end; elseif (firstprop>9), error([upper(mfilename) ' takes at most 8 non-property arguments.']); elseif (firstprop>2), {start,stop,len,baseangle,tipangle,wid,page,crossdir}; args = [varargin(1:firstprop-1) cell(1,length(ans)-(firstprop-1))]; [start,stop,len,baseangle,tipangle,wid,page,crossdir] = deal(args{:}); end; % parse property pairs extraprops={}; for k=firstprop:2:nargin, prop = varargin{k}; val = varargin{k+1}; prop = [lower(prop(:)') ' ']; if strncmp(prop,'start' ,5), start = val; elseif strncmp(prop,'stop' ,4), stop = val; elseif strncmp(prop,'len' ,3), len = val(:); elseif strncmp(prop,'base' ,4), baseangle = val(:); elseif strncmp(prop,'tip' ,3), tipangle = val(:); elseif strncmp(prop,'wid' ,3), wid = val(:); elseif strncmp(prop,'page' ,4), page = val; elseif strncmp(prop,'cross' ,5), crossdir = val; elseif strncmp(prop,'norm' ,4), if (isstr(val)), crossdir=val; else, crossdir=val*sqrt(-1); end; elseif strncmp(prop,'end' ,3), ends = val; elseif strncmp(prop,'object',6), oldh = val(:); elseif strncmp(prop,'handle',6), oldh = val(:); elseif strncmp(prop,'type' ,4), ispatch = val; elseif strncmp(prop,'userd' ,5), %ignore it else, % make sure it is a valid patch or line property try get(0,['DefaultPatch' varargin{k}]); catch errstr = lasterr; try get(0,['DefaultLine' varargin{k}]); catch errstr(1:max(find(errstr==char(13)|errstr==char(10)))) = ''; error([upper(mfilename) ' got ' errstr]); end end; extraprops={extraprops{:},varargin{k},val}; end; end; % Check if we got 'default' values start = arrow_defcheck(start ,defstart ,'Start' ); stop = arrow_defcheck(stop ,defstop ,'Stop' ); len = arrow_defcheck(len ,deflen ,'Length' ); baseangle = arrow_defcheck(baseangle,defbaseangle,'BaseAngle' ); tipangle = arrow_defcheck(tipangle ,deftipangle ,'TipAngle' ); wid = arrow_defcheck(wid ,defwid ,'Width' ); crossdir = arrow_defcheck(crossdir ,defcrossdir ,'CrossDir' ); page = arrow_defcheck(page ,defpage ,'Page' ); ends = arrow_defcheck(ends ,defends ,'' ); oldh = arrow_defcheck(oldh ,[] ,'ObjectHandles'); ispatch = arrow_defcheck(ispatch ,defispatch ,'' ); % check transpose on arguments [m,n]=size(start ); if any(m==[2 3])&(n==1|n>3), start = start'; end; [m,n]=size(stop ); if any(m==[2 3])&(n==1|n>3), stop = stop'; end; [m,n]=size(crossdir); if any(m==[2 3])&(n==1|n>3), crossdir = crossdir'; end; % convert strings to numbers if ~isempty(ends) & isstr(ends), endsorig = ends; [m,n] = size(ends); col = lower([ends(:,1:min(3,n)) ones(m,max(0,3-n))*' ']); ends = NaN*ones(m,1); oo = ones(1,m); ii=find(all(col'==['non']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*0; end; ii=find(all(col'==['sto']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*1; end; ii=find(all(col'==['sta']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*2; end; ii=find(all(col'==['bot']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*3; end; if any(isnan(ends)), ii = min(find(isnan(ends))); error([upper(mfilename) ' does not recognize ''' deblank(endsorig(ii,:)) ''' as a valid ''Ends'' value.']); end; else, ends = ends(:); end; if ~isempty(ispatch) & isstr(ispatch), col = lower(ispatch(:,1)); patchchar='p'; linechar='l'; defchar=' '; mask = col~=patchchar & col~=linechar & col~=defchar; if any(mask), error([upper(mfilename) ' does not recognize ''' deblank(ispatch(min(find(mask)),:)) ''' as a valid ''Type'' value.']); end; ispatch = (col==patchchar)*1 + (col==linechar)*0 + (col==defchar)*defispatch; else, ispatch = ispatch(:); end; oldh = oldh(:); % check object handles if ~all(ishandle(oldh)), error([upper(mfilename) ' got invalid object handles.']); end; % expand root, figure, and axes handles if ~isempty(oldh), ohtype = get(oldh,'Type'); mask = strcmp(ohtype,'root') | strcmp(ohtype,'figure') | strcmp(ohtype,'axes'); if any(mask), oldh = num2cell(oldh); for ii=find(mask)', oldh(ii) = {findobj(oldh{ii},'Tag',ArrowTag)}; end; oldh = cat(1,oldh{:}); if isempty(oldh), return; end; % no arrows to modify, so just leave end; end; % largest argument length [mstart,junk]=size(start); [mstop,junk]=size(stop); [mcrossdir,junk]=size(crossdir); argsizes = [length(oldh) mstart mstop ... length(len) length(baseangle) length(tipangle) ... length(wid) length(page) mcrossdir length(ends) ]; args=['length(ObjectHandle) '; ... '#rows(Start) '; ... '#rows(Stop) '; ... 'length(Length) '; ... 'length(BaseAngle) '; ... 'length(TipAngle) '; ... 'length(Width) '; ... 'length(Page) '; ... '#rows(CrossDir) '; ... '#rows(Ends) ']; if (any(imag(crossdir(:))~=0)), args(9,:) = '#rows(NormalDir) '; end; if isempty(oldh), narrows = max(argsizes); else, narrows = length(oldh); end; if (narrows<=0), narrows=1; end; % Check size of arguments ii = find((argsizes~=0)&(argsizes~=1)&(argsizes~=narrows)); if ~isempty(ii), s = args(ii',:); while ((size(s,2)>1)&((abs(s(:,size(s,2)))==0)|(abs(s(:,size(s,2)))==abs(' ')))), s = s(:,1:size(s,2)-1); end; s = [ones(length(ii),1)*[upper(mfilename) ' requires that '] s ... ones(length(ii),1)*[' equal the # of arrows (' num2str(narrows) ').' c]]; s = s'; s = s(:)'; s = s(1:length(s)-1); error(setstr(s)); end; % check element length in Start, Stop, and CrossDir if ~isempty(start), [m,n] = size(start); if (n==2), start = [start NaN*ones(m,1)]; elseif (n~=3), error([upper(mfilename) ' requires 2- or 3-element Start points.']); end; end; if ~isempty(stop), [m,n] = size(stop); if (n==2), stop = [stop NaN*ones(m,1)]; elseif (n~=3), error([upper(mfilename) ' requires 2- or 3-element Stop points.']); end; end; if ~isempty(crossdir), [m,n] = size(crossdir); if (n<3), crossdir = [crossdir NaN*ones(m,3-n)]; elseif (n~=3), if (all(imag(crossdir(:))==0)), error([upper(mfilename) ' requires 2- or 3-element CrossDir vectors.']); else, error([upper(mfilename) ' requires 2- or 3-element NormalDir vectors.']); end; end; end; % fill empty arguments if isempty(start ), start = [Inf Inf Inf]; end; if isempty(stop ), stop = [Inf Inf Inf]; end; if isempty(len ), len = Inf; end; if isempty(baseangle ), baseangle = Inf; end; if isempty(tipangle ), tipangle = Inf; end; if isempty(wid ), wid = Inf; end; if isempty(page ), page = Inf; end; if isempty(crossdir ), crossdir = [Inf Inf Inf]; end; if isempty(ends ), ends = Inf; end; if isempty(ispatch ), ispatch = Inf; end; % expand single-column arguments o = ones(narrows,1); if (size(start ,1)==1), start = o * start ; end; if (size(stop ,1)==1), stop = o * stop ; end; if (length(len )==1), len = o * len ; end; if (length(baseangle )==1), baseangle = o * baseangle ; end; if (length(tipangle )==1), tipangle = o * tipangle ; end; if (length(wid )==1), wid = o * wid ; end; if (length(page )==1), page = o * page ; end; if (size(crossdir ,1)==1), crossdir = o * crossdir ; end; if (length(ends )==1), ends = o * ends ; end; if (length(ispatch )==1), ispatch = o * ispatch ; end; ax = o * gca; % if we've got handles, get the defaults from the handles if ~isempty(oldh), for k=1:narrows, oh = oldh(k); ud = get(oh,'UserData'); ax(k) = get(oh,'Parent'); ohtype = get(oh,'Type'); if strcmp(get(oh,'Tag'),ArrowTag), % if it's an arrow already if isinf(ispatch(k)), ispatch(k)=strcmp(ohtype,'patch'); end; % arrow UserData format: [start' stop' len base tip wid page crossdir' ends] start0 = ud(1:3); stop0 = ud(4:6); if (isinf(len(k))), len(k) = ud( 7); end; if (isinf(baseangle(k))), baseangle(k) = ud( 8); end; if (isinf(tipangle(k))), tipangle(k) = ud( 9); end; if (isinf(wid(k))), wid(k) = ud(10); end; if (isinf(page(k))), page(k) = ud(11); end; if (isinf(crossdir(k,1))), crossdir(k,1) = ud(12); end; if (isinf(crossdir(k,2))), crossdir(k,2) = ud(13); end; if (isinf(crossdir(k,3))), crossdir(k,3) = ud(14); end; if (isinf(ends(k))), ends(k) = ud(15); end; elseif strcmp(ohtype,'line')|strcmp(ohtype,'patch'), % it's a non-arrow line or patch convLineToPatch = 1; %set to make arrow patches when converting from lines. if isinf(ispatch(k)), ispatch(k)=convLineToPatch|strcmp(ohtype,'patch'); end; x=get(oh,'XData'); x=x(~isnan(x(:))); if isempty(x), x=NaN; end; y=get(oh,'YData'); y=y(~isnan(y(:))); if isempty(y), y=NaN; end; z=get(oh,'ZData'); z=z(~isnan(z(:))); if isempty(z), z=NaN; end; start0 = [x(1) y(1) z(1) ]; stop0 = [x(end) y(end) z(end)]; else, error([upper(mfilename) ' cannot convert ' ohtype ' objects.']); end; ii=find(isinf(start(k,:))); if ~isempty(ii), start(k,ii)=start0(ii); end; ii=find(isinf(stop( k,:))); if ~isempty(ii), stop( k,ii)=stop0( ii); end; end; end; % convert Inf's to NaN's start( isinf(start )) = NaN; stop( isinf(stop )) = NaN; len( isinf(len )) = NaN; baseangle( isinf(baseangle)) = NaN; tipangle( isinf(tipangle )) = NaN; wid( isinf(wid )) = NaN; page( isinf(page )) = NaN; crossdir( isinf(crossdir )) = NaN; ends( isinf(ends )) = NaN; ispatch( isinf(ispatch )) = NaN; % set up the UserData data (here so not corrupted by log10's and such) ud = [start stop len baseangle tipangle wid page crossdir ends]; % Set Page defaults page = ~isnan(page) & trueornan(page); % Get axes limits, range, min; correct for aspect ratio and log scale axm = zeros(3,narrows); axr = zeros(3,narrows); axrev = zeros(3,narrows); ap = zeros(2,narrows); xyzlog = zeros(3,narrows); limmin = zeros(2,narrows); limrange = zeros(2,narrows); oldaxlims = zeros(narrows,7); oneax = all(ax==ax(1)); if (oneax), T = zeros(4,4); invT = zeros(4,4); else, T = zeros(16,narrows); invT = zeros(16,narrows); end; axnotdone = logical(ones(size(ax))); while (any(axnotdone)), ii = min(find(axnotdone)); curax = ax(ii); curpage = page(ii); % get axes limits and aspect ratio axl = [get(curax,'XLim'); get(curax,'YLim'); get(curax,'ZLim')]; oldaxlims(min(find(oldaxlims(:,1)==0)),:) = [curax reshape(axl',1,6)]; % get axes size in pixels (points) u = get(curax,'Units'); axposoldunits = get(curax,'Position'); really_curpage = curpage & strcmp(u,'normalized'); if (really_curpage), curfig = get(curax,'Parent'); pu = get(curfig,'PaperUnits'); set(curfig,'PaperUnits','points'); pp = get(curfig,'PaperPosition'); set(curfig,'PaperUnits',pu); set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); set(curax,'Units','normalized'); curap = pp.*get(curax,'Position'); else, set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); curap = curapscreen; end; set(curax,'Units',u); set(curax,'Position',axposoldunits); % handle non-stretched axes position str_stretch = { 'DataAspectRatioMode' ; ... 'PlotBoxAspectRatioMode' ; ... 'CameraViewAngleMode' }; str_camera = { 'CameraPositionMode' ; ... 'CameraTargetMode' ; ... 'CameraViewAngleMode' ; ... 'CameraUpVectorMode' }; notstretched = strcmp(get(curax,str_stretch),'manual'); manualcamera = strcmp(get(curax,str_camera),'manual'); if ~arrow_WarpToFill(notstretched,manualcamera,curax), % give a warning that this has not been thoroughly tested if 0 & ARROW_STRETCH_WARN, ARROW_STRETCH_WARN = 0; strs = {str_stretch{1:2},str_camera{:}}; strs = [char(ones(length(strs),1)*sprintf('\n ')) char(strs)]'; warning([upper(mfilename) ' may not yet work quite right ' ... 'if any of the following are ''manual'':' strs(:).']); end; % find the true pixel size of the actual axes texttmp = text(axl(1,[1 2 2 1 1 2 2 1]), ... axl(2,[1 1 2 2 1 1 2 2]), ... axl(3,[1 1 1 1 2 2 2 2]),''); set(texttmp,'Units','points'); textpos = get(texttmp,'Position'); delete(texttmp); textpos = cat(1,textpos{:}); textpos = max(textpos(:,1:2)) - min(textpos(:,1:2)); % adjust the axes position if (really_curpage), % adjust to printed size textpos = textpos * min(curap(3:4)./textpos); curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos]; else, % adjust for pixel roundoff textpos = textpos * min(curapscreen(3:4)./textpos); curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos]; end; end; if ARROW_PERSP_WARN & ~strcmp(get(curax,'Projection'),'orthographic'), ARROW_PERSP_WARN = 0; warning([upper(mfilename) ' does not yet work right for 3-D perspective projection.']); end; % adjust limits for log scale on axes curxyzlog = [strcmp(get(curax,'XScale'),'log'); ... strcmp(get(curax,'YScale'),'log'); ... strcmp(get(curax,'ZScale'),'log')]; if (any(curxyzlog)), ii = find([curxyzlog;curxyzlog]); if (any(axl(ii)<=0)), error([upper(mfilename) ' does not support non-positive limits on log-scaled axes.']); else, axl(ii) = log10(axl(ii)); end; end; % correct for 'reverse' direction on axes; curreverse = [strcmp(get(curax,'XDir'),'reverse'); ... strcmp(get(curax,'YDir'),'reverse'); ... strcmp(get(curax,'ZDir'),'reverse')]; ii = find(curreverse); if ~isempty(ii), axl(ii,[1 2])=-axl(ii,[2 1]); end; % compute the range of 2-D values curT = get(curax,'Xform'); lim = curT*[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1;0 0 0 0 1 1 1 1;1 1 1 1 1 1 1 1]; lim = lim(1:2,:)./([1;1]*lim(4,:)); curlimmin = min(lim')'; curlimrange = max(lim')' - curlimmin; curinvT = inv(curT); if (~oneax), curT = curT.'; curinvT = curinvT.'; curT = curT(:); curinvT = curinvT(:); end; % check which arrows to which cur corresponds ii = find((ax==curax)&(page==curpage)); oo = ones(1,length(ii)); axr(:,ii) = diff(axl')' * oo; axm(:,ii) = axl(:,1) * oo; axrev(:,ii) = curreverse * oo; ap(:,ii) = curap(3:4)' * oo; xyzlog(:,ii) = curxyzlog * oo; limmin(:,ii) = curlimmin * oo; limrange(:,ii) = curlimrange * oo; if (oneax), T = curT; invT = curinvT; else, T(:,ii) = curT * oo; invT(:,ii) = curinvT * oo; end; axnotdone(ii) = zeros(1,length(ii)); end; oldaxlims(oldaxlims(:,1)==0,:)=[]; % correct for log scales curxyzlog = xyzlog.'; ii = find(curxyzlog(:)); if ~isempty(ii), start( ii) = real(log10(start( ii))); stop( ii) = real(log10(stop( ii))); if (all(imag(crossdir)==0)), % pulled (ii) subscript on crossdir, 12/5/96 eaj crossdir(ii) = real(log10(crossdir(ii))); end; end; % correct for reverse directions ii = find(axrev.'); if ~isempty(ii), start( ii) = -start( ii); stop( ii) = -stop( ii); crossdir(ii) = -crossdir(ii); end; % transpose start/stop values start = start.'; stop = stop.'; % take care of defaults, page was done above ii=find(isnan(start(:) )); if ~isempty(ii), start(ii) = axm(ii)+axr(ii)/2; end; ii=find(isnan(stop(:) )); if ~isempty(ii), stop(ii) = axm(ii)+axr(ii)/2; end; ii=find(isnan(crossdir(:) )); if ~isempty(ii), crossdir(ii) = zeros(length(ii),1); end; ii=find(isnan(len )); if ~isempty(ii), len(ii) = ones(length(ii),1)*deflen; end; ii=find(isnan(baseangle )); if ~isempty(ii), baseangle(ii) = ones(length(ii),1)*defbaseangle; end; ii=find(isnan(tipangle )); if ~isempty(ii), tipangle(ii) = ones(length(ii),1)*deftipangle; end; ii=find(isnan(wid )); if ~isempty(ii), wid(ii) = ones(length(ii),1)*defwid; end; ii=find(isnan(ends )); if ~isempty(ii), ends(ii) = ones(length(ii),1)*defends; end; % transpose rest of values len = len.'; baseangle = baseangle.'; tipangle = tipangle.'; wid = wid.'; page = page.'; crossdir = crossdir.'; ends = ends.'; ax = ax.'; % given x, a 3xN matrix of points in 3-space; % want to convert to X, the corresponding 4xN 2-space matrix % % tmp1=[(x-axm)./axr; ones(1,size(x,1))]; % if (oneax), X=T*tmp1; % else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; % tmp2=zeros(4,4*N); tmp2(:)=tmp1(:); % X=zeros(4,N); X(:)=sum(tmp2)'; end; % X = X ./ (ones(4,1)*X(4,:)); % for all points with start==stop, start=stop-(verysmallvalue)*(up-direction); ii = find(all(start==stop)); if ~isempty(ii), % find an arrowdir vertical on screen and perpendicular to viewer % transform to 2-D tmp1 = [(stop(:,ii)-axm(:,ii))./axr(:,ii);ones(1,length(ii))]; if (oneax), twoD=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); twoD=zeros(4,length(ii)); twoD(:)=sum(tmp2)'; end; twoD=twoD./(ones(4,1)*twoD(4,:)); % move the start point down just slightly tmp1 = twoD + [0;-1/1000;0;0]*(limrange(2,ii)./ap(2,ii)); % transform back to 3-D if (oneax), threeD=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); threeD=zeros(4,length(ii)); threeD(:)=sum(tmp2)'; end; start(:,ii) = (threeD(1:3,:)./(ones(3,1)*threeD(4,:))).*axr(:,ii)+axm(:,ii); end; % compute along-arrow points % transform Start points tmp1=[(start-axm)./axr;ones(1,narrows)]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); X0=zeros(4,narrows); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % transform Stop points tmp1=[(stop-axm)./axr;ones(1,narrows)]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); Xf=zeros(4,narrows); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute pixel distance between points D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*(ap./limrange)).^2)); D = D + (D==0); %eaj new 2/24/98 % compute and modify along-arrow distances len1 = len; len2 = len - (len.*tan(tipangle/180*pi)-wid/2).*tan((90-baseangle)/180*pi); slen0 = zeros(1,narrows); slen1 = len1 .* ((ends==2)|(ends==3)); slen2 = len2 .* ((ends==2)|(ends==3)); len0 = zeros(1,narrows); len1 = len1 .* ((ends==1)|(ends==3)); len2 = len2 .* ((ends==1)|(ends==3)); % for no start arrowhead ii=find((ends==1)&(D<len2)); if ~isempty(ii), slen0(ii) = D(ii)-len2(ii); end; % for no end arrowhead ii=find((ends==2)&(D<slen2)); if ~isempty(ii), len0(ii) = D(ii)-slen2(ii); end; len1 = len1 + len0; len2 = len2 + len0; slen1 = slen1 + slen0; slen2 = slen2 + slen0; % note: the division by D below will probably not be accurate if both % of the following are true: % 1. the ratio of the line length to the arrowhead % length is large % 2. the view is highly perspective. % compute stoppoints tmp1=X0.*(ones(4,1)*(len0./D))+Xf.*(ones(4,1)*(1-len0./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; stoppoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute tippoints tmp1=X0.*(ones(4,1)*(len1./D))+Xf.*(ones(4,1)*(1-len1./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; tippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute basepoints tmp1=X0.*(ones(4,1)*(len2./D))+Xf.*(ones(4,1)*(1-len2./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; basepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute startpoints tmp1=X0.*(ones(4,1)*(1-slen0./D))+Xf.*(ones(4,1)*(slen0./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; startpoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute stippoints tmp1=X0.*(ones(4,1)*(1-slen1./D))+Xf.*(ones(4,1)*(slen1./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; stippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute sbasepoints tmp1=X0.*(ones(4,1)*(1-slen2./D))+Xf.*(ones(4,1)*(slen2./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; sbasepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute cross-arrow directions for arrows with NormalDir specified if (any(imag(crossdir(:))~=0)), ii = find(any(imag(crossdir)~=0)); crossdir(:,ii) = cross((stop(:,ii)-start(:,ii))./axr(:,ii), ... imag(crossdir(:,ii))).*axr(:,ii); end; % compute cross-arrow directions basecross = crossdir + basepoint; tipcross = crossdir + tippoint; sbasecross = crossdir + sbasepoint; stipcross = crossdir + stippoint; ii = find(all(crossdir==0)|any(isnan(crossdir))); if ~isempty(ii), numii = length(ii); % transform start points tmp1 = [basepoint(:,ii) tippoint(:,ii) sbasepoint(:,ii) stippoint(:,ii)]; tmp1 = (tmp1-axm(:,[ii ii ii ii])) ./ axr(:,[ii ii ii ii]); tmp1 = [tmp1; ones(1,4*numii)]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); X0=zeros(4,4*numii); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % transform stop points tmp1 = [(2*stop(:,ii)-start(:,ii)-axm(:,ii))./axr(:,ii);ones(1,numii)]; tmp1 = [tmp1 tmp1 tmp1 tmp1]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xf=zeros(4,4*numii); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute perpendicular directions pixfact = ((limrange(1,ii)./limrange(2,ii)).*(ap(2,ii)./ap(1,ii))).^2; pixfact = [pixfact pixfact pixfact pixfact]; pixfact = [pixfact;1./pixfact]; [dummyval,jj] = max(abs(Xf(1:2,:)-X0(1:2,:))); jj1 = ((1:4)'*ones(1,length(jj))==ones(4,1)*jj); jj2 = ((1:4)'*ones(1,length(jj))==ones(4,1)*(3-jj)); jj3 = jj1(1:2,:); Xf(jj1)=Xf(jj1)+(Xf(jj1)-X0(jj1)==0); %eaj new 2/24/98 Xp = X0; Xp(jj2) = X0(jj2) + ones(sum(jj2(:)),1); Xp(jj1) = X0(jj1) - (Xf(jj2)-X0(jj2))./(Xf(jj1)-X0(jj1)) .* pixfact(jj3); % inverse transform the cross points if (oneax), Xp=invT*Xp; else, tmp1=[Xp;Xp;Xp;Xp]; tmp1=invT(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xp=zeros(4,4*numii); Xp(:)=sum(tmp2)'; end; Xp=(Xp(1:3,:)./(ones(3,1)*Xp(4,:))).*axr(:,[ii ii ii ii])+axm(:,[ii ii ii ii]); basecross(:,ii) = Xp(:,0*numii+(1:numii)); tipcross(:,ii) = Xp(:,1*numii+(1:numii)); sbasecross(:,ii) = Xp(:,2*numii+(1:numii)); stipcross(:,ii) = Xp(:,3*numii+(1:numii)); end; % compute all points % compute start points axm11 = [axm axm axm axm axm axm axm axm axm axm axm]; axr11 = [axr axr axr axr axr axr axr axr axr axr axr]; st = [stoppoint tippoint basepoint sbasepoint stippoint startpoint stippoint sbasepoint basepoint tippoint stoppoint]; tmp1 = (st - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); X0=zeros(4,11*narrows); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % compute stop points tmp1 = ([start tipcross basecross sbasecross stipcross stop stipcross sbasecross basecross tipcross start] ... - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); Xf=zeros(4,11*narrows); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute lengths len0 = len.*((ends==1)|(ends==3)).*tan(tipangle/180*pi); slen0 = len.*((ends==2)|(ends==3)).*tan(tipangle/180*pi); le = [zeros(1,narrows) len0 wid/2 wid/2 slen0 zeros(1,narrows) -slen0 -wid/2 -wid/2 -len0 zeros(1,narrows)]; aprange = ap./limrange; aprange = [aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange]; D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*aprange).^2)); Dii=find(D==0); if ~isempty(Dii), D=D+(D==0); le(Dii)=zeros(1,length(Dii)); end; %should fix DivideByZero warnings tmp1 = X0.*(ones(4,1)*(1-le./D)) + Xf.*(ones(4,1)*(le./D)); % inverse transform if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[invT invT invT invT invT invT invT invT invT invT invT].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,11*narrows); tmp3(:)=sum(tmp2)'; end; pts = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)) .* axr11 + axm11; % correct for ones where the crossdir was specified ii = find(~(all(crossdir==0)|any(isnan(crossdir)))); if ~isempty(ii), D1 = [pts(:,1*narrows+ii)-pts(:,9*narrows+ii) ... pts(:,2*narrows+ii)-pts(:,8*narrows+ii) ... pts(:,3*narrows+ii)-pts(:,7*narrows+ii) ... pts(:,4*narrows+ii)-pts(:,6*narrows+ii) ... pts(:,6*narrows+ii)-pts(:,4*narrows+ii) ... pts(:,7*narrows+ii)-pts(:,3*narrows+ii) ... pts(:,8*narrows+ii)-pts(:,2*narrows+ii) ... pts(:,9*narrows+ii)-pts(:,1*narrows+ii)]/2; ii = ii'*ones(1,8) + ones(length(ii),1)*[1:4 6:9]*narrows; ii = ii(:)'; pts(:,ii) = st(:,ii) + D1; end; % readjust for reverse directions iicols=(1:narrows)'; iicols=iicols(:,ones(1,11)); iicols=iicols(:).'; tmp1=axrev(:,iicols); ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=-pts(ii); end; % readjust for log scale on axes tmp1=xyzlog(:,iicols); ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=10.^pts(ii); end; % compute the x,y,z coordinates of the patches; ii = narrows*(0:10)'*ones(1,narrows) + ones(11,1)*(1:narrows); ii = ii(:)'; x = zeros(11,narrows); y = zeros(11,narrows); z = zeros(11,narrows); x(:) = pts(1,ii)'; y(:) = pts(2,ii)'; z(:) = pts(3,ii)'; % do the output if (nargout<=1), % % create or modify the patches newpatch = trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'patch')); newline = ~trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'line')); if isempty(oldh), H=zeros(narrows,1); else, H=oldh; end; % % make or modify the arrows for k=1:narrows, if all(isnan(ud(k,[3 6])))&arrow_is2DXY(ax(k)), zz=[]; else, zz=z(:,k); end; xx=x(:,k); yy=y(:,k); if (0), % this fix didn't work, so let's not use it -- 8/26/03 % try to work around a MATLAB 6.x OpenGL bug -- 7/28/02 mask=any([ones(1,2+size(zz,2));diff([xx yy zz],[],1)],2); xx=xx(mask); yy=yy(mask); if ~isempty(zz), zz=zz(mask); end; end; % plot the patch or line xyz = {'XData',xx,'YData',yy,'ZData',zz,'Tag',ArrowTag}; if newpatch(k)|newline(k), if newpatch(k), H(k) = patch(xyz{:}); else, H(k) = line(xyz{:}); end; if ~isempty(oldh), arrow_copyprops(oldh(k),H(k)); end; else, if ispatch(k), xyz={xyz{:},'CData',[]}; end; set(H(k),xyz{:}); end; end; if ~isempty(oldh), delete(oldh(oldh~=H)); end; % % additional properties set(H,'Clipping','off'); set(H,{'UserData'},num2cell(ud,2)); if (length(extraprops)>0), set(H,extraprops{:}); end; % handle choosing arrow Start and/or Stop locations if unspecified [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims); if ~isempty(errstr), error([upper(mfilename) ' got ' errstr]); end; % set the output if (nargout>0), h=H; end; % make sure the axis limits did not change if isempty(oldaxlims), ARROW_AXLIMITS = []; else, lims = get(oldaxlims(:,1),{'XLim','YLim','ZLim'})'; lims = reshape(cat(2,lims{:}),6,size(lims,2)); mask = arrow_is2DXY(oldaxlims(:,1)); oldaxlims(mask,6:7) = lims(5:6,mask)'; ARROW_AXLIMITS = oldaxlims(find(any(oldaxlims(:,2:7)'~=lims)),:); if ~isempty(ARROW_AXLIMITS), warning(arrow_warnlimits(ARROW_AXLIMITS,narrows)); end; end; else, % don't create the patch, just return the data h=x; yy=y; zz=z; end; function out = arrow_defcheck(in,def,prop) % check if we got 'default' values out = in; if ~isstr(in), return; end; if size(in,1)==1 & strncmp(lower(in),'def',3), out = def; elseif ~isempty(prop), error([upper(mfilename) ' does not recognize ''' in(:)' ''' as a valid ''' prop ''' string.']); end; function [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims) % handle choosing arrow Start and/or Stop locations if necessary errstr = ''; if isempty(H)|isempty(ud)|isempty(x), return; end; % determine which (if any) need Start and/or Stop needStart = all(isnan(ud(:,1:3)'))'; needStop = all(isnan(ud(:,4:6)'))'; mask = any(needStart|needStop); if ~any(mask), return; end; ud(~mask,:)=[]; ax(:,~mask)=[]; x(:,~mask)=[]; y(:,~mask)=[]; z(:,~mask)=[]; % make them invisible for the time being set(H,'Visible','off'); % save the current axes and limits modes; set to manual for the time being oldAx = gca; limModes=get(ax(:),{'XLimMode','YLimMode','ZLimMode'}); set(ax(:),{'XLimMode','YLimMode','ZLimMode'},{'manual','manual','manual'}); % loop over each arrow that requires attention jj = find(mask); for ii=1:length(jj), h = H(jj(ii)); axes(ax(ii)); % figure out correct call if needStart(ii), prop='Start'; else, prop='Stop'; end; [wasInterrupted,errstr] = arrow_click(needStart(ii)&needStop(ii),h,prop,ax(ii)); % handle errors and control-C if wasInterrupted, delete(H(jj(ii:end))); H(jj(ii:end))=[]; oldaxlims(jj(ii:end),:)=[]; break; end; end; % restore the axes and limit modes axes(oldAx); set(ax(:),{'XLimMode','YLimMode','ZLimMode'},limModes); function [wasInterrupted,errstr] = arrow_click(lockStart,H,prop,ax) % handle the clicks for one arrow fig = get(ax,'Parent'); % save some things oldFigProps = {'Pointer','WindowButtonMotionFcn','WindowButtonUpFcn'}; oldFigValue = get(fig,oldFigProps); oldArrowProps = {'EraseMode'}; oldArrowValue = get(H,oldArrowProps); set(H,'EraseMode','background'); %because 'xor' makes shaft invisible unless Width>1 global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z ARROW_CLICK_H=H; ARROW_CLICK_PROP=prop; ARROW_CLICK_AX=ax; ARROW_CLICK_USE_Z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); set(fig,'Pointer','crosshair'); % set up the WindowButtonMotion so we can see the arrow while moving around set(fig,'WindowButtonUpFcn','set(gcf,''WindowButtonUpFcn'','''')', ... 'WindowButtonMotionFcn',''); if ~lockStart, set(H,'Visible','on'); set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']); end; % wait for the button to be pressed [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig); % if we wanted to click-drag, set the Start point if lockStart & ~wasInterrupted, pt = arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z); feval(mfilename,H,'Start',pt,'Stop',pt); set(H,'Visible','on'); ARROW_CLICK_PROP='Stop'; set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']); % wait for the mouse button to be released try waitfor(fig,'WindowButtonUpFcn',''); catch errstr = lasterr; wasInterrupted = 1; end; end; if ~wasInterrupted, feval(mfilename,'callback','motion'); end; % restore some things set(gcf,oldFigProps,oldFigValue); set(H,oldArrowProps,oldArrowValue); function arrow_callback(varargin) % handle redrawing callbacks if nargin==0, return; end; str = varargin{1}; if ~isstr(str), error([upper(mfilename) ' got an invalid Callback command.']); end; s = lower(str); if strcmp(s,'motion'), % motion callback global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z feval(mfilename,ARROW_CLICK_H,ARROW_CLICK_PROP,arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z)); drawnow; else, error([upper(mfilename) ' does not recognize ''' str(:).' ''' as a valid Callback option.']); end; function out = arrow_point(ax,use_z) % return the point on the given axes if nargin==0, ax=gca; end; if nargin<2, use_z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); end; out = get(ax,'CurrentPoint'); out = out(1,:); if ~use_z, out=out(1:2); end; function [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig) % wait for button down ignoring object ButtonDownFcn's if nargin==0, fig=gcf; end; errstr = ''; % save ButtonDownFcn values objs = findobj(fig); buttonDownFcns = get(objs,'ButtonDownFcn'); mask=~strcmp(buttonDownFcns,''); objs=objs(mask); buttonDownFcns=buttonDownFcns(mask); set(objs,'ButtonDownFcn',''); % save other figure values figProps = {'KeyPressFcn','WindowButtonDownFcn'}; figValue = get(fig,figProps); % do the real work set(fig,'KeyPressFcn','set(gcf,''KeyPressFcn'','''',''WindowButtonDownFcn'','''');', ... 'WindowButtonDownFcn','set(gcf,''WindowButtonDownFcn'','''')'); lasterr(''); try waitfor(fig,'WindowButtonDownFcn',''); wasInterrupted = 0; catch wasInterrupted = 1; end wasKeyPress = ~wasInterrupted & strcmp(get(fig,'KeyPressFcn'),''); if wasInterrupted, errstr=lasterr; end; % restore ButtonDownFcn and other figure values set(objs,'ButtonDownFcn',buttonDownFcns); set(fig,figProps,figValue); function [out,is2D] = arrow_is2DXY(ax) % check if axes are 2-D X-Y plots % may not work for modified camera angles, etc. out = logical(zeros(size(ax))); % 2-D X-Y plots is2D = out; % any 2-D plots views = get(ax(:),{'View'}); views = cat(1,views{:}); out(:) = abs(views(:,2))==90; is2D(:) = out(:) | all(rem(views',90)==0)'; function out = arrow_planarkids(ax) % check if axes descendents all have empty ZData (lines,patches,surfaces) out = logical(ones(size(ax))); allkids = get(ax(:),{'Children'}); for k=1:length(allkids), kids = get([findobj(allkids{k},'flat','Type','line') findobj(allkids{k},'flat','Type','patch') findobj(allkids{k},'flat','Type','surface')],{'ZData'}); for j=1:length(kids), if ~isempty(kids{j}), out(k)=logical(0); break; end; end; end; function arrow_fixlimits(axlimits) % reset the axis limits as necessary if isempty(axlimits), disp([upper(mfilename) ' does not remember any axis limits to reset.']); end; for k=1:size(axlimits,1), if any(get(axlimits(k,1),'XLim')~=axlimits(k,2:3)), set(axlimits(k,1),'XLim',axlimits(k,2:3)); end; if any(get(axlimits(k,1),'YLim')~=axlimits(k,4:5)), set(axlimits(k,1),'YLim',axlimits(k,4:5)); end; if any(get(axlimits(k,1),'ZLim')~=axlimits(k,6:7)), set(axlimits(k,1),'ZLim',axlimits(k,6:7)); end; end; function out = arrow_WarpToFill(notstretched,manualcamera,curax) % check if we are in "WarpToFill" mode. out = strcmp(get(curax,'WarpToFill'),'on'); % 'WarpToFill' is undocumented, so may need to replace this by % out = ~( any(notstretched) & any(manualcamera) ); function out = arrow_warnlimits(axlimits,narrows) % create a warning message if we've changed the axis limits msg = ''; switch (size(axlimits,1)) case 1, msg=''; case 2, msg='on two axes '; otherwise, msg='on several axes '; end; msg = [upper(mfilename) ' changed the axis limits ' msg ... 'when adding the arrow']; if (narrows>1), msg=[msg 's']; end; out = [msg '.' sprintf('\n') ' Call ' upper(mfilename) ... ' FIXLIMITS to reset them now.']; function arrow_copyprops(fm,to) % copy line properties to patches props = {'EraseMode','LineStyle','LineWidth','Marker','MarkerSize',... 'MarkerEdgeColor','MarkerFaceColor','ButtonDownFcn', ... 'Clipping','DeleteFcn','BusyAction','HandleVisibility', ... 'Selected','SelectionHighlight','Visible'}; lineprops = {'Color', props{:}}; patchprops = {'EdgeColor',props{:}}; patch2props = {'FaceColor',patchprops{:}}; fmpatch = strcmp(get(fm,'Type'),'patch'); topatch = strcmp(get(to,'Type'),'patch'); set(to( fmpatch& topatch),patch2props,get(fm( fmpatch& topatch),patch2props)); %p->p set(to(~fmpatch&~topatch),lineprops, get(fm(~fmpatch&~topatch),lineprops )); %l->l set(to( fmpatch&~topatch),lineprops, get(fm( fmpatch&~topatch),patchprops )); %p->l set(to(~fmpatch& topatch),patchprops, get(fm(~fmpatch& topatch),lineprops) ,'FaceColor','none'); %l->p function arrow_props % display further help info about ARROW properties c = sprintf('\n'); disp([c ... 'ARROW Properties: Default values are given in [square brackets], and other' c ... ' acceptable equivalent property names are in (parenthesis).' c c ... ' Start The starting points. For N arrows, B' c ... ' this should be a Nx2 or Nx3 matrix. /|\ ^' c ... ' Stop The end points. For N arrows, this /|||\ |' c ... ' should be a Nx2 or Nx3 matrix. //|||\\ L|' c ... ' Length Length of the arrowhead (in pixels on ///|||\\\ e|' c ... ' screen, points on a page). [16] (Len) ////|||\\\\ n|' c ... ' BaseAngle Angle (degrees) of the base angle /////|D|\\\\\ g|' c ... ' ADE. For a simple stick arrow, use //// ||| \\\\ t|' c ... ' BaseAngle=TipAngle. [90] (Base) /// ||| \\\ h|' c ... ' TipAngle Angle (degrees) of tip angle ABC. //<----->|| \\ |' c ... ' [16] (Tip) / base ||| \ V' c ... ' Width Width of the base in pixels. Not E angle ||<-------->C' c ... ' the ''LineWidth'' prop. [0] (Wid) |||tipangle' c ... ' Page If provided, non-empty, and not NaN, |||' c ... ' this causes ARROW to use hardcopy |||' c ... ' rather than onscreen proportions. A' c ... ' This is important if screen aspect --> <-- width' c ... ' ratio and hardcopy aspect ratio are ----CrossDir---->' c ... ' vastly different. []' c... ' CrossDir A vector giving the direction towards which the fletches' c ... ' on the arrow should go. [computed such that it is perpen-' c ... ' dicular to both the arrow direction and the view direction' c ... ' (i.e., as if it was pasted on a normal 2-D graph)] (Note' c ... ' that CrossDir is a vector. Also note that if an axis is' c ... ' plotted on a log scale, then the corresponding component' c ... ' of CrossDir must also be set appropriately, i.e., to 1 for' c ... ' no change in that direction, >1 for a positive change, >0' c ... ' and <1 for negative change.)' c ... ' NormalDir A vector normal to the fletch direction (CrossDir is then' c ... ' computed by the vector cross product [Line]x[NormalDir]). []' c ... ' (Note that NormalDir is a vector. Unlike CrossDir,' c ... ' NormalDir is used as is regardless of log-scaled axes.)' c ... ' Ends Set which end has an arrowhead. Valid values are ''none'',' c ... ' ''stop'', ''start'', and ''both''. [''stop''] (End)' c... ' ObjectHandles Vector of handles to previously-created arrows to be' c ... ' updated or line objects to be converted to arrows.' c ... ' [] (Object,Handle)' c ]); function out = arrow_demo % demo % create the data [x,y,z] = peaks; [ddd,out.iii]=max(z(:)); out.axlim = [min(x(:)) max(x(:)) min(y(:)) max(y(:)) min(z(:)) max(z(:))]; % modify it by inserting some NaN's [m,n] = size(z); m = floor(m/2); n = floor(n/2); z(1:m,1:n) = NaN*ones(m,n); % graph it clf('reset'); out.hs=surf(x,y,z); out.x=x; out.y=y; out.z=z; xlabel('x'); ylabel('y'); function h = arrow_demo3(in) % set the view axlim = in.axlim; axis(axlim); zlabel('z'); %set(in.hs,'FaceColor','interp'); view(3); % view(viewmtx(-37.5,30,20)); title(['Demo of the capabilities of the ARROW function in 3-D']); % Normal blue arrow h1 = feval(mfilename,[axlim(1) axlim(4) 4],[-.8 1.2 4], ... 'EdgeColor','b','FaceColor','b'); % Normal white arrow, clipped by the surface h2 = feval(mfilename,axlim([1 4 6]),[0 2 4]); t=text(-2.4,2.7,7.7,'arrow clipped by surf'); % Baseangle<90 h3 = feval(mfilename,[3 .125 3.5],[1.375 0.125 3.5],30,50); t2=text(3.1,.125,3.5,'local maximum'); % Baseangle<90, fill and edge colors different h4 = feval(mfilename,axlim(1:2:5)*.5,[0 0 0],36,60,25, ... 'EdgeColor','b','FaceColor','c'); t3=text(axlim(1)*.5,axlim(3)*.5,axlim(5)*.5-.75,'origin'); set(t3,'HorizontalAlignment','center'); % Baseangle>90, black fill h5 = feval(mfilename,[-2.9 2.9 3],[-1.3 .4 3.2],30,120,[],6, ... 'EdgeColor','r','FaceColor','k','LineWidth',2); % Baseangle>90, no fill h6 = feval(mfilename,[-2.9 2.9 1.3],[-1.3 .4 1.5],30,120,[],6, ... 'EdgeColor','r','FaceColor','none','LineWidth',2); % Stick arrow h7 = feval(mfilename,[-1.6 -1.65 -6.5],[0 -1.65 -6.5],[],16,16); t4=text(-1.5,-1.65,-7.25,'global mininum'); set(t4,'HorizontalAlignment','center'); % Normal, black fill h8 = feval(mfilename,[-1.4 0 -7.2],[-1.4 0 -3],'FaceColor','k'); t5=text(-1.5,0,-7.75,'local minimum'); set(t5,'HorizontalAlignment','center'); % Gray fill, crossdir specified, 'LineStyle' -- h9 = feval(mfilename,[-3 2.2 -6],[-3 2.2 -.05],36,[],27,6,[],[0 -1 0], ... 'EdgeColor','k','FaceColor',.75*[1 1 1],'LineStyle','--'); % a series of normal arrows, linearly spaced, crossdir specified h10y=(0:4)'/3; h10 = feval(mfilename,[-3*ones(size(h10y)) h10y -6.5*ones(size(h10y))], ... [-3*ones(size(h10y)) h10y -.05*ones(size(h10y))], ... 12,[],[],[],[],[0 -1 0]); % a series of normal arrows, linearly spaced h11x=(1:.33:2.8)'; h11 = feval(mfilename,[h11x -3*ones(size(h11x)) 6.5*ones(size(h11x))], ... [h11x -3*ones(size(h11x)) -.05*ones(size(h11x))]); % series of magenta arrows, radially oriented, crossdir specified h12x=2; h12y=-3; h12z=axlim(5)/2; h12xr=1; h12zr=h12z; ir=.15;or=.81; h12t=(0:11)'/6*pi; h12 = feval(mfilename, ... [h12x+h12xr*cos(h12t)*ir h12y*ones(size(h12t)) ... h12z+h12zr*sin(h12t)*ir],[h12x+h12xr*cos(h12t)*or ... h12y*ones(size(h12t)) h12z+h12zr*sin(h12t)*or], ... 10,[],[],[],[], ... [-h12xr*sin(h12t) zeros(size(h12t)) h12zr*cos(h12t)],... 'FaceColor','none','EdgeColor','m'); % series of normal arrows, tangentially oriented, crossdir specified or13=.91; h13t=(0:.5:12)'/6*pi; locs = [h12x+h12xr*cos(h13t)*or13 h12y*ones(size(h13t)) h12z+h12zr*sin(h13t)*or13]; h13 = feval(mfilename,locs(1:end-1,:),locs(2:end,:),6); % arrow with no line ==> oriented downwards h14 = feval(mfilename,[3 3 .100001],[3 3 .1],30); t6=text(3,3,3.6,'no line'); set(t6,'HorizontalAlignment','center'); % arrow with arrowheads at both ends h15 = feval(mfilename,[-.5 -3 -3],[1 -3 -3],'Ends','both','FaceColor','g', ... 'Length',20,'Width',3,'CrossDir',[0 0 1],'TipAngle',25); h=[h1;h2;h3;h4;h5;h6;h7;h8;h9;h10;h11;h12;h13;h14;h15]; function h = arrow_demo2(in) axlim = in.axlim; dolog = 1; if (dolog), set(in.hs,'YData',10.^get(in.hs,'YData')); end; shading('interp'); view(2); title(['Demo of the capabilities of the ARROW function in 2-D']); hold on; [C,H]=contour(in.x,in.y,in.z,20,'-'); hold off; for k=H', set(k,'ZData',(axlim(6)+1)*ones(size(get(k,'XData'))),'Color','k'); if (dolog), set(k,'YData',10.^get(k,'YData')); end; end; if (dolog), axis([axlim(1:2) 10.^axlim(3:4)]); set(gca,'YScale','log'); else, axis(axlim(1:4)); end; % Normal blue arrow start = [axlim(1) axlim(4) axlim(6)+2]; stop = [in.x(in.iii) in.y(in.iii) axlim(6)+2]; if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end; h1 = feval(mfilename,start,stop,'EdgeColor','b','FaceColor','b'); % three arrows with varying fill, width, and baseangle start = [-3 -3 10; -3 -1.5 10; -1.5 -3 10]; stop = [-.03 -.03 10; -.03 -1.5 10; -1.5 -.03 10]; if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end; h2 = feval(mfilename,start,stop,24,[90;60;120],[],[0;0;4],'Ends',str2mat('both','stop','stop')); set(h2(2),'EdgeColor',[0 .35 0],'FaceColor',[0 .85 .85]); set(h2(3),'EdgeColor','r','FaceColor',[1 .5 1]); h=[h1;h2]; function out = trueornan(x) if isempty(x), out=x; else, out = isnan(x); out(~out) = x(~out); end;
github
cosmicBboy/bayesian-reasoning-machine-learning-master
demoBayesErrorAnalysis.m
.m
bayesian-reasoning-machine-learning-master/src/BRMLtoolkit/DemosExercises/demoBayesErrorAnalysis.m
1,860
utf_8
2cd17f883c53fbb75be770a1da1a00a3
function demoBayesErrorAnalysis %DEMOBAYESERRORANALYSIS demo of Bayesian error analysis N = 20; % number of datapoints Q = 3; % number of error types % make some errors for the two classifers : errtype={'IndepSameErrorGenerator','IndepDiffErrorGenerator','DepErrorGenerator'}; GenerateError=errtype{randgen(1:3)} switch GenerateError case 'IndepDiffErrorGenerator' % independent different error generator: ra = rand(Q,1); rb = rand(Q,1); rab = ra*rb'; relprobC = vec(rab); case 'IndepSameErrorGenerator'% independent same error generator: ra = rand(Q,1); rb = ra; rab = ra*rb'; relprobC = vec(rab); case 'DepErrorGenerator'% dependent error generator: relprobC = vec(rand(Q,Q)); end errors = randgen(relprobC,1,N); % sample the errors % form the count matrices and vectors: vec_errorAB=zeros(1,Q*Q); for i=1:N vec_errorAB(errors(i))= vec_errorAB(errors(i))+1; end C = vec2mat(vec_errorAB) % count matrix of errors ca = sum(C,1); cb = sum(C,2)'; % Simple Bayesian analysis of the error counts based on Dirichlet % prior and multinomial error distribution: u =ones(1,Q); % uniform prior distribution lb = logZ(u+ca)+logZ(u+cb) - logZ(u)- logZ(u+ca+cb); disp(['p(classifiers are indep and different)/p(classifiers are independent and same)=',num2str(exp(lb))]); U=ones(Q,Q); % uniform prior lb = logZ(u+ca)+logZ(u+cb)+logZ(vec(U))-2*logZ(u)-logZ(vec(U+C)); disp(['p(classifiers are indep and different)/p(classifiers are dependent)=',num2str(exp(lb))]) % test Hsame/Hdep lb = logZ(u+ca+cb)+logZ(vec(U))-logZ(u)-logZ(vec(U+C)); disp(['p(classifiers are indep and same)/p(classifiers are dependent)=',num2str(exp(lb))]); function v = vec(C) tmp=C'; v=tmp(:); function C=vec2mat(v) Q = sqrt(length(v)); C= reshape(v,Q,Q)'; function lz=logZ(u) lz = sum(gammaln(u))- gammaln(sum(u));
github
cosmicBboy/bayesian-reasoning-machine-learning-master
textoval.m
.m
bayesian-reasoning-machine-learning-master/src/graphlayout/textoval.m
2,151
utf_8
654d6f5117ff68685aac2921423cb76d
function [t, wd] = textoval(x, y, str) % TEXTOVAL Draws an oval around text objects % % [T, WIDTH] = TEXTOVAL(X, Y, STR) % [..] = TEXTOVAL(STR) % Interactive % % Inputs : % X, Y : Coordinates % TXT : Strings % % Outputs : % T : Object Handles % WIDTH : x and y Width of ovals % % Usage Example : [t] = textoval('Visit to Asia?'); % % % Note : % See also TEXTBOX % Uses : % Change History : % Date Time Prog Note % 15-Jun-1998 10:36 AM ATC Created under MATLAB 5.1.0.421 % ATC = Ali Taylan Cemgil, % SNN - University of Nijmegen, Department of Medical Physics and Biophysics % e-mail : [email protected] temp = []; switch nargin, case 1, str = x; if ~isa(str,'cell') str=cellstr(str); end; N = length(str); wd = zeros(N,2); for i=1:N, [x, y] = ginput(1); tx = text(x,y,str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); [ptc wx wy] = draw_oval(tx, x, y); wd(i,:) = [wx wy]; delete(tx); tx = text(x,y,str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); temp = [temp ; tx ptc]; end; case 3, if ~isa(str,'cell') str=cellstr(str); end; N = length(str); wd = zeros(N,2); for i=1:N, tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); [ptc wx wy] = draw_oval(tx, x(i), y(i)); wd(i,:) = [wx wy]; delete(tx); tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); temp = [temp; tx ptc]; end; otherwise, end; if nargout>0, t = temp; end; function [ptc, wx, wy] = draw_oval(tx, x, y) % Draws an oval box around a tex object if isoctave pos=get(gcf,'Position'); xl=pos(3); yl=pos(4); l = length(get(tx,'string')); % octave workaround: db sz = [1 1 0.011*(4+l)*560/xl 0.012*(4)*420/yl]; else sz = get(tx,'Extent'); % octave doesn't understand this end wy = sz(4); wx = max(2/3*sz(3), wy); ptc = ellipse(x, y, wx, wy); set(ptc, 'FaceColor','w');
github
cosmicBboy/bayesian-reasoning-machine-learning-master
textbox.m
.m
bayesian-reasoning-machine-learning-master/src/graphlayout/textbox.m
2,118
utf_8
f7750958b5bdcd1839e4800abdeb9c21
function [t, wd] = textbox(x,y,str) % TEXTBOX Draws A Box around the text % % [T, WIDTH] = TEXTBOX(X, Y, STR) % [..] = TEXTBOX(STR) % % Inputs : % X, Y : Coordinates % TXT : Strings % % Outputs : % T : Object Handles % WIDTH : x and y Width of boxes %% % Usage Example : t = textbox({'Ali','Veli','49','50'}); % % % Note : % See also TEXTOVAL % Uses : % Change History : % Date Time Prog Note % 09-Jun-1998 11:43 AM ATC Created under MATLAB 5.1.0.421 % ATC = Ali Taylan Cemgil, % SNN - University of Nijmegen, Department of Medical Physics and Biophysics % e-mail : [email protected] % See temp = []; switch nargin, case 1, str = x; if ~isa(str,'cell') str=cellstr(str); end; N = length(str); wd = zeros(N,2); for i=1:N, [x, y] = ginput(1); tx = text(x,y,str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); [ptc wx wy] = draw_box(tx, x, y); wd(i,:) = [wx wy]; delete(tx); tx = text(x,y,str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); temp = [temp; tx ptc]; end; case 3, if ~isa(str,'cell') str=cellstr(str); end; N = length(str); for i=1:N, tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); [ptc wx wy] = draw_box(tx, x(i), y(i)); wd(i,:) = [wx wy]; delete(tx); tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlignment','middle'); temp = [temp; tx ptc]; end; otherwise, end; if nargout>0, t = temp; end; function [ptc, wx, wy] = draw_box(tx, x, y) % Draws a box around a tex object if isoctave pos=get(gcf,'Position'); xl=pos(3); yl=pos(4); l = length(get(tx,'string')); % octave workaround: db sz = [1 1 0.01*(4+l)*560/xl 0.01*(4)*420/yl]; else sz = get(tx,'Extent'); end wy = 2/3*sz(4); wx = max(2/3*sz(3), wy); ptc = patch([x-wx x+wx x+wx x-wx], [y+wy y+wy y-wy y-wy],'w'); set(ptc, 'FaceColor','w');
github
cosmicBboy/bayesian-reasoning-machine-learning-master
arrow.m
.m
bayesian-reasoning-machine-learning-master/src/graphlayout/private/arrow.m
56,774
utf_8
2dc514962f607a6855ee3f8bfbee74c4
function [h,yy,zz] = arrow(varargin) % ARROW Draw a line with an arrowhead. % % ARROW(Start,Stop) draws a line with an arrow from Start to Stop (points % should be vectors of length 2 or 3, or matrices with 2 or 3 % columns), and returns the graphics handle of the arrow(s). % % ARROW uses the mouse (click-drag) to create an arrow. % % ARROW DEMO & ARROW DEMO2 show 3-D & 2-D demos of the capabilities of ARROW. % % ARROW may be called with a normal argument list or a property-based list. % ARROW(Start,Stop,Length,BaseAngle,TipAngle,Width,Page,CrossDir) is % the full normal argument list, where all but the Start and Stop % points are optional. If you need to specify a later argument (e.g., % Page) but want default values of earlier ones (e.g., TipAngle), % pass an empty matrix for the earlier ones (e.g., TipAngle=[]). % % ARROW('Property1',PropVal1,'Property2',PropVal2,...) creates arrows with the % given properties, using default values for any unspecified or given as % 'default' or NaN. Some properties used for line and patch objects are % used in a modified fashion, others are passed directly to LINE, PATCH, % or SET. For a detailed properties explanation, call ARROW PROPERTIES. % % Start The starting points. B % Stop The end points. /|\ ^ % Length Length of the arrowhead in pixels. /|||\ | % BaseAngle Base angle in degrees (ADE). //|||\\ L| % TipAngle Tip angle in degrees (ABC). ///|||\\\ e| % Width Width of the base in pixels. ////|||\\\\ n| % Page Use hardcopy proportions. /////|D|\\\\\ g| % CrossDir Vector || to arrowhead plane. //// ||| \\\\ t| % NormalDir Vector out of arrowhead plane. /// ||| \\\ h| % Ends Which end has an arrowhead. //<----->|| \\ | % ObjectHandles Vector of handles to update. / base ||| \ V % E angle||<-------->C % ARROW(H,'Prop1',PropVal1,...), where H is a |||tipangle % vector of handles to previously-created arrows ||| % and/or line objects, will update the previously- ||| % created arrows according to the current view -->|A|<-- width % and any specified properties, and will convert % two-point line objects to corresponding arrows. ARROW(H) will update % the arrows if the current view has changed. Root, figure, or axes % handles included in H are replaced by all descendant Arrow objects. % % A property list can follow any specified normal argument list, e.g., % ARROW([1 2 3],[0 0 0],36,'BaseAngle',60) creates an arrow from (1,2,3) to % the origin, with an arrowhead of length 36 pixels and 60-degree base angle. % % The basic arguments or properties can generally be vectorized to create % multiple arrows with the same call. This is done by passing a property % with one row per arrow, or, if all arrows are to have the same property % value, just one row may be specified. % % You may want to execute AXIS(AXIS) before calling ARROW so it doesn't change % the axes on you; ARROW determines the sizes of arrow components BEFORE the % arrow is plotted, so if ARROW changes axis limits, arrows may be malformed. % % This version of ARROW uses features of MATLAB 6.x and is incompatible with % earlier MATLAB versions (ARROW for MATLAB 4.2c is available separately); % some problems with perspective plots still exist. % Copyright (c)1995-2009, Dr. Erik A. Johnson <[email protected]>, 5/20/2009 % http://www.usc.edu/civil_eng/johnsone/ % Revision history: % 5/20/09 EAJ Fix view direction in (3D) demo. % 6/26/08 EAJ Replace eval('trycmd','catchcmd') with try, trycmd; catch, % catchcmd; end; -- break's MATLAB 5 compatibility. % 8/26/03 EAJ Eliminate OpenGL attempted fix since it didn't fix anyway. % 11/15/02 EAJ Accomodate how MATLAB 6.5 handles NaN and logicals % 7/28/02 EAJ Tried (but failed) work-around for MATLAB 6.x / OpenGL bug % if zero 'Width' or not double-ended % 11/10/99 EAJ Add logical() to eliminate zero index problem in MATLAB 5.3. % 11/10/99 EAJ Corrected warning if axis limits changed on multiple axes. % 11/10/99 EAJ Update e-mail address. % 2/10/99 EAJ Some documentation updating. % 2/24/98 EAJ Fixed bug if Start~=Stop but both colinear with viewpoint. % 8/14/97 EAJ Added workaround for MATLAB 5.1 scalar logical transpose bug. % 7/21/97 EAJ Fixed a few misc bugs. % 7/14/97 EAJ Make arrow([],'Prop',...) do nothing (no old handles) % 6/23/97 EAJ MATLAB 5 compatible version, release. % 5/27/97 EAJ Added Line Arrows back in. Corrected a few bugs. % 5/26/97 EAJ Changed missing Start/Stop to mouse-selected arrows. % 5/19/97 EAJ MATLAB 5 compatible version, beta. % 4/13/97 EAJ MATLAB 5 compatible version, alpha. % 1/31/97 EAJ Fixed bug with multiple arrows and unspecified Z coords. % 12/05/96 EAJ Fixed one more bug with log plots and NormalDir specified % 10/24/96 EAJ Fixed bug with log plots and NormalDir specified % 11/13/95 EAJ Corrected handling for 'reverse' axis directions % 10/06/95 EAJ Corrected occasional conflict with SUBPLOT % 4/24/95 EAJ A major rewrite. % Fall 94 EAJ Original code. % Things to be done: % - in the arrow_clicks section, prompt by printing to the screen so that % the user knows what's going on; also make sure the figure is brought % to the front. % - segment parsing, computing, and plotting into separate subfunctions % - change computing from Xform to Camera paradigms % + this will help especially with 3-D perspective plots % + if the WarpToFill section works right, remove warning code % + when perpsective works properly, remove perspective warning code % - add cell property values and struct property name/values (like get/set) % - get rid of NaN as the "default" data label % + perhaps change userdata to a struct and don't include (or leave % empty) the values specified as default; or use a cell containing % an empty matrix for a default value % - add functionality of GET to retrieve current values of ARROW properties % Many thanks to Keith Rogers <[email protected]> for his many excellent % suggestions and beta testing. Check out his shareware package MATDRAW % (at ftp://ftp.mathworks.com/pub/contrib/v5/graphics/matdraw/) -- he has % permission to distribute ARROW with MATDRAW. % Permission is granted to distribute ARROW with the toolboxes for the book % "Solving Solid Mechanics Problems with MATLAB 5", by F. Golnaraghi et al. % (Prentice Hall, 1999). % Permission is granted to Dr. Josef Bigun to distribute ARROW with his % software to reproduce the figures in his image analysis text. if isoctave myarrow(varargin{1},varargin{2}); return end % global variable initialization global ARROW_PERSP_WARN ARROW_STRETCH_WARN ARROW_AXLIMITS if isempty(ARROW_PERSP_WARN ), ARROW_PERSP_WARN =1; end; if isempty(ARROW_STRETCH_WARN), ARROW_STRETCH_WARN=1; end; % Handle callbacks if (nargin>0 & isstr(varargin{1}) & strcmp(lower(varargin{1}),'callback')), arrow_callback(varargin{2:end}); return; end; % Are we doing the demo? c = sprintf('\n'); if (nargin==1 & isstr(varargin{1})), arg1 = lower(varargin{1}); if strncmp(arg1,'prop',4), arrow_props; elseif strncmp(arg1,'demo',4) clf reset demo_info = arrow_demo; if ~strncmp(arg1,'demo2',5), hh=arrow_demo3(demo_info); else, hh=arrow_demo2(demo_info); end; if (nargout>=1), h=hh; end; elseif strncmp(arg1,'fixlimits',3), arrow_fixlimits(ARROW_AXLIMITS); ARROW_AXLIMITS=[]; elseif strncmp(arg1,'help',4), disp(help(mfilename)); else, error([upper(mfilename) ' got an unknown single-argument string ''' deblank(arg1) '''.']); end; return; end; % Check # of arguments if (nargout>3), error([upper(mfilename) ' produces at most 3 output arguments.']); end; % find first property number firstprop = nargin+1; for k=1:length(varargin), if ~isnumeric(varargin{k}), firstprop=k; break; end; end; lastnumeric = firstprop-1; % check property list if (firstprop<=nargin), for k=firstprop:2:nargin, curarg = varargin{k}; if ~isstr(curarg) | sum(size(curarg)>1)>1, error([upper(mfilename) ' requires that a property name be a single string.']); end; end; if (rem(nargin-firstprop,2)~=1), error([upper(mfilename) ' requires that the property ''' ... varargin{nargin} ''' be paired with a property value.']); end; end; % default output if (nargout>0), h=[]; end; if (nargout>1), yy=[]; end; if (nargout>2), zz=[]; end; % set values to empty matrices start = []; stop = []; len = []; baseangle = []; tipangle = []; wid = []; page = []; crossdir = []; ends = []; ax = []; oldh = []; ispatch = []; defstart = [NaN NaN NaN]; defstop = [NaN NaN NaN]; deflen = 16; defbaseangle = 90; deftipangle = 16; defwid = 0; defpage = 0; defcrossdir = [NaN NaN NaN]; defends = 1; defoldh = []; defispatch = 1; % The 'Tag' we'll put on our arrows ArrowTag = 'Arrow'; % check for oldstyle arguments if (firstprop==2), % assume arg1 is a set of handles oldh = varargin{1}(:); if isempty(oldh), return; end; elseif (firstprop>9), error([upper(mfilename) ' takes at most 8 non-property arguments.']); elseif (firstprop>2), {start,stop,len,baseangle,tipangle,wid,page,crossdir}; args = [varargin(1:firstprop-1) cell(1,length(ans)-(firstprop-1))]; [start,stop,len,baseangle,tipangle,wid,page,crossdir] = deal(args{:}); end; % parse property pairs extraprops={}; for k=firstprop:2:nargin, prop = varargin{k}; val = varargin{k+1}; prop = [lower(prop(:)') ' ']; if strncmp(prop,'start' ,5), start = val; elseif strncmp(prop,'stop' ,4), stop = val; elseif strncmp(prop,'len' ,3), len = val(:); elseif strncmp(prop,'base' ,4), baseangle = val(:); elseif strncmp(prop,'tip' ,3), tipangle = val(:); elseif strncmp(prop,'wid' ,3), wid = val(:); elseif strncmp(prop,'page' ,4), page = val; elseif strncmp(prop,'cross' ,5), crossdir = val; elseif strncmp(prop,'norm' ,4), if (isstr(val)), crossdir=val; else, crossdir=val*sqrt(-1); end; elseif strncmp(prop,'end' ,3), ends = val; elseif strncmp(prop,'object',6), oldh = val(:); elseif strncmp(prop,'handle',6), oldh = val(:); elseif strncmp(prop,'type' ,4), ispatch = val; elseif strncmp(prop,'userd' ,5), %ignore it else, % make sure it is a valid patch or line property try get(0,['DefaultPatch' varargin{k}]); catch errstr = lasterr; try get(0,['DefaultLine' varargin{k}]); catch errstr(1:max(find(errstr==char(13)|errstr==char(10)))) = ''; error([upper(mfilename) ' got ' errstr]); end end; extraprops={extraprops{:},varargin{k},val}; end; end; % Check if we got 'default' values start = arrow_defcheck(start ,defstart ,'Start' ); stop = arrow_defcheck(stop ,defstop ,'Stop' ); len = arrow_defcheck(len ,deflen ,'Length' ); baseangle = arrow_defcheck(baseangle,defbaseangle,'BaseAngle' ); tipangle = arrow_defcheck(tipangle ,deftipangle ,'TipAngle' ); wid = arrow_defcheck(wid ,defwid ,'Width' ); crossdir = arrow_defcheck(crossdir ,defcrossdir ,'CrossDir' ); page = arrow_defcheck(page ,defpage ,'Page' ); ends = arrow_defcheck(ends ,defends ,'' ); oldh = arrow_defcheck(oldh ,[] ,'ObjectHandles'); ispatch = arrow_defcheck(ispatch ,defispatch ,'' ); % check transpose on arguments [m,n]=size(start ); if any(m==[2 3])&(n==1|n>3), start = start'; end; [m,n]=size(stop ); if any(m==[2 3])&(n==1|n>3), stop = stop'; end; [m,n]=size(crossdir); if any(m==[2 3])&(n==1|n>3), crossdir = crossdir'; end; % convert strings to numbers if ~isempty(ends) & isstr(ends), endsorig = ends; [m,n] = size(ends); col = lower([ends(:,1:min(3,n)) ones(m,max(0,3-n))*' ']); ends = NaN*ones(m,1); oo = ones(1,m); ii=find(all(col'==['non']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*0; end; ii=find(all(col'==['sto']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*1; end; ii=find(all(col'==['sta']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*2; end; ii=find(all(col'==['bot']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*3; end; if any(isnan(ends)), ii = min(find(isnan(ends))); error([upper(mfilename) ' does not recognize ''' deblank(endsorig(ii,:)) ''' as a valid ''Ends'' value.']); end; else, ends = ends(:); end; if ~isempty(ispatch) & isstr(ispatch), col = lower(ispatch(:,1)); patchchar='p'; linechar='l'; defchar=' '; mask = col~=patchchar & col~=linechar & col~=defchar; if any(mask), error([upper(mfilename) ' does not recognize ''' deblank(ispatch(min(find(mask)),:)) ''' as a valid ''Type'' value.']); end; ispatch = (col==patchchar)*1 + (col==linechar)*0 + (col==defchar)*defispatch; else, ispatch = ispatch(:); end; oldh = oldh(:); % check object handles if ~all(ishandle(oldh)), error([upper(mfilename) ' got invalid object handles.']); end; % expand root, figure, and axes handles if ~isempty(oldh), ohtype = get(oldh,'Type'); mask = strcmp(ohtype,'root') | strcmp(ohtype,'figure') | strcmp(ohtype,'axes'); if any(mask), oldh = num2cell(oldh); for ii=find(mask)', oldh(ii) = {findobj(oldh{ii},'Tag',ArrowTag)}; end; oldh = cat(1,oldh{:}); if isempty(oldh), return; end; % no arrows to modify, so just leave end; end; % largest argument length [mstart,junk]=size(start); [mstop,junk]=size(stop); [mcrossdir,junk]=size(crossdir); argsizes = [length(oldh) mstart mstop ... length(len) length(baseangle) length(tipangle) ... length(wid) length(page) mcrossdir length(ends) ]; args=['length(ObjectHandle) '; ... '#rows(Start) '; ... '#rows(Stop) '; ... 'length(Length) '; ... 'length(BaseAngle) '; ... 'length(TipAngle) '; ... 'length(Width) '; ... 'length(Page) '; ... '#rows(CrossDir) '; ... '#rows(Ends) ']; if (any(imag(crossdir(:))~=0)), args(9,:) = '#rows(NormalDir) '; end; if isempty(oldh), narrows = max(argsizes); else, narrows = length(oldh); end; if (narrows<=0), narrows=1; end; % Check size of arguments ii = find((argsizes~=0)&(argsizes~=1)&(argsizes~=narrows)); if ~isempty(ii), s = args(ii',:); while ((size(s,2)>1)&((abs(s(:,size(s,2)))==0)|(abs(s(:,size(s,2)))==abs(' ')))), s = s(:,1:size(s,2)-1); end; s = [ones(length(ii),1)*[upper(mfilename) ' requires that '] s ... ones(length(ii),1)*[' equal the # of arrows (' num2str(narrows) ').' c]]; s = s'; s = s(:)'; s = s(1:length(s)-1); error(setstr(s)); end; % check element length in Start, Stop, and CrossDir if ~isempty(start), [m,n] = size(start); if (n==2), start = [start NaN*ones(m,1)]; elseif (n~=3), error([upper(mfilename) ' requires 2- or 3-element Start points.']); end; end; if ~isempty(stop), [m,n] = size(stop); if (n==2), stop = [stop NaN*ones(m,1)]; elseif (n~=3), error([upper(mfilename) ' requires 2- or 3-element Stop points.']); end; end; if ~isempty(crossdir), [m,n] = size(crossdir); if (n<3), crossdir = [crossdir NaN*ones(m,3-n)]; elseif (n~=3), if (all(imag(crossdir(:))==0)), error([upper(mfilename) ' requires 2- or 3-element CrossDir vectors.']); else, error([upper(mfilename) ' requires 2- or 3-element NormalDir vectors.']); end; end; end; % fill empty arguments if isempty(start ), start = [Inf Inf Inf]; end; if isempty(stop ), stop = [Inf Inf Inf]; end; if isempty(len ), len = Inf; end; if isempty(baseangle ), baseangle = Inf; end; if isempty(tipangle ), tipangle = Inf; end; if isempty(wid ), wid = Inf; end; if isempty(page ), page = Inf; end; if isempty(crossdir ), crossdir = [Inf Inf Inf]; end; if isempty(ends ), ends = Inf; end; if isempty(ispatch ), ispatch = Inf; end; % expand single-column arguments o = ones(narrows,1); if (size(start ,1)==1), start = o * start ; end; if (size(stop ,1)==1), stop = o * stop ; end; if (length(len )==1), len = o * len ; end; if (length(baseangle )==1), baseangle = o * baseangle ; end; if (length(tipangle )==1), tipangle = o * tipangle ; end; if (length(wid )==1), wid = o * wid ; end; if (length(page )==1), page = o * page ; end; if (size(crossdir ,1)==1), crossdir = o * crossdir ; end; if (length(ends )==1), ends = o * ends ; end; if (length(ispatch )==1), ispatch = o * ispatch ; end; ax = o * gca; % if we've got handles, get the defaults from the handles if ~isempty(oldh), for k=1:narrows, oh = oldh(k); ud = get(oh,'UserData'); ax(k) = get(oh,'Parent'); ohtype = get(oh,'Type'); if strcmp(get(oh,'Tag'),ArrowTag), % if it's an arrow already if isinf(ispatch(k)), ispatch(k)=strcmp(ohtype,'patch'); end; % arrow UserData format: [start' stop' len base tip wid page crossdir' ends] start0 = ud(1:3); stop0 = ud(4:6); if (isinf(len(k))), len(k) = ud( 7); end; if (isinf(baseangle(k))), baseangle(k) = ud( 8); end; if (isinf(tipangle(k))), tipangle(k) = ud( 9); end; if (isinf(wid(k))), wid(k) = ud(10); end; if (isinf(page(k))), page(k) = ud(11); end; if (isinf(crossdir(k,1))), crossdir(k,1) = ud(12); end; if (isinf(crossdir(k,2))), crossdir(k,2) = ud(13); end; if (isinf(crossdir(k,3))), crossdir(k,3) = ud(14); end; if (isinf(ends(k))), ends(k) = ud(15); end; elseif strcmp(ohtype,'line')|strcmp(ohtype,'patch'), % it's a non-arrow line or patch convLineToPatch = 1; %set to make arrow patches when converting from lines. if isinf(ispatch(k)), ispatch(k)=convLineToPatch|strcmp(ohtype,'patch'); end; x=get(oh,'XData'); x=x(~isnan(x(:))); if isempty(x), x=NaN; end; y=get(oh,'YData'); y=y(~isnan(y(:))); if isempty(y), y=NaN; end; z=get(oh,'ZData'); z=z(~isnan(z(:))); if isempty(z), z=NaN; end; start0 = [x(1) y(1) z(1) ]; stop0 = [x(end) y(end) z(end)]; else, error([upper(mfilename) ' cannot convert ' ohtype ' objects.']); end; ii=find(isinf(start(k,:))); if ~isempty(ii), start(k,ii)=start0(ii); end; ii=find(isinf(stop( k,:))); if ~isempty(ii), stop( k,ii)=stop0( ii); end; end; end; % convert Inf's to NaN's start( isinf(start )) = NaN; stop( isinf(stop )) = NaN; len( isinf(len )) = NaN; baseangle( isinf(baseangle)) = NaN; tipangle( isinf(tipangle )) = NaN; wid( isinf(wid )) = NaN; page( isinf(page )) = NaN; crossdir( isinf(crossdir )) = NaN; ends( isinf(ends )) = NaN; ispatch( isinf(ispatch )) = NaN; % set up the UserData data (here so not corrupted by log10's and such) ud = [start stop len baseangle tipangle wid page crossdir ends]; % Set Page defaults page = ~isnan(page) & trueornan(page); % Get axes limits, range, min; correct for aspect ratio and log scale axm = zeros(3,narrows); axr = zeros(3,narrows); axrev = zeros(3,narrows); ap = zeros(2,narrows); xyzlog = zeros(3,narrows); limmin = zeros(2,narrows); limrange = zeros(2,narrows); oldaxlims = zeros(narrows,7); oneax = all(ax==ax(1)); if (oneax), T = zeros(4,4); invT = zeros(4,4); else, T = zeros(16,narrows); invT = zeros(16,narrows); end; axnotdone = logical(ones(size(ax))); while (any(axnotdone)), ii = min(find(axnotdone)); curax = ax(ii); curpage = page(ii); % get axes limits and aspect ratio axl = [get(curax,'XLim'); get(curax,'YLim'); get(curax,'ZLim')]; oldaxlims(min(find(oldaxlims(:,1)==0)),:) = [curax reshape(axl',1,6)]; % get axes size in pixels (points) u = get(curax,'Units'); axposoldunits = get(curax,'Position'); really_curpage = curpage & strcmp(u,'normalized'); if (really_curpage), curfig = get(curax,'Parent'); pu = get(curfig,'PaperUnits'); set(curfig,'PaperUnits','points'); pp = get(curfig,'PaperPosition'); set(curfig,'PaperUnits',pu); set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); set(curax,'Units','normalized'); curap = pp.*get(curax,'Position'); else, set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); curap = curapscreen; end; set(curax,'Units',u); set(curax,'Position',axposoldunits); % handle non-stretched axes position str_stretch = { 'DataAspectRatioMode' ; ... 'PlotBoxAspectRatioMode' ; ... 'CameraViewAngleMode' }; str_camera = { 'CameraPositionMode' ; ... 'CameraTargetMode' ; ... 'CameraViewAngleMode' ; ... 'CameraUpVectorMode' }; notstretched = strcmp(get(curax,str_stretch),'manual'); manualcamera = strcmp(get(curax,str_camera),'manual'); if ~arrow_WarpToFill(notstretched,manualcamera,curax), % give a warning that this has not been thoroughly tested if 0 & ARROW_STRETCH_WARN, ARROW_STRETCH_WARN = 0; strs = {str_stretch{1:2},str_camera{:}}; strs = [char(ones(length(strs),1)*sprintf('\n ')) char(strs)]'; warning([upper(mfilename) ' may not yet work quite right ' ... 'if any of the following are ''manual'':' strs(:).']); end; % find the true pixel size of the actual axes texttmp = text(axl(1,[1 2 2 1 1 2 2 1]), ... axl(2,[1 1 2 2 1 1 2 2]), ... axl(3,[1 1 1 1 2 2 2 2]),''); set(texttmp,'Units','points'); textpos = get(texttmp,'Position'); delete(texttmp); textpos = cat(1,textpos{:}); textpos = max(textpos(:,1:2)) - min(textpos(:,1:2)); % adjust the axes position if (really_curpage), % adjust to printed size textpos = textpos * min(curap(3:4)./textpos); curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos]; else, % adjust for pixel roundoff textpos = textpos * min(curapscreen(3:4)./textpos); curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos]; end; end; if ARROW_PERSP_WARN & ~strcmp(get(curax,'Projection'),'orthographic'), ARROW_PERSP_WARN = 0; warning([upper(mfilename) ' does not yet work right for 3-D perspective projection.']); end; % adjust limits for log scale on axes curxyzlog = [strcmp(get(curax,'XScale'),'log'); ... strcmp(get(curax,'YScale'),'log'); ... strcmp(get(curax,'ZScale'),'log')]; if (any(curxyzlog)), ii = find([curxyzlog;curxyzlog]); if (any(axl(ii)<=0)), error([upper(mfilename) ' does not support non-positive limits on log-scaled axes.']); else, axl(ii) = log10(axl(ii)); end; end; % correct for 'reverse' direction on axes; curreverse = [strcmp(get(curax,'XDir'),'reverse'); ... strcmp(get(curax,'YDir'),'reverse'); ... strcmp(get(curax,'ZDir'),'reverse')]; ii = find(curreverse); if ~isempty(ii), axl(ii,[1 2])=-axl(ii,[2 1]); end; % compute the range of 2-D values curT = get(curax,'Xform'); lim = curT*[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1;0 0 0 0 1 1 1 1;1 1 1 1 1 1 1 1]; lim = lim(1:2,:)./([1;1]*lim(4,:)); curlimmin = min(lim')'; curlimrange = max(lim')' - curlimmin; curinvT = inv(curT); if (~oneax), curT = curT.'; curinvT = curinvT.'; curT = curT(:); curinvT = curinvT(:); end; % check which arrows to which cur corresponds ii = find((ax==curax)&(page==curpage)); oo = ones(1,length(ii)); axr(:,ii) = diff(axl')' * oo; axm(:,ii) = axl(:,1) * oo; axrev(:,ii) = curreverse * oo; ap(:,ii) = curap(3:4)' * oo; xyzlog(:,ii) = curxyzlog * oo; limmin(:,ii) = curlimmin * oo; limrange(:,ii) = curlimrange * oo; if (oneax), T = curT; invT = curinvT; else, T(:,ii) = curT * oo; invT(:,ii) = curinvT * oo; end; axnotdone(ii) = zeros(1,length(ii)); end; oldaxlims(oldaxlims(:,1)==0,:)=[]; % correct for log scales curxyzlog = xyzlog.'; ii = find(curxyzlog(:)); if ~isempty(ii), start( ii) = real(log10(start( ii))); stop( ii) = real(log10(stop( ii))); if (all(imag(crossdir)==0)), % pulled (ii) subscript on crossdir, 12/5/96 eaj crossdir(ii) = real(log10(crossdir(ii))); end; end; % correct for reverse directions ii = find(axrev.'); if ~isempty(ii), start( ii) = -start( ii); stop( ii) = -stop( ii); crossdir(ii) = -crossdir(ii); end; % transpose start/stop values start = start.'; stop = stop.'; % take care of defaults, page was done above ii=find(isnan(start(:) )); if ~isempty(ii), start(ii) = axm(ii)+axr(ii)/2; end; ii=find(isnan(stop(:) )); if ~isempty(ii), stop(ii) = axm(ii)+axr(ii)/2; end; ii=find(isnan(crossdir(:) )); if ~isempty(ii), crossdir(ii) = zeros(length(ii),1); end; ii=find(isnan(len )); if ~isempty(ii), len(ii) = ones(length(ii),1)*deflen; end; ii=find(isnan(baseangle )); if ~isempty(ii), baseangle(ii) = ones(length(ii),1)*defbaseangle; end; ii=find(isnan(tipangle )); if ~isempty(ii), tipangle(ii) = ones(length(ii),1)*deftipangle; end; ii=find(isnan(wid )); if ~isempty(ii), wid(ii) = ones(length(ii),1)*defwid; end; ii=find(isnan(ends )); if ~isempty(ii), ends(ii) = ones(length(ii),1)*defends; end; % transpose rest of values len = len.'; baseangle = baseangle.'; tipangle = tipangle.'; wid = wid.'; page = page.'; crossdir = crossdir.'; ends = ends.'; ax = ax.'; % given x, a 3xN matrix of points in 3-space; % want to convert to X, the corresponding 4xN 2-space matrix % % tmp1=[(x-axm)./axr; ones(1,size(x,1))]; % if (oneax), X=T*tmp1; % else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; % tmp2=zeros(4,4*N); tmp2(:)=tmp1(:); % X=zeros(4,N); X(:)=sum(tmp2)'; end; % X = X ./ (ones(4,1)*X(4,:)); % for all points with start==stop, start=stop-(verysmallvalue)*(up-direction); ii = find(all(start==stop)); if ~isempty(ii), % find an arrowdir vertical on screen and perpendicular to viewer % transform to 2-D tmp1 = [(stop(:,ii)-axm(:,ii))./axr(:,ii);ones(1,length(ii))]; if (oneax), twoD=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); twoD=zeros(4,length(ii)); twoD(:)=sum(tmp2)'; end; twoD=twoD./(ones(4,1)*twoD(4,:)); % move the start point down just slightly tmp1 = twoD + [0;-1/1000;0;0]*(limrange(2,ii)./ap(2,ii)); % transform back to 3-D if (oneax), threeD=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); threeD=zeros(4,length(ii)); threeD(:)=sum(tmp2)'; end; start(:,ii) = (threeD(1:3,:)./(ones(3,1)*threeD(4,:))).*axr(:,ii)+axm(:,ii); end; % compute along-arrow points % transform Start points tmp1=[(start-axm)./axr;ones(1,narrows)]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); X0=zeros(4,narrows); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % transform Stop points tmp1=[(stop-axm)./axr;ones(1,narrows)]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); Xf=zeros(4,narrows); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute pixel distance between points D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*(ap./limrange)).^2)); D = D + (D==0); %eaj new 2/24/98 % compute and modify along-arrow distances len1 = len; len2 = len - (len.*tan(tipangle/180*pi)-wid/2).*tan((90-baseangle)/180*pi); slen0 = zeros(1,narrows); slen1 = len1 .* ((ends==2)|(ends==3)); slen2 = len2 .* ((ends==2)|(ends==3)); len0 = zeros(1,narrows); len1 = len1 .* ((ends==1)|(ends==3)); len2 = len2 .* ((ends==1)|(ends==3)); % for no start arrowhead ii=find((ends==1)&(D<len2)); if ~isempty(ii), slen0(ii) = D(ii)-len2(ii); end; % for no end arrowhead ii=find((ends==2)&(D<slen2)); if ~isempty(ii), len0(ii) = D(ii)-slen2(ii); end; len1 = len1 + len0; len2 = len2 + len0; slen1 = slen1 + slen0; slen2 = slen2 + slen0; % note: the division by D below will probably not be accurate if both % of the following are true: % 1. the ratio of the line length to the arrowhead % length is large % 2. the view is highly perspective. % compute stoppoints tmp1=X0.*(ones(4,1)*(len0./D))+Xf.*(ones(4,1)*(1-len0./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; stoppoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute tippoints tmp1=X0.*(ones(4,1)*(len1./D))+Xf.*(ones(4,1)*(1-len1./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; tippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute basepoints tmp1=X0.*(ones(4,1)*(len2./D))+Xf.*(ones(4,1)*(1-len2./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; basepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute startpoints tmp1=X0.*(ones(4,1)*(1-slen0./D))+Xf.*(ones(4,1)*(slen0./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; startpoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute stippoints tmp1=X0.*(ones(4,1)*(1-slen1./D))+Xf.*(ones(4,1)*(slen1./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; stippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute sbasepoints tmp1=X0.*(ones(4,1)*(1-slen2./D))+Xf.*(ones(4,1)*(slen2./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; sbasepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute cross-arrow directions for arrows with NormalDir specified if (any(imag(crossdir(:))~=0)), ii = find(any(imag(crossdir)~=0)); crossdir(:,ii) = cross((stop(:,ii)-start(:,ii))./axr(:,ii), ... imag(crossdir(:,ii))).*axr(:,ii); end; % compute cross-arrow directions basecross = crossdir + basepoint; tipcross = crossdir + tippoint; sbasecross = crossdir + sbasepoint; stipcross = crossdir + stippoint; ii = find(all(crossdir==0)|any(isnan(crossdir))); if ~isempty(ii), numii = length(ii); % transform start points tmp1 = [basepoint(:,ii) tippoint(:,ii) sbasepoint(:,ii) stippoint(:,ii)]; tmp1 = (tmp1-axm(:,[ii ii ii ii])) ./ axr(:,[ii ii ii ii]); tmp1 = [tmp1; ones(1,4*numii)]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); X0=zeros(4,4*numii); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % transform stop points tmp1 = [(2*stop(:,ii)-start(:,ii)-axm(:,ii))./axr(:,ii);ones(1,numii)]; tmp1 = [tmp1 tmp1 tmp1 tmp1]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xf=zeros(4,4*numii); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute perpendicular directions pixfact = ((limrange(1,ii)./limrange(2,ii)).*(ap(2,ii)./ap(1,ii))).^2; pixfact = [pixfact pixfact pixfact pixfact]; pixfact = [pixfact;1./pixfact]; [dummyval,jj] = max(abs(Xf(1:2,:)-X0(1:2,:))); jj1 = ((1:4)'*ones(1,length(jj))==ones(4,1)*jj); jj2 = ((1:4)'*ones(1,length(jj))==ones(4,1)*(3-jj)); jj3 = jj1(1:2,:); Xf(jj1)=Xf(jj1)+(Xf(jj1)-X0(jj1)==0); %eaj new 2/24/98 Xp = X0; Xp(jj2) = X0(jj2) + ones(sum(jj2(:)),1); Xp(jj1) = X0(jj1) - (Xf(jj2)-X0(jj2))./(Xf(jj1)-X0(jj1)) .* pixfact(jj3); % inverse transform the cross points if (oneax), Xp=invT*Xp; else, tmp1=[Xp;Xp;Xp;Xp]; tmp1=invT(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xp=zeros(4,4*numii); Xp(:)=sum(tmp2)'; end; Xp=(Xp(1:3,:)./(ones(3,1)*Xp(4,:))).*axr(:,[ii ii ii ii])+axm(:,[ii ii ii ii]); basecross(:,ii) = Xp(:,0*numii+(1:numii)); tipcross(:,ii) = Xp(:,1*numii+(1:numii)); sbasecross(:,ii) = Xp(:,2*numii+(1:numii)); stipcross(:,ii) = Xp(:,3*numii+(1:numii)); end; % compute all points % compute start points axm11 = [axm axm axm axm axm axm axm axm axm axm axm]; axr11 = [axr axr axr axr axr axr axr axr axr axr axr]; st = [stoppoint tippoint basepoint sbasepoint stippoint startpoint stippoint sbasepoint basepoint tippoint stoppoint]; tmp1 = (st - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); X0=zeros(4,11*narrows); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % compute stop points tmp1 = ([start tipcross basecross sbasecross stipcross stop stipcross sbasecross basecross tipcross start] ... - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); Xf=zeros(4,11*narrows); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute lengths len0 = len.*((ends==1)|(ends==3)).*tan(tipangle/180*pi); slen0 = len.*((ends==2)|(ends==3)).*tan(tipangle/180*pi); le = [zeros(1,narrows) len0 wid/2 wid/2 slen0 zeros(1,narrows) -slen0 -wid/2 -wid/2 -len0 zeros(1,narrows)]; aprange = ap./limrange; aprange = [aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange]; D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*aprange).^2)); Dii=find(D==0); if ~isempty(Dii), D=D+(D==0); le(Dii)=zeros(1,length(Dii)); end; %should fix DivideByZero warnings tmp1 = X0.*(ones(4,1)*(1-le./D)) + Xf.*(ones(4,1)*(le./D)); % inverse transform if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[invT invT invT invT invT invT invT invT invT invT invT].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,11*narrows); tmp3(:)=sum(tmp2)'; end; pts = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)) .* axr11 + axm11; % correct for ones where the crossdir was specified ii = find(~(all(crossdir==0)|any(isnan(crossdir)))); if ~isempty(ii), D1 = [pts(:,1*narrows+ii)-pts(:,9*narrows+ii) ... pts(:,2*narrows+ii)-pts(:,8*narrows+ii) ... pts(:,3*narrows+ii)-pts(:,7*narrows+ii) ... pts(:,4*narrows+ii)-pts(:,6*narrows+ii) ... pts(:,6*narrows+ii)-pts(:,4*narrows+ii) ... pts(:,7*narrows+ii)-pts(:,3*narrows+ii) ... pts(:,8*narrows+ii)-pts(:,2*narrows+ii) ... pts(:,9*narrows+ii)-pts(:,1*narrows+ii)]/2; ii = ii'*ones(1,8) + ones(length(ii),1)*[1:4 6:9]*narrows; ii = ii(:)'; pts(:,ii) = st(:,ii) + D1; end; % readjust for reverse directions iicols=(1:narrows)'; iicols=iicols(:,ones(1,11)); iicols=iicols(:).'; tmp1=axrev(:,iicols); ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=-pts(ii); end; % readjust for log scale on axes tmp1=xyzlog(:,iicols); ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=10.^pts(ii); end; % compute the x,y,z coordinates of the patches; ii = narrows*(0:10)'*ones(1,narrows) + ones(11,1)*(1:narrows); ii = ii(:)'; x = zeros(11,narrows); y = zeros(11,narrows); z = zeros(11,narrows); x(:) = pts(1,ii)'; y(:) = pts(2,ii)'; z(:) = pts(3,ii)'; % do the output if (nargout<=1), % % create or modify the patches newpatch = trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'patch')); newline = ~trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'line')); if isempty(oldh), H=zeros(narrows,1); else, H=oldh; end; % % make or modify the arrows for k=1:narrows, if all(isnan(ud(k,[3 6])))&arrow_is2DXY(ax(k)), zz=[]; else, zz=z(:,k); end; xx=x(:,k); yy=y(:,k); if (0), % this fix didn't work, so let's not use it -- 8/26/03 % try to work around a MATLAB 6.x OpenGL bug -- 7/28/02 mask=any([ones(1,2+size(zz,2));diff([xx yy zz],[],1)],2); xx=xx(mask); yy=yy(mask); if ~isempty(zz), zz=zz(mask); end; end; % plot the patch or line xyz = {'XData',xx,'YData',yy,'ZData',zz,'Tag',ArrowTag}; if newpatch(k)|newline(k), if newpatch(k), H(k) = patch(xyz{:}); else, H(k) = line(xyz{:}); end; if ~isempty(oldh), arrow_copyprops(oldh(k),H(k)); end; else, if ispatch(k), xyz={xyz{:},'CData',[]}; end; set(H(k),xyz{:}); end; end; if ~isempty(oldh), delete(oldh(oldh~=H)); end; % % additional properties set(H,'Clipping','off'); set(H,{'UserData'},num2cell(ud,2)); if (length(extraprops)>0), set(H,extraprops{:}); end; % handle choosing arrow Start and/or Stop locations if unspecified [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims); if ~isempty(errstr), error([upper(mfilename) ' got ' errstr]); end; % set the output if (nargout>0), h=H; end; % make sure the axis limits did not change if isempty(oldaxlims), ARROW_AXLIMITS = []; else, lims = get(oldaxlims(:,1),{'XLim','YLim','ZLim'})'; lims = reshape(cat(2,lims{:}),6,size(lims,2)); mask = arrow_is2DXY(oldaxlims(:,1)); oldaxlims(mask,6:7) = lims(5:6,mask)'; ARROW_AXLIMITS = oldaxlims(find(any(oldaxlims(:,2:7)'~=lims)),:); if ~isempty(ARROW_AXLIMITS), warning(arrow_warnlimits(ARROW_AXLIMITS,narrows)); end; end; else, % don't create the patch, just return the data h=x; yy=y; zz=z; end; function out = arrow_defcheck(in,def,prop) % check if we got 'default' values out = in; if ~isstr(in), return; end; if size(in,1)==1 & strncmp(lower(in),'def',3), out = def; elseif ~isempty(prop), error([upper(mfilename) ' does not recognize ''' in(:)' ''' as a valid ''' prop ''' string.']); end; function [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims) % handle choosing arrow Start and/or Stop locations if necessary errstr = ''; if isempty(H)|isempty(ud)|isempty(x), return; end; % determine which (if any) need Start and/or Stop needStart = all(isnan(ud(:,1:3)'))'; needStop = all(isnan(ud(:,4:6)'))'; mask = any(needStart|needStop); if ~any(mask), return; end; ud(~mask,:)=[]; ax(:,~mask)=[]; x(:,~mask)=[]; y(:,~mask)=[]; z(:,~mask)=[]; % make them invisible for the time being set(H,'Visible','off'); % save the current axes and limits modes; set to manual for the time being oldAx = gca; limModes=get(ax(:),{'XLimMode','YLimMode','ZLimMode'}); set(ax(:),{'XLimMode','YLimMode','ZLimMode'},{'manual','manual','manual'}); % loop over each arrow that requires attention jj = find(mask); for ii=1:length(jj), h = H(jj(ii)); axes(ax(ii)); % figure out correct call if needStart(ii), prop='Start'; else, prop='Stop'; end; [wasInterrupted,errstr] = arrow_click(needStart(ii)&needStop(ii),h,prop,ax(ii)); % handle errors and control-C if wasInterrupted, delete(H(jj(ii:end))); H(jj(ii:end))=[]; oldaxlims(jj(ii:end),:)=[]; break; end; end; % restore the axes and limit modes axes(oldAx); set(ax(:),{'XLimMode','YLimMode','ZLimMode'},limModes); function [wasInterrupted,errstr] = arrow_click(lockStart,H,prop,ax) % handle the clicks for one arrow fig = get(ax,'Parent'); % save some things oldFigProps = {'Pointer','WindowButtonMotionFcn','WindowButtonUpFcn'}; oldFigValue = get(fig,oldFigProps); oldArrowProps = {'EraseMode'}; oldArrowValue = get(H,oldArrowProps); set(H,'EraseMode','background'); %because 'xor' makes shaft invisible unless Width>1 global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z ARROW_CLICK_H=H; ARROW_CLICK_PROP=prop; ARROW_CLICK_AX=ax; ARROW_CLICK_USE_Z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); set(fig,'Pointer','crosshair'); % set up the WindowButtonMotion so we can see the arrow while moving around set(fig,'WindowButtonUpFcn','set(gcf,''WindowButtonUpFcn'','''')', ... 'WindowButtonMotionFcn',''); if ~lockStart, set(H,'Visible','on'); set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']); end; % wait for the button to be pressed [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig); % if we wanted to click-drag, set the Start point if lockStart & ~wasInterrupted, pt = arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z); feval(mfilename,H,'Start',pt,'Stop',pt); set(H,'Visible','on'); ARROW_CLICK_PROP='Stop'; set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']); % wait for the mouse button to be released try waitfor(fig,'WindowButtonUpFcn',''); catch errstr = lasterr; wasInterrupted = 1; end; end; if ~wasInterrupted, feval(mfilename,'callback','motion'); end; % restore some things set(gcf,oldFigProps,oldFigValue); set(H,oldArrowProps,oldArrowValue); function arrow_callback(varargin) % handle redrawing callbacks if nargin==0, return; end; str = varargin{1}; if ~isstr(str), error([upper(mfilename) ' got an invalid Callback command.']); end; s = lower(str); if strcmp(s,'motion'), % motion callback global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z feval(mfilename,ARROW_CLICK_H,ARROW_CLICK_PROP,arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z)); drawnow; else, error([upper(mfilename) ' does not recognize ''' str(:).' ''' as a valid Callback option.']); end; function out = arrow_point(ax,use_z) % return the point on the given axes if nargin==0, ax=gca; end; if nargin<2, use_z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); end; out = get(ax,'CurrentPoint'); out = out(1,:); if ~use_z, out=out(1:2); end; function [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig) % wait for button down ignoring object ButtonDownFcn's if nargin==0, fig=gcf; end; errstr = ''; % save ButtonDownFcn values objs = findobj(fig); buttonDownFcns = get(objs,'ButtonDownFcn'); mask=~strcmp(buttonDownFcns,''); objs=objs(mask); buttonDownFcns=buttonDownFcns(mask); set(objs,'ButtonDownFcn',''); % save other figure values figProps = {'KeyPressFcn','WindowButtonDownFcn'}; figValue = get(fig,figProps); % do the real work set(fig,'KeyPressFcn','set(gcf,''KeyPressFcn'','''',''WindowButtonDownFcn'','''');', ... 'WindowButtonDownFcn','set(gcf,''WindowButtonDownFcn'','''')'); lasterr(''); try waitfor(fig,'WindowButtonDownFcn',''); wasInterrupted = 0; catch wasInterrupted = 1; end wasKeyPress = ~wasInterrupted & strcmp(get(fig,'KeyPressFcn'),''); if wasInterrupted, errstr=lasterr; end; % restore ButtonDownFcn and other figure values set(objs,'ButtonDownFcn',buttonDownFcns); set(fig,figProps,figValue); function [out,is2D] = arrow_is2DXY(ax) % check if axes are 2-D X-Y plots % may not work for modified camera angles, etc. out = logical(zeros(size(ax))); % 2-D X-Y plots is2D = out; % any 2-D plots views = get(ax(:),{'View'}); views = cat(1,views{:}); out(:) = abs(views(:,2))==90; is2D(:) = out(:) | all(rem(views',90)==0)'; function out = arrow_planarkids(ax) % check if axes descendents all have empty ZData (lines,patches,surfaces) out = logical(ones(size(ax))); allkids = get(ax(:),{'Children'}); for k=1:length(allkids), kids = get([findobj(allkids{k},'flat','Type','line') findobj(allkids{k},'flat','Type','patch') findobj(allkids{k},'flat','Type','surface')],{'ZData'}); for j=1:length(kids), if ~isempty(kids{j}), out(k)=logical(0); break; end; end; end; function arrow_fixlimits(axlimits) % reset the axis limits as necessary if isempty(axlimits), disp([upper(mfilename) ' does not remember any axis limits to reset.']); end; for k=1:size(axlimits,1), if any(get(axlimits(k,1),'XLim')~=axlimits(k,2:3)), set(axlimits(k,1),'XLim',axlimits(k,2:3)); end; if any(get(axlimits(k,1),'YLim')~=axlimits(k,4:5)), set(axlimits(k,1),'YLim',axlimits(k,4:5)); end; if any(get(axlimits(k,1),'ZLim')~=axlimits(k,6:7)), set(axlimits(k,1),'ZLim',axlimits(k,6:7)); end; end; function out = arrow_WarpToFill(notstretched,manualcamera,curax) % check if we are in "WarpToFill" mode. out = strcmp(get(curax,'WarpToFill'),'on'); % 'WarpToFill' is undocumented, so may need to replace this by % out = ~( any(notstretched) & any(manualcamera) ); function out = arrow_warnlimits(axlimits,narrows) % create a warning message if we've changed the axis limits msg = ''; switch (size(axlimits,1)) case 1, msg=''; case 2, msg='on two axes '; otherwise, msg='on several axes '; end; msg = [upper(mfilename) ' changed the axis limits ' msg ... 'when adding the arrow']; if (narrows>1), msg=[msg 's']; end; out = [msg '.' sprintf('\n') ' Call ' upper(mfilename) ... ' FIXLIMITS to reset them now.']; function arrow_copyprops(fm,to) % copy line properties to patches props = {'EraseMode','LineStyle','LineWidth','Marker','MarkerSize',... 'MarkerEdgeColor','MarkerFaceColor','ButtonDownFcn', ... 'Clipping','DeleteFcn','BusyAction','HandleVisibility', ... 'Selected','SelectionHighlight','Visible'}; lineprops = {'Color', props{:}}; patchprops = {'EdgeColor',props{:}}; patch2props = {'FaceColor',patchprops{:}}; fmpatch = strcmp(get(fm,'Type'),'patch'); topatch = strcmp(get(to,'Type'),'patch'); set(to( fmpatch& topatch),patch2props,get(fm( fmpatch& topatch),patch2props)); %p->p set(to(~fmpatch&~topatch),lineprops, get(fm(~fmpatch&~topatch),lineprops )); %l->l set(to( fmpatch&~topatch),lineprops, get(fm( fmpatch&~topatch),patchprops )); %p->l set(to(~fmpatch& topatch),patchprops, get(fm(~fmpatch& topatch),lineprops) ,'FaceColor','none'); %l->p function arrow_props % display further help info about ARROW properties c = sprintf('\n'); disp([c ... 'ARROW Properties: Default values are given in [square brackets], and other' c ... ' acceptable equivalent property names are in (parenthesis).' c c ... ' Start The starting points. For N arrows, B' c ... ' this should be a Nx2 or Nx3 matrix. /|\ ^' c ... ' Stop The end points. For N arrows, this /|||\ |' c ... ' should be a Nx2 or Nx3 matrix. //|||\\ L|' c ... ' Length Length of the arrowhead (in pixels on ///|||\\\ e|' c ... ' screen, points on a page). [16] (Len) ////|||\\\\ n|' c ... ' BaseAngle Angle (degrees) of the base angle /////|D|\\\\\ g|' c ... ' ADE. For a simple stick arrow, use //// ||| \\\\ t|' c ... ' BaseAngle=TipAngle. [90] (Base) /// ||| \\\ h|' c ... ' TipAngle Angle (degrees) of tip angle ABC. //<----->|| \\ |' c ... ' [16] (Tip) / base ||| \ V' c ... ' Width Width of the base in pixels. Not E angle ||<-------->C' c ... ' the ''LineWidth'' prop. [0] (Wid) |||tipangle' c ... ' Page If provided, non-empty, and not NaN, |||' c ... ' this causes ARROW to use hardcopy |||' c ... ' rather than onscreen proportions. A' c ... ' This is important if screen aspect --> <-- width' c ... ' ratio and hardcopy aspect ratio are ----CrossDir---->' c ... ' vastly different. []' c... ' CrossDir A vector giving the direction towards which the fletches' c ... ' on the arrow should go. [computed such that it is perpen-' c ... ' dicular to both the arrow direction and the view direction' c ... ' (i.e., as if it was pasted on a normal 2-D graph)] (Note' c ... ' that CrossDir is a vector. Also note that if an axis is' c ... ' plotted on a log scale, then the corresponding component' c ... ' of CrossDir must also be set appropriately, i.e., to 1 for' c ... ' no change in that direction, >1 for a positive change, >0' c ... ' and <1 for negative change.)' c ... ' NormalDir A vector normal to the fletch direction (CrossDir is then' c ... ' computed by the vector cross product [Line]x[NormalDir]). []' c ... ' (Note that NormalDir is a vector. Unlike CrossDir,' c ... ' NormalDir is used as is regardless of log-scaled axes.)' c ... ' Ends Set which end has an arrowhead. Valid values are ''none'',' c ... ' ''stop'', ''start'', and ''both''. [''stop''] (End)' c... ' ObjectHandles Vector of handles to previously-created arrows to be' c ... ' updated or line objects to be converted to arrows.' c ... ' [] (Object,Handle)' c ]); function out = arrow_demo % demo % create the data [x,y,z] = peaks; [ddd,out.iii]=max(z(:)); out.axlim = [min(x(:)) max(x(:)) min(y(:)) max(y(:)) min(z(:)) max(z(:))]; % modify it by inserting some NaN's [m,n] = size(z); m = floor(m/2); n = floor(n/2); z(1:m,1:n) = NaN*ones(m,n); % graph it clf('reset'); out.hs=surf(x,y,z); out.x=x; out.y=y; out.z=z; xlabel('x'); ylabel('y'); function h = arrow_demo3(in) % set the view axlim = in.axlim; axis(axlim); zlabel('z'); %set(in.hs,'FaceColor','interp'); view(3); % view(viewmtx(-37.5,30,20)); title(['Demo of the capabilities of the ARROW function in 3-D']); % Normal blue arrow h1 = feval(mfilename,[axlim(1) axlim(4) 4],[-.8 1.2 4], ... 'EdgeColor','b','FaceColor','b'); % Normal white arrow, clipped by the surface h2 = feval(mfilename,axlim([1 4 6]),[0 2 4]); t=text(-2.4,2.7,7.7,'arrow clipped by surf'); % Baseangle<90 h3 = feval(mfilename,[3 .125 3.5],[1.375 0.125 3.5],30,50); t2=text(3.1,.125,3.5,'local maximum'); % Baseangle<90, fill and edge colors different h4 = feval(mfilename,axlim(1:2:5)*.5,[0 0 0],36,60,25, ... 'EdgeColor','b','FaceColor','c'); t3=text(axlim(1)*.5,axlim(3)*.5,axlim(5)*.5-.75,'origin'); set(t3,'HorizontalAlignment','center'); % Baseangle>90, black fill h5 = feval(mfilename,[-2.9 2.9 3],[-1.3 .4 3.2],30,120,[],6, ... 'EdgeColor','r','FaceColor','k','LineWidth',2); % Baseangle>90, no fill h6 = feval(mfilename,[-2.9 2.9 1.3],[-1.3 .4 1.5],30,120,[],6, ... 'EdgeColor','r','FaceColor','none','LineWidth',2); % Stick arrow h7 = feval(mfilename,[-1.6 -1.65 -6.5],[0 -1.65 -6.5],[],16,16); t4=text(-1.5,-1.65,-7.25,'global mininum'); set(t4,'HorizontalAlignment','center'); % Normal, black fill h8 = feval(mfilename,[-1.4 0 -7.2],[-1.4 0 -3],'FaceColor','k'); t5=text(-1.5,0,-7.75,'local minimum'); set(t5,'HorizontalAlignment','center'); % Gray fill, crossdir specified, 'LineStyle' -- h9 = feval(mfilename,[-3 2.2 -6],[-3 2.2 -.05],36,[],27,6,[],[0 -1 0], ... 'EdgeColor','k','FaceColor',.75*[1 1 1],'LineStyle','--'); % a series of normal arrows, linearly spaced, crossdir specified h10y=(0:4)'/3; h10 = feval(mfilename,[-3*ones(size(h10y)) h10y -6.5*ones(size(h10y))], ... [-3*ones(size(h10y)) h10y -.05*ones(size(h10y))], ... 12,[],[],[],[],[0 -1 0]); % a series of normal arrows, linearly spaced h11x=(1:.33:2.8)'; h11 = feval(mfilename,[h11x -3*ones(size(h11x)) 6.5*ones(size(h11x))], ... [h11x -3*ones(size(h11x)) -.05*ones(size(h11x))]); % series of magenta arrows, radially oriented, crossdir specified h12x=2; h12y=-3; h12z=axlim(5)/2; h12xr=1; h12zr=h12z; ir=.15;or=.81; h12t=(0:11)'/6*pi; h12 = feval(mfilename, ... [h12x+h12xr*cos(h12t)*ir h12y*ones(size(h12t)) ... h12z+h12zr*sin(h12t)*ir],[h12x+h12xr*cos(h12t)*or ... h12y*ones(size(h12t)) h12z+h12zr*sin(h12t)*or], ... 10,[],[],[],[], ... [-h12xr*sin(h12t) zeros(size(h12t)) h12zr*cos(h12t)],... 'FaceColor','none','EdgeColor','m'); % series of normal arrows, tangentially oriented, crossdir specified or13=.91; h13t=(0:.5:12)'/6*pi; locs = [h12x+h12xr*cos(h13t)*or13 h12y*ones(size(h13t)) h12z+h12zr*sin(h13t)*or13]; h13 = feval(mfilename,locs(1:end-1,:),locs(2:end,:),6); % arrow with no line ==> oriented downwards h14 = feval(mfilename,[3 3 .100001],[3 3 .1],30); t6=text(3,3,3.6,'no line'); set(t6,'HorizontalAlignment','center'); % arrow with arrowheads at both ends h15 = feval(mfilename,[-.5 -3 -3],[1 -3 -3],'Ends','both','FaceColor','g', ... 'Length',20,'Width',3,'CrossDir',[0 0 1],'TipAngle',25); h=[h1;h2;h3;h4;h5;h6;h7;h8;h9;h10;h11;h12;h13;h14;h15]; function h = arrow_demo2(in) axlim = in.axlim; dolog = 1; if (dolog), set(in.hs,'YData',10.^get(in.hs,'YData')); end; shading('interp'); view(2); title(['Demo of the capabilities of the ARROW function in 2-D']); hold on; [C,H]=contour(in.x,in.y,in.z,20,'-'); hold off; for k=H', set(k,'ZData',(axlim(6)+1)*ones(size(get(k,'XData'))),'Color','k'); if (dolog), set(k,'YData',10.^get(k,'YData')); end; end; if (dolog), axis([axlim(1:2) 10.^axlim(3:4)]); set(gca,'YScale','log'); else, axis(axlim(1:4)); end; % Normal blue arrow start = [axlim(1) axlim(4) axlim(6)+2]; stop = [in.x(in.iii) in.y(in.iii) axlim(6)+2]; if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end; h1 = feval(mfilename,start,stop,'EdgeColor','b','FaceColor','b'); % three arrows with varying fill, width, and baseangle start = [-3 -3 10; -3 -1.5 10; -1.5 -3 10]; stop = [-.03 -.03 10; -.03 -1.5 10; -1.5 -.03 10]; if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end; h2 = feval(mfilename,start,stop,24,[90;60;120],[],[0;0;4],'Ends',str2mat('both','stop','stop')); set(h2(2),'EdgeColor',[0 .35 0],'FaceColor',[0 .85 .85]); set(h2(3),'EdgeColor','r','FaceColor',[1 .5 1]); h=[h1;h2]; function out = trueornan(x) if isempty(x), out=x; else, out = isnan(x); out(~out) = x(~out); end;
github
cosmicBboy/bayesian-reasoning-machine-learning-master
demoBayesErrorAnalysis.m
.m
bayesian-reasoning-machine-learning-master/src/DemosExercises/demoBayesErrorAnalysis.m
1,860
utf_8
2cd17f883c53fbb75be770a1da1a00a3
function demoBayesErrorAnalysis %DEMOBAYESERRORANALYSIS demo of Bayesian error analysis N = 20; % number of datapoints Q = 3; % number of error types % make some errors for the two classifers : errtype={'IndepSameErrorGenerator','IndepDiffErrorGenerator','DepErrorGenerator'}; GenerateError=errtype{randgen(1:3)} switch GenerateError case 'IndepDiffErrorGenerator' % independent different error generator: ra = rand(Q,1); rb = rand(Q,1); rab = ra*rb'; relprobC = vec(rab); case 'IndepSameErrorGenerator'% independent same error generator: ra = rand(Q,1); rb = ra; rab = ra*rb'; relprobC = vec(rab); case 'DepErrorGenerator'% dependent error generator: relprobC = vec(rand(Q,Q)); end errors = randgen(relprobC,1,N); % sample the errors % form the count matrices and vectors: vec_errorAB=zeros(1,Q*Q); for i=1:N vec_errorAB(errors(i))= vec_errorAB(errors(i))+1; end C = vec2mat(vec_errorAB) % count matrix of errors ca = sum(C,1); cb = sum(C,2)'; % Simple Bayesian analysis of the error counts based on Dirichlet % prior and multinomial error distribution: u =ones(1,Q); % uniform prior distribution lb = logZ(u+ca)+logZ(u+cb) - logZ(u)- logZ(u+ca+cb); disp(['p(classifiers are indep and different)/p(classifiers are independent and same)=',num2str(exp(lb))]); U=ones(Q,Q); % uniform prior lb = logZ(u+ca)+logZ(u+cb)+logZ(vec(U))-2*logZ(u)-logZ(vec(U+C)); disp(['p(classifiers are indep and different)/p(classifiers are dependent)=',num2str(exp(lb))]) % test Hsame/Hdep lb = logZ(u+ca+cb)+logZ(vec(U))-logZ(u)-logZ(vec(U+C)); disp(['p(classifiers are indep and same)/p(classifiers are dependent)=',num2str(exp(lb))]); function v = vec(C) tmp=C'; v=tmp(:); function C=vec2mat(v) Q = sqrt(length(v)); C= reshape(v,Q,Q)'; function lz=logZ(u) lz = sum(gammaln(u))- gammaln(sum(u));
github
smilingmaria/speech2vec-master
generalized_MLPG_ver2.m
.m
speech2vec-master/fbank_matlab/generalized_MLPG_ver2.m
4,240
utf_8
adbbb93fe0898f8cf875a705feac00c3
% 2015.2.26 constructed by Hwang, Hsin-Te % 2016.1.26 modified by Wu, Ted % 1.This function performs Maximum likelihood parameter generation (MLPG) algorithm to % smooth ANN-mapping's output function [converted_seq_mlpg]=generalized_MLPG_ver2(Input_seq,Cov,dynamic_flag,featureDIM) converted_seq = zeros(featureDIM/(dynamic_flag+1),size(Input_seq,2)); parfor i=1:(featureDIM/(dynamic_flag+1)) Cov_new = zeros(3,3); Input_seq_new = zeros(3,size(Input_seq,2)); Input_seq_new(1,:) = Input_seq(i,:); Input_seq_new(2,:) = Input_seq(i+(featureDIM/(dynamic_flag+1)),:); Input_seq_new(3,:) = Input_seq(i+(featureDIM/(dynamic_flag+1))*2,:); Cov_new(1,1) = Cov(i,i); Cov_new(2,2) = Cov(i+(featureDIM/(dynamic_flag+1)),... i+(featureDIM/(dynamic_flag+1))); Cov_new(3,3) = Cov(i+(featureDIM/(dynamic_flag+1))*2,... i+(featureDIM/(dynamic_flag+1))*2); [converted_seq(i,:)] = generalized_MLPG_ver1(Input_seq_new,Cov_new,dynamic_flag); % mcc_dim by lenght, using dynamic features end converted_seq_mlpg=converted_seq; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [output_sequence]=generalized_MLPG_ver1(Input_seq,Cov,dynamic_flag) %% Input parameters: % Input_seq: Input sequence obtained by ANN-mapping, % e.g., 3D-by-T -> ( Input_seq = (static+delta+delta^2) by T ), where D = dimension of static/delta/delta^2, T is total % number of input frames. % Cov: A single Gaussian estimated covariance matrix, e.g., 3D by 3D % dynamic_flag: 1 -> using delta, 2-> using delta^2; %% Output parameter: % output_sequence: Generating smoothed output sequence %% 1. Intial values setup for MLPG algorithm sequence_length = size(Input_seq,2); front_term=0; back_term=0; if dynamic_flag ==1 static_dim=size(Input_seq,1)/2; w=[[0*eye(static_dim) 1*eye(static_dim) 0*eye(static_dim)];[-0.5*eye(static_dim) 0*eye(static_dim) 0.5*eye(static_dim)]]; % delta else % dynamic_flag == 2 static_dim=size(Input_seq,1)/3; w=[[0*eye(static_dim) 1*eye(static_dim) 0*eye(static_dim)];[-0.5*eye(static_dim) 0*eye(static_dim) 0.5*eye(static_dim)];[1*eye(static_dim) -2*eye(static_dim) 1*eye(static_dim)]]; %delta^2 end w=sparse(w); CCov_seq = zeros(size(Input_seq,1),size(Input_seq,1),sequence_length); % covariance sequence for i = 1:sequence_length CCov_seq(:,:,i) = Cov(:,:); end %% 2. MLPG algorithm for j=1:sequence_length if j==1 if dynamic_flag==1 W=[w(:,static_dim+1:end),zeros(2*static_dim,(sequence_length-2)*static_dim)]; % delta elseif dynamic_flag==2 W=[w(:,static_dim+1:end),zeros(3*static_dim,(sequence_length-2)*static_dim)]; % delta^2 else W=[w(:,static_dim+1:end),zeros(2*static_dim,(sequence_length-2)*static_dim)]; % delta end elseif j==sequence_length if dynamic_flag==1 W=[zeros(2*static_dim,(sequence_length-2)*static_dim),w(:,1:2*static_dim)]; % delta elseif dynamic_flag==2 W=[zeros(3*static_dim,(sequence_length-2)*static_dim),w(:,1:2*static_dim)]; % delta^2 else W=[zeros(2*static_dim,(sequence_length-2)*static_dim),w(:,1:2*static_dim)]; % delta end else if dynamic_flag==1 W=[zeros(2*static_dim,(j-2)*static_dim),w,zeros(2*static_dim,(sequence_length-3-j+2)*static_dim)]; % delta elseif dynamic_flag==2 W=[zeros(3*static_dim,(j-2)*static_dim),w,zeros(3*static_dim,(sequence_length-3-j+2)*static_dim)]; % delta^2 else W=[zeros(2*static_dim,(j-2)*static_dim),w,zeros(2*static_dim,(sequence_length-3-j+2)*static_dim)]; % delta end end E=Input_seq(:,j); D=CCov_seq(:,:,j); D=sparse(D); Q=W'*(D^-1); front_term=sparse(front_term)+Q*W; back_term=sparse(back_term)+Q*E; end est_t=front_term\back_term; output_sequence=full(reshape(est_t,static_dim,sequence_length));
github
smilingmaria/speech2vec-master
dynamic_feature_ver1.m
.m
speech2vec-master/fbank_matlab/dynamic_feature_ver1.m
1,358
utf_8
7610f02fbfe4fe6461f77397b724202e
% 2013.11.25 constructed by Hwang, Hsin-Te: % 2013.11.25 modified by Hwang, Hsin-Te % Computing static and dynamic features function output_sequence=dynamic_feature_ver1(static_feature_seq,dynamic_flag) % static_feature_seq: static feature sequence % dynamic_flag: 1=>delta, 2=> delta^2 % output_sequence: joint static and dynamic feature sequence output_sequence=[]; [mcc_dim seq_length]=size(static_feature_seq); if dynamic_flag==1 w=[[0*eye(mcc_dim) 1*eye(mcc_dim) 0*eye(mcc_dim)];[-0.5*eye(mcc_dim) 0*eye(mcc_dim) 0.5*eye(mcc_dim)]]; elseif dynamic_flag==2 w=[[0*eye(mcc_dim) 1*eye(mcc_dim) 0*eye(mcc_dim)];[-0.5*eye(mcc_dim) 0*eye(mcc_dim) 0.5*eye(mcc_dim)];[1*eye(mcc_dim) -2*eye(mcc_dim) 1*eye(mcc_dim)]]; else exit(1); end for i=1:seq_length if i==1 static=zeros(mcc_dim,3); static(:,2)=static_feature_seq(:,i); static(:,3)=static_feature_seq(:,i+1); elseif i==size(static_feature_seq,2) static=zeros(mcc_dim,3); static(:,1)=static_feature_seq(:,i-1); static(:,2)=static_feature_seq(:,i); else static=static_feature_seq(:,i-1:i+1); end len=size(static,2); y=reshape(static,mcc_dim*len,1); dynamic_feature_vector=w*y; output_sequence=[output_sequence,dynamic_feature_vector]; end
github
smilingmaria/speech2vec-master
fft2melmx.m
.m
speech2vec-master/fbank_matlab/fft2melmx.m
5,099
utf_8
bc5ec77cf66dbf11ed4f40f366c81a85
function [wts,binfrqs] = fft2melmx(nfft, sr, nfilts, width, minfrq, maxfrq, htkmel, constamp) % wts = fft2melmx(nfft, sr, nfilts, width, minfrq, maxfrq, htkmel, constamp) % Generate a matrix of weights to combine FFT bins into Mel % bins. nfft defines the source FFT size at sampling rate sr. % Optional nfilts specifies the number of output bands required % (else one per bark), and width is the constant width of each % band relative to standard Mel (default 1). % While wts has nfft columns, the second half are all zero. % Hence, Mel spectrum is fft2melmx(nfft,sr)*abs(fft(xincols,nfft)); % minfrq is the frequency (in Hz) of the lowest band edge; % default is 0, but 133.33 is a common standard (to skip LF). % maxfrq is frequency in Hz of upper edge; default sr/2. % You can exactly duplicate the mel matrix in Slaney's mfcc.m % as fft2melmx(512, 8000, 40, 1, 133.33, 6855.5, 0); % htkmel=1 means use HTK's version of the mel curve, not Slaney's. % constamp=1 means make integration windows peak at 1, not sum to 1. % 2004-09-05 [email protected] based on fft2barkmx if nargin < 2; sr = 8000; end if nargin < 3; nfilts = 40; end if nargin < 4; width = 1.0; end if nargin < 5; minfrq = 0; end % default bottom edge at 0 if nargin < 6; maxfrq = sr/2; end % default top edge at nyquist if nargin < 7; htkmel = 0; end if nargin < 8; constamp = 0; end wts = zeros(nfilts, nfft); % Center freqs of each FFT bin fftfrqs = [0:nfft-1]/nfft*sr; % 'Center freqs' of mel bands - uniformly spaced between limits minmel = hz2mel(minfrq, htkmel); maxmel = hz2mel(maxfrq, htkmel); binfrqs = mel2hz(minmel+[0:(nfilts+1)]/(nfilts+1)*(maxmel-minmel), htkmel); %%%%%Add new bandwidth % load BandWeight; % BandWidth=1./Aver.*1; % binfreqs=cumsum(BandWidth); % my_x=linspace(1,60,62); % binfreqs=spline(1:60,binfreqs,my_x); % binfrqs=binfreqs./max(binfreqs)*8000; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% binbin = round(binfrqs/sr*(nfft-1)); for i = 1:nfilts % fs = mel2hz(i + [-1 0 1], htkmel); fs = binfrqs(i+[0 1 2]); % scale by width fs = fs(2)+width*(fs - fs(2)); % lower and upper slopes for all bins loslope = (fftfrqs - fs(1))/(fs(2) - fs(1)); hislope = (fs(3) - fftfrqs)/(fs(3) - fs(2)); % .. then intersect them with each other and zero % wts(i,:) = 2/(fs(3)-fs(1))*max(0,min(loslope, hislope)); wts(i,:) = max(0,min(loslope, hislope)); % actual algo and weighting in feacalc (more or less) % wts(i,:) = 0; % ww = binbin(i+2)-binbin(i); % usl = binbin(i+1)-binbin(i); % wts(i,1+binbin(i)+[1:usl]) = 2/ww * [1:usl]/usl; % dsl = binbin(i+2)-binbin(i+1); % wts(i,1+binbin(i+1)+[1:(dsl-1)]) = 2/ww * [(dsl-1):-1:1]/dsl; % need to disable weighting below if you use this one end if (constamp == 0) % Slaney-style mel is scaled to be approx constant E per channel wts = diag(2./(binfrqs(2+[1:nfilts])-binfrqs(1:nfilts)))*wts; end % Make sure 2nd half of FFT is zero wts(:,(nfft/2+1):nfft) = 0; % seems like a good idea to avoid aliasing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = mel2hz(z, htk) % f = mel2hz(z, htk) % Convert 'mel scale' frequencies into Hz % Optional htk = 1 means use the HTK formula % else use the formula from Slaney's mfcc.m % 2005-04-19 [email protected] if nargin < 2 htk = 0; end if htk == 1 f = 700*(10.^(z/2595)-1); else f_0 = 0; % 133.33333; f_sp = 200/3; % 66.66667; brkfrq = 1000; brkpt = (brkfrq - f_0)/f_sp; % starting mel value for log region logstep = exp(log(6.4)/27); % the magic 1.0711703 which is the ratio needed to get from 1000 Hz to 6400 Hz in 27 steps, and is *almost* the ratio between 1000 Hz and the preceding linear filter center at 933.33333 Hz (actually 1000/933.33333 = 1.07142857142857 and exp(log(6.4)/27) = 1.07117028749447) linpts = (z < brkpt); f = 0*z; % fill in parts separately f(linpts) = f_0 + f_sp*z(linpts); f(~linpts) = brkfrq*exp(log(logstep)*(z(~linpts)-brkpt)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function z = hz2mel(f,htk) % z = hz2mel(f,htk) % Convert frequencies f (in Hz) to mel 'scale'. % Optional htk = 1 uses the mel axis defined in the HTKBook % otherwise use Slaney's formula % 2005-04-19 [email protected] if nargin < 2 htk = 0; end if htk == 1 z = 2595 * log10(1+f/700); else % Mel fn to match Slaney's Auditory Toolbox mfcc.m f_0 = 0; % 133.33333; f_sp = 200/3; % 66.66667; brkfrq = 1000; brkpt = (brkfrq - f_0)/f_sp; % starting mel value for log region logstep = exp(log(6.4)/27); % the magic 1.0711703 which is the ratio needed to get from 1000 Hz to 6400 Hz in 27 steps, and is *almost* the ratio between 1000 Hz and the preceding linear filter center at 933.33333 Hz (actually 1000/933.33333 = 1.07142857142857 and exp(log(6.4)/27) = 1.07117028749447) linpts = (f < brkfrq); z = 0*f; % fill in parts separately z(linpts) = (f(linpts) - f_0)/f_sp; z(~linpts) = brkpt+(log(f(~linpts)/brkfrq))./log(logstep); end
github
Ewenwan/MVision-master
resampindex.m
.m
MVision-master/3D_Object_Detection/Object_Tracking/pf_socker/resampindex.m
616
utf_8
17caee9b7bd62253da8e82b86d55eead
function indices = resampindex(weights) weights = max(0,weights); weights = weights/sum(weights); N = length(weights); cumprob=[0 cumsum(weights)]; indices = zeros(1,N); if (0) %usual version where each sample drawn randomly uni=rand(1,N); for j=1:N ind=find((uni>cumprob(j)) & (uni<=cumprob(j+1))); indices(ind)=j; end return end %more efficient version where one random sample seeds %a deterministically methodical sampling by 1/N i=1; u1 = rand(1)/N; for j=1:N uj = u1 + (j-1)/N; while (uj > cumprob(i)) i=i+1; end indices(j) = (i-1); end return
github
Ewenwan/MVision-master
genfilename.m
.m
MVision-master/3D_Object_Detection/Object_Tracking/pf_socker/genfilename.m
301
utf_8
ce642ba63a549af477c6165624c061ec
%function fname = genfilename(sequencestruct, framenumber) function fname = genfilename(sequencestruct, framenumber) digstr = sprintf('%%0%dd',sequencestruct.digits); filstr = sprintf('%%s%s%%s',digstr); fname = sprintf(filstr,sequencestruct.prefix,framenumber,sequencestruct.postfix); return
github
OliverKohlDSc/x11-novnc-docker-master
lorenz.m
.m
x11-novnc-docker-master/octave_scr/lorenz.m
464
utf_8
b641d130b724a86bacead286119a74bf
% "Visualizing the Lorenz Strange Attractor with Octave" % http://www.ibm.com/developerworks/library/l-datavistools/ (Listing 4) % % Big Thanks to Douglas (http://lists.gnu.org/archive/html/help-octave/2015-07/msg00159.html) % Usage: % x = lsode("lorenz", [3;15;1], (0:0.01:25)'); % plot3(x(:,1),x(:,2),x(:,3)) % plot3(x(:,001),x(:,3),x(:,2)) function y = lorenz( x, t ) y = [10 * (x(2) - x(1)); x(1) * (28 - x(3)); x(1) * x(2) - 8/3 * x(3)]; endfunction
github
NeuBtracker/acquisition-master
fmeasure.m
.m
acquisition-master/03_Util/external/fmeasure.m
9,062
utf_8
ddd88bb978206f149aff0960807c38e2
function FM = fmeasure(Image, Measure, ROI) %This function measures the relative degree of focus of %an image. It may be invoked as: % % FM = fmeasure(IMAGE, METHOD, ROI) % %Where % IMAGE, is a grayscale image and FM is the computed % focus value. % METHOD, is the focus measure algorithm as a string. % see 'operators.txt' for a list of focus % measure methods. % ROI, Image ROI as a rectangle [xo yo width heigth]. % if an empty argument is passed, the whole % image is processed. % % Said Pertuz % Jan/2016 if nargin>2 && ~isempty(ROI) Image = imcrop(Image, ROI); end WSize = 15; % Size of local window (only some operators) switch upper(Measure) case 'ACMO' % Absolute Central Moment (Shirvaikar2004) if ~isinteger(Image), Image = im2uint8(Image); end FM = AcMomentum(Image); case 'BREN' % Brenner's (Santos97) [M, N] = size(Image); DH = zeros(M, N); DV = zeros(M, N); DV(1:M-2,:) = Image(3:end,:)-Image(1:end-2,:); DH(:,1:N-2) = Image(:,3:end)-Image(:,1:end-2); FM = max(DH, DV); FM = FM.^2; FM = mean2(FM); case 'CONT' % Image contrast (Nanda2001) ImContrast = @(x) sum(abs(x(:)-x(5))); FM = nlfilter(Image, [3 3], ImContrast); FM = mean2(FM); case 'CURV' % Image Curvature (Helmli2001) if ~isinteger(Image), Image = im2uint8(Image); end M1 = [-1 0 1;-1 0 1;-1 0 1]; M2 = [1 0 1;1 0 1;1 0 1]; P0 = imfilter(Image, M1, 'replicate', 'conv')/6; P1 = imfilter(Image, M1', 'replicate', 'conv')/6; P2 = 3*imfilter(Image, M2, 'replicate', 'conv')/10 ... -imfilter(Image, M2', 'replicate', 'conv')/5; P3 = -imfilter(Image, M2, 'replicate', 'conv')/5 ... +3*imfilter(Image, M2, 'replicate', 'conv')/10; FM = abs(P0) + abs(P1) + abs(P2) + abs(P3); FM = mean2(FM); case 'DCTE' % DCT energy ratio (Shen2006) FM = nlfilter(Image, [8 8], @DctRatio); FM = mean2(FM); case 'DCTR' % DCT reduced energy ratio (Lee2009) FM = nlfilter(Image, [8 8], @ReRatio); FM = mean2(FM); case 'GDER' % Gaussian derivative (Geusebroek2000) N = floor(WSize/2); sig = N/2.5; [x,y] = meshgrid(-N:N, -N:N); G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig); Gx = -x.*G/(sig^2); Gx = Gx/sum(abs(Gx(:))); Gy = -y.*G/(sig^2); Gy = Gy/sum(abs(Gy(:))); Rx = imfilter(double(Image), Gx, 'conv', 'replicate'); Ry = imfilter(double(Image), Gy, 'conv', 'replicate'); FM = Rx.^2+Ry.^2; FM = mean2(FM); case 'GLVA' % Graylevel variance (Krotkov86) FM = std2(Image); case 'GLLV' %Graylevel local variance (Pech2000) LVar = stdfilt(Image, ones(WSize,WSize)).^2; FM = std2(LVar)^2; case 'GLVN' % Normalized GLV (Santos97) FM = std2(Image)^2/mean2(Image); case 'GRAE' % Energy of gradient (Subbarao92a) Ix = Image; Iy = Image; Iy(1:end-1,:) = diff(Image, 1, 1); Ix(:,1:end-1) = diff(Image, 1, 2); FM = Ix.^2 + Iy.^2; FM = mean2(FM); case 'GRAT' % Thresholded gradient (Snatos97) Th = 0; %Threshold Ix = Image; Iy = Image; Iy(1:end-1,:) = diff(Image, 1, 1); Ix(:,1:end-1) = diff(Image, 1, 2); FM = max(abs(Ix), abs(Iy)); FM(FM<Th)=0; FM = sum(FM(:))/sum(sum(FM~=0)); case 'GRAS' % Squared gradient (Eskicioglu95) Ix = diff(Image, 1, 2); FM = Ix.^2; FM = mean2(FM); case 'HELM' %Helmli's mean method (Helmli2001) MEANF = fspecial('average',[WSize WSize]); U = imfilter(Image, MEANF, 'replicate'); R1 = U./Image; R1(Image==0)=1; index = (U>Image); FM = 1./R1; FM(index) = R1(index); FM = mean2(FM); case 'HISE' % Histogram entropy (Krotkov86) FM = entropy(Image); case 'HISR' % Histogram range (Firestone91) FM = max(Image(:))-min(Image(:)); case 'LAPE' % Energy of laplacian (Subbarao92a) LAP = fspecial('laplacian'); FM = imfilter(Image, LAP, 'replicate', 'conv'); FM = mean2(FM.^2); case 'LAPM' % Modified Laplacian (Nayar89) M = [-1 2 -1]; Lx = imfilter(Image, M, 'replicate', 'conv'); Ly = imfilter(Image, M', 'replicate', 'conv'); FM = abs(Lx) + abs(Ly); FM = mean2(FM); case 'LAPV' % Variance of laplacian (Pech2000) LAP = fspecial('laplacian'); ILAP = imfilter(Image, LAP, 'replicate', 'conv'); FM = std2(ILAP)^2; case 'LAPD' % Diagonal laplacian (Thelen2009) M1 = [-1 2 -1]; M2 = [0 0 -1;0 2 0;-1 0 0]/sqrt(2); M3 = [-1 0 0;0 2 0;0 0 -1]/sqrt(2); F1 = imfilter(Image, M1, 'replicate', 'conv'); F2 = imfilter(Image, M2, 'replicate', 'conv'); F3 = imfilter(Image, M3, 'replicate', 'conv'); F4 = imfilter(Image, M1', 'replicate', 'conv'); FM = abs(F1) + abs(F2) + abs(F3) + abs(F4); FM = mean2(FM); case 'SFIL' %Steerable filters (Minhas2009) % Angles = [0 45 90 135 180 225 270 315]; N = floor(WSize/2); sig = N/2.5; [x,y] = meshgrid(-N:N, -N:N); G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig); Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:)); Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:)); R(:,:,1) = imfilter(double(Image), Gx, 'conv', 'replicate'); R(:,:,2) = imfilter(double(Image), Gy, 'conv', 'replicate'); R(:,:,3) = cosd(45)*R(:,:,1)+sind(45)*R(:,:,2); R(:,:,4) = cosd(135)*R(:,:,1)+sind(135)*R(:,:,2); R(:,:,5) = cosd(180)*R(:,:,1)+sind(180)*R(:,:,2); R(:,:,6) = cosd(225)*R(:,:,1)+sind(225)*R(:,:,2); R(:,:,7) = cosd(270)*R(:,:,1)+sind(270)*R(:,:,2); R(:,:,8) = cosd(315)*R(:,:,1)+sind(315)*R(:,:,2); FM = max(R,[],3); FM = mean2(FM); case 'SFRQ' % Spatial frequency (Eskicioglu95) Ix = Image; Iy = Image; Ix(:,1:end-1) = diff(Image, 1, 2); Iy(1:end-1,:) = diff(Image, 1, 1); FM = mean2(sqrt(double(Iy.^2+Ix.^2))); case 'TENG'% Tenengrad (Krotkov86) Sx = fspecial('sobel'); Gx = imfilter(double(Image), Sx, 'replicate', 'conv'); Gy = imfilter(double(Image), Sx', 'replicate', 'conv'); FM = Gx.^2 + Gy.^2; FM = mean2(FM); case 'TENV' % Tenengrad variance (Pech2000) Sx = fspecial('sobel'); Gx = imfilter(double(Image), Sx, 'replicate', 'conv'); Gy = imfilter(double(Image), Sx', 'replicate', 'conv'); G = Gx.^2 + Gy.^2; FM = std2(G)^2; case 'VOLA' % Vollath's correlation (Santos97) Image = double(Image); I1 = Image; I1(1:end-1,:) = Image(2:end,:); I2 = Image; I2(1:end-2,:) = Image(3:end,:); Image = Image.*(I1-I2); FM = mean2(Image); case 'WAVS' %Sum of Wavelet coeffs (Yang2003) [C,S] = wavedec2(Image, 1, 'db6'); H = wrcoef2('h', C, S, 'db6', 1); V = wrcoef2('v', C, S, 'db6', 1); D = wrcoef2('d', C, S, 'db6', 1); FM = abs(H) + abs(V) + abs(D); FM = mean2(FM); case 'WAVV' %Variance of Wav...(Yang2003) [C,S] = wavedec2(Image, 1, 'db6'); H = abs(wrcoef2('h', C, S, 'db6', 1)); V = abs(wrcoef2('v', C, S, 'db6', 1)); D = abs(wrcoef2('d', C, S, 'db6', 1)); FM = std2(H)^2+std2(V)+std2(D); case 'WAVR' [C,S] = wavedec2(Image, 3, 'db6'); H = abs(wrcoef2('h', C, S, 'db6', 1)); V = abs(wrcoef2('v', C, S, 'db6', 1)); D = abs(wrcoef2('d', C, S, 'db6', 1)); A1 = abs(wrcoef2('a', C, S, 'db6', 1)); A2 = abs(wrcoef2('a', C, S, 'db6', 2)); A3 = abs(wrcoef2('a', C, S, 'db6', 3)); A = A1 + A2 + A3; WH = H.^2 + V.^2 + D.^2; WH = mean2(WH); WL = mean2(A); FM = WH/WL; otherwise error('Unknown measure %s',upper(Measure)) end end %************************************************************************ function fm = AcMomentum(Image) [M, N] = size(Image); Hist = imhist(Image)/(M*N); Hist = abs((0:255)-255*mean2(Image))'.*Hist; fm = sum(Hist); end %****************************************************************** function fm = DctRatio(M) MT = dct2(M).^2; fm = (sum(MT(:))-MT(1,1))/MT(1,1); end %************************************************************************ function fm = ReRatio(M) M = dct2(M); fm = (M(1,2)^2+M(1,3)^2+M(2,1)^2+M(2,2)^2+M(3,1)^2)/(M(1,1)^2); end %******************************************************************
github
NeuBtracker/acquisition-master
progressbar.m
.m
acquisition-master/03_Util/external/progressbar.m
11,820
utf_8
08d8ff8b281b8fa1ee4a4a8e6a8d21b5
% Description: % progressbar() provides an indication of the progress of some task using % graphics and text. Calling progressbar repeatedly will update the figure and % automatically estimate the amount of time remaining. % This implementation of progressbar is intended to be extremely simple to use % while providing a high quality user experience. % % Features: % - Can add progressbar to existing m-files with a single line of code. % - Supports multiple bars in one figure to show progress of nested loops. % - Optional labels on bars. % - Figure closes automatically when task is complete. % - Only one figure can exist so old figures don't clutter the desktop. % - Remaining time estimate is accurate even if the figure gets closed. % - Minimal execution time. Won't slow down code. % - Randomized color. When a programmer gets bored... % % Example Function Calls For Single Bar Usage: % progressbar % Initialize/reset % progressbar(0) % Initialize/reset % progressbar('Label') % Initialize/reset and label the bar % progressbar(0.5) % Update % progressbar(1) % Close % % Example Function Calls For Multi Bar Usage: % progressbar(0, 0) % Initialize/reset two bars % progressbar('A', '') % Initialize/reset two bars with one label % progressbar('', 'B') % Initialize/reset two bars with one label % progressbar('A', 'B') % Initialize/reset two bars with two labels % progressbar(0.3) % Update 1st bar % progressbar(0.3, []) % Update 1st bar % progressbar([], 0.3) % Update 2nd bar % progressbar(0.7, 0.9) % Update both bars % progressbar(1) % Close % progressbar(1, []) % Close % progressbar(1, 0.4) % Close % % Notes: % For best results, call progressbar with all zero (or all string) inputs % before any processing. This sets the proper starting time reference to % calculate time remaining. % Bar color is choosen randomly when the figure is created or reset. Clicking % the bar will cause a random color change. % % Demos: % % Single bar % m = 500; % progressbar % Init single bar % for i = 1:m % pause(0.01) % Do something important % progressbar(i/m) % Update progress bar % end % % % Simple multi bar (update one bar at a time) % m = 4; % n = 3; % p = 100; % progressbar(0,0,0) % Init 3 bars % for i = 1:m % progressbar([],0) % Reset 2nd bar % for j = 1:n % progressbar([],[],0) % Reset 3rd bar % for k = 1:p % pause(0.01) % Do something important % progressbar([],[],k/p) % Update 3rd bar % end % progressbar([],j/n) % Update 2nd bar % end % progressbar(i/m) % Update 1st bar % end % % % Fancy multi bar (use labels and update all bars at once) % m = 4; % n = 3; % p = 100; % progressbar('Monte Carlo Trials','Simulation','Component') % Init 3 bars % for i = 1:m % for j = 1:n % for k = 1:p % pause(0.01) % Do something important % % Update all bars % frac3 = k/p; % frac2 = ((j-1) + frac3) / n; % frac1 = ((i-1) + frac2) / m; % progressbar(frac1, frac2, frac3) % end % end % end % % Author: % Steve Hoelzer % % Revisions: % 2002-Feb-27 Created function % 2002-Mar-19 Updated title text order % 2002-Apr-11 Use floor instead of round for percentdone % 2002-Jun-06 Updated for speed using patch (Thanks to waitbar.m) % 2002-Jun-19 Choose random patch color when a new figure is created % 2002-Jun-24 Click on bar or axes to choose new random color % 2002-Jun-27 Calc time left, reset progress bar when fractiondone == 0 % 2002-Jun-28 Remove extraText var, add position var % 2002-Jul-18 fractiondone input is optional % 2002-Jul-19 Allow position to specify screen coordinates % 2002-Jul-22 Clear vars used in color change callback routine % 2002-Jul-29 Position input is always specified in pixels % 2002-Sep-09 Change order of title bar text % 2003-Jun-13 Change 'min' to 'm' because of built in function 'min' % 2003-Sep-08 Use callback for changing color instead of string % 2003-Sep-10 Use persistent vars for speed, modify titlebarstr % 2003-Sep-25 Correct titlebarstr for 0% case % 2003-Nov-25 Clear all persistent vars when percentdone = 100 % 2004-Jan-22 Cleaner reset process, don't create figure if percentdone = 100 % 2004-Jan-27 Handle incorrect position input % 2004-Feb-16 Minimum time interval between updates % 2004-Apr-01 Cleaner process of enforcing minimum time interval % 2004-Oct-08 Seperate function for timeleftstr, expand to include days % 2004-Oct-20 Efficient if-else structure for sec2timestr % 2006-Sep-11 Width is a multiple of height (don't stretch on widescreens) % 2010-Sep-21 Major overhaul to support multiple bars and add labels % function progressbar(varargin) persistent progfig progdata lastupdate % Get inputs if nargin > 0 input = varargin; ninput = nargin; else % If no inputs, init with a single bar input = {0}; ninput = 1; end % If task completed, close figure and clear vars, then exit if input{1} == 1 if ishandle(progfig) delete(progfig) % Close progress bar end clear progfig progdata lastupdate % Clear persistent vars drawnow return end % Init reset flag resetflag = false; % Set reset flag if first input is a string if ischar(input{1}) resetflag = true; end % Set reset flag if all inputs are zero if input{1} == 0 % If the quick check above passes, need to check all inputs if all([input{:}] == 0) && (length([input{:}]) == ninput) resetflag = true; end end % Set reset flag if more inputs than bars if ninput > length(progdata) resetflag = true; end % If reset needed, close figure and forget old data if resetflag if ishandle(progfig) delete(progfig) % Close progress bar end progfig = []; progdata = []; % Forget obsolete data end % Create new progress bar if needed if ishandle(progfig) else % This strange if-else works when progfig is empty (~ishandle() does not) % Define figure size and axes padding for the single bar case height = 0.03; width = height * 8; hpad = 0.02; vpad = 0.25; % Figure out how many bars to draw nbars = max(ninput, length(progdata)); % Adjust figure size and axes padding for number of bars heightfactor = (1 - vpad) * nbars + vpad; height = height * heightfactor; vpad = vpad / heightfactor; % Initialize progress bar figure %left = (1 - width) / 2; bottom = (1 - height) / 2; %ORIGINAL left = 0.1; bottom = 0.5; %MINE progfig = figure(... 'Units', 'normalized',... 'Position', [left bottom width height],... 'NumberTitle', 'off',... 'Resize', 'off',... 'MenuBar', 'none' ); % Initialize axes, patch, and text for each bar left = hpad; width = 1 - 2*hpad; vpadtotal = vpad * (nbars + 1); height = (1 - vpadtotal) / nbars; for ndx = 1:nbars % Create axes, patch, and text bottom = vpad + (vpad + height) * (nbars - ndx); progdata(ndx).progaxes = axes( ... 'Position', [left bottom width height], ... 'XLim', [0 1], ... 'YLim', [0 1], ... 'Box', 'on', ... 'ytick', [], ... 'xtick', [] ); progdata(ndx).progpatch = patch( ... 'XData', [0 0 0 0], ... 'YData', [0 0 1 1] ); progdata(ndx).progtext = text(0.99, 0.5, '', ... 'HorizontalAlignment', 'Right', ... 'FontUnits', 'Normalized', ... 'FontSize', 0.7 ); progdata(ndx).proglabel = text(0.01, 0.5, '', ... 'HorizontalAlignment', 'Left', ... 'FontUnits', 'Normalized', ... 'FontSize', 0.7 ); if ischar(input{ndx}) set(progdata(ndx).proglabel, 'String', input{ndx}) input{ndx} = 0; end % Set callbacks to change color on mouse click set(progdata(ndx).progaxes, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).progpatch, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).progtext, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).proglabel, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) % Pick a random color for this patch changecolor([], [], progdata(ndx).progpatch) % Set starting time reference if ~isfield(progdata(ndx), 'starttime') || isempty(progdata(ndx).starttime) progdata(ndx).starttime = clock; end end % Set time of last update to ensure a redraw lastupdate = clock - 1; end % Process inputs and update state of progdata for ndx = 1:ninput if ~isempty(input{ndx}) progdata(ndx).fractiondone = input{ndx}; progdata(ndx).clock = clock; end end % Enforce a minimum time interval between graphics updates myclock = clock; if abs(myclock(6) - lastupdate(6)) < 0.01 % Could use etime() but this is faster return end % Update progress patch for ndx = 1:length(progdata) set(progdata(ndx).progpatch, 'XData', ... [0, progdata(ndx).fractiondone, progdata(ndx).fractiondone, 0]) end % Update progress text if there is more than one bar if length(progdata) > 1 for ndx = 1:length(progdata) set(progdata(ndx).progtext, 'String', ... sprintf('%1d%%', floor(100*progdata(ndx).fractiondone))) end end % Update progress figure title bar if progdata(1).fractiondone > 0 runtime = etime(progdata(1).clock, progdata(1).starttime); timeleft = runtime / progdata(1).fractiondone - runtime; timeleftstr = sec2timestr(timeleft); titlebarstr = sprintf('%2d%% %s remaining', ... floor(100*progdata(1).fractiondone), timeleftstr); else titlebarstr = ' 0%'; end set(progfig, 'Name', titlebarstr) % Force redraw to show changes drawnow % Record time of this update lastupdate = clock; % ------------------------------------------------------------------------------ function changecolor(h, e, progpatch) %#ok<INUSL> % Change the color of the progress bar patch % Prevent color from being too dark or too light colormin = 1.5; colormax = 2.8; thiscolor = rand(1, 3); while (sum(thiscolor) < colormin) || (sum(thiscolor) > colormax) thiscolor = rand(1, 3); end set(progpatch, 'FaceColor', thiscolor) % ------------------------------------------------------------------------------ function timestr = sec2timestr(sec) % Convert a time measurement from seconds into a human readable string. % Convert seconds to other units w = floor(sec/604800); % Weeks sec = sec - w*604800; d = floor(sec/86400); % Days sec = sec - d*86400; h = floor(sec/3600); % Hours sec = sec - h*3600; m = floor(sec/60); % Minutes sec = sec - m*60; s = floor(sec); % Seconds % Create time string if w > 0 if w > 9 timestr = sprintf('%d week', w); else timestr = sprintf('%d week, %d day', w, d); end elseif d > 0 if d > 9 timestr = sprintf('%d day', d); else timestr = sprintf('%d day, %d hr', d, h); end elseif h > 0 if h > 9 timestr = sprintf('%d hr', h); else timestr = sprintf('%d hr, %d min', h, m); end elseif m > 0 if m > 9 timestr = sprintf('%d min', m); else timestr = sprintf('%d min, %d sec', m, s); end else timestr = sprintf('%d sec', s); end
github
NeuBtracker/acquisition-master
dftregistration.m
.m
acquisition-master/03_Util/external/dftregistration.m
9,281
utf_8
8ba8c554cc9ad00df6d4276b74c64b36
function [output, Greg] = dftregistration(buf1ft,buf2ft,usfac) % function [output Greg] = dftregistration(buf1ft,buf2ft,usfac); % Efficient subpixel image registration by crosscorrelation. This code % gives the same precision as the FFT upsampled cross correlation in a % small fraction of the computation time and with reduced memory % requirements. It obtains an initial estimate of the crosscorrelation peak % by an FFT and then refines the shift estimation by upsampling the DFT % only in a small neighborhood of that estimate by means of a % matrix-multiply DFT. With this procedure all the image points are used to % compute the upsampled crosscorrelation. % Manuel Guizar - Dec 13, 2007 % % Rewrote all code not authored by either Manuel Guizar or Jim Fienup % Manuel Guizar - May 13, 2016 % % Citation for this algorithm: % Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup, % "Efficient subpixel image registration algorithms," Opt. Lett. 33, % 156-158 (2008). % % Inputs % buf1ft Fourier transform of reference image, % DC in (1,1) [DO NOT FFTSHIFT] % buf2ft Fourier transform of image to register, % DC in (1,1) [DO NOT FFTSHIFT] % usfac Upsampling factor (integer). Images will be registered to % within 1/usfac of a pixel. For example usfac = 20 means the % images will be registered within 1/20 of a pixel. (default = 1) % % Outputs % output = [error,diffphase,net_row_shift,net_col_shift] % error Translation invariant normalized RMS error between f and g % diffphase Global phase difference between the two images (should be % zero if images are non-negative). % net_row_shift net_col_shift Pixel shifts between images % Greg (Optional) Fourier transform of registered version of buf2ft, % the global phase difference is compensated for. % % % Copyright (c) 2016, Manuel Guizar Sicairos, James R. Fienup, University of Rochester % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in % the documentation and/or other materials provided with the distribution % * Neither the name of the University of Rochester nor the names % of its contributors may be used to endorse or promote products derived % from this software without specific prior written permission. % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE % ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE % LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS % INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE % POSSIBILITY OF SUCH DAMAGE. if ~exist('usfac','var') usfac = 1; end [nr,nc]=size(buf2ft); Nr = ifftshift(-fix(nr/2):ceil(nr/2)-1); Nc = ifftshift(-fix(nc/2):ceil(nc/2)-1); if usfac == 0 % Simple computation of error and phase difference without registration CCmax = sum(buf1ft(:).*conj(buf2ft(:))); row_shift = 0; col_shift = 0; elseif usfac == 1 % Single pixel registration CC = ifft2(buf1ft.*conj(buf2ft)); CCabs = abs(CC); [row_shift, col_shift] = find(CCabs == max(CCabs(:))); CCmax = CC(row_shift,col_shift)*nr*nc; % Now change shifts so that they represent relative shifts and not indices row_shift = Nr(row_shift); col_shift = Nc(col_shift); elseif usfac > 1 % Start with usfac == 2 CC = ifft2(FTpad(buf1ft.*conj(buf2ft),[2*nr,2*nc])); CCabs = abs(CC); [row_shift, col_shift] = find(CCabs == max(CCabs(:)),1,'first'); CCmax = CC(row_shift,col_shift)*nr*nc; % Now change shifts so that they represent relative shifts and not indices Nr2 = ifftshift(-fix(nr):ceil(nr)-1); Nc2 = ifftshift(-fix(nc):ceil(nc)-1); row_shift = Nr2(row_shift)/2; col_shift = Nc2(col_shift)/2; % If upsampling > 2, then refine estimate with matrix multiply DFT if usfac > 2, %%% DFT computation %%% % Initial shift estimate in upsampled grid row_shift = round(row_shift*usfac)/usfac; col_shift = round(col_shift*usfac)/usfac; dftshift = fix(ceil(usfac*1.5)/2); %% Center of output array at dftshift+1 % Matrix multiply DFT around the current shift estimate CC = conj(dftups(buf2ft.*conj(buf1ft),ceil(usfac*1.5),ceil(usfac*1.5),usfac,... dftshift-row_shift*usfac,dftshift-col_shift*usfac)); % Locate maximum and map back to original pixel grid CCabs = abs(CC); [rloc, cloc] = find(CCabs == max(CCabs(:)),1,'first'); CCmax = CC(rloc,cloc); rloc = rloc - dftshift - 1; cloc = cloc - dftshift - 1; row_shift = row_shift + rloc/usfac; col_shift = col_shift + cloc/usfac; end % If its only one row or column the shift along that dimension has no % effect. Set to zero. if nr == 1, row_shift = 0; end if nc == 1, col_shift = 0; end end rg00 = sum(abs(buf1ft(:)).^2); rf00 = sum(abs(buf2ft(:)).^2); error = 1.0 - abs(CCmax).^2/(rg00*rf00); error = sqrt(abs(error)); diffphase = angle(CCmax); output=[error,diffphase,row_shift,col_shift]; % Compute registered version of buf2ft if (nargout > 1)&&(usfac > 0), [Nc,Nr] = meshgrid(Nc,Nr); Greg = buf2ft.*exp(1i*2*pi*(-row_shift*Nr/nr-col_shift*Nc/nc)); Greg = Greg*exp(1i*diffphase); elseif (nargout > 1)&&(usfac == 0) Greg = buf2ft*exp(1i*diffphase); end return function out=dftups(in,nor,noc,usfac,roff,coff) % function out=dftups(in,nor,noc,usfac,roff,coff); % Upsampled DFT by matrix multiplies, can compute an upsampled DFT in just % a small region. % usfac Upsampling factor (default usfac = 1) % [nor,noc] Number of pixels in the output upsampled DFT, in % units of upsampled pixels (default = size(in)) % roff, coff Row and column offsets, allow to shift the output array to % a region of interest on the DFT (default = 0) % Recieves DC in upper left corner, image center must be in (1,1) % Manuel Guizar - Dec 13, 2007 % Modified from dftus, by J.R. Fienup 7/31/06 % This code is intended to provide the same result as if the following % operations were performed % - Embed the array "in" in an array that is usfac times larger in each % dimension. ifftshift to bring the center of the image to (1,1). % - Take the FFT of the larger array % - Extract an [nor, noc] region of the result. Starting with the % [roff+1 coff+1] element. % It achieves this result by computing the DFT in the output array without % the need to zeropad. Much faster and memory efficient than the % zero-padded FFT approach if [nor noc] are much smaller than [nr*usfac nc*usfac] [nr,nc]=size(in); % Set defaults if exist('roff', 'var')~=1, roff=0; end if exist('coff', 'var')~=1, coff=0; end if exist('usfac','var')~=1, usfac=1; end if exist('noc', 'var')~=1, noc=nc; end if exist('nor', 'var')~=1, nor=nr; end % Compute kernels and obtain DFT by matrix products kernc=exp((-1i*2*pi/(nc*usfac))*( ifftshift(0:nc-1).' - floor(nc/2) )*( (0:noc-1) - coff )); kernr=exp((-1i*2*pi/(nr*usfac))*( (0:nor-1).' - roff )*( ifftshift([0:nr-1]) - floor(nr/2) )); out=kernr*in*kernc; return function [ imFTout ] = FTpad(imFT,outsize) % imFTout = FTpad(imFT,outsize) % Pads or crops the Fourier transform to the desired ouput size. Taking % care that the zero frequency is put in the correct place for the output % for subsequent FT or IFT. Can be used for Fourier transform based % interpolation, i.e. dirichlet kernel interpolation. % % Inputs % imFT - Input complex array with DC in [1,1] % outsize - Output size of array [ny nx] % % Outputs % imout - Output complex image with DC in [1,1] % Manuel Guizar - 2014.06.02 if ~ismatrix(imFT) error('Maximum number of array dimensions is 2') end Nout = outsize; Nin = size(imFT); imFT = fftshift(imFT); center = floor(size(imFT)/2)+1; imFTout = zeros(outsize); centerout = floor(size(imFTout)/2)+1; % imout(centerout(1)+[1:Nin(1)]-center(1),centerout(2)+[1:Nin(2)]-center(2)) ... % = imFT; cenout_cen = centerout - center; imFTout(max(cenout_cen(1)+1,1):min(cenout_cen(1)+Nin(1),Nout(1)),max(cenout_cen(2)+1,1):min(cenout_cen(2)+Nin(2),Nout(2))) ... = imFT(max(-cenout_cen(1)+1,1):min(-cenout_cen(1)+Nout(1),Nin(1)),max(-cenout_cen(2)+1,1):min(-cenout_cen(2)+Nout(2),Nin(2))); imFTout = ifftshift(imFTout)*Nout(1)*Nout(2)/(Nin(1)*Nin(2)); return
github
NeuBtracker/acquisition-master
mouseinput_timeout.m
.m
acquisition-master/01_Acquisition/Functions/mouseinput_timeout.m
3,655
utf_8
480bb97f4f606096de22a342aed79ef2
% MOUSEINPUT_TIMEOUT returns continuous mouse locations with timeout % OUT = MOUSEINPUT_TIMEOUT returns the sequence of mouse locations between % a button press and a button release in the current axes. It does % not timeout. OUT is an Nx2 matrix, where OUT(1,:) is the location % at button press and OUT(END,:) is the location at button release. % % OUT = MOUSEINPUT_TIMEOUT(T) times out after a period of T seconds. % T can be a fractional value (T=inf indicates no timeout). If % the mouse-button has not been pressed during that time, OUT is []. % If the timeout occurs during a mouse movement, OUT contains the % mouse locations before the timeout. % % OUT = MOUSEINPUT_TIMEOUT(T,AH) records the mouse movement from % the axes specified by axes handle AH. % % Note: MOUSEINPUT_TIMEOUT differs from GINPUT in two ways. % (1) It does not return information about which mouse button % was pressed, and % (2) It ignores key presses. % % Example: % % record movements from current axes, timeout after 4.5 sec % out = mouseinput_timeout(4.5, gca); % figure; % plot(out(:,1), out(:,2), '.-'); % plot the mouse movement % % See also ginput, waitforbuttonpress % % Gautam Vallabha, Sep-23-2007, [email protected] % Copyright 2009 The MathWorks, Inc. % % Updated minor typo that caused an error in 2009b % (Gautam Vallabha, Nov-17-2009) function selectedPts = mouseinput_timeout(timeoutval, axesHandle) if ~exist('axesHandle', 'var') axesHandle = gca; end if ~exist('timeoutval', 'var'), timeoutval = inf; end if ~(ishandle(axesHandle) && strcmp(get(axesHandle,'type'),'axes')) error('Axis handle is not valid'); end if ~(isscalar(timeoutval) && (timeoutval > 0)) error('Timeout should be a positive scalar'); end %----------------------- figHandle = get(axesHandle, 'parent'); selectedPts = []; % get existing figure properties oldProperties = get(figHandle, ... {'WindowButtonDownFcn','WindowButtonUpFcn',... 'WindowButtonMotionFcn', 'units','pointer'}); % replace with new properties to register mouse input set(figHandle, ... {'WindowButtonDownFcn','WindowButtonUpFcn',... 'WindowButtonMotionFcn', 'units','pointer'}, ... { @buttonDownCallback, @buttonUpCallback, ... [], 'pixels', 'crosshair' }); figLocation = get(figHandle, 'Position'); % key step: wait until timeout or until UIRESUME is called if isinf(timeoutval) uiwait(figHandle); else uiwait(figHandle, timeoutval); end % restore pre-existing figure properties set(figHandle, ... {'WindowButtonDownFcn','WindowButtonUpFcn',... 'WindowButtonMotionFcn', 'units','pointer'}, ... oldProperties); %% -------------------------------------------- function buttonMotionCallback(obj, eventdata) %#ok<INUSD> pt = mapCurrentPosition(); selectedPts(end+1,:) = pt(1,1:2); end function buttonDownCallback(obj, eventdata) %#ok<INUSD> selectedPts = []; set(obj, 'WindowButtonMotionFcn', @buttonMotionCallback); end function buttonUpCallback(obj, eventdata) %#ok<INUSD> pt = mapCurrentPosition(); selectedPts(end+1,:) = pt(1,1:2); set(obj, 'WindowButtonMotionFcn', [] ); uiresume(figHandle); end %% -------------------------------------------- % The following adjustment is based on GINPUT function pt = mapCurrentPosition() scrn_pt = get(0, 'PointerLocation'); set(figHandle,'CurrentPoint',... [scrn_pt(1) - figLocation(1) + 1, scrn_pt(2) - figLocation(2) + 1]); pt = get(axesHandle,'CurrentPoint'); end %% end
github
NeuBtracker/acquisition-master
fmeasure.m
.m
acquisition-master/01_Acquisition/Functions/Autofocus/fmeasure.m
9,062
utf_8
ddd88bb978206f149aff0960807c38e2
function FM = fmeasure(Image, Measure, ROI) %This function measures the relative degree of focus of %an image. It may be invoked as: % % FM = fmeasure(IMAGE, METHOD, ROI) % %Where % IMAGE, is a grayscale image and FM is the computed % focus value. % METHOD, is the focus measure algorithm as a string. % see 'operators.txt' for a list of focus % measure methods. % ROI, Image ROI as a rectangle [xo yo width heigth]. % if an empty argument is passed, the whole % image is processed. % % Said Pertuz % Jan/2016 if nargin>2 && ~isempty(ROI) Image = imcrop(Image, ROI); end WSize = 15; % Size of local window (only some operators) switch upper(Measure) case 'ACMO' % Absolute Central Moment (Shirvaikar2004) if ~isinteger(Image), Image = im2uint8(Image); end FM = AcMomentum(Image); case 'BREN' % Brenner's (Santos97) [M, N] = size(Image); DH = zeros(M, N); DV = zeros(M, N); DV(1:M-2,:) = Image(3:end,:)-Image(1:end-2,:); DH(:,1:N-2) = Image(:,3:end)-Image(:,1:end-2); FM = max(DH, DV); FM = FM.^2; FM = mean2(FM); case 'CONT' % Image contrast (Nanda2001) ImContrast = @(x) sum(abs(x(:)-x(5))); FM = nlfilter(Image, [3 3], ImContrast); FM = mean2(FM); case 'CURV' % Image Curvature (Helmli2001) if ~isinteger(Image), Image = im2uint8(Image); end M1 = [-1 0 1;-1 0 1;-1 0 1]; M2 = [1 0 1;1 0 1;1 0 1]; P0 = imfilter(Image, M1, 'replicate', 'conv')/6; P1 = imfilter(Image, M1', 'replicate', 'conv')/6; P2 = 3*imfilter(Image, M2, 'replicate', 'conv')/10 ... -imfilter(Image, M2', 'replicate', 'conv')/5; P3 = -imfilter(Image, M2, 'replicate', 'conv')/5 ... +3*imfilter(Image, M2, 'replicate', 'conv')/10; FM = abs(P0) + abs(P1) + abs(P2) + abs(P3); FM = mean2(FM); case 'DCTE' % DCT energy ratio (Shen2006) FM = nlfilter(Image, [8 8], @DctRatio); FM = mean2(FM); case 'DCTR' % DCT reduced energy ratio (Lee2009) FM = nlfilter(Image, [8 8], @ReRatio); FM = mean2(FM); case 'GDER' % Gaussian derivative (Geusebroek2000) N = floor(WSize/2); sig = N/2.5; [x,y] = meshgrid(-N:N, -N:N); G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig); Gx = -x.*G/(sig^2); Gx = Gx/sum(abs(Gx(:))); Gy = -y.*G/(sig^2); Gy = Gy/sum(abs(Gy(:))); Rx = imfilter(double(Image), Gx, 'conv', 'replicate'); Ry = imfilter(double(Image), Gy, 'conv', 'replicate'); FM = Rx.^2+Ry.^2; FM = mean2(FM); case 'GLVA' % Graylevel variance (Krotkov86) FM = std2(Image); case 'GLLV' %Graylevel local variance (Pech2000) LVar = stdfilt(Image, ones(WSize,WSize)).^2; FM = std2(LVar)^2; case 'GLVN' % Normalized GLV (Santos97) FM = std2(Image)^2/mean2(Image); case 'GRAE' % Energy of gradient (Subbarao92a) Ix = Image; Iy = Image; Iy(1:end-1,:) = diff(Image, 1, 1); Ix(:,1:end-1) = diff(Image, 1, 2); FM = Ix.^2 + Iy.^2; FM = mean2(FM); case 'GRAT' % Thresholded gradient (Snatos97) Th = 0; %Threshold Ix = Image; Iy = Image; Iy(1:end-1,:) = diff(Image, 1, 1); Ix(:,1:end-1) = diff(Image, 1, 2); FM = max(abs(Ix), abs(Iy)); FM(FM<Th)=0; FM = sum(FM(:))/sum(sum(FM~=0)); case 'GRAS' % Squared gradient (Eskicioglu95) Ix = diff(Image, 1, 2); FM = Ix.^2; FM = mean2(FM); case 'HELM' %Helmli's mean method (Helmli2001) MEANF = fspecial('average',[WSize WSize]); U = imfilter(Image, MEANF, 'replicate'); R1 = U./Image; R1(Image==0)=1; index = (U>Image); FM = 1./R1; FM(index) = R1(index); FM = mean2(FM); case 'HISE' % Histogram entropy (Krotkov86) FM = entropy(Image); case 'HISR' % Histogram range (Firestone91) FM = max(Image(:))-min(Image(:)); case 'LAPE' % Energy of laplacian (Subbarao92a) LAP = fspecial('laplacian'); FM = imfilter(Image, LAP, 'replicate', 'conv'); FM = mean2(FM.^2); case 'LAPM' % Modified Laplacian (Nayar89) M = [-1 2 -1]; Lx = imfilter(Image, M, 'replicate', 'conv'); Ly = imfilter(Image, M', 'replicate', 'conv'); FM = abs(Lx) + abs(Ly); FM = mean2(FM); case 'LAPV' % Variance of laplacian (Pech2000) LAP = fspecial('laplacian'); ILAP = imfilter(Image, LAP, 'replicate', 'conv'); FM = std2(ILAP)^2; case 'LAPD' % Diagonal laplacian (Thelen2009) M1 = [-1 2 -1]; M2 = [0 0 -1;0 2 0;-1 0 0]/sqrt(2); M3 = [-1 0 0;0 2 0;0 0 -1]/sqrt(2); F1 = imfilter(Image, M1, 'replicate', 'conv'); F2 = imfilter(Image, M2, 'replicate', 'conv'); F3 = imfilter(Image, M3, 'replicate', 'conv'); F4 = imfilter(Image, M1', 'replicate', 'conv'); FM = abs(F1) + abs(F2) + abs(F3) + abs(F4); FM = mean2(FM); case 'SFIL' %Steerable filters (Minhas2009) % Angles = [0 45 90 135 180 225 270 315]; N = floor(WSize/2); sig = N/2.5; [x,y] = meshgrid(-N:N, -N:N); G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig); Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:)); Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:)); R(:,:,1) = imfilter(double(Image), Gx, 'conv', 'replicate'); R(:,:,2) = imfilter(double(Image), Gy, 'conv', 'replicate'); R(:,:,3) = cosd(45)*R(:,:,1)+sind(45)*R(:,:,2); R(:,:,4) = cosd(135)*R(:,:,1)+sind(135)*R(:,:,2); R(:,:,5) = cosd(180)*R(:,:,1)+sind(180)*R(:,:,2); R(:,:,6) = cosd(225)*R(:,:,1)+sind(225)*R(:,:,2); R(:,:,7) = cosd(270)*R(:,:,1)+sind(270)*R(:,:,2); R(:,:,8) = cosd(315)*R(:,:,1)+sind(315)*R(:,:,2); FM = max(R,[],3); FM = mean2(FM); case 'SFRQ' % Spatial frequency (Eskicioglu95) Ix = Image; Iy = Image; Ix(:,1:end-1) = diff(Image, 1, 2); Iy(1:end-1,:) = diff(Image, 1, 1); FM = mean2(sqrt(double(Iy.^2+Ix.^2))); case 'TENG'% Tenengrad (Krotkov86) Sx = fspecial('sobel'); Gx = imfilter(double(Image), Sx, 'replicate', 'conv'); Gy = imfilter(double(Image), Sx', 'replicate', 'conv'); FM = Gx.^2 + Gy.^2; FM = mean2(FM); case 'TENV' % Tenengrad variance (Pech2000) Sx = fspecial('sobel'); Gx = imfilter(double(Image), Sx, 'replicate', 'conv'); Gy = imfilter(double(Image), Sx', 'replicate', 'conv'); G = Gx.^2 + Gy.^2; FM = std2(G)^2; case 'VOLA' % Vollath's correlation (Santos97) Image = double(Image); I1 = Image; I1(1:end-1,:) = Image(2:end,:); I2 = Image; I2(1:end-2,:) = Image(3:end,:); Image = Image.*(I1-I2); FM = mean2(Image); case 'WAVS' %Sum of Wavelet coeffs (Yang2003) [C,S] = wavedec2(Image, 1, 'db6'); H = wrcoef2('h', C, S, 'db6', 1); V = wrcoef2('v', C, S, 'db6', 1); D = wrcoef2('d', C, S, 'db6', 1); FM = abs(H) + abs(V) + abs(D); FM = mean2(FM); case 'WAVV' %Variance of Wav...(Yang2003) [C,S] = wavedec2(Image, 1, 'db6'); H = abs(wrcoef2('h', C, S, 'db6', 1)); V = abs(wrcoef2('v', C, S, 'db6', 1)); D = abs(wrcoef2('d', C, S, 'db6', 1)); FM = std2(H)^2+std2(V)+std2(D); case 'WAVR' [C,S] = wavedec2(Image, 3, 'db6'); H = abs(wrcoef2('h', C, S, 'db6', 1)); V = abs(wrcoef2('v', C, S, 'db6', 1)); D = abs(wrcoef2('d', C, S, 'db6', 1)); A1 = abs(wrcoef2('a', C, S, 'db6', 1)); A2 = abs(wrcoef2('a', C, S, 'db6', 2)); A3 = abs(wrcoef2('a', C, S, 'db6', 3)); A = A1 + A2 + A3; WH = H.^2 + V.^2 + D.^2; WH = mean2(WH); WL = mean2(A); FM = WH/WL; otherwise error('Unknown measure %s',upper(Measure)) end end %************************************************************************ function fm = AcMomentum(Image) [M, N] = size(Image); Hist = imhist(Image)/(M*N); Hist = abs((0:255)-255*mean2(Image))'.*Hist; fm = sum(Hist); end %****************************************************************** function fm = DctRatio(M) MT = dct2(M).^2; fm = (sum(MT(:))-MT(1,1))/MT(1,1); end %************************************************************************ function fm = ReRatio(M) M = dct2(M); fm = (M(1,2)^2+M(1,3)^2+M(2,1)^2+M(2,2)^2+M(3,1)^2)/(M(1,1)^2); end %******************************************************************
github
NeuBtracker/acquisition-master
fmeasure.m
.m
acquisition-master/01_Acquisition/Functions/Autofocus/fmeasure/fmeasure.m
9,062
utf_8
ddd88bb978206f149aff0960807c38e2
function FM = fmeasure(Image, Measure, ROI) %This function measures the relative degree of focus of %an image. It may be invoked as: % % FM = fmeasure(IMAGE, METHOD, ROI) % %Where % IMAGE, is a grayscale image and FM is the computed % focus value. % METHOD, is the focus measure algorithm as a string. % see 'operators.txt' for a list of focus % measure methods. % ROI, Image ROI as a rectangle [xo yo width heigth]. % if an empty argument is passed, the whole % image is processed. % % Said Pertuz % Jan/2016 if nargin>2 && ~isempty(ROI) Image = imcrop(Image, ROI); end WSize = 15; % Size of local window (only some operators) switch upper(Measure) case 'ACMO' % Absolute Central Moment (Shirvaikar2004) if ~isinteger(Image), Image = im2uint8(Image); end FM = AcMomentum(Image); case 'BREN' % Brenner's (Santos97) [M, N] = size(Image); DH = zeros(M, N); DV = zeros(M, N); DV(1:M-2,:) = Image(3:end,:)-Image(1:end-2,:); DH(:,1:N-2) = Image(:,3:end)-Image(:,1:end-2); FM = max(DH, DV); FM = FM.^2; FM = mean2(FM); case 'CONT' % Image contrast (Nanda2001) ImContrast = @(x) sum(abs(x(:)-x(5))); FM = nlfilter(Image, [3 3], ImContrast); FM = mean2(FM); case 'CURV' % Image Curvature (Helmli2001) if ~isinteger(Image), Image = im2uint8(Image); end M1 = [-1 0 1;-1 0 1;-1 0 1]; M2 = [1 0 1;1 0 1;1 0 1]; P0 = imfilter(Image, M1, 'replicate', 'conv')/6; P1 = imfilter(Image, M1', 'replicate', 'conv')/6; P2 = 3*imfilter(Image, M2, 'replicate', 'conv')/10 ... -imfilter(Image, M2', 'replicate', 'conv')/5; P3 = -imfilter(Image, M2, 'replicate', 'conv')/5 ... +3*imfilter(Image, M2, 'replicate', 'conv')/10; FM = abs(P0) + abs(P1) + abs(P2) + abs(P3); FM = mean2(FM); case 'DCTE' % DCT energy ratio (Shen2006) FM = nlfilter(Image, [8 8], @DctRatio); FM = mean2(FM); case 'DCTR' % DCT reduced energy ratio (Lee2009) FM = nlfilter(Image, [8 8], @ReRatio); FM = mean2(FM); case 'GDER' % Gaussian derivative (Geusebroek2000) N = floor(WSize/2); sig = N/2.5; [x,y] = meshgrid(-N:N, -N:N); G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig); Gx = -x.*G/(sig^2); Gx = Gx/sum(abs(Gx(:))); Gy = -y.*G/(sig^2); Gy = Gy/sum(abs(Gy(:))); Rx = imfilter(double(Image), Gx, 'conv', 'replicate'); Ry = imfilter(double(Image), Gy, 'conv', 'replicate'); FM = Rx.^2+Ry.^2; FM = mean2(FM); case 'GLVA' % Graylevel variance (Krotkov86) FM = std2(Image); case 'GLLV' %Graylevel local variance (Pech2000) LVar = stdfilt(Image, ones(WSize,WSize)).^2; FM = std2(LVar)^2; case 'GLVN' % Normalized GLV (Santos97) FM = std2(Image)^2/mean2(Image); case 'GRAE' % Energy of gradient (Subbarao92a) Ix = Image; Iy = Image; Iy(1:end-1,:) = diff(Image, 1, 1); Ix(:,1:end-1) = diff(Image, 1, 2); FM = Ix.^2 + Iy.^2; FM = mean2(FM); case 'GRAT' % Thresholded gradient (Snatos97) Th = 0; %Threshold Ix = Image; Iy = Image; Iy(1:end-1,:) = diff(Image, 1, 1); Ix(:,1:end-1) = diff(Image, 1, 2); FM = max(abs(Ix), abs(Iy)); FM(FM<Th)=0; FM = sum(FM(:))/sum(sum(FM~=0)); case 'GRAS' % Squared gradient (Eskicioglu95) Ix = diff(Image, 1, 2); FM = Ix.^2; FM = mean2(FM); case 'HELM' %Helmli's mean method (Helmli2001) MEANF = fspecial('average',[WSize WSize]); U = imfilter(Image, MEANF, 'replicate'); R1 = U./Image; R1(Image==0)=1; index = (U>Image); FM = 1./R1; FM(index) = R1(index); FM = mean2(FM); case 'HISE' % Histogram entropy (Krotkov86) FM = entropy(Image); case 'HISR' % Histogram range (Firestone91) FM = max(Image(:))-min(Image(:)); case 'LAPE' % Energy of laplacian (Subbarao92a) LAP = fspecial('laplacian'); FM = imfilter(Image, LAP, 'replicate', 'conv'); FM = mean2(FM.^2); case 'LAPM' % Modified Laplacian (Nayar89) M = [-1 2 -1]; Lx = imfilter(Image, M, 'replicate', 'conv'); Ly = imfilter(Image, M', 'replicate', 'conv'); FM = abs(Lx) + abs(Ly); FM = mean2(FM); case 'LAPV' % Variance of laplacian (Pech2000) LAP = fspecial('laplacian'); ILAP = imfilter(Image, LAP, 'replicate', 'conv'); FM = std2(ILAP)^2; case 'LAPD' % Diagonal laplacian (Thelen2009) M1 = [-1 2 -1]; M2 = [0 0 -1;0 2 0;-1 0 0]/sqrt(2); M3 = [-1 0 0;0 2 0;0 0 -1]/sqrt(2); F1 = imfilter(Image, M1, 'replicate', 'conv'); F2 = imfilter(Image, M2, 'replicate', 'conv'); F3 = imfilter(Image, M3, 'replicate', 'conv'); F4 = imfilter(Image, M1', 'replicate', 'conv'); FM = abs(F1) + abs(F2) + abs(F3) + abs(F4); FM = mean2(FM); case 'SFIL' %Steerable filters (Minhas2009) % Angles = [0 45 90 135 180 225 270 315]; N = floor(WSize/2); sig = N/2.5; [x,y] = meshgrid(-N:N, -N:N); G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig); Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:)); Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:)); R(:,:,1) = imfilter(double(Image), Gx, 'conv', 'replicate'); R(:,:,2) = imfilter(double(Image), Gy, 'conv', 'replicate'); R(:,:,3) = cosd(45)*R(:,:,1)+sind(45)*R(:,:,2); R(:,:,4) = cosd(135)*R(:,:,1)+sind(135)*R(:,:,2); R(:,:,5) = cosd(180)*R(:,:,1)+sind(180)*R(:,:,2); R(:,:,6) = cosd(225)*R(:,:,1)+sind(225)*R(:,:,2); R(:,:,7) = cosd(270)*R(:,:,1)+sind(270)*R(:,:,2); R(:,:,8) = cosd(315)*R(:,:,1)+sind(315)*R(:,:,2); FM = max(R,[],3); FM = mean2(FM); case 'SFRQ' % Spatial frequency (Eskicioglu95) Ix = Image; Iy = Image; Ix(:,1:end-1) = diff(Image, 1, 2); Iy(1:end-1,:) = diff(Image, 1, 1); FM = mean2(sqrt(double(Iy.^2+Ix.^2))); case 'TENG'% Tenengrad (Krotkov86) Sx = fspecial('sobel'); Gx = imfilter(double(Image), Sx, 'replicate', 'conv'); Gy = imfilter(double(Image), Sx', 'replicate', 'conv'); FM = Gx.^2 + Gy.^2; FM = mean2(FM); case 'TENV' % Tenengrad variance (Pech2000) Sx = fspecial('sobel'); Gx = imfilter(double(Image), Sx, 'replicate', 'conv'); Gy = imfilter(double(Image), Sx', 'replicate', 'conv'); G = Gx.^2 + Gy.^2; FM = std2(G)^2; case 'VOLA' % Vollath's correlation (Santos97) Image = double(Image); I1 = Image; I1(1:end-1,:) = Image(2:end,:); I2 = Image; I2(1:end-2,:) = Image(3:end,:); Image = Image.*(I1-I2); FM = mean2(Image); case 'WAVS' %Sum of Wavelet coeffs (Yang2003) [C,S] = wavedec2(Image, 1, 'db6'); H = wrcoef2('h', C, S, 'db6', 1); V = wrcoef2('v', C, S, 'db6', 1); D = wrcoef2('d', C, S, 'db6', 1); FM = abs(H) + abs(V) + abs(D); FM = mean2(FM); case 'WAVV' %Variance of Wav...(Yang2003) [C,S] = wavedec2(Image, 1, 'db6'); H = abs(wrcoef2('h', C, S, 'db6', 1)); V = abs(wrcoef2('v', C, S, 'db6', 1)); D = abs(wrcoef2('d', C, S, 'db6', 1)); FM = std2(H)^2+std2(V)+std2(D); case 'WAVR' [C,S] = wavedec2(Image, 3, 'db6'); H = abs(wrcoef2('h', C, S, 'db6', 1)); V = abs(wrcoef2('v', C, S, 'db6', 1)); D = abs(wrcoef2('d', C, S, 'db6', 1)); A1 = abs(wrcoef2('a', C, S, 'db6', 1)); A2 = abs(wrcoef2('a', C, S, 'db6', 2)); A3 = abs(wrcoef2('a', C, S, 'db6', 3)); A = A1 + A2 + A3; WH = H.^2 + V.^2 + D.^2; WH = mean2(WH); WL = mean2(A); FM = WH/WL; otherwise error('Unknown measure %s',upper(Measure)) end end %************************************************************************ function fm = AcMomentum(Image) [M, N] = size(Image); Hist = imhist(Image)/(M*N); Hist = abs((0:255)-255*mean2(Image))'.*Hist; fm = sum(Hist); end %****************************************************************** function fm = DctRatio(M) MT = dct2(M).^2; fm = (sum(MT(:))-MT(1,1))/MT(1,1); end %************************************************************************ function fm = ReRatio(M) M = dct2(M); fm = (M(1,2)^2+M(1,3)^2+M(2,1)^2+M(2,2)^2+M(3,1)^2)/(M(1,1)^2); end %******************************************************************
github
NeuBtracker/acquisition-master
F_IMdif2Coord_131.m
.m
acquisition-master/01_Acquisition/Functions/OriginalTrackingObsolete/F_IMdif2Coord_131.m
3,598
utf_8
4ba37d580fe7c5d3367af2e6c07e8efd
function [status, Coord, IMdif] = F_IMdif2Coord_131(IM, IM_o,ill_type, pl, blur_fact, nsig_bin, npxl_min, npxl_max) % This function computes the difference between the coordinates of the % fish in the two input images. % INPUT: IM first input image % IM_o second input image (presumably the previous image) % ill_type type of illumination: 'transmit' or 'reflex' % pl plot option (1>yes, 0>no) % blur_fact blurring factor % nsig_bin number of sigma defining the binary threshold % npxl_min Minimal number of pixels for a valid detection % This is roughtly equal to the area of the fish % npxl_max Maximal number of pixels for a valid detection % This upper limit is usefull in case the whole % arena moves. In case the detected changing are is % bigger, then the status is set to 0 % OUTPUT: status 1: the fish moved, 0: the fish didn't move % Coord coordinates in the image IM % IMdif Difference if nargin<7, npxl_min=200; end if nargin<6, nsig_bin=5; end if nargin<5, blur_fact=3; end if nargin<4, pl=0; end if nargin<3, ill_type='transmit'; end status=0; Coord=[]; %---------------------------------------------------------------------- switch ill_type case 'transmit' IMdif=(IM_o-IM); case 'reflex' IMdif=(IM)-(IM_o); end if blur_fact~=0 IMdif_blur = F_IMfilt(IMdifX,'gaussian',0,blur_fact*4*[1 1],blur_fact); else IMdif_blur=IMdif; end dif_thr = nsig_bin * std(IMdif_blur(:)); IMdif_pos=uint8((IMdif_blur>dif_thr)); IMdif_pos_big = bwareaopen(IMdif_pos,npxl_min); if sum(IMdif_pos_big(:))>npxl_min && sum(IMdif_pos_big(:))<npxl_max status=1; Coord = F_Mask2Cetroid(IMdif_pos_big,0); end %====================================================================== if pl figure colormap gray ax(1)=subplot(2,3,1); imagesc(IM) title('IM status=0') ax(2)=subplot(2,3,2); imagesc(IM_o) title('IMo') ax(3)=subplot(2,3,3); imshowpair(IM_o,IM) title('Comparison') ax(6)=subplot(2,3,6); imagesc(IMdif) title('IM dif') ax(5)=subplot(2,3,5); imagesc(IMdif_pos) title('IMdif pos') ax(4)=subplot(2,3,4); imagesc(IMdif_pos_big) title('IMdif pos big') linkaxes(ax,'xy') if status subplot(2,3,1) hold on plot(Coord(1),Coord(2),'.r'); plot(Coord(1),Coord(2),'or'); title('IM status=1') end end end function [Coord] = F_Mask2Cetroid(Mask,pl) % This function computes the centroid of the input Mask if nargin<2, pl=0; end if sum(Mask(:))~=0 X=(1:size(Mask,2))'; Y=(1:size(Mask,1))'; Ix=sum(Mask,1)'; Iy=sum(Mask,2); Coord=[sum(X.*Ix)/sum(Ix), sum(Y.*Iy)/sum(Iy)]; else Coord=[0 0]; end if pl figure colormap gray imagesc(Mask) hold on plot(Coord(1),Coord(2),'.r') plot(Coord(1),Coord(2),'ob') title(['Coord=[',num2str(Coord(1),'%.2f'),',',num2str(Coord(2),'%.2f'),']']) end end
github
NeuBtracker/acquisition-master
F_IMdif2Coord_132.m
.m
acquisition-master/01_Acquisition/Functions/OriginalTrackingObsolete/F_IMdif2Coord_132.m
3,625
utf_8
ed66f02f1c3f1a080a230a504fcad6dc
function [status, Coord, IMdif] = F_IMdif2Coord_131(IM, IM_o,ill_type, pl, blur_fact, nsig_bin, npxl_min, npxl_max) % This function computes the difference between the coordinates of the % fish in the two input images. % INPUT: IM first input image % IM_o second input image (presumably the previous image) % ill_type type of illumination: 'transmit' or 'reflex' % pl plot option (1>yes, 0>no) % blur_fact blurring factor % nsig_bin number of sigma defining the binary threshold % npxl_min Minimal number of pixels for a valid detection % This is roughtly equal to the area of the fish % npxl_max Maximal number of pixels for a valid detection % This upper limit is usefull in case the whole % arena moves. In case the detected changing are is % bigger, then the status is set to 0 % OUTPUT: status 1: the fish moved, 0: the fish didn't move % Coord coordinates in the image IM % IMdif Difference if nargin<7, npxl_min=200; end if nargin<6, nsig_bin=5; end if nargin<5, blur_fact=3; end if nargin<4, pl=0; end if nargin<3, ill_type='transmit'; end status=0; Coord=[]; %---------------------------------------------------------------------- % switch ill_type % case 'transmit' % IMdif=(IM_o-IM); % case 'reflex' % IMdif=(IM)-(IM_o); % end IMdif=(IM_o-IM); if blur_fact~=0 IMdif_blur = F_IMfilt(IMdif,'gaussian',0,blur_fact*4*[1 1],blur_fact); else IMdif_blur=IMdif; end dif_thr = nsig_bin * std(IMdif_blur(:)); IMdif_pos=uint8((IMdif_blur>dif_thr)); IMdif_pos_big = bwareaopen(IMdif_pos,npxl_min); if sum(IMdif_pos_big(:))>npxl_min && sum(IMdif_pos_big(:))<npxl_max status=1; Coord = F_Mask2Cetroid(IMdif_pos_big,0); end %====================================================================== if pl figure colormap gray ax(1)=subplot(2,3,1); imagesc(IM) title('IM status=0') ax(2)=subplot(2,3,2); imagesc(IM_o) title('IMo') ax(3)=subplot(2,3,3); imshowpair(IM_o,IM) title('Comparison') ax(6)=subplot(2,3,6); imagesc(IMdif) title('IM dif') ax(5)=subplot(2,3,5); imagesc(IMdif_pos) title('IMdif pos') ax(4)=subplot(2,3,4); imagesc(IMdif_pos_big) title('IMdif pos big') linkaxes(ax,'xy') if status subplot(2,3,1) hold on plot(Coord(1),Coord(2),'.r'); plot(Coord(1),Coord(2),'or'); title('IM status=1') end end end function [Coord] = F_Mask2Cetroid(Mask,pl) % This function computes the centroid of the input Mask if nargin<2, pl=0; end if sum(Mask(:))~=0 X=(1:size(Mask,2))'; Y=(1:size(Mask,1))'; Ix=sum(Mask,1)'; Iy=sum(Mask,2); Coord=[sum(X.*Ix)/sum(Ix), sum(Y.*Iy)/sum(Iy)]; else Coord=[0 0]; end if pl figure colormap gray imagesc(Mask) hold on plot(Coord(1),Coord(2),'.r') plot(Coord(1),Coord(2),'ob') title(['Coord=[',num2str(Coord(1),'%.2f'),',',num2str(Coord(2),'%.2f'),']']) end end
github
NeuBtracker/acquisition-master
Acq_Controll.m
.m
acquisition-master/01_Acquisition/GUI_version/Acq_Controll.m
45,165
utf_8
eb7104ec7b6f60c56a4426acc59d9afc
function varargout = Acq_Controll(varargin) % ACQ_CONTROLL MATLAB code for Acq_Controll.fig % ACQ_CONTROLL, by itself, creates a new ACQ_CONTROLL or raises the existing % singleton*. % % H = ACQ_CONTROLL returns the handle to a new ACQ_CONTROLL or the handle to % the existing singleton*. % % ACQ_CONTROLL('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in ACQ_CONTROLL.M with the given input arguments. % % ACQ_CONTROLL('Property','Value',...) creates a new ACQ_CONTROLL or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before Acq_Controll_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Acq_Controll_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 Acq_Controll % Last Modified by GUIDE v2.5 18-May-2016 17:38:02 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Acq_Controll_OpeningFcn, ... 'gui_OutputFcn', @Acq_Controll_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before Acq_Controll is made visible. function Acq_Controll_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to Acq_Controll (see VARARGIN) % Choose default command line output for Acq_Controll handles.output = hObject; %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ handles.MessNumber=0; addpath(genpath('D:\ZT_Matlab')); load('D:\ZT_Matlab\Default_Fluoro_Camera_Params'); load('D:\ZT_Matlab\Default_Ref_Camera_Params'); handles.path4saving=create_saving_directory; display([num2str(handles.MessNumber) 'Path Greated']);handles.MessNumber=handles.MessNumber+1; set(handles.ref_exp_str,'String',num2str((RcP.ExposureTime)./1000)); set(handles.ref_bin_str,'String',num2str(RcP.BinningHorizontal)); set(handles.ref_gain_str,'String',num2str(RcP.Gain)); set(handles.flr_exp_str,'String',num2str((FcP.ExposureTime)*1000)); set(handles.flr_bin_str,'String',(FcP.AOIBinning)); set(handles.flr_gain_str,'String',(FcP.SimplePreAmpGainControl)); tp=num2str(fix(clock)); save(['Fluoro_Camera_Params_' num2str(tp)],'FcP'); save(['Ref_Camera_Params_' (tp)],'RcP'); save('Next_Fluoro_Camera_Params','FcP'); save('Next_Ref_Camera_Params','RcP'); system(' "D:\Program Files\MATLAB\R2015a\bin\matlab.exe" -nosplash -r "cd(''D:\ZT_Matlab\GUI_version''); run(''Image_Previewing_GUI.m'');" '); display([num2str(handles.MessNumber) 'Preview SUB_GUI started(Matlab2015a)']);handles.MessNumber=handles.MessNumber+1; fileID = fopen('Recording_ON_OFF_variable','w+');fwrite(fileID,uint8(0),'uint8');fclose(fileID); %handles.j1=batch(parcluster('local1'),'Scrip2Worker_FLUOR'); handles.j1=batch(parcluster('local1'),'Scrip2Worker_FLUOR_ExtraFast'); %Scrip2Worker_FLUOR%Scrip2Worker_FLUOR_ExtraFast %handles.j1=batch(parcluster('local1'),'Scrip2Worker_FLUOR4Solis'); %handles.j1=batch(parcluster('local1'),'Scrip2Worker_FLUOR_EF'); handles.j2=batch(parcluster('local2'),'Scrip2Worker_REF'); %handles.j3=batch(parcluster('local3'),'Scrip2Worker_DeleteOldFiles'); handles.j3=batch(parcluster('local3'),'Scrip2Worker_DeleteOldFiles4MoveRecordings'); display([num2str(handles.MessNumber) 'CameraS are acquiring <3']);handles.MessNumber=handles.MessNumber+1; devices = daq.getDevices; s = daq.createSession('ni'); addAnalogOutputChannel(s,'Dev1',0,'Voltage'); addAnalogOutputChannel(s,'Dev1',2,'Voltage'); xValue=0; yValue=0; outputSingleScan(s,[xValue yValue]); %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ % Update handles structure guidata(hObject, handles); % UIWAIT makes Acq_Controll wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = Acq_Controll_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in restrart_refcam_btn. function restrart_refcam_btn_Callback(hObject, eventdata, handles) % hObject handle to restrart_refcam_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load('D:\ZT_Matlab\Default_Ref_Camera_Params'); RcP.ExposureTime=1000.*str2double(get(handles.ref_exp_str,'String')); RcP.BinningHorizontal=str2double(get(handles.ref_bin_str,'String')); RcP.Gain= str2double(get(handles.ref_gain_str,'String')); tp=num2str(fix(clock)); save(['Ref_Camera_Params_' num2str(tp)],'RcP'); save('Next_Ref_Camera_Params','RcP'); cancel(handles.j2); handles.j2=batch(parcluster('local2'),'Scrip2Worker_REF'); display([handles.MessNumber 'Reflection Camera is Re-initialized']);handles.MessNumber=handles.MessNumber+1; % --- Executes on button press in restrart_fluorocam_btn. function restrart_fluorocam_btn_Callback(hObject, eventdata, handles) % hObject handle to restrart_fluorocam_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load('D:\ZT_Matlab\Default_Fluoro_Camera_Params'); FcP.ExposureTime=str2double(get(handles.flr_exp_str,'String'))./1000; FcP.AOIBinning=(get(handles.flr_bin_str,'String')); FcP.SimplePreAmpGainControl= (get(handles.flr_gain_str,'String')); tp=num2str(fix(clock)); save(['Fluoro_Camera_Params_' num2str(tp)],'FcP'); save('Next_Fluoro_Camera_Params','FcP'); cancel(handles.j1); handles.j1=batch(parcluster('local1'),'Scrip2Worker_FLUOR'); display([handles.MessNumber 'Fluorescence Camera is Re-initialized']);handles.MessNumber=handles.MessNumber+1; % --- Executes on button press in folder_description_pshb. function folder_description_pshb_Callback(hObject, eventdata, handles) % hObject handle to folder_description_pshb (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) exp_description=(get(handles.exp_description_str,'String')); fileID = fopen([handles.path4saving(1:12) handles.path4saving(13:16) '_' exp_description] ,'w'); fprintf(fileID,'%s',':)'); fclose(fileID); display([num2str(handles.MessNumber) 'Folder Description Generated']);handles.MessNumber=handles.MessNumber+1; % --- Executes on button press in load_registration_btn. function load_registration_btn_Callback(hObject, eventdata, handles) % hObject handle to load_registration_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in load_registration_btn. handles.ref2galvo_tmat=load(get(handles.tform2load_str,'String')); % PUT HERE AXIS UPDATE. display([num2str(handles.MessNumber) ':Prexisting Tranformation Matrix Loaded']); handles.MessNumber=handles.MessNumber+1; % --- Executes on button press in manual_reg_btn. function manual_reg_btn_Callback(hObject, eventdata, handles) % hObject handle to manual_reg_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) system('D:\ZT_Matlab\auto_opening_bash_shortcuts\Registraion.bat'); display([num2str(handles.MessNumber) ':SUB_VI for manual segmention opened']); handles.MessNumber=handles.MessNumber+1; % --- Executes on button press in load_est_reg_btn. function load_est_reg_btn_Callback(hObject, eventdata, handles) % hObject handle to load_est_reg_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) load('I:\NEXT_tform'); handles.ref2galvo_tmat=mytform; display([num2str(handles.MessNumber) ':Estimated transformation loaded']); handles.MessNumber=handles.MessNumber+1; guidata(hObject, handles); % --- Executes on button press in update_reg_preview_btn. function update_reg_preview_btn_Callback(hObject, eventdata, handles) % hObject handle to update_reg_preview_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.tform_str,'String',num2str(handles.ref2galvo_tmat.tdata.T)); org_test_imag=im2bw(256-imread('D:\ZT_Matlab\Functions\Smiley4Registration.tif')); org_test_imag(:,1:5)=256;org_test_imag(:,end-5:end)=256;org_test_imag(1:5,:)=256;org_test_imag(end-5:end,:)=256; for i=25:25:175 org_test_imag(:,i)=100; org_test_imag(i,:)=100;end myaffine2d=affine2d(handles.ref2galvo_tmat.tdata.Tinv); trs_test_imag=imresize(imwarp(org_test_imag,myaffine2d),0.01); max_dim=max(max(size(org_test_imag)),max(size(trs_test_imag))); im2show=zeros(max_dim,max_dim,3); im2show(1:size(org_test_imag,1),1:size(org_test_imag,2),1)=org_test_imag; im2show(1:size(trs_test_imag,1),1:size(trs_test_imag,2),3)=trs_test_imag; %figure;imshow(im2show); hh_r=handles.prv_reg_tfrom_axes; axes(hh_r);hhh_r=imshow(im2show); % --- Executes on button press in get_background_btn. function get_background_btn_Callback(hObject, eventdata, handles) % hObject handle to get_background_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) duration_of_averaging=str2double(get(handles.aver_dur_str,'String')); fileID = fopen('DatasetAnnotation','a');fprintf(fileID,'%s',... ['GettinBackgroundStarted' 'Time:' datestr(datetime('now')) '\n']);fclose(fileID); [Background]=get_background_data(duration_of_averaging); fileID = fopen('DatasetAnnotation','a');fprintf(fileID,'%s',... ['GettinBackgroundFinished' 'Time:' datestr(datetime('now')) '\n']);fclose(fileID); hh_r=handles.backgroun_n_roi_preview; axes(hh_r);hhh_r=imagesc(Background);axis image;axis off; imwrite(Background,'BackgroundImage.tiff'); handles.background=Background; display([num2str(handles.MessNumber) ':Background Image saved']); handles.MessNumber=handles.MessNumber+1; guidata(hObject, handles); % --- Executes on button press in select_roi_btn. function select_roi_btn_Callback(hObject, eventdata, handles) % hObject handle to select_roi_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %%based on michele's code % BKGR_o = uint8(handles.background); % figure % imagesc(BKGR_o); colormap gray [~,IM]=read_most_recent_fluoroANDreflection();%M size_R=size(IM);%M figure; imagesc(IM); title('Select X points on the edge of the arena') % [x,y] = ginput(3); % [arena_c, arena_r] = calc_circle([x(1) y(1)], [x(2) y(2)], [x(3) y(3)]); % %rectangle('Position', [arena_c(1)-arena_r,arena_c(2)-arena_r,2*arena_r,2*arena_r],'Curvature', [1,1], 'EdgeColor', 'r') % [x,y]=meshgrid(-(arena_c(1)-1):(size(BKGR_o,2)-arena_c(1)),-(arena_c(2)-1):(size(BKGR_o,1)-arena_c(2))); % MASK_1=uint8(((x.^2+y.^2)<=arena_r^2)); MASK_o = roipoly; MASK_o=uint8(MASK_o); imagesc(double(MASK_o).*double(IM)); % im2show=zeros(size(BKGR_o,1),size(BKGR_o,2),3); % im2show(:,:,1)=MASK_o.*imadjust(BKGR_o,stretchlim(BKGR_o,[0.25 0.97])).*256; % im2show(:,:,2)=imadjust(BKGR_o,stretchlim(BKGR_o,[0.02 0.98])).*256; hh_r=handles.backgroun_n_roi_preview; axes(hh_r);hhh_r=imagesc(im2show);axis image;axis off; display([num2str(handles.MessNumber) ':ROI selection finished']); handles.MessNumber=handles.MessNumber+1; handles.roi=MASK_o; imwrite(MASK_o,'CurrentROI.jpg'); time_stmp=datestr(datetime('now'),'yymmddHHMMSSFFF'); imwrite(MASK_o,['ROI_' time_stmp '.jpg']); guidata(hObject, handles); % --- Executes on button press in Tracking_Preview_tbtn. function Tracking_Preview_tbtn_Callback(hObject, eventdata, handles) % hObject handle to Tracking_Preview_tbtn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) devices = daq.getDevices;galvo_handle = daq.createSession('ni'); addAnalogOutputChannel(galvo_handle,'Dev1',0,'Voltage'); addAnalogOutputChannel(galvo_handle,'Dev1',2,'Voltage'); galvo_handle.Rate = 8000; reb_fact=1; display('TrackingPrevie') [~,IM]=read_most_recent_fluoroANDreflection();%M size_R=size(IM);%M %[Mask_logic]=F_IM2ArenaMask_112(IM,0,'ell_sep'); %handles.Mask=Mask_logic; % Hint: get(hObject,'Value') returns toggle state of Tracking_Preview_tbtn k=0;COORD=[]; Xg=0;Yg=0; while get(hObject,'Value')==1 htime=tic; k=k+1; [~,IM1]=read_most_recent_fluoroANDreflection();%M pause(0.05); [~,IM2]=read_most_recent_fluoroANDreflection();%M if ~(size(IM1)==size(IM2)); continue; end size_R=size(IM);%M % function_str=get(handles.used_algorithm_str,'String'); %try % Coord=feval(function_str,256-IM,256-BKGR,MASK,reb_fact,myfilter); % [Coord,IM_mask] = F_IM2COORD_200(IM,0,Mask_logic,1); [Coord_diff,Coord_f,Coord_i,Imdif] = F_IMdif2Coord_102(IM1, IM2, 0,... round(handles.sld_blr.Value), round(handles.sld_nsig.Value), round(handles.sld_minsize.Value), 'trasmit'); % [Coord_diff,Coord_f,Coord_i,IMdif] = F_IMdif2Coord_102(IM, IM_o, 0,blur_fact,nsig_bin ,npxl_min,'trasmit') %[Coord_diff,Coord_f,Coord_i,Imdif] = F_IMdif2Coord_102(IM1, IM2,0); Coord=Coord_f; %catch %end %Coord = F_IM2COORD_113(IM,BKGR,MASK,reb_fact,myfilter);%M COORD=[COORD;Coord]; %M xA=Coord(2); yA=Coord(1); [Xt, Yt]= tformfwd(handles.ref2galvo_tmat, yA, xA); %% if (abs(Xt-Xg)>0.05 || abs(Yt-Yg)>0.05) & ~(Coord==[0,0]) %If tracked (XY) away from galvo move galvos to new position display('GalvoMove') Xg=Xt; Yg=Yt; if Yg>10; Yg=10; end if Xg>10; xg=10; end if Xg<-10; Xg=-10; end if Yg<-10; Yg=-10; end outputSingleScan(galvo_handle,[Xg Yg]); end %display(num2str([Xg Yg Xt Yt xA yA])); hh_r=handles.tracking_preview_axis; axes(hh_r); title('Fish head position') hold off imagesc(Imdif,[-10 10]); colormap('spring');axis image;axis off; % %rectangle('Position', [arena_c(1)-arena_r,arena_c(2)-arena_r,2*arena_r,2*arena_r],'Curvature', [1,1], 'EdgeColor', 'r') hold on plot(yA,xA,'-*k') % xlim([0 size_R(2)]); ylim([0 size_R(1)]); %display(k) drawnow; set(handles.time4tracking_str,'String',[toc(htime)./1000 'ms']) fileID = fopen('GalvoXYpos','a');fprintf(fileID,'%s',... ['Xt:' num2str(Xt,4) 'Y:' num2str(Yt,4) ... 'Xg:' num2str(Xg,4) 'Yg:' num2str(Yg,4) 'Time:' datestr(datetime('now')) '\n']);fclose(fileID); end clear galvo_handle % --- Executes on button press in save_tracking_params4worker_btn. function save_tracking_params4worker_btn_Callback(hObject, eventdata, handles) % hObject handle to save_tracking_params4worker_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) par4tracking.background=handles.background; par4tracking.roi=handles.roi; par4tracking.used_algorithm_str=handles.used_algorithm_str; par4tracking.ref2galvo_tmat=handles.ref2galvo_tmat; save('Tracking_Params.mat','par4tracking'); display([num2str(handles.MessNumber) ':ParamsSaved. Ready for auto-tracking']); handles.MessNumber=handles.MessNumber+1; % --- Executes on button press in start_rec_tbtn. function start_rec_tbtn_Callback(hObject, eventdata, handles) % hObject handle to start_rec_tbtn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) fileID = fopen('Recording_ON_OFF_variable','w+');fwrite(fileID,uint8(1),'uint8');fclose(fileID); display([num2str(handles.MessNumber) ':REC started']); handles.MessNumber=handles.MessNumber+1; % --- Executes on button press in stop_rec_btn. function stop_rec_btn_Callback(hObject, eventdata, handles) % hObject handle to stop_rec_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) fileID = fopen('Recording_ON_OFF_variable','w+');fwrite(fileID,uint8(0),'uint8');fclose(fileID); set(handles.start_rec_tbtn,'Value',0); display([num2str(handles.MessNumber) ':REC stoped']); handles.MessNumber=handles.MessNumber+1; guidata(hObject, handles); % --- Executes on button press in update_dataset_annotation_btn. function update_dataset_annotation_btn_Callback(hObject, eventdata, handles) % hObject handle to update_dataset_annotation_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) fileID = fopen('DatasetAnnotation','a');fprintf(fileID,'%s',... [char(get(handles.next_annotation_str,'String')) 'Time:' datestr(datetime('now')) '\n']);fclose(fileID); % --- Executes on button press in start_autotracking_tbtn. function start_autotracking_tbtn_Callback(hObject, eventdata, handles) % hObject handle to start_autotracking_tbtn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.j4=batch(parcluster('local4'),'Scrip2Worker_GALVOS_debugi'); display([num2str(handles.MessNumber) ':AutTracking started']); handles.MessNumber=handles.MessNumber+1; guidata(hObject, handles); % --- Executes on button press in stop_auto_tracking_btn. function stop_auto_tracking_btn_Callback(hObject, eventdata, handles) % hObject handle to stop_auto_tracking_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of stop_auto_tracking_btn cancel(handles.j4); display([num2str(handles.MessNumber) ':AutTracking Stopped']); handles.MessNumber=handles.MessNumber+1; set(handles.start_autotracking_tbtn,'Value',0); guidata(hObject, handles); % --- Executes on button press in start_joy_controll_tbtn. function start_joy_controll_tbtn_Callback(hObject, eventdata, handles) % hObject handle to start_joy_controll_tbtn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of start_joy_controll_tbtn devices = daq.getDevices s = daq.createSession('ni') addAnalogOutputChannel(s,'Dev1',0,'Voltage'); addAnalogOutputChannel(s,'Dev1',2,'Voltage'); s.Rate = 8000 %% Also joystic joy = vrjoystick(1) figure; while get(hObject,'Value')==1; [axes, buttons, povs] = read(joy); if buttons(1)==1 xValue = +axes(2)*10; yValues = -axes(1)*10; % if xValue>10; xValue=10;end % if xValue<-10;xValue=-10;end % if yValues>10;yValues=10;end % if yValues<-10;yValues=-10;end outputSingleScan(s,[xValue yValues]); plot(xValue,yValues,'or','MarkerSize',10);xlim([-10 10]);ylim([-10 10]);drawnow; end end %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %% DO NOT TOUCH BELLOW THIS POINT. %% %$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ function exp_description_str_Callback(hObject, eventdata, handles) % hObject handle to exp_description_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of exp_description_str as text % str2double(get(hObject,'String')) returns contents of exp_description_str as a double % --- Executes during object creation, after setting all properties. function exp_description_str_CreateFcn(hObject, eventdata, handles) % hObject handle to exp_description_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in f_gain_listbox. function f_gain_listbox_Callback(hObject, eventdata, handles) % hObject handle to f_gain_listbox (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns f_gain_listbox contents as cell array % contents{get(hObject,'Value')} returns selected item from f_gain_listbox % --- Executes during object creation, after setting all properties. function f_gain_listbox_CreateFcn(hObject, eventdata, handles) % hObject handle to f_gain_listbox (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: listbox controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function f_exptime_str_Callback(hObject, eventdata, handles) % hObject handle to f_exptime_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of f_exptime_str as text % str2double(get(hObject,'String')) returns contents of f_exptime_str as a double % --- Executes during object creation, after setting all properties. function f_exptime_str_CreateFcn(hObject, eventdata, handles) % hObject handle to f_exptime_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in f_bin_listbox. function f_bin_listbox_Callback(hObject, eventdata, handles) % hObject handle to f_bin_listbox (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns f_bin_listbox contents as cell array % contents{get(hObject,'Value')} returns selected item from f_bin_listbox % --- Executes during object creation, after setting all properties. function f_bin_listbox_CreateFcn(hObject, eventdata, handles) % hObject handle to f_bin_listbox (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: listbox controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ref_exp_str_Callback(hObject, eventdata, handles) % hObject handle to ref_exp_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ref_exp_str as text % str2double(get(hObject,'String')) returns contents of ref_exp_str as a double % --- Executes during object creation, after setting all properties. function ref_exp_str_CreateFcn(hObject, eventdata, handles) % hObject handle to ref_exp_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ref_bin_str_Callback(hObject, eventdata, handles) % hObject handle to ref_bin_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ref_bin_str as text % str2double(get(hObject,'String')) returns contents of ref_bin_str as a double % --- Executes during object creation, after setting all properties. function ref_bin_str_CreateFcn(hObject, eventdata, handles) % hObject handle to ref_bin_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function ref_gain_str_Callback(hObject, eventdata, handles) % hObject handle to ref_gain_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ref_gain_str as text % str2double(get(hObject,'String')) returns contents of ref_gain_str as a double % --- Executes during object creation, after setting all properties. function ref_gain_str_CreateFcn(hObject, eventdata, handles) % hObject handle to ref_gain_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function flr_gain_str_Callback(hObject, eventdata, handles) % hObject handle to flr_gain_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of flr_gain_str as text % str2double(get(hObject,'String')) returns contents of flr_gain_str as a double % --- Executes during object creation, after setting all properties. function flr_gain_str_CreateFcn(hObject, eventdata, handles) % hObject handle to flr_gain_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function flr_bin_str_Callback(hObject, eventdata, handles) % hObject handle to flr_bin_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of flr_bin_str as text % str2double(get(hObject,'String')) returns contents of flr_bin_str as a double % --- Executes during object creation, after setting all properties. function flr_bin_str_CreateFcn(hObject, eventdata, handles) % hObject handle to flr_bin_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function flr_exp_str_Callback(hObject, eventdata, handles) % hObject handle to flr_exp_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of flr_exp_str as text % str2double(get(hObject,'String')) returns contents of flr_exp_str as a double % --- Executes during object creation, after setting all properties. function flr_exp_str_CreateFcn(hObject, eventdata, handles) % hObject handle to flr_exp_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function tform2load_str_Callback(hObject, eventdata, handles) % hObject handle to tform2load_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of tform2load_str as text % str2double(get(hObject,'String')) returns contents of tform2load_str as a double % --- Executes during object creation, after setting all properties. function tform2load_str_CreateFcn(hObject, eventdata, handles) % hObject handle to tform2load_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton6. function pushbutton6_Callback(hObject, eventdata, handles) % hObject handle to pushbutton6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on slider movement. function sld_blr_Callback(hObject, eventdata, handles) % hObject handle to sld_blr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function sld_blr_CreateFcn(hObject, eventdata, handles) % hObject handle to sld_blr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on button press in checkbox2. function checkbox2_Callback(hObject, eventdata, handles) % hObject handle to checkbox2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox2 function next_annotation_str_Callback(hObject, eventdata, handles) % hObject handle to next_annotation_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of next_annotation_str as text % str2double(get(hObject,'String')) returns contents of next_annotation_str as a double % --- Executes during object creation, after setting all properties. function next_annotation_str_CreateFcn(hObject, eventdata, handles) % hObject handle to next_annotation_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton13. function pushbutton13_Callback(hObject, eventdata, handles) % hObject handle to pushbutton13 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton14. function pushbutton14_Callback(hObject, eventdata, handles) % hObject handle to pushbutton14 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) function edit14_Callback(hObject, eventdata, handles) % hObject handle to edit14 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit14 as text % str2double(get(hObject,'String')) returns contents of edit14 as a double % --- Executes during object creation, after setting all properties. function edit14_CreateFcn(hObject, eventdata, handles) % hObject handle to edit14 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton15. function pushbutton15_Callback(hObject, eventdata, handles) % hObject handle to pushbutton15 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) function edit15_Callback(hObject, eventdata, handles) % hObject handle to edit15 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit15 as text % str2double(get(hObject,'String')) returns contents of edit15 as a double % --- Executes during object creation, after setting all properties. function edit15_CreateFcn(hObject, eventdata, handles) % hObject handle to edit15 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on slider movement. function slider2_Callback(hObject, eventdata, handles) % hObject handle to slider2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function slider2_CreateFcn(hObject, eventdata, handles) % hObject handle to slider2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function sld_nsig_Callback(hObject, eventdata, handles) % hObject handle to sld_nsig (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function sld_nsig_CreateFcn(hObject, eventdata, handles) % hObject handle to sld_nsig (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function used_algorithm_str_Callback(hObject, eventdata, handles) % hObject handle to used_algorithm_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of used_algorithm_str as text % str2double(get(hObject,'String')) returns contents of used_algorithm_str as a double % --- Executes during object creation, after setting all properties. function used_algorithm_str_CreateFcn(hObject, eventdata, handles) % hObject handle to used_algorithm_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in togglebutton2. function togglebutton2_Callback(hObject, eventdata, handles) % hObject handle to togglebutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of togglebutton2 % --- Executes when uipanel3 is resized. function uipanel3_SizeChangedFcn(hObject, eventdata, handles) % hObject handle to uipanel3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton17. function pushbutton17_Callback(hObject, eventdata, handles) % hObject handle to pushbutton17 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton18. function pushbutton18_Callback(hObject, eventdata, handles) % hObject handle to pushbutton18 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in save_reg_str. function save_reg_str_Callback(hObject, eventdata, handles) % hObject handle to save_reg_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) function edit17_Callback(hObject, eventdata, handles) % hObject handle to edit17 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit17 as text % str2double(get(hObject,'String')) returns contents of edit17 as a double % --- Executes during object creation, after setting all properties. function edit17_CreateFcn(hObject, eventdata, handles) % hObject handle to edit17 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton22. function pushbutton22_Callback(hObject, eventdata, handles) % hObject handle to pushbutton22 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton23. function pushbutton23_Callback(hObject, eventdata, handles) % hObject handle to pushbutton23 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) function aver_dur_str_Callback(hObject, eventdata, handles) % hObject handle to aver_dur_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of aver_dur_str as text % str2double(get(hObject,'String')) returns contents of aver_dur_str as a double % --- Executes during object creation, after setting all properties. function aver_dur_str_CreateFcn(hObject, eventdata, handles) % hObject handle to aver_dur_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in togglebutton3. function togglebutton3_Callback(hObject, eventdata, handles) % hObject handle to togglebutton3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of togglebutton3 % --- Executes on slider movement. function sld_minsize_Callback(hObject, eventdata, handles) % hObject handle to sld_minsize (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function sld_minsize_CreateFcn(hObject, eventdata, handles) % hObject handle to sld_minsize (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end
github
NeuBtracker/acquisition-master
Image_Previewing_GUI.m
.m
acquisition-master/01_Acquisition/GUI_version/Image_Previewing_GUI.m
16,485
utf_8
937bf2a71a48d2e5b6a58fe2b4da4b86
function varargout = Image_Previewing_GUI(varargin) % IMAGE_PREVIEWING_GUI MATLAB code for Image_Previewing_GUI.fig % IMAGE_PREVIEWING_GUI, by itself, creates a new IMAGE_PREVIEWING_GUI or raises the existing % singleton*. % % H = IMAGE_PREVIEWING_GUI returns the handle to a new IMAGE_PREVIEWING_GUI or the handle to % the existing singleton*. % % IMAGE_PREVIEWING_GUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in IMAGE_PREVIEWING_GUI.M with the given input arguments. % % IMAGE_PREVIEWING_GUI('Property','Value',...) creates a new IMAGE_PREVIEWING_GUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before Image_Previewing_GUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Image_Previewing_GUI_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 Image_Previewing_GUI % Last Modified by GUIDE v2.5 31-Oct-2015 19:42:27 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Image_Previewing_GUI_OpeningFcn, ... 'gui_OutputFcn', @Image_Previewing_GUI_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before Image_Previewing_GUI is made visible. function Image_Previewing_GUI_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to Image_Previewing_GUI (see VARARGIN) % Choose default command line output for Image_Previewing_GUI handles.output = hObject; %!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! %% Make sure you have access to all functions/subfucntions addpath(genpath('D:\ZT_Matlab')); %% Move to spooling disk and find "live-recording" directory cd('K:\'); fileID = fopen('Path2SaveNextExperiment','r');livepath=fscanf(fileID,'%s');fclose(fileID); handles.livepath=livepath; cd(livepath); %% %!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! % Update handles structure guidata(hObject, handles); % UIWAIT makes Image_Previewing_GUI wait for user response (see UIRESUME) % uiwait(handles.figure1); %!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! % --- Executes on button press in live_upd_toggle. function live_upd_toggle_Callback(hObject, eventdata, handles) % hObject handle to live_upd_toggle (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of live_upd_toggle set(handles.path_string,'String',handles.livepath); fi_flag=0; t_pr=0; MouseCordb=0; send_location=0; % k=0; while get(handles.live_upd_toggle,'Value')==1; t_pr=t_pr+1; % try [F,R,Fnum,Rnum]=read_most_recent_fluoroANDreflection(); c_upper_limit_r=get(handles.clim_up_ref,'Value'); c_lower_limit_r=get(handles.clim_down_ref,'Value'); c_upper_limit_f=get(handles.clim_up_flr,'Value'); c_lower_limit_f=get(handles.clim_down_flr,'Value'); if fi_flag==0; hh_r=handles.im_axis_ref; axes(hh_r);hhh_r=imshow(R,[c_lower_limit_r c_upper_limit_r]); hh_f=handles.im_axis_flr; axes(hh_f);hhh_f=imshow(F,[c_lower_limit_f c_upper_limit_f]); fi_flag=1; drawnow; else set(hhh_r,'CData',R); set(hh_r,'CLim',[c_lower_limit_r c_upper_limit_r]); title(hh_r,['Reflection Image\_Lim:[' num2str(c_lower_limit_r) '-' num2str(c_upper_limit_r) '] Frame' num2str(Rnum)]); drawnow limitrate; set(hhh_f,'CData',F); set(hh_f,'CLim',[c_lower_limit_f c_upper_limit_f]); title(hh_f,['Fluoro Image\_Lim:[' num2str(c_lower_limit_f) '-' num2str(c_upper_limit_f) '] Frame' num2str(Fnum)]); drawnow limitrate; try try delete(h4_r); delete(h5_r); catch; end trackingImageF_ID = fopen('TrackingXYimage_current','r');XY_Imag_TRC=fread(trackingImageF_ID,[1,2],'uint16');fclose(trackingImageF_ID); trackingGalvoF_ID = fopen('TrackingXYgalvo','r');XY_Galvo_TRC=fread(trackingGalvoF_ID,[1,2],'uint16');fclose(trackingGalvoF_ID); hold(hh_r,'on'); h4_r=plot(hh_r,XY_Imag_TRC(1),XY_Imag_TRC(2),'or','MarkerSize',7); h5_r=plot(hh_r,XY_Galvo_TRC(1),XY_Galvo_TRC(2),'*g','MarkerSize',12); drawnow limitrate; catch end % set(hhh_r,'ButtonDownFcn', 'send_location=1'); MouseCordn= get(hh_r, 'currentpoint'); %MouseCordn=[MouseCordn(1,1) MouseCordn(1,2)] if ~sum(sum(MouseCordb-MouseCordn))==0 send_location=1; end set(handles.Send_Coord,'String',[num2str(send_location)]); set(handles.Coord_X,'String',[num2str(MouseCordn(1))]); set(handles.Coord_Y,'String',[num2str(MouseCordn(2))]); if send_location==1 % MouseCord; % display(MouseCord); fileID = fopen('MouseOveride','w+');fwrite(fileID,uint16(MouseCordn),'uint16');fclose(fileID); send_location=0; end MouseCordb=MouseCordn; end % catch display(['Updating during like view has issues...' num2str(t_pr)]; end end % --- Executes on button press in upd_path_button. function upd_path_button_Callback(hObject, eventdata, handles) % hObject handle to upd_path_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) display('Preloading images... Please wait') recorded_path=get(handles.path_string,'String'); cd(recorded_path); sizeR=fread(fopen('Size_RefImag'),[1 2],'uint16'); sizeF=fread(fopen('Size_FluoroImag'),[1 2],'uint16'); All_refl_imag=dir('R_*'); All_fluoro_imag=dir('F_*'); f_frames_number=length(All_fluoro_imag); i_f_frames=1; fi_flag=0; display('Images Preloades. Preview will start soon...') set(handles.total_frames_str,'String',num2str(f_frames_number)); MouseCordPreviews=[0]; k=0; while get(handles.upd_path_button,'Value')==1; i_0to1=get(handles.time_slider,'Value'); i_f_frames=round(i_0to1*f_frames_number); if get(handles.play_rec_toggle,'Value')==0; i_0to1=get(handles.time_slider,'Value'); i_f_frames=round(i_0to1*f_frames_number); else speed_multipler=str2double(get(handles.playback_speed_str,'String')); i_f_frames=i_f_frames+1*speed_multipler; i_0to1=i_f_frames./f_frames_number; if i_f_frames>=f_frames_number i_f_frames=1; i_0to1=i_f_frames./f_frames_number; end set(handles.time_slider,'Value',i_0to1); end set(handles.current_frame_str,'String',[num2str(i_0to1.*100)]); %% Find correspondance between frames % display(i./f_frames_number) i_f=round((length(All_fluoro_imag)*i_f_frames./f_frames_number)); i_r=round((length(All_refl_imag)*i_f_frames./f_frames_number)); try %% Load images. Rfile=fopen(All_refl_imag(i_r).name);R=fread(Rfile,sizeR,'uint8');fclose(Rfile); Ffile=fopen(All_fluoro_imag(i_f).name);F=fread(Ffile,sizeF,'uint16');fclose(Ffile); catch end %% Show images. c_upper_limit_r=get(handles.clim_up_ref,'Value'); c_lower_limit_r=get(handles.clim_down_ref,'Value'); c_upper_limit_f=get(handles.clim_up_flr,'Value'); c_lower_limit_f=get(handles.clim_down_flr,'Value'); if fi_flag==0; hh_r=handles.im_axis_ref; axes(hh_r);hhh_r=imshow(R,[c_lower_limit_r c_upper_limit_r]); hh_f=handles.im_axis_flr; axes(hh_f);hhh_f=imshow(F,[c_lower_limit_f c_upper_limit_f]); fi_flag=1; drawnow; else set(hhh_r,'CData',R); set(hh_r,'CLim',[c_lower_limit_r c_upper_limit_r]); title(hh_r,['Reflection Image\_Lim:[' num2str(c_lower_limit_r) '-' num2str(c_upper_limit_r) '] Perc' num2str(i_0to1) 'N' All_refl_imag(i_r).name ]); drawnow limitrate; set(hhh_f,'CData',F); set(hh_f,'CLim',[c_lower_limit_f c_upper_limit_f]); title(hh_f,['Fluoro Image\_Lim:[' num2str(c_lower_limit_f) '-' num2str(c_upper_limit_f) '] Perc' num2str(i_0to1) 'N' All_fluoro_imag(i_f).name ]); drawnow limitrate; end end %!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! % --- Outputs from this function are returned to the command line. function varargout = Image_Previewing_GUI_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on slider movement. function clim_up_ref_Callback(hObject, eventdata, handles) % hObject handle to clim_up_ref (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function clim_up_ref_CreateFcn(hObject, eventdata, handles) % hObject handle to clim_up_ref (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function clim_down_ref_Callback(hObject, eventdata, handles) % hObject handle to clim_down_ref (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function clim_down_ref_CreateFcn(hObject, eventdata, handles) % hObject handle to clim_down_ref (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function clim_up_flr_Callback(hObject, eventdata, handles) % hObject handle to clim_up_flr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function clim_up_flr_CreateFcn(hObject, eventdata, handles) % hObject handle to clim_up_flr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function clim_down_flr_Callback(hObject, eventdata, handles) % hObject handle to clim_down_flr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function clim_down_flr_CreateFcn(hObject, eventdata, handles) % hObject handle to clim_down_flr (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function time_slider_Callback(hObject, eventdata, handles) % hObject handle to time_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function time_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to time_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function path_string_Callback(hObject, eventdata, handles) % hObject handle to path_string (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of path_string as text % str2double(get(hObject,'String')) returns contents of path_string as a double % --- Executes during object creation, after setting all properties. function path_string_CreateFcn(hObject, eventdata, handles) % hObject handle to path_string (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in play_rec_toggle. function play_rec_toggle_Callback(hObject, eventdata, handles) % hObject handle to play_rec_toggle (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of play_rec_toggle function playback_speed_str_Callback(hObject, eventdata, handles) % hObject handle to playback_speed_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of playback_speed_str as text % str2double(get(hObject,'String')) returns contents of playback_speed_str as a double % --- Executes during object creation, after setting all properties. function playback_speed_str_CreateFcn(hObject, eventdata, handles) % hObject handle to playback_speed_str (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end
github
xiashang0624/electrochemical_simulation-master
CDI_2D_Demo.m
.m
electrochemical_simulation-master/CDI_2D_Demo.m
29,273
utf_8
ca5de5c008d8a778fe031ee65181fc9a
%% Capacitive deionization 2D simulation % % Developed by: Xia Shang % Advisors: Kyle Smith, Roland Cusick % Copyright: Xia Shang, Roland Cusick, Kyle Smith % University of Illinois at Urbana-Champaign % All rights reserved. % % Funded by: US National Science Foundation Award No. 1605290 entitiled % "SusChEM: Increasing Access to Sustainable Freshwater Resources with % Membrane Capacitve Deionization", and Joint Center for Energy Storage % Research, an Energy Innovation Hub funded by the U.S. Department of % Energy, Office of Science, Basic Energy Sciences. % % Redistribution and use in source and binary forms, with or % without modification, are permitted provided that the following % conditions are met: % % * Redistributions of source code must retain the above copyright notice, % this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above % copyright notice, this list of conditions and the following % disclaimer in the documentation and/or other materials provided % with the distribution. % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, % THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR % PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR % CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, % EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, % PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, % OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF % LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING % NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS % SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. function [T_r, V_cell, C_eff] = CDI_2D_Demo(C0, Q_FC,... J, Q_fix_pos, Q_fix_neg,... V_max, V_min, Cycle_limit, L_FC, T_pos, T_neg, ... T_FC, R_FC, R_Macro, R_Micro, dt_record) %clc; clear; close all; tic %% cell operating parameters %C0=30; % mM, influent concentration %V_max=200; % mV, cell voltage %V_min = 0; %J= 1; % mA/cm2, projected area %Cycle_limit = 2; % -, total cycle number %Q_FC = 0.0736; % mL/min, flow rate suggested range (0.05 - 1 mL/min) %% Cell design T_CC1 = 0; % um, thickness of current collector 1 T_pos = 450; % um, thickness of Cathod T_FC = 250; % um, thickness of Flow channel T_neg = 450; % um, thickness of Anode T_CC2 = 0; % um, thickness of current collector 2 L_FC = 9; % cm, Length of flow channel W_FC = 2; % cm, Width of flow channel V_internal = 0.455; % mL, volume of a well mixed internal tank, dead-volume %% Electrode Porosities M_e = 0.4214; % g/cm3; electrode desity C_Measured = 49; % F/g; Stern-layer capacitance, this value can be initially estimated based on the whole cell capacitance measured in CV at low scan rate (e.g., < 1mV/s) in 1 M NaCl %Q_fix_pos = -4; % C/cm3, immobile charge density %Q_fix_neg = 0; % C/cm3, immobile charge density uatt=0; % -, attracitve chemical force using in the mD theory R_Macro = 0.4; % Macropore ratio R_Micro = 0.2; % Micropore ratio R_FC = 0.7; % Average porosity of flow channel R_e= 1-(1-R_Macro)*(1-R_Micro); % Total porosity of electrode %% numerical parameters dt = 0.008; % s, dt dx = 25; % um dy=200*L_FC; % um %% data storage to reduce membrane usage tmin = 0; % s, starting time tmax =round(800*Cycle_limit*1.2/J); % s, ending time, this value can be adjusted dt_record=1; % s, time step to record data Nt=round((tmax-tmin)/dt); % total number of nodes in time Nt_r = round((tmax-tmin)/dt_record); % no. of stored nodes in time % other related parameters E_Dielectric = 80.4; % dielectric constant of water E_Permittivity = 8.85*10^-12; % F/m; permittivity of free space r_Na = 0.16; % nm, radius of Na+ ion d_H2O = 0.29; % nm, diameter of a H2O molecule d_Helmholtz = (r_Na + d_H2O)/10^9; % m c_Helmholtz = E_Dielectric*E_Permittivity/d_Helmholtz; % F/m2 A_effective = C_Measured/c_Helmholtz; % m2/g; effective surface area Temp = 298.16; % K, temperature KB = 1.38*10^-23; % C V K-1; Boltzmann constant e = 1.602*10^-19; % C; Na = 6.02*10^23; % mol-1; F = 96485.3365; % C mol-1; Faraday constant M_NaCl=58.44; % g/mole z_a =-1; % valence of anion z_c = 1; % valence of cation q_a = 1; % charge of anion q_c = 1; % charge of cation t_Na = 0.5; % transference number of Na+ t_Cl = 1-t_Na; % transference number of Cl- % Diffusion coefficient D_NaCl = 1.61*10^-5; % cm2/s; diffusion coeff. in spacer D_e=D_NaCl*10^8*R_Macro^0.5; % um2/s, effective diffusion coefficient in electrode D_FC = D_NaCl*10^8*R_FC^0.5; % um2/s, effective diffusion coefficient D_mid = 2*D_FC*D_e/(D_FC+D_e); % resistance R_contact = 9; % ohm cm2 R_electrode = 0.1625; % ohm*m % flow rate and mixing in the dead-volume v_FC = Q_FC/T_FC*10^4/W_FC/60*10^4; % um/s, flow velocity, assume uniform flow profile in the cross section k_mix = Q_FC/60/V_internal; % /s, factor used in the equation accounting for the effect of mixing in the dead-volume %% Leakage current sub-models % B-V model parameter a_ele = 11000; % cm2/cm3 electrode volume I0_C = 2.5*10^-7; % mA/cm2 I0_O2 = 5.5 *10^-7; % mA/cm2 E0_C = 0.207; % V, vs SHE E0_O2 = 0.81; % V, vs SHE RT_F = 0.0592; % V a_C = 0.5; a_O2 = 0.5; E0_An = 0.5419; % V, vs SHE, measured at equlibrium condition when two electrodes were short circuited E0_Ca = 0.5419; % V, vs SHE, measured at equlibrium condition when two electrodes were short circuited % imperical limiting current model parameter E_half=0.124; % V, vs SHE IL_O2=3.558; % mA/cm3-electrode %% Indexing % Current collector xmin_CC1 = 0; % um, minimum value of x xmax_CC1 = (xmin_CC1+T_CC1)/dx; % um, maximum value of x %Postive electrode xmin_pos = xmax_CC1; % left boundary node point of the positive electrode xmax_pos = (xmin_pos+T_pos)/dx; % right boundary node point of the positive electrode L_pos = L_FC; % cm, length of the positive electrode W_pos = W_FC; % cm, width of the positive electrode A_edge = 0; % cm2, area of cathod in the triangular spot A_pos = L_pos*W_pos+A_edge; % cm2, area of projected area of the positive electrode V_pos = T_pos/10000 * A_pos; % cm^3, volume of the positive electrode %Flow channel xmin_FC = xmax_pos; % left boundary node point of FC xmax_FC = xmin_FC+T_FC/dx; % right boundary node point of FC A_edge_FC = 0; % cm2, area of flow channel in the triangular spot A_FC = L_FC*W_FC +A_edge_FC; % cm2, projected area of flow channel Vol_FC = T_FC/10^4*A_FC/1000*R_FC; % L, Volume of flow channel %Negative electrode xmin_neg = xmax_FC; % left boundary node point of the negtive electrode xmax_neg = xmin_neg+T_neg/dx; % right boundary node point of the negtive electrode %Current collector 2 xmin_CC2 = xmax_neg; % um, minimum value of x xmax_CC2 = xmin_CC2+T_CC2/dx; % um, maximum value of x % indexing of vectors and matrix nx = xmax_CC2-xmin_CC1; % total number of compartments in the cell ny=L_FC*10000/dy; % ny N=T_pos/dx; % total number of compartments in the electrode N_FC=T_FC/dx; % total number of compartments in the FC V_i = W_pos*dy/10000*dx/10000; % cm3, volume per compartment x_ind=[1:xmax_pos, xmin_neg+1:xmax_neg]; % indexing for the electrodes FC_ind=[xmax_pos+1:xmin_neg]; % indexing for the flow channel FC_ind_A = zeros(numel(FC_ind)*ny,1); % indexing for the flow channel in 2D for i=1:ny FC_ind_A(1+(i-1)*numel(FC_ind):i*numel(FC_ind)) = FC_ind + (i-1)*nx; end %% Initiation Vt=zeros(Nt_r, 4); % mV, 1st column: electrode voltage, 2nd column: IEM resistance voltage; 3rd column: spacer resistance voltage; 4th total voltage T0=0; % s previous time step T1=0; % s current time step T_r=zeros(Nt_r,1); % s, reduced time domain for data storage Cycle_index=zeros(100,1); % index of cycles Discharge_index=zeros(100,1); % index of discharge cycles VV_0 = zeros(nx,ny); % mV, Voltage matrix V_N = zeros (nx, ny); % mV, Voltage matrix of ionic resistance in the electrode II_0 = zeros(nx,ny); % mA, Current matrix: current passing each capacitor II_1 = zeros(nx,ny); % mA, Current matrix: current passing each capacitor Ri_M =zeros(nx,ny); % ohm, individual ionic resistor matrix Re_M =zeros(nx,ny); % ohm, individual electronic resistor matrix Cond_M = zeros(nx,ny); % Conductivity matrix IL = zeros(nx,ny); % mA, Current matrix: current passing each resistor in parallel to the capacitor I_Ri = zeros (nx,ny); % mA, Current matrix : current passing each ionic resistor I_Re = zeros (nx,ny); % mA, Current matrix: current passing each electronic resistor C_0 = zeros (nx,ny); % mM, Concentration matrix coresponding to the capacitor matrix C_1 = zeros (nx,ny); % mM, Concentration matrix coresponding to the capacitor matrix C1 = zeros(nx,ny); % mM, concentration matrix C_re =zeros(nx,ny,Nt_r); % mM, recorded concentration tensor II_re =zeros(nx,ny,Nt_r); % mA, recorded current tensor Q_mi_re = zeros(nx,ny,Nt_r); % mV, recorded charge density tensor IL_re = zeros(nx,ny,Nt_r); % mA, recorded leakage density tensor Qt_0 = zeros (nx,ny); % C, charge density matrix Qt_1 = zeros (nx,ny); % C, charge density matrix Qt_e=Qt_0; % C, charge density matrix Qt_mi=-Qt_0; % C, charge density matrix V_D=zeros(nx,ny); % mV, Donnan potential matrix C_mi_0=zeros(nx,ny); % mmol-L micropores, ionic charges matrix inside micropores C_mi_1=zeros(nx,ny); % mmol-L micropores, ionic charges matrix inside micropores C_eff = zeros(Nt_r,1); % mM avg effulent concentration per batch C_eff_mix = C_eff; % mM, true effluent considering the effect of well mixed condition at the end of effluent % Initial concentration and polarization C_0(:,:)=C0; % mM, Initial concentration profile in the electrode phase C_1(:,:)=C0; % mM, Initial concentration profile in the electrode phase VV_0(:,:)=0; % mV, Initial polarization profile in the electrode phase % determine the inital current distribution across the cell I = J*A_FC; % mA, total current applied indx=(1:nx)'; indx_1=circshift(indx,1); indx_0=circshift(indx,-1); indy=(1:ny)'; indy_1=circshift(indy,1); indy_0=circshift(indy,-1); % calculate ionic conductivity S/cm Cond_M(:,:)=2*D_NaCl*C_0(:,:)/KB/Temp/1000000*F*e*R_e^1.5; Cond_M(xmax_pos+1:xmin_neg,:)=2*D_NaCl*C_0(xmax_pos+1:xmin_neg,:)/KB/Temp/1000000*F*e*R_FC^1.5; Cond_M(1:xmax_pos-1,:)=2.*Cond_M(1:xmax_pos-1,:).*Cond_M(indx_0(1:xmax_pos-1),:)./(Cond_M(1:xmax_pos-1,:)+Cond_M(indx_0(1:xmax_pos-1),:)); Cond_M(xmin_neg+1:xmax_neg-1,:)=2.*Cond_M(xmin_neg+1:xmax_neg-1,:).*Cond_M(indx_0(xmin_neg+1:xmax_neg-1),:)./(Cond_M(xmin_neg+1:xmax_neg-1,:)+Cond_M(indx_0(xmin_neg+1:xmax_neg-1),:)); Ri_M(:,:) = 1./Cond_M(:,:)*dx/dy/W_FC; Ri_S=zeros(ny,1); Ri_S(:)=sum(Ri_M(xmax_pos:xmin_neg,:)); % calculate the current distribution in the electrode M_I = zeros(ny,ny); % Coefficient matrix for current distribution in the electrode M_I(1:(ny+1):(end-ny))=Ri_S(1:(end-1)); M_I((ny+1):(ny+1):end)=-Ri_S(2:end); M_I(ny,:)=1; S_I=sparse(M_I); B_I =zeros(ny,1); % vector for current distribution in the electrode B_I(1:end-1)=VV_0(xmax_pos,indy_0(1:(end-1)))-VV_0(xmin_neg+1,indy_0(1:(end-1)))-VV_0(xmax_pos,1:(end-1))+VV_0(xmin_neg+1,1:(end-1)); B_I(end)=I; I_y=S_I\B_I; % solve the current distribution in the electrode in the y-direction % calculate the leakage current in the positive electrode Oe = 0; % set the electronic resistance %IL(1:xmax_pos,1)=a_ele*I0_C*V_i*exp(a_C/RT_F.*(VV(1:xmax_pos,1)/1000+E0_An-E0_C)); IL(1:xmax_pos,:)=0; % Update the current distribution in the positive electrode II_0(2:xmax_pos-1, :)=-IL(2:xmax_pos-1,:)+(VV_0(indx_0(2:xmax_pos-1),:)-VV_0(indx(2:xmax_pos-1),:))./(Oe+Ri_M(2:xmax_pos-1,:))-(VV_0(indx(2:xmax_pos-1),:)-VV_0(indx_1(2:xmax_pos-1),:))./(Oe+Ri_M(indx_1(2:xmax_pos-1),:)); II_0(1,:)=-IL(1,:)+(VV_0(2,:)-VV_0(1,:))/(Oe+Ri_M(1,:)); II_0(xmax_pos,:)=I_y-IL(xmax_pos,1)-sum(II_0(1:xmax_pos-1)); % calculate the leakage current in the negative electrode IL(xmin_neg+1:xmax_neg,:)=0; %IL(xmin_neg+1:xmax_neg,1)=a_ele*I0_O2*V_i*(exp(a_O2/RT_F.*(VV(xmin_neg+1:xmax_neg,1)/1000+E0_Ca-E0_O2))-exp(-a_O2/RT_F.*(VV(xmin_neg+1:xmax_neg,1)/1000+E0_Ca-E0_O2))) ; %IL(xmin_neg+1:xmax_neg,1)=-IL_O2*V_i./(1+exp((VV_0(xmin_neg+1:xmax_neg,:)/1000+E0_Ca-E_half)/RT_F)); % update the current distribution in the negative electrode II_0(xmin_neg+2:end-1,:)=-IL(xmin_neg+2:end-1,:)+(VV_0(indx_1(xmin_neg+2:end-1),:)-VV_0(indx(xmin_neg+2:end-1),:))./(Oe+Ri_M(indx_1(xmin_neg+2:end-1),:))-(VV_0(indx(xmin_neg+2:end-1),:)-VV_0(indx_0(xmin_neg+2:end-1),:))./(Oe+Ri_M(indx(xmin_neg+2:end-1),:)); II_0(end,:)=-IL(end,:)+(VV_0(end-1,:)-VV_0(end,:))./(Oe+Ri_M(end,:)); II_0(xmin_neg+1,:)=-I_y'-sum(II_0(xmin_neg+2:end,:))-sum(IL(xmin_neg+1:end,:)); % calculate the ionic current in the electrode A = tril (ones(N)); A1=A'; A2=tril(ones(N_FC))'; I_Ri(1:xmax_pos,1)=A*(IL(1:xmax_pos,1)+II_0(1:xmax_pos,1)); I_Ri(xmax_pos+1:xmin_neg,1)=I_y(1); I_Ri(xmin_neg+1:xmax_neg,1)=-A1*(IL(xmin_neg+1:xmax_neg,1)+II_0(xmin_neg+1:xmax_neg,1)); %B.C vector bc=zeros(nx,ny); bc(1,:)=0; bc(nx,:)=0; %Neumann B.Cs bc(:,1)=0; bc(:,ny)=0; %bc(xmax_pos+1:xmin_neg,1)=C0/dy^2; %Dirichlet B.Cs %B.Cs at the corners: bc(1,1)=0; bc(nx,1)=0; bc(1,ny)=0; bc(nx,ny)=0; bc(x_ind,:)=D_e*dt*bc(x_ind,:); bc(FC_ind,:)=D_e*dt*bc(FC_ind,:); %Calculating the coefficient matrix for the implicit scheme Ex=sparse(2:nx,1:nx-1,1,nx,nx); Ax=Ex+Ex'-2*speye(nx); %Dirichlet B.Cs Ax(1,1)=-1; Ax(nx,nx)=-1; %Neumann B.Cs Ey=sparse(2:ny,1:ny-1,1,ny,ny); Ay=Ey+Ey'-2*speye(ny); %Dirichlet B.Cs Ay(1,1)=-1; Ay(ny,ny)=-1; %Neumann B.Cs D=R_Macro*speye((nx)*(ny)); D(FC_ind_A,:)=D(FC_ind_A,:)/R_Macro*R_FC; D_y = speye(nx)*D_e*dt; D_y = kron(Ay/dy^2,D_y); D_x = speye(ny)*D_e*dt; D_x = kron(D_x,Ax/dx^2); D_x (FC_ind_A,:) = D_x(FC_ind_A,:)/D_e*D_FC; % update the diffusion coefficient in the flow channel D_x (length(D_x)*(xmax_pos-1)+xmax_pos+1:length(D_x)*nx+nx:end) = D_x(2)/D_e*D_mid; % update the diffusion coefficient at the interfaces between electrode and flow channel D_x (length(D_x)*(xmax_pos)+xmax_pos:length(D_x)*nx+nx:end) = D_x(2)/D_e*D_mid; % update the diffusion coefficient at the interfaces between electrode and flow channel D_x (length(D_x)*(xmin_neg)+xmin_neg:length(D_x)*nx+nx:end) = D_x(2)/D_e*D_mid; % update the diffusion coefficient at the interfaces between electrode and flow channel D_x (length(D_x)*(xmin_neg-1)+xmin_neg+1:length(D_x)*nx+nx:end) = D_x(2)/D_e*D_mid; % update the diffusion coefficient at the interfaces between electrode and flow channel D_x (length(D_x)*(xmax_pos-1)+xmax_pos:length(D_x)*nx+nx:end) = -(D_mid+D_e)*dt/dx^2; % update the diffusion coefficient at the interfaces between electrode and flow channel D_x (length(D_x)*(xmax_pos)+xmax_pos+1:length(D_x)*nx+nx:end) = -(D_mid+D_FC)*dt/dx^2; % update the diffusion coefficient at the interfaces between electrode and flow channel D_x (length(D_x)*(xmin_neg-1)+xmin_neg:length(D_x)*nx+nx:end) = -(D_mid+D_FC)*dt/dx^2; % update the diffusion coefficient at the interfaces between electrode and flow channel D_x (length(D_x)*(xmin_neg)+xmin_neg+1:length(D_x)*nx+nx:end) = -(D_mid+D_e)*dt/dx^2; % update the diffusion coefficient at the interfaces between electrode and flow channel D=D-D_x - D_y; %D=D-D_x; %D=D-D_e*dt*(kron(Ay/dy^2,speye(nx))+kron(speye(ny),Ax/dx^2)); %D((size(D,1)+1)*(xmax_pos)+1:(size(D,1)+1):1+(size(D,1)+1)*(xmin_neg-1))=R_FC-; clear D_x D_y % Other initial values C_eff(1)=C0; Qt_0(:,:)=0; %C/cm3-electrode; Initial charge density at time step n=1 Count_C = zeros(Nt,1); % Iternation number for the concentration matrix for the last current matrix iteration at each time step Count_Q = zeros(Nt,1); % Iteration number for the current matrix at each time step Error_Q = 0; % error of the charge iterative loop flag_0=1; % flag for the current convergence loop flag_1=1; % flag for the concentration convergence loop flag_3=0; % flag for adjusting the concentration convergence flag_4=1; % flag for the technique after charging flag_5=1; % flag for the technique after discharging flag_6=1; % flag for ocv study flag_7=0; % flag for iterative time step flag_8=0; % flag for iteration loops Cycle_number=1; n_r=1; ind_B=(1:size(D,1))'; ind_B1=circshift(ind_B,1); ind_B0=circshift(ind_B,-1); err=zeros(500,1); Vt_1=zeros(4,1); % Calculate the initial charge storage and Donnan layer potential Qt_mi(1:xmax_pos,:) = -Qt_e(1:xmax_pos,:)-Q_fix_pos; Qt_mi(xmin_neg+1:end,:) = -Qt_e(xmin_neg+1:end,:) - Q_fix_neg; V_D(x_ind,:)=-asinh(Qt_mi(x_ind,:)/R_Micro*10^6/F/2./(C0)/exp(uatt)); % non-dimentional Donnan layer potential VV_0(x_ind,:)=V_D(x_ind,:)*25.7+Qt_e(x_ind,:)/C_Measured/M_e*1000; % mV, electrode polarization C_mi_1(x_ind,:)=2*(C0)*exp(uatt).*cosh(V_D(x_ind,:)); % mmol-L micropores C_eff_0 = C0; C_mix_0 = C0; % Calculate the inital voltage distribution V_N (xmin_neg+1:xmax_neg,1)= A1*(Ri_M(xmin_neg+1:xmax_neg,1).*I_Ri(xmin_neg+1:xmax_neg,1))+Oe*I_y(1)-VV_0(xmax_neg,1); % liquid potential across one electrode when the cathod is grounded V_N(xmax_pos+1:xmin_neg,1)=A2*Ri_M(xmax_pos+1:xmin_neg,1).*I_y(1)+V_N(xmin_neg+1,1); % liquid across Flow channel V_N (1:xmax_pos,1)=A1*(Ri_M(1:xmax_pos,1).*I_Ri(1:xmax_pos,1))+V_N(xmax_pos+1,1) ; % liquid across one electrode Vt (1,1)=V_N(1,1)+I_y(1)*Oe+VV_0(1,1); % mV, voltage in the solution Vt (1,2)=R_contact*J; % mV, voltage due to the resistance of two IEMs and external resistance Vt (1,3)=0; % mV, membrane Donnan potential Vt (1,4)=sum(Vt(1,1:3)); % mV, Cell voltage fprintf('Thank you for using the CDI simulation tool\n') fprintf('***************************\n') fprintf('*******CDI 2D Model********\n') fprintf('Developed by Xia Shang at UIUC\n') fprintf('Copyright: Xia Shang, Prof. Roland Cusick, Prof. Kyle Smith\n\n') fprintf('*******Selected input******\n') fprintf('Current Density = %4.2f mA/cm2\nVoltage Window= %4.2f mV\nInfluent Concentration = %4.2f mM.\n', J, V_max-V_min, C0) time_stamp = datestr(now, 'HH:MM:SS'); date = datetime('today'); fprintf('Simulation starting time: %s', time_stamp) fprintf('Date: %s', date) fprintf('\n') fprintf('*********Output***********\n') fprintf('Time; Cell Voltage; Effluent Concentration\n') %% Main time loop for n=2:1:Nt % time step n flag_7=0; % reset flag_7 C_0=C_1; % update concentration field C_mi_0=C_mi_1; % update micro-pores ionic concentration field Qt_0=Qt_1; % update charge density field T0=T1; % update time while flag_7==0; % adaptive time loop flag_8=0; % reset flag 8 flag_0=1; % reset flag_0 for the current while loop flag_3=0; % reset flag_3 T1=T0+dt; % guess electric charge density based on the information at the previous time step Qt_e(:,:)=Qt_0(:,:)+II_0(:,:)*dt/10^3/V_i; % C/cm3-electrode Count_Q(n)=0; while flag_0==1 % charge density iterative loop flag_1=1; % reset flag_1 for the concentration while loop % guess Ce* based on the calculated charge efficiency at time step n-1 C1=C_0; Count_C(n) = 0; while flag_1==1 % concentration iterative loop % Solve for total ionic charge density in the micropores Qt_mi(1:xmax_pos,:) = -Qt_e(1:xmax_pos,:)-Q_fix_pos; Qt_mi(xmin_neg+1:end,:) = -Qt_e(xmin_neg+1:end,:) - Q_fix_neg; V_D(x_ind,:)=-asinh(Qt_mi(x_ind,:)/R_Micro*10^6/F/2./(C1(x_ind,:))/exp(uatt)); % non-dimentional Donnan layer potential VV_0(x_ind,:)=V_D(x_ind,:)*25.7+Qt_e(x_ind,:)/C_Measured/M_e*1000; % mV, electrode polarization C_mi_1(x_ind,:)=2*(C1(x_ind,:))*exp(uatt).*cosh(V_D(x_ind,:)); % mmol-L micropores % Solve for new Ce including the effect of diffusion (implicit, forward time, CN in diffusion, upwind explicit in aadvection) C_1=C1; C1(x_ind,:)=R_Macro*C_0(x_ind,:)-(C_mi_1(x_ind,:)-C_mi_0(x_ind,:))/2*R_Micro; C1(FC_ind,:)=R_FC*C_0(FC_ind,:); C1(FC_ind,2:end)=C1(FC_ind,2:end)+v_FC*dt/dy*(C_0(xmax_pos+1:xmin_neg,indy_1(2:end))-C_0(xmax_pos+1:xmin_neg,indy(2:end))); C1(FC_ind,1)=C1(FC_ind,1)+v_FC*dt/dy*(C0-C_0(xmax_pos+1:xmin_neg,1)); C1=reshape(C1+bc,[],1); C1=D\C1; C1=reshape(C1,nx,ny); % check for convergence err(Count_C(n)+1,1)=max(max(abs(C1-C_1)./C_1)); if err(Count_C(n)+1,1)<10^-7; flag_1=0; flag_8=1; C_1=C1; end Count_C(n) = Count_C(n)+1; end % update the current and voltage distribution Cond_M(:,:)=2*D_NaCl*C_1(:,:)/KB/Temp/1000000*F*e*R_e^1.5; % S/cm conductivity matrix Cond_M(xmax_pos+1:xmin_neg,:)=2*D_NaCl*C_1(xmax_pos+1:xmin_neg,:)/KB/Temp/1000000*F*e*R_FC^1.5; % S/cm conductivity matrix Cond_M(1:xmax_pos-1,:)=2.*Cond_M(1:xmax_pos-1,:).*Cond_M(indx_0(1:xmax_pos-1),:)./(Cond_M(1:xmax_pos-1,:)+Cond_M(indx_0(1:xmax_pos-1),:)); Cond_M(xmin_neg+1:xmax_neg-1,:)=2.*Cond_M(xmin_neg+1:xmax_neg-1,:).*Cond_M(indx_0(xmin_neg+1:xmax_neg-1),:)./(Cond_M(xmin_neg+1:xmax_neg-1,:)+Cond_M(indx_0(xmin_neg+1:xmax_neg-1),:)); Ri_M(:,:) = 1./Cond_M(:,:)*dx/dy/W_FC; % ohm, resistance matrix Ri_S(:)=sum(Ri_M(xmax_pos:xmin_neg,:)); % calculate the current distribution in the electrode M_I(1:(ny+1):(end-ny))=Ri_S(1:(end-1)); M_I((ny+1):(ny+1):end)=-Ri_S(2:end); S_I=sparse(M_I); B_I(1:end-1)=VV_0(xmax_pos,indy_0(1:(end-1)))-VV_0(xmin_neg+1,indy_0(1:(end-1)))-VV_0(xmax_pos,1:(end-1))+VV_0(xmin_neg+1,1:(end-1)); B_I(end)=I; I_y=S_I\B_I; % solve the current distribution in the electrode in the y-direction % calculate the leakage current IL(1:xmax_pos,:)=a_ele*I0_C*V_i*exp(a_C/RT_F.*(VV_0(1:xmax_pos,:)/1000+E0_An-E0_C)); % VB model %IL(1:xmax_pos,:)=0; % no leakage current % Update the current distribution in the anode II_1(2:xmax_pos-1, :)=-IL(2:xmax_pos-1,:)+(VV_0(indx_0(2:xmax_pos-1),:)-VV_0(indx(2:xmax_pos-1),:))./(Oe+Ri_M(2:xmax_pos-1,:))-(VV_0(indx(2:xmax_pos-1),:)-VV_0(indx_1(2:xmax_pos-1),:))./(Oe+Ri_M(indx_1(2:xmax_pos-1),:)); II_1(1,:)=-IL(1,:)+(VV_0(2,:)-VV_0(1,:))/(Oe+Ri_M(1,:)); II_1(xmax_pos,:)=I_y'-sum(II_1(1:xmax_pos-1,:))-sum(IL(1:xmax_pos,:)); % calculate the current distribution in the Cathode %IL(xmin_neg+1:xmax_neg,:)=0; % no leakage curret IL(xmin_neg+1:xmax_neg,:)=-IL_O2*V_i./(1+exp((VV_0(xmin_neg+1:xmax_neg,:)/1000+E0_Ca-E_half)/RT_F)); % limiting current model %IL(xmin_neg+1:xmax_neg,:)=a_ele*I0_O2*V_i*(exp(a_O2/RT_F.*(VV_0(xmin_neg+1:xmax_neg,:)/1000+E0_Ca-E0_O2))-exp(-a_O2/RT_F.*(VV_0(xmin_neg+1:xmax_neg,:)/1000+E0_Ca-E0_O2))); %BV model % update the current distribution in the cathode II_1(xmin_neg+2:end-1,:)=-IL(xmin_neg+2:end-1,:)+(VV_0(indx_1(xmin_neg+2:end-1),:)-VV_0(indx(xmin_neg+2:end-1),:))./(Oe+Ri_M(indx_1(xmin_neg+2:end-1),:))-(VV_0(indx(xmin_neg+2:end-1),:)-VV_0(indx_0(xmin_neg+2:end-1),:))./(Oe+Ri_M(indx(xmin_neg+2:end-1),:)); II_1(end,:)=-IL(end,:)+(VV_0(end-1,:)-VV_0(end,:))./(Oe+Ri_M(end,:)); II_1(xmin_neg+1,:)=-I_y'-sum(II_1(xmin_neg+2:end,:))-sum(IL(xmin_neg+1:end,:)); % Calculate the charge density Qt_1(:,:)=Qt_0(:,:)+(II_0(:,:)+II_1(:,:))/2/1000/V_i*dt; % Check for convergence Error_Q =max(max(abs(Qt_1-Qt_e))); if (Error_Q<10^-7||Count_Q(n)>200)&&flag_8==1; flag_0=0; flag_7=1; II_0=II_1; else Qt_e=Qt_1; end Count_Q(n) = Count_Q(n)+1; end end C_eff_1=mean(C_1(xmax_pos+1:xmin_neg,ny)); C_mid = (C_eff_1+C_eff_0)/2; C_mix_1 = C_mid - (C_mid - C_mix_0)*exp(-k_mix*dt); C_eff_0 = C_eff_1; C_mix_0 = C_mix_1; % Calculate the voltage distribution Vt_1 (1)=-VV_0(xmin_neg+1,end)+I_y(end)*Ri_S(end)+VV_0(xmax_pos,end); % mV, voltage in the solution Vt_1 (2)=R_contact/A_FC*I; % mV, voltage due to the resistance of two IEMs and external resistance Vt_1 (3)=0; % mV, Donnan potential Vt_1 (4)=sum(Vt_1(1:3)); % check if cell voltage reaches the maximum voltage limit if Vt_1(4)>V_max&&flag_4==1; I=-I; Discharge_index(Cycle_number)=n_r; flag_4=0; flag_5=1; end % check if cell voltage reaches the minimum voltage limit if Vt_1(4)<0&&flag_5==1 && n_r>100 I=-I; Cycle_number=Cycle_number+1 Cycle_index(Cycle_number)=n_r; flag_5=0; flag_4=1; end % check for data storage if T1-T_r(n_r)>=dt_record n_r=n_r+1; T_r(n_r)=T1; C_eff(n_r)=C_eff_1; C_eff_mix(n_r)=C_mix_1; Vt(n_r,:)=Vt_1(:); C_re(:,:,n_r)=C_1(:,:); II_re(:,:,n_r)=II_1(:,:); Q_mi_re(:,:,n_r)=Qt_mi; IL_re(:,:,n_r) = IL; fprintf('T = %4.2f s, V_cell = %4.2f mV, C_eff = %4.2f mM.\n', T1, Vt_1(4), C_eff_1) end % check if the maximum cycle litmits is reached if Cycle_number==Cycle_limit+1; %I=0; flag_6=0; break end end T_r = T_r(1:n_r)'; V_cell = Vt(1:n_r, 4)'; C_eff = C_eff(1:n_r)'; %%%%%%post-treatment, save data in file %filename = sprintf('CDI_2D_target_effluent_%icm_%imV_%imM_amph_D_%iA_%iFg_%iC_%s.mat',L_FC, V_max,C0,int32(J*10),C_Measured,Q_fix_pos,date); %save(filename,'Vol_FC','V_max','n_r','T_r','II_re','C_re','C_eff','C_eff_mix','Vt','Q_mi_re','Cycle_index','Discharge_index','L_FC','Q_FC','J','A_FC','dx','dy','Batch_index','B_number','IL_re','C_Measured','Q_fix_pos','Q_fix_neg','k_mix') toc end
github
pablogmendez/gerris-master
panial.m
.m
gerris-master/Gerris/Gerris-ControllerModule/MLC/panial.m
1,728
utf_8
4967b798a0104c1e6cfe6d432e7b9934
function panial timelimit=0.007; fprintf('Panial is on\n') while 1 try fprintf('Panial is') if ~exist('cylinder_control/log.txt','file') pause(1) fprintf(' waiting for log to appear\n'); pause(1) continue end system('tail -n 20 cylinder_control/log.txt > last.txt'); pause(1) A=importdata('last.txt'); delete last.txt if isa(A,'cell') for i=1:20 ok(i)=0; if ~isempty(strfind(A{i},'Controller - Waiting for call request')); ok(i)=1; end end ids=strfind(A{end},':'); time_check='not checked'; if ids(1)==14 && ids(2)==17 log_time=A{end}(1:ids(2)+2); if now-datenum(log_time)>timelimit savelog('timelimit'); system('killall gerris2D'); timelimit=0.007*2; else timelimit=0.007; end time_check=sprintf('%s minute ago',datestr(now-datenum(log_time),'MM')); end if sum(ok)==20 savelog('waitingcallrequest'); system('killall gerris2D'); end end d=dir(fullfile('error_logs','*.txt')); if isempty(d) n_logs=0; else n_logs=numel(d); end fprintf(' on (last time on log: %s) - (%d panial(s) used)\n',time_check,n_logs) pause(1) catch err fprintf(err.message); end end end function savelog(reason) if ~exist('error_logs','dir') mkdir('error_logs'); end if exist('cylinder_control/log.txt','file') copyfile('cylinder_control/log.txt',fullfile('error_logs',sprintf('%s-log-%s.txt',datestr(now,'yyyymmdd-HHMMSS'),reason))); delete('cylinder_control/log.txt'); end end
github
pablogmendez/gerris-master
MLC_Gerris_cylinder_evaluator.m
.m
gerris-master/Gerris/Gerris-ControllerModule/MLC/MLC_Gerris_cylinder_evaluator.m
2,926
utf_8
438365e79e29569e66cc7ca051fc0d11
function J=MLC_Gerris_cylinder_evaluator(idv,parameters,i,fig) %% Variable grocery curdir=pwd; if nargin<3 i=[]; end %% Quick drop of innapropriate control laws if ~MLC_Gerris_cylinder_pre_evaluator(idv,parameters) J=parameters.badvalue; return end %% Setting up the simulation try %% Simulation if strcmp(parameters.evaluation_method,'mfile_multi') t=getCurrentTask(); WorkerID=t.ID; else WorkerID=[]; end if ~exist(sprintf('%s%d',parameters.problem_variables.SimDirectory,WorkerID),'dir') copyfile(parameters.problem_variables.SimDirectory,sprintf('%s%d',parameters.problem_variables.SimDirectory,WorkerID)); pause(2); end xSetFinalTime(parameters.problem_variables,parameters.verbose>2,WorkerID); xSetActuator(idv,parameters,WorkerID); cd(sprintf('%s%d',parameters.problem_variables.SimDirectory,WorkerID)) system('make clean'); system('./exec_from_steady_state.sh'); cd (curdir) %% Get the cost [t,x,y,s,b,dJa,dJb]=xGetResults(idv,parameters,WorkerID); [t0,dJ0]=xGetUncontrolledResults(); if length(t0)~=length(t) error('Time vectors does not match with uncontrolled case (length).'); else if any(t~=t0) error('Time vectors does not match with uncontrolled case (values).'); end end if t(end)==parameters.problem_variables.total_time J=(trapz(t,dJa+parameters.problem_variables.gamma*dJb)/trapz(t,dJ0)); else J=t(end)*parameters.badvalue; end %% Show results if nargin>3 figure(667) else figure(1) end subplot(4,1,1) plot(t,s) subplot(4,1,2) plot(t,b) subplot(4,1,3) plot(t,dJa,t,dJb);hold on plot(t,dJ0,'linewidth',1.2,'color','k') hold off subplot(4,1,4) try plot(t,cumtrapz(t,dJa)./cumtrapz(t,t),t,cumtrapz(t,dJb)./cumtrapz(t,t),... t,cumtrapz(t,dJa+parameters.problem_variables.gamma*dJb)./cumtrapz(t,t)); hold on plot(t,cumtrapz(t,dJ0)./cumtrapz(t,t),'linewidth',1.2,'color','k') hold off catch end drawnow %% deal with errors catch err cd(curdir); fprintf(err.message); savelog('MatlabCatch') idv.comment=sprintf('Eval fail: %s',err.message); J=parameters.badvalue; end end function savelog(reason) if ~exist('error_logs','dir') mkdir('error_logs'); end if exist('cylinder_control/log.txt','file') copyfile('cylinder_control/log.txt',fullfile('error_logs',sprintf('%s-log-%s.txt',datestr(now,'yyyymmdd-HHMMSS'),reason))); end end
github
pablogmendez/gerris-master
panial.m
.m
gerris-master/Gerris/Gerris-ControllerModule/MLC/MLC_cyl.old/panial.m
1,296
utf_8
22b6149da0d41efbae44deaf503a0350
function [ok]=panial(MLC_parameters,varargin) % PANIAL function that checks that the simulation did not shit itself and % does what is needed if it did. check = 1; % the programm waits until either the sim is finished, either it is % frozen old_time=-1; while check new_time=get_time(MLC_parameters); if new_time==old_time % finished or stalled check=0; else pause(3); end if isempty(new_time) check=0; end old_time=new_time; end if old_time>MLC_parameters.problem_variables.total_time-1 ok=1; else ok=0; killall; end end function t=get_time(MLC_parameters) log_file=MLC_parameters.problem_variables.outputfile; temp_file='time.txt'; cd cylinder system(sprintf('cat %s | tail -n 1 | awk ''{print $4}'' > %s',log_file,temp_file)); t=importdata(temp_file); %delete(temp_file); cd .. end function killall temp_file='pid.txt'; sprintf('ps aux | grep gerris | awk ''{print $2}'' > %s',temp_file) system(sprintf('ps aux | grep gerris | awk ''{print $2}'' > %s',temp_file)); pid_list=importdata(temp_file); for i=1:length(pid_list) sprintf('kill -9 %i',pid_list(i)) system(sprintf('kill -9 %i',pid_list(i))) end end
github
mehta-lab/Instantaneous-PolScope-master
interactivePolHist.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/interactivePolHist.m
5,399
utf_8
5ed4134946be75ed9f2d1f06e7f1f4e0
function hROI=interactivePolHist(I0,I45,I90,I135,aniso,orient,avg,varargin) % hROI=interactivePolHist(I0,I45,I90,I135,aniso,orient,avg) % Allows interactive exploration of orientation histogram. % hROI is the handle of ROI used to display the orientation histogram if % 'analyzeROI' option is set true. Otherwise hROI is NaN. arg.avgCeiling=NaN; arg.anisoCeiling=NaN; arg.Statistic='PixelAnisotropy'; arg.analyzeROI=true; arg.Parent=NaN; arg.orientationRelativeToROI=true; arg.scaleLUTtoROI=false; arg.exportPath=[]; %If export path is set, export the current image and also the statistics. arg.showColorbar=false; arg.getDirection=false; arg.radialRange=NaN; arg=parsepropval(arg,varargin{:}); if(ishandle(arg.Parent)) hfig=arg.Parent; else hfig=togglefig('Interactive orientation histogram',1); clf(hfig); set(hfig,'color','w','defaultaxesfontsize',15,'Units','Normalized','Position',[0.05 0.05 0.9 0.9]); colormap gray; end % Calculate the ceiling if not set. if(isnan(arg.avgCeiling) || arg.avgCeiling == 0) arg.avgCeiling=max(avg(:)); end % Calculate the ceiling if not set. if(isnan(arg.anisoCeiling) || arg.anisoCeiling == 0) arg.anisoCeiling=max(aniso(:)); end avgDisp=avg; avgDisp(avg>arg.avgCeiling)=arg.avgCeiling; OrientationMap=pol2color(aniso,orient,avgDisp,'sbm','border',15,'legend',true,'avgCeiling',arg.avgCeiling,'anisoCeiling',arg.anisoCeiling); if(arg.showColorbar) ha=imagecat(I0,I45,I90,I135,OrientationMap,aniso,avg,'link','equal','off','colorbar',hfig); else ha=imagecat(I0,I45,I90,I135,OrientationMap,aniso,avg,'link','equal','off',hfig); end set(ha(6),'clim',[0 arg.anisoCeiling]); set(ha(7),'clim',[0 arg.avgCeiling]); if(arg.analyzeROI) % Draw the ROI interactively. set(get(ha(7),'Title'),'String','Average (select ROI)'); hROI=impoly(ha(7)); setColor(hROI,'magenta'); % Setup a callback to update the histogram everytime ROI is updated. addNewPositionCallback(hROI,@(p) updatePolHist(p,ha,hfig,I0,I45,I90,I135,aniso,orient,avg,arg)); % Constrain the ROI's boundaries. fcn = makeConstrainToRectFcn('impoly',get(ha(7),'XLim'),get(ha(7),'YLim')); setPositionConstraintFcn(hROI,fcn); % Draw the histogram for the first time. updatePolHist(hROI.getPosition(),ha,hfig,I0,I45,I90,I135,aniso,orient,avg,arg); else hROI=NaN; end end function updatePolHist(p,ha,hfig,I0,I45,I90,I135,aniso,orient,avg,params) persistent hLineROI hLineOrient; % p is ROI, ha is handles to the axes. histMask=poly2mask(p(:,1),p(:,2),size(I0,2),size(I0,1)); rpMask=regionprops(histMask,'Orientation','MajorAxisLength','Centroid','MinorAxisLength'); Lm=rpMask.MajorAxisLength; % Length of line indicating orientation of the mask. maskCen=rpMask.Centroid; maskOrient=mod(rpMask.Orientation*(pi/180),pi); if(params.getDirection) % Assign the direction consistent with the order of the points. % Point-1 to point-2 is reference direction. end % Determine the display limits after ignoring the % border. I0crop=I0(histMask); I135crop=I135(histMask); I90crop=I90(histMask); I45crop=I45(histMask); OrientationCrop=orient(histMask); AnisotropyCrop=aniso(histMask); AverageCrop=avg(histMask); maxAniso=max(AnisotropyCrop(:)); Ivec=[I0crop(:); I135crop(:); I90crop(:); I45crop(:)]; Ilims=[min(Ivec) 0.5*max(Ivec)]; subplot(2,4,8,'Parent',hfig); [meanAniso,meanOrient]=anisoStats(AnisotropyCrop,OrientationCrop,AverageCrop); polarPlotAnisoStat(AnisotropyCrop,OrientationCrop,AverageCrop,'PlotType','Polar','ReferenceOrient',maskOrient,... 'Statistic',params.Statistic,'orientationRelativeToROI',params.orientationRelativeToROI,'anisoCeiling',params.anisoCeiling); %[meanOrient,meanAniso]=ComputeFluorAnisotropy(mean(I0crop),mean(I45crop),mean(I90crop),mean(I135crop),'anisotropy'); Lf=Lm*meanAniso; % Scale down the length of line indicating orientation of fluorophore depending on the anisotropy. if(params.scaleLUTtoROI) set([ha(1:4); ha(7)],'Clim',Ilims); set(ha(6),'Clim',[0 maxAniso]); end %%% Label anisotropy display. axes(ha(6)); title(['anisotropy: max ' num2str(maxAniso,2) ',mean ' num2str(meanAniso,2)]); %%% Label intensity display. axes(ha(7)); TotalI=sum(AverageCrop(:)); MeanI=mean(AverageCrop(:)); title(['total:' num2str(TotalI,3) ', mean:' num2str(MeanI,3) ]); if(ishandle(hLineROI)) delete(hLineROI); end if(ishandle(hLineOrient)) delete(hLineOrient); end % Note that order of Y-coordinates is flipped because the Y-axis used % by image processing toolbox is top to bottom, whereas visually and in % polarization computations it is bottom to top. hLineROI=line([maskCen(1)-0.5*Lm*cos(maskOrient) maskCen(1)+0.5*Lm*cos(maskOrient)],... [maskCen(2)+0.5*Lm*sin(maskOrient) maskCen(2)-0.5*Lm*sin(maskOrient)],'LineWidth',2,'Color','k'); % Draw a line indicating the polarization orientation. hLineOrient=line([maskCen(1)-0.5*Lf*cos(meanOrient) maskCen(1)+0.5*Lf*cos(meanOrient)],... [maskCen(2)+0.5*Lf*sin(meanOrient) maskCen(2)-0.5*Lf*sin(meanOrient)],'LineWidth',2,'Color','b'); % [counts,levels]=hist(mod(OrientwrtMask,180),0:0.5:180); % stem(levels,counts); % % xlim([0 180]); % end
github
mehta-lab/Instantaneous-PolScope-master
tiffread.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/tiffread.m
23,985
utf_8
ad13854ba30cf671ab07bfc42e12bd32
function stack = tiffread(filename, indices) % tiffread, version 2.7 January 28, 2009 % % stack = tiffread; % stack = tiffread(filename); % stack = tiffread(filename, indices); % % Reads 8,16,32 bits uncompressed grayscale and (some) color tiff files, % as well as stacks or multiple tiff images, for example those produced % by metamorph, Zeiss LSM or NIH-image. % % The function can be called with a file name in the current directory, % or without argument, in which case it pops up a file opening dialog % to allow for a manual selection of the file. % If the stacks contains multiples images, reading can be restricted by % specifying the indices of the images to read, or just one index. % % The returned value 'stack' is a vector struct containing the images % and their meta-data. The length of the vector is the number of images. % The image pixels values are stored in a field .data, which is a simple % matrix for gray-scale images, or a cell-array of matrices for color images. % % The pixels values are returned in their native (usually integer) format, % and must be converted to be used in most matlab functions. % % Example: % im = tiffread('spindle.stk'); % imshow( double(im(5).data) ); % % Only a fraction of the TIFF standard is supported, but you may extend support % by modifying this file. If you do so, please return your modification to % F. Nedelec, so that the added functionality can be distributed in the future. % % Francois Nedelec, EMBL, Copyright 1999-2008. % rewriten July 7th, 2004 at Woods Hole during the physiology course. % last modified March 7, 2008. % With contributions from: % Kendra Burbank for the waitbar % Hidenao Iwai for the code to read floating point images, % Stephen Lang to be more compliant with PlanarConfiguration % Jan-Ulrich Kreft for Zeiss LSM support % Elias Beauchanp and David Kolin for additional Metamorph support % Jean-Pierre Ghobril for requesting that image indices may be specified % Urs Utzinger for the better handling of color images, and LSM meta-data % % Please, send us feedback/bugs/suggestions to improve this code. % This software is provided at no cost by a public research institution. % % Francois Nedelec % nedelec (at) embl.de % Cell Biology and Biophysics, EMBL; Meyerhofstrasse 1; 69117 Heidelberg; Germany % http://www.embl.org % http://www.cytosim.org %Optimization: join adjacent TIF strips: this results in faster reads consolidateStrips = 1; %without argument, we ask the user to choose a file: if nargin < 1 [filename, pathname] = uigetfile('*.tif;*.stk;*.lsm', 'select image file'); filename = [ pathname, filename ]; end if (nargin<=1); indices = 1:10000; end % not all valid tiff tags have been included, as they are really a lot... % if needed, tags can easily be added to this code % See the official list of tags: % http://partners.adobe.com/asn/developer/pdfs/tn/TIFF6.pdf % % the structure IMG is returned to the user, while TIF is not. % so tags usefull to the user should be stored as fields in IMG, while % those used only internally can be stored in TIF. global TIF; TIF = []; %counters for the number of images read and skipped img_skip = 0; img_read = 1; %hWaitbar = []; %% set defaults values : TIF.SampleFormat = 1; TIF.SamplesPerPixel = 1; TIF.BOS = 'ieee-le'; %byte order string if isempty(findstr(filename,'.')) filename = [filename,'.tif']; end TIF.file = fopen(filename,'r','l'); if TIF.file == -1 stkname = strrep(filename, '.tif', '.stk'); TIF.file = fopen(stkname,'r','l'); if TIF.file == -1 error(['File "',filename,'" not found.']); else filename = stkname; end end [s, m] = fileattrib(filename); % obtain the full file path: filename = m.Name; % find the file size in bytes: % m = dir(filename); % filesize = m.bytes; %% read header % read byte order: II = little endian, MM = big endian byte_order = fread(TIF.file, 2, '*char'); if ( strcmp(byte_order', 'II') ) TIF.BOS = 'ieee-le'; % Intel little-endian format elseif ( strcmp(byte_order','MM') ) TIF.BOS = 'ieee-be'; else error('This is not a TIFF file (no MM or II).'); end %% ---- read in a number which identifies file as TIFF format tiff_id = fread(TIF.file,1,'uint16', TIF.BOS); if (tiff_id ~= 42) error('This is not a TIFF file (missing 42).'); end %% ---- read the byte offset for the first image file directory (IFD) TIF.img_pos = fread(TIF.file, 1, 'uint32', TIF.BOS); while TIF.img_pos ~= 0 clear IMG; IMG.filename = filename; % move in the file to the first IFD status = fseek(TIF.file, TIF.img_pos, -1); if status == -1 error('invalid file offset (error on fseek)'); end %disp(strcat('reading img at pos :',num2str(TIF.img_pos))); %read in the number of IFD entries num_entries = fread(TIF.file,1,'uint16', TIF.BOS); %disp(strcat('num_entries =', num2str(num_entries))); %read and process each IFD entry for i = 1:num_entries % save the current position in the file file_pos = ftell(TIF.file); % read entry tag TIF.entry_tag = fread(TIF.file, 1, 'uint16', TIF.BOS); % read entry entry = readIFDentry; %disp(strcat('reading entry <',num2str(TIF.entry_tag),'>')); switch TIF.entry_tag case 254 TIF.NewSubfiletype = entry.val; case 256 % image width - number of column IMG.width = entry.val; case 257 % image height - number of row IMG.height = entry.val; TIF.ImageLength = entry.val; case 258 % BitsPerSample per sample TIF.BitsPerSample = entry.val; TIF.BytesPerSample = TIF.BitsPerSample / 8; IMG.bits = TIF.BitsPerSample(1); %fprintf('BitsPerSample %i %i %i\n', entry.val); case 259 % compression if ( entry.val ~= 1 ) error(['Compression format ', num2str(entry.val),' not supported.']); end case 262 % photometric interpretation TIF.PhotometricInterpretation = entry.val; if ( TIF.PhotometricInterpretation == 3 ) warning('tiffread2:LookUp', 'Ignoring TIFF look-up table'); end case 269 IMG.document_name = entry.val; case 270 % comments: IMG.info = entry.val; case 271 IMG.make = entry.val; case 273 % strip offset TIF.StripOffsets = entry.val; TIF.StripNumber = entry.cnt; %fprintf('StripNumber = %i, size(StripOffsets) = %i %i\n', TIF.StripNumber, size(TIF.StripOffsets)); case 277 % sample_per pixel TIF.SamplesPerPixel = entry.val; %fprintf('Color image: sample_per_pixel=%i\n', TIF.SamplesPerPixel); case 278 % rows per strip TIF.RowsPerStrip = entry.val; case 279 % strip byte counts - number of bytes in each strip after any compressio TIF.StripByteCounts= entry.val; case 282 % X resolution IMG.x_resolution = entry.val; case 283 % Y resolution IMG.y_resolution = entry.val; case 284 %planar configuration describe the order of RGB TIF.PlanarConfiguration = entry.val; case 296 % resolution unit IMG.resolution_unit= entry.val; case 305 % software IMG.software = entry.val; case 306 % datetime IMG.datetime = entry.val; case 315 IMG.artist = entry.val; case 317 %predictor for compression if (entry.val ~= 1); error('unsuported predictor value'); end case 320 % color map IMG.cmap = entry.val; IMG.colors = entry.cnt/3; case 339 TIF.SampleFormat = entry.val; case 33628 %metamorph specific data IMG.MM_private1 = entry.val; case 33629 %this tag identify the image as a Metamorph stack! TIF.MM_stack = entry.val; TIF.MM_stackCnt = entry.cnt; case 33630 %metamorph stack data: wavelength TIF.MM_wavelength = entry.val; case 33631 %metamorph stack data: gain/background? TIF.MM_private2 = entry.val; case 34412 % Zeiss LSM data LSM_info = entry.val; otherwise %fprintf( 'Ignored TIFF entry with tag %i (cnt %i)\n', TIF.entry_tag, entry.cnt); end % move to next IFD entry in the file status = fseek(TIF.file, file_pos+12, -1); if status == -1 error('invalid file offset (error on fseek)'); end end %Planar configuration is not fully supported %Per tiff spec 6.0 PlanarConfiguration irrelevent if SamplesPerPixel==1 %Contributed by Stephen Lang if (TIF.SamplesPerPixel ~= 1) && ( ~isfield(TIF, 'PlanarConfiguration') || TIF.PlanarConfiguration == 1 ) error('PlanarConfiguration = 1 is not supported'); end %total number of bytes per image: PlaneBytesCnt = IMG.width * IMG.height * TIF.BytesPerSample; %% try to consolidate the TIFF strips if possible if consolidateStrips %Try to consolidate the strips into a single one to speed-up reading: BytesCnt = TIF.StripByteCounts(1); if BytesCnt < PlaneBytesCnt ConsolidateCnt = 1; %Count how many Strip are needed to produce a plane while TIF.StripOffsets(1) + BytesCnt == TIF.StripOffsets(ConsolidateCnt+1) ConsolidateCnt = ConsolidateCnt + 1; BytesCnt = BytesCnt + TIF.StripByteCounts(ConsolidateCnt); if ( BytesCnt >= PlaneBytesCnt ); break; end end %Consolidate the Strips if ( BytesCnt <= PlaneBytesCnt(1) ) && ( ConsolidateCnt > 1 ) %fprintf('Consolidating %i stripes out of %i', ConsolidateCnt, TIF.StripNumber); TIF.StripByteCounts = [BytesCnt; TIF.StripByteCounts(ConsolidateCnt+1:TIF.StripNumber ) ]; TIF.StripOffsets = TIF.StripOffsets( [1 , ConsolidateCnt+1:TIF.StripNumber] ); TIF.StripNumber = 1 + TIF.StripNumber - ConsolidateCnt; end end end %read the next IFD address: TIF.img_pos = fread(TIF.file, 1, 'uint32', TIF.BOS); %if (TIF.img_pos) disp(['next ifd at', num2str(TIF.img_pos)]); end if isfield( TIF, 'MM_stack' ) sel = ( indices <= TIF.MM_stackCnt ); indices = indices(sel); %if numel(indices) > 1 % hWaitbar = waitbar(0,'Reading images...','Name','TiffRead'); %end %this loop reads metamorph stacks: for ii = indices TIF.StripCnt = 1; offset = PlaneBytesCnt * (ii-1); %read the image channels for c = 1:TIF.SamplesPerPixel IMG.data{c} = read_plane(offset, IMG.width, IMG.height, c); end % print a text timer on the main window, or update the waitbar % fprintf('img_read %i img_skip %i\n', img_read, img_skip); %if ~isempty( hWaitbar ) % waitbar(img_read/numel(indices), hWaitbar); %end [ IMG.MM_stack, IMG.MM_wavelength, IMG.MM_private2 ] = splitMetamorph(ii); stack(img_read) = IMG; img_read = img_read + 1; end break; else %this part reads a normal TIFF stack: read_img = any( img_skip+img_read == indices ); if exist('stack','var') if IMG.width ~= stack(1).width || IMG.height ~= stack(1).height %setting read_it=0 will skip dissimilar images: %comment-out the line below to allow dissimilar stacks read_img = 0; end end if read_img TIF.StripCnt = 1; %read the image channels for c = 1:TIF.SamplesPerPixel IMG.data{c} = read_plane(0, IMG.width, IMG.height, c); end try stack(img_read) = IMG; % = orderfields(IMG); img_read = img_read + 1; catch fprintf('Tiffread skipped dissimilar image %i\n', img_read+img_skip); img_skip = img_skip + 1; end if all( img_skip+img_read > indices ) break; end else img_skip = img_skip + 1; end end end %% remove the cell structure if there is always only one channel flat = 1; for i = 1:numel(stack) if numel(stack(i).data) ~= 1 flat = 0; break; end end if flat for i = 1:numel(stack) stack(i).data = stack(i).data{1}; end end %% distribute the MetaMorph info if isfield(TIF, 'MM_stack') && isfield(IMG, 'info') && ~isempty(deblank(IMG.info)) MM = parseMetamorphInfo(IMG.info, TIF.MM_stackCnt); for i = 1:numel(stack) stack(i).MM = MM(i); end end %% duplicate the LSM info if exist('LSM_info', 'var') for i = 1:numel(stack) stack(i).lsm = LSM_info; end end %% return if ~ exist('stack', 'var') stack = []; end %clean-up fclose(TIF.file); % if ~isempty( hWaitbar ) % delete( hWaitbar ); % end end %% =========================================================================== function plane = read_plane(offset, width, height, plane_nb) global TIF; %return an empty array if the sample format has zero bits if ( TIF.BitsPerSample(plane_nb) == 0 ) plane=[]; return; end %fprintf('reading plane %i size %i %i\n', plane_nb, width, height); %determine the type needed to store the pixel values: switch( TIF.SampleFormat ) case 1 classname = sprintf('uint%i', TIF.BitsPerSample(plane_nb)); case 2 classname = sprintf('int%i', TIF.BitsPerSample(plane_nb)); case 3 if ( TIF.BitsPerSample(plane_nb) == 32 ) classname = 'single'; else classname = 'double'; end otherwise error('unsuported TIFF sample format %i', TIF.SampleFormat); end % Preallocate a matrix to hold the sample data: try plane = zeros(width, height, classname); catch %compatibility with older matlab versions: eval(['plane = ', classname, '(zeros(width, height));']); end % Read the strips and concatenate them: line = 1; while ( TIF.StripCnt <= TIF.StripNumber ) strip = read_strip(offset, width, plane_nb, TIF.StripCnt, classname); TIF.StripCnt = TIF.StripCnt + 1; % copy the strip onto the data plane(:, line:(line+size(strip,2)-1)) = strip; line = line + size(strip,2); if ( line > height ) break; end end % Extract valid part of data if needed if ~all(size(plane) == [width height]), plane = plane(1:width, 1:height); warning('tiffread2:Crop','Cropping data: found more bytes than needed'); end % transpose the image (otherwise display is rotated in matlab) plane = plane'; end %% ================== sub-functions to read a strip =================== function strip = read_strip(offset, width, plane_nb, stripCnt, classname) global TIF; %fprintf('reading strip at position %i\n',TIF.StripOffsets(stripCnt) + offset); StripLength = TIF.StripByteCounts(stripCnt) ./ TIF.BytesPerSample(plane_nb); %fprintf( 'reading strip %i\n', stripCnt); status = fseek(TIF.file, TIF.StripOffsets(stripCnt) + offset, 'bof'); if status == -1 error('invalid file offset (error on fseek)'); end bytes = fread( TIF.file, StripLength, classname, TIF.BOS ); if any( length(bytes) ~= StripLength ) error('End of file reached unexpectedly.'); end strip = reshape(bytes, width, StripLength / width); end %% ==================sub-functions that reads an IFD entry:=================== function [nbBytes, matlabType] = convertType(tiffType) switch (tiffType) case 1 nbBytes=1; matlabType='uint8'; case 2 nbBytes=1; matlabType='uchar'; case 3 nbBytes=2; matlabType='uint16'; case 4 nbBytes=4; matlabType='uint32'; case 5 nbBytes=8; matlabType='uint32'; case 7 nbBytes=1; matlabType='uchar'; case 11 nbBytes=4; matlabType='float32'; case 12 nbBytes=8; matlabType='float64'; otherwise error('tiff type %i not supported', tiffType) end end %% ==================sub-functions that reads an IFD entry:=================== function entry = readIFDentry() global TIF; entry.tiffType = fread(TIF.file, 1, 'uint16', TIF.BOS); entry.cnt = fread(TIF.file, 1, 'uint32', TIF.BOS); %disp(['tiffType =', num2str(entry.tiffType),', cnt = ',num2str(entry.cnt)]); [ entry.nbBytes, entry.matlabType ] = convertType(entry.tiffType); if entry.nbBytes * entry.cnt > 4 %next field contains an offset: offset = fread(TIF.file, 1, 'uint32', TIF.BOS); %disp(strcat('offset = ', num2str(offset))); status = fseek(TIF.file, offset, -1); if status == -1 error('invalid file offset (error on fseek)'); end end if TIF.entry_tag == 33629 % metamorph 'rationals' entry.val = fread(TIF.file, 6*entry.cnt, entry.matlabType, TIF.BOS); elseif TIF.entry_tag == 34412 %TIF_CZ_LSMINFO entry.val = readLSMinfo; else if entry.tiffType == 5 entry.val = fread(TIF.file, 2*entry.cnt, entry.matlabType, TIF.BOS); else entry.val = fread(TIF.file, entry.cnt, entry.matlabType, TIF.BOS); end end if ( entry.tiffType == 2 ); entry.val = char(entry.val'); end end %% =============distribute the metamorph infos to each frame: function [MMstack, MMwavelength, MMprivate2] = splitMetamorph(imgCnt) global TIF; MMstack = []; MMwavelength = []; MMprivate2 = []; if TIF.MM_stackCnt == 1 return; end left = imgCnt - 1; if isfield( TIF, 'MM_stack' ) S = length(TIF.MM_stack) / TIF.MM_stackCnt; MMstack = TIF.MM_stack(S*left+1:S*left+S); end if isfield( TIF, 'MM_wavelength' ) S = length(TIF.MM_wavelength) / TIF.MM_stackCnt; MMwavelength = TIF.MM_wavelength(S*left+1:S*left+S); end if isfield( TIF, 'MM_private2' ) S = length(TIF.MM_private2) / TIF.MM_stackCnt; MMprivate2 = TIF.MM_private2(S*left+1:S*left+S); end end %% %% Parse the Metamorph camera info tag into respective fields % EVBR 2/7/2005, FJN Dec. 2007 function mm = parseMetamorphInfo(info, cnt) info = regexprep(info, '\r\n|\o0', '\n'); parse = textscan(info, '%s %s', 'Delimiter', ':'); tokens = parse{1}; values = parse{2}; % If the stk file has been created in imageJ, the delimiter used is '='. if isempty(str2mat(values)) parse = textscan(info, '%s%s', 'Delimiter', '='); tokens = parse{1}; values = parse{2}; if isempty(str2mat(values)) error('Invalid delimiter in metamorph stack info.'); end end first = char(tokens(1,1)); k = 0; mm = struct('Exposure', zeros(cnt,1)); for i=1:size(tokens,1) tok = char(tokens(i,1)); val = char(values(i,1)); %fprintf( '"%s" : "%s"\n', tok, val); if strcmp(tok, first) k = k + 1; end if strcmp(tok, 'Exposure') [v, c, e, pos] = sscanf(val, '%i'); unit = val(pos:length(val)); %return the exposure in milli-seconds switch( unit ) case 'ms' mm(k).Exposure = v; case 's' mm(k).Exposure = v * 1000; otherwise warning('tiffread2:Unit', ['Exposure unit "',unit,'" not recognized']); mm(k).Exposure = v; end else switch tok case 'Binning' % Binning: 1 x 1 -> [1 1] mm(k).Binning = sscanf(val, '%d x %d')'; case 'Region' mm(k).Region = sscanf(val, '%d x %d, offset at (%d, %d)')'; otherwise field = genvarname(regexprep(tok, ' ', '')); if strcmp(val, 'Off') eval(['mm(k).',field,'=0;']); elseif strcmp(val, 'On') eval(['mm(k).',field,'=1;']); elseif isstrprop(val,'digit') eval(['mm(k).',field,'=str2num(val)'';']); else mm(k).(field)=val; end end end end end %% ==============partial-parse of LSM info: function R = readLSMinfo() % Read part of the LSM info table version 2 % this provides only very partial information, since the offset indicate that % additional data is stored in the file global TIF; R.MagicNumber = sprintf('0x%09X',fread(TIF.file, 1, 'uint32', TIF.BOS)); StructureSize = fread(TIF.file, 1, 'uint32', TIF.BOS); R.DimensionX = fread(TIF.file, 1, 'uint32', TIF.BOS); R.DimensionY = fread(TIF.file, 1, 'uint32', TIF.BOS); R.DimensionZ = fread(TIF.file, 1, 'uint32', TIF.BOS); R.DimensionChannels = fread(TIF.file, 1, 'uint32', TIF.BOS); R.DimensionTime = fread(TIF.file, 1, 'uint32', TIF.BOS); R.IntensityDataType = fread(TIF.file, 1, 'uint32', TIF.BOS); R.ThumbnailX = fread(TIF.file, 1, 'uint32', TIF.BOS); R.ThumbnailY = fread(TIF.file, 1, 'uint32', TIF.BOS); R.VoxelSizeX = fread(TIF.file, 1, 'float64', TIF.BOS); R.VoxelSizeY = fread(TIF.file, 1, 'float64', TIF.BOS); R.VoxelSizeZ = fread(TIF.file, 1, 'float64', TIF.BOS); R.OriginX = fread(TIF.file, 1, 'float64', TIF.BOS); R.OriginY = fread(TIF.file, 1, 'float64', TIF.BOS); R.OriginZ = fread(TIF.file, 1, 'float64', TIF.BOS); R.ScanType = fread(TIF.file, 1, 'uint16', TIF.BOS); R.SpectralScan = fread(TIF.file, 1, 'uint16', TIF.BOS); R.DataType = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetVectorOverlay = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetInputLut = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetOutputLut = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetChannelColors = fread(TIF.file, 1, 'uint32', TIF.BOS); R.TimeInterval = fread(TIF.file, 1, 'float64', TIF.BOS); OffsetChannelDataTypes = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetScanInformation = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetKsData = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetTimeStamps = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetEventList = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetRoi = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetBleachRoi = fread(TIF.file, 1, 'uint32', TIF.BOS); OffsetNextRecording = fread(TIF.file, 1, 'uint32', TIF.BOS); % There are more information stored in this table, which is not read here %read real acquisition times: if ( OffsetTimeStamps > 0 ) status = fseek(TIF.file, OffsetTimeStamps, -1); if status == -1 error('error on fseek'); end StructureSize = fread(TIF.file, 1, 'int32', TIF.BOS); NumberTimeStamps = fread(TIF.file, 1, 'int32', TIF.BOS); for i=1:NumberTimeStamps R.TimeStamp(i) = fread(TIF.file, 1, 'float64', TIF.BOS); end %calculate elapsed time from first acquisition: R.TimeOffset = R.TimeStamp - R.TimeStamp(1); end end
github
mehta-lab/Instantaneous-PolScope-master
parsepropval.m
.m
Instantaneous-PolScope-master/MehtaetalPNAS2016/parsepropval.m
2,622
utf_8
71cde36da325e23d6e64232c3598e0f4
function prop = parsepropval(prop,varargin) %parsepropval: Parse property/value pairs and return a structure. % Manages property/value pairs like MathWorks Handle Graphics functions. % This means that in addition to passing in Property name strings and % Values, you can also include structures with appropriately named fields. % The full, formal property names are defined by the defaults structure % (first input argument). This is followed by any number of property/value % pairs and/or structures with property names for the field names. The % property name matching is case-insensitive and needs only be % unambiguous. % % For example, % % params.FileName = 'Untitled'; % params.FileType = 'text'; % params.Data = [1 2 3]; % s.dat = [4 5 6]; % parsepropval(params,'filenam','mydata.txt',s,'filety','binary') % % returns a structure with the same field names as params, filled in % according to the property/value pairs and structures passed in. % ans = % FileName: 'mydata.txt' % FileType: 'binary' % Data: [4 5 6] % % The inputs are processed from left to right so if any property is % specified more than once the latest value is retained. % % An error is generated if property names are ambiguous. Values can be % any MATLAB variable. % % Typical use is in a function with a variable number of input arguments. % For example, % % function myfun(varargin) % properties.prop1 = []; % properties.prop2 = 'default'; % properties = parsepropval(properties,varargin{:}); % Version: 1.0, 13 January 2009 % Author: Douglas M. Schwarz % Email: dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu % Real_email = regexprep(Email,{'=','*'},{'@','.'}) % Process inputs and set prop fields. properties = fieldnames(prop); arg_index = 1; while arg_index <= length(varargin) arg = varargin{arg_index}; if ischar(arg) prop_index = match_property(arg,properties); prop.(properties{prop_index}) = varargin{arg_index + 1}; arg_index = arg_index + 2; elseif isstruct(arg) arg_fn = fieldnames(arg); for i = 1:length(arg_fn) prop_index = match_property(arg_fn{i},properties); prop.(properties{prop_index}) = arg.(arg_fn{i}); end arg_index = arg_index + 1; else error(['Properties must be specified by property/value pairs',... ' or structures.']) end end function prop_index = match_property(arg,properties) prop_index = find(strcmpi(arg,properties)); if isempty(prop_index) prop_index = find(strncmpi(arg,properties,length(arg))); end if length(prop_index) ~= 1 error('Property ''%s'' does not exist or is ambiguous.',arg) end