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
jhwjhw0123/HSIC_Lasso_with_optimization-master
dalsqal1.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/dalsqal1.m
2,790
utf_8
976ba39446c76feaeec113048240b2b5
% dalsqal1 - DAL with the squared loss and the adaptive L1 regularization % % Overview: % Solves the optimization problem: % xx = argmin 0.5||A*x-bb||^2 + ||pp.*x||_1 % % Syntax: % [xx,status]=dalsqal1(xx, A, bb, pp, <opt>) % % Inputs: % xx : initial solution ([nn,1]) % A : the design matrix A ([mm,nn]) or a cell array {fA, fAT, mm, nn} % where fA and fAT are function handles to the functions that % return A*x and A'*x, respectively, and mm and nn are the % numbers of rows and columns of A. % bb : the target vector ([mm,1]) % pp : the regularization constant vector ([nn, 1]) % <opt> : list of 'fieldname1', value1, 'filedname2', value2, ... % stopcond : stopping condition, which can be % 'pdg' : Use relative primal dual gap (default) % 'fval' : Use the objective function value % (see dal.m for other options) % Outputs: % xx : the final solution ([nn,1]) % status : various status values % % Example: % m = 1024; n = 4096; k = round(0.04*n); A=randn(m,n); % w0=randsparse(n,k); bb=A*w0+0.01*randn(m,1); % pp=0.1*abs(A'*bb); % [ww,stat]=dalsqal1(zeros(n,1), A, bb, pp); % % Copyright(c) 2009- Ryota Tomioka, Satoshi Hara % This software is distributed under the MIT license. See license.txt function [ww,status]=dalsqal1(ww,A,bb, pp, varargin) opt=propertylist2struct(varargin{:}); opt=set_defaults(opt,'solver','cg',... 'stopcond','pdg',... 'lambda','mean'); if isscalar(pp) pp=pp*ones(length(ww),1); end switch(opt.lambda) case 'mean' lambda = mean(abs(pp)); otherwise if isnumeric(opt.lambda); lambda = opt.lambda; else lambda = 1; end end pp = pp/lambda; prob.floss = struct('p',@loss_sqp,'d',@loss_sqd,'args',{{bb}}); prob.fspec = @(xx)pp.*abs(xx); prob.dnorm = @(vv)max(abs(vv)./pp); prob.obj = @objdall1; prob.softth = @(vv,eta)al1_softth(vv,eta*pp); prob.stopcond = opt.stopcond; prob.ll = -inf*ones(size(bb)); prob.uu = inf*ones(size(bb)); prob.Ac =[]; prob.bc =[]; prob.info =[]; if isequal(opt.solver,'cg') prob.hessMult = @hessMultdall1; end if isequal(opt.stopcond,'fval') opt.feval = 1; end if isnumeric(A) A = A(:,:); [mm,nn]=size(A); At=A'; fA = struct('times',@(x)A*x,... 'Ttimes',@(x)At*x,... 'slice', @(I)A(:,I)); clear At; elseif iscell(A) mm = A{3}; nn = A{4}; fAslice = @(I)fA(sparse(I,1:length(I),ones(length(I),1), nn, length(I))); fA = struct('times',A{1},... 'Ttimes',A{2},... 'slice',fAslice); else error('A must be either numeric or cell {@(x)A*x, @(y)(A''*y), mm, nn}'); end prob.mm = mm; prob.nn = nn; [ww,uu,status]=dal(prob,ww,[],fA,[],lambda,opt);
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
gl_spec.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/gl_spec.m
324
utf_8
85b9979a663d9937f3cfa0f3ef96c135
% gl_spec - spectrum function for the grouped L1 regularizer % % Copyright(c) 2009 Ryota Tomioka % This software is distributed under the MIT license. See license.txt function nm=gl_spec(ww,blks) nn=length(blks); nm=zeros(nn,1); ixw=0; for kk=1:length(blks) I=ixw+(1:blks(kk)); ixw=I(end); nm(kk)=norm(ww(I)); end
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
loss_sqp.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/loss_sqp.m
224
utf_8
22264a52cbc12f19b18430efdb90d6a9
% loss_sqp - squared loss function % % Copyright(c) 2009 Ryota Tomioka % This software is distributed under the MIT license. See license.txt function [floss, gloss]=loss_sqp(zz, bb) gloss = zz-bb; floss = 0.5*sum(gloss.^2);
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
dalhsgl.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/dalhsgl.m
3,258
utf_8
7094eb2149ed9308f5af6fc035a3755c
% dalhsgl - DAL with hyperbolic secant loss and grouped L1 regularization % % Overview: % Solves the optimization problem: % [xx,bias] = argmin sum(log(sech(A*x+bias))) + lambda*||x||_G1 % where % ||x||_G1 = sum(sqrt(sum(xx(Ii).^2))) % (Ii is the index-set of the i-th group % % Syntax: % [xx,bias,status]=dallrgl(xx0, bias0, A, yy, lambda, <opt>) % % Inputs: % xx0 : initial solution ([nn,1] with opt.blks or [ns nc] with % ns*nc=nn for nc groups of size ns) % bias0 : initial bias (set [] if bias term is unnecessary) % A : the design matrix A ([mm,nn]) or a cell array {fA, fAT, mm, nn} % where fA and fAT are function handles to the functions that % return A*x and A'*x, respectively, and mm and nn are the % numbers of rows and columns of A. % yy : the target label vector (-1 or +1) ([mm,1]) % lambda : the regularization constant % <opt> : list of 'fieldname1', value1, 'filedname2', value2, ... % blks : vector that contains the size of the groups. % sum(opt.blks)=nn. If omitted, opt.blks = [ns,..., ns] % and length(opt.blks)=nc, where nc is the number of groups. % stopcond : stopping condition, which can be % 'pdg' : Use relative primal dual gap (default) % 'fval' : Use the objective function value % (see dal.m for other options) % Outputs: % xx : the final solution ([nn,1]) % bias : the final bias term (scalar) % status : various status values % % Example: % See s_test_hsgl.m. % % Copyright(c) 2009-2011 Ryota Tomioka % 2009 Stefan Haufe % This software is distributed under the MIT license. See license.txt function [ww,bias,status]=dalhsgl(ww, bias, A, B, yy, lambda, varargin) opt=propertylist2struct(varargin{:}); opt=set_defaults(opt,'solver','cg',... 'stopcond','pdg',... 'blks',[]); if isempty(opt.blks) opt.blks=size(ww,1)*ones(1,size(ww,2)); ww = ww(:); else if size(opt.blks,1)>size(opt.blks,2) opt.blks=opt.blks'; end end prob.floss = struct('p',@loss_hsp,'d',@loss_hsd,'args',{{yy}}); prob.fspec = @(ww)gl_spec(ww, opt.blks); prob.dnorm = @(ww)gl_dnorm(ww, opt.blks); prob.obj = @objdalgl; prob.softth = @gl_softth; prob.stopcond = opt.stopcond; prob.ll = -1*ones(size(yy)); prob.uu = ones(size(yy)); prob.Ac =[]; prob.bc =[]; prob.info = struct('blks',opt.blks); if isequal(opt.solver,'cg') prob.hessMult = @hessMultdalgl; end if isequal(opt.stopcond,'fval') opt.feval = 1; end if isnumeric(A) A = A(:,:); [mm,nn]=size(A); At=A'; fA = struct('times',@(x)A*x,... 'Ttimes',@(x)At*x,... 'slice', @(I)A(:,I)); clear At; elseif iscell(A) mm = A{3}; nn = A{4}; fAslice = @(I)fA(sparse(I,1:length(I),ones(length(I),1), nn, length(I))); fA = struct('times',A{1},... 'Ttimes',A{2},... 'slice',fAslice); else error('A must be either numeric or cell {@(x)A*x, @(y)(A''*y), mm, nn}'); end prob.mm = mm; prob.nn = nn; [ww,bias,status]=dal(prob,ww,bias,fA,B,lambda,opt); if all(opt.blks==opt.blks(1)) ns=opt.blks(1); nc=length(ww)/ns; ww=reshape(ww, [ns,nc]); end
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
dallrds.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/dallrds.m
2,882
utf_8
2ec9546bce6e8b6b9424f0ff1e4aee2a
% dallrds - DAL with logistic loss and the dual spectral norm % (trace norm) regularization % % Overview: % Solves the optimization problem: % ww = argmin sum(log(1+exp(-yy.*(A*w+b)))) + lambda*||w||_DS % % where ||w||_DS = sum(svd(w)) % % Syntax: % [ww,bias,status]=dallrds(ww, bias, A, yy, lambda, <opt>) % % Inputs: % ww : initial solution ([nn,1]) % A : the design matrix A ([mm,nn]) or a cell array {fA, fAT, mm, nn} % where fA and fAT are function handles to the functions that % return A*x and A'*x, respectively, and mm and nn are the % numbers of rows and columns of A. % yy : the target label vector (-1 or +1) ([mm,1]) % lambda : the regularization constant % <opt> : list of 'fieldname1', value1, 'filedname2', value2, ... % stopcond : stopping condition, which can be % 'pdg' : Use relative primal dual gap (default) % 'fval' : Use the objective function value % (see dal.m for other options) % Outputs: % ww : the final solution ([nn,1]) % status : various status values % % Example: % m = 2048; n = [64 64]; r = round(0.1*n(1)); A=randn(m,prod(n)); % w0=randsparse(n,'rank',r); yy=sign(A*w0(:)+0.01*randn(m,1)); % lambda=0.2*norm(reshape(A'*yy/2,n)); % [ww,bias,stat]=dallrds(zeros(n), 0, A, yy, lambda); % % Copyright(c) 2009-2011 Ryota Tomioka % This software is distributed under the MIT license. See license.txt function [ww,bias,status]=dallrds(ww, bias, A, yy, lambda, varargin) opt=propertylist2struct(varargin{:}); opt=set_defaults(opt,'solver','cg',... 'stopcond','pdg',... 'blks',[]); if isempty(opt.blks) opt.blks=size(ww); ww = ww(:); end prob.floss = struct('p',@loss_lrp,'d',@loss_lrd,'args',{{yy}}); prob.fspec = @(ww)ds_spec(ww,opt.blks); prob.dnorm = @(ww)ds_dnorm(ww,opt.blks); prob.obj = @objdalds; prob.softth = @ds_softth; prob.stopcond = opt.stopcond; prob.ll = min(0,yy); prob.uu = max(0,yy); prob.Ac =[]; prob.bc =[]; prob.info = struct('blks',opt.blks,'nsv',5*ones(1,size(opt.blks,1))); if isequal(opt.solver,'cg') prob.hessMult = @hessMultdalds; end if isnumeric(A) A = A(:,:); [mm,nn]=size(A); At=A'; fA = struct('times',@(x)A*x,... 'Ttimes',@(x)At*x,... 'slice', @(I)A(:,I)); clear At; elseif iscell(A) mm = A{3}; nn = A{4}; fAslice = @(I)fA(sparse(I,1:length(I),ones(length(I),1), nn, length(I))); fA = struct('times',A{1},... 'Ttimes',A{2},... 'slice',fAslice); else error('A must be either numeric or cell {@(x)A*x, @(y)(A''*y), mm, nn}'); end prob.mm = mm; prob.nn = nn; if isempty(bias) B = []; else B = ones(mm,1); end [ww,bias,status]=dal(prob,ww,bias,fA,B,lambda,opt); if size(opt.blks,1)==1 ww=reshape(ww,opt.blks); end
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
loss_sqdw.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/loss_sqdw.m
516
utf_8
61ee88516875cda0bd1bd4a5ed3b0468
% loss_sqd - conjugate of weighted squared loss function % % Syntax: % [floss, gloss, hloss, hmin]=loss_sqd(aa, bb, weight) % % Copyright(c) 2009 Ryota Tomioka % This software is distributed under the MIT license. See license.txt function varargout = loss_sqdw(aa, bb, weight) gloss = aa./weight-bb; floss = 0.5*sum(weight.*gloss.^2)-0.5*sum(weight.*bb.^2); hloss = spdiag(1./weight); hmin = 1/max(weight); if nargout<=3 varargout = {floss, gloss, hmin}; else varargout = {floss, gloss, hloss, hmin}; end
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
lbfgs.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/lbfgs.m
4,442
utf_8
83c09fde390bb3fe637fb9bd8997bdfb
% lbfgs - L-BFGS algorithm % % Syntax: % [xx, status] = lbfgs(fun, xx, ll, uu, <opt>) % % Input: % fun - objective function % xx - Initial point for optimization % ll - lower bound on xx % uu - upper bound on xx % Ac - inequality constraint: % bc - Ac*xx<=bc % opt - Struct or property/value list of optional properties: % .m - size of limited memory % .epsg - gradient tolerance % .maxiter - maximum number of iterations % .display - display level % % Output: % xx - Final point of optimization % status - Various numbers % % Copyright(c) 2009 Ryota Tomioka % This software is distributed under the MIT license. See license.txt function [xx, status] = lbfgs(fun, xx, ll, uu, Ac, bc, info, opt, varargin) opt=set_defaults(opt, 'm', 6,... 'ftol', 1e-5, ... 'maxiter', 0,... 'max_linesearch', 50,... 'display', 0,... 'epsg', 1e-5,... 'epsginfo', 1); if ischar(fun) fun = {fun}; end nn = size(xx,1); t0 = cputime; % Limited memory lm = repmat(struct('s',zeros(nn,1),'y',zeros(nn,1),'ys',0,'alpha',0),[1, opt.m]); [fval,gg,info]=fun(xx, info); % The initial step is gradient dd = -gg; kk = 1; stp = 1/norm(dd); bResetLBFGS = 0; ixend = 1; bound = 0; while 1 fp = fval; xxp = xx; ggp = gg; % Perform line search [ret, xx,fval,gg,info,stp]=... linesearch_backtracking(fun, xx, ll, uu, Ac, bc, fval, gg, dd, stp, info, opt, varargin{:}); if ret<0 fprintf('ginfo=%g\n',info.ginfo); break; end % Progress report gnorm = norm(gg); if opt.display>1 fprintf('[%d] xx=[%g %g...] fval=%g gnorm=%g step=%g\n',kk,xx(1),xx(2),fval,gnorm,stp); end if info.ginfo<opt.epsginfo % || gnorm<opt.epsg if opt.display>1 fprintf('Optimization success! ginfo=%g\n',info.ginfo); end ret=0; break; end if kk==opt.maxiter if opt.display>0 fprintf('Maximum #iterations=%d reached.\n', kk); end ret = -3; break; end % L-BFGS update if opt.m>0 lm(ixend).s = xx-xxp; lm(ixend).y = gg-ggp; ys = lm(ixend).y'*lm(ixend).s; yy = sum(lm(ixend).y.^2); lm(ixend).ys = ys; else ys = 1; yy = 1; end bound = min(bound+1, opt.m); ixend = (opt.m>0)*(mod(ixend, opt.m)+1); % Initially set the negative gradient as descent direction dd = -gg; jj = ixend; for ii=1:bound jj = mod(jj + opt.m -2, opt.m)+1; lm(jj).alpha = lm(jj).s'*dd/lm(jj).ys; dd = dd -lm(jj).alpha*lm(jj).y; end dd = dd *(ys/yy); for ii=1:bound beta = lm(jj).y'*dd/lm(jj).ys; dd = dd + (lm(jj).alpha-beta)*lm(jj).s; jj = mod(jj,opt.m)+1; end stp = 1.0; kk = kk + 1; end status=struct('ret', ret,... 'kk', kk,... 'fval', fval,... 'gg', gg,... 'time', cputime-t0,... 'info', info,... 'opt', opt); function [ret, xx, fval, gg, info, step]... =linesearch_backtracking(fun, xx, ll, uu, Ac, bc, fval, gg, dd, step, info, opt, varargin) floss=0; gloss=zeros(size(gg)); dginit=gg'*dd; if dginit>=0 if opt.display>0 fprintf('dg=%g is not a descending direction!\n', dginit); end step = 0; ret = -1; return; end Ip=find(dd>0); In=find(dd<0); step=min([step, 0.999*min((xx(In)-ll(In))./(-dd(In))), 0.999*min((uu(Ip)-xx(Ip))./dd(Ip))]); xx0 = xx; f0 = fval; gg0 = gg; if opt.display>2 fprintf('finit=%.20f\n',f0); end ATaa0 = info.ATaa; % The value of AT(xx0) info.ATaa = []; cc = 0; while cc<opt.max_linesearch ftest = f0 + opt.ftol*step*dginit; xx = xx0 + step*dd; if ~isempty(info.ATaa) info.ATaa = (ATaa0 + info.ATaa)/2; % Step size is decreased by % a factor 2. end if ~isempty(Ac) bineq = all(Ac*xx<=bc); else bineq = true; end if bineq && all(xx>ll) && all(xx<uu) [fval, gg, info]=fun(xx, info); if fval<=ftest break; end else fval = inf; end if opt.display>2 fprintf('[%d] step=%g fval=%.20f > ftest=%.20f\n', cc, step, fval, ftest); end step = step/2; cc = cc+1; end if cc==opt.max_linesearch if opt.display>0 fprintf('Maximum linesearch=%d reached\n', cc); end xx = xx0; [fval, gg, info]=fun(xx, info); step = 0; ret = -2; return; end ret = 0;
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
al1_softth.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/al1_softth.m
366
utf_8
0d5966a03bcccf0e0716ff9eb364d7db
% al1_softth - soft threshold function for adaptive L1 regularization % % Copyright(c) 2009- Ryota Tomioka, Satoshi Hara % This software is distributed under the MIT license. See license.txt function [vv,ss]=al1_softth(vv,pp,info) n = size(vv,1); Ip=find(vv>pp); In=find(vv<-pp); vv=sparse([Ip;In],1,[vv(Ip)-pp(Ip);vv(In)+pp(In)],n,1); ss=abs(vv);
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
dalsql1n.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/dalsql1n.m
2,565
utf_8
29827f9adfbbda961080d78bedcfa02d
% dalsql1n - DAL with the squared loss and the non-negative L1 regularization % % Overview: % Solves the optimization problem: % xx = argmin 0.5||A*x-bb||^2 + lambda*||x||_1 s.t. x>=0 % % Syntax: % [xx,status]=dalsql1(xx, A, bb, lambda, <opt>) % % Inputs: % xx : initial solution ([nn,1]) % A : the design matrix A ([mm,nn]) or a cell array {fA, fAT, mm, nn} % where fA and fAT are function handles to the functions that % return A*x and A'*x, respectively, and mm and nn are the % numbers of rows and columns of A. % bb : the target vector ([mm,1]) % lambda : the regularization constant % <opt> : list of 'fieldname1', value1, 'filedname2', value2, ... % stopcond : stopping condition, which can be % 'pdg' : Use relative primal dual gap (default) % 'fval' : Use the objective function value % (see dal.m for other options) % Outputs: % xx : the final solution ([nn,1]) % status : various status values % % Example: % m = 1024; n = 4096; k = round(0.04*n); A=randn(m,n); % w0=randsparse(n,2*k); w0(w0<0)=0; bb=A*w0+0.01*randn(m,1); % lambda=0.1*max(A'*bb); % [ww,stat]=dalsql1n(zeros(n,1), A, bb, lambda); % % Copyright(c) 2009-2011 Ryota Tomioka % 2011 Shigeyuki Oba % This software is distributed under the MIT license. See license.txt function [ww,status]=dalsql1n(ww,A,bb, lambda, varargin) opt=propertylist2struct(varargin{:}); opt=set_defaults(opt,'solver','cg',... 'stopcond','pdg'); prob.floss = struct('p',@loss_sqp,'d',@loss_sqd,'args',{{bb}}); prob.fspec = @l1n_spec; prob.dnorm = @(vv)max(vv); prob.obj = @objdall1n; prob.softth = @l1n_softth; prob.stopcond = opt.stopcond; prob.ll = -inf*ones(size(bb)); prob.uu = inf*ones(size(bb)); prob.Ac =[]; prob.bc =[]; prob.info =[]; if isequal(opt.solver,'cg') prob.hessMult = @hessMultdall1; end if isequal(opt.stopcond,'fval') opt.feval = 1; end if isnumeric(A) A = A(:,:); [mm,nn]=size(A); At=A'; fA = struct('times',@(x)A*x,... 'Ttimes',@(x)At*x,... 'slice', @(I)A(:,I)); clear At; elseif iscell(A) mm = A{3}; nn = A{4}; fAslice = @(I)fA(sparse(I,1:length(I),ones(length(I),1), nn, length(I))); fA = struct('times',A{1},... 'Ttimes',A{2},... 'slice',fAslice); else error('A must be either numeric or cell {@(x)A*x, @(y)(A''*y), mm, nn}'); end prob.mm = mm; prob.nn = nn; [ww,uu,status]=dal(prob,ww,[],fA,[],lambda,opt);
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
gl_softth.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/gl_softth.m
733
utf_8
69690be9f0204d2642cd8d56d0ed6ed9
% gl_softth - soft threshold function for grouped L1 regularization % % Copyright(c) 2009 Ryota Tomioka % This software is distributed under the MIT license. See license.txt function [vv,ss]=gl_softth(vv, lambda,info) if all(info.blks==info.blks(1)) n=length(vv); bsz=info.blks(1); vv=reshape(vv,[bsz,n/bsz]); ss0=sqrt(sum(vv.^2)); ss=max(ss0-lambda,0); J=ss0>0; vv(:,~J)=0; vv(:,J)=bsxfun(@mtimes, vv(:,J), ss(J)./ss0(J)); vv=vv(:); else ss=zeros(length(info.blks),1); ix0=0; for kk=1:length(info.blks) I=ix0+(1:info.blks(kk)); ix0=I(end); ss(kk)=norm(vv(I)); ssk=max(ss(kk)-lambda,0); if ssk>0 vv(I)=ssk/ss(kk)*vv(I); else vv(I)=0; end ss(kk)=ssk; end end
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
randsparse.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/randsparse.m
525
utf_8
9edbce6f3773a80edb5dbfbea5e78b89
% randsparse - generates a random sparse vector or a column-wise % sparse matrix % % Example: % ww = randsparse(64, 8); % ww = randsparse([64, 64], 8); % % Copyright(c) 2009 Ryota Tomioka % This software is distributed under the MIT license. See license.txt function ww = randsparse(n, k, r) if length(n)==1 I=randperm(n); ww=zeros(n,1); ww(I(1:k))=randn(k,1); elseif isnumeric(k) ww=zeros(n); I=randperm(n(2)); ww(:,I(1:k))=randn(n(1),k); else ww=randn(n(1),r)*spdiag(1:r)*randn(n(2),r)'; end
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
loss_sqd.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/loss_sqd.m
456
utf_8
5e1a573866b0ab6ef9dbf2dab1a96d33
% loss_sqd - conjugate squared loss function % % Syntax: % [floss, gloss, hloss, hmin]=loss_sqd(aa, bb) % % Copyright(c) 2009 Ryota Tomioka % This software is distributed under the MIT license. See license.txt function varargout = loss_sqd(aa, bb) gloss = aa-bb; floss = 0.5*sum(gloss.^2)-0.5*sum(bb.^2); hloss = spdiag(ones(size(aa))); hmin = 1; if nargout<=3 varargout = {floss, gloss, hmin}; else varargout = {floss, gloss, hloss, hmin}; end
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
dalsqen.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/dalsqen.m
2,721
utf_8
c3d31a07e41eed3c3facdb9c94eebd6a
% dalsqen - DAL with squared loss and the Elastic-net regularization % % Overview: % Solves the optimization problem: % [xx, bias] = argmin 0.5||A*x-bb||^2 + lambda*sum(theta*abs(x)+0.5*(1-theta)*x.^2) % % Syntax: % [xx,status]=dalsqen(xx, A, bb, lambda, theta, <opt>) % % Inputs: % xx : initial solution ([nn,1]) % A : the design matrix A ([mm,nn]) or a cell array {fA, fAT, mm, nn} % where fA and fAT are function handles to the functions that % return A*x and A'*x, respectively, and mm and nn are the % numbers of rows and columns of A. % bb : the target vector ([mm,1]) % lambda : the regularization constant % theta : parameter controlling the balance between the % L1 term and the L2 term (theta=0->L2, theta=1->L1) % <opt> : list of 'fieldname1', value1, 'filedname2', value2, ... % stopcond : stopping condition, which can be % 'pdg' : Use relative primal dual gap (default) % 'fval' : Use the objective function value % (see dal.m for other options) % Outputs: % xx : the final solution ([nn,1]) % status : various status values % % Example: % m = 1024; n = 4096; k = round(0.04*n); A=randn(m,n); % w0=randsparse(n,k); bb=A*w0+0.01*randn(m,1); % lambda=0.1*max(abs(A'*bb)); % [ww,stat]=dalsqen(zeros(n,1), A, bb, lambda, 0.5); % % Copyright(c) 2009 Ryota Tomioka % This software is distributed under the MIT license. See license.txt function [ww,status]=dalsqen(ww, A, bb, lambda, theta, varargin) opt=propertylist2struct(varargin{:}); opt=set_defaults(opt,'solver','nt',... 'stopcond','pdg'); prob.floss = struct('p',@loss_sqp,'d',@loss_sqd,'args',{{bb}}); prob.fspec = @(ww)en_spec(ww, theta); prob.dnorm = @(vv)en_dnorm(vv, lambda, theta); prob.obj = @objdalen; prob.softth = @en_softth; prob.stopcond = opt.stopcond; prob.ll = -inf*ones(size(bb)); prob.uu = inf*ones(size(bb)); prob.Ac =[]; prob.bc =[]; prob.info =struct('theta',theta); if isequal(opt.solver,'cg') prob.hessMult = @hessMultdalen; end if isequal(opt.stopcond,'fval') opt.feval = 1; end if isnumeric(A) A = A(:,:); [mm,nn]=size(A); At=A'; fA = struct('times',@(x)A*x,... 'Ttimes',@(x)At*x,... 'slice', @(I)A(:,I)); clear At; elseif iscell(A) mm = A{3}; nn = A{4}; fAslice = @(I)fA(sparse(I,1:length(I),ones(length(I),1), nn, length(I))); fA = struct('times',A{1},... 'Ttimes',A{2},... 'slice',fAslice); else error('A must be either numeric or cell {@(x)A*x, @(y)(A''*y), mm, nn}'); end prob.mm = mm; prob.nn = nn; [ww,uu,status]=dal(prob,ww,[],fA,[],lambda,opt);
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
en_softth.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/en_softth.m
450
utf_8
eb1b8dde47c826e2bcb46d180aa69e05
% en_softth - soft threshold function for the Elastic-net regularization % % Copyright(c) 2009 Ryota Tomioka % This software is distributed under the MIT license. See license.txt function [vv,ss]=en_softth(vv,lambda,info) n = size(vv,1); theta = info.theta; if theta<1 I=find(abs(vv)>lambda*theta); vv=sparse(I,1,(abs(vv(I))-lambda*theta).*sign(vv(I))/(1+lambda*(1-theta)),n,1); else vv=l1_softth(vv,lambda,info); end ss=en_spec(vv,theta);
github
jhwjhw0123/HSIC_Lasso_with_optimization-master
newton.m
.m
HSIC_Lasso_with_optimization-master/DAL_opt/newton.m
2,870
utf_8
86ab8f25bd6ab5b755f157d6b6f04e6a
% newton - a simple implementation of the Newton method % % Syntax: % [xx,fval,gg,status]=newton(fun, xx, ll, uu, Ac, bc, tol, finddir, info, verbose, varargin); % % Copyright(c) 2009 Ryota Tomioka % This software is distributed under the MIT license. See license.txt % function [xx,fval,gg,status]=newton(fun, xx, ll, uu, Ac, bc, tol, ... finddir, info, verbose, varargin) if isempty(verbose) verbose=0; end if iscell(fun) fcnHessMult = fun{2}; fun = fun{1}; else fcnHessMult = []; end if isempty(finddir) if isempty(fcnHessMult) finddir = @dir_chol; else finddir = @dir_pcg; end end n = size(xx,1); if verbose fprintf('n=%d tol=%g\n', n, tol); end cc = 0; step = nan; num_pcg = 0; while 1 [fval,gg,H,info]=fun(xx, info); if verbose fprintf('[%d] fval=%g norm(gg)=%g step=%g\n',cc, fval, norm(gg),step); end if info.ginfo<tol % || norm(gg)<1e-3 if verbose fprintf('Optimization success! ginfo=%g\n',info.ginfo); end ret = 0; status=archive('ret','cc','info','num_pcg'); break; end if isstruct(H) H.fcnHessMult=fcnHessMult; end dd = finddir(gg, H); num_pcg=num_pcg+1; [step,fval, info]=linesearch(fun, fval, xx, ll, uu, Ac, bc, dd, info, varargin{:}); if step==0 ret = -2; fprintf('[newton] max linesearch reached. ginfo=%g\n',info.ginfo); status=archive('ret','cc','info','num_pcg'); break; end xx = xx + step*dd; cc = cc+1; if cc>1000 ret = -1; fprintf('[newton] #iterations>1000.\n'); status=archive('ret','cc','info','num_pcg'); break; end end function dd = dir_chol(gg, H) R = chol(H); dd = -R\(R'\gg); %dd = pcg(H, -gg, max(1e-6,tol*0.01)); function dd = dir_pcg(gg, Hinfo) S=warning('off','all'); [dd,dum1,dum2]=pcg(Hinfo.fcnHessMult, -gg, 1e-2,... length(gg),Hinfo.prec,[],[],Hinfo); warning(S); % [dd,dum1,dum2] = pcg(@(xx)fcnHessMult(xx,Hinfo), -gg, max(1e-6,tol*0.01), length(xx),Hinfo.prec); function [step,fval, info] = linesearch(fun, fval0, xx, ll, uu, Ac, bc, dd, info, varargin) Ip=find(dd>0); In=find(dd<0); step=min([1.0, 0.999*min((xx(In)-ll(In))./(-dd(In))), 0.999*min((uu(Ip)-xx(Ip))./dd(Ip))]); xx0 = xx; ATaa0 = info.ATaa; % The value of AT(xx0) info.ATaa = []; cc = 1; while 1 xx = xx0 + step*dd; if ~isempty(info.ATaa) info.ATaa = (ATaa0 + info.ATaa)/2; % Step size is decreased by % a factor 2. end if ~isempty(Ac) bineq = all(Ac*xx<=bc); else bineq = true; end if bineq && all(ll<xx) && all(xx<uu) [fval,info] = fun(xx, info); if fval<fval0 break; end else % keyboard; end %fprintf('step=%g fval=%g (fval0=%g)\n',step, fval, fval0); step = step/2; cc = cc+1; if cc>30 fval=fval0; step = 0; break; end end
github
MatCip/Simulation_wireless_channels-master
plot_all.m
.m
Simulation_wireless_channels-master/simulation_final/rician/plot_all.m
8,108
utf_8
13a37a8d2f7fc1402bab5320338efbce
%% this function plots all the results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% plot all function plot_all() close all; load('data/all_data.mat') clc; disp('plotting...') global delta_t; lags = (0:N_step-1)*(fd*delta_t); lags = lags'; ln_wdt = 2; %line width for plot f_size = 20; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Rician pl1 = figure('Name','Rician - Second Order Statistic','NumberTitle','off'); set(pl1, 'Position', [200, 100, 800, 600]); grid on; hold on; plot(lags,real(R_sim_0{5}),':','LineWidth',ln_wdt); plot(lags,real(R_sim_1{5}),':','LineWidth',ln_wdt); plot(lags,real(R_sim_3{5}),':','LineWidth',ln_wdt); plot(lags,real(R_id_0{5}),'k','LineWidth',ln_wdt/2); plot(lags,real(R_id_1{5}),'k','LineWidth',ln_wdt/2); plot(lags,real(R_id_3{5}),'k','LineWidth',ln_wdt/2); xlabel({'Normalized Time: $f_d \tau$'},'Interpreter','latex','FontSize',f_size); ylabel({'$Re[R_{Z,Z}(\tau)]$'},'Interpreter','latex','FontSize',f_size); xlim([0,10]); ylim([-1,1.2]); legend({'$K=0$','$K=1$','$K=3$','$Theory$'},'Interpreter','latex','FontSize',f_size); pl2 = figure('Name','Rician - Second Order Statistic','NumberTitle','off'); set(pl2, 'Position', [200, 100, 800, 600]); grid on; hold on; plot(lags,R_sim_0{6},':','LineWidth',ln_wdt); plot(lags,R_sim_1{6},':','LineWidth',ln_wdt); plot(lags,R_sim_3{6},':','LineWidth',ln_wdt); plot(lags,R_id_0{6}/max(R_id_0{6}),'k','LineWidth',ln_wdt/2); plot(lags,R_id_1{6}/max(R_id_1{6}),'k','LineWidth',ln_wdt/2); plot(lags,R_id_3{6}/max(R_id_3{6}),'k','LineWidth',ln_wdt/2); xlabel({'Normalized Time: $f_d \tau$'},'Interpreter','latex','FontSize',f_size); ylabel({'Normalized $R_{|Z|^2,|Z|^2}(\tau)$'},'Interpreter','latex','FontSize',f_size); xlim([0,10]); ylim([0.4,1.2]); legend({'$K=0$','$K=1$','$K=3$','$Theory$'},'Interpreter','latex','FontSize',f_size); pl3 = figure('Name','Rician - Second Order Statistic','NumberTitle','off'); set(pl3, 'Position', [200, 100, 800, 600]); grid on; hold on; plot(lags,imag(R_sim_0{5}),':','LineWidth',ln_wdt); plot(lags,imag(R_sim_1{5}),':','LineWidth',ln_wdt); plot(lags,imag(R_sim_3{5}),':','LineWidth',ln_wdt); plot(lags,imag(R_id_0{5}),'k','LineWidth',ln_wdt/2); plot(lags,imag(R_id_1{5}),'k','LineWidth',ln_wdt/2); plot(lags,imag(R_id_3{5}),'k','LineWidth',ln_wdt/2); xlabel({'Normalized Time: $f_d \tau$'},'Interpreter','latex','FontSize',f_size); ylabel({'$Im[R_{Z,Z}(\tau)]$'},'Interpreter','latex','FontSize',f_size); xlim([0,10]); ylim([-1,1.2]); legend({'$K=0$','$K=1$','$K=3$','$Theory$'},'Interpreter','latex','FontSize',f_size); pl4 = figure('Name','Rician - Fading Envelope','NumberTitle','off'); set(pl4, 'Position', [200, 100, 800, 600]); grid on; hold on; x = linspace(0,4,500); plot(x,pdf_sim_0{1},':','LineWidth',ln_wdt); plot(x,pdf_sim_1{1},':','LineWidth',ln_wdt); plot(x,pdf_sim_3{1},':','LineWidth',ln_wdt); plot(x,pdf_sim_5{1},':','LineWidth',ln_wdt); plot(x,pdf_sim_10{1},':','LineWidth',ln_wdt); plot(x,pdf_id_0{1},'k','LineWidth',ln_wdt/2); plot(x,pdf_id_1{1},'k','LineWidth',ln_wdt/2); plot(x,pdf_id_3{1},'k','LineWidth',ln_wdt/2); plot(x,pdf_id_5{1},'k','LineWidth',ln_wdt/2); plot(x,pdf_id_10{1},'k','LineWidth',ln_wdt/2); xlabel({'$z$'},'Interpreter','latex','FontSize',f_size); ylabel({'$f_{|Z|}(z)$'},'Interpreter','latex','FontSize',f_size); xlim([0,4]); ylim([-0.2,2]); legend({'$K=0 (N=8)$','$K=1 (N=8)$','$K=3 (N=8)$','$K=5 (N=8)$','$K=10 (N=8)$','$Theory (N=\infty)$'},'Interpreter','latex','FontSize',f_size); pl5 = figure('Name','Rician - Fading Envelope','NumberTitle','off'); set(pl5, 'Position', [200, 100, 800, 600]); grid on; hold on; x1 = linspace(-1,1,50); x = linspace(-1,1,500); plot(x1,smooth(pdf_sim_0{2},0.9),':','LineWidth',ln_wdt); plot(x1,smooth(pdf_sim_1{2},0.5),':','LineWidth',ln_wdt); plot(x1,smooth(pdf_sim_3{2},0.5),':','LineWidth',ln_wdt); plot(x1,smooth(pdf_sim_5{2},0.5),':','LineWidth',ln_wdt); plot(x1,smooth(pdf_sim_10{2},0.5),':','LineWidth',ln_wdt); plot(x,pdf_id_0{2},'k','LineWidth',ln_wdt/2); plot(x,pdf_id_1{2},'k','LineWidth',ln_wdt/2); plot(x,pdf_id_3{2},'k','LineWidth',ln_wdt/2); plot(x,pdf_id_5{2},'k','LineWidth',ln_wdt/2); plot(x,pdf_id_10{2},'k','LineWidth',ln_wdt/2); xlabel({'$\psi (\times \pi)$'},'Interpreter','latex','FontSize',f_size); ylabel({'$f_{\Psi}(\psi)$'},'Interpreter','latex','FontSize',f_size); xlim([-1,1]); ylim([0.14,0.18]); legend({'$K=0 (N=8)$','$K=1 (N=8)$','$K=3 (N=8)$','$K=5 (N=8)$','$K=10 (N=8)$','$Theory (N=\infty)$'},'Interpreter','latex','FontSize',f_size); pl6 = figure('Name','Rician - Level Crossing Rate','NumberTitle','off'); rho_db = 20*log10(rho); set(pl6, 'Position', [200, 100, 800, 600]); semilogy(rho_db, LCR_sim_0,':','LineWidth',ln_wdt); grid on; hold on; semilogy(rho_db, LCR_sim_1,':','LineWidth',ln_wdt); grid on; hold on; semilogy(rho_db, LCR_sim_3,':','LineWidth',ln_wdt); grid on; hold on; semilogy(rho_db, LCR_sim_5,':','LineWidth',ln_wdt); grid on; hold on; semilogy(rho_db, LCR_sim_10,':','LineWidth',ln_wdt); grid on; hold on; semilogy(rho_db, LCR_id_0,'k','LineWidth',ln_wdt/2); semilogy(rho_db, LCR_id_1,'k','LineWidth',ln_wdt/2); semilogy(rho_db, LCR_id_3,'k','LineWidth',ln_wdt/2); semilogy(rho_db, LCR_id_5,'k','LineWidth',ln_wdt/2); semilogy(rho_db, LCR_id_10,'k','LineWidth',ln_wdt/2); xlabel({'Normalized fading envelope level $\rho$ [dB]'},'Interpreter','latex','FontSize',f_size); ylabel({'Normalized LCR'},'Interpreter','latex','FontSize',f_size); xlim([-25,10]); ylim([1e-3,10^0.5]); legend({'$K=0 (N=8)$','$K=1 (N=8)$','$K=3 (N=8)$','$K=5 (N=8)$','$K=10 (N=8)$','$Theory (N=\infty)$'},'Interpreter','latex','FontSize',f_size,'Location','northwest'); pl7 = figure('Name','Rician - Average Fading Duration','NumberTitle','off'); rho_db = 20*log10(rho); set(pl7, 'Position', [200, 100, 800, 600]); semilogy(rho_db, AFD_sim_0, ':', 'LineWidth', ln_wdt); grid on; hold on; semilogy(rho_db, AFD_sim_1, ':', 'LineWidth', ln_wdt); semilogy(rho_db, AFD_sim_3, ':', 'LineWidth', ln_wdt); semilogy(rho_db, AFD_sim_5, ':', 'LineWidth', ln_wdt); semilogy(rho_db, AFD_sim_10, ':', 'LineWidth', ln_wdt); semilogy(rho_db, AFD_id_0, 'k', 'LineWidth', ln_wdt/2); semilogy(rho_db, AFD_id_1, 'k', 'LineWidth', ln_wdt/2); semilogy(rho_db, AFD_id_3, 'k', 'LineWidth', ln_wdt/2); semilogy(rho_db, AFD_id_5, 'k', 'LineWidth', ln_wdt/2); semilogy(rho_db, AFD_id_10, 'k', 'LineWidth', ln_wdt/2); xlabel({'Normalized fading envelope level $\rho$ [dB]'},'Interpreter','latex','FontSize',f_size); ylabel({'Normalized AFD'},'Interpreter','latex','FontSize',f_size); xlim([-20,5]); ylim([10^-1.3,10^1]); legend({'$K=0 (N=8)$','$K=1 (N=8)$','$K=3 (N=8)$','$K=5 (N=8)$','$K=10 (N=8)$','$Theory (N=\infty)$'},'Interpreter','latex','FontSize',f_size,'Location','northwest'); %% save plots plots = cell(1,7); plots{1} = pl1; plots{2} = pl2; plots{3} = pl3; plots{4} = pl4; plots{5} = pl5; plots{6} = pl6; plots{7} = pl7; %save_plots(plots); %save plots clc;disp('Simulation is finished!') end %% save plots function save_plots(pl) clc;disp('Saving Plots...') saveas(pl{1}, 'graphs/rician_re_rgrg','epsc'); saveas(pl{2}, 'graphs/rician_r2r2','epsc'); saveas(pl{3}, 'graphs/rician_im_rgrg','epsc'); saveas(pl{4}, 'graphs/rician_pdf_abs','epsc'); saveas(pl{5}, 'graphs/rician_pdf_ph','epsc'); saveas(pl{6}, 'graphs/rician_lcr','epsc'); saveas(pl{7}, 'graphs/rician_afd','epsc'); end
github
MatCip/Simulation_wireless_channels-master
gen_channel.m
.m
Simulation_wireless_channels-master/simulation_final/rician/gen_channel.m
5,371
utf_8
d7f08970519eb0f6183f880a4d711468
%% this function implement the channel based on the work of Jakes, Pop-Beaulieu and Xiao-Zheng. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % INPUT: % str_mode : string for selecting which channel has to be computed. % N_stat : number of statistical trials. % K : ratio between power of LoS and power of non-LoS. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % OUTPUT: % g : fading, % pdf : a cell that contains the pdf of the absolute value of g and % the pdf of the phase of g. % R : a cell that contains the autocorrelations and the % crosscorrelations of the fading g. % rho : normalized levels for lcr and afd. % LCR : level crossing rate. % AFD : average fading duration. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% generate channels function [g,pdf,R,rho,LCR,AFD] = gen_channel(str_mode,N_stat,K) global N_step; global delta_t; global theta_0; global N; global fd; % R{1} = Rgcgc, R{2} = Rgsgs, R{3} = Rgcgs, R{4} = Rgsgc, R{5} = Rgg, % R{6} = Rg2g2. g = zeros(N_step,1); pdf = cell(1,2); pdf{1} = zeros(1,500); pdf{2} = zeros(1,50); R = cell(1,6); for i=1:6 R{i} = zeros(N_step,1); end N_lev = 1000; normalize = true; rho = zeros(N_lev,1); LCR = zeros(N_lev,1); AFD = zeros(N_lev,1); switch str_mode case 'sim_rician' for i=1:N_stat clc; disp(strcat('Generating Simulated Rician Channel... (N_stat_max=',num2str(N_stat),')')) disp(strcat('N_stat=',num2str(i))) disp(strcat('K=',num2str(K))) %generate the temporary channel [g_temp,pdf_temp,R_temp] = gen_si_rician_ch(N,fd,K); [rho, LCR_temp, AFD_temp] = get_LCR_AFD(g_temp,fd,'simulated',0,normalize,N_lev); %update g = g + g_temp/N_stat; for j=1:2 pdf{j} = pdf{j} + pdf_temp{j}/N_stat; end for j=1:6 R{j} = R{j} + R_temp{j}/N_stat; end LCR = LCR + LCR_temp/N_stat; AFD = AFD + AFD_temp/N_stat; end case 'id_rician' clc; disp('Generating Ideal Rician Channel...') disp(strcat('K=',num2str(K))) r = linspace(0,4,500); pdf = cell(1,2); pdf{1} = 2*(1+K)*r.*exp(-K-(1+K)*r.^2).*besseli(0,2*r*sqrt(K*(K+1))); pdf{2} = 1/(2*pi)*ones(1,size(r,2)); g=0; R = cell(1,6); lags = (0:N_step-1)*(fd*delta_t); lags = lags'; wd_tau = 2*pi*lags; bes = besselj(0,wd_tau); R{1} = (bes + K*cos(wd_tau*cos(theta_0)))/(2+2*K); R{2} = R{1}; R{3} = K*sin(wd_tau*cos(theta_0))/(2+2*K); R{4} = -R{3}; R{5} = (bes + K*cos(wd_tau*cos(theta_0)) + 1i*K*sin(wd_tau*cos(theta_0)))/(1+K); load('data/fc_fs.mat'); R{6} = (1 + bes.^2 + K^2 - f_c - f_s + 2*K*(1 + bes.*cos(wd_tau*cos(theta_0))))/(1+K)^2; [lev, LCR, AFD] = get_LCR_AFD(g,fd,'id_rician',K,normalize,N_lev); rho = lev; otherwise disp('Error in string mode.'); end end %% Simulated Rician function [z,pdf,R] = gen_si_rician_ch(N,fd,K) global time; global theta_0; %------------------------ w_0 = 2*pi*fd; y_c = zeros(size(time,1),1); y_s = zeros(size(time,1),1); for n = 1:N theta_n = rand(1,1)*2*pi-pi; phi_n = rand(1,1)*2*pi-pi; alpha_n = (2*pi*n + theta_n)/N; y_c = y_c + 1/sqrt(N)*cos(w_0*time*cos(alpha_n) + phi_n); y_s = y_s + 1/sqrt(N)*sin(w_0*time*cos(alpha_n) + phi_n); end phi_0 = rand(1,1)*2*pi-pi; z_c = (y_c + sqrt(K)*cos(w_0*time*cos(theta_0)+phi_0))/sqrt(1+K); z_s = (y_s + sqrt(K)*sin(w_0*time*cos(theta_0)+phi_0))/sqrt(1+K); z = z_c + 1i*z_s; F = abs(z); %fading power [pdf_abs,~] = ksdensity(F,linspace(0,4,500));% pdf of fading power TH = angle(z); pdf_ph = get_pdf_ph(TH,50); pdf = cell(1,2); pdf{1} = pdf_abs; pdf{2} = pdf_ph; R = get_corr(z,z_c,z_s); R{5} = R{5}/2; R{6} = R{6}/8; end %% get cross correlation function R = get_corr(g,gr,gi) global N_step; R = cell(6,1); Rgcgc = xcorr(gr,gr,'coeff'); Rgcgc = Rgcgc(N_step:end); Rgsgs = xcorr(gi,gi,'coeff'); Rgsgs= Rgsgs(N_step:end); Rgcgs = xcorr(gr,gi,'coeff'); Rgcgs = Rgcgs(N_step:end); Rgsgc = xcorr(gi,gr,'coeff'); Rgsgc = Rgsgc(N_step:end); Rgg = 2*xcorr(g,g,'coeff'); Rgg = Rgg(N_step:end); Rg2g2 = 8*xcorr(abs(g).^2,abs(g).^2,'coeff'); Rg2g2 = Rg2g2(N_step:end); R{1} = Rgcgc; R{2} = Rgsgs; R{3} = Rgcgs; R{4} = Rgsgc; R{5} = Rgg; R{6} = Rg2g2; end %% get pdf phase function pdf_ph = get_pdf_ph(TH,n_points) edges = linspace(-pi,pi,n_points+1); d_theta = edges(2)-edges(1); [counts,edges] = histcounts(TH,edges); pdf_ph = counts/(sum(counts)*d_theta); end
github
MatCip/Simulation_wireless_channels-master
get_LCR_AFD.m
.m
Simulation_wireless_channels-master/simulation_final/rician/get_LCR_AFD.m
2,768
utf_8
806e5e3a3e989ed30153d6d4dc796058
%% this function compute the LCR and the AFD. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % INPUT: % g : fading, % fd : doppler frequency. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % OUTPUT: % lambda : lambda = R/Rrms where R is the level, % LCR_id : ideal level crossing rate, % LCR : computed level crossing rate, % AFD_id : ideal average fade duration, % AFD : computed average fade duration. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% function [rho, LCR, AFD] = get_LCR_AFD(g,fd,str_mode,K,normalize,N_dim) global N_step; global delta_t; global theta_0; F = abs(g); %fading rho_db = linspace(-30,10,N_dim); rho = 10.^(rho_db/20); R = rho*rms(F); %% ideal LCR and AFD LCR = zeros(N_dim,1); AFD = zeros(N_dim,1); switch str_mode case 'id_rayleigh' LCR = sqrt(2*pi)*fd*rho.*exp(-rho.^2); AFD = (exp(rho.^2)-1)./(rho*fd*sqrt(2*pi)); if normalize AFD = AFD*fd; LCR = LCR/fd; end case 'id_rician' %LCR_id rician alpha=0:0.001:pi; delta_area=zeros(length(rho),length(alpha)-1); for j=1:length(rho) for i=1:1:length(alpha)-1 delta_area(j,i)=(alpha(i+1)-alpha(i))*(1+(2/rho(j))*sqrt(K/(1+K))*(cos(theta_0))^2*cos(alpha(i+1)))*exp(2*rho(j)*sqrt(K*(1+K))*cos(alpha(i+1))-2*K*(cos(theta_0))^2*(sin(alpha(i+1)))^2); end end sum_area=sum(delta_area,2); LCR = (sqrt(2*(1+K)/pi)*rho*fd).*exp(-K-(1+K)*(rho.^2)).*(sum_area)'; %AFD_id rician for i=1:1:length(AFD) AFD(i)= (1 - marcumq(sqrt(2*K),sqrt(2*(1+K)*(rho(i)^2)),1))/LCR(i); end %%%%% %normalization AFD = AFD*fd; LCR = LCR/fd; case 'simulated' %% simulated LCR and AFD for i=1:N_dim g_trasl = F-R(i); g_trasl_abs = abs(F-R(i)); g_diff = g_trasl-g_trasl_abs; for j=1:(N_step-1) if g_diff(j)==0 && g_diff(j+1)~=0; LCR(i) = LCR(i)+1; end end LCR(i) = LCR(i)/(N_step*delta_t); AFD(i) = mean(g_trasl<0)/LCR(i); end if normalize AFD = AFD*fd; LCR = LCR/fd; end end end
github
MatCip/Simulation_wireless_channels-master
plot_all.m
.m
Simulation_wireless_channels-master/simulation_final/rayleigh/plot_all.m
11,263
utf_8
33c2e81974d2bb87364373b109d19f39
%% this function plots all the results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% plot all function plot_all() close all; load('data/all_data.mat') clc; disp('plotting...') global delta_t; ln_wdt = 2; %line width for plot f_size = 20; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Pop - Beaulieu pl1 = figure('Name','Pop/Beaulieu - Fading Envelope','NumberTitle','off'); set(pl1, 'Position', [200, 100, 800, 600]); grid on; hold on; x = linspace(0,4,500); plot(x,pdf_2_id{1},'k','LineWidth',ln_wdt); plot(x,pdf_2_3{1},':','LineWidth',ln_wdt); plot(x,pdf_2_4{1},'-.','LineWidth',ln_wdt); plot(x,pdf_2_8{1},'--','LineWidth',ln_wdt); xlabel({'$r$'},'Interpreter','latex','FontSize',f_size); ylabel({'$f_{|g|}(r)$'},'Interpreter','latex','FontSize',f_size); xlim([0,4]); legend({'Reference','$M=3$','$M=4$','$M=8$'},'Interpreter','latex','FontSize',f_size); %% Xiao - Zheng pl2 = figure('Name','Xiao/Zheng - Second Order Statistic','NumberTitle','off'); set(pl2, 'Position', [200, 100, 800, 600]); lags_3 = (0:N_step-1)*(fd_3*delta_t); lags_3 = lags_3'; grid on; hold on; plot(lags_3,R_3_id{1},'k','LineWidth',ln_wdt); plot(lags_3,R_3_10{1},':','LineWidth',ln_wdt); plot(lags_3,R_3_50{1},'-.','LineWidth',ln_wdt); plot(lags_3,R_3_100{1},'--','LineWidth',ln_wdt); xlabel({'Normalized Time: $f_d \tau$'},'Interpreter','latex','FontSize',f_size); ylabel({'$R_{X_c,X_c}(\tau)$'},'Interpreter','latex','FontSize',f_size); xlim([0,t_sim]); legend({'Reference','$N_{stat}=10$','$N_{stat}=50$','$N_{stat}=100$'},'Interpreter','latex','FontSize',f_size); pl3 = figure('Name','Xiao/Zheng - Second Order Statistic','NumberTitle','off'); set(pl3, 'Position', [200, 100, 800, 600]); lags_3 = (0:N_step-1)*(fd_3*delta_t); lags_3 = lags_3'; grid on; hold on; plot(lags_3,R_3_id{3},'k','LineWidth',ln_wdt); plot(lags_3,R_3_10{3},':','LineWidth',ln_wdt); plot(lags_3,R_3_50{3},'-.','LineWidth',ln_wdt); plot(lags_3,R_3_100{3},'--','LineWidth',ln_wdt); xlabel({'Normalized Time: $f_d \tau$'},'Interpreter','latex','FontSize',f_size); ylabel({'$R_{X_c,X_s}(\tau)$'},'Interpreter','latex','FontSize',f_size); ylim([-0.5,0.5]); xlim([0,t_sim]); legend({'Reference','$N_{stat}=10$','$N_{stat}=50$','$N_{stat}=100$'},'Interpreter','latex','FontSize',f_size); pl4 = figure('Name','Xiao/Zheng - Second Order Statistic','NumberTitle','off'); set(pl4, 'Position', [200, 100, 800, 600]); lags_3 = (0:N_step-1)*(fd_3*delta_t); lags_3 = lags_3'; grid on; hold on; plot(lags_3,R_3_id{2},'k','LineWidth',ln_wdt); plot(lags_3,R_3_10{2},':','LineWidth',ln_wdt); plot(lags_3,R_3_50{2},'-.','LineWidth',ln_wdt); plot(lags_3,R_3_100{2},'--','LineWidth',ln_wdt); xlabel({'Normalized Time: $f_d \tau$'},'Interpreter','latex','FontSize',f_size); ylabel({'$R_{X_s,X_s}(\tau)$'},'Interpreter','latex','FontSize',f_size); xlim([0,t_sim]); legend({'Reference','$N_{stat}=10$','$N_{stat}=50$','$N_{stat}=100$'},'Interpreter','latex','FontSize',f_size); pl5 = figure('Name','Xiao/Zheng - Second Order Statistic','NumberTitle','off'); set(pl5, 'Position', [200, 100, 800, 600]); lags_3 = (0:N_step-1)*(fd_3*delta_t); lags_3 = lags_3'; grid on; hold on; plot(lags_3,real(R_3_id{5}),'k','LineWidth',ln_wdt); plot(lags_3,real(R_3_10{5}),':','LineWidth',ln_wdt); plot(lags_3,real(R_3_50{5}),'-.','LineWidth',ln_wdt); plot(lags_3,real(R_3_100{5}),'--','LineWidth',ln_wdt); xlabel({'Normalized Time: $f_d \tau$'},'Interpreter','latex','FontSize',f_size); ylabel({'Re[$R_{X,X}(\tau)$]'},'Interpreter','latex','FontSize',f_size); xlim([0,t_sim]);ylim([-1,2]); legend({'Reference','$N_{stat}=10$','$N_{stat}=50$','$N_{stat}=100$'},'Interpreter','latex','FontSize',f_size); pl6 = figure('Name','Xiao/Zheng - Second Order Statistic','NumberTitle','off'); set(pl6, 'Position', [200, 100, 800, 600]); lags_3 = (0:N_step-1)*(fd_3*delta_t); lags_3 = lags_3'; grid on; hold on; plot(lags_3,imag(R_3_id{5}),'k','LineWidth',ln_wdt); plot(lags_3,imag(R_3_10{5}),':','LineWidth',ln_wdt); plot(lags_3,imag(R_3_50{5}),'-.','LineWidth',ln_wdt); plot(lags_3,imag(R_3_100{5}),'--','LineWidth',ln_wdt); xlabel({'Normalized Time: $f_d \tau$'},'Interpreter','latex','FontSize',f_size); ylabel({'Im[$R_{X,X}(\tau)$]'},'Interpreter','latex','FontSize',f_size); xlim([0,t_sim]);ylim([-0.5,0.5]); legend({'Reference','$N_{stat}=10$','$N_{stat}=50$','$N_{stat}=100$'},'Interpreter','latex','FontSize',f_size); pl7 = figure('Name','Xiao/Zheng - Second Order Statistic','NumberTitle','off'); set(pl7, 'Position', [200, 100, 800, 600]); lags_3 = (0:N_step-1)*(fd_3*delta_t); lags_3 = lags_3'; grid on; hold on; plot(lags_3,R_3_id{6},'k','LineWidth',ln_wdt); plot(lags_3,R_3_10{6},':','LineWidth',ln_wdt); plot(lags_3,R_3_50{6},'-.','LineWidth',ln_wdt); plot(lags_3,R_3_100{6},'--','LineWidth',ln_wdt); xlabel({'Normalized time: $f_d \tau$'},'Interpreter','latex','FontSize',f_size); ylabel({'$R_{|X|^2,|X|^2}(\tau)$'},'Interpreter','latex','FontSize',f_size); xlim([0,t_sim]); legend({'Reference','$N_{stat}=10$','$N_{stat}=50$','$N_{stat}=100$'},'Interpreter','latex','FontSize',f_size); pl8 = figure('Name','Xiao/Zheng - Fading Envelope','NumberTitle','off'); set(pl8, 'Position', [200, 100, 800, 600]); grid on; hold on; x = linspace(0,4,500); plot(x,pdf_3_id{1},'k','LineWidth',ln_wdt); plot(x,pdf_3_10{1},':','LineWidth',ln_wdt); plot(x,pdf_3_50{1},'-.','LineWidth',ln_wdt); plot(x,pdf_3_100{1},'--','LineWidth',ln_wdt); xlabel({'$x$'},'Interpreter','latex','FontSize',f_size); ylabel({'$f_{|X|}(x)$'},'Interpreter','latex','FontSize',f_size); xlim([0,4]); legend({'Reference','$N_{stat}=10$','$N_{stat}=50$','$N_{stat}=100$'},'Interpreter','latex','FontSize',f_size); pl9 = figure('Name','Xiao/Zheng - Fading Envelope','NumberTitle','off'); set(pl9, 'Position', [200, 100, 800, 600]); grid on; hold on; xlabel({'$\theta_X$ ($\times \pi$)'},'Interpreter','latex','FontSize',f_size); x = linspace(-1,1,30); x1 = linspace(-1,1,500); plot(x1,pdf_3_id{2},'k','LineWidth',ln_wdt); plot(x,smooth(pdf_3_10{2}',1-1e-12),':','LineWidth',ln_wdt); plot(x,smooth(pdf_3_50{2}',0.9999999),'-.','LineWidth',ln_wdt); plot(x,smooth(pdf_3_100{2}',0.8),'--','LineWidth',ln_wdt); ylabel({'$f_{\theta_X}(\theta_X)$'},'Interpreter','latex','FontSize',f_size); xlim([-1,1]); ylim([0.13,0.19]); legend({'Reference','$N_{stat}=10$','$N_{stat}=50$','$N_{stat}=100$'},'Interpreter','latex','FontSize',f_size); pl10 = figure('Name','Xiao/Zheng - Level Crossing Rate','NumberTitle','off'); set(pl10, 'Position', [200, 100, 800, 600]); semilogy(20*log10(lambda_3_10),LCR_3_id,'k','LineWidth',ln_wdt); grid on; hold on; semilogy(20*log10(lambda_3_10),LCR_3_10,':','LineWidth',ln_wdt); semilogy(20*log10(lambda_3_50),LCR_3_50,'-.','LineWidth',ln_wdt); semilogy(20*log10(lambda_3_100),LCR_3_100,'--','LineWidth',ln_wdt); xlabel({'Normalized fading envelope level $\rho$ [dB]'},'Interpreter','latex','FontSize',f_size); ylabel({'Normalized LCR'},'Interpreter','latex','FontSize',f_size); xlim([-30,10]); ylim([10^-3,10^1]); legend({'Reference','$N_{stat}=10$','$N_{stat}=50$','$N_{stat}=100$'},'Interpreter','latex','FontSize',f_size,'Location','northwest'); pl11 = figure('Name','Xiao/Zheng - Average Fading Duration','NumberTitle','off'); set(pl11, 'Position', [200, 100, 800, 600]); semilogy(20*log10(lambda_3_10),AFD_3_id,'k','LineWidth',ln_wdt); grid on; hold on; semilogy(20*log10(lambda_3_10),AFD_3_10,':','LineWidth',ln_wdt); semilogy(20*log10(lambda_3_50),AFD_3_50,'-.','LineWidth',ln_wdt); semilogy(20*log10(lambda_3_100),AFD_3_100,'--','LineWidth',ln_wdt); xlabel({'Normalized fading envelope level $\rho$ [dB]'},'Interpreter','latex','FontSize',f_size); ylabel({'Normalized AFD'},'Interpreter','latex','FontSize',f_size); xlim([-30,5]); ylim([10^-2,10^1.5]); legend({'Reference','$N_{stat}=10$','$N_{stat}=50$','$N_{stat}=100$'},'Interpreter','latex','FontSize',f_size,'Location','northwest'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Komninakis paper pl12 = figure('Name','Komninakis - Magnitude Response of the Filter','NumberTitle','off'); set(pl12, 'Position', [200, 100, 800, 600]); M = 500; W = linspace(0,1,M+1); hold on; grid on; plot(W,20*log10(Y),'k','LineWidth',ln_wdt); plot(W,20*log10(abs(H_abs)),'r','LineWidth',ln_wdt/2); ylim([-80,20]); xlim([0,1]); xlabel({'Normalized Frequency $f_d\tau$ (1 = Fc/2)'},'Interpreter','latex','FontSize',f_size); ylabel({'$|$H$|$ [dB]'},'Interpreter','latex','FontSize',f_size); legend({'Ideal Deideres Response','Designed Response'},'Interpreter','latex','FontSize',f_size); pl13 = figure('Name','Komninakis - Second Order Statistic','NumberTitle','off'); set(pl13, 'Position', [200, 100, 800, 600]); grid on; hold on; R_id_shift = besselj(0,1/pi*linspace(-100,100,N_step)); plot(-N_step+1:N_step-1,real(R_4{5}),'--','LineWidth',ln_wdt); plot(-N_step+1:N_step-1,imag(R_4{5}),'--','LineWidth',ln_wdt); plot(linspace(-100,100,N_step),real(R_id_shift),'k','LineWidth',ln_wdt/2); plot(linspace(-100,100,N_step),imag(R_id_shift),'k','LineWidth',ln_wdt/2); xlabel({'Correlation lag in samples'},'Interpreter','latex','FontSize',f_size); xlim([-100,100]); legend({'Simulated Re[$R_{g,g}$]','Simulated Im[$R_{g,g}$]','Theory'},'Interpreter','latex','FontSize',f_size); %% pl = cell(13,1); pl{1 } = pl1; pl{2 } = pl2; pl{3 } = pl3; pl{4 } = pl4; pl{5 } = pl5; pl{6 } = pl6; pl{7 } = pl7; pl{8 } = pl8; pl{9 } = pl9; pl{10} = pl10; pl{11} = pl11; pl{12} = pl12; pl{13} = pl13; %save_plots(pl); %save plots clc;disp('Simulation is finished!') end %% save plots function save_plots(pl) clc;disp('Saving Plots...') saveas(pl{1 }, 'graphs/pop_beaulieu_fading_abs','epsc'); saveas(pl{2 }, 'graphs/xiao_zheng_rgcgc','epsc'); saveas(pl{3 }, 'graphs/xiao_zheng_rgcgs','epsc'); saveas(pl{4 }, 'graphs/xiao_zheng_rgsgs','epsc'); saveas(pl{5 }, 'graphs/xiao_zheng_re_rgg','epsc'); saveas(pl{6 }, 'graphs/xiao_zheng_im_rgg','epsc'); saveas(pl{7 }, 'graphs/xiao_zheng_rg2g2','epsc'); saveas(pl{8 }, 'graphs/xiao_zheng_fading_abs','epsc'); saveas(pl{9 }, 'graphs/xiao_zheng_fading_ang','epsc'); saveas(pl{10}, 'graphs/xiao_zheng_lcr','epsc'); saveas(pl{11}, 'graphs/xiao_zheng_afd','epsc'); saveas(pl{12}, 'graphs/komninakis_filter','epsc'); saveas(pl{13}, 'graphs/komninakis_rgg','epsc'); end
github
MatCip/Simulation_wireless_channels-master
gen_channel.m
.m
Simulation_wireless_channels-master/simulation_final/rayleigh/gen_channel.m
8,027
utf_8
95e0c7cfd00be2996af5b3813972ac23
%% this function implement the channel based on the work of Jakes, Pop-Beaulieu and Xiao-Zheng. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % INPUT: % M : N = 4*M+2 where N is the number of oscillators in the Jakes % simulator, % fd : the doppler frequency, % str_mode : string for selecting which channel has to be computed, % N_stat : number of statistical trials. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % OUTPUT: % g : fading, % pdf : a cell that contains the pdf of the absolute value of g and % the pdf of the phase of g, % R : a cell that contains the autocorrelations and the % crosscorrelations of the fading g. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% generate channels function [g,pdf,R,rho,LCR_id,LCR,AFD_id,AFD] = gen_channel(M,fd,str_mode,N_stat) global N_step; global delta_t; % R{1} = Rgcgc, R{2} = Rgsgs, R{3} = Rgcgs, R{4} = Rgsgc, R{5} = Rgg, % R{6} = Rg2g2. g = zeros(N_step,1); pdf = cell(1,2); pdf{1} = zeros(1,500); pdf{2} = zeros(1,30); R = cell(1,6); for i=1:6 R{i} = zeros(N_step,1); end N_lev = 1000; normalize = true; rho = zeros(N_lev,1); LCR = zeros(N_lev,1); AFD = zeros(N_lev,1); LCR_id = zeros(N_lev,1); AFD_id = zeros(N_lev,1); switch str_mode case 'ideal' clc; disp('Generating Ideal Channel...') R = cell(1,6); g=0; lags = (0:N_step-1)*(fd*delta_t); lags = lags'; R{1} = besselj(0,2*pi*lags); R{2} = besselj(0,2*pi*lags); R{3} = zeros(N_step,1); R{4} = zeros(N_step,1); R{5} = 2*besselj(0,2*pi*lags); R{6} = 4 + 4*besselj(0,2*pi*lags).^2; r = linspace(0,4,500); theta = ones(1,500); pdf_abs = r.*exp(-r.^2/2); pdf_ph = 1/(2*pi)*theta; pdf = cell(1,2); pdf{1} = pdf_abs; pdf{2} = pdf_ph; case 'jakes' clc; disp('Generating Jakes Channel...') [g,pdf,R] = gen_rayleigh_ch_1(M,fd); case 'pop_beaulieu' for i=1:N_stat clc; disp(strcat('Generating Pop-Beaulieu Channel... (N_stat_max=',num2str(N_stat),')',' M=',num2str(M))) disp(strcat('N_stat=',num2str(i))) [g_temp,pdf_temp,R_temp] = gen_rayleigh_ch_2(M,fd); %g= fading g = g + g_temp/N_stat; for j=1:2 pdf{j} = pdf{j} + pdf_temp{j}/N_stat; end for j=1:6 R{j} = R{j} + R_temp{j}/N_stat; end end case 'zheng_xiao' for i=1:N_stat clc; disp(strcat('Generating Zheng-Xiao Channel... (N_stat_max=',num2str(N_stat),')')) disp(strcat('N_stat=',num2str(i))) %generate the temporary channel [g_temp,pdf_temp,R_temp] = gen_rayleigh_ch_3(M,fd); [rho, LCR_temp, AFD_temp] = get_LCR_AFD(g_temp,fd,'simulated',0,normalize,N_lev); %update g = g + g_temp/N_stat; for j=1:2 pdf{j} = pdf{j} + pdf_temp{j}/N_stat; end for j=1:6 R{j} = R{j} + R_temp{j}/N_stat; end LCR = LCR + LCR_temp/N_stat; AFD = AFD + AFD_temp/N_stat; end [rho,LCR_id,AFD_id] = get_LCR_AFD(g,fd,'id_rayleigh',0,normalize,N_lev); otherwise disp('Error in string mode.'); end end %% ch_1 Jakes function [g,pdf,R] = gen_rayleigh_ch_1(M,fd) global time; N=4*M+2; %------------------------ beta_0 = pi/4; a_0 = sqrt(2)*cos(beta_0); b_0 = sqrt(2)*sin(beta_0); w_0 = 2*pi*fd; phi = 0; %------------------------ gr = a_0*cos(w_0*time + phi); gi = b_0*cos(w_0*time + phi); %------------------------ for n = 1:M %------------------------ beta_n = n*pi/M; a_n = 2*cos(beta_n); b_n = 2*sin(beta_n); w_n = w_0*cos((2*pi*n)/N); %------------------------ gr = gr + a_n*cos(w_n*time + phi); gi = gi + b_n*cos(w_n*time + phi); end g = 2/sqrt(N)*(gr + 1i*gi); F = abs(g); %fading power [pdf_abs,~] = ksdensity(F,linspace(0,4,100));% pdf of fading power TH = angle(g); [pdf_ph,~] = ksdensity(TH,linspace(-pi,pi,100)); pdf = cell(1,2); pdf{1} = pdf_abs; pdf{2} = pdf_ph; R = get_corr(g,gr,gi); end %% ch_2 Pop-Beaulieau function [g,pdf,R] = gen_rayleigh_ch_2(M,fd) global time; N=4*M+2; phi= 2*pi*rand(4*M+2,1); X_c=zeros(length(time),1); for n = 1:M A_n=2*pi*n/N; w_n=2*pi*fd*cos(A_n); Term1=(cos(phi(n))+cos(phi(2*M+1-n))+cos(phi(2*M+1+n))+cos(phi(4*M+2-n)))*cos(w_n*time); Term2=(sin(phi(n))-sin(phi(2*M+1-n))-sin(phi(2*M+1+n))+sin(phi(4*M+2-n)))*sin(w_n*time); X_c=X_c+Term1-Term2; end Term3=(cos(phi(2*M+1))+cos(phi(4*M+2)))*cos(2*pi*fd*time); Term4=(sin(phi(2*M+1))-sin(phi(4*M+2)))*sin(2*pi*fd*time); X_c=X_c+Term3+Term4; X_c=X_c*sqrt(2/(N)); X_s=zeros(length(time),1); for n = 1:M A_n=2*pi*n/N; w_n=2*pi*fd*cos(A_n); Term1=(cos(phi(n))-cos(phi(2*M+1-n))-cos(phi(2*M+1+n))+cos(phi(4*M+2-n)))*sin(w_n*time); Term2=(sin(phi(n))+sin(phi(2*M+1-n))+sin(phi(2*M+1+n))+sin(phi(4*M+2-n)))*cos(w_n*time); X_s=X_s+Term1+Term2; end Term3=(cos(phi(2*M+1))-cos(phi(4*M+2)))*sin(2*pi*fd*time); Term4=(sin(phi(2*M+1))+sin(phi(4*M+2)))*cos(2*pi*fd*time); X_s=X_s-Term3+Term4; X_s=X_s*sqrt(2/(N)); g=X_c+1i*X_s; gc=X_c; gs=X_s; F = abs(g); %fading power [pdf_abs,~] = ksdensity(F,linspace(0,4,500));% pdf of fading power TH = angle(g); [pdf_ph,~] = ksdensity(TH,linspace(-pi,pi,30),'support',[-pi,pi]); pdf=cell(1,2); pdf{1} = pdf_abs; pdf{2} = pdf_ph; R = get_corr(g,gc,gs); end %% ch_3 Zheng-Xiao function [g,pdf,R] = gen_rayleigh_ch_3(M,fd) global time; gc = zeros(length(time),1); gs = zeros(length(time),1); wd = 2*pi*fd; theta = 2*pi*rand - pi; phi = 2*pi*rand - pi; for n = 1:M %------------------------ psi_n = 2*pi*rand - pi; alpha_n = (2*pi*n - pi + theta)/(4*M); wn = wd*cos(alpha_n); %------------------------ gc = gc + cos(psi_n)*cos(wn*time + phi); gs = gs + sin(psi_n)*cos(wn*time + phi); end; g = 2/sqrt(M)*(gc + 1i*gs); F = abs(g); %fading power [pdf_abs,~] = ksdensity(F,linspace(0,4,500));% pdf of fading power TH = angle(g); pdf_ph = get_pdf_ph(TH,30); pdf=cell(1,2); pdf{1} = pdf_abs; pdf{2} = pdf_ph; R = get_corr(g,gc,gs); end %% get cross correlation function R = get_corr(g,gr,gi) global N_step; R = cell(6,1); Rgcgc = xcorr(gr,gr,'coeff'); Rgcgc = Rgcgc(N_step:end); Rgsgs = xcorr(gi,gi,'coeff'); Rgsgs= Rgsgs(N_step:end); Rgcgs = xcorr(gr,gi,'coeff'); Rgcgs = Rgcgs(N_step:end); Rgsgc = xcorr(gi,gr,'coeff'); Rgsgc = Rgsgc(N_step:end); Rgg = 2*xcorr(g,g,'coeff'); Rgg = Rgg(N_step:end); Rg2g2 = 8*xcorr(abs(g).^2,abs(g).^2,'coeff'); Rg2g2 = Rg2g2(N_step:end); R{1} = Rgcgc; R{2} = Rgsgs; R{3} = Rgcgs; R{4} = Rgsgc; R{5} = Rgg; R{6} = Rg2g2; end %% get pdf phase function pdf_ph = get_pdf_ph(TH,n_points) edges = linspace(-pi,pi,n_points+1); d_theta = edges(2)-edges(1); [counts, edges] = histcounts(TH,edges); pdf_ph = counts/(sum(counts)*d_theta); end
github
MatCip/Simulation_wireless_channels-master
get_LCR_AFD.m
.m
Simulation_wireless_channels-master/simulation_final/rayleigh/get_LCR_AFD.m
2,754
utf_8
f8bb6f77466614272e057eefedab0272
%% this function compute the LCR and the AFD. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % INPUT: % g : fading, % fd : doppler frequency. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % OUTPUT: % lambda : lambda = R/Rrms where R is the level, % LCR_id : ideal level crossing rate, % LCR : computed level crossing rate, % AFD_id : ideal average fade duration, % AFD : computed average fade duration. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% function [rho, LCR, AFD] = get_LCR_AFD(g,fd,str_mode,K,normalize,N_dim) global N_step; global delta_t; F = abs(g); %fading rho_db = linspace(-30,10,N_dim); rho = 10.^(rho_db/20); R = rho*rms(F); %% ideal LCR and AFD LCR = zeros(N_dim,1); AFD = zeros(N_dim,1); switch str_mode case 'id_rayleigh' LCR = sqrt(2*pi)*fd*rho.*exp(-rho.^2); AFD = (exp(rho.^2)-1)./(rho*fd*sqrt(2*pi)); if normalize AFD = AFD*fd; LCR = LCR/fd; end case 'id_rician' %LCR_id rician alpha=0:0.001:pi; delta_area=zeros(length(rho),length(alpha)-1); for j=1:length(rho) for i=1:1:length(alpha)-1 delta_area(j,i)=(alpha(i+1)-alpha(i))*(1+(2/rho(j))*sqrt(K/(1+K))*(cos(pi/4))^2*cos(alpha(i+1)))*exp(2*rho(j)*sqrt(K*(1+K))*cos(alpha(i+1))-2*K*(cos(pi/4))^2*(sin(alpha(i+1)))^2); end end sum_area=sum(delta_area,2); LCR = (sqrt(2*(1+K)/pi)*rho*fd*delta_t).*exp(-K-(1+K)*(rho.^2)).*(sum_area)'; %AFD_id rician for i=1:1:length(AFD) AFD(i)= (1 - marcumq(sqrt(2*K),sqrt(2*(1+K)*(rho(i)^2)),1))/LCR(i); end %%%%% %normalization AFD = AFD*fd; LCR = LCR/fd; case 'simulated' %% simulated LCR and AFD for i=1:N_dim g_trasl = F-R(i); g_trasl_abs = abs(F-R(i)); g_diff = g_trasl-g_trasl_abs; for j=1:(N_step-1) if g_diff(j)==0 && g_diff(j+1)~=0; LCR(i) = LCR(i)+1; end end LCR(i) = LCR(i)/(N_step*delta_t); AFD(i) = mean(g_trasl<0)/LCR(i); end if normalize AFD = AFD*fd; LCR = LCR/fd; end end end
github
MatCip/Simulation_wireless_channels-master
gen_channel_IIR.m
.m
Simulation_wireless_channels-master/simulation_final/rayleigh/gen_channel_IIR.m
5,264
utf_8
e8c2f73e792bba3624f421765c385585
%% this function compute the channel based on the work of Komninakis. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % OUTPUT: % g : fading, % pdf_abs : pdf of the absolute value of g, % pdf_ph : pdf of the phase of g, % R : a cell that contains the autocorrelations and crosscorrelations, % H_abs : amplitude of the computed filter, % Y : ideal amplitude of the filter, % zer : zeros of the computed filter, % pol : poles of the computed filter. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% generate channel with an IIR filter function [g,pdf_abs,pdf_ph,R ,H_abs,Y,zer,pol] = gen_channel_IIR(fd) global delta_t; %filter parameters K = 7; % filter order is 2K M = 500; rho_0 = 0.2; N= floor(rho_0/(fd*delta_t)); rho=N*(fd*delta_t); Y = get_Y(M,rho); W = linspace(0,1,M+1); z = exp((1i*pi).*W); %initialization of the paramaters for the ellip. alg. x = zeros(4*K,1); B = 100*eye(4*K); %usata per aggiornare x ad ogni iterazione eps = 0.01; %accuracy for the convergence F = get_F(M,K,z,x); A0 = ((abs(F'))*(Y))/((abs(F'))*(abs(F))); R_gd = get_R_gd(M,K,F,z,x,A0,Y); beta = sqrt(R_gd'*B*R_gd); iter = 0; while(beta>eps) g=R_gd/beta; x=x-(B*g)/(4*K+1); B=(4*K)^2/((4*K)^2-1)*(B-2/(4*K+1)*B*g*(g'*B)); F = get_F(M,K,z,x); A0=((abs(F'))*(Y))/((abs(F'))*(abs(F))); R_gd = get_R_gd(M,K,F,z,x,A0,Y); beta=abs(sqrt(R_gd'*B*R_gd)); if mod(iter,50) == 0 clc;disp(strcat('Filter Design Convergence... (threshold=',num2str(eps),')')) disp(strcat('beta=',num2str(beta))) disp(strcat('iteration=',num2str(iter))) end iter = iter+1; end H_abs = A0*F; g = A0*get_fading(x,K,delta_t,rho,fd); %fading [pdf_abs,~ ] = ksdensity(abs(g)); [pdf_ph,~ ] = ksdensity(angle(g)); [zer,pol] = get_zer_pol(x); R = get_corr(g,real(g),imag(g)); end %% compute the gradient of R function R_gd = get_R_gd(M,K,F,z,x,A0,Y) G=ones(4*K,M+1); R_gd=ones(4*K,1); for m=1:M+1 for k=1:K-1 a_k = x(4*k+1); b_k = x(4*k+2); c_k = x(4*k+3); d_k = x(4*k+4); G(4*k+1,m)= abs(F(m))*real(z(m)^(-1)/(1+a_k*z(m)^(-1)+b_k*z(m)^(-2))); G(4*k+2,m)= abs(F(m))*real(z(m)^(-2)/(1+a_k*z(m)^(-1)+b_k*z(m)^(-2))); G(4*k+3,m)=-abs(F(m))*real(z(m)^(-1)/(1+c_k*z(m)^(-1)+d_k*z(m)^(-2))); G(4*k+4,m)=-abs(F(m))*real(z(m)^(-2)/(1+c_k*z(m)^(-1)+d_k*z(m)^(-2))); end end for k=1:4*K for m=1:M+1 R_gd(k)=R_gd(k)+(A0*abs(F(m))-Y(m))*G(k,m); end R_gd(k)=R_gd(k)*2*A0; end end %% compute the function F function F = get_F(M,K,z,x) F=ones(M+1,1); for m=1:(M+1) %for each zi for k=1:K-1 a_k = x(4*k+1); b_k = x(4*k+2); c_k = x(4*k+3); d_k = x(4*k+4); F(m)=F(m)*((1+a_k*z(m)^-1+b_k*z(m)^-2)/(1+c_k*z(m)^-1+d_k*z(m)^-2)); end end end %% compute the target filter amplitude Y function Y = get_Y(M,rho) L = floor(2*rho*M); Y = zeros(M+1,1); for i=0:M if i<=L-1 Y(i+1) = sqrt(1/(sqrt(1-(i/L)^2))); end if i==L Y(i+1) = sqrt(L*(pi/2-asin((L-1)/L))); end if i>=L+1 Y(i+1) = 0; end end end %% compute the fading function g = get_fading(x,K,T,rho,fd) global N_step; I=rho/(fd*T); % generate gaussian process input_dim=ceil(N_step/I); w_real=randn(input_dim,1); w_im=randn(input_dim,1); w=w_real+1i*w_im; % h = ifft(H_abs); % g = conv(h,w); g=w; for i=1:K a=[1,x(3+4*(i-1)),x(4+4*(i-1))]; b=[1,x(1+4*(i-1)),x(2+4*(i-1))]; a = polystab(a); b = polystab(b); g = filter(b,a,g); end g=interp(g,I); g = g(1:N_step); end %% get the zeros and the poles of the designed filter function [zer,pol] = get_zer_pol(x) K = length(x)/4; zer = zeros(2*K,1); pol = zeros(2*K,1); for i=1:K a=[1,x(3+4*(i-1)),x(4+4*(i-1))]; b=[1,x(1+4*(i-1)),x(2+4*(i-1))]; a = polystab(a); b = polystab(b); zer(2*(i-1)+1:2*(i-1)+2) = roots(b); pol(2*(i-1)+1:2*(i-1)+2) = roots(a); end end %% get cross correlation function R = get_corr(g,gr,gi) R = cell(1,6); Rgcgc = xcorr(gr,gr,'coeff'); %Rgcgc = Rgcgc(N_step:end); Rgsgs = xcorr(gi,gi,'coeff'); %Rgsgs = Rgsgs(N_step:end); Rgcgs = xcorr(gr,gi,'coeff'); %Rgcgs = Rgcgs(N_step:end); Rgsgc = xcorr(gi,gr,'coeff'); %Rgsgc = Rgsgc(N_step:end); Rgg = xcorr(g,g,'coeff'); %Rgg = Rgg(N_step:end); Rg2g2 = 8*xcorr(abs(g).^2,abs(g).^2,'coeff'); %Rg2g2 = Rg2g2(N_step:end); R{1} = Rgcgc; R{2} = Rgsgs; R{3} = Rgcgs; R{4} = Rgsgc; R{5} = Rgg; R{6} = Rg2g2; end
github
damianomal/Shearlet-Framework-master
AxelRot.m
.m
Shearlet-Framework-master/shearlets_utils/AxelRot.m
3,606
utf_8
35b06e6d09ea3b89a8386c5c63ddc83a
function varargout=AxelRot(varargin) %Generate roto-translation matrix for the rotation around an arbitrary line in 3D. %The line need not pass through the origin. Optionally, also, apply this %transformation to a list of 3D coordinates. % %SYNTAX 1: % % M=AxelRot(deg,u,x0) % % %in: % % u, x0: 3D vectors specifying the line in parametric form x(t)=x0+t*u % Default for x0 is [0,0,0] corresponding to pure rotation (no shift). % If x0=[] is passed as input, this is also equivalent to passing % x0=[0,0,0]. % % deg: The counter-clockwise rotation about the line in degrees. % Counter-clockwise is defined using the right hand rule in reference % to the direction of u. % % %out: % % M: A 4x4 affine transformation matrix representing % the roto-translation. Namely, M will have the form % % M=[R,t;0 0 0 1] % % where R is a 3x3 rotation and t is a 3x1 translation vector. % % % %SYNTAX 2: % % [R,t]=AxelRot(deg,u,x0) % % Same as Syntax 1 except that R and t are returned as separate arguments. % % % %SYNTAX 3: % % This syntax requires 4 input arguments be specified, % % [XYZnew, R, t] = AxelRot(XYZold, deg, u, x0) % % where the columns of the 3xN matrix XYZold specify a set of N point % coordinates in 3D space. The output XYZnew is the transformation of the % columns of XYZold by the specified rototranslation about the axis. All % other input/output arguments are as before. % % by Matt Jacobson % % Copyright, Xoran Technologies, Inc. 2011 if nargin>3 XYZold=varargin{1}; varargin(1)=[]; [R,t]=AxelRot(varargin{:}); XYZnew=bsxfun(@plus,R*XYZold,t); varargout={XYZnew, R,t}; return; end [deg,u]=deal(varargin{1:2}); if nargin>2, x0=varargin{3}; end R3x3 = nargin>2 && isequal(x0,'R'); if nargin<3 || R3x3 || isempty(x0), x0=[0;0;0]; end x0=x0(:); u=u(:)/norm(u); AxisShift=x0-(x0.'*u).*u; Mshift=mkaff(eye(3),-AxisShift); Mroto=mkaff(R3d(deg,u)); M=inv(Mshift)*Mroto*Mshift; varargout(1:2)={M,[]}; if R3x3 || nargout>1 varargout{1}=M(1:3,1:3); end if nargout>1, varargout{2}=M(1:3,4); end function R=R3d(deg,u) %R3D - 3D Rotation matrix counter-clockwise about an axis. % %R=R3d(deg,axis) % % deg: The counter-clockwise rotation about the axis in degrees. % axis: A 3-vector specifying the axis direction. Must be non-zero R=eye(3); u=u(:)/norm(u); x=deg; %abbreviation for ii=1:3 v=R(:,ii); R(:,ii)=v*cosd(x) + cross(u,v)*sind(x) + (u.'*v)*(1-cosd(x))*u; %Rodrigues' formula end function M=mkaff(varargin) % M=mkaff(R,t) % M=mkaff(R) % M=mkaff(t) % %Makes an affine transformation matrix, either in 2D or 3D. %For 3D transformations, this has the form % % M=[R,t;[0 0 0 1]] % %where R is a square matrix and t is a translation vector (column or row) % %When multiplied with vectors [x;y;z;1] it gives [x';y';z;1] which accomplishes the %the corresponding affine transformation % % [x';y';z']=R*[x;y;z]+t % if nargin==1 switch numel(varargin{1}) case {4,9} %Only rotation provided, 2D or 3D R=varargin{1}; nn=size(R,1); t=zeros(nn,1); case {2,3} t=varargin{1}; nn=length(t); R=eye(nn); end else [R,t]=deal(varargin{1:2}); nn=size(R,1); end t=t(:); M=eye(nn+1); M(1:end-1,1:end-1)=R; M(1:end-1,end)=t(:);
github
damianomal/Shearlet-Framework-master
munkres.m
.m
Shearlet-Framework-master/shearlets_to_reorganize/munkres.m
6,971
utf_8
d287696892e8ef857858223a49ad48fd
function [assignment,cost] = munkres(costMat) % MUNKRES Munkres (Hungarian) Algorithm for Linear Assignment Problem. % % [ASSIGN,COST] = munkres(COSTMAT) returns the optimal column indices, % ASSIGN assigned to each row and the minimum COST based on the assignment % problem represented by the COSTMAT, where the (i,j)th element represents the cost to assign the jth % job to the ith worker. % % Partial assignment: This code can identify a partial assignment is a full % assignment is not feasible. For a partial assignment, there are some % zero elements in the returning assignment vector, which indicate % un-assigned tasks. The cost returned only contains the cost of partially % assigned tasks. % This is vectorized implementation of the algorithm. It is the fastest % among all Matlab implementations of the algorithm. % Examples % Example 1: a 5 x 5 example %{ [assignment,cost] = munkres(magic(5)); disp(assignment); % 3 2 1 5 4 disp(cost); %15 %} % Example 2: 400 x 400 random data %{ n=400; A=rand(n); tic [a,b]=munkres(A); toc % about 2 seconds %} % Example 3: rectangular assignment with inf costs %{ A=rand(10,7); A(A>0.7)=Inf; [a,b]=munkres(A); %} % Example 4: an example of partial assignment %{ A = [1 3 Inf; Inf Inf 5; Inf Inf 0.5]; [a,b]=munkres(A) %} % a = [1 0 3] % b = 1.5 % Reference: % "Munkres' Assignment Algorithm, Modified for Rectangular Matrices", % http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html % version 2.3 by Yi Cao at Cranfield University on 11th September 2011 assignment = zeros(1,size(costMat,1)); cost = 0; validMat = costMat == costMat & costMat < Inf; bigM = 10^(ceil(log10(sum(costMat(validMat))))+1); costMat(~validMat) = bigM; % costMat(costMat~=costMat)=Inf; % validMat = costMat<Inf; validCol = any(validMat,1); validRow = any(validMat,2); nRows = sum(validRow); nCols = sum(validCol); n = max(nRows,nCols); if ~n return end maxv=10*max(costMat(validMat)); dMat = zeros(n) + maxv; dMat(1:nRows,1:nCols) = costMat(validRow,validCol); %************************************************* % Munkres' Assignment Algorithm starts here %************************************************* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % STEP 1: Subtract the row minimum from each row. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% minR = min(dMat,[],2); minC = min(bsxfun(@minus, dMat, minR)); %************************************************************************** % STEP 2: Find a zero of dMat. If there are no starred zeros in its % column or row start the zero. Repeat for each zero %************************************************************************** zP = dMat == bsxfun(@plus, minC, minR); starZ = zeros(n,1); while any(zP(:)) [r,c]=find(zP,1); starZ(r)=c; zP(r,:)=false; zP(:,c)=false; end while 1 %************************************************************************** % STEP 3: Cover each column with a starred zero. If all the columns are % covered then the matching is maximum %************************************************************************** if all(starZ>0) break end coverColumn = false(1,n); coverColumn(starZ(starZ>0))=true; coverRow = false(n,1); primeZ = zeros(n,1); [rIdx, cIdx] = find(dMat(~coverRow,~coverColumn)==bsxfun(@plus,minR(~coverRow),minC(~coverColumn))); while 1 %************************************************************************** % STEP 4: Find a noncovered zero and prime it. If there is no starred % zero in the row containing this primed zero, Go to Step 5. % Otherwise, cover this row and uncover the column containing % the starred zero. Continue in this manner until there are no % uncovered zeros left. Save the smallest uncovered value and % Go to Step 6. %************************************************************************** cR = find(~coverRow); cC = find(~coverColumn); rIdx = cR(rIdx); cIdx = cC(cIdx); Step = 6; while ~isempty(cIdx) uZr = rIdx(1); uZc = cIdx(1); primeZ(uZr) = uZc; stz = starZ(uZr); if ~stz Step = 5; break; end coverRow(uZr) = true; coverColumn(stz) = false; z = rIdx==uZr; rIdx(z) = []; cIdx(z) = []; cR = find(~coverRow); z = dMat(~coverRow,stz) == minR(~coverRow) + minC(stz); rIdx = [rIdx(:);cR(z)]; cIdx = [cIdx(:);stz(ones(sum(z),1))]; end if Step == 6 % ************************************************************************* % STEP 6: Add the minimum uncovered value to every element of each covered % row, and subtract it from every element of each uncovered column. % Return to Step 4 without altering any stars, primes, or covered lines. %************************************************************************** [minval,rIdx,cIdx]=outerplus(dMat(~coverRow,~coverColumn),minR(~coverRow),minC(~coverColumn)); minC(~coverColumn) = minC(~coverColumn) + minval; minR(coverRow) = minR(coverRow) - minval; else break end end %************************************************************************** % STEP 5: % Construct a series of alternating primed and starred zeros as % follows: % Let Z0 represent the uncovered primed zero found in Step 4. % Let Z1 denote the starred zero in the column of Z0 (if any). % Let Z2 denote the primed zero in the row of Z1 (there will always % be one). Continue until the series terminates at a primed zero % that has no starred zero in its column. Unstar each starred % zero of the series, star each primed zero of the series, erase % all primes and uncover every line in the matrix. Return to Step 3. %************************************************************************** rowZ1 = find(starZ==uZc); starZ(uZr)=uZc; while rowZ1>0 starZ(rowZ1)=0; uZc = primeZ(rowZ1); uZr = rowZ1; rowZ1 = find(starZ==uZc); starZ(uZr)=uZc; end end % Cost of assignment rowIdx = find(validRow); colIdx = find(validCol); starZ = starZ(1:nRows); vIdx = starZ <= nCols; assignment(rowIdx(vIdx)) = colIdx(starZ(vIdx)); pass = assignment(assignment>0); pass(~diag(validMat(assignment>0,pass))) = 0; assignment(assignment>0) = pass; cost = trace(costMat(assignment>0,assignment(assignment>0))); function [minval,rIdx,cIdx]=outerplus(M,x,y) ny=size(M,2); minval=inf; for c=1:ny M(:,c)=M(:,c)-(x+y(c)); minval = min(minval,min(M(:,c))); end [rIdx,cIdx]=find(M==minval);
github
damianomal/Shearlet-Framework-master
benchminmax.m
.m
Shearlet-Framework-master/shearlets_to_reorganize/MinMaxFilterFolder/benchminmax.m
1,913
utf_8
d889c60b2507d650848cb3c47da26a7c
function benchminmax() % function benchminmax() % % Benchmark runtime minmax filter among four methods: Matlab vectorized, % for-loop, Lemire's MEX files, and vanherk by Frederico D'Almeida % try lemire_engine(1,1); catch minmaxfilter_install(); end % Data fprintf('Random, win=100\n'); B = randperm(100000); win = 100; b(B, win); fprintf('Ordered, win=100\n'); B = -(1:100000); win = 100; b(B, win); fprintf('Random, win=3\n'); B = randperm(100000); win = 3; b(B, win); fprintf('Ordered, win=3\n'); B = -(1:100000); win = 3; b(B, win); end % benchminmax function b(B, win) N = 5; % number of tests t1 = Inf; t2 = Inf; t3 = Inf; t4=Inf; for j = 1:N % Vectorized engine tic subs = ones(win*length(B)-(win-1)*win,1); subs(win+1:win:end) = 2-win; maxdata = max(reshape(B(cumsum(subs)),win,[])); t1=min(t1,toc); % For-loop engine tic maxdata = zeros(1,length(B)-win+1); m = max(B(1:win)); for k=win+1:length(B) maxdata(k-win) = m; if B(k-win) < m m = max(m, B(k)); else % Matt Fig's improvement m = B(1+k-win); for ii = 1+k-win+1:k if B(ii)>m m = B(ii); end end % m = max(B(1+k-win:k)); end end maxdata(end) = m; t2=min(t2,toc); % Lemire's engine tic %maxdata = minmaxfilt1(B, win, 'max'); [trash maxdata] = lemire_engine(B, win); t3=min(t3,toc); % Lemire's engine tic [maxdata] = vanherk(B, win, 'max'); t4=min(t4,toc); end fprintf('\tAbsolute time [s]\n') fprintf('\t\thankel: %f, for-loop: %f, lemire: %f, vanherk: %f\n', ... t1, t2, t3, t4); tmin = min([t1 t2 t3 t4]); fprintf('\tRelative time\n') fprintf('\t\thankel: %f, for-loop: %f, lemire: %f, vanherk: %f\n', ... t1/tmin, t2/tmin, t3/tmin, t4/tmin); end
github
damianomal/Shearlet-Framework-master
vanherk.m
.m
Shearlet-Framework-master/shearlets_to_reorganize/MinMaxFilterFolder/vanherk.m
4,757
utf_8
b2f034412c598fc54a59c79d1c7547fa
function Y = vanherk(X,N,TYPE,varargin) % VANHERK Fast max/min 1D filter % % Y = VANHERK(X,N,TYPE) performs the 1D max/min filtering of the row % vector X using a N-length filter. % The filtering type is defined by TYPE = 'max' or 'min'. This function % uses the van Herk algorithm for min/max filters that demands only 3 % min/max calculations per element, independently of the filter size. % % If X is a 2D matrix, each row will be filtered separately. % % Y = VANHERK(...,'col') performs the filtering on the columns of X. % % Y = VANHERK(...,'shape') returns the subset of the filtering specified % by 'shape' : % 'full' - Returns the full filtering result, % 'same' - (default) Returns the central filter area that is the % same size as X, % 'valid' - Returns only the area where no filter elements are outside % the image. % % X can be uint8 or double. If X is uint8 the processing is quite faster, so % dont't use X as double, unless it is really necessary. % % http://www.mathworks.com/matlabcentral/fileexchange/1358 % Author: Frederico D'Almeida % % Initialization [direc, shape] = parse_inputs(varargin{:}); if strcmp(direc,'col') X = X'; end if strcmp(TYPE,'max') maxfilt = 1; elseif strcmp(TYPE,'min') maxfilt = 0; else error([ 'TYPE must be ' char(39) 'max' char(39) ' or ' char(39) 'min' char(39) '.']) end % Correcting X size fixsize = 0; addel = 0; if mod(size(X,2),N) ~= 0 fixsize = 1; addel = N-mod(size(X,2),N); if maxfilt f = [ X zeros(size(X,1), addel) ]; else f = [X repmat(X(:,end),1,addel)]; end else f = X; end lf = size(f,2); lx = size(X,2); clear X % Declaring aux. mat. g = f; h = g; % Filling g & h (aux. mat.) ig = 1:N:size(f,2); ih = ig + N - 1; g(:,ig) = f(:,ig); h(:,ih) = f(:,ih); if maxfilt for i = 2 : N igold = ig; ihold = ih; ig = ig + 1; ih = ih - 1; g(:,ig) = max(f(:,ig),g(:,igold)); h(:,ih) = max(f(:,ih),h(:,ihold)); end else for i = 2 : N igold = ig; ihold = ih; ig = ig + 1; ih = ih - 1; g(:,ig) = min(f(:,ig),g(:,igold)); h(:,ih) = min(f(:,ih),h(:,ihold)); end end clear f % Comparing g & h if strcmp(shape,'full') ig = [ N : 1 : lf ]; ih = [ 1 : 1 : lf-N+1 ]; if fixsize if maxfilt Y = [ g(:,1:N-1) max(g(:,ig), h(:,ih)) h(:,end-N+2:end-addel) ]; else Y = [ g(:,1:N-1) min(g(:,ig), h(:,ih)) h(:,end-N+2:end-addel) ]; end else if maxfilt Y = [ g(:,1:N-1) max(g(:,ig), h(:,ih)) h(:,end-N+2:end) ]; else Y = [ g(:,1:N-1) min(g(:,ig), h(:,ih)) h(:,end-N+2:end) ]; end end elseif strcmp(shape,'same') if fixsize if addel > (N-1)/2 %disp('hoi') ig = [ N : 1 : lf - addel + floor((N-1)/2) ]; ih = [ 1 : 1 : lf-N+1 - addel + floor((N-1)/2)]; if maxfilt Y = [ g(:,1+ceil((N-1)/2):N-1) max(g(:,ig), h(:,ih)) ]; else Y = [ g(:,1+ceil((N-1)/2):N-1) min(g(:,ig), h(:,ih)) ]; end else ig = [ N : 1 : lf ]; ih = [ 1 : 1 : lf-N+1 ]; if maxfilt Y = [ g(:,1+ceil((N-1)/2):N-1) max(g(:,ig), h(:,ih)) h(:,lf-N+2:lf-N+1+floor((N-1)/2)-addel) ]; else Y = [ g(:,1+ceil((N-1)/2):N-1) min(g(:,ig), h(:,ih)) h(:,lf-N+2:lf-N+1+floor((N-1)/2)-addel) ]; end end else % not fixsize (addel=0, lf=lx) ig = [ N : 1 : lx ]; ih = [ 1 : 1 : lx-N+1 ]; if maxfilt Y = [ g(:,N-ceil((N-1)/2):N-1) max( g(:,ig), h(:,ih) ) h(:,lx-N+2:lx-N+1+floor((N-1)/2)) ]; else Y = [ g(:,N-ceil((N-1)/2):N-1) min( g(:,ig), h(:,ih) ) h(:,lx-N+2:lx-N+1+floor((N-1)/2)) ]; end end elseif strcmp(shape,'valid') ig = [ N : 1 : lx]; ih = [ 1 : 1: lx-N+1]; if maxfilt Y = [ max( g(:,ig), h(:,ih) ) ]; else Y = [ min( g(:,ig), h(:,ih) ) ]; end end if strcmp(direc,'col') Y = Y'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [direc, shape] = parse_inputs(varargin) direc = 'lin'; shape = 'same'; flag = [0 0]; % [dir shape] for i = 1 : nargin t = varargin{i}; if strcmp(t,'col') & flag(1) == 0 direc = 'col'; flag(1) = 1; elseif strcmp(t,'full') & flag(2) == 0 shape = 'full'; flag(2) = 1; elseif strcmp(t,'same') & flag(2) == 0 shape = 'same'; flag(2) = 1; elseif strcmp(t,'valid') & flag(2) == 0 shape = 'valid'; flag(2) = 1; else error(['Too many / Unkown parameter : ' t ]) end end
github
damianomal/Shearlet-Framework-master
slowminmaxfilt_algo.m
.m
Shearlet-Framework-master/shearlets_to_reorganize/MinMaxFilterFolder/slowminmaxfilt_algo.m
2,710
utf_8
5f0d989708867b1e7759e19c2bd356c1
function [minval maxval] = slowminmaxfilt_algo(a, window) % % function [minval maxval] = slowminmaxfilt_algo(a, window) % % This function uses to illustrate how Lemire's streaming min/max % works. It is NOT recommended to use in your application. % This algorithm is used by this package % % Reference: Lemire's "STREAMING MAXIMUM-MINIMUM FILTER USING NO MORE THAN % THREE COMPARISONS PER ELEMENT" Nordic Journal of Computing, Volume 13, % Number 4, pages 328-339, 2006. % % AUTHOR: Bruno Luong <[email protected]> % HISTORY % Original: 12-Jul-2009 n=length(a); minval = nan(1,n-window+1); maxval = nan(1,n-window+1); L = initwedge(window+1); U = initwedge(window+1); for i = 2:n if i > window if ~wedgeisempty(U) maxval(i-window) = a(getfirst(U)); else maxval(i-window) = a(i-1); end if ~wedgeisempty(L) minval(i-window) = a(getfirst(L)); else minval(i-window) = a(i-1); end end % i>window if a(i) > a(i-1) L = pushback(L, i-1); if i==window+getfirst(L), L = popfront(L); end while ~wedgeisempty(U) if a(i)<=a(getlast(U)) if i==window+getfirst(U), U = popfront(U); end break end U = popback(U); end % while loop else U = pushback(U, i-1); if i==window+getfirst(U), U = popfront(U); end while ~wedgeisempty(L) if a(i)>=a(getlast(L)) if i==window+getfirst(L), L = popfront(L); end break end L = popback(L); end % while loop end % if fprintf('---- i=%d \n', i); dispw(L) dispw(U) end % for-loop i=n+1; if ~wedgeisempty(U) maxval(i-window) = a(getfirst(U)); else maxval(i-window) = a(i-1); end if ~wedgeisempty(L) minval(i-window) = a(getfirst(L)); else minval(i-window) = a(i-1); end % L.mxn % U.mxn end function X = initwedge(sz) X = struct('buffer', zeros(1, sz), ... 'sz', sz, ... 'n', 0, ... 'first', 1, ... 'last', 0, ... 'mxn', 0); end function b = wedgeisempty(X) b = X.n <= 0; end function X = pushback(X, v) X.last = mod(X.last,X.sz) + 1; X.buffer(X.last) = v; X.n = X.n+1; X.mxn = max(X.mxn,X.n); % track the maximul of buffer size end function X = popback(X) X.n = X.n-1; X.last = mod(X.last-2,X.sz) + 1; end function X = popfront(X) X.n = X.n-1; X.first = mod(X.first,X.sz) + 1; end function v = getfirst(X) v = X.buffer(X.first); end function v = getlast(X) v = X.buffer(X.last); end function dispw(X) A = X.buffer(mod(X.first+(-1:X.n-2), X.sz) + 1); disp(A) end
github
damianomal/Shearlet-Framework-master
SLgetShearlets3D.m
.m
Shearlet-Framework-master/ShearLab3Dv11/Util/SLgetShearlets3D.m
8,630
utf_8
7c91f62f439af4ab25bd792d48818770
function [shearlets,RMS,dualFrameWeights] = SLgetShearlets3D(preparedFilters,shearletIdxs) %SLgetShearlets3D Compute 3D shearlets in the frequency domain. % %Usage: % % [shearlets, RMS, dualFrameWeights] = SLgetShearlets3D(preparedFilters) % [shearlets, RMS, dualFrameWeights] = SLgetShearlets3D(preparedFilters, shearletIdxs) % %Input: % % preparedFilters: A structure containing filters that can be used to compute 3D shearlets. % Such filters can be generated with SLprepareFilters3D. % shearletdIdxs: A Nx4 array, specifying each shearlet that is to be % computed in the format [cone scale shearing1 shearing2] where N % denotes the number of shearlets. The three pyramids are % indexed by 1, 2 and 3. Note that the values for scale and shearings are limited by % the precomputed filters. The lowpass shearlet is indexed by % [0 0 0 0]. If no shearlet indexes are specified, SLgetShearlets3D % returns a standard shearlet system based on the precomputed filters. % Such a standard index set can also be obtained by % calling SLgetShearletIdxs3D. % %Output: % % shearlets: A XxYxZxN array of N 3D shearlets in the frequency domain where X, Y and Z % denote the size of each shearlet. % RMS: A 1xnShearlets array containing the root mean % squares (L2-norm divided by sqrt(X*Y*Z)) of all shearlets stored in % shearlets. These values can be used to normalize % shearlet coefficients to make them comparable. % dualFrameWeights: A XxYxZ matrix containing the absolute and squared sum over all shearlets % stored in shearlets. These weights are needed to compute the dual shearlets during reconstruction. % %Description: % % The 2D shearlets in preparedFilters are used to compute % shearlets on different scales and of different shearings, as specified by % the shearletIdxs array. Shearlets are computed in the frequency domain. % To get the i-th shearlet in the time domain, use % fftshift(ifftn(ifftshift(shearlets(:,:,:,i)))). % % Each Shearlet is centered at floor([X Y Z]/2) + 1. % %Example 1: % % %compute the lowpass shearlet % preparedFilters = SLprepareFilters3D(128,128,128,2); % lowpassShearlet = SLgetShearlets3D(preparedFilters,[0 0 0 0]); % lowpassShearletTimeDomain = fftshift(ifftn(ifftshift(lowpassShearlet))); % %Example 2: % % %compute a standard shearlet system of one scale % preparedFilters = SLprepareFilters3D(128,128,128,1); % shearlets = SLgetShearlets3D(preparedFilters); % %Example 3: % % %compute a full shearlet system of one scale % preparedFilters = SLprepareFilters3D(128,128,128,1); % shearlets = SLgetShearlets3D(preparedFilters,SLgetShearletIdxs3D(preparedFilters.shearLevels,1)); % %See also: SLprepareFilters3D, SLgetShearletIdxs3D, SLsheardec3D, % SLshearrec3D %% check input arguments if nargin < 1 error('Too few input arguments!'); end; if nargin < 2 shearletIdxs = SLgetShearletIdxs3D(preparedFilters.shearLevels); end; ndim1 = preparedFilters.size(1); ndim2 = preparedFilters.size(2); ndim3 = preparedFilters.size(3); nShearlets = size(shearletIdxs,1); useGPU = preparedFilters.useGPU; if useGPU if verLessThan('distcomp','6.1') shearlets = complex(parallel.gpu.GPUArray.zeros(ndim1, ndim2, ndim3, nShearlets)); shearletAbsSqrd = parallel.gpu.GPUArray.zeros(ndim1,ndim2,ndim3); if nargout > 1 RMS = parallel.gpu.GPUArray.zeros(1,nShearlets); if nargout > 2 dualFrameWeights = parallel.gpu.GPUArray.zeros(ndim1,ndim2,ndim3); end end else shearlets = complex(gpuArray.zeros(ndim1, ndim2, ndim3, nShearlets)); shearletAbsSqrd = gpuArray.zeros(ndim1,ndim2,ndim3); if nargout > 1 RMS = gpuArray.zeros(1,nShearlets); if nargout > 2 dualFrameWeights = gpuArray.zeros(ndim1,ndim2,ndim3); end end end kGetShearlet3D = parallel.gpu.CUDAKernel('SLgetShearlet3DCUDA.ptx','SLgetShearlet3DCUDA.cu'); kGetShearlet3D.GridSize = [ndim1 ndim2]; kGetShearlet3D.ThreadBlockSize = [ndim3 1 1]; else shearletAbsSqrd = zeros(ndim1,ndim2,ndim3); shearlets = complex(zeros(ndim1, ndim2, ndim3, nShearlets)); if nargout > 1 RMS = zeros(1,nShearlets); if nargout > 2 dualFrameWeights = zeros(ndim1,ndim2,ndim3); end end end for j = 1:nShearlets pyramid = shearletIdxs(j,1); scale = shearletIdxs(j,2); shearing1 = shearletIdxs(j,3); shearing2 = shearletIdxs(j,4); if pyramid == 0 if useGPU [shearlets(:,:,:,j), shearletAbsSqrd] = feval(kGetShearlet3D,shearlets(:,:,:,j),shearletAbsSqrd,pyramid,preparedFilters.d1d2(:,:,end),preparedFilters.d3d2(:,:,end)); else shearlet1 = preparedFilters.d1d2(:,:,end); shearlet2 = preparedFilters.d3d2(:,:,end); for k = 1:ndim2 shearlets(:,k,:,j) = shearlet1(:,k)*permute(shearlet2(:,k),[2 1]); end end elseif pyramid == 1 if useGPU [shearlets(:,:,:,j), shearletAbsSqrd] = feval(kGetShearlet3D,shearlets(:,:,:,j),shearletAbsSqrd,pyramid,preparedFilters.d1d2(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,1,scale,shearing1)),preparedFilters.d3d2(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,1,scale,shearing2))); else shearlet1 = preparedFilters.d1d2(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,1,scale,shearing1)); shearlet2 = preparedFilters.d3d2(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,1,scale,shearing2)); for k = 1:ndim2 shearlets(:,k,:,j) = shearlet1(:,k)*permute(shearlet2(:,k),[2 1]); end end elseif pyramid == 2 if useGPU [shearlets(:,:,:,j), shearletAbsSqrd] = feval(kGetShearlet3D,shearlets(:,:,:,j),shearletAbsSqrd,pyramid,preparedFilters.d1d3(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,1,scale,shearing1)),preparedFilters.d3d2(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,2,scale,shearing2))); else shearlet1 = preparedFilters.d1d3(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,1,scale,shearing1)); shearlet2 = preparedFilters.d3d2(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,2,scale,shearing2)); for k = 1:ndim3 shearlets(:,:,k,j) = shearlet1(:,k)*shearlet2(k,:); end end else if useGPU [shearlets(:,:,:,j), shearletAbsSqrd] = feval(kGetShearlet3D,shearlets(:,:,:,j),shearletAbsSqrd,pyramid,preparedFilters.d1d2(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,2,scale,shearing1)),preparedFilters.d1d3(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,2,scale,shearing2))); else shearlet1 = preparedFilters.d1d2(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,2,scale,shearing1)); shearlet2 = preparedFilters.d1d3(:,:,SLgetShearletPosFromIdxs(preparedFilters.shearLevels,2,scale,shearing2)); for k = 1:ndim1 shearlets(k,:,:,j) = permute(shearlet1(k,:),[2 1])*shearlet2(k,:); end end end if nargout > 1 if useGPU == 0 shearletAbsSqrd = abs(shearlets(:,:,:,j)).^2; end RMS(j) = sqrt(sum(shearletAbsSqrd(:))/(ndim1*ndim2*ndim3)); if nargout > 2 dualFrameWeights = dualFrameWeights + shearletAbsSqrd; end end end end function pos = SLgetShearletPosFromIdxs(shearLevels,cone,scale,shearing) pos = 1+sum(2.^(shearLevels+1) + 1)*(cone-1) + shearing + 2^shearLevels(scale); if scale > 1 pos = pos + sum(2.^(shearLevels(1:(scale-1))+1)+1); end; end % % Copyright (c) 2014. Rafael Reisenhofer % % Part of ShearLab3D v1.1 % Built Mon, 10/11/2014 % This is Copyrighted Material
github
libertysoft3/saidit-master
newlink.m
.m
saidit-master/r2/r2/templates/newlink.m
6,347
utf_8
1a12dbd14cb171dd5f7d09819ee64b05
## The contents of this file are subject to the Common Public Attribution ## License Version 1.0. (the "License"); you may not use this file except in ## compliance with the License. You may obtain a copy of the License at ## http://code.reddit.com/LICENSE. The License is based on the Mozilla Public ## License Version 1.1, but Sections 14 and 15 have been added to cover use of ## software over a computer network and provide for limited attribution for the ## Original Developer. In addition, Exhibit A has been modified to be ## consistent with Exhibit B. ## ## Software distributed under the License is distributed on an "AS IS" basis, ## WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for ## the specific language governing rights and limitations under the License. ## ## The Original Code is reddit. ## ## The Original Developer is the Initial Developer. The Initial Developer of ## the Original Code is reddit Inc. ## ## All portions of the code written by reddit are Copyright (c) 2006-2015 ## reddit Inc. All Rights Reserved. ############################################################################### <%! from r2.lib.strings import strings from r2.lib.pages import SubredditSelector, UserText from r2.lib.template_helpers import add_sr, _wsf, format_html from r2.lib.filters import safemarkdown %> <%namespace file="utils.m" import="error_field, submit_form, _a_buffered, text_with_links"/> <%namespace name="utils" file="utils.m"/> <% if thing.default_sr: sr = format_html("&#32;%s", unsafe(_a_buffered(thing.default_sr.name, href=thing.default_sr.path))) else: sr = _("SaidIt") %> <h1>${_wsf("submit to %(sr)s", sr=sr)}</h1> <%utils:submit_form onsubmit="return post_form(this, 'submit', linkstatus, null, true)" action=${add_sr("/submit")}, _class="submit content warn-on-unload", _id="newlink"> %if thing.show_link and thing.show_self: ${thing.formtabs_menu} %endif <div class="formtabs-content"> <div class="spacer"> %if thing.show_link: <div id="link-desc" class="infobar">${strings.submit_link}</div> %endif %if thing.show_self: <div id="text-desc" class="infobar">${strings.submit_text}</div> %endif </div> <script type="text/javascript"> function countChars(countfrom,displayto) { var len = document.getElementById(countfrom).value.length; document.getElementById(displayto).innerHTML = len; } </script> <div class="spacer"> <%utils:round_field title="${_('title')}" id="title-field"> <textarea name="title" id="title_text" rows="2" required onkeyup="countChars('title_text','charcount');" onkeydown="countChars('title_text','charcount');" onmousemove="countChars('title_text','charcount');">${thing.title}</textarea><p align="right"><span align="right" id="charcount">0</span>/300</p> ${error_field("NO_TEXT", "title", "div")} ${error_field("TOO_LONG", "title", "div")} </%utils:round_field> </div> %if thing.show_link: <div class="spacer"> <%utils:round_field title="${_('url')}" id="url-field"> <input name="kind" value="link" type="hidden"/> <input id="url" name="url" type="url" value="${thing.url}" required> ${error_field("NO_URL", "url", "div")} ${error_field("BAD_URL", "url", "div")} ${error_field("DOMAIN_BANNED", "url", "div")} ${error_field("ALREADY_SUB", "url", "div")} ${error_field("NO_LINKS", "sr")} ${error_field("NO_SELFS", "sr")} <div id="suggest-title"> <span class="title-status"></span> <button type="button" tabindex="100" onclick="fetch_title()" onmouseup="countChars('title_text','charcount');" onmousemove="countChars('title_text','charcount');">${_("suggest title")}</button> </div> </%utils:round_field> </div> %endif %if thing.show_self: <div class="spacer"> <%utils:round_field title="${_('text')}", description="${_('(optional)')}" id="text-field"> <input name="kind" value="self" type="hidden"/> ${UserText(None, text = thing.text, have_form = False, creating = True)} ${error_field("NO_SELFS", "sr")} </%utils:round_field> </div> %endif <div class="spacer"> <%utils:round_field title="${_('choose a sub')}" id="reddit-field"> ${SubredditSelector(thing.default_sr, extra_subreddits=thing.extra_subreddits, required=True)} </%utils:round_field> </div> <div class="spacer"> <div class="submit_text roundfield"> <h1>${_wsf('submitting to %(sr)s', sr=unsafe('/' + g.brander_community_abbr + '/<span class="sr"></span>'))}</h1> <span class="content md-container"> %if thing.default_sr and thing.default_sr.submit_text: ${unsafe(safemarkdown(thing.default_sr.submit_text))} %endif </span> </div> </div> <div class="spacer"> <%utils:round_field title="${_('options')}" id="sendreplies-field"> <input class="nomargin" type="checkbox" ${'checked="checked"' if c.user.pref_sendreplies else ''} name="sendreplies" id="sendreplies" data-send-checked="true"/> <label for="sendreplies"> ${_("send replies to my inbox")} </label> </%utils:round_field> </div> ${thing.captcha} </div> <div class="roundfield info-notice"> ${text_with_links(_("please be mindful of SaidIt's %(content_policy)s"), content_policy=dict( link_text=_("content policy"), path="/r/SaidIt/comments/j1/the_saiditnet_terms_and_content_policy/", target="_blank"), good_reddiquette=dict( link_text=_("good reddiquette"), path="/wiki/reddiquette", target="_blank"), )} </div> <input name="resubmit" value="${thing.resubmit}" type="hidden"/> <div class="spacer"> <button class="btn" name="submit" value="form" type="submit" onmousemove="countChars('title_text','charcount');">${_("submit")}</button> <span class="status"></span> ${error_field("RATELIMIT", "ratelimit")} ${error_field("INVALID_OPTION", "sr")} ${error_field("IN_TIMEOUT", "sr")} </div> </%utils:submit_form> %if thing.show_self and thing.show_link: <script type="text/javascript"> $(function() { var form = $("#newlink"); if(form.length) { var default_menu = form.find(".${thing.default_tab}-button:first"); select_form_tab(default_menu, "${thing.default_show}", "${thing.default_hide}"); } }); </script> %endif
github
libertysoft3/saidit-master
widgetdemopanel.m
.m
saidit-master/r2/r2/templates/widgetdemopanel.m
9,113
utf_8
40974db660788dadafaaa7b008e93bbc
## The contents of this file are subject to the Common Public Attribution ## License Version 1.0. (the "License"); you may not use this file except in ## compliance with the License. You may obtain a copy of the License at ## http://code.reddit.com/LICENSE. The License is based on the Mozilla Public ## License Version 1.1, but Sections 14 and 15 have been added to cover use of ## software over a computer network and provide for limited attribution for the ## Original Developer. In addition, Exhibit A has been modified to be ## consistent with Exhibit B. ## ## Software distributed under the License is distributed on an "AS IS" basis, ## WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for ## the specific language governing rights and limitations under the License. ## ## The Original Code is reddit. ## ## The Original Developer is the Initial Developer. The Initial Developer of ## the Original Code is reddit Inc. ## ## All portions of the code written by reddit are Copyright (c) 2006-2015 ## reddit Inc. All Rights Reserved. ############################################################################### <%! from r2.lib.template_helpers import get_domain, _wsf %> <% domain = get_domain(subreddit=False) sr_domain = get_domain(subreddit=True) %> <script type="text/javascript"> function escapeHTML(text) { var div = document.createElement('div'); var text = document.createTextNode(text); div.appendChild(text); return div.innerHTML; } function getrval(r) { for (var i=0; i < r.length; i++) { if (r[i].checked) return r[i].value; } } function showPreview(val) { $("#previewbox").html(val) } function update() { f = document.forms.widget; which = getrval(f.which); if (which == "all") { url = "${g.default_scheme}://${sr_domain}/" + f.what.value + "/.embed?limit=" + f.num.value + "&t=" + f.when.value; if(f.what.value == "new") { url += "&sort=new"; } } else if (which == "one") { if (!f.who.value) return; url = "${g.default_scheme}://${domain}/user/"+f.who.value+"/"+ f.where2.value+".embed?limit=" + f.num.value + "&sort="+f.what.value; } else if (which == "two") { if(!f.domain.value) return; url = "${g.default_scheme}://${domain}/domain/" + f.domain.value + "/" + f.what.value + "/.embed?limit=" + f.num.value + "&t=" + f.when.value; if(f.what.value == "new") { url += "&sort=new"; } } else { alert(which); } $("#preview").css("width", ""); if(f.expanded.checked) { url += "&expanded=1"; } if(f.nostyle.checked) { url += "&style=off"; $("#css-options").hide(); } else { $("#css-options").show(); if(f.border.checked && f.bord_color.value) { url += "&bordercolor=" + f.bord_color.value; } if(f.background.checked && f.bg_color.value) { url += "&bgcolor=" + f.bg_color.value; } if(f.twocol.checked) { url += "&twocolumn=true"; $("#preview").css("width", "550px"); } } script = '<script src="' + escapeHTML(url).replace(/&amp;/g, '&') + '" type="text/javascript"><'+'/script>'; $("#codebox").html(escapeHTML(script)); $.getScript(url+'&callback=showPreview'); } </script> <div class="instructions"> <div id="preview"> <span>preview</span> <div id="previewbox"> <script src="${g.default_scheme}://${sr_domain}/.embed?limit=5" type="text/javascript"></script> </div> </div> <h1>${_("get live %(site)s headlines on your site") % dict(site=c.site.name)}</h1> <p>${_("just cut and paste the generated code into your site and your specified %(site)s feed will be displayed and updated as new stories bubble up") % dict(site=c.site.name)}</p> <h2>${_("which links do you want to display?")}</h2> <form name="widget" action="" onsubmit="update(); return false" id="widget" class="pretty-form"> <%def name="when()" buffered="True"> <select name="when" onchange="update()" onfocus="update()"> <option value="hour">${_("this hour")}</option> <option value="day">${_("today")}</option> <option value="week">${_("this week")}</option> <option value="month">${_("this month")}</option> <option value="all" selected="selected">${_("all-time")}</option> </select> </%def> <%def name="where2()" buffered="True"> <select name="where2" onchange="update()" onfocus="this.parentNode.firstChild.checked='checked'"> <option value="submitted">${_("submitted by")}</option> <option value="saved">${_("saved by")}</option> <option value="liked">${_("upvoted by")}</option> <option value="disliked">${_("downvoted by")}</option> </select> </%def> <%def name="text_input(name)" buffered="True"> <input type="text" name="${name}" value="" onfocus="this.parentNode.firstChild.checked='checked'" onchange="update()" onblur="update()" /> </%def> <table class="widget-preview preftable"> <tr> <th> ${_("listing options")} </th> <td class="prefright"> <p> <input type="radio" name="which" value="all" checked="checked" onclick="update()" /> ${_("links from %(domain)s") % dict(domain = get_domain())} </p> <p> <input type="radio" name="which" value="one" onclick="update()" /> ${_wsf("links %(submitted_by)s the user %(who)s", submitted_by=unsafe(where2()), who=unsafe(text_input("who")))} </p> <p> <input type="radio" name="which" value="two" onclick="update()" /> ${_wsf("links from the domain %(domain)s", domain=unsafe(text_input("domain")))} </p> </td> </tr> <tr> <th> ${_("sorting options")} </th> <td class="prefright"> <p> <%def name="what()" buffered="True"> <select name="what" onchange="update()"> <option value="hot" selected="selected">${_("hottest")}</option> <option value="new">${_("newest")}</option> <option value="top">${_("top")}</option> </select> </%def> ${_wsf("sort links by %(what)s", what=unsafe(what()))} </p> <p> ${_wsf("date range includes %(when)s", when=unsafe(when()))} </p> <p> ${_("number of links to show")}: <select name="num" onchange="update()"> <option value="5" selected="selected">5</option> <option value="10">10</option> <option value="20">20</option> </select> </p> </td> </tr> <tr> <th> ${_("display options")} </th> <td class="prefright"> <p> <input name="nostyle" id="nostyle" type="checkbox" onchange="update()"/> <label for="nostyle"> ${_("remove css styling")} &#32;<span class="little gray"> ${_("(the widget will inherit all styles from the page)")} </span> </label> </p> <p> <input name="expanded" id="expanded" type="checkbox" onchange="update()"/> <label for="expanded"> ${_("enable in-widget voting")} &#32;<span class="little gray"> ${_("(will slow down the rendering)")} </span> </label> </p> <div id="css-options"> <p> <input name="twocol" id="twocol" type="checkbox" onchange="update()"/> <label for="twocol"> ${_("two columns")} </label> </p> <p> <input name="background" id="background" type="checkbox" onchange="update()"/> <label for="background"> ${_("background color")} </label> &nbsp;#${unsafe(text_input("bg_color"))} &#32;<span class="little gray"> ${_("(e.g., FF0000 = red)")} </span> </p> <p> <input name="border" id="border" type="checkbox" onchange="update()"/> <label for="border"> ${_("border color")} </label> &nbsp;#${unsafe(text_input("bord_color"))} </p> </div> </td> </tr> </table> </form> <h2>${_("the code")}</h2> <p>${_("add this into your HTML where you want the %(site)s links displayed") %dict(site=c.site.name)}</p> <p> <textarea rows="5" cols="50" id="codebox"> &lt;script src="${g.default_scheme}://${domain}/.embed?limit=5" type="text/javascript">&lt;/script> </textarea> </p> </div>
github
vandermeerlab/MountainSort-Hackathon-master
readmda_block.m
.m
MountainSort-Hackathon-master/matlab/mdaio/readmda_block.m
2,963
utf_8
038ab7452375ecd0557ffa24df272223
function A=readmda_block(fname,index0,size0) %READMDA - read a subarray from an .mda file. % % Syntax: A=readmda_block(fname,index0,size0) % % Inputs: % fname - path to the .mda file % index0 - the array index, e.g., [1,1,1000], to start reading % size0 - the size of the array to use % The length of index0 and size0 should equal the number of dimensions % of the array represented by the .mda file % % Outputs: % A - the multi-dimensional array % % Other m-files required: none % % See also: readmda % Author: Jeremy Magland % Jan 2015; Last revision: 15-Feb-2106 if (nargin<1) test_readmda_block; return; end; if (strcmp(fname(end-4:end),'.csv')==1) warning('Case of .csv file not supported for readmda_block'); return; end F=fopen(fname,'rb'); try code=fread(F,1,'int32'); catch error('Problem reading file: %s',fname); end if (code>0) num_dims=code; code=-1; else fread(F,1,'int32'); num_dims=fread(F,1,'int32'); end; dim_type_str='int32'; if (num_dims<0) num_dims=-num_dims; dim_type_str='int64'; end; S=zeros(1,num_dims); for j=1:num_dims S(j)=fread(F,1,dim_type_str); end; if num_dims == 1, num_dims=2; S=[1,S(1)]; end % Remove singleton dimensions at end until length(index0) equals num_dims while ((num_dims>2)&&(num_dims>length(index0))&&(S(end)==1)) S=S(1:end-1); num_dims=num_dims-1; end; % check that we can handle the situation for j=1:num_dims-1 if (index0(j)~=1)||(size0(j)~=S(j)) disp(index0); disp(size0); error('Cannot yet handle this case when reading block from %s',fname); end; end; A=zeros(size0); N=prod(size0); seek_size=prod(S(1:end-1))*(index0(end)-1); if (code==-1) fseek(F,seek_size*8,'cof'); M=zeros(1,N*2); M(:)=fread(F,N*2,'float'); A(:)=M(1:2:N*2)+i*M(2:2:N*2); elseif (code==-2) fseek(F,seek_size*1,'cof'); A(:)=fread(F,N,'uchar'); elseif (code==-3) fseek(F,seek_size*4,'cof'); A(:)=fread(F,N,'float'); elseif (code==-4) fseek(F,seek_size*2,'cof'); A(:)=fread(F,N,'int16'); elseif (code==-5) fseek(F,seek_size*4,'cof'); A(:)=fread(F,N,'int32'); elseif (code==-6) fseek(F,seek_size*2,'cof'); A(:)=fread(F,N,'uint16'); elseif (code==-7) fseek(F,seek_size*8,'cof'); A(:)=fread(F,N,'double'); elseif (code==-8) fseek(F,seek_size*4,'cof'); A(:)=fread(F,N,'uint32'); else error('Unsupported data type code: %d',code); end; fclose(F); function test_readmda_block X=rand(10,20,30); writemda(X,'tmp.mda'); Y=readmda_block('tmp.mda',[1,1,5],[10,20,10]); tmp=X(:,:,5:5+10-1)-Y; fprintf('This should be small: %g\n',max(abs(tmp(:)))); X2=floor(X*1000); writemda16ui(X2,'tmp.mda'); Y=readmda_block('tmp.mda',[1,1,5],[10,20,10]); tmp=X2(:,:,5:5+10-1)-Y; fprintf('This should be zero: %g\n',max(abs(tmp(:))));
github
vandermeerlab/MountainSort-Hackathon-master
writemda.m
.m
MountainSort-Hackathon-master/matlab/mdaio/writemda.m
3,745
utf_8
92328d2311adcaa732cd4738ee391fc0
function writemda(X,fname,dtype) %WRITEMDA - write to a .mda file. MDA stands for %multi-dimensional array. % % See http://magland.github.io//articles/mda-format/ % % Syntax: writemda(X,fname) % % Inputs: % X - the multi-dimensional array % fname - path to the output .mda file % dtype - 'complex32', 'int32', 'float32','float64' % % Other m-files required: none % % See also: readmda % Author: Jeremy Magland % Jan 2015; Last revision: 15-Feb-2016; typo fixed Barnett 2/26/16 num_dims=2; if (size(X,3)~=1) num_dims=3; end; % ~=1 added by jfm on 11/5/2015 to handle case of, eg, 10x10x0 if (size(X,4)~=1) num_dims=4; end; if (size(X,5)~=1) num_dims=5; end; if (size(X,6)~=1) num_dims=6; end; if nargin<3, dtype=''; end; if isempty(dtype) %warning('Please use writemda32 or writemda64 rather than directly calling writemda. This way you have control on whether the file stores 32-bit or 64-bit floating points.'); is_complex=1; if (isreal(X)) is_complex=0; end; if (is_complex) dtype='complex32'; else is_integer=check_if_integer(X); if (~is_integer) dtype='float32'; else dtype='int32'; end; end; end; FF=fopen(fname,'w'); if strcmp(dtype,'complex32') fwrite(FF,-1,'int32'); fwrite(FF,8,'int32'); fwrite(FF,num_dims,'int32'); dimprod=1; for dd=1:num_dims fwrite(FF,size(X,dd),'int32'); dimprod=dimprod*size(X,dd); end; XS=reshape(X,dimprod,1); Y=zeros(dimprod*2,1); Y(1:2:dimprod*2-1)=real(XS); Y(2:2:dimprod*2)=imag(XS); fwrite(FF,Y,'float32'); elseif strcmp(dtype,'float32') fwrite(FF,-3,'int32'); fwrite(FF,4,'int32'); fwrite(FF,num_dims,'int32'); dimprod=1; for dd=1:num_dims fwrite(FF,size(X,dd),'int32'); dimprod=dimprod*size(X,dd); end; Y=reshape(X,dimprod,1); fwrite(FF,Y,'float32'); elseif strcmp(dtype,'float64') fwrite(FF,-7,'int32'); fwrite(FF,8,'int32'); fwrite(FF,num_dims,'int32'); dimprod=1; for dd=1:num_dims fwrite(FF,size(X,dd),'int32'); dimprod=dimprod*size(X,dd); end; Y=reshape(X,dimprod,1); fwrite(FF,Y,'float64'); elseif strcmp(dtype,'int32') fwrite(FF,-5,'int32'); fwrite(FF,4,'int32'); fwrite(FF,num_dims,'int32'); dimprod=1; for dd=1:num_dims fwrite(FF,size(X,dd),'int32'); dimprod=dimprod*size(X,dd); end; Y=reshape(X,dimprod,1); fwrite(FF,Y,'int32'); elseif strcmp(dtype,'int16') fwrite(FF,-4,'int32'); fwrite(FF,2,'int32'); fwrite(FF,num_dims,'int32'); dimprod=1; for dd=1:num_dims fwrite(FF,size(X,dd),'int32'); dimprod=dimprod*size(X,dd); end; Y=reshape(X,dimprod,1); fwrite(FF,Y,'int16'); elseif strcmp(dtype,'uint16') fwrite(FF,-6,'int32'); fwrite(FF,2,'int32'); fwrite(FF,num_dims,'int32'); dimprod=1; for dd=1:num_dims fwrite(FF,size(X,dd),'int32'); dimprod=dimprod*size(X,dd); end; Y=reshape(X,dimprod,1); fwrite(FF,Y,'uint16'); elseif strcmp(dtype,'uint32') fwrite(FF,-8,'int32'); fwrite(FF,4,'int32'); fwrite(FF,num_dims,'int32'); dimprod=1; for dd=1:num_dims fwrite(FF,size(X,dd),'int32'); dimprod=dimprod*size(X,dd); end; Y=reshape(X,dimprod,1); fwrite(FF,Y,'uint32'); else error('Unknown dtype %s',dtype); end; fclose(FF); end function ret=check_if_integer(X) ret=0; if (length(X)==0) ret=1; return; end; if (X(1)~=round(X(1))) ret=0; return; end; tmp=X(:)-round(X(:)); if (max(abs(tmp))==0) ret=1; end; end
github
vandermeerlab/MountainSort-Hackathon-master
mp_run_process.m
.m
MountainSort-Hackathon-master/matlab/wrap/mp_run_process.m
1,247
utf_8
faf321249ca562430c66c06f8ce102b8
function mp_run_process(processor_name,inputs,outputs,params,opts) %% Example: mp_run_process('mountainsort.bandpass_filter',struct('timeseries','tetrode6.mda'),struct('timeseries_out','tetrode6_filt.mda'),struct('samplerate',32556,'freq_min',300,'freq_max',6000)); if nargin<4, params=struct; end; if nargin<5, opts=struct; end; if ~isfield(opts,'mp_command') opts.mp_command='mp-run-process'; end; cmd=opts.mp_command; cmd=[cmd,' ',processor_name]; cmd=[cmd,' ',create_arg_string(inputs)]; cmd=[cmd,' ',create_arg_string(outputs)]; cmd=[cmd,' ',create_arg_string(params)]; return_code=system_call(cmd); if (return_code~=0) error('Error running processor: %s',processor_name); end; function str=create_arg_string(params) list={}; keys=fieldnames(params); for i=1:length(keys) key=keys{i}; val=params.(key); if (iscell(val)) for cc=1:length(val) list{end+1}=sprintf('--%s=%s',key,create_val_string(val{cc})); end; else list{end+1}=sprintf('--%s=%s',key,create_val_string(val)); end; end; str=strjoin(list,' '); function str=create_val_string(val) str=num2str(val); function return_code=system_call(cmd) cmd=sprintf('LD_LIBRARY_PATH=/usr/local/lib %s',cmd); return_code=system(cmd);
github
aida-alvera/DINEOF-master
dineof.m
.m
DINEOF-master/Scripts/Matlab/dineof.m
4,327
utf_8
ee2dc9735e04629dad991bf1abff3fb2
% filled = dineof(data,...) % run DINEOF from Matlab/Octave. data is a 3-d matrix with the dimensions % longitude, latitude and time. % % INSTALLATION: place the binary dineof (or dineof.exe under PC) in the parent % directory (relative to this script dineof.m) or set the option 'exec' % described below. % % Optional input arguments are: % % mask: land-sea mask, if it is not provided it is determined by the script % dineof_mask % frac: minium fraction of data in time to that a pixel is considered sea % (default 0.05, i.e. 5 %) % exec: executable of DINEOF (default: the full path of the parent directory % followed by "dineof" or "dineof.exe" (on PC)) % dir: working directory (default a temporary directory) % % For all other optional parameters, please refer to the DINEOF documentation. % nev % neini % tol % toliter % rec % eof % norm % seed % alpha % numit % time % % Note this scripts unset the variable LD_LIBRARY_PATH % te prevent errors likes these in matlab: % % /opt/matlab-R2013a/sys/os/glnxa64/libgfortran.so.3: version `GFORTRAN_1.4' not found (required by /home/abarth/src/dineof/dineof) function [filled,info] = dineof(data,varargin) global DINEOF_EXEC % default values nev = 10; neini = 1; ncv = nev + 10; tol = 1.0e-8; nitemax = 300; toliter = 1.0e-3; rec = 1; eof = 1; norm = 0; seed = 243435; alpha = 0.; numit = 3; frac = 0.05; dir = tempname; time = []; mask = []; exec = DINEOF_EXEC; if isempty(exec) exec = getenv('DINEOF_EXEC'); if isempty(exec) % assume the dineof binary is in the parent directory if ispc exec = fullfile(fileparts(mfilename('fullpath')),'..','dineof.exe'); else exec = fullfile(fileparts(mfilename('fullpath')),'..','dineof'); end end end prop = varargin; for i=1:2:length(prop) if strcmp(prop{i},'nev') nev = prop{i+1}; elseif strcmp(prop{i},'neini') neini = prop{i+1}; elseif strcmp(prop{i},'tol') tol = prop{i+1}; elseif strcmp(prop{i},'toliter') toliter = prop{i+1}; elseif strcmp(prop{i},'rec') rec = prop{i+1}; elseif strcmp(prop{i},'eof') eof = prop{i+1}; elseif strcmp(prop{i},'norm') norm = prop{i+1}; elseif strcmp(prop{i},'seed') seed = prop{i+1}; elseif strcmp(prop{i},'alpha') alpha = prop{i+1}; elseif strcmp(prop{i},'numit') numit = prop{i+1}; elseif strcmp(prop{i},'dir') dir = prop{i+1}; elseif strcmp(prop{i},'exec') exec = prop{i+1}; elseif strcmp(prop{i},'time') time = prop{i+1}; elseif strcmp(prop{i},'mask') mask = prop{i+1}; elseif strcmp(prop{i},'frac') frac = prop{i+1}; else error(['unkown argument ' prop{i}]); end end fprintf('Using dineof binary: %s\n',exec); if isempty(mask) mask = dineof_mask(data,frac); end d = [dir filesep]; mkdir(d); gwrite([d 'data'],data); gwrite([d 'mask'],mask); if alpha > 0 gwrite([d 'time'],time); end initfile = [d 'dineof.init']; fid = fopen(initfile,'w'); fprintf(fid,'# inpput File for dineof\n'); fprintf(fid,'# created by the script %s\n',mfilename); fprintf(fid,'data = [''%s'']\n',[d 'data']); fprintf(fid,'mask = [''%s'']\n',[d 'mask']); fprintf(fid,'nev = %d\n',nev); fprintf(fid,'neini = %d\n',neini); fprintf(fid,'ncv = %d\n',ncv); fprintf(fid,'tol = %g\n',tol); fprintf(fid,'nitemax = %d\n',nitemax); fprintf(fid,'toliter = %g\n',toliter); fprintf(fid,'rec = %d\n',rec); fprintf(fid,'eof = %d\n',eof); fprintf(fid,'norm = %d\n',norm); fprintf(fid,'Output = ''%s''\n',[d]); fprintf(fid,'results = [''%s'']\n',[d 'output']); fprintf(fid,'seed = %d\n',seed); fprintf(fid,'EOF.U = [''eof.nc#U''] \n'); fprintf(fid,'EOF.V = ''eof.nc#V''\n'); % must be there but it is not used fprintf(fid,'EOF.Sigma = ''eof.nc#Sigma''\n'); fprintf(fid,'alpha = %g\n',alpha); fprintf(fid,'numit = %d\n',numit); if alpha > 0 fprintf(fid,'time = ''%s''\n',[d 'time']); end fclose(fid); cmd = sprintf('"%s" "%s"',exec,initfile); disp(cmd) cmd = ['unset LD_LIBRARY_PATH; ' cmd]; [status,result] = system(cmd,'-echo'); if status ~= 0 disp(result) error('dineof failed'); end filled = gread([d 'output']); ncfile = fullfile(d,'eof.nc'); info.U = ncread(ncfile,'U'); info.V = ncread(ncfile,'V'); %info.Sigma = ncread(ncfile,'Sigma'); info.Sigma = ncread(fullfile(d,'DINEOF_diagnostics.nc'),'vlsng');
github
aida-alvera/DINEOF-master
gzfopen.m
.m
DINEOF-master/Scripts/Matlab/IO/gzfopen.m
563
utf_8
6a9cfc7af379fe303596c7119a18b424
% fid=gzfopen(fname,permisson,machineformat) % % same as fopen except that the file is decompressed if it ends % with ".gz" or ".bz2" % % % Alexander Barth function fid=gzfopen(fname,permisson,machineformat) global GZ_FILE_IDS GZ_FILE_NAMES if isempty(GZ_FILE_NAMES) GZ_FILE_NAMES={}; end [fname] = gread_tilde_expand(fname); [tmp] = decompress(fname); zipped = ~strcmp(tmp,fname); if zipped fid = fopen(tmp,permisson,machineformat); GZ_FILE_IDS(end+1) = fid; GZ_FILE_NAMES{end+1} = tmp; else fid = fopen(fname,permisson,machineformat); end
github
aida-alvera/DINEOF-master
gzfclose.m
.m
DINEOF-master/Scripts/Matlab/IO/gzfclose.m
636
utf_8
7ca248f9527f4d19c25c56bdbf4f79a2
% gzfclose(fid) % % same as fclose except that a decompressed temporary file % is deleted if the file ends with ".gz" or ".bz2" % % % Alexander Barth, 2008-03-19 function fid = gzfclose(fid) global GZ_FILE_IDS GZ_FILE_NAMES fid = fclose(fid); index = []; if ~isempty(GZ_FILE_IDS) index = find(GZ_FILE_IDS == fid); end if ~isempty(index) tmp = GZ_FILE_NAMES{index}; delete(tmp); GZ_FILE_IDS(index)=[]; % GZ_FILE_NAMES={GZ_FILE_NAMES{1:index-1} GZ_FILE_NAMES{index+1:end}}; % for compatability witch octave GZ_FILE_NAMES(index:end-1) = GZ_FILE_NAMES(index+1:end); GZ_FILE_NAMES = GZ_FILE_NAMES(1:end-1) ; end
github
aida-alvera/DINEOF-master
gwrite.m
.m
DINEOF-master/Scripts/Matlab/IO/gwrite.m
1,478
utf_8
7b2d3d1136ff74c13e4036c55618e8bb
% flag = gwrite(name,tab) % % save a file in GHER format or a NetCDF variable in NetCDF file % % Input: % name: name of the GHER file or NetCDF file name and % variable name concanenated by a # % tab: the variable to save % % % Output: % flag: 1 on success; 0 otherwise % % Example: % % For GHER format: % gwrite('data.TEM',temp) % % Alexander Barth, 2008-03-19 function flag = gwrite(name,tab) [name] = gread_tilde_expand(name); valex = -9999; tab(isnan(tab)) = valex; i = find(name == '#'); if isempty(i) [imax] = size(tab,1); [jmax] = size(tab,2); [kmax] = size(tab,3); nbmots = 10*1024*1024; % 10 MB record length [flag]=uwrite(name,tab(:),imax,jmax,kmax,valex,nbmots); else fname = name(1:i-1); vname = name(i+1:end); if (fexist(fname)) nf = netcdf(fname,'write'); else nf = netcdf(fname,'clobber'); end tab = permute(tab,[ndims(tab):-1:1]); % re-use dimensions that are already defined in the netCDF file for i=1:myndims(tab); dim{i} = gendim(nf,size(tab,i)); end nf{vname} = ncfloat(dim{:}); nf{vname}(:) = tab; nf{vname}.missing_value = ncfloat(valex); close(nf); end function ncdim = gendim(nf,len) d = dim(nf); for i=1:length(d) if length(d{i})==len ncdim = name(d{i}); return end end ncdim = ['dim' num2str(length(nf)+1,'%3.3i')]; nf(ncdim) = len; return function d = myndims(a) d = ndims(a); if (d==2 & size(a,2) == 1) d=1; end
github
aida-alvera/DINEOF-master
gread.m
.m
DINEOF-master/Scripts/Matlab/IO/gread.m
2,244
utf_8
8926ef7fee41c4a6fc5506762e65c839
% tab = gread(name) % % loads a NetCDF variable from a NetCDF file % % Input: % name: file name and variable name concanenated by a # % % Output: % tab: the loaded variable % % Example: % % Tair = gread('atm.nc#Tair') % % Alexander Barth, 2007-08-03 function [tab,info] = gread(name) [name] = gread_tilde_expand(name); extraction = []; % search for extraction list i = find(name == '('); if ~isempty(i) extraction = name(i:end); name = name(1:i-1); end i = find(name == '#'); if isempty(i) [flag,c4,imax,jmax,kmax,info.valex] = uread(name); if (imax < 0) imax = abs(imax); jmax = abs(jmax); kmax = abs(kmax); tab = zeros(imax,jmax,kmax); [i,j,k] = ndgrid([1:imax],[1:jmax],[1:kmax]); tab = c4(1) + c4(2)*i + c4(3)*j + c4(4)*k; else tab = reshape(c4,imax,jmax,kmax); if (~isempty(extraction)) eval(['tab = tab' extraction ';']); end end else fname = name(1:i-1); vname = name(i+1:end); i = find(vname == '('); [tmp] = decompress(fname); zipped = ~strcmp(tmp,fname); if zipped [tab,info] = gread([tmp '#' vname extraction]); delete(tmp); else nf = netcdf(fname,'r'); % without auto scaling nv = nf{vname}; % with auto scaling % nv = nf{vname,1}; if isempty(nv) error(['variable ' vname ' not found in netcdf file ' fname]); end if (isempty(extraction)) tab = nv(:); else % reverse extraction list delim = [ strfind(extraction,'(') strfind(extraction,',') strfind(extraction,')')]; n = length(delim)-1; rev = '('; for i=0:n-2; rev = [rev extraction(delim(n-i)+1:delim(n-i+1)-1) ',']; end; rev = [rev extraction(delim(1)+1:delim(2)-1) ')']; eval(['tab = nv' rev ';']); end tab = permute(tab,[ndims(tab):-1:1]); if ~isempty(nv.missing_value(:)) info.valex = nv.missing_value(:); elseif ~isempty(fillval(nv)) info.valex = fillval(nv); else info.valex = NaN; end close(nf); end end if isnan(info.valex) info.excl = 0; else info.excl = sum(tab(:) == info.valex); tab(tab == info.valex) = NaN; end
github
aida-alvera/DINEOF-master
gread_tilde_expand.m
.m
DINEOF-master/Scripts/Matlab/IO/gread_tilde_expand.m
242
utf_8
e913f0b4efa099bad7dec370f5213492
% replace ~ by home dir % (function build-in in octave) % % Alexander Barth, 2008-07-16 function [fname] = gread_tilde_expand(fname) homedir = getenv('HOME'); if ~isempty(homedir) & fname(1) == '~' fname = strrep(fname,'~',homedir); end
github
aida-alvera/DINEOF-master
uwrite.m
.m
DINEOF-master/Scripts/Matlab/IO/uwrite.m
2,139
utf_8
35fb074ced648dbfa125972e7686cbfe
% [flag]=uwrite(file,c4,imax,jmax,kmax,valex,nbmots) % % low-level routine for writing data redable by a Fortran program % % Input: % file: filename % c4: data % imax,jmax,kmax: size of the array % valex: exclusion value % nbmots: word length % % Output: % flag: 1 is successful % % Example: % % [flag] = uread('file.TEM',a,size(a,1),size(a,2),size(a,3),9999,1000) % % M. Rixen 2000 % ----------------------------------------------------- % ------------ GHER file : write function -------------- % ------------ for MATLAB routines -------------------- % ------------ M. Rixen 2000 -------------------------- % % 2008-07-14 % change format with global variable UWRITE_DEFAULT_FORMAT % Alexander % % 2010-01-06 % NaNs are no longer substituted by valex since this is done % in gwrite function [flag]=uwrite(file,c4,imax,jmax,kmax,valex,nbmots) global UWRITE_DEFAULT_FORMAT global UWRITE_DEFAULT_PRECISION if isempty(UWRITE_DEFAULT_FORMAT) format = 'ieee-be'; else format = UWRITE_DEFAULT_FORMAT; end if isempty(UWRITE_DEFAULT_PRECISION) iprec=4; else iprec=UWRITE_DEFAULT_PRECISION; end if iprec == 4 float_precision = 'single'; else float_precision = 'double'; end [file] = gread_tilde_expand(file); flag=0; file; dummy=0; dummyf=0.; dummy24=24; fid=fopen(file,'w',format); if fid==-1 error(['uwrite: could not write ' file]); end if nbmots==-1 nbmots=imax*jmax*kmax end for i=1:10 fwrite(fid,dummy,'int32'); fwrite(fid,dummy,'int32'); end nl=fix((imax*jmax*kmax)/nbmots); ir=imax*jmax*kmax-nbmots*nl; dummyval2=4*nbmots; fwrite(fid,dummy24,'int32'); fwrite(fid,imax,'int32'); fwrite(fid,jmax,'int32'); fwrite(fid,kmax,'int32'); fwrite(fid,iprec,'int32'); fwrite(fid,nbmots,'int32'); fwrite(fid,valex,'single'); fwrite(fid,dummy24,'int32'); if imax<0 | jmax<0 | kmax<0 nl=0; ir=4; disp('Degenerated matrix'); end ide=1; for kl=1:nl fwrite(fid,4*nbmots,'int32'); fwrite(fid,c4(ide:ide+nbmots-1),float_precision); fwrite(fid,4*nbmots,'int32'); ide=ide+nbmots; end fwrite(fid,4*ir,'int32'); fwrite(fid,c4(ide:ide+ir-1),float_precision); fwrite(fid,4*ir,'int32'); flag=1; fclose(fid);
github
aida-alvera/DINEOF-master
uread.m
.m
DINEOF-master/Scripts/Matlab/IO/uread.m
1,960
utf_8
47b2752727884afb4cf99a64487076e0
% [flag,data,imax,jmax,kmax,valex,nbmots,format] = uread(file) % % low-level routine for loading Fortran files % % Input: % file: filename % % Output: % flag: 1 is successful % c4: data % imax,jmax,kmax: size of the array % valex: exclusion value % nbmots: word length % % Example: % % [flag,c4,imax,jmax,kmax,valex,nbmots] = uread('file.TEM') % % M. Rixen 2000 % Alexander Barth, 2007-08-03 % optimisation: 03/04/2003 % Alexander % % support of double precision % Alexander % % 2008-07-14 % detecting binary format % Alexander function [flag,data,imax,jmax,kmax,valex,nbmots,format] = uread(file) flag=0; % all formats to try formats = {'ieee-be','ieee-le','native'}; for i=1:length(formats) fid=gzfopen(file,'r',formats{i}); if fid==-1 error(['uread: ' file ' not found.']); end % ignore header fread(fid,20,'int32'); reclen = fread(fid,1,'int32'); if reclen==24 break else fid = gzfclose(fid); end end format = formats{i}; %disp(['uread: file is ' formats{i}]); if fid==0 error(['uread: format of ' file ' is not recognized.']); end imax=fread(fid,1,'int32'); jmax=fread(fid,1,'int32'); kmax=fread(fid,1,'int32'); iprec=fread(fid,1,'int32'); nbmots=fread(fid,1,'int32'); valex=fread(fid,1,'float'); fread(fid,2,'int32'); if (iprec==4) vtype = 'float'; else vtype = 'double'; end nl=fix((imax*jmax*kmax)/nbmots); ir=imax*jmax*kmax-nbmots*nl; ide=1; if imax<0 | jmax<0 | kmax<0 nl=0; ir=4; % disp('Degenerated matrix'); end % load all full records including leading and tailing 4 byte integer % for efficiency these integers are read as two floats or one double if (iprec==4) data = reshape(fread(fid,nl*(nbmots+2),vtype),nbmots+2,nl); else data = reshape(fread(fid,nl*(nbmots+1),vtype),nbmots+1,nl); end % remove leading and tailing 4 byte integer data = data(1:nbmots,:); data = data(:); % read last record data = [data; fread(fid,ir,vtype)]; flag=1; fid = gzfclose(fid);
github
aida-alvera/DINEOF-master
filelist.m
.m
DINEOF-master/Scripts/Matlab/IO/filelist.m
556
utf_8
b53ab0ff1f7ea38eb800613e23df57ed
% files = filelist(pattern); % create a list of a file names matching the pattern (include wild-cards such as *) % expands ~ to home directory and sorts all files alphabetically function files = filelist(pattern); pattern = gread_tilde_expand(pattern); i = regexp(pattern,'[#(]'); if ~isempty(i) subset = pattern(i:end); pattern = pattern(1:i-1); else subset = ''; end %[basedir] = fileparts (pattern); %d = dir(pattern); l = uglob(pattern); files = cell(1,length(l)); for i=1:length(l) files{i} = [l{i} subset]; end files = sort(files);
github
aida-alvera/DINEOF-master
ureadslice.m
.m
DINEOF-master/Scripts/Matlab/rcv/ureadslice.m
1,273
utf_8
8591b1eb682e1d681ab4d607a013ba29
% ----------------------------------------------------- % ------------ GHER file : read function -------------- % ------------ for MATLAB routines -------------------- % ------------ M. Rixen 2000 -------------------------- function tab = ureadslice(fidslice,imax,jmax,kmax,valex,nbmots,nl,ir,pastread) %ide=1; c4 = zeros(imax,1); % need distinction : if imax > nbmots % load all full records including leading and tailing 4 byte integer %data = reshape(fread(fid,nl*(nbmots+2),'single'),nbmots+2,nl); % remove leading and tailing 4 byte integer %c4(1:nbmots*nl) = reshape(data(1:nbmots,:),nbmots*nl,1); % read last record %c4(nbmots*nl+1:end)=fread(fid,ir,'single'); %stop=stopnow if (nbmots-pastread) > imax c4 = fread(fidslice,imax,'single'); pastread=pastread+imax; else leftinline=nbmots-pastread; c4(1:leftinline) = fread(fidslice,leftinline,'single'); empty=fread(fid,2,'single'); stilltoread=imax-leftinline; c4(leftinline+1:imax) = fread(fidslice,stilltoread,'single'); pastread=stilltoread; end %%%%%%%%%% c4(find(c4(:)==valex)) = NaN; %tab = reshape(c4,imax,jmax,kmax); tab = reshape(c4,imax,1,1); flag=1; %fclose(fid); %modified gzfclose
github
aida-alvera/DINEOF-master
ureadsingle.m
.m
DINEOF-master/Scripts/Matlab/rcv/ureadsingle.m
1,321
utf_8
d214da91558aad236a564427ada0f285
% ----------------------------------------------------- % ------------ GHER file : read function -------------- % ------------ for MATLAB routines -------------------- % ------------ M. Rixen 2000 -------------------------- % optimisation: 03/04/2003 % Alexander function [flag,c4,imax,jmax,kmax,valex,nbmots] = uread(file) flag=0; imax=0; jmax=0; kmax=0; valex=0; fid=fopen(file,'r','ieee-be'); %modified ori: gzfopen and ieee.be if fid==-1 error([file ' not found.']); end % ignore header fread(fid,21,'int32') imax=fread(fid,1,'int32') jmax=fread(fid,1,'int32') kmax=fread(fid,1,'int32') iprec=fread(fid,1,'int32') nbmots=fread(fid,1,'int32') valex=fread(fid,1,'single') fread(fid,2,'int32'); nl=fix((imax*jmax*kmax)/nbmots); ir=imax*jmax*kmax-nbmots*nl; ide=1; if imax<0 | jmax<0 | kmax<0 nl=0; ir=4; % disp('Degenerated matrix'); end % allocation %nbmots %nl %ir c4 = zeros(nbmots*nl+ir,1); % load all full records including leading and tailing 4 byte integer data = reshape(fread(fid,nl*(nbmots+2),'single'),nbmots+2,nl); % remove leading and tailing 4 byte integer c4(1:nbmots*nl) = reshape(data(1:nbmots,:),nbmots*nl,1); % read last record c4(nbmots*nl+1:end)=fread(fid,ir,'single'); flag=1; fclose(fid); %modified gzfclose
github
aida-alvera/DINEOF-master
ureadslicedouble.m
.m
DINEOF-master/Scripts/Matlab/rcv/ureadslicedouble.m
1,273
utf_8
d403e8db2356ea6516bec5b1063079b2
% ----------------------------------------------------- % ------------ GHER file : read function -------------- % ------------ for MATLAB routines -------------------- % ------------ M. Rixen 2000 -------------------------- function tab = ureadslice(fidslice,imax,jmax,kmax,valex,nbmots,nl,ir,pastread) %ide=1; c4 = zeros(imax,1); % need distinction : if imax > nbmots % load all full records including leading and tailing 4 byte integer %data = reshape(fread(fid,nl*(nbmots+2),'single'),nbmots+2,nl); % remove leading and tailing 4 byte integer %c4(1:nbmots*nl) = reshape(data(1:nbmots,:),nbmots*nl,1); % read last record %c4(nbmots*nl+1:end)=fread(fid,ir,'single'); %stop=stopnow if (nbmots-pastread) > imax c4 = fread(fidslice,imax,'double'); pastread=pastread+imax; else leftinline=nbmots-pastread; c4(1:leftinline) = fread(fidslice,leftinline,'double'); empty=fread(fid,2,'double'); stilltoread=imax-leftinline; c4(leftinline+1:imax) = fread(fidslice,stilltoread,'double'); pastread=stilltoread; end %%%%%%%%%% c4(find(c4(:)==valex)) = NaN; %tab = reshape(c4,imax,jmax,kmax); tab = reshape(c4,imax,1,1); flag=1; %fclose(fid); %modified gzfclose
github
aida-alvera/DINEOF-master
uread.m
.m
DINEOF-master/Scripts/Matlab/rcv/uread.m
1,321
utf_8
d214da91558aad236a564427ada0f285
% ----------------------------------------------------- % ------------ GHER file : read function -------------- % ------------ for MATLAB routines -------------------- % ------------ M. Rixen 2000 -------------------------- % optimisation: 03/04/2003 % Alexander function [flag,c4,imax,jmax,kmax,valex,nbmots] = uread(file) flag=0; imax=0; jmax=0; kmax=0; valex=0; fid=fopen(file,'r','ieee-be'); %modified ori: gzfopen and ieee.be if fid==-1 error([file ' not found.']); end % ignore header fread(fid,21,'int32') imax=fread(fid,1,'int32') jmax=fread(fid,1,'int32') kmax=fread(fid,1,'int32') iprec=fread(fid,1,'int32') nbmots=fread(fid,1,'int32') valex=fread(fid,1,'single') fread(fid,2,'int32'); nl=fix((imax*jmax*kmax)/nbmots); ir=imax*jmax*kmax-nbmots*nl; ide=1; if imax<0 | jmax<0 | kmax<0 nl=0; ir=4; % disp('Degenerated matrix'); end % allocation %nbmots %nl %ir c4 = zeros(nbmots*nl+ir,1); % load all full records including leading and tailing 4 byte integer data = reshape(fread(fid,nl*(nbmots+2),'single'),nbmots+2,nl); % remove leading and tailing 4 byte integer c4(1:nbmots*nl) = reshape(data(1:nbmots,:),nbmots*nl,1); % read last record c4(nbmots*nl+1:end)=fread(fid,ir,'single'); flag=1; fclose(fid); %modified gzfclose
github
aida-alvera/DINEOF-master
ureaddouble.m
.m
DINEOF-master/Scripts/Matlab/rcv/ureaddouble.m
1,321
utf_8
b62044134ddb9218c9597118eeaaaa8f
% ----------------------------------------------------- % ------------ GHER file : read function -------------- % ------------ for MATLAB routines -------------------- % ------------ M. Rixen 2000 -------------------------- % optimisation: 03/04/2003 % Alexander function [flag,c4,imax,jmax,kmax,valex,nbmots] = uread(file) flag=0; imax=0; jmax=0; kmax=0; valex=0; fid=fopen(file,'r','ieee-be'); %modified ori: gzfopen and ieee.be if fid==-1 error([file ' not found.']); end % ignore header fread(fid,21,'int32') imax=fread(fid,1,'int32') jmax=fread(fid,1,'int32') kmax=fread(fid,1,'int32') iprec=fread(fid,1,'int32') nbmots=fread(fid,1,'int32') valex=fread(fid,1,'single') fread(fid,2,'int32'); nl=fix((imax*jmax*kmax)/nbmots); ir=imax*jmax*kmax-nbmots*nl; ide=1; if imax<0 | jmax<0 | kmax<0 nl=0; ir=4; % disp('Degenerated matrix'); end % allocation %nbmots %nl %ir c4 = zeros(nbmots*nl+ir,1); % load all full records including leading and tailing 4 byte integer data = reshape(fread(fid,nl*(nbmots+2),'double'),nbmots+2,nl); % remove leading and tailing 4 byte integer c4(1:nbmots*nl) = reshape(data(1:nbmots,:),nbmots*nl,1); % read last record c4(nbmots*nl+1:end)=fread(fid,ir,'double'); flag=1; fclose(fid); %modified gzfclose
github
oiwic/QOS-master
spectroscopy1_zpa_bndSwp.m
.m
QOS-master/qos/+data_taking/+public/+xmon/spectroscopy1_zpa_bndSwp.m
2,326
utf_8
2b4653159d4d8231fadea4c5358e1ffe
function varargout = spectroscopy1_zpa_bndSwp(varargin) % spectroscopy1: qubit spectroscopy with band sweep % % <_o_> = spectroscopy1_zpa_bndSwp('qubit',_c&o_,'biasAmp',<[_f_]>,... % 'swpBandCenterFcn',<_o_>,'swpBandWdth',<[_f_]>,... % 'driveFreq',<[_f_]>,... % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2016/12/27 fcn_name = 'data_taking.public.xmon.spectroscopy1_zpa_bndSwp'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'r_avg',[],'biasAmp',0,'driveFreq',[],... 'swpBandCenterFcn',[],'swpBandWdth',10e6,'gui',false,'notes','','save',true}); q = data_taking.public.util.getQubits(args,{'qubit'}); if isempty(args.driveFreq) args.driveFreq = q.f01-3*q.t_spcFWHM_est:... q.t_spcFWHM_est/10:q.f01+3*q.t_spcFWHM_est; end if isempty(args.swpBandCenterFcn) args.swpBandCenterFcn = @(x_)1; args.swpBandWdth = Inf; end if ~isempty(args.r_avg) q.r_avg=args.r_avg; end X = op.mwDrive4Spectrum(q); X.Run(); Z = op.zBias4Spectrum(q); R = measure.resonatorReadout_ss(q); R.delay = X.length; R.state = 2; function proc = procFactory(amp) Z.amp = amp; proc = Z.*X; end x = expParam(@procFactory,true); x.name = [q.name,' z bias amplitude']; y = expParam(X.mw_src{1},'frequency'); y.offset = -q.spc_sbFreq; y.name = [q.name,' driving frequency (Hz)']; y.callbacks ={@(x_)x.fcnval.Run()}; s1 = sweep(x); s1.vals = args.biasAmp; s2 = sweep(y); s2.vals = args.driveFreq; swpRngObj = util.dynMwSweepRngBnd(s1,s2); swpRngObj.centerfunc = args.swpBandCenterFcn; swpRngObj.bandwidth = args.swpBandWdth; e = experiment(); e.name = 'Spectroscopy'; e.sweeps = [s1,s2]; e.measurements = R; e.datafileprefix = sprintf('%s', q.name); if ~args.gui e.showctrlpanel = false; e.plotdata = false; end if ~args.save e.savedata = false; end e.notes = args.notes; e.addSettings({'fcn','args'},{fcn_name,args}); e.Run(); varargout{1} = e; end
github
oiwic/QOS-master
spectroscopy111_zpa_s21.m
.m
QOS-master/qos/+data_taking/+public/+xmon/spectroscopy111_zpa_s21.m
2,856
utf_8
0edd98df80fbf837c1bd3a0eb4f24a9a
function varargout = spectroscopy111_zpa_s21(varargin) % qubit spectroscopy of one qubit with s21 as measurement data. % comparison: spectroscopy111_zpa and spectroscopy111_zdc measure % probability of |1>. % spectroscopy1_zpa_s21 is used during tune up when mesurement of % probability of |1> has not been setup. % % <_o_> = spectroscopy1_zpa_s21('biasQubit',_c&o_,'biasAmp',<[_f_]>,... % 'driveQubit','driveFreq',<[_f_]>,... % 'readoutQubit',_c&o_,... % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float% _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2016/1/14 error('spectroscopy111_zpa_s21 is obsolete, use spectroscopy111_zpa with dataTyp set to ''S21'''); fcn_name = 'data_taking.public.xmon.spectroscopy111_zpa_s21'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'biasAmp',0,'driveFreq',[],'r_avg',[],'gui',false,'notes','','save',true}); [readoutQubit, biasQubit, driveQubit] = data_taking.public.util.getQubits(... args,{'readoutQubit','biasQubit','driveQubit'}); if isempty(args.driveFreq) args.driveFreq = driveQubit.f01-5*driveQubit.t_spcFWHM_est:... driveQubit.t_spcFWHM_est/5:driveQubit.f01+5*driveQubit.t_spcFWHM_est; end if ~isempty(args.r_avg) %add by GM, 20170416 readoutQubit.r_avg=args.r_avg; end X = op.mwDrive4Spectrum(driveQubit); R = measure.resonatorReadout_ss(readoutQubit); R.delay = X.length; R.swapdata = true; R.name = '|IQ|'; R.datafcn = @(x)mean(abs(x)); Z = op.zBias4Spectrum(biasQubit); function proc = procFactory(amp) Z.amp = amp; proc = X.*Z; end x = expParam(@procFactory,true); x.name = [biasQubit.name,' z bias amplitude']; y = expParam(X.mw_src{1},'frequency'); y.offset = -driveQubit.spc_sbFreq; y.name = [driveQubit.name,' driving frequency (Hz)']; y.callbacks ={@(x_)x.fcnval.Run()}; s1 = sweep(x); s1.vals = args.biasAmp; s2 = sweep(y); s2.vals = args.driveFreq; e = experiment(); e.name = 'Spectroscopy'; e.sweeps = [s1,s2]; e.measurements = R; % e.plotfcn = @util.plotfcn.OneMeas_Def; % if numel(s1.vals{1})>1 && numel(s2.vals{1})>1% add by GM, 20170413 % e.plotfcn = @util.plotfcn.OneMeasComplex_2DMap_Amp_Y; % else % e.plotfcn = @util.plotfcn.OneMeasComplex_1D_Amp; % end e.datafileprefix = sprintf('[%s]_spect_zpa', readoutQubit.name); if ~args.gui e.showctrlpanel = false; e.plotdata = false; end if ~args.save e.savedata = false; end e.notes = args.notes; e.addSettings({'fcn','args'},{fcn_name,args}); e.Run(); varargout{1} = e; end
github
oiwic/QOS-master
zDelay.m
.m
QOS-master/qos/+data_taking/+public/+xmon/zDelay.m
1,973
utf_8
71a050af492f440a8d192986744c5832
function varargout = zDelay(varargin) % measures the syncronization of Z pulse % % <_o_> = zDelay('qubit',_c&o_,'zAmp',[_f_],'zLn',<_i_>,'zDelay',[_i_],... % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2017/5/10 fcn_name = 'data_taking.public.xmon.zDelay'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'zLn',[],'r_avg',[],'gui',false,'notes','','save',true}); q = data_taking.public.util.getQubits(args,{'qubit'}); if ~isempty(args.r_avg) q.r_avg=args.r_avg; end if isempty(args.zLn) args.zLn=q.g_XY_ln; end X = gate.X(q); Z = op.zBias4Spectrum(q); Z.ln = args.zLn; Z.amp = args.zAmp; padLn11 = ceil(-min(X.length/2 - Z.length/2 + min(args.zDelay),0)); padLn12 = ceil(max(max(X.length/2 + Z.length/2 + max(args.zDelay),X.length)-X.length,0)); I1 = gate.I(q); I1.ln = padLn11; I2 = copy(I1); I2.ln = padLn12; XY = I2*X*I1; I3 = copy(I1); function procFactory(delay) I3.ln = ceil(X.length/2 + padLn11 - Z.length/2 + delay); proc = XY.*(I3*Z); proc.Run(); end R = measure.resonatorReadout_ss(q); R.state = 2; R.delay = XY.length; y = expParam(@procFactory); y.name = [q.name,' z Pulse delay(da sampling points)']; s2 = sweep(y); s2.vals = {args.zDelay}; e = experiment(); e.sweeps = s2; e.measurements = R; e.name = 'Z Pulse Delay'; e.datafileprefix = sprintf('%s_zDelay', q.name); if ~args.gui e.showctrlpanel = false; e.plotdata = false; end if ~args.save e.savedata = false; end e.notes = args.notes; e.addSettings({'fcn','args'},{fcn_name,args}); e.Run(); varargout{1} = e; end
github
oiwic/QOS-master
T1_111.m
.m
QOS-master/qos/+data_taking/+public/+xmon/T1_111.m
2,409
utf_8
66b636c06d1d3dc5969f0d939dc0ba6a
function varargout = T1_111(varargin) % T1_111: T1 % bias qubit q1, drive qubit q2 and readout qubit q3, % q1, q2, q3 can be the same qubit or diferent qubits, % q1, q2, q3 all has to be the selected qubits in the current session, % % <_o_> = T1_111('biasQubit',_c&o_,'biasAmp',<[_f_]>,'biasDelay',<_i_>,... % 'backgroundWithZBias',<_b_>,... % 'driveQubit',_c&o_,'readoutQubit',_c&o_,... % 'time',[_i_],... % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2016/12/27 fcn_name = 'data_taking.public.xmon.T1_111'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'r_avg',[],'biasAmp',0,'biasDelay',0,'backgroundWithZBias',true,... 'gui',false,'notes',''}); [readoutQubit, biasQubit, driveQubit] =... data_taking.public.util.getQubits(args,{'readoutQubit', 'biasQubit', 'driveQubit'}); if ~isempty(args.r_avg) readoutQubit.r_avg=args.r_avg; end X = gate.X(driveQubit); I = gate.I(biasQubit); I.ln = args.biasDelay; Z = op.zBias4Spectrum(biasQubit); function procFactory(delay) Z.ln = delay; proc = X*I*Z; proc.Run(); R.delay = proc.length; end R = measure.rReadout4T1(readoutQubit,X.mw_src{1}); function rerunZ() piAmpBackup = X.amp; X.amp = 0; procFactory(y.val); X.amp = piAmpBackup; end if args.backgroundWithZBias R.postRunFcns = @rerunZ; end x = expParam(Z,'amp'); x.name = [biasQubit.name,' z bias amplitude']; y = expParam(@procFactory); y.name = [driveQubit.name,' decay time(da sampling interval)']; s1 = sweep(x); s1.vals = args.biasAmp; s2 = sweep(y); s2.vals = args.time; e = experiment(); e.name = 'T1'; e.sweeps = [s1,s2]; e.measurements = R; e.plotfcn = @qes.util.plotfcn.T1; e.datafileprefix = sprintf('%s%s[%s]',biasQubit.name, driveQubit.name,readoutQubit.name); if ~args.gui e.showctrlpanel = false; e.plotdata = false; end if ~args.save e.savedata = false; end e.notes = args.notes; e.addSettings({'fcn','args'},{fcn_name,args}); e.Run(); varargout{1} = e; end
github
oiwic/QOS-master
rabi_amp111.m
.m
QOS-master/qos/+data_taking/+public/+xmon/rabi_amp111.m
3,875
utf_8
83ad002e265f66ca9a58436dbb826434
function varargout = rabi_amp111(varargin) % rabi_amp111: Rabi oscillation by changing the pi pulse amplitude % bias qubit q1, drive qubit q2 and readout qubit q3, % q1, q2, q3 can be the same qubit or different qubits, % q1, q2, q3 all has to be the selected qubits in the current session, % the selelcted qubits can be listed with: % QS.loadSSettings('selected'); % QS is the qSettings object % % <_o_> = rabi_amp111('biasQubit',_c&o_,'biasAmp',<_f_>,'biasLonger',<_i_>,... % 'driveQubit',_c&o_,... % 'readoutQubit',_c&o_,... % 'xyDriveAmp',[_f_],'detuning',<[_f_]>,'driveTyp',<_c_>,... % 'dataTyp','_c_',... % S21 or P % 'numPi',<_i_>,... % number of pi rotations, default 1, use numPi > 1, e.g. 11 for pi pulse amplitude fine tuning. % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2016/12/27 fcn_name = 'data_taking.public.xmon.rabi_amp111'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'biasAmp',0,'biasLonger',0,'detuning',0,'driveTyp','X','dataTyp','P',... 'numPi',1,'r_avg',0,'gui',false,'notes','','save',true}); [readoutQubit, biasQubit, driveQubit] =... data_taking.public.util.getQubits(args,{'readoutQubit', 'biasQubit', 'driveQubit'}); if args.r_avg~=0 %add by GM, 20170414 readoutQubit.r_avg=args.r_avg; end switch args.driveTyp case 'X' g = gate.X(driveQubit); n = 1; case {'X/2','X2p'} g = gate.X2p(driveQubit); n = 2; case {'-X/2','X2m'} g = gate.X2m(driveQubit); n = 2; case {'X/4','X4p'} g = gate.X4p(driveQubit); n = 4; case {'-X/4','X4m'} g = gate.X4m(driveQubit); n = 4; case 'Y' g = gate.Y(driveQubit); n = 1; case {'Y/2', 'Y2p'} g = gate.Y2p(driveQubit); n = 2; case {'-Y/2', 'Y2m'} g = gate.Y2m(driveQubit); n = 2; case {'Y/4','Y4p'} g = gate.Y4p(driveQubit); n = 4; case {'-Y/4','Y4m'} g = gate.Y4m(driveQubit); n = 4; otherwise throw(MException('QOS_rabi_amp111:illegalDriverTyp',... sprintf('the given drive type %s is not one of the allowed drive types: X, X/2, -X/2, X/4, -X/4, Y, Y/2, -Y/2, Y/4, -Y/4',... args.driveTyp))); end I = gate.I(driveQubit); I.ln = args.biasLonger; Z = op.zBias4Spectrum(biasQubit); Z.amp = args.biasAmp; m = n*args.numPi; function procFactory(amp_) g.amp = amp_; XY = g^m; Z.ln = XY.length + 2*args.biasLonger; proc = Z.*(XY*I); R.delay = proc.length; proc.Run(); end R = measure.resonatorReadout_ss(readoutQubit); switch args.dataTyp case 'P' R.state = 2; case 'S21' R.swapdata = true; R.name = '|IQ|'; R.datafcn = @(x)mean(abs(x)); otherwise throw(MException('QOS_rabi_amp111:unsupportedDataTyp',... 'unrecognized dataTyp %s, available dataTyp options are P and S21.',... args.dataTyp)); end x = expParam(g,'f01'); x.offset = driveQubit.f01; x.name = [driveQubit.name,' detunning(f-f01, Hz)']; y = expParam(@procFactory); y.name = [driveQubit.name,' xyDriveAmp']; s1 = sweep(x); s1.vals = args.detuning; s2 = sweep(y); s2.vals = args.xyDriveAmp; e = experiment(); e.sweeps = [s1,s2]; e.measurements = R; e.name = 'rabi_amp111'; e.datafileprefix = sprintf('[%s]_rabi', readoutQubit.name); if ~args.gui e.showctrlpanel = false; e.plotdata = false; end if ~args.save e.savedata = false; end e.notes = args.notes; e.addSettings({'fcn','args'},{fcn_name,args}); e.Run(); varargout{1} = e; end
github
oiwic/QOS-master
qqRamsey.m
.m
QOS-master/qos/+data_taking/+public/+xmon/qqRamsey.m
2,408
utf_8
3c6834b41ad5c353db6da28178578291
function qqRamsey(varargin) % qqRamsey: two qubits ramsey for the calibration of the phase offset between % two qubits by simultaneously applying a 90 deg. X pulse on qubit1 and and a 90 theta % pulse on qubit2, where theta is an adjustable microwave phase angle. A plot of the % occupation probabilities versus free evolution time gives oscillations whose amplitude depends % on the phase angle theta. The oscillation amplitudes of P01 and P10 are maximized (minimized) % whenever the relative phase between the |01> and |10> states is 90(0) degrees. % When the oscillation amplitude is maximized and P10 peaks first, theta corresponds to a y-rotation % for the second qubit and serves as the calibration. % Ref.: M. Steffen, Science Vol. 313, 1423; Bialczak, Phd. thesis P97 % % bias qubit q1 or q2, drive qubit q1 or q2 and readout qubit q1 and q2, % q1, q2 all has to be the selected qubits in the current session, % % <_o_> = twoQRamsey('qubit1',_o&c_,'qubit2',_o&c_,... % 'biasAmp1',[_f_],'biasDelay1',<_i_>,... % 'biasAmp2',[_f_],'biasDelay2',<_i_>,... % 'theta',[_i_],'time',[_i_],... % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2017/3/15 fcn_name = 'data_taking.public.xmon.qqRamsey'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'biasDelay1',0,'biasDelay2',0,'gui',false,'notes',''}); [q1, q2] =... data_taking.public.util.getQubits(args,{'qubit1', 'qubit2'}); if q1==q2 throw(MException('QOS_qqRamsey:sameQubitError',... 'qubit1 and qubit2 are the same qubit.')); end X1 = gate.X2p(q1); I1 = gate.I(q1); I1.ln = args.biasDelay1; Z1 = op.zBias4Spectrum(q1); % todo: use iSwap gate X2 = gate.XY2p(q1,0); I2 = gate.I(q2); I2.ln = args.biasDelay2; Z2 = op.zBias4Spectrum(q2); % todo: use iSwap gate function procFactory(delay) Z1.ln = delay; Z2.ln = delay; proc = ((Z1*I1).*(Z2*I2))*(X1.*X2); proc.Run(); R.delay = proc.length; end R = measure.resonatorReadout({q1,q2}); error('todo...'); end
github
oiwic/QOS-master
spectroscopy111_zpa.m
.m
QOS-master/qos/+data_taking/+public/+xmon/spectroscopy111_zpa.m
2,877
utf_8
21920f76346deeaf9ad2c9362c2c76d1
function varargout = spectroscopy111_zpa(varargin) % spectroscopy111: qubit spectroscopy % bias qubit q1, drive qubit q2 and readout qubit q3, % q1, q2, q3 can be the same qubit or different qubits, % q1, q2, q3 all has to be the selected qubits in the current session, % the selelcted qubits can be listed with: % QS.loadSSettings('selected'); % QS is the qSettings object % % <_o_> = spectroscopy111_zpa('biasQubit',_c&o_,'biasAmp',<[_f_]>,... % 'driveQubit',_c&o_,'driveFreq',<[_f_]>,... % 'readoutQubit',_c&o_,'dataTyp',<_c_>,... % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2016/12/27 fcn_name = 'data_taking.public.xmon.spectroscopy111_zpa'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'dataTyp','P','r_avg',[],'biasAmp',0,'driveFreq',[],'gui',false,'notes','','save',true}); [readoutQubit, biasQubit, driveQubit] = data_taking.public.util.getQubits(... args,{'readoutQubit','biasQubit','driveQubit'}); if isempty(args.driveFreq) args.driveFreq = driveQubit.f01-3*driveQubit.t_spcFWHM_est:... driveQubit.t_spcFWHM_est/15:driveQubit.f01+3*driveQubit.t_spcFWHM_est; end if ~isempty(args.r_avg) readoutQubit.r_avg=args.r_avg; end X = op.mwDrive4Spectrum(driveQubit); R = measure.resonatorReadout_ss(readoutQubit); R.delay = X.length; switch args.dataTyp case 'P' R.state = 2; case 'S21' R.swapdata = true; R.name = '|S21|'; R.datafcn = @(x)mean(abs(x)); otherwise throw(MException('QOS_spectroscopy111_zdc',... 'unrecognized dataTyp %s, available dataTyp options are P and S21.',... args.dataTyp)); end Z = op.zBias4Spectrum(biasQubit); function proc = procFactory(amp) Z.amp = amp; proc = X.*Z; end x = expParam(@procFactory,true); x.name = [biasQubit.name,' z bias amplitude']; y = expParam(X.mw_src{1},'frequency'); y.offset = -driveQubit.spc_sbFreq; y.name = [driveQubit.name,' driving frequency (Hz)']; y.callbacks ={@(x_)x.fcnval.Run()}; s1 = sweep(x); s1.vals = args.biasAmp; s2 = sweep(y); s2.vals = args.driveFreq; e = experiment(); e.name = 'Spectroscopy'; e.sweeps = [s1,s2]; e.measurements = R; e.datafileprefix = sprintf('%s%s[%s]', biasQubit.name, driveQubit.name, readoutQubit.name); if ~args.gui e.showctrlpanel = false; e.plotdata = false; end if ~args.save e.savedata = false; end e.notes = args.notes; e.addSettings({'fcn','args'},{fcn_name,args}); e.Run(); varargout{1} = e; end
github
oiwic/QOS-master
resonatorT1.m
.m
QOS-master/qos/+data_taking/+public/+xmon/resonatorT1.m
2,217
utf_8
847a32f673eaaf013f8d7816cc05e1ff
function varargout = resonatorT1(varargin) % resonatorT1: resonator T1 % bias qubit q1, drive qubit q2 and readout qubit q3, % q1, q2, q3 can be the same qubit or diferent qubits, % q1, q2, q3 all has to be the selected qubits in the current session, % % <_o_> = resonatorT1('qubit',_c&o_,... % 'swpPiAmp',_f_,'biasDelay',biasDelay,'swpPiLn',_i_,... % 'backgroundWithZBias',b,... % 'time',[_i_],'r_avg',<_i_>,... % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2017/4/28 fcn_name = 'data_taking.public.xmon.resonatorT1'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'r_avg',[],'biasDelay',0,'backgroundWithZBias',true,... 'gui',false,'notes',''}); q = data_taking.public.util.getQubits(args,{'qubit'}); if ~isempty(args.r_avg) %add by GM, 20170416 q.r_avg=args.r_avg; end X = gate.X(q); I1 = gate.I(q); I1.ln = args.biasDelay; I2 = gate.I(q); I2.ln = X.length+args.biasDelay; Z = op.zBias4Spectrum(q); Z.amp = args.swpPiAmp; Z.ln = args.swpPiLn; function proc = procFactory(delay) I2.ln = delay; proc = X*I1*Z*I2*Z; proc.Run(); R.delay = proc.length; end R = measure.rReadout4T1(q,X.mw_src{1},false); function rerunZ() piAmpBackup = X.amp; X.amp = 0; procFactory(y.val); X.amp = piAmpBackup; end if args.backgroundWithZBias R.postRunFcns = @rerunZ; end y = expParam(@procFactory); y.name = [q.name,' decay time(da sampling interval)']; s1 = sweep(y); s1.vals = args.time; e = experiment(); e.name = 'Resonator T1'; e.sweeps = s1; e.measurements = R; e.datafileprefix = sprintf('%s',q.name); if ~args.gui e.showctrlpanel = false; e.plotdata = false; end if ~args.save e.savedata = false; end e.notes = args.notes; e.addSettings({'fcn','args'},{fcn_name,args}); e.Run(); varargout{1} = e; end
github
oiwic/QOS-master
rabi_long1.m
.m
QOS-master/qos/+data_taking/+public/+xmon/rabi_long1.m
2,288
utf_8
410a1139572d845e4bd9af561e2bdbce
function varargout = rabi_long1(varargin) % rabi_long1: Rabi oscillation by changing the pi pulse length % bias, drive and readout all one qubit % % <_o_> = rabi_long1('qubit',_c&o_,'biasAmp',[_f_],'biasLonger',<_i_>,... % 'xyDriveAmp',[_f_],'driveTyp',<_c_>,... % 'dataTyp','_c_',... % S21 or P % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2016/12/27 % GM, 2017/04/15 fcn_name = 'data_taking.public.xmon.rabi_long1'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'biasAmp',0,'biasLonger',0,'driveTyp','X','dataTyp','P',... 'r_avg',[],'gui',false,'notes','','save',true}); q = data_taking.public.util.getQubits(args,{'qubit'}); if ~isempty(args.r_avg) %add by GM, 20170414 q.r_avg=args.r_avg; end q.spc_zLonger = args.biasLonger; q.spc_sbFreq = q.f01-q.qr_xy_fc; X = op.mwDrive4Spectrum(q); X.amp = args.xyDriveAmp; Z = op.zBias4Spectrum(q); Z.amp = args.biasAmp; R = measure.resonatorReadout_ss(q); function procFactory(ln) X.ln = ln; Z.ln = ln+2*args.biasLonger; proc = X.*Z; proc.Run(); R.delay = proc.length; end switch args.dataTyp case 'P' R.state = 2; case 'S21' R.swapdata = true; R.name = '|S21|'; R.datafcn = @(x)mean(abs(x)); otherwise throw(MException('QOS_rabi_long1',... 'unrecognized dataTyp %s, available dataTyp options are P and S21.',... args.dataTyp)); end y = expParam(@procFactory); y.name = [q.name,' xy Drive Pulse Length']; s2 = sweep(y); s2.vals = args.xyDriveLength; e = experiment(); e.sweeps = s2; e.measurements = R; e.name = 'Rabi Long'; e.datafileprefix = sprintf('[%s]_rabi', q.name); if ~args.gui e.showctrlpanel = false; e.plotdata = false; end if ~args.save e.savedata = false; end e.notes = args.notes; e.addSettings({'fcn','args'},{fcn_name,args}); e.Run(); varargout{1} = e; end
github
oiwic/QOS-master
qqSwap.m
.m
QOS-master/qos/+data_taking/+public/+xmon/qqSwap.m
2,547
utf_8
14df6122e60b4583bac79a9d77a95329
function qqSwap(varargin) % twoQSwap: two qubits swap % bias qubit q1 or q2, drive qubit q1 and q2, readout qubit q1 or q2, % q1, q2 all has to be the selected qubits in the current session, % % <_o_> = qqQSwap('qubit1',_o&c_,'qubit2',_o&c_,... % 'biasQubit',<_i_>,'biasAmp',[_f_],'biasDelay',<_i_>,... % 'q1XYGate',_c_,'q2XYGate',_c_,... % 'swapTime',[_i_],'readoutQubit',<_i_>,... % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2017/7/3 fcn_name = 'data_taking.public.xmon.qqSwap'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'biasQubit',1,'readoutQubit',2,'biasDelay',0,'gui',false,'notes',''}); [q1, q2] =... data_taking.public.util.getQubits(args,{'qubit1', 'qubit2'}); if q1==q2 throw(MException('QOS_TwoQSwap:sameQubitError',... 'the source qubit and the target qubit are the same.')); end if args.readoutQubit==1 readoutQ = q1; else readoutQ = q2; end if args.biasQubit==1 biasQ = q1; else biasQ = q2; end G1 = feval(str2func(['@(q)sqc.op.physical.gate.',args.q1XYGate,'(q)']),q1); G2 = feval(str2func(['@(q)sqc.op.physical.gate.',args.q2XYGate,'(q)']),q2); I1 = gate.I(biasQ); I1.ln = args.biasDelay; Is = gate.I(q1); Is.ln = G1.length+10; Z = op.zBias4Spectrum(biasQ); % todo: use iSwap gate R = measure.resonatorReadout_ss(readoutQ); R.state = 2; zAmp = qes.util.hvar(0); function procFactory(swapTime) Z.ln = swapTime; Z.amp = zAmp.val; % G1.amp = 5000; proc = (G1.*G2)*I1*Z; % proc = (G2.*Is)*G1*I1*Z; R.delay = proc.length; proc.Run(); end x = expParam(zAmp,'val'); x.name = [biasQ.name,' zpa']; y = expParam(@procFactory); y.name = [q1.name,', ',q2.name,' swap time']; s1 = sweep(x); s1.vals = args.biasAmp; s2 = sweep(y); s2.vals = args.swapTime; e = experiment(); e.name = 'Q-Q swap'; e.sweeps = [s1,s2]; e.measurements = R; e.datafileprefix = sprintf('%s,%s', q1.name, q2.name); if ~args.gui e.showctrlpanel = false; e.plotdata = false; end if ~args.save e.savedata = false; end e.notes = args.notes; e.addSettings({'fcn','args'},{fcn_name,args}); e.Run(); varargout{1} = e; end
github
oiwic/QOS-master
T1_1_s21.m
.m
QOS-master/qos/+data_taking/+public/+xmon/T1_1_s21.m
1,972
utf_8
3be240682b75c624b34889b7393e9367
function varargout = T1_1_s21(varargin) % T1_1_s21: T1 % bias qubit q1, drive qubit q2 and readout qubit q3, % q1, q2, q3 can be the same qubit or diferent qubits, % q1, q2, q3 all has to be the selected qubits in the current session, % % <_o_> = T1_111('qubit',_c&o_,'biasAmp',<[_f_]>,... % 'time',[_i_],'r_avg',<_i_>,... % 'notes',<_c_>,'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as they form correct pairs. % Yulin Wu, 2016/12/27 fcn_name = 'data_taking.public.xmon.T1_1_s21'; % this and args will be saved with data import qes.* import sqc.* import sqc.op.physical.* args = util.processArgs(varargin,{'r_avg',[],'biasAmp',0,'gui',false,'notes',''}); q = data_taking.public.util.getQubits(args,{'qubit'}); if ~isempty(args.r_avg) %add by GM, 20170416 q.r_avg=args.r_avg; end X = gate.X(driveQubit); I = gate.I(biasQubit); I.ln = args.biasDelay; Z = op.zBias4Spectrum(biasQubit); function procFactory(delay) Z.ln = delay; proc = X*I*Z; proc.Run(); R.delay = proc.length; end R = measure.resonatorReadout_ss(q); R.swapdata = true; R.name = '|IQ|'; R.datafcn = @(x)mean(abs(x)); x = expParam(Z,'amp'); x.name = [q.name,' z bias amplitude']; y = expParam(@procFactory); y.name = [q.name,' decay time(da sampling interval)']; s1 = sweep(x); s1.vals = args.biasAmp; s2 = sweep(y); s2.vals = args.time; e = experiment(); e.name = 'T1'; e.sweeps = [s1,s2]; e.measurements = R; e.datafileprefix = sprintf('%s',q.name); if ~args.gui e.showctrlpanel = false; e.plotdata = false; end if ~args.save e.savedata = false; end e.notes = args.notes; e.addSettings({'fcn','args'},{fcn_name,args}); e.Run(); varargout{1} = e; end
github
oiwic/QOS-master
xyGateAmpTuner.m
.m
QOS-master/qos/+data_taking/+public/+xmon/+tuneup/xyGateAmpTuner.m
9,767
utf_8
90704a2d52efa716cc821c7cba76299d
function varargout = xyGateAmpTuner(varargin) % tune xy gate amplitude: X, X/2, -X/2, X/4, -X/4, Y, Y/2, -Y/2, Y/4, -Y/4 % % <_f_> = xyGateAmpTuner('qubit',_c&o_,'gateTyp',_c_,... % 'AE',<_b_>,'AENumPi',<_i_>,... % insert multiple Idle gate(implemented by two pi rotations) to Amplify Error or not % 'gui',<_b_>,'save',<_b_>) % _f_: float % _i_: integer % _c_: char or char string % _b_: boolean % _o_: object % a&b: default type is a, but type b is also acceptable % []: can be an array, scalar also acceptable % {}: must be a cell array % <>: optional, for input arguments, assume the default value if not specified % arguments order not important as long as the form correct pairs. % Yulin Wu, 2017/1/8 import data_taking.public.xmon.rabi_amp1 NUM_RABI_SAMPLING_PTS = 30; MIN_VISIBILITY = 0.3; AE_NUM_PI = 11; % must be an positive odd number args = qes.util.processArgs(varargin,{'AE',false,'AENumPi',AE_NUM_PI,'gui',false,'save',true}); args.AENumPi = round(args.AENumPi); q = data_taking.public.util.getQubits(args,{'qubit'}); F = q.r_iq2prob_fidelity; vis = F(1)+F(2)-1; if vis < 0.2 throw(MException('QOS_xyGateAmpTuner:visibilityTooLow',... sprintf('visibility(%0.2f) too low, run xyGateAmpTuner at low visibility might produce wrong result, thus not supported.', vis))); end q.r_iq2prob_intrinsic = true; da = qes.qHandle.FindByClassProp('qes.hwdriver.hardware',... 'name', q.channels.xy_i.instru); switch args.gateTyp case {'X','Y'} % maxAmp = da.vpp/2; case {'X/2','-X/2','X2m','X2p','Y/2','-Y/2','Y2m','Y2p'} % maxAmp = da.vpp/4; case {'X/4','-X/4','X4m','X4p','Y/4','-Y/4','Y4m','Y4p'} % maxAmp = da.vpp/8; otherwise throw(MException('QOS_xyGateAmpTuner:unsupportedGataType',... sprintf('gate %s is not supported, supported types are %s',args.gateTyp,... 'X Y X/2 -X/2 X2m X2p X/4 -X/4 X4m X4p Y/2 -Y/2 Y2m Y2p Y/4 -Y/4 Y4m Y4p'))); end QS = qes.qSettings.GetInstance(); switch args.gateTyp case {'X','Y'} gateAmpSettingsKey ='g_XY_amp'; case {'X/2','X2p','-X/2','X2m','Y/2','Y2p','-Y/2','Y2m'} gateAmpSettingsKey ='g_XY2_amp'; case {'X/4','X4p','-X/4','X4m','Y/4','Y4p','-Y/4','Y4m'} gateAmpSettingsKey ='g_XY4_amp'; otherwise throw(MException('QOS_xyGateAmpTuner:unsupportedGataType',... sprintf('gate %s is not supported, supported types are %s',args.gateTyp,... 'X Y X/2 -X/2 X2m X2p X/4 -X/4 X4m X4p Y/2 -Y/2 Y2m Y2p Y/4 -Y/4 Y4m Y4p'))); end currentGateAmp = QS.loadSSettings({q.name,gateAmpSettingsKey}); if isempty(currentGateAmp) amps = linspace(0,(1-da.dynamicReserve{1})*da.vpp/2,NUM_RABI_SAMPLING_PTS*2); else amps = linspace(0.5*currentGateAmp,min(1.5*currentGateAmp,(1-da.dynamicReserve{1})*da.vpp/2),NUM_RABI_SAMPLING_PTS); end e = rabi_amp1('qubit',q,'biasAmp',0,'biasLonger',0,'xyDriveAmp',amps,... 'detuning',0,'driveTyp',args.gateTyp,'gui',false,'save',false); P = e.data{1}; rP = range(P); P0 = min(P); P1 = max(P); if rP < MIN_VISIBILITY throw(MException('QOS_xyGateAmpTuner:visibilityTooLow',... sprintf('visibility(%0.2f) too low, run xyGateAmpTuner at low visibility might produce wrong result, thus not supported.', rP))); elseif rP < 5/sqrt(q.r_avg) throw(MException('QOS_xyGateAmpTuner:rAvgTooLow',... 'readout average number %d too small.', q.r_avg)); end gateAmp = findsPkLoc(amps,P); % [pks,locs,~,~] = findpeaks(P,'MinPeakHeight',2*rP/3,... % 'MinPeakProminence',rP/2,'MinPeakDistance',numel(P)/4,... % 'WidthReference','halfprom'); % if ~isempty(pks) % [locs,idx] = sort(locs,'ascend'); % pks = pks(idx); % % maxIdx = locs(1); % if numel(pks) > 3 % throw(MException('QOS_xyGateAmpTuner:tooManyOscCycles',... % 'too many oscillation cycles or data SNR too low.')); % end % dP = pks(1)-P; % else % [mP,maxIdx] = max(P); % dP = mP-P; % end % % % idx1 = find(dP(maxIdx:-1:1)>rP/4,1,'first'); % if isempty(idx1) % idx1 = 1; % else % idx1 = maxIdx-idx1+1; % end % % idx2 = find(dP(maxIdx:end)>rP/4,1,'first'); % if isempty(idx2) % idx2 = NUM_RABI_SAMPLING_PTS; % else % idx2 = maxIdx+idx2-1; % end % % [~, gateAmp, ~, ~] = toolbox.data_tool.fitting.gaussianFit.gaussianFit(... % % amps(idx1:idx2),P(idx1:idx2),maxP,amps(maxIdx),amps(idx2)-amp(idx1)); % % % gateAmp = roots(polyder(polyfit(amps(idx1:idx2),P(idx1:idx2),2))); % warning('off'); % p = polyfit(amps(idx1:idx2),P(idx1:idx2),2); % warning('on'); % if mean(abs(polyval(p,amps(idx1:idx2))-P(idx1:idx2))) > range(P(idx1:idx2))/4 % throw(MException('QOS_xyGateAmpTuner:fittingFailed','fitting error too large.')); % end % gateAmp = roots(polyder(p)); % % if gateAmp < amps(idx1) || gateAmp > amps(idx2) % throw(MException('QOS_xyGateAmpTuner:xyGateAmpTuner',... % 'gate amplitude probably out of range.')); % end if args.AE % use multiple pi gates to amplify error to fine tune gateAmp % ~0.5% precision if args.AENumPi <= 11 amps_ae = linspace(0.9*gateAmp,min(da.vpp,1.1*gateAmp),NUM_RABI_SAMPLING_PTS*2); else amps_ae = linspace(0.95*gateAmp,min(da.vpp,1.05*gateAmp),NUM_RABI_SAMPLING_PTS*3); end % switch args.gateTyp % case {'X','Y'} % if args.AENumPi <= 11 % amps_ae = linspace(0.9*gateAmp,min(da.vpp,1.1*gateAmp),NUM_RABI_SAMPLING_PTS*2); % else % amps_ae = linspace(0.95*gateAmp,min(da.vpp,1.05*gateAmp),NUM_RABI_SAMPLING_PTS*3); % end % case {'X/2','-X/2','X2m','X2p','Y/2','-Y/2','Y2m','Y2p'... % 'X/4','-X/4','X4m','X4p','Y/4','-Y/4','Y4m','Y4p'} % if args.AENumPi <= 11 % amps_ae = linspace(0.85*gateAmp,min(da.vpp,1.15*gateAmp),NUM_RABI_SAMPLING_PTS*2); % else % amps_ae = linspace(0.9*gateAmp,min(da.vpp,1.1*gateAmp),NUM_RABI_SAMPLING_PTS*3); % end % end e = rabi_amp1('qubit',q,'biasAmp',0,'biasLonger',0,'xyDriveAmp',amps_ae,... 'detuning',0,'numPi',args.AENumPi,'driveTyp',args.gateTyp,'gui',false,'save',false); P_ae = e.data{1}; if max(P_ae) < P0 + MIN_VISIBILITY warning('QOS_xyGateAmpTuner:visibilityTooLow',... 'AE visibility too low, AE result not used.'); else % P_aeS = smooth(P_ae,5); % rP = range(P_aeS); % [pks,locs,~,~] = findpeaks(P_aeS,'MinPeakHeight',2*rP/3,... % 'MinPeakProminence',rP/2,'MinPeakDistance',numel(P_aeS)/4,... % 'WidthReference','halfprom'); try gateAmp_f = findsPkLoc(amps_ae,P_ae); catch gateAmp_f = []; end if ~isempty(gateAmp_f) gateAmp = gateAmp_f; else args.AE = false; end end end if args.gui h = qes.ui.qosFigure(sprintf('XY Gate Tuner | %s: %s', q.name, args.gateTyp),true); ax = axes('parent',h); plot(ax,amps,P,'-b'); hold(ax,'on'); if args.AE plot(ax,amps_ae,P_ae); end % ylim = get(ax,'YLim'); ylim = [0,1]; plot(ax,[gateAmp,gateAmp],ylim,'--r'); xlabel(ax,'xy drive amplitude'); ylabel(ax,'P|1>'); if args.AE legend(ax,{'data(1\pi)',... [sprintf('data(AE:%0.0f',args.AENumPi),'\pi)'],... sprintf('%s gate amplitude',args.gateTyp)}); title('Precision: ~0.5%'); else legend(ax,{'data(1\pi)',sprintf('%s gate amplitude',args.gateTyp)}); title('Precision: ~2%'); end set(ax,'YLim',ylim); drawnow; end if ischar(args.save) args.save = false; choice = questdlg('Update settings?','Save options',... 'Yes','No','No'); if ~isempty(choice) && strcmp(choice, 'Yes') args.save = true; end end if args.save QS.saveSSettings({q.name,gateAmpSettingsKey},gateAmp); end varargout{1} = gateAmp; end function xp = findsPkLoc(x,y) rng = range(y); [pks,locs,~,~] = findpeaks(y,'MinPeakHeight',2*rng/3,... 'MinPeakProminence',rng/2,'MinPeakDistance',numel(x)/4,... 'WidthReference','halfprom'); if ~isempty(pks) [locs,idx] = sort(locs,'ascend'); pks = pks(idx); maxIdx = locs(1); if numel(pks) > 3 throw(MException('QOS_xyGateAmpTuner:tooManyOscCycles',... 'too many oscillation cycles or data SNR too low.')); end dy = pks(1)-y; else [mP,maxIdx] = max(y); dy = mP-y; end idx1 = find(dy(maxIdx:-1:1)>rng/3,1,'first'); if isempty(idx1) idx1 = 1; else idx1 = maxIdx-idx1+1; end idx2 = find(dy(maxIdx:end)>rng/4,1,'first'); if isempty(idx2) idx2 = numel(x); else idx2 = maxIdx+idx2-1; end % [~, gateAmp, ~, ~] = toolbox.data_tool.fitting.gaussianFit.gaussianFit(... % amps(idx1:idx2),P(idx1:idx2),maxP,amps(maxIdx),amps(idx2)-amp(idx1)); % gateAmp = roots(polyder(polyfit(amps(idx1:idx2),P(idx1:idx2),2))); warning('off'); p = polyfit(x(idx1:idx2),y(idx1:idx2),2); warning('on'); if mean(abs(polyval(p,x(idx1:idx2))-y(idx1:idx2))) > range(y(idx1:idx2))/4 throw(MException('QOS_xyGateAmpTuner:fittingFailed','fitting error too large.')); end xp = roots(polyder(p)); if xp < x(idx1) || xp > x(idx2) throw(MException('QOS_xyGateAmpTuner:xyGateAmpTuner',... 'gate amplitude probably out of range.')); end end
github
oiwic/QOS-master
FlxQbtSpcFit.m
.m
QOS-master/qos/+toolbox/+data_tool/FlxQbtSpcFit.m
2,757
utf_8
d8f10cf0592d56e5652cd8cb69437a6f
function FlxQbtSpcFit() % fit flux qubit spectrum by openning the spectrum figure file % how to use: % just run this funcion. % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] persistent lastselecteddir if isempty(lastselecteddir) || ~exist(lastselecteddir,'dir') Datafile = fullfile(pwd,'*.fig'); else Datafile = fullfile(lastselecteddir,'*.fig'); end [FileName,PathName,~] = uigetfile(Datafile,'Select the flux qubit spectrum figure(*.fig) file to fit:'); if ischar(PathName) && isdir(PathName) lastselecteddir = PathName; end figfile = fullfile(PathName,FileName); if ~exist(figfile,'file') return; end open(figfile); title('Adjust the figure window for good eye sight if needed.'); pause(4); title(['Left click to select data points then press Enter.',char(10),... 'Fitting coefficients will be displayed in command window.']); [x,y] = ginput; [x, idx] = sort(x); y = y(idx); if length(x)<3 || x(1)+x(end) == 0 error('Pick at least three data points!'); else Coefficients(1) = (x(1)+x(end))/2; Coefficients(2) = min(y); % Coefficients(3) = abs(2*max(y)/(x(1)-x(end))); Coefficients(3) = abs(2*(max(y) - Coefficients(2))/(x(1)-x(end))); for ii = 1:5 Coefficients = lsqcurvefit(@FlxQbtSpc,Coefficients,x,y); end x0 = Coefficients(1); Delta = Coefficients(2); k = Coefficients(3); title(['Fit coefficients are displayed in command window.']); home; disp('Formula: y = sqrt((k*(x-x0)).^2 + Delta^2)'); disp(['Center position x0 = ', num2str(x0,'%0.6f')]); disp(['Energy gap Delta = ', num2str(Delta,'%0.6f')]); disp(['k = ', num2str(k,'%0.6f')]); b = 6.626068e-34*k/2.067833636e-15*1e9/2*1e9; disp(['Ip = ', num2str(b,'%0.6f'), '*T*b (nA), where T and b are unitless, x/T is the qubit flux bias(Phi0), b*y is the microwave frequency(GHz),']); disp(['e.g., if the unit of y axis is Hz, b = 1e-9, if the unit of y axis is GHz, b = 1.']); xi = linspace(min(x),max(x),2000); yi = FlxQbtSpc(Coefficients,xi); hold(gca,'on'); xlimit = get(gca,'XLim'); ylimit = get(gca,'YLim'); set(gcf,'Color',[1,1,1]); plot(x,y,'xb',xi,yi,'-b'); set(gca,'XLim',xlimit); set(gca,'YLim',ylimit); set(gcf,'Color',[1,1,1]); end end function [y]=FlxQbtSpc(Coefficients,x) % y = sqrt((k(x-x0)).^2+Delta^2); x0 = Coefficients(1); Delta = Coefficients(2); k = Coefficients(3); y = sqrt((k*(x-x0)).^2+Delta^2); end
github
oiwic/QOS-master
FitQ.m
.m
QOS-master/qos/+toolbox/+data_tool/ExtractQ/FitQ.m
1,714
utf_8
5fcdc9ffed99161b2ef7bf7ffe19a4af
function [Qi,Qc,varargout] = FitQ(df,invs21,plotfilt) % fit internal quality factors(Qi) and coupling quality factors(Qc) of % a resonator from its normalized transmission invs21 = 1/S21. % df = (f-f0)/f0 is the normalized frequency, f0 is the resonance % frequency. % plotfilt: true/false, optional, plot data or not. % based on Applied Physics Letters 100(11):113510. % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] Coefficients(1) = 2; Coefficients(2) = 100; for ii = 1:5 [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@InvS21,Coefficients,df,invs21); end Qi = Coefficients(2)/(1i*2); Qc = abs(Qi/Coefficients(1)); if nargout > 4 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end %% plot if nargin == 2 || ~plotfilt return; end figure(); plot(real(invs21),imag(invs21),'ob','LineWidth',2); hold on; invs21f = InvS21(Coefficients,df); plot(real(invs21f),imag(invs21f),'-r','LineWidth',2); pbaspect([1 1 1]); xlabel('Re[S_{21}^{-1}]'); ylabel('Im[S_{21}^{-1}]'); legend({'data','fit'}); figure(); plot(df,mag2db(abs(1./invs21)),'ob','LineWidth',2); hold on; plot(df,mag2db(1./invs21f),'-r','LineWidth',2); xlabel('(f - f_0)/f0'); ylabel('S_{21} Amplitude (dB)'); legend({'data','fit'}); figure(); plot(df,angle(1./invs21),'ob','LineWidth',2); hold on; plot(df,angle(1./invs21f),'-r','LineWidth',2); xlabel('(f - f_0)/f0'); ylabel('S_{21} Phase'); legend({'data','fit'}); end function IS = InvS21(Coefficients,x) a = Coefficients(1); b = Coefficients(2); IS = 1+a./(1+b*x); end
github
oiwic/QOS-master
SXPParse.m
.m
QOS-master/qos/+toolbox/+data_tool/ExtractQ/SXPParse.m
13,880
utf_8
4ec2f38203a1b9371c05371bc2e82f3b
function [freq, data, freq_noise, data_noise, Zo] = SXPParse(DataFileName, fid_log) % reads .sxp file data in MDIF (a.k.a. Touchstone / HPEEsof format) % % EXAMPLE : % [freq, data, freq_noise, data_noise, Zo] = SXPParse(DataFileName, fid_log); % % freq, freq_noise - 1xF arrays % data - PxPxF matrix, P- number of ports, F- number of freq points % data_noise - Fn x 3 matrix, complex, Fn is size(freq_noise), columns are : % 1. NFmin <dB>, 2. Gamma_opt<complex), 3. Rn <normalized> % (in order to use NFmin and Rn you have to take the real part) % Zo - impedance used in normalization of data % % type SXPParse('info') for info on MDIF/Touchstone/HPEESof file format % % written by Tudor Dima, last rev. 29.05.2012, tudima at zahoo dot com % (change the z into y...) % ver 1.42: 2012.05.29, close the parsed file, thanks Julien Hillairet % ver 1.41: 2009.09.05, more separators, Phrase2Word out as cell, include as subfunc % ver 1.4 : 2008.10.25, fix nPort>4 (when lines get split) % allow comments on lines % better parsing, subfunctions introduced % limited protection for non-standard files % ver 1.33: 26.01.2008, small bug fixed (again!) in 'db' conversion % better help, info on MDIF standard % ver 1.32: 08.03.2006, handle comment lines anywhere inside body % ver 1.31: 15.12.2005, switch by type (S,Y,Z); % ver 1.3 : 13.03.2003, rescris tot, read line by line, Y,Z, not yet % ver 1.21: 24.04.2002, max. nr of ports increased from 9 to 99 % ver 1.2 : 04.03.1999, added noise reading (4martie99) % ver 1.1 : 26.02.1999, data in complex format(26feb99) if strcmp(DataFileName, 'info') || strcmp(DataFileName, 'help') || strcmp(DataFileName, '?') dispHelp % show extended help return end %------- read from file DataFileName ------- format compact; if nargin<2 fid_log = 1; % no log ? to screen (to check fid_log before passing it...) end fid = fopen(DataFileName, 'rt'); if fid < 1 fprintf(fid_log, '%s \n %s', ' ... exiting...', ... ['Error : requested parameter file ' DataFileName ' not found ! ']); return end % --- start parsing --- fprintf(fid_log, '\n %s \n %s', 'reading parameter data from file ', [ DataFileName ' ...']); % --- find out matrix order --- fnl = size(DataFileName,2); NoOfPorts = str2double(DataFileName(fnl-1) ); candidate_zeci = str2double(DataFileName(fnl-2) ); if ~isempty(candidate_zeci) && ~isnan(candidate_zeci) % some early matlab versions return empty for str2double(non-numbers) NoOfPorts = NoOfPorts + 10*candidate_zeci; end % works up to 99 ports, should be ok ... :-) % --- init default options --- opt.multiplier = 1e6; opt.param = 's'; opt.format = 'ma'; opt.Zo = 50; % -> use MA in noise line, irespective of specifier in #-line opt.Touchstone = 'old'; % to change this uncomment next line % opt.Touchstone = 'new'; % - initialise defaults, in case file is corrupted freq = []; data = []; Zo = 0; data_noise = []; freq_noise = []; % - init parsing flags flagDataStarted = 0; % assuming spec.line first ! flagNoiseStarted = 0; flagGotOptions = 0; FreqPoint = 0; LastFrequency = 0; thisFreqTerms = 2*NoOfPorts.^2; % like you have just finished a line % --- incepe si citeste linie cu linie --- phrase = lower(fgets(fid)); while ~flagDataStarted % get options line if ~isempty(phrase) if strcmp(phrase(1),'#') % read specifier line word = opPhrase2Word(deblank(phrase(2:end))); opt = opFigureOptions(word, opt); flagGotOptions = 1; flagDataStarted = 1; end end phrase = fgets(fid); if ~ischar(phrase), break; end; phrase = lower(phrase); end % --- read data, one frequency at a time --- while ~flagNoiseStarted && flagGotOptions word = opPhrase2Word(phrase, {}, {','}); data_row = str2double(word); % sweet ! cell 2 double array ! if ~isempty(word) % && ~strcmp(word(1,1),'!') % read freq data; assume that new_freq is always on new line ! if thisFreqTerms == 2*NoOfPorts.^2 % got all current freq data, increment FreqPoint if data_row(1) < LastFrequency % flagNoiseStarted = 1; % noise data detected ! FreqPoint = 0; break end FreqPoint = FreqPoint+1; freq(FreqPoint) = data_row(1); thisFreqTerms = 0; LastFrequency = freq(FreqPoint); data_row = data_row(2:end); % remove frequency end; % append data raw_data(FreqPoint,thisFreqTerms+1:thisFreqTerms+size(data_row,2)) = data_row; thisFreqTerms = thisFreqTerms + size(data_row,2); end phrase = fgets(fid); if ~ischar(phrase), break; end; phrase = lower(phrase); end % finished reading S-data while flagGotOptions && flagNoiseStarted % --- start reading noise data --- % store all, including freq FreqPoint = FreqPoint+1; raw_data_noise(FreqPoint,(1:size(data_row,2))) = data_row; phrase = fgets(fid); if ~ischar(phrase), break; end; phrase = deblank(lower(phrase)); word = opPhrase2Word(phrase); data_row = str2double(word); % store next round end % while phrase contine ceva if ~flagGotOptions fprintf('\n%s', ' > SPXParse : no options line found in file') fprintf('\n%s\n', ' did not assign any return values !'); return end % --- now we have all the raw data --- freq = freq * opt.multiplier; % will arrange(slice) it as needed Zo = opt.Zo; % function of format(s/z/y/a/g/h) data = opAdjFreqData(raw_data, NoOfPorts, opt);% f(NoOfPorts), if flagNoiseStarted % --- arrange noise data %freq_noise = freq_noise * opt.multiplier; [freq_noise, data_noise] = opAdjNoizData(raw_data_noise, opt); end; fprintf(fid_log, '\n%s\n', '... done.'); % don't forget to close the file :-) fclose(fid); end function word = opPhrase2Word(phrase, comment_list, separator_list) % WORD = opPhrase2Word(PHRASE, separator_list, comment_list); % % gets one raw ASCII line, turns it into a word cell array % uses default chars + separator_list to separe, ingnores all after comment signs % 09.05.2003 - ver 0.0 : , noua (pt ParseSXP in printzip) % 30.07.2009 - ver. 1.41, included in ParseSXP, cell output ! % hunt comment lines here if nargin < 2, comment_list = {'!'}; end; if isempty(comment_list), comment_list = {'!'}; end if nargin < 3, separator_list = {}; end; % just standard ones : % space, newline, CR, tab, vert. tab, or formfeed characters. % > inspect phrase, discard commented part, if any phrase = deblank(phrase); for iC = 1:size(comment_list,2) tCheckCommentChar = phrase == comment_list{iC}; if any(tCheckCommentChar) % shorten the phrase upto the comment sign ixComm = find(tCheckCommentChar); phrase = phrase(1:ixComm(1)-1); end end % > split phrase into words using separator_list PhraseLength = size(phrase,2); if PhraseLength % bother looking inside allSeparatorChars = isspace(phrase); % false(1, PhraseLength); % in case more characters are used as separators > for iS = 1:size(separator_list,2) theseSeparatorChars = phrase == separator_list{iS}; allSeparatorChars = allSeparatorChars | theseSeparatorChars; end % trim extra separators LookForGluedSeparators = true; while LookForGluedSeparators % hunt adjacent 1-s FoundGluedSeparators = [ allSeparatorChars(1:end-1) &... allSeparatorChars(2:end) false]; % not to miss last char if ~all(~FoundGluedSeparators) % eliminate duplicated (adjacent) 1-s phrase = phrase(~FoundGluedSeparators); allSeparatorChars = allSeparatorChars(~FoundGluedSeparators); else % stop looking LookForGluedSeparators = false; end end if allSeparatorChars(1) % catch one leading separator ! ixWStart = find(allSeparatorChars)+1; nWords = sum(allSeparatorChars); else % normal ixWStart = [1 find(allSeparatorChars)+1]; nWords = sum(allSeparatorChars)+ 1 ; end % last word first :-) also serves as prealloc word{nWords} = phrase(ixWStart(nWords):end); for iW=1:nWords-1 word{iW} = phrase(ixWStart(iW):ixWStart(iW+1)-2); end % another catch in case extra separators removing is buggy ?... later :-) % eliminate empty words else word = {}; end end % ----------------------------------------------------- function data = opAdjFreqData(raw_data, NoOfPorts, opt) % ----------------------------------------------------- % intii exceptia 2-port : if NoOfPorts == 1 raw_data_A(1,1,:) = raw_data(:,1); raw_data_B(1,1,:) = raw_data(:,2); elseif NoOfPorts == 2 raw_data_A(1,1,:) = raw_data(:,1); raw_data_B(1,1,:) = raw_data(:,2); raw_data_A(2,1,:) = raw_data(:,3); raw_data_B(2,1,:) = raw_data(:,4); raw_data_A(1,2,:) = raw_data(:,5); raw_data_B(1,2,:) = raw_data(:,6); raw_data_A(2,2,:) = raw_data(:,7); raw_data_B(2,2,:) = raw_data(:,8); else % --- cut nFreq square slices of size NoOfPorts nFreq = size(raw_data,1); tAB = zeros(NoOfPorts,2*NoOfPorts,nFreq); for i=1:nFreq tAB(:,:,i) = reshape(raw_data(i,:)',2*NoOfPorts, NoOfPorts)'; end; raw_data_A = tAB(:,1:2:end-1,:); raw_data_B = tAB(:,2:2:end,:); clear tAB end % using dual-field numbers will calculate complex numbers, f(format_specifier) j=sqrt(-1); switch opt.format case 'ri' data = raw_data_A + j*raw_data_B; case 'ma' data = raw_data_A .* cos(raw_data_B*pi/180) + j* raw_data_A .* sin(raw_data_B*pi/180); case 'db' t_mag = 10.^(raw_data_A/20); t_ang = raw_data_B*pi/180; data = t_mag .* cos(t_ang) + j* t_mag .* sin(t_ang); end % now adjust data f(opt.param) Z,Y,G,H,A switch opt.param case 'y' data = y2s(data*opt.Zo); % to check in standard if Zo always or Yo case 'z' data = z2s(data/opt.Zo); case 'a' data = a2s(data); % to double check units... case 'g' data = g2s(data); % ... case 'h' data = h2s(data); % ... end end % function ! % ----------------------------------------------------- function [freq_noise, data_noise] = opAdjNoizData(raw_data_noise, opt) % one line is f NFmin Gopt-Mag Gopt-Ang Rn freq_noise = raw_data_noise(:,1) *opt.multiplier; % freq data_noise(:,1) = raw_data_noise(:,2); % NFmin data_noise(:,3) = raw_data_noise(:,5); % Rn % find GammaOpt Tm = raw_data_noise(:,3); Ta = raw_data_noise(:,4); switch opt.Touchstone case 'old' % is MA anyways, old style Touchstone Ta = Ta*pi/180; data_noise(:,2) = Tm .*cos(Ta) + j* Tm .*sin(Ta); case 'new' switch opt.format % gamma opt case 'ri' data_noise(:,2) = Tm + j*Ta; case 'ma' Ta = Ta*pi/180; data_noise(:,2) = Tm .*cos(Ta) + j* Tm .*sin(Ta); case 'db' Tm = 10.^(Tm(:,2)/20); Ta = Ta*pi/180; data_noise(:,2) = Tm .*cos(Ta) + j* Tm .*sin(Ta); end end end function opt = opFigureOptions(word, opt) % ---> crude, fara protexe yet for i = 1:size(word,2) thisWord = deblank(word{i}); switch thisWord case {'mhz'} opt.multiplier = 1e6; case 'ghz' opt.multiplier = 1e9; case 'khz' opt.multiplier = 1e3; case 'hz' opt.multiplier = 1; case {'s','z','y','g','h','abcd'} opt.param = thisWord; case {'ri','ma','db'} opt.format = thisWord; case 'r' opt.Zo = str2double(deblank(word{i+1})); end end end function dispHelp word = strvcat(... ' ',... 'format of MDIF/Touchstone/HPEESof files :',... ' comment line starts with ''!''',... ' specifier line is :',... ' # <freq_unit> <param> <format> R <reference resistance value>',... '',... 'examples :',... ' -- S-par, real and imaginary -->',... ' # GHz S RI R 50 ',... ' -- Z-par, linear mag and angle <deg> --> ',... ' # MHz Z MA R 75 ',... ' -- Y-par, log mag (dB) and angle <deg> --> ',... ' # kHz Y DB R 50 ',... ' -- ABCD-par, real and imaginary --> ',... ' # Hz ABCD RI R 50 ',... '',... ' (defaults : # MHz S MA R 50)',... '',... ' -------------------------------------------------',... ' format of data in file (*.s2p) is :',... ' f s11.1 s11.2 s21.1 s21.2 s12.1 s12.2 s22.1 s22.2',... ' -------------------------------------------------',... '',... ' format of data in file (*.sxp) with x>2 is :',... ' -------------------------------------------------',... ' f s11.1 s11.2 s12.1 s12.2 ... s1x.1 s1x.2',... ' s21.1 s21.2 s22.2 s22.2 ... s2x.1 s2x.2',... ' ...',... ' sx1.1 sx1.2 sx2.1 sx2.2 ... sxx.1 sxx.2',... ' -------------------------------------------------',... '',... 'noise data has some HP/Touchstone legacy stuff : ', ... ' - noise data will start when the frequency decreases for the',... ' first time; otherwise frecuency is monotonically increasing ',... ' - Gopt is always MA, irrespective of S data format above (to change this uncomment line 98)',... ' - NFmin is always in <dB>, Rn is normalized', ... 'ex.:',... '! freq NFmin Gopt-Mag Gopt-Ang Rn(norm!)',... ' 900 1.8 0.34 135 0.2 '); disp(word); end
github
oiwic/QOS-master
sinDecayFit_auto.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/sinDecayFit_auto.m
5,619
utf_8
03f8f2cc253692f1ae4087520e90d98b
function [A,B,C,D,freq,td,varargout] = sinDecayFit_auto(t,P,varargin) % SinDecayFit fits curve P = P(t) with a Sinusoidal Decay function: % P = A +B*(exp(-t/td)*(sin(2*pi*freq*t+D)+C)); % t unit should be nano-second. % Original data length should not less than 20 (length(t)>20) % % A function call returns the following fitting Coefficients: % A,B,C,D,freq,td OR 'error message'. % optional output: 95% confidence interval of Coefficients % % varargin{1}: MINIMUM oscillation circles P has (LeastOscN). If not specifid, % the programme sets it to 6. % Note: the bigger the value of 'LeastOscN', the less likely for the fitting % to fail, but make sure it dose not exceed the REAL oscillation circles P % has, for example: % If you can clearly see that there is more than 30 oscillation circles and % the exact oscillation circle number is less than 150: % [A,B,C,D,freq,td] = SinDecayFit(t,P); % Default, alright for most cases % [A,B,C,D,freq,td] = SinDecayFit(t,P,2); % very likely to fail % [A,B,C,D,freq,td] = SinDecayFit(t,P,30); % most likey to be successful % [A,B,C,D,freq,td] = SinDecayFit(t,P,160); % may fail % % varargin{2}, initial value of oscillation frequency, if auto fitting % failed, specify this value(as close to the real oscillation frequency % value as possible). In this case, value of varargin{1} will not % be used, given any value will be alright % % varargin{3}, initial value of decay time, if fitting still fail when % initial value of oscillation frequency is given, specify this value( % as close to the real decay time value as possible). % % varargin{4}, initial value A % varargin{5}, initial value B % varargin{6}, initial value C % varargin{7}, initial value D % % varargout{1}: ci, 6 by 2 matrix, ci(5,1) is the lower bound of 'freq', % ci(6,2) is the upper bound of 'td',... % % Yulin Wu, SC5,IoP,CAS. [email protected] % $Revision: 1.1 $ $Date: 2012/10/18 $ L = length(t); if L > 15 % data dense enoughe A0 = NaN; B0 = NaN; C0 = NaN; D0 = NaN; freq0 = NaN; td0 = NaN; LeastOscN = 6; if nargin > 2 temp = varargin{1}; LeastOscN = temp; end if nargin > 3 temp = varargin{2}; if ~isempty(temp) freq0 = temp; end end if nargin > 4 temp = varargin{3}; if ~isempty(temp) td0 = temp; end end if nargin > 5 A0 = varargin{4}; end if nargin > 6 B0 = varargin{5}; end if nargin > 7 C0 = varargin{6}; end if nargin > 8 D0 = varargin{7}; end if L<40 NSegs = 4; elseif L<100 NSegs = 6; elseif L< 200 NSegs = 8; else NSegs = 12; end NperSeg = ceil(L/NSegs); if isnan(A0) A0 = mean(P(end-NperSeg+1:end)); end if isnan(B0) B0 = max(P) - min(P); end if isnan(C0) C0 = A0 - (max(P) + min(P))/2; end if isnan(D0) D0 = 0; end if isnan(td0) td0 = t(end)/2; end if isnan(freq0) idx1 = NperSeg+1; idx2 = L; for ii = 1:NSegs-1 idx2 = idx1+NperSeg-1; if idx2 <= L && (max(P(idx1:idx2)) - min(P(idx1:idx2))) < B0/5 td0 = t(idx2)/2; break; end idx1 = idx2; end FreqLB = max([40e-3, LeastOscN/(t(min(idx2,L))-t(1))]); FreqHB = min([0.5, (1/(t(2)-t(1)))/2]); [Frequency,Amp] = qes.util.fftSpectrum(t,P); <<<<<<< HEAD ======= %[Frequency,Amp] = FFTSpectrum(t,P); >>>>>>> a8438932b119574226b65e1ef4c2a76db4f154ce Lf = length(Amp); if Lf < 50 Amp = smooth(Amp,3); elseif Lf < 150 Amp = smooth(Amp,5); elseif Lf < 300 Amp = smooth(Amp,7); else Amp = smooth(Amp,9); end for ii = 1:length(Frequency); if Frequency(ii)>FreqLB if ii>1 Frequency(1:ii-1)=[]; Amp(1:ii-1)=[]; end break; end end for ii = 1:length(Frequency); if Frequency(ii)>FreqHB Frequency(ii:end)=[]; Amp(ii:end)=[]; break; end end [~,idx]=max(Amp); freq0 = Frequency(idx); end Coefficients(1) = A0; Coefficients(2) = B0; Coefficients(3) = C0; Coefficients(4) = D0; Coefficients(5) = freq0; Coefficients(6) = td0; for ii = 1:3 [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@SinusoidalDecay,Coefficients,t,P); end A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); D = Coefficients(4); freq = Coefficients(5); td = Coefficients(6); if nargout > 6 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end else A = 'Not enough data points, unable to do fitting!'; B = A; C = A; D = A; freq = A; td = A; if nargout > 6 varargout{1} = A; end end function [P]=SinusoidalDecay(Coefficients,t) % Sinusoidal Decay % Parameter estimation: % A: value of P at large x: P(end) or mean(P(end-##,end)) % B: max(P) - min(P) % C: A - (max(P) + min(P))/2 % D: 0 % freq: use fft to detect % td: ... % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/03/28 $ A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); D = Coefficients(4); freq = Coefficients(5); td = Coefficients(6); P = A +B*(exp(-t/td).*(sin(2*pi*freq*t+D)+C));
github
oiwic/QOS-master
sinDecayFitTilt.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/sinDecayFitTilt.m
1,595
utf_8
9187160bc61d77983180e6a75bde16af
function [A,B,C,D,freq,td,varargout] = sinDecayFitTilt(t,P,... A0,ABnd,... B0,BBnd,... C0,CBnd,... D0,DBnd,... freq0,freqBnd,... td0,tdBnd) % SinDecayFit fits curve P = P(t) with a Sinusoidal Decay function: % P = A +B*(exp(-t/td)*(sin(2*pi*freq*t+D)+C)); % % varargout{1}: ci, 6 by 2 matrix, ci(5,1) is the lower bound of 'freq', % ci(6,2) is the upper bound of 'td',... % % Yulin Wu, SC5,IoP,CAS. [email protected] % $Revision: 1.1 $ $Date: 2012/10/18 $ Coefficients(1) = A0; Coefficients(2) = B0; Coefficients(3) = C0; Coefficients(4) = D0; Coefficients(5) = freq0; Coefficients(6) = td0; lb = [ABnd(1),BBnd(1),CBnd(1),DBnd(1),freqBnd(1),tdBnd(1)]; ub = [ABnd(2),BBnd(2),CBnd(2),DBnd(2),freqBnd(2),tdBnd(2)]; for ii = 1:3 [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@SinusoidalDecay,Coefficients,t,P,lb,ub); end A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); D = Coefficients(4); freq = Coefficients(5); td = Coefficients(6); if nargout > 6 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end function [P]=SinusoidalDecay(Coefficients,t) % Sinusoidal Decay % Parameter estimation: % A: value of P at large x: P(end) or mean(P(end-##,end)) % B: max(P) - min(P) % C: A - (max(P) + min(P))/2 % D: 0 % freq: use fft to detect % td: ... % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/03/28 $ A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); D = Coefficients(4); freq = Coefficients(5); td = Coefficients(6); P = A +B*(exp(-t/td).*(sin(2*pi*freq*t+D)+C));
github
oiwic/QOS-master
gaussianFit.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/gaussianFit.m
827
utf_8
f903cbe5ed82911baa93c9e673524009
function [a, x0, sigma, y0, varargout] = gaussianFit(x,y,a0,x00,sigma0,y00) % fit data x to a gaussian: % y = a*exp(-(x-x0)^2/(2*sigma^2)) + y0 % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] Coefficients(1) = a0; Coefficients(2) = x0; Coefficients(3) = sigma0; Coefficients(4) = y00; warning('off'); [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@Lorentzian,Coefficients,x,y); warning('on'); a = Coefficients(1); x0 = Coefficients(2); sigma = Coefficients(3); y00 = Coefficients(4); if nargout > 4 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end end function y=gaussian(Coefficients,x) a = Coefficients(1); x0 = Coefficients(2); sigma = Coefficients(3); y0 = Coefficients(4); y = a*exp(-(x-x0).^2/(2*sigma^2))+y0; end
github
oiwic/QOS-master
sinDecayFitNoTilt.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/sinDecayFitNoTilt.m
1,297
utf_8
5fab97a26550d707281a89c911c4da81
function [B,C,D,freq,td,varargout] = sinDecayFitNoTilt(t,P,... B0,BBnd,... C0,CBnd,... D0,DBnd,... freq0,freqBnd,... td0,tdBnd) % SinDecayFit fits curve P = P(t) with a Sinusoidal Decay function: % P = B*(exp(-t/td)*(sin(2*pi*freq*t+D)+C)); % % varargout{1}: ci, 5 by 2 matrix, ci(4,1) is the lower bound of 'freq', % ci(5,2) is the upper bound of 'td',... % % Yulin Wu, SC5,IoP,CAS. [email protected] % $Revision: 1.1 $ $Date: 2012/10/18 $ Coefficients(1) = B0; Coefficients(2) = C0; Coefficients(3) = D0; Coefficients(4) = freq0; Coefficients(5) = td0; lb = [BBnd(1),CBnd(1),DBnd(1),freqBnd(1),tdBnd(1)]; ub = [BBnd(2),CBnd(2),DBnd(2),freqBnd(2),tdBnd(2)]; [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@SinusoidalDecay,Coefficients,t,P,lb,ub); B = Coefficients(1); C = Coefficients(2); D = Coefficients(3); freq = Coefficients(4); td = Coefficients(5); if nargout > 5 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end function [P]=SinusoidalDecay(Coefficients,t) % Sinusoidal Decay % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/03/28 $ B = Coefficients(1); C = Coefficients(2); D = Coefficients(3); freq = Coefficients(4); td = Coefficients(5); P = B*(exp(-(t/td)).*(sin(2*pi*freq*t+D)+C));
github
oiwic/QOS-master
expDecayFitNoBackground.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/expDecayFitNoBackground.m
1,520
utf_8
7275eee2ec0beb6df3efcac27586f5e4
function [B,td,varargout] = ExpDecayFit_NoBackground(t,P,varargin) % ExpDecayFit fits curve P = P(t) with Decay function: % P = B*exp(-t/td); % % optional output: 95% confidence interval of Coefficients % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/04/08 $ B0 = P(1) -P(end); td0 = t(end)-t(1)/2; Coefficients(1) = B0; Coefficients(2) = td0; if nargin > 2 Coefficients(1) = varargin{1}; end if nargin > 3 Coefficients(2) = varargin{2}; end lb = []; ub = []; if nargin > 5 lb = varargin{3}; ub = varargin{4}; end for ii = 1:3 % admonition: % lsqcurvefit is more robust than nlinfit, nlinfit produces erros % for some data set. if ~isempty(lb) && ~isempty(ub) [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@ExpDecay,Coefficients,t(:),P(:),lb,ub); else [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@ExpDecay,Coefficients,t(:),P(:)); end % [Coefficients, residual, J,~,~,~] = nlinfit(t,P,@ExpDecay,Coefficients); end B = Coefficients(1); td = Coefficients(2); if nargout > 2 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end function [P]=ExpDecay(Coefficients,t) % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/04/08 $ B = Coefficients(1); td = Coefficients(2); P = B*exp(-t/td);
github
oiwic/QOS-master
lorentzianPkFitAdv.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/lorentzianPkFitAdv.m
3,578
utf_8
76f3f3d38569d9609c29c8c7f49b6b26
function [y0, k1, k2, A, w, x0, varargout] = lorentzianPkFitAdv(x,y,varargin) % LorentzianPkFit_Adv fits Lorentzian shaped peak/dip (single peak/dip) with a % linear or almost linear background using the following model: % y = y0 + k1*x + k2*x^2 + (2*A/pi)*(w/(4*(x-x0)^2+w^2)); % Original data length should not less than 20 (length(x)>20) % % A function call returns the following fitting Coefficients: % y0, k1, k2, A, w(FWHM), x0(Peak position) OR 'error message'. % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/03/29 $ assert(numel(x)==numel(y)); r = range(x); c = mean(x); x = (x-c)/r; y00 = NaN; k10 = NaN; k20 = NaN; A0 = NaN; w0 = NaN; x00 = NaN; L = length(x); if L < 10 y0 = 'Unable to do fitting for the present set of data!'; k1 = y0; k2 = y0; A = y0; w = y0; x0 = y0; else if nargin > 2 x00 = varargin{1}; end if nargin > 3 A0 = varargin{2}; end if nargin > 4 w0 = varargin{3}; end if nargin > 5 y00 = varargin{4}; end if nargin > 6 k10 = varargin{5}; end if nargin > 7 k20 = varargin{6}; end if L < 25 ys = y; elseif L < 50 ys = smooth(y,3); else ys = smooth(y,5); end if isnan(y00) || isnan(k10) if L < 25 k10 = (ys(end) - ys(1))/(x(end) - x(1)); y00 = ys(1) - k10*x(1); elseif L < 50 k10 = (ys(end-1) - ys(2))/(x(end-1) - x(2)); y00 = ys(2) - k10*x(2); else k10 = (ys(end-2) - ys(3))/(x(end-2) - x(3)); y00 = ys(3) - k10*x(3); end end if isnan(k20) k20 = 0; end CoarseBkgrnd = y00+k10*x; CoarsePk = reshape(ys,1,[]) - CoarseBkgrnd; if sum(CoarsePk) < 0 % is dip [AMP, idx] = min(CoarsePk); else [AMP, idx] = max(CoarsePk); end if isnan(x00) x00 = x(idx); end jj = 1; temp = abs(AMP); if L - idx > L/2 while 1 if idx+jj >= L || abs(CoarsePk(idx+jj)) < temp/2 if isnan(w0) w0 = 2*(x(idx+jj)-x00); end break; end jj = jj+1; end else while 1 if idx-jj <= 1 || abs(CoarsePk(idx-jj)) < temp/2 if isnan(w0) w0 = 2*(x00-x(idx-jj)); end break; end jj = jj+1; end end w0 = abs(w0); % just in case if isnan(w0) w0 = range(x)/5; end if isnan(A0) A0 = pi*w0*AMP/2; end Coefficients(1) = y00; Coefficients(2) = k10; Coefficients(3) = k20; Coefficients(4) = A0; Coefficients(5) = w0; Coefficients(6) = x00; for ii = 1:1 [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@Lorentzian_Adv,Coefficients,x,y); end y0 = Coefficients(1); k1_ = Coefficients(2); k2_ = Coefficients(3); A = Coefficients(4); w = Coefficients(5); x0 = Coefficients(6); y0 = y0 - k1_*c/r+k2_*c^2/r^2; k1 = k1_/r-2*c*k2_/r^2; k2 = k2_/r^2; A = r*A; w = r*w; x0 = c+r*x0; if nargout > 6 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end end function [y]=Lorentzian_Adv(Coefficients,x) y0 = Coefficients(1); k1 = Coefficients(2); k2 = Coefficients(3); A = Coefficients(4); w = Coefficients(5); % FWHM x0 = Coefficients(6); y = y0+k1*x+k2*x.^2+(2*A/pi).*(w./(4*(x-x0).^2+w.^2));
github
oiwic/QOS-master
expDecayFit.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/expDecayFit.m
1,673
utf_8
96cfcee3a507130f1260ddb8049712b0
function [A,B,td,varargout] = ExpDecayFit(t,P,varargin) % ExpDecayFit fits curve P = P(t) with Decay function: % P = A +B*exp(-t/td); % % optional output: 95% confidence interval of Coefficients % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/04/08 $ A0 = P(end); B0 = P(1) -P(end); td0 = t(end)-t(1)/2; Coefficients(1) = A0; Coefficients(2) = B0; Coefficients(3) = td0; if nargin > 2 Coefficients(1) = varargin{1}; end if nargin > 3 Coefficients(2) = varargin{2}; end if nargin > 4 Coefficients(3) = varargin{3}; end lb = []; ub = []; if nargin > 5 lb = varargin{4}; ub = varargin{5}; end for ii = 1:3 % admonition: % lsqcurvefit is more robust than nlinfit, nlinfit produces erros % for some data set. if ~isempty(lb) && ~isempty(ub) [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@ExpDecay,Coefficients,t(:),P(:),lb,ub); else [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@ExpDecay,Coefficients,t(:),P(:)); end % [Coefficients, residual, J,~,~,~] = nlinfit(t,P,@ExpDecay,Coefficients); end A = Coefficients(1); B = Coefficients(2); td = Coefficients(3); if nargout > 3 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end function [P]=ExpDecay(Coefficients,t) % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/04/08 $ A = Coefficients(1); B = Coefficients(2); td = Coefficients(3); P = A +B*exp(-t/td);
github
oiwic/QOS-master
sinDecayFit.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/sinDecayFit.m
1,591
utf_8
9eb7058d0cb739052c56eff00a76f641
function [A,B,C,D,freq,td,varargout] = sinDecayFit(t,P,... A0,ABnd,... B0,BBnd,... C0,CBnd,... D0,DBnd,... freq0,freqBnd,... td0,tdBnd) % SinDecayFit fits curve P = P(t) with a Sinusoidal Decay function: % P = A +B*(exp(-t/td)*(sin(2*pi*freq*t+D)+C)); % % varargout{1}: ci, 6 by 2 matrix, ci(5,1) is the lower bound of 'freq', % ci(6,2) is the upper bound of 'td',... % % Yulin Wu, SC5,IoP,CAS. [email protected] % $Revision: 1.1 $ $Date: 2012/10/18 $ Coefficients(1) = A0; Coefficients(2) = B0; Coefficients(3) = C0; Coefficients(4) = D0; Coefficients(5) = freq0; Coefficients(6) = td0; lb = [ABnd(1),BBnd(1),CBnd(1),DBnd(1),freqBnd(1),tdBnd(1)]; ub = [ABnd(2),BBnd(2),CBnd(2),DBnd(2),freqBnd(2),tdBnd(2)]; for ii = 1:3 [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@SinusoidalDecay,Coefficients,t,P,lb,ub); end A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); D = Coefficients(4); freq = Coefficients(5); td = Coefficients(6); if nargout > 6 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end function [P]=SinusoidalDecay(Coefficients,t) % Sinusoidal Decay % Parameter estimation: % A: value of P at large x: P(end) or mean(P(end-##,end)) % B: max(P) - min(P) % C: A - (max(P) + min(P))/2 % D: 0 % freq: use fft to detect % td: ... % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/03/28 $ A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); D = Coefficients(4); freq = Coefficients(5); td = Coefficients(6); P = A +B*(exp(-t/td).*(sin(2*pi*freq*t+D)+C));
github
oiwic/QOS-master
RBFit.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/RBFit.m
738
utf_8
42a5935e890715a216623be994b9ea84
function [A,B,p,varargout] = RBFit(m,P,... A0,ABnd,... B0,BBnd,... p0,pBnd) % fit randomized benchmarking data if nargin < 3 A0 = range(P); ABnd = [0.9*A0, 1.1]; B0 = P(end); BBnd = [0, 1.1*B0]; p0 = 0.97; pBnd = [0.5,1]; end Coefficients(1) = A0; Coefficients(2) = B0; Coefficients(3) = p0; lb = [ABnd(1),BBnd(1),pBnd(1)]; ub = [ABnd(2),BBnd(2),pBnd(2)]; [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@fitFunc,Coefficients,m,P,lb,ub); A = Coefficients(1); B = Coefficients(2); p = Coefficients(3); if nargout > 3 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end function y=fitFunc(Coefficients,x) A = Coefficients(1); B = Coefficients(2); p = Coefficients(3); y = A*p.^x+B;
github
oiwic/QOS-master
lorentzianPkFit.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/lorentzianPkFit.m
2,882
utf_8
f5154da3d577520c5609e2cb81e7c265
function [y0, A, w, x0, varargout] = lorentzianPkFit(x,y,varargin) % LorentzianPkFit fits Lorentzian shaped peak/dip (single peak/dip) % y = y0 + (2*A/pi)*(w/(4*(x-x0)^2+w^2)); % Original data length should not less than 20 (length(x)>20) % % A function call returns the following fitting Coefficients: % y0, A, w(FWHM), x0(Peak position) OR 'error message'. % optional output: 95% confidence interval of Coefficients % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/03/29 $ % convert to colon to avoid shape mismatch(1*N and N*1 for example) assert(numel(x)==numel(y)); x = x(:); y = y(:); y00 = NaN; A0 = NaN; w0 = NaN; x00 = NaN; L = length(x); if L < 20 y0 = 'Unable to do fitting for the present set of data!'; A = y0; w = y0; x0 = y0; if nargout > 4 varargout{1} = y0; end else if nargin > 2 x00 = varargin{1}; end if nargin > 3 A0 = varargin{2}; end if nargin > 4 w0 = varargin{3}; end if nargin > 5 y00 = varargin{4}; end if L < 40 ys = y; elseif L < 100 ys = smooth(y,3); else ys = smooth(y,5); end if isnan(y00) if L < 40 y00 = ys(1); elseif L < 100 y00 = ys(2); else y00 = ys(3); end end CoarseBkgrnd = y00; CoarsePk = reshape(ys,1,[]) - CoarseBkgrnd; if sum(CoarsePk) < 0 % is dip [AMP, idx] = min(CoarsePk); else [AMP, idx] = max(CoarsePk); end if isnan(x00) x00 = x(idx); end jj = 1; temp = abs(AMP); if L - idx > L/2 while 1 if idx+jj >= L || abs(CoarsePk(idx+jj)) < temp/2 if isnan(w0) w0 = 2*(x(idx+jj)-x00); end break; end jj = jj+1; end else while 1 if idx-jj <= 1 || abs(CoarsePk(idx-jj)) < temp/2 if isnan(w0) w0 = 2*(x00-x(idx-jj)); end break; end jj = jj+1; end end w0 = abs(w0); % just in case if isnan(A0) A0 = pi*w0*AMP/2; end Coefficients(1) = y00; Coefficients(2) = A0; Coefficients(3) = w0; Coefficients(4) = x00; for ii = 1:1 [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@Lorentzian,Coefficients,x,y); end y0 = Coefficients(1); A = Coefficients(2); w = Coefficients(3); x0 = Coefficients(4); if nargout > 4 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end end function [y]=Lorentzian(Coefficients,x) y0 = Coefficients(1); A = Coefficients(2); w = Coefficients(3); % FWHM x0 = Coefficients(4); y = y0 + (2*A/pi).*(w./(4*(x-x0).^2+w.^2));
github
oiwic/QOS-master
lorentzianFit.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/lorentzianFit.m
834
utf_8
b040f6192990d8318742926f16f1640a
function [A, w, y0, x0, varargout] = gaussianFit(x,y,a0,x00,sigma0) % fit data x to a lorentzian: % y = y0 + (2*A/pi)*(w/(4*(x-x0)^2+w^2)); % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] Coefficients(1) = y00; Coefficients(2) = A0; Coefficients(3) = w0; Coefficients(4) = x00; warning('off'); [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@Lorentzian,Coefficients,x,y); warning('on'); y0 = Coefficients(1); A = Coefficients(2); w = Coefficients(3); x0 = Coefficients(4); if nargout > 4 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end end function [y]=Lorentzian(Coefficients,x) y0 = Coefficients(1); A = Coefficients(2); w = Coefficients(3); % FWHM x0 = Coefficients(4); y = y0 + (2*A/pi).*(w./(4*(x-x0).^2+w.^2)); end
github
oiwic/QOS-master
cosFit.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/cosFit.m
980
utf_8
ca956e3f2cd032cd5d505b7f6f3deba9
function [A,B,C,freq,varargout] = cosFit(t,P,... A0,ABnd,... B0,BBnd,... C0,CBnd,... freq0,freqBnd) % SinDecayFit fits curve P = P(t) with a Sinusoidal Decay function: % P = A*(cos(2*pi*freq*t+B)+C)); % % varargout{1}: ci, 4 by 2 matrix, ci(4,1) is the lower bound of 'freq' % % Yulin Wu, SC5,IoP,CAS. [email protected] % $Revision: 1.1 $ $Date: 2012/10/18 $ Coefficients(1) = A0; Coefficients(2) = B0; Coefficients(3) = C0; Coefficients(4) = freq0; lb = [ABnd(1),BBnd(1),CBnd(1),freqBnd(1)]; ub = [ABnd(2),BBnd(2),CBnd(2),freqBnd(2)]; for ii = 1:3 [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@cos_,Coefficients,t,P,lb,ub); end A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); freq = Coefficients(4); if nargout > 4 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end function [P]=cos_(Coefficients,t) A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); freq = Coefficients(4); P = A*(cos(2*pi*freq*t+B)+C);
github
oiwic/QOS-master
expDecayFit4fig.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/+scripts/expDecayFit4fig.m
2,308
utf_8
2fb0b9b205253426ada8203a3cfeed73
function expDecayFit4fig() % Fit exponential decay data by load the figure file in which the data is % plotted. Fit results are displayed in the cmd window and plotted on to the the figure. % How to use: just run this funciton, no input arguments needed. % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/04/08 $ import toolbox.data_tool.fitting.* persistent lastselecteddir % last direction selection is remembered if isempty(lastselecteddir) || ~exist(lastselecteddir,'dir') Datafile = fullfile(pwd,'*.fig'); else Datafile = fullfile(lastselecteddir,'*.fig'); end [FileName,PathName,~] = uigetfile(Datafile,'Select the fig to fit:'); if ischar(PathName) && isdir(PathName) lastselecteddir = PathName; end datafig = fullfile(PathName,FileName); if ~exist(datafig,'file') return; end h = openfig(datafig); figure(h); ln = findobj(gca,'type','line'); if isempty(ln) title('No data found in figure.'); return; elseif length(ln) > 1 title('More than two data sets found, trying to fit the first.'); end x = get(ln(1),'XData'); y = get(ln(1),'YData'); if length(x)<3 || x(1)+x(end) == 0 title('Data length too short.'); return; end [A,B,xd] = expDecayFit(x,y); L = length(x); step = (x(end)-x(1))/L/50; % 50 times sampling density xf = x(1):step:x(end); yf = expDecay([A,B,xd],xf); home; fprintf('y = A +B*exp(-x/xd)\n'); fprintf('A = %f B = %f td = %f\n ',A,B,xd); hold(gca,'on'); xlimit = get(gca,'XLim'); ylimit = get(gca,'YLim'); plot(x,y,'bo','MarkerSize',8,'MarkerEdgeColor','b','MarkerFaceColor','b'); plot(xf,yf,'r-','LineWidth',2); legend('data','fit'); xlabel('x','FontSize',28); ylabel('y','FontSize',28); ylim([0.6,0.9]); title(['xd: ',num2str(xd,'%4.1f'),''],'FontSize',20) set(gca,'XLim',xlimit); set(gca,'YLim',ylimit); set(gcf,'Color',[1,1,1]); end function [P]=ExpDecay(Coefficients,t) % % Yulin Wu, SC5,IoP,CAS. [email protected] % $Revision: 1.0 $ $Date: 2012/04/08 $ A = Coefficients(1); B = Coefficients(2); td = Coefficients(3); P = A +B*exp(-t/td); end
github
oiwic/QOS-master
SinDecayFit.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/SinDecayFit/fitfunc/SinDecayFit.m
5,490
utf_8
c5851b5442a388111510426ecca97e29
function [A,B,C,D,freq,td,varargout] = SinDecayFit(t,P,varargin) % SinDecayFit fits curve P = P(t) with a Sinusoidal Decay function: % P = A +B*(exp(-t/td)*(sin(2*pi*freq*t+D)+C)); % t unit should be nano-second. % Original data length should not less than 20 (length(t)>20) % % A function call returns the following fitting Coefficients: % A,B,C,D,freq,td OR 'error message'. % optional output: 95% confidence interval of Coefficients % % varargin{1}: MINIMUM oscillation circles P has (LeastOscN). If not specifid, % the programme sets it to 6. % Note: the bigger the value of 'LeastOscN', the less likely for the fitting % to fail, but make sure it dose not exceed the REAL oscillation circles P % has, for example: % If you can clearly see that there is more than 30 oscillation circles and % the exact oscillation circle number is less than 150: % [A,B,C,D,freq,td] = SinDecayFit(t,P); % Default, alright for most cases % [A,B,C,D,freq,td] = SinDecayFit(t,P,2); % very likely to fail % [A,B,C,D,freq,td] = SinDecayFit(t,P,30); % most likey to be successful % [A,B,C,D,freq,td] = SinDecayFit(t,P,160); % may fail % % varargin{2}, initial value of oscillation frequency, if auto fitting % failed, specify this value(as close to the real oscillation frequency % value as possible). In this case, value of varargin{1} will not % be used, given any value will be alright % % varargin{3}, initial value of decay time, if fitting still fail when % initial value of oscillation frequency is given, specify this value( % as close to the real decay time value as possible). % % varargin{4}, initial value A % varargin{5}, initial value B % varargin{6}, initial value C % varargin{7}, initial value D % % varargout{1}: ci, 6 by 2 matrix, ci(5,1) is the lower bound of 'freq', % ci(6,2) is the upper bound of 'td',... % % Yulin Wu, SC5,IoP,CAS. [email protected] % $Revision: 1.1 $ $Date: 2012/10/18 $ L = length(t); if L > 15 % data dense enoughe A0 = NaN; B0 = NaN; C0 = NaN; D0 = NaN; freq0 = NaN; td0 = NaN; LeastOscN = 6; if nargin > 2 temp = varargin{1}; LeastOscN = temp; end if nargin > 3 temp = varargin{2}; if ~isempty(temp) freq0 = temp; end end if nargin > 4 temp = varargin{3}; if ~isempty(temp) td0 = temp; end end if nargin > 5 A0 = varargin{4}; end if nargin > 6 B0 = varargin{5}; end if nargin > 7 C0 = varargin{6}; end if nargin > 8 D0 = varargin{7}; end if L<40 NSegs = 4; elseif L<100 NSegs = 6; elseif L< 200 NSegs = 8; else NSegs = 12; end NperSeg = ceil(L/NSegs); if isnan(A0) A0 = mean(P(end-NperSeg+1:end)); end if isnan(B0) B0 = max(P) - min(P); end if isnan(C0) C0 = A0 - (max(P) + min(P))/2; end if isnan(D0) D0 = 0; end if isnan(td0) td0 = t(end)/2; end if isnan(freq0) idx1 = NperSeg+1; idx2 = L; for ii = 1:NSegs-1 idx2 = idx1+NperSeg-1; if idx2 <= L && (max(P(idx1:idx2)) - min(P(idx1:idx2))) < B0/5 td0 = t(idx2)/2; break; end idx1 = idx2; end FreqLB = max([40e-3, LeastOscN/(t(min(idx2,L))-t(1))]); FreqHB = min([0.5, (1/(t(2)-t(1)))/2]); [Frequency,Amp] = FFTSpectrum(t,P); Lf = length(Amp); if Lf < 50 Amp = smooth(Amp,3); elseif Lf < 150 Amp = smooth(Amp,5); elseif Lf < 300 Amp = smooth(Amp,7); else Amp = smooth(Amp,9); end for ii = 1:length(Frequency); if Frequency(ii)>FreqLB if ii>1 Frequency(1:ii-1)=[]; Amp(1:ii-1)=[]; end break; end end for ii = 1:length(Frequency); if Frequency(ii)>FreqHB Frequency(ii:end)=[]; Amp(ii:end)=[]; break; end end [~,idx]=max(Amp); freq0 = Frequency(idx); end Coefficients(1) = A0; Coefficients(2) = B0; Coefficients(3) = C0; Coefficients(4) = D0; Coefficients(5) = freq0; Coefficients(6) = td0; for ii = 1:3 [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@SinusoidalDecay,Coefficients,t,P); end A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); D = Coefficients(4); freq = Coefficients(5); td = Coefficients(6); if nargout > 6 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end else A = 'Not enough data points, unable to do fitting!'; B = A; C = A; D = A; freq = A; td = A; if nargout > 6 varargout{1} = A; end end function [P]=SinusoidalDecay(Coefficients,t) % Sinusoidal Decay % Parameter estimation: % A: value of P at large x: P(end) or mean(P(end-##,end)) % B: max(P) - min(P) % C: A - (max(P) + min(P))/2 % D: 0 % freq: use fft to detect % td: ... % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/03/28 $ A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); D = Coefficients(4); freq = Coefficients(5); td = Coefficients(6); P = A +B*(exp(-t/td).*(sin(2*pi*freq*t+D)+C));
github
oiwic/QOS-master
DSinDecayFit.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/SinDecayFit/fitfunc/DSinDecayFit.m
1,574
utf_8
f7fa7a681ba575ca2988cea163efcb75
function [A,B1,C1,D1,freq1,td1,B2,C2,D2,freq2,td2] = DSinDecayFit(t,P,A0,B0,C0,D0,freq0,td0) % SinDecayFit fits curve P = P(t) with a Sinusoidal Decay function: % P = A +B1*(exp(-t/td1)*(sin(2*pi*freq1*t+D1)+C1))+B2*(exp(-t/td2)*(sin(2*pi*freq2*t+D2)+C2)); % t unit should be nano-second. % % Yulin Wu, SC5,IoP,CAS. [email protected] % $Revision: 1.0 $ $Date: 2012/10/18 $ Coefficients(1) = A0; Coefficients(2) = B0; Coefficients(3) = C0; Coefficients(4) = D0; Coefficients(5) = freq0; Coefficients(6) = td0; Coefficients(7) = B0; Coefficients(8) = C0; Coefficients(9) = D0; Coefficients(10) = freq0; Coefficients(11) = td0; for ii = 1:10 Coefficients = lsqcurvefit(@DSinusoidalDecay,Coefficients,t,P); end A = Coefficients(1); B1 = Coefficients(2); C1 = Coefficients(3); D1 = Coefficients(4); freq1 = Coefficients(5); td1 = Coefficients(6); B2 = Coefficients(7); C2 = Coefficients(8); D2 = Coefficients(9); freq2 = Coefficients(10); td2 = Coefficients(11); function [P]=DSinusoidalDecay(Coefficients,t) % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/03/28 $ A = Coefficients(1); B1 = Coefficients(2); C1 = Coefficients(3); D1 = Coefficients(4); freq1 = Coefficients(5); td1 = Coefficients(6); B2 = Coefficients(7); C2 = Coefficients(8); D2 = Coefficients(9); freq2 = Coefficients(10); td2 = Coefficients(11); P = A +B1*(exp(-t/td1).*(sin(2*pi*freq1*t+D1)+C1))+B2*(exp(-t/td2).*(sin(2*pi*freq2*t+D2)+C2));
github
oiwic/QOS-master
SinDecayFit_G.m
.m
QOS-master/qos/+toolbox/+data_tool/+fitting/SinDecayFit/fitfunc/SinDecayFit_G.m
5,502
utf_8
37605efcff04c56296a1d008f3931ba7
function [A,B,C,D,freq,td,varargout] = SinDecayFit_G(t,P,varargin) % SinDecayFit fits curve P = P(t) with a Sinusoidal Decay function: % P = A +B*(exp(-(t/td).^2)*(sin(2*pi*freq*t+D)+C)); % t unit should be nano-second. % Original data length should not less than 20 (length(t)>20) % % A function call returns the following fitting Coefficients: % A,B,C,D,freq,td OR 'error message'. % optional output: 95% confidence interval of Coefficients % % varargin{1}: MINIMUM oscillation circles P has (LeastOscN). If not specifid, % the programme sets it to 6. % Note: the bigger the value of 'LeastOscN', the less likely for the fitting % to fail, but make sure it dose not exceed the REAL oscillation circles P % has, for example: % If you can clearly see that there is more than 30 oscillation circles and % the exact oscillation circle number is less than 150: % [A,B,C,D,freq,td] = SinDecayFit(t,P); % Default, alright for most cases % [A,B,C,D,freq,td] = SinDecayFit(t,P,2); % very likely to fail % [A,B,C,D,freq,td] = SinDecayFit(t,P,30); % most likey to be successful % [A,B,C,D,freq,td] = SinDecayFit(t,P,160); % may fail % % varargin{2}, initial value of oscillation frequency, if auto fitting % failed, specify this value(as close to the real oscillation frequency % value as possible). In this case, value of varargin{1} will not % be used, given any value will be alright % % varargin{3}, initial value of decay time, if fitting still fail when % initial value of oscillation frequency is given, specify this value( % as close to the real decay time value as possible). % % varargin{4}, initial value A % varargin{5}, initial value B % varargin{6}, initial value C % varargin{7}, initial value D % % varargout{1}: ci, 6 by 2 matrix, ci(5,1) is the lower bound of 'freq', % ci(6,2) is the upper bound of 'td',... % % Yulin Wu, SC5,IoP,CAS. [email protected] % $Revision: 1.1 $ $Date: 2012/10/18 $ L = length(t); if L > 15 % data dense enoughe A0 = NaN; B0 = NaN; C0 = NaN; D0 = NaN; freq0 = NaN; td0 = NaN; LeastOscN = 6; if nargin > 2 temp = varargin{1}; LeastOscN = temp; end if nargin > 3 temp = varargin{2}; if ~isempty(temp) freq0 = temp; end end if nargin > 4 temp = varargin{3}; if ~isempty(temp) td0 = temp; end end if nargin > 5 A0 = varargin{4}; end if nargin > 6 B0 = varargin{5}; end if nargin > 7 C0 = varargin{6}; end if nargin > 8 D0 = varargin{7}; end if L<40 NSegs = 4; elseif L<100 NSegs = 6; elseif L< 200 NSegs = 8; else NSegs = 12; end NperSeg = ceil(L/NSegs); if isnan(A0) A0 = mean(P(end-NperSeg+1:end)); end if isnan(B0) B0 = max(P) - min(P); end if isnan(C0) C0 = A0 - (max(P) + min(P))/2; end if isnan(D0) D0 = 0; end if isnan(td0) td0 = t(end)/2; end if isnan(freq0) idx1 = NperSeg+1; idx2 = L; for ii = 1:NSegs-1 idx2 = idx1+NperSeg-1; if idx2 <= L && (max(P(idx1:idx2)) - min(P(idx1:idx2))) < B0/5 td0 = t(idx2)/2; break; end idx1 = idx2; end FreqLB = max([40e-3, LeastOscN/(t(min(idx2,L))-t(1))]); FreqHB = min([0.5, (1/(t(2)-t(1)))/2]); [Frequency,Amp] = FFTSpectrum(t,P); Lf = length(Amp); if Lf < 50 Amp = smooth(Amp,3); elseif Lf < 150 Amp = smooth(Amp,5); elseif Lf < 300 Amp = smooth(Amp,7); else Amp = smooth(Amp,9); end for ii = 1:length(Frequency); if Frequency(ii)>FreqLB if ii>1 Frequency(1:ii-1)=[]; Amp(1:ii-1)=[]; end break; end end for ii = 1:length(Frequency); if Frequency(ii)>FreqHB Frequency(ii:end)=[]; Amp(ii:end)=[]; break; end end [~,idx]=max(Amp); freq0 = Frequency(idx); end Coefficients(1) = A0; Coefficients(2) = B0; Coefficients(3) = C0; Coefficients(4) = D0; Coefficients(5) = freq0; Coefficients(6) = td0; for ii = 1:3 [Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@SinusoidalDecay,Coefficients,t,P); end A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); D = Coefficients(4); freq = Coefficients(5); td = Coefficients(6); if nargout > 6 varargout{1} = nlparci(Coefficients,residual,'jacobian',J); end else A = 'Not enough data points, unable to do fitting!'; B = A; C = A; D = A; freq = A; td = A; if nargout > 6 varargout{1} = A; end end function [P]=SinusoidalDecay(Coefficients,t) % Sinusoidal Decay % Parameter estimation: % A: value of P at large x: P(end) or mean(P(end-##,end)) % B: max(P) - min(P) % C: A - (max(P) + min(P))/2 % D: 0 % freq: use fft to detect % td: ... % % Yulin Wu, SC5,IoP,CAS. [email protected]/[email protected] % $Revision: 1.0 $ $Date: 2012/03/28 $ A = Coefficients(1); B = Coefficients(2); C = Coefficients(3); D = Coefficients(4); freq = Coefficients(5); td = Coefficients(6); P = A +B*(exp(-(t/td).^2).*(sin(2*pi*freq*t+D)+C));
github
oiwic/QOS-master
inlineCallbacks.m
.m
QOS-master/qos/+mtwisted/+defer/inlineCallbacks.m
7,599
utf_8
0e0f303ff4ee61aa35b4930e170d2555
function new_f = inlineCallbacks(f) % inlineCallbacks helps you write L{Deferred}-using code that looks like a % regular sequential function. For example:: % @inlineCallbacks % def thingummy(): % thing = yield makeSomeRequestResultingInDeferred() % print(thing) # the result! hoorj! % When you call anything that results in a L{Deferred}, you can simply yield it; % your generator will automatically be resumed when the Deferred's result is % available. The generator will be sent the result of the L{Deferred} with the % 'send' method on generators, or if the result was a failure, 'throw'. % Things that are not L{Deferred}s may also be yielded, and your generator % will be resumed with the same object sent back. This means C{yield} % performs an operation roughly equivalent to L{maybeDeferred}. % Your inlineCallbacks-enabled generator will return a L{Deferred} object, which % will result in the return value of the generator (or will fail with a % failure object if your generator raises an unhandled exception). Note that % you can't use C{return result} to return a value; use C{returnValue(result)} % instead. Falling off the end of the generator, or simply using C{return} % will cause the L{Deferred} to have a result of L{None}. % Be aware that L{returnValue} will not accept a L{Deferred} as a parameter. % If you believe the thing you'd like to return could be a L{Deferred}, do % this:: % result = yield result % returnValue(result) % The L{Deferred} returned from your deferred generator may errback if your % generator raised an exception:: % @inlineCallbacks % def thingummy(): % thing = yield makeSomeRequestResultingInDeferred() % if thing == 'I love Twisted': % # will become the result of the Deferred % returnValue('TWISTED IS GREAT!') % else: % # will trigger an errback % raise Exception('DESTROY ALL LIFE') % If you are using Python 3.3 or later, it is possible to use the C{return} % statement instead of L{returnValue}:: % @inlineCallbacks % def loadData(url): % response = yield makeRequest(url) % return json.loads(response) function d = unwindGenerator(varargin) try gen = f(varargin); catch _DefGen_Return error('inlineCallbacks requires %s to produce a generator; instead caught returnValue being used in a non-generator', f); end if ~isa(gen, 'mtwisted.Generator') error('inlineCallbacks requires %s to produce a generator; instead got %r', f, gen); end d = inlineCallbacks_(None, gen, mtwisted.defer.Deferred()); end new_f = @unwindGenerator; end function deferred = inlineCallbacks_(result, g, deferred) % See L{inlineCallbacks}. % This function is complicated by the need to prevent unbounded recursion % arising from repeatedly yielding immediately ready deferreds. This while % loop and the waiting variable solve that by manually unfolding the % recursion. waiting = [true,... % waiting for result? mtwisted.None]; % result while 1 try % Send the last result back as the result of the yield expression. if isa(result, 'mtwisted.Failure') result = result.throwExceptionIntoGenerator(g); %%%%%%%%%%%%%%%%%% else result = g.send(result); end catch ME switch ME.identifier case 'mtwisted:StopIteration' % fell off the end, or "return" statement deferred.callback(ME.value); return; case 'mtwisted:DefGen_Return' % returnValue() was called; time to give a result to the original % Deferred. First though, let's try to identify the potentially % confusing situation which results when returnValue() is % accidentally invoked from a different function, one that wasn't % decorated with @inlineCallbacks % The traceback starts in this frame (the one for % _inlineCallbacks); the next one down should be the application % code. appCodeTrace = exc_info(); appCodeTrace = appCodeTrace(2).tb_next; if isFailure % If we invoked this generator frame by throwing an exception % into it, then throwExceptionIntoGenerator will consume an % additional stack frame itself, so we need to skip that too. appCodeTrace = appCodeTrace.tb_next; end % Now that we've identified the frame being exited by the % exception, let's figure out if returnValue was called from it % directly. returnValue itself consumes a stack frame, so the % application code will have a tb_next, but it will *not* have a % second tb_next. if appCodeTrace.tb_next.tb_next % If returnValue was invoked non-local to the frame which it is % exiting, identify the frame that ultimately invoked % returnValue so that we can warn the user, as this behavior is % confusing. ultimateTrace = appCodeTrace; while ultimateTrace.tb_next.tb_next ultimateTrace = ultimateTrace.tb_next; end filename = ultimateTrace.tb_frame.f_code.co_filename; lineno = ultimateTrace.tb_lineno; warnings.warn_explicit(... 'returnValue() in %s causing %s to exit: returnValue should only be invoked by functions decorated with inlineCallbacks',... ultimateTrace.tb_frame.f_code.co_name, appCodeTrace.tb_frame.f_code.co_name),DeprecationWarning, filename, lineno); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end deferred.callback(ME.value) return; otherwise deferred.errback() return; end end if isa(result, 'mtwisted.defer.Deferred') % a deferred was yielded, get the result. result.addBoth(@gotResult); if waiting(0) % Haven't called back yet, set flag so that we get reinvoked % and return from the loop waiting(0) = false; return; end result = waiting(1); % Reset waiting to initial values for next loop. gotResult uses % waiting, but this isn't a problem because gotResult is only % executed once, and if it hasn't been executed yet, the return % branch above would have been taken. waiting(0) = true; waiting(1) = mtwisted.defer.None(); end end function gotResult(r) if waiting(0) waiting(0) = false; waiting(1) = r; else inlineCallbacks_(r, g, deferred); end end end
github
oiwic/QOS-master
RE.m
.m
QOS-master/qos/+app/RE.m
63
utf_8
bde05fcab817305e123936e51aad3b31
% Open RegistryEditor function RE() qes.app.RegEditor; end
github
oiwic/QOS-master
DV.m
.m
QOS-master/qos/+app/DV.m
60
utf_8
396271d0e2cfed99f73f7cd432cf5480
% Open DataViewer function DV() qes.app.DataViewer; end
github
oiwic/QOS-master
breakyaxis.m
.m
QOS-master/qos/+misc/breakyaxis.m
11,688
utf_8
8f631ebff0d84d743e8ee60e7fe1ca00
% breakyaxes splits data in an axes so that data is in a low and high pane. % % breakYAxes(splitYLim) splitYLim is a 2 element vector containing a range % of y values from splitYLim(1) to splitYLim(2) to remove from the axes. % They must be within the current yLimis of the axes. % % breakYAxes(splitYLim,splitHeight) splitHeight is the distance to % seperate the low and high side. Units are the same as % get(AX,'uints') default is 0.015 % % breakYAxes(splitYLim,splitHeight,xOverhang) xOverhang stretches the % axis split graphic to extend past the top and bottom of the plot by % the distance set by XOverhang. Units are the same as get(AX,'units') % default value is 0.015 % % breakYAxes(AX, ...) performs the operation on the axis specified by AX % function breakInfo = breakyaxis(varargin) %Validate Arguements if nargin < 1 || nargin > 4 error('Wrong number of arguements'); end if isscalar(varargin{1}) && ishandle(varargin{1}) mainAxes = varargin{1}; argOffset = 1; argCnt = nargin - 1; if ~strcmp(get(mainAxes,'Type'),'axes') error('Handle object must be Type Axes'); end else mainAxes = gca; argOffset = 0; argCnt = nargin; end if (strcmp(get(mainAxes,'XScale'),'log')) error('Log X Axes are not supported'); end if (argCnt < 3) xOverhang = 0.015; else xOverhang = varargin{3 + argOffset}; if numel(xOverhang) ~= 1 || ~isreal(xOverhang) || ~isnumeric(xOverhang) error('XOverhang must be a scalar number'); elseif (xOverhang < 0) error('XOverhang must not be negative'); end xOverhang = double(xOverhang); end if (argCnt < 2) splitHeight = 0.015; else splitHeight = varargin{2 + argOffset}; if numel(xOverhang) ~= 1 || ~isreal(xOverhang) || ~isnumeric(xOverhang) error('splitHeight must be a scalar number'); elseif (xOverhang < 0) error('splitHeight must not be negative'); end splitHeight = double(splitHeight); end splitYLim = varargin{1 + argOffset}; if numel(splitYLim) ~= 2 || ~isnumeric(splitYLim) || ~isreal(xOverhang) error(splitYLim,'Must be a vector length 2'); end splitYLim = double(splitYLim); mainYLim = get(mainAxes,'YLim'); if (any(splitYLim >= mainYLim(2)) || any(splitYLim <= mainYLim(1))) error('splitYLim must be in the range given by get(AX,''YLim'')'); end mainPosition = get(mainAxes,'Position'); if (splitHeight > mainPosition(3) ) error('Split width is too large') end %We need to create 4 axes % lowAxes - is used for the low y axis and low pane data % highAxes - is used to the high y axis and high pane data % annotationAxes - is used to display the x axis and title % breakAxes - this is an axes with the same size and position as main % is it used to draw a seperator between the low and high side %Grab Some Parameters from the main axis (e.g the one we are spliting) mainYLim = get(mainAxes,'YLim'); mainXLim = get(mainAxes,'XLim'); mainPosition = get(mainAxes,'Position'); mainParent = get(mainAxes,'Parent'); mainHeight = mainPosition(4); %Positions have the format [low bottom width height] %mainYRange = mainYLim(2) - mainYLim(1); mainFigure = get(mainAxes,'Parent'); mainXColor = get(mainAxes,'XColor'); mainLineWidth = get(mainAxes,'LineWidth'); figureColor = get(mainFigure,'Color'); mainXTickLabelMode = get(mainAxes,'XTickLabelMode'); mainYLabel = get(mainAxes,'YLabel'); mainYDir = get(mainAxes,'YDir'); mainLayer = get(mainAxes,'Layer'); %Save Main Axis Z Order figureChildren = get(mainFigure,'Children'); zOrder = find(figureChildren == mainAxes); %Calculate where axesLow and axesHigh will be layed on screen %And their respctive YLimits lowYLimTemp = [mainYLim(1) splitYLim(1)]; highYLimTemp = [splitYLim(2) mainYLim(2)]; lowYRangeTemp = lowYLimTemp(2) - lowYLimTemp(1); highYRangeTemp = highYLimTemp(2) - highYLimTemp(1); lowHeightTemp = lowYRangeTemp / (lowYRangeTemp + highYRangeTemp) * (mainHeight - splitHeight); highHeightTemp = highYRangeTemp / (lowYRangeTemp + highYRangeTemp) * (mainHeight - splitHeight); lowStretch = (lowHeightTemp + splitHeight/2) / lowHeightTemp; lowYRange = lowYRangeTemp * lowStretch; lowHeight = lowHeightTemp * lowStretch; highStretch = (highHeightTemp + splitHeight/2) / highHeightTemp; highYRange = highYRangeTemp * highStretch; highHeight = highHeightTemp * highStretch; lowYLim = [mainYLim(1) mainYLim(1)+lowYRange]; highYLim = [mainYLim(2)-highYRange mainYLim(2)]; if (strcmp(mainYDir, 'normal')) lowPosition = mainPosition; lowPosition(4) = lowHeight; highPosition = mainPosition; %(!!!) look here for position indices! highPosition(2) = mainPosition(2) + lowHeight; highPosition(4) = highHeight; else %Low Axis will actually go on the high side a vise versa highPosition = mainPosition; highPosition(4) = highHeight; lowPosition = mainPosition; lowPosition(2) = mainPosition(2) + highHeight; lowPosition(4) = lowHeight; end %Create the Annotations layer, if the Layer is top, draw the axes on %top (e.g. after) drawing the low and high pane if strcmp(mainLayer,'bottom') annotationAxes = CreateAnnotaionAxes(mainAxes,mainParent) end %Create and position the lowAxes. Remove all X Axis Annotations, the %title, and a potentially offensive tick mark lowAxes = copyobj(mainAxes,mainParent); set(lowAxes,'Position', lowPosition, ... 'YLim', lowYLim, ... 'XLim', mainXLim, ... 'XGrid' ,'off', ... 'XMinorGrid', 'off', ... 'XMinorTick','off', ... 'XTick', [], ... 'XTickLabel', [], ... 'box','off'); if strcmp(mainLayer,'bottom') set(lowAxes,'Color','none'); end delete(get(lowAxes,'XLabel')); delete(get(lowAxes,'YLabel')); delete(get(lowAxes,'Title')); if strcmp(mainXTickLabelMode,'auto') yTick = get(lowAxes,'YTick'); set(lowAxes,'YTick',yTick(1:(end-1))); end %Create and position the highAxes. Remove all X Axis annotations, the %title, and a potentially offensive tick mark highAxes = copyobj(mainAxes,mainParent); set(highAxes,'Position', highPosition, ... 'YLim', highYLim, ... 'XLim', mainXLim, ... 'XGrid' ,'off', ... 'XMinorGrid', 'off', ... 'XMinorTick','off', ... 'XTick', [], ... 'XTickLabel', [], ... 'box','off'); if strcmp(mainLayer,'bottom') %(!!!) is it only about layers? set(highAxes,'Color','none'); end delete(get(highAxes,'XLabel')); delete(get(highAxes,'YLabel')); delete(get(highAxes,'Title')); if strcmp(mainXTickLabelMode,'auto') yTick = get(highAxes,'YTick'); set(highAxes,'YTick',yTick(2:end)); end %Create the Annotations layer, if the Layer is top, draw the axes on %top (e.g. after) drawing the low and high pane if strcmp(mainLayer,'top') annotationAxes = CreateAnnotaionAxes(mainAxes,mainParent); set(annotationAxes, 'Color','none'); end %Create breakAxes, remove all graphics objects and hide all annotations breakAxes = copyobj(mainAxes,mainParent); children = get(breakAxes,'Children'); for i = 1:numel(children) delete(children(i)); end set(breakAxes,'Color','none'); %Stretch the breakAxes horizontally to cover the vertical axes lines orignalUnits = get(breakAxes,'Units'); set(breakAxes,'Units','Pixel'); breakPosition = get(breakAxes,'Position'); nudgeFactor = get(breakAxes,'LineWidth'); breakPosition(3) = breakPosition(3) + nudgeFactor; set(breakAxes,'Position',breakPosition); set(breakAxes,'Units',orignalUnits); %Stretch the breakAxes horizontally to create an overhang for sylistic %effect breakPosition = get(breakAxes,'Position'); breakPosition(1) = breakPosition(1) - xOverhang; breakPosition(3) = breakPosition(3) + 2*xOverhang; set(breakAxes,'Position',breakPosition); %Create a sine shaped patch to seperate the 2 sides breakYLim = [mainPosition(2) mainPosition(2)+mainPosition(4)]; set(breakAxes,'ylim',breakYLim); theta = linspace(0,2*pi,100); xPoints = linspace(mainXLim(1),mainXLim(2),100); amp = splitHeight/2 * 0.9; yPoints1 = amp * sin(theta) + mainPosition(2) + lowHeightTemp; yPoints2 = amp * sin(theta) + mainPosition(2) + mainPosition(4) - highHeightTemp; patchPointsY = [yPoints1 yPoints2(end:-1:1) yPoints1(1)]; patchPointsX = [xPoints xPoints(end:-1:1) xPoints(1)]; patch(patchPointsX,patchPointsY ,figureColor,'EdgeColor',figureColor,'Parent',breakAxes); %use of pathc(!!!)? %Create A Line To Delineate the low and high edge of the patch line('yData',yPoints1,'xdata',xPoints,'Parent',breakAxes,'Color',mainXColor,'LineWidth',mainLineWidth); line('yData',yPoints2,'xdata',xPoints,'Parent',breakAxes,'Color',mainXColor,'LineWidth',mainLineWidth); set(breakAxes,'Visible','off'); %Make the old main axes invisiable invisibleObjects = RecursiveSetVisibleOff(mainAxes); %Preserve the z-order of the figure uistack([lowAxes highAxes breakAxes annotationAxes],'down',zOrder-1) %Set the rezise mode to position so that we can dynamically change the %size of the figure without screwing things up set([lowAxes highAxes breakAxes annotationAxes],'ActivePositionProperty','Position'); %Playing with the titles labels etc can cause matlab to reposition %the axes in some cases. Mannually force the position to be correct. set([breakAxes annotationAxes],'Position',mainPosition); %Save the axes so we can unbreak the axis easily breakInfo = struct(); breakInfo.lowAxes = lowAxes; breakInfo.highAxes = highAxes; breakInfo.breakAxes = breakAxes; breakInfo.annotationAxes = annotationAxes; breakInfo.invisibleObjects = invisibleObjects; end function list = RecursiveSetVisibleOff(handle) list = []; list = SetVisibleOff(handle,list); end function list = SetVisibleOff(handle, list) if (strcmp(get(handle,'Visible'),'on')) set(handle,'Visible','off'); list = [list handle]; end children = get(handle,'Children'); for i = 1:numel(children) list = SetVisibleOff(children(i),list); end end function annotationAxes = CreateAnnotaionAxes(mainAxes,mainParent) %Create Annotation Axis, Remove graphics objects, YAxis annotations %(except YLabel) and make background transparent annotationAxes = copyobj(mainAxes,mainParent); set(annotationAxes,'XLimMode','Manual'); children = get(annotationAxes,'Children'); for i = 1:numel(children) delete(children(i)); end %Save the yLabelpostion because it will move when we delete yAxis %ticks yLabel = get(annotationAxes,'YLabel'); yLabelPosition = get(yLabel,'Position'); set(annotationAxes,'YGrid' ,'off', ... 'YMinorGrid', 'off', ... 'YMinorTick','off', ... 'YTick', [], ... 'YTickLabel', []); %Restore the pevious label postition set(yLabel,'Position',yLabelPosition); end
github
oiwic/QOS-master
CodeCounter.m
.m
QOS-master/qos/+misc/CodeCounter.m
1,952
utf_8
f5c3c150cc96c24c020bbda733250130
function NumLines = CodeCounter(DirName,CodeFileSurfix) [FilePaths, FileNames]= GetAllFiles(DirName); NFiles = numel(FilePaths); ln_s = length(CodeFileSurfix); NumLines = 0; NumClasses = 0; NumFcns = 0; for ii = 1:NFiles if length(FileNames{ii}) < ln_s || ~strcmp(FileNames{ii}(end-ln_s+1:end),CodeFileSurfix) continue; end fid = fopen(fullfile(FilePaths{ii},FileNames{ii}),'r'); while ~feof(fid) [~] = fgetl(fid); NumLines = NumLines+1; end fclose(fid); end end function [FilePaths, FileNames]= GetAllFiles(DirName) % List all files within a folder, subfolders included. % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] DirData = dir(DirName); % Get the data for the current directory DirIndex = [DirData.isdir]; % Find the index for directories FileNames = {DirData(~DirIndex).name}'; % Get a list of the files NumFiles = length(FileNames); FilePaths = cell(NumFiles,1); for ii = 1:NumFiles FilePaths{ii} = DirName; end FullFileNames = []; if ~isempty(FileNames) FullFileNames = cellfun(@(x) fullfile(DirName,x),... % Prepend path to files FileNames,'UniformOutput',false); end SubDirs = {DirData(DirIndex).name}; % Get a list of the subdirectories ValidIndex = ~ismember(SubDirs,{'.','..'}); % Find index of subdirectories % that are not '.' or '..' for iDir = find(ValidIndex) % Loop over valid subdirectories NextDir = fullfile(DirName,SubDirs{iDir}); % Get the subdirectory path [FilePaths_, FileNames_] = GetAllFiles(NextDir); FilePaths = [FilePaths; FilePaths_]; % Recursively call GetAllFiles FileNames = [FileNames; FileNames_]; end end
github
oiwic/QOS-master
questdlg_multi.m
.m
QOS-master/qos/+qes/+ui/questdlg_multi.m
8,537
utf_8
eea135f1f91ae6fa64d606f59d7f8e2a
function choise=questdlg_multi(dlgOptions, dlgTitle, defOption, qStr, bttnsOredring) %% bttnChoiseDialog % Create and open a button dialog box with many buttons. % %% Syntax % bttnChoiseDialog(dlgOptions); % bttnChoiseDialog(dlgOptions, dlgTitle); % bttnChoiseDialog(dlgOptions, dlgTitle, defOption); % bttnChoiseDialog(dlgOptions,dlgTitle, defOption, qStr); % bttnChoiseDialog(dlgOptions, dlgTitle, defOption, qStr, bttnsOredring); % %% Description % Create and open a push button dialog box, which is a generalized version of a question % dialog box (called by questdlg). User can enter any number of input options (buttons) % for one to choose from, as opposed to questdlg, where only 2 or 3 options are % supported. User can also set the buttons ordering (columns, rows). Dialog will attempt % to set parameters to optimally present button text. % %% Input arguments (defaults exist): % dlgOptions- a cell array of strings, each of which is an option proposed to user as a % push button, for selection from. % dlgTitle- a 'title' displayed in the figure's title bar. Expected to be a string. A % space by default. % defOption- a default preset option, used if user makes no choise, and closes dilaog. Can % be either a string- one of the dlgOptions cell array elements, or an integer- the % dlgOptions elements index. % qStr- a string of the dialog question, instructing the user to choose among his options. % Expected to be a sting. Empty by default. % bttnsOredring- an 2X1 array of integers, describing the number of button rows and % columns. Default value exist. Similar to format used in subplot. % %% Output arguments % choise- index ot the user chosen (clicked) button. % %% Issues & Comments % Choosing the deafult button is achived by clicking it (naturally) or closing figure. If % functione wasn't exited properly, figure should be closed via inline delete(figH) % command. Clicking figure "X" mark on top left corner will fail, as it's overriden. % %% Example % inputOptions={'MATLAB', '(matrix laboratory)', 'is a numerical', 'computing',... % 'environment and 4G PL'}; % defSelection=inputOptions{3}; % iSel=bttnChoiseDialog(inputOptions, 'Demonstarte bttnChoiseDialog', defSelection,... % 'What is your preferred option?'); % fprintf( 'User selection "%s"\n', inputOptions{iSel}); % %% See also % - questdlg % %% Revision history % First version: Nikolay S. 2012-06-06. % Last update: Nikolay S. 2013-01-02. % % *List of Changes:* % -2013-01-02- An ossue reported by Dan K and Louis Vallance was fixed, % using Dan K proposal. % -2012-06-21- changed elements 'Units' to 'characters' instead of 'normalized' to % quarantee proper font size, cross platform. Changes root units back and foprth during % run time. % % Copyright (c) 2012, Nikolay S. % 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 % % 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. % Modified by Yulin Wu %% Default params if nargout>1 error('MATLAB:bttnChoiseDialog:WrongNumberOutputs',... 'Wrong number of output arguments for QUESTDLG'); end if nargin<1 error('MATLAB:bttnChoiseDialog:WrongNumberInputs',... 'Wrong number of input arguments for bttnChoiseDialog'); end if nargin==1 dlgTitle=' '; end if nargin<=2 defOption=dlgOptions{1}; end if nargin<=3 qStr=[]; titleSps=0; end if nargin<=4 bttnsOredring=[]; end if nargin>5 error('MATLAB:bttnChoiseDialog:TooManyInputs', 'Too many input arguments'); end % internal params bttnFontSize=0.6; btntxtH=2; %% Buttons ordering definition nButtons=length(dlgOptions); nLongestOption=max( cellfun(@length, dlgOptions) ); % Set buttons ordering- N Columns and N Rows if isempty (bttnsOredring) bttnsOredring=zeros(1, 2); bttnsOredring(1)=ceil( sqrt(nButtons) ); bttnsOredring(2)=ceil( nButtons/bttnsOredring(1) ); end if bttnsOredring(1)>1 && bttnsOredring(1)<=nButtons bttnRows=bttnsOredring(1); bttnCols=ceil( nButtons/bttnRows ); else if bttnsOredring(2)>1 && bttnsOredring(2)<=nButtons bttnCols=bttnsOredring(2); else bttnCols=floor(sqrt(nButtons)); end bttnRows=ceil( nButtons/bttnCols ); end if exist('titleSps', 'var')~=1 titleSps=1.25*btntxtH; % Title gets more space then buttons. end spaceH=0.5; spaceW=2; %% Dialog Figure definition % Open a figure about screen center menuFigH=figure('Units', 'normalized', 'Position', [.5, .5, .1, .1], 'MenuBar', 'none',... 'NumberTitle', 'off', 'Name', dlgTitle, 'CloseRequestFcn', @FigCloseRequestFcn); % 'CloseRequestFcn' override figure closing % make sure figure form allows good text representation Get screen resolution in % characters getRootUnits= get(0, 'Units'); set(0, 'Units', 'characters'); ScreenSize=get(0, 'ScreenSize'); % In characters set(0, 'Units', getRootUnits); set(menuFigH, 'Units', 'characters'); FigPos=get(menuFigH, 'Position'); figH=titleSps+(btntxtH+spaceH)*bttnRows+spaceH; figW=max( spaceW+btntxtH*bttnCols*(nLongestOption+spaceW),... titleSps*length(qStr)+2*spaceW ); if figW > ScreenSize(3) figW=ScreenSize(3); % raise some flag, figure Width will be too small, use textwrap... end if figH > ScreenSize(4) figH=ScreenSize(4); % raise some flag, figure Height will be too small end FigL=FigPos(1)-figW/2; FigB=FigPos(2)-figH/2; FigPos=[FigL, FigB, figW, figH]; % [left bottom width height] set(menuFigH, 'Position', FigPos); %% Button group definition iDefOption=1; buttonGroup = uibuttongroup('Parent', menuFigH, 'Position', [0 0 1 1]); if exist('defOption', 'var')==1 && ~isempty(defOption) if ischar(defOption) iDefOption=strcmpi(defOption, dlgOptions); elseif isnumeric(defOption) && defOption>1 && defOption<nButtons iDefOption=defOption; % defOption is an index of the default option end end %% Question definition if titleSps>0 titleH=uicontrol( buttonGroup, 'Style', 'text', 'String', qStr,... 'FontUnits', 'normalized', 'FontSize', bttnFontSize,... 'HorizontalAlignment', 'center', 'Units', 'characters',... 'Position', [spaceW , figH-titleSps, figW-2*spaceW, titleSps] ); end %% Radio buttons definition bttnH=max(1, (figH-titleSps-spaceH)/bttnRows-spaceH); interBttnStpH=bttnH+spaceH; bttnW=nLongestOption*btntxtH; interBttnStpW=max((figW-spaceW)/(bttnCols), bttnW+spaceW); buttnHndl=zeros(nButtons, 1); for iBttn=1:nButtons [iRow, iCol]=ind2sub([bttnRows, bttnCols],iBttn); currBttnHeigth=figH-titleSps-iRow*interBttnStpH; currBttnLeft=(iCol-1)*interBttnStpW+spaceW+(interBttnStpW-bttnW-spaceW)/2; buttnHndl(iBttn) = uicontrol( buttonGroup, 'Style', 'pushbutton',... 'FontUnits', 'normalized', 'Units', 'characters', 'FontSize', bttnFontSize,... 'String', dlgOptions{iBttn}, 'Callback', @my_bttnCallBack,... 'Position', [currBttnLeft , currBttnHeigth, bttnW, bttnH] ); end set(buttnHndl(iDefOption), 'Value', 1); % set default option set(cat(1, buttnHndl, titleH, buttonGroup),'Units', 'normalized') uiwait(menuFigH); % wait untill user makes his choise, or closes figure % choise=find( cell2mat( get(buttnHndl, 'Value') ) ); delete(menuFigH); function my_bttnCallBack(hObject, ~) choise=find(strcmp(dlgOptions,get(hObject,'String'))); uiresume(gcbf) end function FigCloseRequestFcn(src,ent) choise = []; uiresume(gcbf); end end
github
oiwic/QOS-master
waitbar2a.m
.m
QOS-master/qos/+qes/+ui/waitbar2a.m
16,130
utf_8
7e418c0b09e9df05a79f8a957d7bd145
function fout = waitbar2a(x, whichbar, varargin) % WAITBAR2a - Displays wait bar with fancy color shift effect % % Adaptation of the MatLab standard waitbar function: % % H = WAITBAR2A(X,'title', property, value, property, value, ...) % creates and displays a waitbar of fractional length X. The % handle to the waitbar figure is returned in H. % X should be between 0 and 1. Optional arguments property and % value allow to set corresponding waitbar figure properties. % Property can also be an action keyword 'CreateCancelBtn', in % which case a cancel button will be added to the figure, and % the passed value string will be executed upon clicking on the % cancel button or the close figure button. % % WAITBAR2A(X) will set the length of the bar in the most recently % created waitbar window to the fractional length X. % % WAITBAR2A(X, H) will set the length of the bar in waitbar H % to the fractional length X. % % WAITBAR2A(X, H), where H is the handle to a uipanel GUI object, will % initialize the waitbar inside that uipanel, rather than in its own % window. % % WAITBAR2A(X, H, 'updated title') will update the title text in % the waitbar figure, in addition to setting the fractional % length to X. % % WAITBAR2A is typically used inside a FOR loop that performs a % lengthy computation. A sample usage is shown below: % % h = waitbar2a(0,'Please wait...', 'BarColor', 'g'); % for i = 1:100, % % computation here % % waitbar2a(i/100, h); % end % close(h); % % Examples for the 'BarColor' option: % - Standard color names: 'red', 'blue', 'green', etcetera % - Standard color codes: 'r', 'b', 'k', etcetera % - A RGB vector, such as [.5 0 .5] (deep purple) % - Two RGB colors in a matrix, such as [1 0 0; 0 0 1] (gradient red-blue) % % The latter example shows how to create a custom color-shift effect. The top % row of the 2x3 matrix gives the initial color, and the bottom row the % end color. % % Clay M. Thompson 11-9-92 % Vlad Kolesnikov 06-7-99 % Jasper Menger 12-5-05 ['BarColor' option added, code cleaned up] % Ross L. Hatton 02-4-09 [Added option to put progress bar into a GUI % uipanel, and support for decrementing the waitbar display (useful for % resetting an embedded waitbar) % (Copyright 1984-2002 The MathWorks, Inc.) if nargin >= 2 if ischar(whichbar) % We are initializing type = 2; name = whichbar; % elseif isnumeric(whichbar) elseif isa(whichbar, 'matlab.ui.container.Panel') % check if the handle is a handle to an existing waitbar, or is the % handle of a uipanel to create a waitbar into if strcmp(get(whichbar,'Tag'),'TMWWaitbar') % We are updating an existing waitbar, given a handle type = 1; f = whichbar; elseif strcmp(get(whichbar,'Type'),'uipanel') % We are creating a new waitbar in an existing ui panel type = 3; f = whichbar; name = get(whichbar,'Title'); %pull the existing title, if any else error('Handle inputs should be either existing waitbars or uipanels') end else error(['Input arguments of type ', class(whichbar), ' not valid.']); end elseif nargin == 1 % If only given one argument, apply to the first waitbar, or create a % new one if none exist (this search will ignore waitbars which have % been embedded into uipanels) f = findobj(allchild(0), 'flat', 'Tag', 'TMWWaitbar'); if isempty(f) type = 2; name = 'Waitbar'; else type = 1; f = f(1); end else error('Input arguments not valid.'); end % Progress coordinate (0 - 100%) x = max(0, min(100 * x, 100)); switch type case 1 % waitbar(x) update p = findobj(f, 'Tag', 'progress'); l = findobj(f, 'Tag', 'background'); if isempty(f) || isempty(p) || isempty(l), error('Couldn''t find waitbar handles.'); end xpatch = [0 x x 0]; xline = get(l, 'XData'); udata = get(f, 'UserData'); b_map = udata.colormap; p_color = b_map(floor(x / 100 * (size(b_map,1)-1)) + 1, :); % Check to see if the waitbar is being decremented. If it is, then % temporarily set the erasemode of the progress bar to "normal" oldxpatch = get(p,'XData'); if x < oldxpatch(2) % Warning: The EraseMode property is no longer supported and will error in a future release. Use the ANIMATEDLINE function for animating lines and points instead of EraseMode 'none'. Removing % instances of EraseMode set to 'normal', 'xor', and 'background' has minimal impact. % warning('off'); % set(p,'EraseMode','normal'); % warning('on'); end set(p, 'XData' , xpatch); set(p, 'FaceColor', p_color); set(l, 'XData' , xline); if nargin > 2 % Update waitbar title hAxes = findobj(f, 'type', 'axes'); hTitle = get(hAxes, 'title'); set(hTitle, 'string', varargin{1}); end % make sure that the erase mode on the progress bar is back to "none" % set(p,'EraseMode','none') case 2 % waitbar(x,name) initialize vertMargin = 0; if nargin > 2 % we have optional arguments: property-value pairs if rem(nargin, 2) ~= 0 error( 'Optional initialization arguments must be passed in pairs' ); end end % Set units to points, and put the waitbar in the centre of the screen oldRootUnits = get(0,'Units'); set(0, 'Units', 'points'); screenSize = get(0,'ScreenSize'); axFontSize = get(0,'FactoryAxesFontSize'); pointsPerPixel = 72/get(0,'ScreenPixelsPerInch'); width = 360 * pointsPerPixel; height = 75 * pointsPerPixel; pos = [screenSize(3) / 2 - width / 2, ... screenSize(4) / 2 - height / 2, ... width, height]; f = figure(... 'Units' , 'points', ... 'BusyAction' , 'queue', ... 'Position' , pos, ... 'Resize' , 'off', ... 'CreateFcn' , '', ... 'NumberTitle' , 'off', ... 'IntegerHandle', 'off', ... 'MenuBar' , 'none', ... 'Interruptible', 'off', ... 'HandleVisibility','callback',... 'Visible' , 'off'); %Set the figure properties and get color information from input %arguments [f, waitbartext, cancelBtnFcn] = propset(f,varargin); %If the user called for the creation of a cancel button, make it if ~isempty(cancelBtnFcn) % Create a cancel button cancelBtnHeight = 23 * pointsPerPixel; cancelBtnWidth = 60 * pointsPerPixel; newPos = pos; vertMargin = vertMargin + cancelBtnHeight; newPos(4) = newPos(4) + vertMargin; callbackFcn = cancelBtnFcn; set(f, 'Position', newPos, 'CloseRequestFcn', callbackFcn); cancelButt = uicontrol(... 'Parent' , f, ... 'Units' , 'points', ... 'Callback' , callbackFcn, ... 'ButtonDownFcn', callbackFcn, ... 'Enable' , 'on', ... 'Interruptible', 'off', ... 'String' , 'Cancel', ... 'Tag' , 'TMWWaitbarCancelButton', ... 'Position' , [pos(3) - cancelBtnWidth * 1.4, 7, ... cancelBtnWidth, cancelBtnHeight]); end % ----------------------------------------------------------------- % Create axes axNorm = [.05 .3 .9 .2]; axPos = axNorm .* [pos(3:4), pos(3:4)] + [0 vertMargin 0 0]; ha = axes(... 'XLim' , [0 100], ... 'YLim' , [0 1], ... 'Box' , 'on', ... 'Units' , 'Points', ... 'FontSize' , axFontSize, ... 'Position' , axPos, ... 'XTickMode' , 'manual', ... 'YTickMode' , 'manual', ... 'XTick' , [], ... 'YTick' , [], ... 'XTickLabelMode', 'manual', ... 'XTickLabel' , [], ... 'YTickLabelMode', 'manual', ... 'YTickLabel' , []); % Display text on top of axes tHandle = title(name); tHandle = get(ha,'title'); oldTitleUnits = get(tHandle,'Units'); tExtent = get(tHandle,'Extent'); set(tHandle, 'Units', 'points', 'String', name, 'Units', oldTitleUnits); % Make sure the lay-out is OK titleHeight = tExtent(4) + axPos(2) + axPos(4) + 5; if titleHeight > pos(4) pos(4) = titleHeight; pos(2) = screenSize(4) / 2 - pos(4) / 2; figPosDirty = true; else figPosDirty = false; end if tExtent(3) > pos(3) * 1.1; pos(3) = min(tExtent(3) * 1.1, screenSize(3)); pos(1) = screenSize(3) / 2 - pos(3) / 2; axPos([1,3]) = axNorm([1, 3]) * pos(3); figPosDirty = true; set(ha, 'Position', axPos); end if figPosDirty set(f, 'Position', pos); end %Draw the progress bar draw_progress_bar(f,ha,x); % Make figure visible, and restore the original units set(f, 'HandleVisibility', 'Callback', 'Visible', 'on'); set(0, 'Units', oldRootUnits); case 3 % waitbar(x,uipanel_handle) initialize waitbar inside a uipanel if nargin > 2 % we have optional arguments: property-value pairs if rem(nargin, 2) ~= 0 error( 'Optional initialization arguments must be passed in pairs' ); end end %Get the default units and font size axFontSize = get(0,'FactoryAxesFontSize'); [f, waitbartext, cancelBtnFcn] = propset(f,varargin); %%%% %Geometry of the waitbar, relative to the uipanel bar_length = .96; bar_height = .4; bar_vertical_margin = .1; text_to_bar_height = .5; button_to_bar_height = .8; button_to_bar_length = .3; button_to_bar_right_align = 0; %derived measures bar_horizontal_margin = .5*(1-bar_length); center_above_bar = 1 - .5*(1-bar_height-bar_vertical_margin); %If the user called for the creation of a cancel button, make it if ~isempty(cancelBtnFcn) % Create a cancel button cancelBtnHeight = bar_height * button_to_bar_height; cancelBtnWidth = bar_length * button_to_bar_length; cancelBtnLeft = 1 - bar_horizontal_margin - ... button_to_bar_right_align - cancelBtnWidth; cancelBtnBottom = center_above_bar - .5*cancelBtnHeight; cancelBtnPos = [cancelBtnLeft cancelBtnBottom cancelBtnWidth cancelBtnHeight]; callbackFcn = [cancelBtnFcn]; cancelButt = uicontrol(... 'Parent' , f, ... 'Units' , 'normalized', ... 'Callback' , callbackFcn, ... 'ButtonDownFcn', callbackFcn, ... 'Enable' , 'on', ... 'Interruptible', 'off', ... 'String' , 'Cancel', ... 'Tag' , 'TMWWaitbarCancelButton', ... 'Position' , cancelBtnPos); end % ----------------------------------------------------------------- % Create axes for the bar axPos = [bar_horizontal_margin bar_vertical_margin bar_length bar_height]; ha = axes(... 'XLim' , [0 100], ... 'YLim' , [0 1], ... 'Box' , 'on', ... 'FontSize' , axFontSize, ... 'Position' , axPos, ... 'XTickMode' , 'manual', ... 'YTickMode' , 'manual', ... 'XTick' , [], ... 'YTick' , [], ... 'XTickLabelMode', 'manual', ... 'XTickLabel' , [], ... 'YTickLabelMode', 'manual', ... 'YTickLabel' , [], ... 'Parent' , f); % Display text on top of axes tHandle = title(ha,waitbartext,'FontUnits','normalized','FontSize',text_to_bar_height); %Initialize the progress bar draw_progress_bar(f,ha,x); % Make figure visible, and restore the original units set(f, 'HandleVisibility', 'Callback', 'Visible', 'on'); end % of case drawnow; % Pass on figure handles to output if nargout == 1, fout = f; end end %main function %Initialization function that handles common code for figure or uipanel %waitbars function [f, waitbartext, cancelBtnFcn] = propset(f,propargs) % Default color shift: dark red -> light barcolor1 = [0.5 0 0]; barcolor2 = [1.0 0 0]; %Set the tag to show that this is a waitbar set(f,'Tag','TMWWaitbar'); %set default waitbartext waitbartext = 'Waitbar'; %set default empty cancelbtnfcn cancelBtnFcn = []; %%%%%%%%%%%%%%%%%%%%% % set figure properties as passed to the function % pay special attention to the 'cancel' request % also, look for the 'waitbartext' option, which acts like 'name' when % initializing into a uipanel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin > 1 propList = propargs(1:2:end); valueList = propargs(2:2:end); cancelBtnCreated = 0; for ii = 1:length(propList) try if strcmpi(propList{ii}, 'createcancelbtn') cancelBtnFcn = valueList{ii}; elseif strcmpi(propList{ii}, 'barcolor') % Set color of waitbar barcolor = valueList{ii}; if ischar(barcolor) % Character color input: convert color code or name to RGB vector switch lower(barcolor) case {'r', 'red'} , barcolor2 = [1 0 0]; case {'g', 'green'} , barcolor2 = [0 1 0]; case {'b', 'blue'} , barcolor2 = [0 0 1]; case {'c', 'cyan'} , barcolor2 = [0 1 1]; case {'m', 'magenta'}, barcolor2 = [1 0 1]; case {'y', 'yellow'} , barcolor2 = [1 1 0]; case {'k', 'black'} , barcolor2 = [0 0 0]; case {'w', 'white'} , barcolor2 = [1 1 1]; otherwise , barcolor2 = rand(1, 3); end % Color shift: dark -> light barcolor1 = 0.5 * barcolor2; else % RGB vector color input barcolor1 = barcolor(1, :); if size(barcolor, 1) > 1 barcolor2 = barcolor(2, :); else barcolor2 = barcolor1; end end % of BarColor option elseif strcmpi(propList{ii}, 'waitbartext') waitbartext = valueList{ii}; else % simply set the prop/value pair of the figure set(f, propList{ii}, valueList{ii}); end catch % Something went wrong, so display warning warning('Could not set property ''%s'' with value ''%s'' ', propList{ii}, num2str(valueList{ii})); end % of try end % of proplist loop end % of setting figure properties % Create two color gradient colormap color_res = 64; b_map = [linspace(barcolor1(1),barcolor2(1),color_res)',... linspace(barcolor1(2),barcolor2(2),color_res)',... linspace(barcolor1(3),barcolor2(3),color_res)']; %Store the b_map into the userdata for the panel udata = get(f,'UserData'); %To make sure we don't wipe out any other UserData udata.colormap = b_map; set(f, 'UserData', udata); end function draw_progress_bar(f,ha,x) %get the colormap data udata = get(f,'UserData'); b_map = udata.colormap; % Draw the bar xprogress = [0 x x 0]; yprogress = [0 0 1 1]; xbackground = [100 0 0 100]; ybackground = [0 0 1 1]; p_color = b_map(floor(x / 100 * (size(b_map,1)-1)) + 1, :); l_color = get(ha, 'XColor'); % p = patch(xprogress, yprogress, p_color, 'Tag', 'progress', 'EdgeColor', 'none', 'EraseMode', 'none','Parent',ha); p = patch(xprogress, yprogress, p_color, 'Tag', 'progress', 'EdgeColor', 'none','Parent',ha); l = patch(xbackground, ybackground, 'w', 'Tag', 'background', 'FaceColor', 'none', 'EdgeColor', l_color,'Parent',ha); % l = patch(xbackground, ybackground, 'w', 'Tag', 'background', 'FaceColor', 'none', 'EdgeColor', l_color, 'EraseMode', 'none','Parent',ha); end
github
oiwic/QOS-master
questdlg_timer.m
.m
QOS-master/qos/+qes/+ui/questdlg_timer.m
16,415
utf_8
3fe834a1505c8cf39be0a7793f5f9c70
function ButtonName=questdlg_timer(TimeOutValue,Question,Title,Btn1,Btn2,Btn3,Default) %QUESTDLG_TIMER Question dialog box. % ButtonName = QUESTDLG_TIMER(Time, Question) creates a dialog box that % automatically wraps the cell array or string (vector or matrix) % Question to fit an appropriately sized window. The name of the % button that is pressed is returned in ButtonName. The Title of % the figure may be specified by adding a second string argument: % % ButtonName = questdlg_timer(Time, Question, Title) % % Question will be interpreted as a normal string. % % QUESTDLG_TIMER uses UIWAIT to suspend execution until user responds, OR % TimeOutValue is reached % % The default set of buttons names for QUESTDLG_TIMER are 'Yes','No' and % 'Cancel'. The default answer for the above calling syntax is 'Yes'. % This can be changed by adding a third argument which specifies the % default Button: % % ButtonName = questdlg_timer(Time, Question, Title, 'No') % % Up to 3 custom button names may be specified by entering % the button string name(s) as additional arguments to the function % call. If custom button names are entered, the default button % must be specified by adding an extra argument, DEFAULT, and % setting DEFAULT to the same string name as the button you want % to use as the default button: % % ButtonName = questdlg_timer(Time, Question, Title, Btn1, Btn2, DEFAULT); % % where DEFAULT is set to Btn1. This makes Btn1 the default answer. % If the DEFAULT string does not match any of the button string names, % a warning message is displayed. % % To use TeX interpretation for the Question string, a data % structure must be used for the last argument, i.e. % % ButtonName = questdlg_timer(Time, Question, Title, Btn1, Btn2, OPTIONS); % % The OPTIONS structure must include the fields Default and Interpreter. % Interpreter may be 'none' or 'tex' and Default is the default button % name to be used. % % If the dialog is closed without a valid selection, the return value % is empty. % % Example: % % ButtonName = questdlg_timer(15,'What is your favorite color?', ... % 'Color Question', ... % 'Red', 'Green', 'Blue', 'Green'); % switch ButtonName, % case 'Red', % disp('Your favorite color is Red'); % case 'Blue', % disp('Your favorite color is Blue.') % case 'Green', % disp('Your favorite color is Green.'); % end % switch % % See also DIALOG, ERRORDLG, HELPDLG, INPUTDLG, LISTDLG, % MSGBOX, WARNDLG, FIGURE, TEXTWRAP, UIWAIT, UIRESUME. % Modified from Matlab's questdlg.m %%%%%%%%%%%%%%%%%%%%%%%%% %%% Narg out/in Check %%% %%%%%%%%%%%%%%%%%%%%%%%%% if nargout>1 error('MATLAB:questdlg_timer:WrongNumberOutputs', 'Wrong number of output arguments for QUESTDLG_TIMER'); end if nargin<2 error('MATLAB:questdlg_timer:TooFewArguments', 'Too few arguments for QUESTDLG_TIMER'); end if ~isa(TimeOutValue, 'numeric') error('MATLAB:questdlg_timer:TimerValNotNumeric', 'Timer value has to be numeric') end if nargin==2, Title=' ';end if nargin<=3, Default='Yes';end if nargin==4, Default=Btn1 ;end if nargin<=4, Btn1='Yes'; Btn2='No'; Btn3='Cancel';NumButtons=3;end if nargin==5, Default=Btn2;Btn2=[];Btn3=[];NumButtons=1;end if nargin==6, Default=Btn3;Btn3=[];NumButtons=2;end if nargin==7, NumButtons=3;end if nargin>7 error('MATLAB:questdlg_timer:TooManyInputs', 'Too many input arguments');NumButtons=3; %#ok end Title=[Title,' ',num2str(TimeOutValue),' sec']; Interpreter='none'; if ~iscell(Question),Question=cellstr(Question);end if isstruct(Default), Interpreter=Default.Interpreter; Default=Default.Default; end %%%%%%%%%%%%%%%%%%%%% %%% General Info. %%% %%%%%%%%%%%%%%%%%%%%% Black =[0 0 0 ]/255; % LightGray =[192 192 192 ]/255; % LightGray2 =[160 160 164 ]/255; % MediumGray =[128 128 128 ]/255; % White =[255 255 255 ]/255; %%%%%%%%%%%%%%%%%%%%%%% %%% Create QuestFig %%% %%%%%%%%%%%%%%%%%%%%%%% FigPos = get(0,'DefaultFigurePosition'); FigPos(3) = 267; FigPos(4) = 70; FigPos = getnicedialoglocation(FigPos, get(0,'DefaultFigureUnits')); QuestFig=dialog( ... 'Visible' ,'off' , ... 'Name' ,Title , ... 'Pointer' ,'arrow' , ... 'Position' ,FigPos , ... 'KeyPressFcn' ,@doFigureKeyPress , ... 'IntegerHandle' ,'off' , ... 'WindowStyle' ,'normal' , ... 'HandleVisibility','callback' , ... 'CloseRequestFcn' ,@doDelete , ... 'Tag' ,Title ... ); %%%%%%%%%%%%%%%%%%%%% %%% Set Positions %%% %%%%%%%%%%%%%%%%%%%%% DefOffset =10; IconWidth =54; IconHeight =54; IconXOffset=DefOffset; IconYOffset=FigPos(4)-DefOffset-IconHeight; %#ok IconCMap=[Black;get(QuestFig,'Color')]; %#ok DefBtnWidth =56; BtnHeight =22; BtnYOffset=DefOffset; BtnWidth=DefBtnWidth; ExtControl=uicontrol(QuestFig , ... 'Style' ,'pushbutton', ... 'String' ,' ' ... ); btnMargin=1.4; set(ExtControl,'String',Btn1); BtnExtent=get(ExtControl,'Extent'); BtnWidth=max(BtnWidth,BtnExtent(3)+8); if NumButtons > 1 set(ExtControl,'String',Btn2); BtnExtent=get(ExtControl,'Extent'); BtnWidth=max(BtnWidth,BtnExtent(3)+8); if NumButtons > 2 set(ExtControl,'String',Btn3); BtnExtent=get(ExtControl,'Extent'); BtnWidth=max(BtnWidth,BtnExtent(3)*btnMargin); end end BtnHeight = max(BtnHeight,BtnExtent(4)*btnMargin); delete(ExtControl); MsgTxtXOffset=IconXOffset+IconWidth; FigPos(3)=max(FigPos(3),MsgTxtXOffset+NumButtons*(BtnWidth+2*DefOffset)); set(QuestFig,'Position',FigPos); BtnXOffset=zeros(NumButtons,1); if NumButtons==1, BtnXOffset=(FigPos(3)-BtnWidth)/2; elseif NumButtons==2, BtnXOffset=[MsgTxtXOffset FigPos(3)-DefOffset-BtnWidth]; elseif NumButtons==3, BtnXOffset=[MsgTxtXOffset 0 FigPos(3)-DefOffset-BtnWidth]; BtnXOffset(2)=(BtnXOffset(1)+BtnXOffset(3))/2; end MsgTxtYOffset=DefOffset+BtnYOffset+BtnHeight; MsgTxtWidth=FigPos(3)-DefOffset-MsgTxtXOffset-IconWidth; MsgTxtHeight=FigPos(4)-DefOffset-MsgTxtYOffset; MsgTxtForeClr=Black; MsgTxtBackClr=get(QuestFig,'Color'); CBString='uiresume(gcbf)'; DefaultValid = false; DefaultWasPressed = false; BtnHandle = []; DefaultButton = 0; % Check to see if the Default string passed does match one of the % strings on the buttons in the dialog. If not, throw a warning. for i = 1:NumButtons switch i case 1 ButtonString=Btn1; ButtonTag='Btn1'; if strcmp(ButtonString, Default) DefaultValid = true; DefaultButton = 1; end case 2 ButtonString=Btn2; ButtonTag='Btn2'; if strcmp(ButtonString, Default) DefaultValid = true; DefaultButton = 2; end case 3 ButtonString=Btn3; ButtonTag='Btn3'; if strcmp(ButtonString, Default) DefaultValid = true; DefaultButton = 3; end end BtnHandle(end+1)=uicontrol(QuestFig , ... 'Style' ,'pushbutton', ... 'Position' ,[ BtnXOffset(1) BtnYOffset BtnWidth BtnHeight ] , ... 'KeyPressFcn' ,@doControlKeyPress , ... 'CallBack' ,CBString , ... 'String' ,ButtonString, ... 'HorizontalAlignment','center' , ... 'Tag' ,ButtonTag ... ); end if ~DefaultValid warnstate = warning('backtrace','off'); warning('MATLAB:QUESTDLG_TIMER:stringMismatch','Default string does not match any button string name.'); warning(warnstate); end MsgHandle=uicontrol(QuestFig , ... 'Style' ,'text' , ... 'Position' ,[MsgTxtXOffset MsgTxtYOffset 0.95*MsgTxtWidth MsgTxtHeight ] , ... 'String' ,{' '} , ... 'Tag' ,'Question' , ... 'HorizontalAlignment','left' , ... 'FontWeight' ,'bold' , ... 'BackgroundColor' ,MsgTxtBackClr , ... 'ForegroundColor' ,MsgTxtForeClr ... ); [WrapString,NewMsgTxtPos]=textwrap(MsgHandle,Question,75); % NumLines=size(WrapString,1); AxesHandle=axes('Parent',QuestFig,'Position',[0 0 1 1],'Visible','off'); texthandle=text( ... 'Parent' ,AxesHandle , ... 'Units' ,'pixels' , ... 'Color' ,get(BtnHandle(1),'ForegroundColor') , ... 'HorizontalAlignment' ,'left' , ... 'FontName' ,get(BtnHandle(1),'FontName') , ... 'FontSize' ,get(BtnHandle(1),'FontSize') , ... 'VerticalAlignment' ,'bottom' , ... 'String' ,WrapString , ... 'Interpreter' ,Interpreter , ... 'Tag' ,'Question' ... ); %#ok textExtent = get(texthandle, 'extent'); % (g357851)textExtent and extent from uicontrol are not the same. For window, extent from uicontrol is larger %than textExtent. But on Mac, it is reverse. Pick the max value. MsgTxtWidth=max([MsgTxtWidth NewMsgTxtPos(3)+2 textExtent(3)]); MsgTxtHeight=max([MsgTxtHeight NewMsgTxtPos(4)+2 textExtent(4)]); MsgTxtXOffset=IconXOffset+IconWidth+DefOffset; FigPos(3)=max(NumButtons*(BtnWidth+DefOffset)+DefOffset, ... MsgTxtXOffset+MsgTxtWidth+DefOffset); % Center Vertically around icon if IconHeight>MsgTxtHeight, IconYOffset=BtnYOffset+BtnHeight+DefOffset; MsgTxtYOffset=IconYOffset+(IconHeight-MsgTxtHeight)/2; FigPos(4)=IconYOffset+IconHeight+DefOffset; % center around text else MsgTxtYOffset=BtnYOffset+BtnHeight+DefOffset; IconYOffset=MsgTxtYOffset+(MsgTxtHeight-IconHeight)/2; FigPos(4)=MsgTxtYOffset+MsgTxtHeight+DefOffset; end if NumButtons==1, BtnXOffset=(FigPos(3)-BtnWidth)/2; elseif NumButtons==2, BtnXOffset=[(FigPos(3)-DefOffset)/2-BtnWidth (FigPos(3)+DefOffset)/2 ]; elseif NumButtons==3, BtnXOffset(2)=(FigPos(3)-BtnWidth)/2; BtnXOffset=[BtnXOffset(2)-DefOffset-BtnWidth BtnXOffset(2) BtnXOffset(2)+BtnWidth+DefOffset ]; end set(QuestFig ,'Position',getnicedialoglocation(FigPos, get(QuestFig,'Units'))); BtnPos=get(BtnHandle,{'Position'}); BtnPos=cat(1,BtnPos{:}); BtnPos(:,1)=BtnXOffset; BtnPos=num2cell(BtnPos,2); set(BtnHandle,{'Position'},BtnPos); if DefaultValid setdefaultbutton(QuestFig, BtnHandle(DefaultButton)); end delete(MsgHandle); set(texthandle, 'Position',[MsgTxtXOffset MsgTxtYOffset 0]); IconAxes=axes( ... 'Parent' ,QuestFig , ... 'Units' ,'Pixels' , ... 'Position' ,[IconXOffset IconYOffset IconWidth IconHeight], ... 'NextPlot' ,'replace' , ... 'Tag' ,'IconAxes' ... ); set(QuestFig ,'NextPlot','add'); load dialogicons.mat questIconData questIconMap; IconData=questIconData; questIconMap(256,:)=get(QuestFig,'color'); IconCMap=questIconMap; Img=image('CData',IconData,'Parent',IconAxes); set(QuestFig, 'Colormap', IconCMap); set(IconAxes, ... 'Visible','off' , ... 'YDir' ,'reverse' , ... 'XLim' ,get(Img,'XData'), ... 'YLim' ,get(Img,'YData') ... ); % make sure we are on screen movegui(QuestFig) set(QuestFig ,'WindowStyle','modal','Visible','on'); % drawnow; if DefaultButton ~= 0 uicontrol(BtnHandle(DefaultButton)); end if ishghandle(QuestFig) % Go into uiwait if the figure handle is still valid. % This is mostly the case during regular use. uiwait(QuestFig,TimeOutValue); end % Check handle validity again since we may be out of uiwait because the % figure was deleted. if ishghandle(QuestFig) if DefaultWasPressed ButtonName=Default; else ButtonName=get(get(QuestFig,'CurrentObject'),'String'); end doDelete; else ButtonName=''; end function doFigureKeyPress(obj, evd) %#ok switch(evd.Key) case {'return','space'} if DefaultValid DefaultWasPressed = true; uiresume(gcbf); end case 'escape' doDelete end end function doControlKeyPress(obj, evd) %#ok switch(evd.Key) case {'return'} if DefaultValid DefaultWasPressed = true; uiresume(gcbf); end case 'escape' doDelete end end function doDelete(varargin) %#ok delete(QuestFig); end end %-------------------------------------------------------------------------- function setdefaultbutton(figHandle, btnHandle) % WARNING: This feature is not supported in MATLAB and the API and % functionality may change in a future release. %SETDEFAULTBUTTON Set default button for a figure. % SETDEFAULTBUTTON(BTNHANDLE) sets the button passed in to be the default button % (the button and callback used when the user hits "enter" or "return" % when in a dialog box. % % This function is used by inputdlg.m, msgbox.m, questdlg.m and % uigetpref.m. % % Example: % % f = figure; % b1 = uicontrol('style', 'pushbutton', 'string', 'first', ... % 'position', [100 100 50 20]); % b2 = uicontrol('style', 'pushbutton', 'string', 'second', ... % 'position', [200 100 50 20]); % b3 = uicontrol('style', 'pushbutton', 'string', 'third', ... % 'position', [300 100 50 20]); % setdefaultbutton(b2); % % Copyright 2005-2007 The MathWorks, Inc. %--------------------------------------- NOTE ------------------------------------------ % This file was copied into matlab/toolbox/local/private. % These two files should be kept in sync - when editing please make sure % that *both* files are modified. % Nargin Check if nargin<1, error('MATLAB:setdefaultbutton:InvalidNumberOfArguments','Too few arguments for setdefaultbutton'); end if nargin>2, error('MATLAB:setdefaultbutton:InvalidNumberOfArguments','Too many arguments for setdefaultbutton'); end if (usejava('awt') == 1) % We are running with Java Figures useJavaDefaultButton(figHandle, btnHandle) else % We are running with Native Figures useHGDefaultButton(figHandle, btnHandle); end function useJavaDefaultButton(figH, btnH) % Get a UDD handle for the figure. fh = handle(figH); % Call the setDefaultButton method on the figure handle fh.setDefaultButton(btnH); end function useHGDefaultButton(figHandle, btnHandle) % First get the position of the button. btnPos = getpixelposition(btnHandle); % Next calculate offsets. leftOffset = btnPos(1) - 1; bottomOffset = btnPos(2) - 2; widthOffset = btnPos(3) + 3; heightOffset = btnPos(4) + 3; % Create the default button look with a uipanel. % Use black border color even on Mac or Windows-XP (XP scheme) since % this is in natve figures which uses the Win2K style buttons on Windows % and Motif buttons on the Mac. h1 = uipanel(get(btnHandle, 'Parent'), 'HighlightColor', 'black', ... 'BorderType', 'etchedout', 'units', 'pixels', ... 'Position', [leftOffset bottomOffset widthOffset heightOffset]); % Make sure it is stacked on the bottom. uistack(h1, 'bottom'); end end %-------------------------------------------------------------------------- function figure_size = getnicedialoglocation(figure_size, figure_units) % adjust the specified figure position to fig nicely over GCBF % or into the upper 3rd of the screen % Copyright 1999-2006 The MathWorks, Inc. % $Revision: 1.1.6.3 $ %%%%%% PLEASE NOTE %%%%%%%%% %%%%%% This file has also been copied into: %%%%%% matlab/toolbox/ident/idguis %%%%%% If this functionality is changed, please %%%%%% change it also in idguis. %%%%%% PLEASE NOTE %%%%%%%%% parentHandle = gcbf; propName = 'Position'; if isempty(parentHandle) parentHandle = 0; propName = 'ScreenSize'; end old_u = get(parentHandle,'Units'); set(parentHandle,'Units',figure_units); container_size=get(parentHandle,propName); set(parentHandle,'Units',old_u); figure_size(1) = container_size(1) + 1/2*(container_size(3) - figure_size(3)); figure_size(2) = container_size(2) + 2/3*(container_size(4) - figure_size(4)); end
github
oiwic/QOS-master
freezeColors.m
.m
QOS-master/qos/+qes/+ui/+colormap/freezeColors.m
9,815
utf_8
2068d7a4f7a74d251e2519c4c5c1c171
function freezeColors(varargin) % freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3) % % Problem: There is only one colormap per figure. This function provides % an easy solution when plots using different colomaps are desired % in the same figure. % % freezeColors freezes the colors of graphics objects in the current axis so % that subsequent changes to the colormap (or caxis) will not change the % colors of these objects. freezeColors works on any graphics object % with CData in indexed-color mode: surfaces, images, scattergroups, % bargroups, patches, etc. It works by converting CData to true-color rgb % based on the colormap active at the time freezeColors is called. % % The original indexed color data is saved, and can be restored using % unfreezeColors, making the plot once again subject to the colormap and % caxis. % % % Usage: % freezeColors applies to all objects in current axis (gca), % freezeColors(axh) same, but works on axis axh. % % Example: % subplot(2,1,1); imagesc(X); colormap hot; freezeColors % subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc... % % Note: colorbars must also be frozen. Due to Matlab 'improvements' this can % no longer be done with freezeColors. Instead, please % use the function CBFREEZE by Carlos Adrian Vargas Aguilera % that can be downloaded from the MATLAB File Exchange % (http://www.mathworks.com/matlabcentral/fileexchange/24371) % % h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar) % % For additional examples, see test/test_main.m % % Side effect on render mode: freezeColors does not work with the painters % renderer, because Matlab doesn't support rgb color data in % painters mode. If the current renderer is painters, freezeColors % changes it to zbuffer. This may have unexpected effects on other aspects % of your plots. % % See also unfreezeColors, freezeColors_pub.html, cbfreeze. % % % John Iversen ([email protected]) 3/23/05 % % Changes: % JRI ([email protected]) 4/19/06 Correctly handles scaled integer cdata % JRI 9/1/06 should now handle all objects with cdata: images, surfaces, % scatterplots. (v 2.1) % JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded) % JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3) % JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it. % JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf) % JRI 4/7/10 Change documentation for colorbars % Hidden option for NaN colors: % Missing data are often represented by NaN in the indexed color % data, which renders transparently. This transparency will be preserved % when freezing colors. If instead you wish such gaps to be filled with % a real color, add 'nancolor',[r g b] to the end of the arguments. E.g. % freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]), % where [r g b] is a color vector. This works on images & pcolor, but not on % surfaces. % Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes % attributed in the code. % Free for all uses, but please retain the following: % Original Author: % John Iversen, 2005-10 % [email protected] appdatacode = 'JRI__freezeColorsData'; [h, nancolor] = checkArgs(varargin); %gather all children with scaled or indexed CData cdatah = getCDataHandles(h); %current colormap cmap = colormap; nColors = size(cmap,1); cax = caxis; % convert object color indexes into colormap to true-color data using % current colormap for hh = cdatah', g = get(hh); %preserve parent axis clim parentAx = getParentAxes(hh); originalClim = get(parentAx, 'clim'); % Note: Special handling of patches: For some reason, setting % cdata on patches created by bar() yields an error, % so instead we'll set facevertexcdata instead for patches. if ~strcmp(g.Type,'patch'), cdata = g.CData; else cdata = g.FaceVertexCData; end %get cdata mapping (most objects (except scattergroup) have it) if isfield(g,'CDataMapping'), scalemode = g.CDataMapping; else scalemode = 'scaled'; end %save original indexed data for use with unfreezeColors siz = size(cdata); setappdata(hh, appdatacode, {cdata scalemode}); %convert cdata to indexes into colormap if strcmp(scalemode,'scaled'), %4/19/06 JRI, Accommodate scaled display of integer cdata: % in MATLAB, uint * double = uint, so must coerce cdata to double % Thanks to O Yamashita for pointing this need out idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors); else %direct mapping idx = cdata; %10/8/09 in case direct data is non-int (e.g. image;freezeColors) % (Floor mimics how matlab converts data into colormap index.) % Thanks to D Armyr for the catch idx = floor(idx); end %clamp to [1, nColors] idx(idx<1) = 1; idx(idx>nColors) = nColors; %handle nans in idx nanmask = isnan(idx); idx(nanmask)=1; %temporarily replace w/ a valid colormap index %make true-color data--using current colormap realcolor = zeros(siz); for i = 1:3, c = cmap(idx,i); c = reshape(c,siz); c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified) realcolor(:,:,i) = c; end %apply new true-color color data %true-color is not supported in painters renderer, so switch out of that if strcmp(get(gcf,'renderer'), 'painters'), set(gcf,'renderer','zbuffer'); end %replace original CData with true-color data if ~strcmp(g.Type,'patch'), set(hh,'CData',realcolor); else set(hh,'faceVertexCData',permute(realcolor,[1 3 2])) end %restore clim (so colorbar will show correct limits) if ~isempty(parentAx), set(parentAx,'clim',originalClim) end end %loop on indexed-color objects % ============================================================================ % % Local functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% getCDataHandles -- get handles of all descendents with indexed CData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hout = getCDataHandles(h) % getCDataHandles Find all objects with indexed CData %recursively descend object tree, finding objects with indexed CData % An exception: don't include children of objects that themselves have CData: % for example, scattergroups are non-standard hggroups, with CData. Changing % such a group's CData automatically changes the CData of its children, % (as well as the children's handles), so there's no need to act on them. error(nargchk(1,1,nargin,'struct')) hout = []; if isempty(h),return;end ch = get(h,'children'); for hh = ch' g = get(hh); if isfield(g,'CData'), %does object have CData? %is it indexed/scaled? if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1, hout = [hout; hh]; %#ok<AGROW> %yes, add to list end else %no CData, see if object has any interesting children hout = [hout; getCDataHandles(hh)]; %#ok<AGROW> end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% getParentAxes -- return handle of axes object to which a given object belongs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hAx = getParentAxes(h) % getParentAxes Return enclosing axes of a given object (could be self) error(nargchk(1,1,nargin,'struct')) %object itself may be an axis if strcmp(get(h,'type'),'axes'), hAx = h; return end parent = get(h,'parent'); if (strcmp(get(parent,'type'), 'axes')), hAx = parent; else hAx = getParentAxes(parent); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% checkArgs -- Validate input arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [h, nancolor] = checkArgs(args) % checkArgs Validate input arguments to freezeColors nargs = length(args); error(nargchk(0,3,nargs,'struct')) %grab handle from first argument if we have an odd number of arguments if mod(nargs,2), h = args{1}; if ~ishandle(h), error('JRI:freezeColors:checkArgs:invalidHandle',... 'The first argument must be a valid graphics handle (to an axis)') end % 4/2010 check if object to be frozen is a colorbar if strcmp(get(h,'Tag'),'Colorbar'), if ~exist('cbfreeze.m'), warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',... ['You seem to be attempting to freeze a colorbar. This no longer'... 'works. Please read the help for freezeColors for the solution.']) else cbfreeze(h); return end end args{1} = []; nargs = nargs-1; else h = gca; end %set nancolor if that option was specified nancolor = [nan nan nan]; if nargs == 2, if strcmpi(args{end-1},'nancolor'), nancolor = args{end}; if ~all(size(nancolor)==[1 3]), error('JRI:freezeColors:checkArgs:badColorArgument',... 'nancolor must be [r g b] vector'); end nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0; else error('JRI:freezeColors:checkArgs:unrecognizedOption',... 'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1}) end end
github
oiwic/QOS-master
InitializeInstr.m
.m
QOS-master/qos/+qes/+hwdriver/+async/@MWSource/InitializeInstr.m
1,589
utf_8
e2612624ba84bfc05de506e45ee7bb44
function d = InitializeInstr(obj) % Initialize instrument % set reference oscillator source to auto: % Applying a 10 MHz signal to the Reference Oscillator connector automatically sets the % Reference Oscillator to EXTernal, when NO signal is present at the 10 MHz % Reference Oscillator connector, internal source is used. % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] TYP = lower(obj.drivertype); switch TYP case {'agle82xx','agle8200','agl e82xx','agl e8200'} % implement a deferred list [d1,d2,d3,d4] = Set_Agle82xx_rssma100_anritsu_mg36xx(obj); obj.freqlimits = [250e-6,40]; % GHz obj.powerlimits = [-120,20]; % dBm case {'rohde&schwarz sma100', 'r&s sma100'} d = Set_Agle82xx_rssma100_anritsu_mg36xx(obj); case {'anritsu_mg3692c'} d = Set_Agle82xx_rssma100_anritsu_mg36xx(obj); obj.freqlimits = [2e9,20e9]; % GHz obj.powerlimits = [-130,22]; % dBm otherwise d = mtwisted.defer.fail(... mtwisted.Failure(MException(... 'qes:hwdriver:MWSource:InitializeInstrFail',['Unsupported instrument: ',TYP]))); end end function [d1,d2,d3,d4] = Set_Agle82xx_rssma100_anritsu_mg36xx(obj) d1 = fprintf(obj.interfaceobj,'*RST'); d2 = fprintf(obj.interfaceobj,':SOUR:FREQ:MODE FIX'); d3 = fprintf(obj.interfaceobj,':SOUR:POW:MODE FIX'); d4 = fprintf(obj.interfaceobj,':ROSCillator:SOURce:AUTO ON'); end
github
oiwic/QOS-master
parseJson.m
.m
QOS-master/qos/+qes/+util/parseJson.m
5,633
utf_8
9c8d0e3758dd872b30beb58b1af01b63
function [data, json] = parseJson(json) % [DATA JSON] = PARSE_JSON(json) % This function parses a JSON(JavaScript Object Notation) string and % returns a cell array with the parsed data. JSON objects are converted % to structures and JSON arrays are converted to cell arrays. % % Example: % google_search = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=matlab'; % matlab_results = parse_json(urlread(google_search)); % disp(matlab_results{1}.responseData.results{1}.titleNoFormatting) % disp(matlab_results{1}.responseData.results{1}.visibleUrl) % by Joel Feenstra % Code used from: % http://www.mathworks.com/matlabcentral/fileexchange/20565 data = cell(0,1); while ~isempty(json) [value, json_] = parse_value(json); data{end+1} = value; %#ok<AGROW> if length(json_) == length(json) break; end json = json_; end % Yulin Wu if isempty(data) data = []; elseif numel(data) == 1 data = data{1}; end end function [value, json] = parse_value(json) value = []; if isempty(json) return; end id = json(1); json(1) = []; json = strtrim(json); switch lower(id) case '"' [value, json] = parse_string(json); case '{' [value, json] = parse_object(json); case '[' [value, json] = parse_array(json); case 't' value = true; if (length(json) >= 3) json(1:3) = []; else ME = MException('json:parse_value',['Invalid TRUE identifier: ' id json]); ME.throw; end case 'f' value = false; if (length(json) >= 4) json(1:4) = []; else ME = MException('json:parse_value',['Invalid FALSE identifier: ' id json]); ME.throw; end case 'n' value = []; if (length(json) >= 3) json(1:3) = []; else ME = MException('json:parse_value',['Invalid NULL identifier: ' id json]); ME.throw; end otherwise [value, json] = parse_number([id json]); % Need to put the id back on the string end end function [data, json] = parse_array(json) data = cell(0,1); while ~isempty(json) if strcmp(json(1),']') % Check if the array is closed json(1) = []; return end [value, json] = parse_value(json); if isempty(value) ME = MException('json:parse_array',['Parsed an empty value: ' json]); ME.throw; end data{end+1} = value; %#ok<AGROW> while ~isempty(json) && ~isempty(regexp(json(1),'[\s,]','once')) json(1) = []; end end end function [data, json] = parse_object(json) data = []; while ~isempty(json) id = json(1); json(1) = []; switch id case '"' % Start a name/value pair [name, value, remaining_json] = parse_name_value(json); if isempty(name) ME = MException('json:parse_object',['Can not have an empty name: ' json]); ME.throw; end data.(name) = value; json = remaining_json; case '}' % End of object, so exit the function return otherwise % Ignore other characters end end end function [name, value, json] = parse_name_value(json) name = []; value = []; if ~isempty(json) [name, json] = parse_string(json); % Skip spaces and the : separator while ~isempty(json) && ~isempty(regexp(json(1),'[\s:]','once')) json(1) = []; end [value, json] = parse_value(json); end end function [string, json] = parse_string(json) string = []; while ~isempty(json) letter = json(1); json(1) = []; switch lower(letter) case '\' % Deal with escaped characters if ~isempty(json) code = json(1); json(1) = []; switch lower(code) case '"' new_char = '"'; case '\' new_char = '\'; case '/' new_char = '/'; case {'b' 'f' 'n' 'r' 't'} new_char = sprintf('\%c',code); case 'u' if length(json) >= 4 new_char = sprintf('\\u%s',json(1:4)); json(1:4) = []; end otherwise new_char = []; end end case '"' % Done with the string return otherwise new_char = letter; end % Append the new character string = [string new_char]; %#ok<AGROW> end end function [num, json] = parse_number(json) num = []; if ~isempty(json) % Validate the floating point number using a regular expression [s, e] = regexp(json,'^[\w]?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?[\w]?','once'); if ~isempty(s) num_str = json(s:e); json(s:e) = []; num = str2double(strtrim(num_str)); end end end
github
oiwic/QOS-master
fminsearchbnd.m
.m
QOS-master/qos/+qes/+util/fminsearchbnd.m
8,543
utf_8
28a42661a739b30bd52aca73ca033601
function [x,fval,exitflag,output] = fminsearchbnd(fun,x0,LB,UB,options,varargin) % FMINSEARCHBND: FMINSEARCH, but with bound constraints by transformation % usage: x=FMINSEARCHBND(fun,x0) % usage: x=FMINSEARCHBND(fun,x0,LB) % usage: x=FMINSEARCHBND(fun,x0,LB,UB) % usage: x=FMINSEARCHBND(fun,x0,LB,UB,options) % usage: x=FMINSEARCHBND(fun,x0,LB,UB,options,p1,p2,...) % usage: [x,fval,exitflag,output]=FMINSEARCHBND(fun,x0,...) % % arguments: % fun, x0, options - see the help for FMINSEARCH % % LB - lower bound vector or array, must be the same size as x0 % % If no lower bounds exist for one of the variables, then % supply -inf for that variable. % % If no lower bounds at all, then LB may be left empty. % % Variables may be fixed in value by setting the corresponding % lower and upper bounds to exactly the same value. % % UB - upper bound vector or array, must be the same size as x0 % % If no upper bounds exist for one of the variables, then % supply +inf for that variable. % % If no upper bounds at all, then UB may be left empty. % % Variables may be fixed in value by setting the corresponding % lower and upper bounds to exactly the same value. % % Notes: % % If options is supplied, then TolX will apply to the transformed % variables. All other FMINSEARCH parameters should be unaffected. % % Variables which are constrained by both a lower and an upper % bound will use a sin transformation. Those constrained by % only a lower or an upper bound will use a quadratic % transformation, and unconstrained variables will be left alone. % % Variables may be fixed by setting their respective bounds equal. % In this case, the problem will be reduced in size for FMINSEARCH. % % The bounds are inclusive inequalities, which admit the % boundary values themselves, but will not permit ANY function % evaluations outside the bounds. These constraints are strictly % followed. % % If your problem has an EXCLUSIVE (strict) constraint which will % not admit evaluation at the bound itself, then you must provide % a slightly offset bound. An example of this is a function which % contains the log of one of its parameters. If you constrain the % variable to have a lower bound of zero, then FMINSEARCHBND may % try to evaluate the function exactly at zero. % % % Example usage: % rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2; % % fminsearch(rosen,[3 3]) % unconstrained % ans = % 1.0000 1.0000 % % fminsearchbnd(rosen,[3 3],[2 2],[]) % constrained % ans = % 2.0000 4.0000 % % See test_main.m for other examples of use. % % % See also: fminsearch, fminspleas % % % Author: John D'Errico % E-mail: [email protected] % Release: 4 % Release date: 7/23/06 % size checks xsize = size(x0); x0 = x0(:); n=length(x0); if (nargin<3) || isempty(LB) LB = repmat(-inf,n,1); else LB = LB(:); end if (nargin<4) || isempty(UB) UB = repmat(inf,n,1); else UB = UB(:); end if (n~=length(LB)) || (n~=length(UB)) error 'x0 is incompatible in size with either LB or UB.' end % set default options if necessary if (nargin<5) || isempty(options) options = optimset('fminsearch'); end % stuff into a struct to pass around params.args = varargin; params.LB = LB; params.UB = UB; params.fun = fun; params.n = n; % note that the number of parameters may actually vary if % a user has chosen to fix one or more parameters params.xsize = xsize; params.OutputFcn = []; % 0 --> unconstrained variable % 1 --> lower bound only % 2 --> upper bound only % 3 --> dual finite bounds % 4 --> fixed variable params.BoundClass = zeros(n,1); for i=1:n k = isfinite(LB(i)) + 2*isfinite(UB(i)); params.BoundClass(i) = k; if (k==3) && (LB(i)==UB(i)) params.BoundClass(i) = 4; end end % transform starting values into their unconstrained % surrogates. Check for infeasible starting guesses. x0u = x0; k=1; for i = 1:n switch params.BoundClass(i) case 1 % lower bound only if x0(i)<=LB(i) % infeasible starting value. Use bound. x0u(k) = 0; else x0u(k) = sqrt(x0(i) - LB(i)); end % increment k k=k+1; case 2 % upper bound only if x0(i)>=UB(i) % infeasible starting value. use bound. x0u(k) = 0; else x0u(k) = sqrt(UB(i) - x0(i)); end % increment k k=k+1; case 3 % lower and upper bounds if x0(i)<=LB(i) % infeasible starting value x0u(k) = -pi/2; elseif x0(i)>=UB(i) % infeasible starting value x0u(k) = pi/2; else x0u(k) = 2*(x0(i) - LB(i))/(UB(i)-LB(i)) - 1; % shift by 2*pi to avoid problems at zero in fminsearch % otherwise, the initial simplex is vanishingly small x0u(k) = 2*pi+asin(max(-1,min(1,x0u(k)))); end % increment k k=k+1; case 0 % unconstrained variable. x0u(i) is set. x0u(k) = x0(i); % increment k k=k+1; case 4 % fixed variable. drop it before fminsearch sees it. % k is not incremented for this variable. end end % if any of the unknowns were fixed, then we need to shorten % x0u now. if k<=n x0u(k:n) = []; end % were all the variables fixed? if isempty(x0u) % All variables were fixed. quit immediately, setting the % appropriate parameters, then return. % undo the variable transformations into the original space x = xtransform(x0u,params); % final reshape x = reshape(x,xsize); % stuff fval with the final value fval = feval(params.fun,x,params.args{:}); % fminsearchbnd was not called exitflag = 0; output.iterations = 0; output.funcCount = 1; output.algorithm = 'fminsearch'; output.message = 'All variables were held fixed by the applied bounds'; % return with no call at all to fminsearch return end % Check for an outputfcn. If there is any, then substitute my % own wrapper function. if ~isempty(options.OutputFcn) params.OutputFcn = options.OutputFcn; options.OutputFcn = @outfun_wrapper; end %%%%%%% % by Yulin Wu if isfield(options,'TolX') options.TolX = tolxtransform(options.TolX,params); end %%%%%%% % now we can call fminsearch, but with our own % intra-objective function. [xu,fval,exitflag,output] = fminsearch(@intrafun,x0u,options,params); % undo the variable transformations into the original space x = xtransform(xu,params); % final reshape to make sure the result has the proper shape x = reshape(x,xsize); % Use a nested function as the OutputFcn wrapper function stop = outfun_wrapper(x,varargin) % we need to transform x first xtrans = xtransform(x,params); % then call the user supplied OutputFcn stop = params.OutputFcn(xtrans,varargin{1:(end-1)}); end end % mainline end % ====================================== % ========= begin subfunctions ========= % ====================================== function fval = intrafun(x,params) % transform variables, then call original function % transform xtrans = xtransform(x,params); % and call fun fval = feval(params.fun,reshape(xtrans,params.xsize),params.args{:}); end % sub function intrafun end % ====================================== function xtrans = xtransform(x,params) % converts unconstrained variables into their original domains xtrans = zeros(params.xsize); % k allows some variables to be fixed, thus dropped from the % optimization. k=1; for i = 1:params.n switch params.BoundClass(i) case 1 % lower bound only xtrans(i) = params.LB(i) + x(k).^2; k=k+1; case 2 % upper bound only xtrans(i) = params.UB(i) - x(k).^2; k=k+1; case 3 % lower and upper bounds xtrans(i) = (sin(x(k))+1)/2; xtrans(i) = xtrans(i)*(params.UB(i) - params.LB(i)) + params.LB(i); % just in case of any floating point problems xtrans(i) = max(params.LB(i),min(params.UB(i),xtrans(i))); k=k+1; case 4 % fixed variable, bounds are equal, set it at either bound xtrans(i) = params.LB(i); case 0 % unconstrained variable. xtrans(i) = x(k); k=k+1; end end end % sub function xtransform end % ====================================== function xtrans = tolxtransform(tolx,params) % by Yulin Wu switch params.BoundClass(1) case {1,2} % lower/upper bound only xtrans = tolx^2; case 3 % lower and upper bounds xtrans = sin(abs(tolx)); otherwise xtrans = abs(tolx); end end
github
oiwic/QOS-master
hist2d.m
.m
QOS-master/qos/+qes/+util/hist2d.m
1,145
utf_8
c8febdddbcb3728cfcb0f6a26643686c
%function mHist = hist2d ([vY, vX], vYEdge, vXEdge) %2 Dimensional Histogram %Counts number of points in the bins defined by vYEdge, vXEdge. %size(vX) == size(vY) == [n,1] %size(mHist) == [length(vYEdge) -1, length(vXEdge) -1] % %EXAMPLE % mYX = rand(100,2); % vXEdge = linspace(0,1,10); % vYEdge = linspace(0,1,20); % mHist2d = hist2d(mYX,vYEdge,vXEdge); % % nXBins = length(vXEdge); % nYBins = length(vYEdge); % vXLabel = 0.5*(vXEdge(1:(nXBins-1))+vXEdge(2:nXBins)); % vYLabel = 0.5*(vYEdge(1:(nYBins-1))+vYEdge(2:nYBins)); % pcolor(vXLabel, vYLabel,mHist2d); colorbar function [vXLabel,vYLabel,mHist] = hist2d (X, Y, XBinEdges, YBinEdges) if length(X)~=length(Y) error ('X, Y length not equal.') end nRow = length (XBinEdges)-1; nCol = length (YBinEdges)-1; mHist = zeros(nRow,nCol); for iRow = 1:nRow rRowLB = XBinEdges(iRow); rRowUB = XBinEdges(iRow+1); vColFound = Y((X > rRowLB) & (X <= rRowUB)); if (~isempty(vColFound)) mHist(iRow, :)= histcounts(vColFound, YBinEdges); end end vXLabel = 0.5*(XBinEdges(1:end-1)+XBinEdges(2:end)); vYLabel = 0.5*(YBinEdges(1:end-1)+YBinEdges(2:end));
github
oiwic/QOS-master
ParseJson.m
.m
QOS-master/qos/+qes/+util/@pushover/ParseJson.m
5,509
utf_8
9afd107ad21f708a06345a7c1e8fc084
function [data, json] = ParseJson(json) % [DATA JSON] = PARSE_JSON(json) % This function parses a JSON(JavaScript Object Notation) string and % returns a cell array with the parsed data. JSON objects are converted % to structures and JSON arrays are converted to cell arrays. % % Example: % google_search = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=matlab'; % matlab_results = parse_json(urlread(google_search)); % disp(matlab_results{1}.responseData.results{1}.titleNoFormatting) % disp(matlab_results{1}.responseData.results{1}.visibleUrl) % by Joel Feenstra % Code used from: % http://www.mathworks.com/matlabcentral/fileexchange/20565 data = cell(0,1); while ~isempty(json) [value, json_] = parse_value(json); data{end+1} = value; %#ok<AGROW> if length(json_) == length(json) break; end json = json_; end end function [value, json] = parse_value(json) value = []; if isempty(json) return; end id = json(1); json(1) = []; json = strtrim(json); switch lower(id) case '"' [value, json] = parse_string(json); case '{' [value, json] = parse_object(json); case '[' [value, json] = parse_array(json); case 't' value = true; if (length(json) >= 3) json(1:3) = []; else ME = MException('json:parse_value',['Invalid TRUE identifier: ' id json]); ME.throw; end case 'f' value = false; if (length(json) >= 4) json(1:4) = []; else ME = MException('json:parse_value',['Invalid FALSE identifier: ' id json]); ME.throw; end case 'n' value = []; if (length(json) >= 3) json(1:3) = []; else ME = MException('json:parse_value',['Invalid NULL identifier: ' id json]); ME.throw; end otherwise [value, json] = parse_number([id json]); % Need to put the id back on the string end end function [data, json] = parse_array(json) data = cell(0,1); while ~isempty(json) if strcmp(json(1),']') % Check if the array is closed json(1) = []; return end [value, json] = parse_value(json); if isempty(value) ME = MException('json:parse_array',['Parsed an empty value: ' json]); ME.throw; end data{end+1} = value; %#ok<AGROW> while ~isempty(json) && ~isempty(regexp(json(1),'[\s,]','once')) json(1) = []; end end end function [data, json] = parse_object(json) data = []; while ~isempty(json) id = json(1); json(1) = []; switch id case '"' % Start a name/value pair [name, value, remaining_json] = parse_name_value(json); if isempty(name) ME = MException('json:parse_object',['Can not have an empty name: ' json]); ME.throw; end data.(name) = value; json = remaining_json; case '}' % End of object, so exit the function return otherwise % Ignore other characters end end end function [name, value, json] = parse_name_value(json) name = []; value = []; if ~isempty(json) [name, json] = parse_string(json); % Skip spaces and the : separator while ~isempty(json) && ~isempty(regexp(json(1),'[\s:]','once')) json(1) = []; end [value, json] = parse_value(json); end end function [string, json] = parse_string(json) string = []; while ~isempty(json) letter = json(1); json(1) = []; switch lower(letter) case '\' % Deal with escaped characters if ~isempty(json) code = json(1); json(1) = []; switch lower(code) case '"' new_char = '"'; case '\' new_char = '\'; case '/' new_char = '/'; case {'b' 'f' 'n' 'r' 't'} new_char = sprintf('\%c',code); case 'u' if length(json) >= 4 new_char = sprintf('\\u%s',json(1:4)); json(1:4) = []; end otherwise new_char = []; end end case '"' % Done with the string return otherwise new_char = letter; end % Append the new character string = [string new_char]; %#ok<AGROW> end end function [num, json] = parse_number(json) num = []; if ~isempty(json) % Validate the floating point number using a regular expression [s, e] = regexp(json,'^[\w]?[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?[\w]?','once'); if ~isempty(s) num_str = json(s:e); json(s:e) = []; num = str2double(strtrim(num_str)); end end end
github
oiwic/QOS-master
OneMeas_Def.m
.m
QOS-master/qos/+qes/+util/+plotfcn/OneMeas_Def.m
21,129
utf_8
904024cdd5e7b8ef5ebeb2397709996a
function [varargout] = OneMeas_Def(Data, SweepVals,ParamNames,MainParam,MeasurementName,AX,IsPreview) % default plot function for data: % One measurement, measure data are scalar, array or % maxtrix. % 2D data is transposed to take the convention of a spectrum plot, the first sweep is taken as y % This is the default plot function for class Experiment and DataViewer. % varargout: data parsed from QES format to simple x, y and z, % varargout{1} is x, varargout{2} is y, varargout{3} is z, if % not exist in data, an empty matrix is returned, for example, % varargout{3} will be an empty matrix if there is no z data. % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] nSwps = numel(SweepVals); a = numel(MainParam); if a < nSwps MainParam = [MainParam, ones(1,nSwps-a)]; end if nargin < 7 IsPreview = false; end if (iscell(Data{1}) && ~isempty(Data{1}{1}) && ~isreal(Data{1}{1}(1))) ||... (~iscell(Data{1}) && ~isreal(Data{1}(1))) [x,y,z] = OneMeasComplex_Def(Data, SweepVals,ParamNames,MainParam,MeasurementName,AX,IsPreview); else [x,y,z] = OneMeasReal_Def(Data, SweepVals,ParamNames,MainParam,MeasurementName,AX,IsPreview); end varargout{1} = x; varargout{2} = y; varargout{3} = z; end function [varargout] = OneMeasReal_Def(Data, SweepVals,ParamNames,MainParam,MeasurementName,AX,IsPreview) % default plot function for data: % One measurement, measure data are real number scalar, array or % maxtrix. % 2D data is transposed to take the convention of a spectrum plot, the first sweep is taken as y % This is the default plot function for class Experiment and DataViewer. % varargout: data parsed from QES format to simple x, y and z, % varargout{1} is x, varargout{2} is y, varargout{3} is z, if % not exist in data, an empty matrix is returned, for example, % varargout{3} will be an empty matrix if there is no z data. % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] x = []; y = []; z = []; if isempty(Data) || isempty(Data{1}) || isempty(SweepVals) ||... (iscell(Data{1}) && isempty(Data{1}{1})) varargout{1} = x; varargout{2} = y; varargout{3} = z; plot(AX,NaN,NaN); XLIM = get(AX,'XLim'); YLIM = get(AX,'YLim'); text('Parent',AX,'Position',[mean(XLIM),mean(YLIM)],'String','Empty data',... 'HorizontalAlignment','center','VerticalAlignment','middle',... 'Color',[1,0,0],'FontSize',10,'FontWeight','bold'); return; end if nargin < 7 IsPreview = false; end if (iscell(Data{1}) && ~isreal(Data{1}{1}(1))) ||... (~iscell(Data{1}) && ~isreal(Data{1}(1))) error('OneMeasReal_* only handles numeric real data.'); end if length(Data) > 1 error('OneMeasReal_* only handles data of experiments with one measurement.'); end Data = Data{1}; hold(AX,'off'); NumSweeps = numel(SweepVals); if NumSweeps == 1 if length(SweepVals{1}{MainParam(1)}) == 1 % single sweep, single sweep point measurement if iscell(Data) % in case of numeric scalar measurement data, data may saved as matrix to reduce volume Data = Data{1}; end Data = squeeze(Data); sz = size(Data); % sz is the size of each data point if length(sz) == 2 % scalar, array or 2D matrix if any(sz == 1) % 1D data x = []; y = Data(:)'; z = []; plot(AX,y,'Color',[0,0.3,1]); xlim = [0,length(y)+1]; dr = range(y); ylim = [min(y)-0.1*dr,max(y)+0.1*dr]; if all(~isnan(xlim)) && xlim(2) > xlim(1) set(AX,'XLim',xlim); end if all(~isnan(ylim)) && ylim(2) > ylim(1) set(AX,'YLim',ylim); end if ~IsPreview xlabel(AX,'Data Index'); ylabel(AX, MeasurementName{1}); end else % 2D data, each measurement data point is a matrix x = []; y = []; z = Data; imagesc(z','Parent',AX); % transpose Data to take the convention of spectrum, the first sweep is taken y if ~IsPreview colormap(jet); colorbar('peer',AX); end set(AX,'YDir','normal'); if ~IsPreview xlabel(AX,'Data Index 1'); ylabel(AX,'Data Index 2'); end end else % more than 2D data, too complex to plot. error('data too complex to be handled by this plot function.'); end elseif length(SweepVals{1}{MainParam(1)}) > 1 % single sweep, multipoint sweep point measurement if iscell(Data) % sz is the size of each data point sz = size(squeeze(Data{1})); else sz = [1, 1]; end if all(sz > 1) || length(sz) > 2 % error('data too complex to be handled by this plot function.'); else if all(sz== 1) % 1D data, each measurement data point is a scalar if iscell(Data) % in case of numeric scalar measurement data, data may saved as matrix to reduce volume sz_d = size(Data); for ii = 1:sz_d(1) for jj = 1:sz_d(2) Data{ii,jj} = squeeze(Data{ii,jj}); if isempty(Data{ii,jj}) Data{ii,jj} = NaN; % fill empties with NaNs end end end Data = cell2mat(Data); end x = SweepVals{1}{MainParam(1)}(:)'; y = Data(:)'; z = []; plot(AX,x,y,'Color',[0,0.3,1]); xlim = [x(1),x(end)]; dr = range(y); ylim = [min(y)-0.1*dr,max(y)+0.1*dr]; if all(~isnan(xlim)) && xlim(2) > xlim(1) set(AX,'XLim',xlim); end if all(~isnan(ylim)) && ylim(2) > ylim(1) set(AX,'YLim',ylim); end if ~IsPreview xlabel(AX,ParamNames{1}{MainParam(1)}); if iscell(MeasurementName) % deals with a bug in old version data ylabel(AX, MeasurementName{1}); end end else % 2D data, each measurement data point is an array, in this case Data can only be a cell swpsize = length(SweepVals{1}{MainParam(1)}); data = NaN*ones(swpsize,numel(Data{1})); for ii = 1:swpsize if ~isempty(Data{ii}(:)) data(ii,:) = Data{ii}(:); % Nx1 should be converted to 1xN end end x = SweepVals{1}{MainParam(1)}(:)'; y = 1:sz(2); z = data; imagesc(x, y, z','Parent',AX); % transpose Data to take the convention of spectrum, the first sweep is taken y set(AX,'YDir','normal'); if ~IsPreview colormap(jet); colorbar('peer',AX); xlabel(AX,ParamNames{1}{MainParam(1)}); ylabel(AX, 'Unknonwn'); end end end end elseif NumSweeps == 2 if iscell(Data) && numel(Data{1}) > 1 % in cases of more than one sweeps, each measurement data point can only be a scalar, otherwise it is too complex to be plotted. error('data too complex to be handled by this plot function.'); end if iscell(Data) % in case of numeric scalar measurement data, data may saved as matrix to reduce volume sz = size(Data); for ii = 1:sz(1) for jj = 1:sz(2) Data{ii,jj} = squeeze(Data{ii,jj}); if isempty(Data{ii,jj}) Data{ii,jj} = NaN; % fill empties with NaNs end end end Data = cell2mat(Data); end sz = size(Data); % if all(sz==1) % warning('single data point measurement experiment, to plot, have at least two data points.'); % return; % single point measurement, this is the case of having multiple sweeps, yet all sweeps are only having one sweep point. % end if all(sz>1) % 2D data x = SweepVals{1}{MainParam(1)}(:)'; y = SweepVals{2}{MainParam(2)}(:)'; z = Data; imagesc(x,y,z','Parent',AX); % transpose Data to take the convention of spectrum, the first sweep is taken y set(AX,'YDir','normal'); if ~IsPreview colormap(jet); colorbar('peer',AX); xlabel(AX,ParamNames{1}{MainParam(1)}); ylabel(AX,ParamNames{2}{MainParam(2)}); end else % 1D data if sz(1)==1 x = SweepVals{2}{MainParam(2)}(:)'; y = Data(:)'; z = []; plot(AX,x,y,'Color',[0,0.3,1]); if ~IsPreview xlabel(AX,ParamNames{2}{MainParam(2)}); ylabel(AX,MeasurementName{1}); end else x = SweepVals{1}{MainParam(1)}(:)'; y = Data(:)'; z = []; plot(AX,x,y,'Color',[0,0.3,1]); if ~IsPreview xlabel(AX,ParamNames{1}{MainParam(1)}); ylabel(AX,MeasurementName{1}); end end xlim = [x(1),x(end)]; dr = range(y); ylim = [min(y)-0.1*dr,max(y)+0.1*dr]; if all(~isnan(xlim)) && xlim(2) > xlim(1) set(AX,'XLim',xlim); end if all(~isnan(ylim)) && ylim(2) > ylim(1) set(AX,'YLim',ylim); end end else % more than 2 sweeps error('data too complex to be handled by this plot function.'); end varargout{1} = x; varargout{2} = y; varargout{3} = z; end function [varargout] = OneMeasComplex_Def(Data, SweepVals,ParamNames,MainParam,MeasurementName,AX,IsPreview) % default plot function for data: % One measurement, measure data are complex number scalar, array or % maxtrix. % 2D data is transposed to take the convention of a spectrum plot, the first sweep is taken as y % This is the default plot function for class Experiment and DataViewer. % varargout: data parsed from QES format to simple x, y and z, % varargout{1} is x, varargout{2} is y, varargout{3} is z, if % not exist in data, an empty matrix is returned, for example, % varargout{3} will be an empty matrix if there is no z data. % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] x = []; y = []; z = []; if isempty(Data) || isempty(Data{1}) || isempty(SweepVals) ||... (iscell(Data{1}) && isempty(Data{1}{1})) varargout{1} = x; varargout{2} = y; varargout{3} = z; plot(AX,NaN,NaN); XLIM = get(AX,'XLim'); YLIM = get(AX,'YLim'); text('Parent',AX,'Position',[mean(XLIM),mean(YLIM)],'String','Empty data',... 'HorizontalAlignment','center','VerticalAlignment','middle',... 'Color',[1,0,0],'FontSize',10,'FontWeight','bold'); return; end if nargin < 7 IsPreview = false; end if length(Data) > 1 error('OneMeasComplex_* only handles data of experiments with one measurement.'); end Data = Data{1}; hold(AX,'off'); NumSweeps = numel(SweepVals); if NumSweeps == 1 if length(SweepVals{1}{MainParam(1)}) == 1 % single sweep, single sweep point measurement if iscell(Data) % in case of numeric scalar measurement data, data may saved as matrix to reduce volume Data = Data{1}; end Data = squeeze(Data); sz = size(Data); if length(sz) == 2 % scalar, array or 2D matrix if any(sz == 1) % 1D data x = []; y = Data(:)'; z = []; x_ = real(y); y_ = imag(y); plot(AX,x_,y_,'Color',[0,0.3,1]); dr = range(x_); xlim = [min(x_)-0.1*dr,max(x_)+0.1*dr]; dr = range(y_); ylim = [min(y_)-0.1*dr,max(y_)+0.1*dr]; if all(~isnan(xlim)) && xlim(2) > xlim(1) set(AX,'XLim',xlim); end if all(~isnan(ylim)) && ylim(2) > ylim(1) set(AX,'YLim',ylim); end if ~IsPreview xlabel(AX,['Re[',MeasurementName{1},']']); ylabel(AX, ['Im[',MeasurementName{1},']']); end else % 2D data, each measurement data point is a matrix x = []; y = []; z = Data; z_ = abs(z); imagesc(z_','Parent',AX); % transpose Data to take the convention of spectrum, the first sweep is taken y if ~IsPreview colormap(jet); colorbar('peer',AX); end set(AX,'YDir','normal'); if ~IsPreview xlabel(AX,'Data Index 1(color scale: amplitude)'); ylabel(AX,'Data Index 2(color scale: amplitude)'); end end else % more than 2D data, too complex to plot. error('data too complex to be handled by this plot function.'); end elseif length(SweepVals{1}{MainParam(1)}) > 1 % single sweep, multipoint sweep point measurement if iscell(Data) sz = size(squeeze(Data{1})); else sz = [1, 1]; end if all(sz > 1) || length(sz) > 2 % error('data too complex to be handled by this plot function.'); else if all(sz== 1) % 1D data, each measurement data point is a scalar if iscell(Data) % in case of numeric scalar measurement data, data may saved as matrix to reduce volume sz_d = size(Data); for ii = 1:sz_d(1) for jj = 1:sz_d(2) Data{ii,jj} = squeeze(Data{ii,jj}); if isempty(Data{ii,jj}) Data{ii,jj} = NaN; % fill empties with NaNs end end end Data = cell2mat(Data); end x = SweepVals{1}{MainParam(1)}(:)'; y = Data(:)'; z = []; y_ = abs(y); plot(AX,x,y_,'Color',[0,0.3,1]); xlim = [x(1),x(end)]; dr = range(y_); ylim = [min(y_)-0.1*dr,max(y_)+0.1*dr]; if all(~isnan(xlim)) && xlim(2) > xlim(1) set(AX,'XLim',xlim); end if all(~isnan(ylim)) && ylim(2) > ylim(1) set(AX,'YLim',ylim); end if ~IsPreview xlabel(AX,ParamNames{1}{MainParam(1)}); if iscell(MeasurementName) % deals with a bug in old version data ylabel(AX, ['Amplitude of ', MeasurementName{1}]); end end else % 2D data, each measurement data point is an array, in this case Data can only be a cell swpsize = length(SweepVals{1}{MainParam(1)}); data = NaN*ones(swpsize,numel(Data{1})); for ii = 1:swpsize if ~isempty(Data{ii}(:)) data(ii,:) = Data{ii}(:); % Nx1 should be converted to 1xN end end x = SweepVals{1}{MainParam(1)}(:)'; y = 1:sz(2); z = data; z_ = abs(z); imagesc(x, y, z_','Parent',AX); % transpose Data to take the convention of spectrum, the first sweep is taken y set(AX,'YDir','normal'); if ~IsPreview colormap(jet); colorbar('peer',AX); xlabel(AX,ParamNames{1}{MainParam(1)}); ylabel(AX, 'Unknonwn, colorbar: amplitude of data'); end end end end elseif NumSweeps == 2 if iscell(Data) && numel(Data{1}) > 1 % in cases of more than one sweeps, each measurement data point can only be a scalar, otherwise it is too complex to be plotted. error('data too complex to be handled by this plot function.'); end if iscell(Data) % in case of numeric scalar measurement data, data may saved as matrix to reduce volume sz = size(Data); for ii = 1:sz(1) for jj = 1:sz(2) Data{ii,jj} = squeeze(Data{ii,jj}); if isempty(Data{ii,jj}) Data{ii,jj} = NaN; % fill empties with NaNs end end end Data = cell2mat(Data); end sz = size(Data); % if all(sz==1) % warning('single data point measurement experiment, to plot, have at least two data points.'); % return; % single point measurement, this is the case of having multiple sweeps, yet all sweeps are only having one sweep point. % end if all(sz>1) % 2D data x = SweepVals{1}{MainParam(1)}(:)'; y = SweepVals{2}{MainParam(2)}(:)'; z = Data; z_ = abs(z); imagesc(x,y,z_','Parent',AX); % transpose Data to take the convention of spectrum, the first sweep is taken y set(AX,'YDir','normal'); if ~IsPreview colormap(jet); colorbar('peer',AX); xlabel(AX,ParamNames{1}{MainParam(1)}); ylabel(AX,[ParamNames{2}{MainParam(2)},'(colorbar: amplitude of data)']); end else % 1D data if sz(1)==1 x = SweepVals{2}{MainParam(2)}(:)'; y = Data(:)'; z = []; y_ = abs(y); plot(AX,x,y_,'Color',[0,0.3,1]); if ~IsPreview xlabel(AX,ParamNames{2}{MainParam(2)}); ylabel(AX,['Amplitude of ', MeasurementName{1}]); end else x = SweepVals{1}{MainParam(1)}(:)'; y = Data(:)'; z = []; y_ = abs(y); plot(AX,x,y_,'Color',[0,0.3,1]); if ~IsPreview xlabel(AX,ParamNames{1}{MainParam(1)}); ylabel(AX,['Amplitude of ', MeasurementName{1}]); end end xlim = [x(1),x(end)]; dr = range(y_); ylim = [min(y_)-0.1*dr,max(y_)+0.1*dr]; if all(~isnan(xlim)) && xlim(2) > xlim(1) set(AX,'XLim',xlim); end if all(~isnan(ylim)) && ylim(2) > ylim(1) set(AX,'YLim',ylim); end end else % more than 2 sweeps error('data too complex to be handled by this plot function.'); end varargout{1} = x; varargout{2} = y; varargout{3} = z; end
github
oiwic/QOS-master
CreateGUI.m
.m
QOS-master/qos/+qes/+app/@OxfordDRMonitor/CreateGUI.m
9,662
utf_8
a1d1b5c439f3d5d63e97f15cdfb97d17
function CreateGUI(obj) % % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] AlertSchemeOptions = {'Idle','Base Temperature','Warming up','Cooling down','No Alert'}; choice = questdlg_multi(AlertSchemeOptions, 'Alert options', 'No Alert', 'Select an alert scheme:'); if isempty(choice) obj.process = length(AlertSchemeOptions); else obj.process = choice; end BkGrndColor = [0.941 0.941 0.941]; if isempty(obj.parent) || ~ishghandle(obj.parent) obj.parent = figure('NumberTitle','off','MenuBar','none','Toolbar','none',... 'Name',['QOS | Dilution Fridge | ', obj.fridgeobj.name],... 'HandleVisibility','callback','Color',BkGrndColor,... 'CloseRequestFcn',{@ExitCbk},'UserData',obj,'DockControls','off','Visible','off'); tb = uitoolbar(obj.parent); uitoggletool(tb,'CData',icons.ZoomIn,'TooltipString','Zoom In','ClickedCallback','putdowntext(''zoomin'',gcbo)'); uitoggletool(tb,'CData',icons.ZoomOut,'TooltipString','Zoom Out','ClickedCallback','putdowntext(''zoomout'',gcbo)'); uipushtool(tb,'CData',icons.DoubleArrow,'TooltipString','Restore Axes Range','ClickedCallback',{@RestoreAxesRange},'UserData',obj); uitoggletool(tb,'CData',icons.Datatip,'TooltipString','Data Cursor','ClickedCallback','putdowntext(''datatip'',gcbo)','Separator','on'); movegui(obj.parent,'center'); else return; end ParentUnitOrig = get(obj.parent,'Units'); set(obj.parent,'Units','characters'); ParentPosOrig = get(obj.parent,'Position'); panelpossize = [0,0,200,47]; set(obj.parent,'Position',[ParentPosOrig(1),ParentPosOrig(2),panelpossize(3),panelpossize(4)]); set(obj.parent,'Units',ParentUnitOrig); % restore to original units. handles.basepanel = uipanel(... 'Parent',obj.parent,... 'Units','characters',... 'Position',panelpossize,... 'backgroundColor',BkGrndColor,... 'Title','',... 'BorderType','none',... 'HandleVisibility','callback',... 'visible','on',... 'Tag','parameterpanel','DeleteFcn',{@GUIDeleteCallback}); movegui(obj.parent,'center'); pos = [13,3.5,120,19]; if obj.time(1)<obj.time(obj.dpoint) xlimits = [obj.time(1),obj.time(obj.dpoint)]; else xlimits = [now-2,now+0.5]; end obj.temperatureax = axes('Parent',obj.parent,... 'Units','characters','Position',pos,... 'Box','on','Units','characters','YScal','log',... 'XLim',xlimits,'YLim',[5e-3,400]); pos = [12,4,120,19]; pos(2) = 26; obj.pressureax = axes('Parent',obj.parent,... 'Units','characters','Position',pos,... 'Box','on','Units','characters','YScal','log',... 'XLim',xlimits,'YLim',[10e-4,10e4]); linkaxes([obj.temperatureax,obj.pressureax],'x'); pos = [137,44,20,1.5]; handles.EnableBtn = uicontrol('Parent',handles.basepanel,'Style','togglebutton','string','Enable',... 'Min',0,'Max',1,'Value',0,'FontSize',10,'FontUnits','points','Units','characters',... 'Position',pos,'Callback',{@EnableBtnCallback},... 'Tooltip','Enable or disable control panel.'); pos_ = pos; pos_(1) = pos(1)+pos(3)+2; handles.AlarmBtn = uicontrol('Parent',handles.basepanel,'Style','togglebutton','string','Test/Stop Alarm',... 'Min',0,'Max',1,'Value',0,'FontSize',10,'FontUnits','points','Units','characters',... 'Position',pos_,'Callback',{@TestStopAlarm},... 'Tooltip','Test alarm or stop alarm.'); pos = [137,42,20,1]; handles.SetProcessTitle = uicontrol('Parent',handles.basepanel,'Style','text','string','Alert scheme',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters','Position',pos,... 'Tooltip','Select a emergency alert scheme.'); pos(1) = pos(1)+pos(3)+1; pos(3) = 35; handles.Process = uicontrol('Parent',handles.basepanel,'Style','popupmenu',... 'string',AlertSchemeOptions,... 'FontSize',9,'FontUnits','points','HorizontalAlignment','Left',... 'ForegroundColor',[0.5,0.5,1],'BackgroundColor',[0.9,1,0.8],'Units','characters','Position',pos,... 'Callback',{@SelectProcessCallback},'Tooltip','Select a emergency alert scheme.','Enable','off'); set(handles.Process,'value',obj.process); pos = get(handles.SetProcessTitle,'Position'); pos(2) = pos(2) - 1.5; handles.SetNotIntTitle = uicontrol('Parent',handles.basepanel,'Style','text','string','Notification interval',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters','Position',pos,... 'Tooltip','Select the notification iterval.'); pos(1) = pos(1)+pos(3)+1; pos(3) = 35; handles.SetNotInt = uicontrol('Parent',handles.basepanel,'Style','popupmenu',... 'string',{'30 minutes','1 hour','2 hours','3 hours','4 hours','never except emergency'},... 'FontSize',9,'FontUnits','points','HorizontalAlignment','Left','Value',2,... 'ForegroundColor',[0.5,0.5,1],'BackgroundColor',[0.9,1,0.8],'Units','characters','Position',pos,... 'Callback',{@SelectNotIntervalCallback},'Tooltip','Set the current process.','Enable','off'); pos_ = get(handles.SetNotIntTitle,'Position'); pos_(2) = pos_(2) - 26.5; pos_(3) = pos(1)+pos(3)-pos_(1); pos_(4) = 25; handles.InfoDisp = uicontrol('Parent',handles.basepanel,'Style','text',... 'string',[datestr(obj.time(obj.dpoint,1),'dd mmm HH:MM:SS'),10,'Monitor started.'],... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters','Position',pos_,... 'Min',0,'Max',3,'Tooltip','Latest actions.'); if obj.notifyinterval < 45 set(handles.SetNotInt,'value',1); obj.notifyinterval = 30; elseif obj.notifyinterval < 90 set(handles.SetNotInt,'value',2); obj.notifyinterval = 60; elseif obj.notifyinterval < 150 set(handles.SetNotInt,'value',3); obj.notifyinterval = 120; elseif obj.notifyinterval < 210 set(handles.SetNotInt,'value',4); obj.notifyinterval = 180; elseif obj.notifyinterval < 500 set(handles.SetNotInt,'value',5); obj.notifyinterval = 240; else set(handles.SetNotInt,'value',6); obj.notifyinterval = Inf; end pvflag = hvar; pvflag.x = false; handles.pvflag = pvflag; obj.uihandles = handles; set(handles.basepanel,'UserData',obj); obj.Chart(); set(obj.parent,'Visible','on'); end function EnableBtnCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; % to do: add password validation if get(handles.EnableBtn,'Value'); PasswordValidation(obj.password,handles.pvflag,['QES | ',obj.fridgeobj.name]); if ~handles.pvflag.x set(handles.EnableBtn,'Value',get(handles.EnableBtn,'Min')); return; end set(handles.EnableBtn,'String','Disable'); set(handles.Process,'Enable','on'); set(handles.SetNotInt,'Enable','on'); else set(handles.EnableBtn,'String','Enable'); set(handles.Process,'Enable','off'); set(handles.SetNotInt,'Enable','off'); end end function TestStopAlarm(src,entdata) obj = get(get(src,'Parent'),'UserData'); if ~isempty(obj.alarmobj) && isobject(obj.alarmobj) && isvalid(obj.alarmobj) switch obj.alarmobj.Running case 'on' stop(obj.alarmobj); oldinfostr = get(obj.uihandles.InfoDisp,'String'); oldinfostr = TrimNotes(oldinfostr); oldinfostr = oldinfostr(:)'; newinfostr = [datestr(obj.time(obj.dpoint,1),'dd mmm HH:MM:SS'),10,'Stop alarm',10,oldinfostr]; case 'off' start(obj.alarmobj); oldinfostr = get(obj.uihandles.InfoDisp,'String'); oldinfostr = TrimNotes(oldinfostr); oldinfostr = oldinfostr(:)'; newinfostr = [datestr(obj.time(obj.dpoint,1),'dd mmm HH:MM:SS'),10,'Start alarm',10,oldinfostr]; end if length(newinfostr) > 1024; newinfostr(1024:end) = []; end set(obj.uihandles.InfoDisp,'String',newinfostr); end end function SelectProcessCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; % to do: add password validation selection = get(handles.Process,'Value'); obj.process = selection; end function SelectNotIntervalCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; % to do: add password validation notifyinterval = get(handles.SetNotInt,'value'); switch notifyinterval case 1 obj.notifyinterval = 30; case 2 obj.notifyinterval = 60; case 3 obj.notifyinterval = 120; case 4 obj.notifyinterval = 180; case 5 obj.notifyinterval = 240; case 6 obj.notifyinterval = Inf; end end function RestoreAxesRange(src,entdata) obj = get(src,'UserData'); obj.RestoreAxesRange(); end function GUIDeleteCallback(src,entdata) end function ExitCbk(src,entdata) obj = get(src,'UserData'); pvflag = hvar; pvflag.x = false; PasswordValidation(obj.password,pvflag,['QES | ',obj.fridgeobj.name]); if ~pvflag.x return; end obj.delete(); delete(src); end
github
oiwic/QOS-master
CreateGUI_resizable.m
.m
QOS-master/qos/+qes/+app/@DataViewer/CreateGUI_resizable.m
27,703
utf_8
ba2ffd146e41d53506cdfa54e4098e9a
function CreateGUI_resizable(obj) % create gui % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] OPSYSTEM = lower(system_dependent('getos')); if any([strfind(OPSYSTEM, 'microsoft windows xp'),... strfind(OPSYSTEM, 'microsoft windows Vista'),... strfind(OPSYSTEM, 'microsoft windows 7'),... strfind(OPSYSTEM, 'microsoft windows server 2008'),... strfind(OPSYSTEM, 'microsoft windows server 2003')]) InfoDispHeight = 5; % characters SelectDataUILn = 30; panelpossize = [0,0,260,45]; mainaxshift = 4; elseif any([strfind(OPSYSTEM, 'microsoft windows 10'),... strfind(OPSYSTEM, 'microsoft windows server 10'),... strfind(OPSYSTEM, 'microsoft windows server 2012')]) InfoDispHeight = 6; % characters SelectDataUILn = 35; panelpossize = [0,0,258.5,45]; mainaxshift = 5; else InfoDispHeight = 5; % characters SelectDataUILn = 30; % characters panelpossize = [0,0,260,45]; % characters mainaxshift = 4; end % str = system_dependent('getwinsys'); % import qes.ui.* BkGrndColor = [0.941 0.941 0.941]; handles.dataviewwin = figure('Units','characters','MenuBar','none',... 'ToolBar','none','NumberTitle','off','Name','QOS | Data Viewer',... 'Resize','on','HandleVisibility','callback','Color',BkGrndColor,... 'DockControls','off','Visible','off'); warning('off'); jf = get(handles.dataviewwin,'JavaFrame'); jf.setFigureIcon(javax.swing.ImageIcon(... im2java(qes.ui.icons.qos1_32by32()))); warning('on'); ParentUnitOrig = get(handles.dataviewwin,'Units'); %set(handles.dataviewwin,'Units','characters'); ParentPosOrig = get(handles.dataviewwin,'Position'); %set(handles.dataviewwin,'Position',[ParentPosOrig(1),ParentPosOrig(2),panelpossize(3),panelpossize(4)]); %set(handles.dataviewwin,'Units',ParentUnitOrig); % restore to original units. handles.dataviewwin.Units='normalized'; handles.basepanel=uix.Panel(... 'Parent',handles.dataviewwin,... 'Units','characters',... 'Position',panelpossize,... 'backgroundColor',BkGrndColor,... 'Title','',... 'BorderType','none',... 'HandleVisibility','callback',... 'visible','on',... 'Tag','parameterpanel','DeleteFcn',{@GUIDeleteCallback}); % handles.basepanel.Units='normalized'; handles.dataviewwin.Position=[0 0 .8 .8]; handles.basepanel.Position=[0 0 1 1]; backgroundlayout=uix.Grid('parent',handles.basepanel,'UserData',obj); headlayout=uix.Grid('parent',backgroundlayout,'padding',6,'UserData',obj); footlayout=uix.Grid('parent',backgroundlayout,'padding',2,'UserData',obj); backgroundlayout.Heights=[-8 -0.75]; % leftlayout=uix.Grid('parent',headlayout,'padding',2,'UserData',obj); midlayout=uix.Grid('parent',headlayout,'padding',2,'spacing',6,'UserData',obj); rightlayout=uix.Grid('parent',headlayout,'padding',2,'UserData',obj); headlayout.Widths=[-10 -5 -4]; % footleftlayout=uix.Grid('parent',footlayout,'padding',2,'UserData',obj); footmidlayout=uix.Grid('parent',footlayout,'padding',2,'spacing',2,'UserData',obj); footrightlayout=uix.Grid('parent',footlayout,'padding',2,'UserData',obj); footlayout.Widths=[35 -1 35]; %footlayout handles.PreviousPageBtn = uicontrol('Parent',footleftlayout,'Style','pushbutton','string','<<',... 'FontSize',18,'FontUnits','points','Units','characters','Callback',{@PNPageBtnCallback,-1},... 'Tooltip','Single click: backward one page; Double click: backward multiple pages.'); handles.PreviewAX = zeros(1,2*obj.numpreview+1); for ii = 1:2*obj.numpreview+1 handles.PreviewAX(ii) = axes('Parent',uix.Grid('parent',footmidlayout,'UserData',obj),'Visible','on','HandleVisibility','callback',... 'XTick',[],'YTick',[],'Box','on','Units','characters','Position',[0 0 1 1],... 'UserData',[obj.numpreview,ii],'ButtonDownFcn',{@PreviewAXClickCallback}); end % set(handles.PreviewAX(ceil(length(handles.PreviewAX)/2)),'XColor',[1,0,0],'YColor',[1,0,0],... % 'LineWidth',3,'ButtonDownFcn',{}); handles.NextPageBtn = uicontrol('Parent',footrightlayout,'Style','pushbutton','string','>>',... 'FontSize',18,'FontUnits','points','Units','characters','Callback',{@PNPageBtnCallback,+1},... 'Tooltip','Single click: forward one page; Double click: forward multiple pages.'); %leftlayout % axeslayout=uix.Panel(... % 'Parent',leftlayout,... % 'Units','normalized',... % 'UserData',obj,... % 'Title','',... % 'BorderType','none',... % 'HandleVisibility','callback',... % 'visible','on'); axeslayout=uicontainer('Parent', leftlayout,'Units','normalized','UserData',obj); axeslayout.Units='normalized'; handles.axeslayout=axeslayout; %pos = get(handles.PreviewAX(end),'Position'); pos = [235 0.8 13 3.5]; pos(1) = 12; pos(3) = 110; pos(2) = pos(2)+pos(4)+mainaxshift; pos(4) = panelpossize(4) - pos(2) - 2.5; mainaxfullpos = pos; handles.mainaxfullpos = mainaxfullpos; pos_ = pos; pos_(3) = 90; pos_(4) = 26; mainaxreducedpos = pos_; colorbarpos = [mainaxfullpos(1)+mainaxfullpos(3)+1,7.25,1.5,36]; handles.colorbarpos = colorbarpos; pos_xs = pos_; pos_xs(2) = pos_xs(2)+pos_xs(4); pos_xs(4) = pos(2)+pos(4) - pos_xs(2); handles.xsliceax = axes('Parent',axeslayout,'Visible','on','HandleVisibility','callback',... 'HitTest','off','XTick',[],'YTick',[],'Box','on','Units','normalized',... 'Position',Unitsturning(pos_xs),'Visible','off'); pos_ys = pos_; pos_ys(1) = pos_ys(1)+pos_ys(3); pos_ys(3) = pos(1)+pos(3) - pos_ys(1); handles.ysliceax = axes('Parent',axeslayout,'Visible','on','HandleVisibility','callback',... 'HitTest','off','XTick',[],'YTick',[],'Box','on','Units','normalized',... 'Position',Unitsturning(pos_ys),'Visible','off'); handles.mainax = axes('Parent',axeslayout,'Visible','on','HandleVisibility','callback',... 'HitTest','off','XTick',[],'YTick',[],'Box','on','Units','normalized',... 'Position',Unitsturning(pos)); linkaxes([handles.mainax,handles.xsliceax],'x'); linkaxes([handles.mainax,handles.ysliceax],'y'); pos_cz = pos_ys; pos_cz(1) = pos_cz(1) + 3; pos_cz(2) = pos_cz(2)+pos_cz(4)+2; pos_cz(3) = 30; pos_cz(4) = 1.5; handles.cz = uicontrol('Parent',axeslayout,'Style','text','string','z:',... 'FontSize',12,'FontUnits','points','HorizontalAlignment','Left',... 'Units','normalized','Position',Unitsturning(pos_cz),'Visible','off'); pos_cy = pos_cz; pos_cy(2) = pos_cy(2)+pos_cy(4); handles.cy = uicontrol('Parent',axeslayout,'Style','text','string','y:',... 'FontSize',12,'FontUnits','points','HorizontalAlignment','Left',... 'Units','normalized','Position',Unitsturning(pos_cy),'Visible','off'); pos_cx = pos_cy; pos_cx(2) = pos_cx(2)+pos_cx(4); handles.cx = uicontrol('Parent',axeslayout,'Style','text','string','x:',... 'FontSize',12,'FontUnits','points','HorizontalAlignment','Left',... 'Units','normalized','Position',Unitsturning(pos_cx),'Visible','off'); mainaxfullpos = Unitsturning(mainaxfullpos); handles.mainaxfullpos = mainaxfullpos; mainaxreducedpos = Unitsturning(mainaxreducedpos); colorbarpos = Unitsturning(colorbarpos); handles.colorbarpos = colorbarpos; % pos_xs = Unitsturning(pos_xs); % pos_ys = Unitsturning(pos_ys); % pos_cz = Unitsturning(pos_cz); % pos_cy = Unitsturning(pos_cy); % pos_cx = Unitsturning(pos_cx); % set(handles.xsliceax,'Units','characters'); % set(handles.ysliceax,'Units','characters'); % set(handles.mainax,'Units','characters'); % set(handles.cz,'Units','characters'); % set(handles.cy,'Units','characters'); % set(handles.cx,'Units','characters'); %midlayout midlayout1=uix.Grid('parent',midlayout,'spacing',2,'UserData',obj); midlayout2=uix.Grid('parent',midlayout,'spacing',2,'UserData',obj); midlayout3=uix.Grid('parent',midlayout,'spacing',6,'UserData',obj); midlayout4=uix.Grid('parent',midlayout,'spacing',2,'UserData',obj); midlayout.Heights=[118 30 -1 30]; %midlayout1 handles.DataFolderTitle = uicontrol('Parent',midlayout1,'Style','text','string','Data folder:',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters'); handles.SelectDataTitle = uicontrol('Parent',midlayout1,'Style','text','string','Select data:',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters'); handles.SelectPlotFcnitle = uicontrol('Parent',midlayout1,'Style','text','string','Plot fcn:',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters'); handles.SelectfitFcnitle = uicontrol('Parent',midlayout1,'Style','text','string','Fit type:',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters'); % handles.DataFolder = uicontrol('Parent',midlayout1,'Style','edit','string',obj.datadir,... 'FontSize',10,'FontUnits','points','FontAngle','oblique','ForegroundColor',[0.5,0.5,1],... 'BackgroundColor',[0.9,1,0.8],'HorizontalAlignment','Left','Units','characters'); handles.SelectData = uicontrol('Parent',midlayout1,'Style','popupmenu','string','All|Exclude hidden|Highlighted',... 'value',1,'FontSize',9,'FontUnits','points','HorizontalAlignment','Left',... 'ForegroundColor',[0.5,0.5,1],'BackgroundColor',[0.9,1,0.8],'Units','characters','Callback',{@SelectDataCallback},... 'Tooltip','Select the type of data to view.'); handles.PlotFunction = uicontrol('Parent',midlayout1,'Style','popupmenu','string',obj.availableplotfcns,... 'FontSize',9,'FontUnits','points','HorizontalAlignment','Left',... 'ForegroundColor',[0.5,0.5,1],'BackgroundColor',[0.9,1,0.8],'Units','characters',... 'Callback',{@SelectPlotFcnCallback},'Tooltip','Select the data plot fucntion.'); handles.FitFunction = uicontrol('Parent',midlayout1,'Style','popupmenu','string',obj.availablefitfcns,... 'FontSize',9,'FontUnits','points','HorizontalAlignment','Left',... 'ForegroundColor',[0.5,0.5,1],'BackgroundColor',[0.9,1,0.8],'Units','characters',... 'Tooltip','Select the data fit fucntion.'); % midlayout1_9=uix.Grid('parent',midlayout1,'UserData',obj); handles.SelectFolderBtn = uicontrol('Parent',midlayout1_9,'Style','pushbutton','string','S',... 'FontSize',10,'FontUnits','points',... 'Units','characters','Callback',{@SelectFolderCallback},... 'Tooltip','Select the data folder to view.'); handles.RefreshFolderBtn = uicontrol('Parent',midlayout1_9,'Style','pushbutton','string','R',... 'FontSize',10,'FontUnits','points',... 'Units','characters','Callback',{@RefreshFolderCallback},... 'Tooltip','Refresh the files in current folder.'); handles.OpenFolderBtn = uicontrol('Parent',midlayout1_9,'Style','pushbutton','string','O',... 'FontSize',10,'FontUnits','points',... 'Units','characters','Callback',{@OpenFolderCallback},... 'Tooltip','Open folder in explorer.'); handles.SaveBtn = uicontrol('Parent',midlayout1,'Style','pushbutton','string','Save',... 'FontSize',10,'FontUnits','points','ForegroundColor',[1,0,0],'Units','characters',... 'Callback',{@SaveCallback},'Tooltip','Save changes to disk.'); handles.DeleteBtn = uicontrol('Parent',midlayout1,'Style','pushbutton','string','Delete',... 'FontSize',10,'FontUnits','points','ForegroundColor',[1,0,0],'Units','characters',... 'Callback',{@DeleteCallback},'Tooltip','Delect the current data file from disk.'); uix.Empty( 'Parent',midlayout1); % midlayout1.Heights=[-1 -1 -1 -1]; midlayout1.Widths=[75 -1 100]; %midlayout2 handles.HideUnhideBtn = uicontrol('Parent',midlayout2,'Style','pushbutton','string','Hide +/-',... 'FontSize',10,'FontUnits','points','Units','characters',... 'Callback',{@HideCallback},'Tooltip','Hide the current data file.'); handles.HighlightPlusBtn = uicontrol('Parent',midlayout2,'Style','togglebutton','string','Highlight +/- ',... 'FontSize',10,'FontUnits','points','Units','characters',... 'Callback',{@HighlightCallback},'Tooltip','Hilight the current data file.'); handles.DataFitBtn = uicontrol('Parent',midlayout2,'Style','pushbutton','string','Data Fit',... 'FontSize',10,'FontUnits','points','Units','characters',... 'Callback',{@DataFit},'Tooltip','Fit the data.'); handles.SaveFigBtn = uicontrol('Parent',midlayout2,'Style','pushbutton','string','Save Fig',... 'FontSize',10,'FontUnits','points','Units','characters',... 'Callback',{},'Tooltip','place holder.'); %midlayout3 InfoStr = ['Data file: ',10, 'Sample: ',10,'Measurement system: ',10, 'Operator: ',10, 'Time: ']; handles.InfoDisp = uicontrol('Parent',midlayout3,'Style','text','string',InfoStr,... 'BackgroundColor',[0.8,1,0.9],'FontAngle','oblique','ForegroundColor',[0.5,0.5,1],'Min',0,'Max',10,... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters'); handles.NotesBox = uicontrol('Parent',midlayout3,'Style','edit','string','',... 'FontSize',10,'FontUnits','points','ForegroundColor',[0.5,0.5,1],'Min',0,'Max',10,... 'BackgroundColor',[0.9,1,0.8],'HorizontalAlignment','Left','Units','characters',... 'Tooltip','Edit notes.'); midlayout3.Heights=[85 -1]; %midlayout4 handles.XYTraceBtn = uicontrol('Parent',midlayout4,'Style','toggle','string','XY Traces',... 'FontSize',10,'FontUnits','points','Units','characters','Callback',@XYTrace,... 'Value',0,'Tooltip','Show X and Y trace, 2D data only'); handles.ExtractLineBtn = uicontrol('Parent',midlayout4,'Style','pushbutton','string','Trace Data',... 'FontSize',10,'FontUnits','points','Units','characters','Callback',{@ExtractLine},... 'Tooltip','Extract and plot X, Y or free trace data from 2D data'); handles.ExportDataBtn = uicontrol('Parent',midlayout4,'Style','pushbutton','string','x,y,z->]',... 'FontSize',10,'FontUnits','points','Units','characters','Callback',{@ExportDataCallback},... 'Tooltip','Export data to workspace as x, y and z.'); handles.fileidxdisp = uicontrol('Parent',midlayout4,'Style','text','string','',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters'); midlayout4.Widths=[73 73 73 -1]; handles.InfoTable = uitable('Parent',rightlayout,... 'Data',[],... 'ColumnName',{'Key','Value'},... 'ColumnFormat',{'char','char'},... 'ColumnEditable',[false,false],... 'ColumnWidth',{145,145},... 'RowName',[],... 'Units','characters'); handles.dataviewwin.Position=[0 0 .65 .55]; movegui(handles.dataviewwin,'center'); xdata = []; ydata = []; zdata = []; xline = []; yline = []; xhair = []; yhair = []; zdatamin = 0; zdatamax = 1; SliceYTick = [0,1]; function wbmcb(src,evnt) cp = get(handles.mainax,'CurrentPoint'); XLim = get(handles.mainax,'XLim'); YLim = get(handles.mainax,'YLim'); x_e = cp(1,1); y_e = cp(1,2); xrange = range(xdata); yrange = range(ydata); if x_e < min(xdata)-0.01*xrange || x_e > max(xdata)+0.01*xrange ||... y_e < min(ydata)-0.01*yrange || y_e > max(ydata)+0.01*yrange set(xline,'XData',NaN,'YData',NaN); set(yline,'XData',NaN,'YData',NaN); set(xhair,'XData',NaN,'YData',NaN); set(yhair,'XData',NaN,'YData',NaN); set(handles.cx,'String',''); set(handles.cy,'String',''); set(handles.cz,'String',''); else if abs(x_e) < 1e3 set(handles.cx,'String',['X: ',num2str(x_e)]); else set(handles.cx,'String',['X: ',num2str(x_e,'%0.4e')]); end if abs(y_e) < 1e3 set(handles.cy,'String',['Y: ',num2str(y_e)]); else set(handles.cy,'String',['Y: ',num2str(y_e,'%0.4e')]); end [~,y_idx] = (min(abs(ydata - y_e))); y = zdata(:,y_idx); set(xline,'XData',xdata,'YData',y); y_ = y(~isnan(y)); if ~isempty(y_) ymax = max(y); ymin = min(y); if ymax > ymin yr = ymax - ymin; yaxr = [ymin-0.1*yr,ymax+0.1*yr]; set(handles.xsliceax,'YLim',yaxr,'YTick',linspace(yaxr(1),yaxr(end),4),'YGrid','on'); end end set(yhair,'XData',[x_e,x_e],'YData',[zdatamin,zdatamax]); [~,x_idx] = (min(abs(xdata - x_e))); x = zdata(x_idx,:); set(yline,'XData',x,'YData',ydata); x_ = x(~isnan(x)); if ~isempty(x_) xmax = max(x); xmin = min(x); if xmax > xmin xr = xmax - xmin; xaxr = [xmin-0.1*xr,xmax+0.1*xr]; set(handles.ysliceax,'XLim',xaxr,'XTick',linspace(xaxr(1),xaxr(end),4),'XGrid','on'); end end set(xhair,'XData',[zdatamin,zdatamax],'YData',[y_e,y_e]); z_e = zdata(x_idx,y_idx); if abs(y_e) < 1e3 set(handles.cz,'String',['Z: ',num2str(z_e)]); else set(handles.cz,'String',['Z: ',num2str(z_e,'%0.4e')]); end end set(handles.xsliceax,'XLim',XLim,'Ylim',[zdatamin,zdatamax],'YTick',SliceYTick); set(handles.ysliceax,'YLim',YLim,'Xlim',[zdatamin,zdatamax],'XTick',SliceYTick); drawnow; end function XYTrace(src,entdata) obj = get(get(src,'Parent'),'UserData'); if ~get(src,'Value') set(handles.xsliceax,'Visible','off'); set(handles.ysliceax,'Visible','off'); set(handles.mainax,'Position',mainaxfullpos); obj.uihandles.ColorBar = colorbar('peer',handles.mainax); set(obj.uihandles.ColorBar,'Units','characters','Position',colorbarpos); set(handles.dataviewwin,'WindowButtonMotionFcn',[]) hold(handles.xsliceax,'off'); hold(handles.ysliceax,'off'); set(handles.cx,'Visible','off'); set(handles.cy,'Visible','off'); set(handles.cz,'Visible','off'); return; end h = figure('Visible','off'); ax = axes('Parent',h); try idx = find(obj.previewfiles == obj.currentfile,1); data = obj.loadeddata{idx}; if obj.plotfunc == 1 if isfield(data,'Info') && isfield(data.Info,'plotfcn') && ~isempty(data.Info.plotfcn) &&... (ischar(data.Info.plotfcn) ||... isa(data.Info.plotfcn,'function_handle')) if ischar(data.Info.plotfcn) PlotFcn = str2func(data.Info.plotfcn); else PlotFcn = data.Info.plotfcn; end elseif isfield(data,'Config') && isfield(data.Config,'plotfcn') &&... ~isempty(data.Config.plotfcn) && (ischar(data.Config.plotfcn) ||... isa(data.Config.plotfcn,'function_handle')) if ischar(data.Config.plotfcn) PlotFcn = str2func(data.Config.plotfcn); else PlotFcn = data.Config.plotfcn; end else PlotFcn = @qes.util.plotfcn.OneMeas_Def; % default end else PlotFcn = str2func(['qes.util.plotfcn.',obj.availableplotfcns{obj.plotfunc}]); end [x,y,z] = feval(PlotFcn,data.Data, data.SweepVals,'',data.SwpMainParam,'',ax,true); delete(h); catch msgbox('Unable to extract data, make sure the selected plot function supports the currents data set and has data exportation functionality.','modal'); if ishghandle(h) delete(h); end set(src,'Value',0); return; end if isempty(z) msgbox('Extract line data is for 3D data only.','modal'); set(src,'Value',0); return; end if isempty(x) || isempty(y) msgbox('x data or y data empty.','modal'); set(src,'Value',0); return; elseif any(isnan(x)) || any(isnan(y)) msgbox('x data or y data contains empty data(NaN)','modal'); set(src,'Value',0); return; end xdata = x; ydata = y; if isreal(z) zdata = z; else if ~isempty(strfind(obj.availableplotfcns{obj.plotfunc},'Phase')) ||... ~isempty(strfind(obj.availableplotfcns{obj.plotfunc},'phase')) sz = size(z); z_ = NaN*zeros(sz); for ww = 1:sz(1) z(ww,:) = fixunknowns_ln(z(ww,:)); ang = unwrap(angle(z(ww,:))); z_(ww,:) = ang - linspace(ang(1),ang(end),length(ang)); end zdata = z_; else zdata = abs(z); end end zdatamin = min(min(zdata)); zdatamax = max(max(zdata)); zr = zdatamax - zdatamin; SliceYTick = linspace(zdatamin+0.1*zr,zdatamax-0.1*zr,3); set(handles.xsliceax,'Visible','on'); set(handles.ysliceax,'Visible','on'); set(handles.cx,'Visible','on'); set(handles.cy,'Visible','on'); set(handles.cz,'Visible','on'); set(handles.mainax,'Position',mainaxreducedpos); colorbar('off','peer',handles.mainax); XLim = get(handles.mainax,'XLim'); YLim = get(handles.mainax,'YLim'); hold(handles.xsliceax,'on'); xline = plot(handles.xsliceax,NaN,NaN,... 'Color',[0,0.3,1],'Marker','o','MarkerSize',3,'MarkerFaceColor',[0,0.3,1]); yhair = plot(handles.xsliceax,NaN,NaN,'Color',[0.8,0.8,0.8]); hold(handles.xsliceax,'off'); set(handles.xsliceax,'XTick',[]); hold(handles.ysliceax,'on'); yline = plot(handles.ysliceax,NaN,NaN,... 'Color',[1,0.3,0],'Marker','o','MarkerSize',3,'MarkerFaceColor',[1,0.3,0]); xhair = plot(handles.ysliceax,NaN,NaN,'Color',[0.8,0.8,0.8]); hold(handles.ysliceax,'off'); set(handles.ysliceax,'YTick',[]); set(handles.dataviewwin,'WindowButtonMotionFcn',@wbmcb) set(handles.mainax,'XLim',XLim,'YLim',YLim); end obj.uihandles = handles; set(handles.basepanel,'UserData',obj); obj.RefreshGUI(); function SelectFolderCallback(src,entdata) persistent lastselecteddir if isempty(lastselecteddir) || ~exist(lastselecteddir,'dir') lastselecteddir = pwd; end obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; datadir = uigetdir(lastselecteddir,'Select the data folder'); if ~ischar(datadir) return; end lastselecteddir = datadir; set(handles.DataFolder,'String',datadir); obj.datadir = datadir; % OpenFolder(datadir,src,entdata); obj.RefreshGUI(); end function RefreshFolderCallback(src,entdata) selection=get(handles.SelectData,'value'); dirstr = get(handles.DataFolder,'String'); if ~exist(dirstr,'dir') msgbox('Directory not exist!'); return; end obj.datadir = dirstr; % OpenFolder(obj.datadir,src,entdata); obj.RefreshGUI(); set(handles.SelectData,'value',selection) SelectDataCallback(src,entdata) end function OpenFolderCallback(src,entdata) winopen( get(handles.DataFolder,'String')) end function pos_normalized = Unitsturning(pos_characters) %only works in axeslayout %pos_normalized=[pos_characters(1),pos_characters(2)-4.3,pos_characters(3),pos_characters(4)]; pos_normalized=[pos_characters(1)/134.0,(pos_characters(2)-4.3)/40.7,pos_characters(3)/134.0,pos_characters(4)/40.7]; end set(handles.dataviewwin,'Visible','on'); end function PNPageBtnCallback(src,entdata,NorP) persistent lastFwdClick persistent lastBkwdClick obj = get(get(src,'Parent'),'UserData'); if NorP > 0 if ~isempty(lastFwdClick) && now - lastFwdClick < 6.941e-06 % 0.6 second obj.NextN(100); else obj.NextPage(); end lastFwdClick = now; lastBkwdClick = []; elseif NorP < 0 if ~isempty(lastBkwdClick) && now - lastBkwdClick < 6.941e-06 % 0.6 second obj.NextN(-100); else obj.PreviousPage(); end lastFwdClick = []; lastBkwdClick = now; end end function SelectPlotFcnCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; selection = get(handles.PlotFunction,'value'); obj.plotfunc = selection; end function SaveCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); obj.Save(); end function HideCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); obj.HideFile(); end function HighlightCallback(src,entdata) option=get(src,'Value'); obj = get(get(src,'Parent'),'UserData'); obj.HilightFile(option); end function SelectDataCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; selection = get(handles.SelectData,'value'); obj.SelectData(selection); obj.RefreshGUI(); end function ExtractLine(src,entdata) obj = get(get(src,'Parent'),'UserData'); obj.ExtractLine(); end function PreviewAXClickCallback(src,entdata) persistent clickcount temp = get(src,'UserData'); if isempty(clickcount) clickcount = zeros(2,2*temp(1)+1); end clickcount(:,1:2*temp(1)+1~=temp(2)) = 0; if clickcount(1,temp(2)) > 0 && now - clickcount(2,temp(2)) > 6.941e-06 % 0.6 second clickcount(1,temp(2)) = 0; end clickcount(1,temp(2)) = clickcount(1,temp(2)) + 1; clickcount(2,temp(2)) = now; if clickcount(1,temp(2)) < 2 return; end clickcount(temp(2)) = 0; obj = get(get(src,'Parent'),'UserData'); nextn = temp(2)-(temp(1)+1); if nextn ~= 0 obj.NextN(nextn); else % double click on the current data figure to edit obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; h = figure('Units','normalized'); warning('off'); jf = get(h,'JavaFrame'); jf.setFigureIcon(javax.swing.ImageIcon(... im2java(qes.ui.icons.qos1_32by32()))); warning('on'); hax_new = copyobj(handles.mainax,h); set(hax_new,'Units','normalized','Position',[0.12,0.12,0.8,0.8]); end end function DeleteCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); obj.DeleteFile(); end function ExportDataCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); obj.ExportData(); end function GUIDeleteCallback(src,entdata) end
github
oiwic/QOS-master
ExtractLine.m
.m
QOS-master/qos/+qes/+app/@DataViewer/ExtractLine.m
9,860
utf_8
188aca08188af99deb2e69143ed4e96c
function ExtractLine(obj) % % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] h = figure('Visible','off'); ax = axes('Parent',h); try idx = find(obj.previewfiles == obj.currentfile,1); data = obj.loadeddata{idx}; if obj.plotfunc == 1 if isfield(data,'Info') && isfield(data.Info,'plotfcn') && ~isempty(data.Info.plotfcn) &&... (ischar(data.Info.plotfcn) ||... isa(data.Info.plotfcn,'function_handle')) if ischar(data.Info.plotfcn) PlotFcn = str2func(data.Info.plotfcn); else PlotFcn = data.Info.plotfcn; end elseif isfield(data,'Config') && isfield(data.Config,'plotfcn') &&... ~isempty(data.Config.plotfcn) && (ischar(data.Config.plotfcn) ||... isa(data.Config.plotfcn,'function_handle')) if ischar(data.Config.plotfcn) PlotFcn = str2func(data.Config.plotfcn); else PlotFcn = data.Config.plotfcn; end else PlotFcn = @qes.util.plotfcn.OneMeas_Def; % default end else PlotFcn = str2func(['qes.util.plotfcn.',obj.availableplotfcns{obj.plotfunc}]); end [x,y,z] = feval(PlotFcn,data.Data, data.SweepVals,'',data.SwpMainParam,'',ax,true); delete(h); if ~isreal(z) z = abs(z); end catch qes.ui.msgbox('Unable to extract data, make sure the selected plot function supports the currents data set and has data exportation functionality.'); if ishghandle(h) delete(h); end return; end if isempty(z) qes.ui.msgbox('Extract line data is for 3D data only.','modal'); return; end if isempty(x) || isempty(y) qes.ui.msgbox('x data or y data empty.','modal'); return; elseif any(isnan(x)) || any(isnan(y)) qes.ui.msgbox('x data or y data contains empty data(NaN)','modal'); return; end choice = questdlg('Select mode:','','Horizontal','Vertical','Free line','Horizontal'); if isempty(choice) || strcmp(choice, 'Horizontal') || strcmp(choice, 'Vertical') set(obj.uihandles.mainax,'HandleVisibility','on'); axes(obj.uihandles.mainax); try cp = qes.app.DataViewer.Ginput(1); catch set(obj.uihandles.mainax,'HandleVisibility','callback'); return; end % cp = get(obj.uihandles.mainax,'CurrentPoint'); x_e = cp(1,1); y_e = cp(1,2); xrange = range(x); yrange = range(y); if (isempty(choice) || strcmp(choice, 'Horizontal')) && (x_e < min(x)-0.05*xrange || x_e > max(x)+0.05*xrange) qes.ui.msgbox('Out of data range, click within the data range to extract.','modal'); return; elseif y_e < min(y)-0.05*yrange || y_e > max(y)+0.05*yrange qes.ui.msgbox('Out of data range, click within the data range to extract.','modal'); return; end if isempty(choice) || strcmp(choice, 'Horizontal') [~,y_idx] = (min(abs(y - y_e))); choice = questdlg('Where to plot horizontal line data?',... 'Plot options','A new plot','Append to the current axes(if exists)','A new plot'); if ~isempty(choice) && strcmp(choice, 'A new plot') h1 = qes.ui.qosFigure('Horizontal Trace',false); warning('off'); jf = get(h1,'JavaFrame'); jf.setFigureIcon(javax.swing.ImageIcon(... im2java(qes.ui.icons.qos1_32by32()))); warning('on'); ha1 = axes('Parent',h1); else qes.ui.msgbox('Raise the axis to add the plot to the front by cliking on it.'); pause(5); ha1 = gca(); hold(ha1,'on'); end plot(ha1,x,z(:,y_idx)); xlabel(ha1,'x'); ylabel(ha1,'z'); title(ha1,'horizontal line data, data also exported to base workspace as ''x_{ex}'',''z_{ex}''',... 'FontSize',10,'FontWeight','normal'); assignin('base','x_ex',x); assignin('base','x_ex',z(:,y_idx)); else [~,x_idx] = (min(abs(x - x_e))); choice = questdlg('Where to plot vertical line data?','Plot options',... 'A new plot','Append to the current axes(if exists)','A new plot'); if ~isempty(choice) && strcmp(choice, 'A new plot') h2 = qes.ui.qosFigure('Vertical Trace',false); warning('off'); jf = get(h2,'JavaFrame'); jf.setFigureIcon(javax.swing.ImageIcon(... im2java(qes.ui.icons.qos1_32by32()))); warning('on'); warning('off'); jf = get(h2,'JavaFrame'); jf.setFigureIcon(javax.swing.ImageIcon(... im2java(qes.ui.icons.qos1_32by32()))); warning('on'); ha2 = axes('Parent',h2); else qes.ui.msgbox('Raise the axis to add the plot to the front by cliking on it.'); pause(3); ha2 = gca; hold(ha2,'on'); end plot(ha2,y,z(x_idx,:)); xlabel(ha2,'y'); ylabel(ha2,'z'); title(ha2,'vertical line data, data exported to base workspace as ''y_{ex}'',''z_{ex}''',... 'FontSize',10,'FontWeight','normal'); assignin('base','y_ex',y); assignin('base','z_ex',z(x_idx,:)); end else % free line SelectFreeLineData(obj,x,y,z); end end function SelectFreeLineData(obj,data_x,data_y,data_z) % choice = questdlg('Choose line color:','Line color','Black','White','Red','Black'); if ~isempty(choice) && strcmp(choice, 'Black') Color = [0,0,0]; elseif strcmp(choice, 'White') Color = [1,1,1]; elseif strcmp(choice, 'Red') Color = [1,0,0]; end spts = []; set(obj.uihandles.dataviewwin,'WindowButtonDownFcn',@wbdcb); ah = axes('Parent',get(obj.uihandles.mainax,'Parent'),... 'XLim',get(obj.uihandles.mainax,'XLim'),... 'YLim',get(obj.uihandles.mainax,'YLim'),... 'YTick',[],'YTick',[],'Box','on',... 'Color','none',... 'Unit',get(obj.uihandles.mainax,'Unit'),... 'UserData',spts); % 'DrawMode','fast', set(ah,'Position',get(obj.uihandles.mainax,'Position')); set(obj.uihandles.mainax,'UserData',spts); linkaxes([obj.uihandles.mainax,ah],'xy'); % hold(ah,'on'); x_e = []; y_e = []; function wbdcb(src,evnt) if strcmp(get(src,'SelectionType'),'normal') cp = get(ah,'CurrentPoint'); x = cp(1,1); y = cp(1,2); hl = line('Parent',ah,'XData',x,'YData',y,... 'Marker','.','Color',Color,'LineStyle','--'); drawnow; set(src,'WindowButtonMotionFcn',@wbmcb); x_e = [x_e,x]; y_e = [y_e,y]; set(obj.uihandles.mainax,'UserData',[get(obj.uihandles.mainax,'UserData');cp]); elseif strcmp(get(src,'SelectionType'),'alt') set(src,'WindowButtonMotionFcn',''); set(obj.uihandles.dataviewwin,'WindowButtonDownFcn',''); delete(ah); if length(x_e) < 2 errordlg('Select at least two data points!','Error!','modal'); return; end xdatarange = range(data_x); ydatarange = range(data_y); x_e_r = (x_e - min(data_x))/xdatarange; y_e_r = (y_e - min(data_y))/ydatarange; D = sqrt(diff(x_e_r).^2+diff(y_e_r).^2); if sum(D)== 0 errordlg('Select at least two different data points!','Error!','modal'); return; end DD = sqrt(2); ND = max(numel(data_x),numel(data_x)); x_e_u = []; y_e_u = []; for ww = 1:numel(x_e)-1 R = max(ND*D(ww)/DD,1); temp = linspace(x_e(ww),x_e(ww+1),R+1); x_e_u = [x_e_u,temp(1:end-1)]; temp = linspace(y_e(ww),y_e(ww+1),R+1); y_e_u = [y_e_u,temp(1:end-1)]; end zi = interp2(data_x,data_y,data_z',x_e_u,y_e_u); h2 = qes.ui.qosFigure('Freeline Trace',false); set(h2,'Position',[123 246 950 420]); hax_new = copyobj(obj.uihandles.mainax,h2); set(hax_new,'Units','normalized','Position',[0.08,0.12,0.40,0.8]); hold(hax_new,'on'); line('Parent',hax_new,'XData',x_e,'YData',y_e,... 'Marker','.','Color',Color,'LineStyle','none'); line('Parent',hax_new,'XData',x_e_u,'YData',y_e_u,... 'Marker','none','Color',Color,'LineStyle',':'); hold(hax_new,'off'); colorbar('peer',hax_new); hax_line = axes('Parent',h2,'Units','normalized','Position',[0.58,0.12,0.4,0.8]); plot(hax_line,1:length(zi),zi); xlabel(hax_line,['idx of selected points, up sampled ',num2str(R,'%0.0f'),' times']); ylabel(hax_line,'z'); title(hax_line,{'extrated free line data,', 'data exported to base workspace as: ''x_{ex}'',''y_{ex}'',''z_{ex}'''},... 'FontSize',10,'FontWeight','normal'); assignin('base','x_ex',x_e_u); assignin('base','y_ex',y_e_u); assignin('base','z_ex',zi); end function wbmcb(src,evnt) cp = get(ah,'CurrentPoint'); xdat = [x,cp(1,1)]; ydat = [y,cp(1,2)]; set(hl,'XData',xdat,'YData',ydat); end end end
github
oiwic/QOS-master
CreateGUI_fixed.m
.m
QOS-master/qos/+qes/+app/@DataViewer/CreateGUI_fixed.m
27,648
utf_8
2f2efd12d894e7e5c2ef3673a59caf77
function CreateGUI_fixed(obj) % create gui % Copyright 2015 Yulin Wu, Institute of Physics, Chinese Academy of Sciences % [email protected]/[email protected] OPSYSTEM = lower(system_dependent('getos')); if any([strfind(OPSYSTEM, 'microsoft windows xp'),... strfind(OPSYSTEM, 'microsoft windows Vista'),... strfind(OPSYSTEM, 'microsoft windows 7'),... strfind(OPSYSTEM, 'microsoft windows server 2008'),... strfind(OPSYSTEM, 'microsoft windows server 2003')]) InfoDispHeight = 5; % characters SelectDataUILn = 30; panelpossize = [0,0,260,45]; mainaxshift = 4; elseif any([strfind(OPSYSTEM, 'microsoft windows 10'),... strfind(OPSYSTEM, 'microsoft windows server 10'),... strfind(OPSYSTEM, 'microsoft windows server 2012')]) InfoDispHeight = 6; % characters SelectDataUILn = 35; panelpossize = [0,0,258.5,45]; mainaxshift = 5; else InfoDispHeight = 5; % characters SelectDataUILn = 30; % characters panelpossize = [0,0,260,45]; % characters mainaxshift = 4; end % str = system_dependent('getwinsys'); BkGrndColor = [0.941 0.941 0.941]; handles.dataviewwin = figure('Units','characters','MenuBar','none',... 'ToolBar','none','NumberTitle','off','Name','QOS | Data Viewer',... 'Resize','off','HandleVisibility','callback','Color',BkGrndColor,... 'DockControls','off','Visible','off'); warning('off'); jf = get(handles.dataviewwin,'JavaFrame'); jf.setFigureIcon(javax.swing.ImageIcon(... im2java(qes.ui.icons.qos1_32by32()))); warning('on'); ParentUnitOrig = get(handles.dataviewwin,'Units'); set(handles.dataviewwin,'Units','characters'); ParentPosOrig = get(handles.dataviewwin,'Position'); set(handles.dataviewwin,'Position',[ParentPosOrig(1),ParentPosOrig(2),panelpossize(3),panelpossize(4)]); set(handles.dataviewwin,'Units',ParentUnitOrig); % restore to original units. movegui(handles.dataviewwin,'center'); handles.basepanel=uipanel(... 'Parent',handles.dataviewwin,... 'Units','characters',... 'Position',panelpossize,... 'backgroundColor',BkGrndColor,... 'Title','',... 'BorderType','none',... 'HandleVisibility','callback',... 'visible','on',... 'Tag','parameterpanel','DeleteFcn',{@GUIDeleteCallback}); pos = [2,0.8,8,3.5]; handles.PreviousPageBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','<<',... 'FontSize',18,'FontUnits','points','Units','characters','Position',pos,'Callback',{@PNPageBtnCallback,-1},... 'Tooltip','Single click: backward one page; Double click: backward multiple pages.'); pos = [11,0.8,13,3.5]; handles.PreviewAX = zeros(1,2*obj.numpreview+1); handles.PreviewAX(1) = axes('Parent',handles.basepanel,'Visible','on','HandleVisibility','callback',... 'HitTest','off','XTick',[],'YTick',[],'Box','on','Units','characters','Position',pos,... 'UserData',[obj.numpreview,1],'ButtonDownFcn',{@PreviewAXClickCallback}); for ii = 2:2*obj.numpreview+1 pos(1) = pos(1)+pos(3)+1; handles.PreviewAX(ii) = axes('Parent',handles.basepanel,'Visible','on','HandleVisibility','callback',... 'XTick',[],'YTick',[],'Box','on','Units','characters',... 'Position',pos,'UserData',[obj.numpreview,ii],'ButtonDownFcn',{@PreviewAXClickCallback}); end % set(handles.PreviewAX(ceil(length(handles.PreviewAX)/2)),'XColor',[1,0,0],'YColor',[1,0,0],... % 'LineWidth',3,'ButtonDownFcn',{}); pos_NextPageBtn = get(handles.PreviousPageBtn,'Position'); pos_NextPageBtn(1) = pos(1)+pos(3)+1; handles.NextPageBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','>>',... 'FontSize',18,'FontUnits','points','Units','characters','Position',pos_NextPageBtn,'Callback',{@PNPageBtnCallback,+1},... 'Tooltip','Single click: forward one page; Double click: forward multiple pages.'); pos = get(handles.PreviewAX(end),'Position'); pos(1) = 12; pos(3) = 110; pos(2) = pos(2)+pos(4)+mainaxshift; pos(4) = panelpossize(4) - pos(2) - 2.5; mainaxfullpos = pos; handles.mainaxfullpos = mainaxfullpos; pos_ = pos; pos_(3) = 90; pos_(4) = 26; mainaxreducedpos = pos_; colorbarpos = [mainaxfullpos(1)+mainaxfullpos(3)+1,7.25,1.5,36]; handles.colorbarpos = colorbarpos; pos_xs = pos_; pos_xs(2) = pos_xs(2)+pos_xs(4); pos_xs(4) = pos(2)+pos(4) - pos_xs(2); handles.xsliceax = axes('Parent',handles.basepanel,'Visible','on','HandleVisibility','callback',... 'HitTest','off','XTick',[],'YTick',[],'Box','on','Units','characters',... 'Position',pos_xs,'Visible','off'); pos_ys = pos_; pos_ys(1) = pos_ys(1)+pos_ys(3); pos_ys(3) = pos(1)+pos(3) - pos_ys(1); handles.ysliceax = axes('Parent',handles.basepanel,'Visible','on','HandleVisibility','callback',... 'HitTest','off','XTick',[],'YTick',[],'Box','on','Units','characters',... 'Position',pos_ys,'Visible','off'); handles.mainax = axes('Parent',handles.basepanel,'Visible','on','HandleVisibility','callback',... 'HitTest','off','XTick',[],'YTick',[],'Box','on','Units','characters',... 'Position',pos); linkaxes([handles.mainax,handles.xsliceax],'x'); linkaxes([handles.mainax,handles.ysliceax],'y'); pos_cz = pos_ys; pos_cz(1) = pos_cz(1) + 3; pos_cz(2) = pos_cz(2)+pos_cz(4)+2; pos_cz(3) = 30; pos_cz(4) = 1.5; handles.cz = uicontrol('Parent',handles.basepanel,'Style','text','string','z:',... 'FontSize',12,'FontUnits','points','HorizontalAlignment','Left',... 'Units','characters','Position',pos_cz,'Visible','off'); pos_cy = pos_cz; pos_cy(2) = pos_cy(2)+pos_cy(4); handles.cy = uicontrol('Parent',handles.basepanel,'Style','text','string','y:',... 'FontSize',12,'FontUnits','points','HorizontalAlignment','Left',... 'Units','characters','Position',pos_cy,'Visible','off'); pos_cx = pos_cy; pos_cx(2) = pos_cx(2)+pos_cx(4); handles.cx = uicontrol('Parent',handles.basepanel,'Style','text','string','x:',... 'FontSize',12,'FontUnits','points','HorizontalAlignment','Left',... 'Units','characters','Position',pos_cx,'Visible','off'); pos(1) = pos(1)+pos(3)+12; pos(2) = pos(2)+pos(4)-0; pos(3) = 14; pos(4) = 1.1; handles.DataFolderTitle = uicontrol('Parent',handles.basepanel,'Style','text','string','Data folder:',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters','Position',pos); pos(1) = pos(1)+pos(3)+1; pos(2) = pos(2)-0.3; pos(3) = 33; pos(4) = 1.5; handles.DataFolder = uicontrol('Parent',handles.basepanel,'Style','edit','string',obj.datadir,... 'FontSize',10,'FontUnits','points','FontAngle','oblique','ForegroundColor',[0.5,0.5,1],... 'BackgroundColor',[0.9,1,0.8],'HorizontalAlignment','Left','Units','characters','Position',pos); pos(1) = pos(1)+pos(3)+1; pos(3) = 5; handles.SelectFolderBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','S',... 'FontSize',10,'FontUnits','points',... 'Units','characters','Position',pos,'Callback',{@SelectFolderCallback},... 'Tooltip','Select the data folder to view.'); pos(1) = pos(1)+pos(3)+1; pos(3) = 5; handles.RefreshFolderBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','R',... 'FontSize',10,'FontUnits','points',... 'Units','characters','Position',pos,'Callback',{@RefreshFolderCallback},... 'Tooltip','Refresh the files in current folder.'); pos(1) = pos(1)+pos(3)+1; pos(3) = 5; handles.OpenFolderBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','O',... 'FontSize',10,'FontUnits','points',... 'Units','characters','Position',pos,'Callback',{@OpenFolderCallback},... 'Tooltip','Open folder in explorer.'); pos = get(handles.DataFolderTitle,'Position'); pos(2) = pos(2)-2; handles.SelectDataTitle = uicontrol('Parent',handles.basepanel,'Style','text','string','Select data:',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters','Position',pos); pos(1) = pos(1)+pos(3)+1; pos(3) = SelectDataUILn; handles.SelectData = uicontrol('Parent',handles.basepanel,'Style','popupmenu','string','All|Exclude hidden|Highlighted',... 'value',1,'FontSize',9,'FontUnits','points','HorizontalAlignment','Left',... 'ForegroundColor',[0.5,0.5,1],'BackgroundColor',[0.9,1,0.8],'Units','characters','Position',pos,'Callback',{@SelectDataCallback},... 'Tooltip','Select the type of data to view.'); pos = get(handles.SelectDataTitle,'Position'); pos(2) = pos(2)-2; handles.SelectPlotFcnitle = uicontrol('Parent',handles.basepanel,'Style','text','string','Plot fcn:',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters','Position',pos); pos(1) = pos(1)+pos(3)+1; pos(3) = SelectDataUILn; handles.PlotFunction = uicontrol('Parent',handles.basepanel,'Style','popupmenu','string',obj.availableplotfcns,... 'FontSize',9,'FontUnits','points','HorizontalAlignment','Left',... 'ForegroundColor',[0.5,0.5,1],'BackgroundColor',[0.9,1,0.8],'Units','characters','Position',pos,... 'Callback',{@SelectPlotFcnCallback},'Tooltip','Select the data plot fucntion.'); pos(1) = pos(1)+pos(3)+1; pos(2) = pos(2)+0.4; pos(3) = 23 - (SelectDataUILn- 27); pos(4) = 2.7; handles.SaveBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','Save',... 'FontSize',10,'FontUnits','points','ForegroundColor',[1,0,0],'Units','characters','Position',pos,... 'Callback',{@SaveCallback},'Tooltip','Save changes to disk.'); pos(2) = pos(2)-3; handles.DeleteBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','Delete',... 'FontSize',10,'FontUnits','points','ForegroundColor',[1,0,0],'Units','characters','Position',pos,... 'Callback',{@DeleteCallback},'Tooltip','Delect the current data file from disk.'); pos = get(handles.SelectPlotFcnitle,'Position'); pos(2) = pos(2)-2.2; handles.SelectfitFcnitle = uicontrol('Parent',handles.basepanel,'Style','text','string','Fit type:',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters','Position',pos); pos(1) = pos(1)+pos(3)+1; pos(3) = SelectDataUILn; handles.FitFunction = uicontrol('Parent',handles.basepanel,'Style','popupmenu','string',obj.availablefitfcns,... 'FontSize',9,'FontUnits','points','HorizontalAlignment','Left',... 'ForegroundColor',[0.5,0.5,1],'BackgroundColor',[0.9,1,0.8],'Units','characters','Position',pos,... 'Tooltip','Select the data fit fucntion.'); pos = get(handles.DataFolderTitle,'Position'); pos(2) = pos(2)-10; pos(3) = 15; pos(4) = 3; handles.HideUnhideBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','Hide +/-',... 'FontSize',10,'FontUnits','points','Units','characters','Position',pos,... 'Callback',{@HideCallback},'Tooltip','Hide the current data file.'); pos(1) = pos(1)+pos(3)+1; pos(3) = 16; handles.HighlightPlusBtn = uicontrol('Parent',handles.basepanel,'Style','togglebutton','string','Highlight +/- ',... 'FontSize',10,'FontUnits','points','Units','characters','Position',pos,... 'Callback',{@HighlightCallback},'Tooltip','Hilight the current data file.'); pos(1) = pos(1)+pos(3)+1; pos(3) = 16; handles.DataFitBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','Data Fit',... 'FontSize',10,'FontUnits','points','Units','characters','Position',pos,... 'Callback',{@DataFit},'Tooltip','Fit the data.'); pos(1) = pos(1)+pos(3)+1; pos(3) = 16; handles.SaveFigBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','Save Fig',... 'FontSize',10,'FontUnits','points','Units','characters','Position',pos,... 'Callback',{},'Tooltip','place holder.'); pos = get(handles.DataFolderTitle,'Position'); pos(2) = pos(2)-10.5-InfoDispHeight; pos(3) = 66; pos(4) = InfoDispHeight; InfoStr = ['Data file: ',10, 'Sample: ',10,'Measurement system: ',10, 'Operator: ',10, 'Time: ']; handles.InfoDisp = uicontrol('Parent',handles.basepanel,'Style','text','string',InfoStr,... 'BackgroundColor',[0.8,1,0.9],'FontAngle','oblique','ForegroundColor',[0.5,0.5,1],'Min',0,'Max',10,... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters','Position',pos); pos = get(handles.DataFolderTitle,'Position'); pos(2) = pos(2)-6.5-27; pos(3) = 66; pos(4) = 16.5; handles.NotesBox = uicontrol('Parent',handles.basepanel,'Style','edit','string','',... 'FontSize',10,'FontUnits','points','ForegroundColor',[0.5,0.5,1],'Min',0,'Max',10,... 'BackgroundColor',[0.9,1,0.8],'HorizontalAlignment','Left','Units','characters','Position',pos,... 'Tooltip','Edit notes.'); pos = get(handles.HideUnhideBtn,'Position'); pos_ = get(handles.NotesBox,'Position'); % if any([strfind(OPSYSTEM, 'microsoft windows 10'),... % strfind(OPSYSTEM, 'microsoft windows server 10'),... % strfind(OPSYSTEM, 'microsoft windows server 2012')]) % pos(3) = 15; % else % pos(3) = 15; % end pos(2) = pos_(2)-3.5; pos(4) = 3; handles.XYTraceBtn = uicontrol('Parent',handles.basepanel,'Style','toggle','string','XY Traces',... 'FontSize',10,'FontUnits','points','Units','characters','Position',pos,'Callback',@XYTrace,... 'Value',0,'Tooltip','Show X and Y trace, 2D data only'); pos_ = pos; pos_(1) = pos(1)+pos(3)+1; pos_(3) = pos(3)+3; handles.ExtractLineBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','Trace Data',... 'FontSize',10,'FontUnits','points','Units','characters','Position',pos_,'Callback',{@ExtractLine},... 'Tooltip','Extract and plot X, Y or free trace data from 2D data'); pos(1) = pos_(1)+pos_(3)+1; handles.ExportDataBtn = uicontrol('Parent',handles.basepanel,'Style','pushbutton','string','x,y,z->]',... 'FontSize',10,'FontUnits','points','Units','characters','Position',pos,'Callback',{@ExportDataCallback},... 'Tooltip','Export data to workspace as x, y and z.'); % pos = get(handles.NextPageBtn,'Position'); pos(1) = pos(1)+pos(3)+1; pos(2) = pos(2) + 1; pos_ = get(handles.DeleteBtn,'Position'); pos(3) = pos_(1)+pos_(3)-pos(1); pos(4) = 1; handles.fileidxdisp = uicontrol('Parent',handles.basepanel,'Style','text','string','',... 'FontSize',10,'FontUnits','points','HorizontalAlignment','Left','Units','characters','Position',pos); pos = get(handles.OpenFolderBtn,'Position'); pos_ = get(handles.NextPageBtn,'Position'); pos(1) = pos(1)+pos(3)+1; pos(2) = pos_(2)+pos_(4)+1; pos(3) = panelpossize(3) - pos(1) - 1; pos(4) = panelpossize(4) - pos(2) - 1; handles.InfoTable = uitable('Parent',handles.basepanel,... 'Data',[],... 'ColumnName',{'Key','Value'},... 'ColumnFormat',{'char','char'},... 'ColumnEditable',[false,false],... 'ColumnWidth',{145,145},... 'RowName',[],... 'Units','characters','Position',pos); xdata = []; ydata = []; zdata = []; xline = []; yline = []; xhair = []; yhair = []; zdatamin = 0; zdatamax = 1; SliceYTick = [0,1]; function wbmcb(src,evnt) cp = get(handles.mainax,'CurrentPoint'); XLim = get(handles.mainax,'XLim'); YLim = get(handles.mainax,'YLim'); x_e = cp(1,1); y_e = cp(1,2); xrange = range(xdata); yrange = range(ydata); if x_e < min(xdata)-0.01*xrange || x_e > max(xdata)+0.01*xrange ||... y_e < min(ydata)-0.01*yrange || y_e > max(ydata)+0.01*yrange set(xline,'XData',NaN,'YData',NaN); set(yline,'XData',NaN,'YData',NaN); set(xhair,'XData',NaN,'YData',NaN); set(yhair,'XData',NaN,'YData',NaN); set(handles.cx,'String',''); set(handles.cy,'String',''); set(handles.cz,'String',''); else if abs(x_e) < 1e3 set(handles.cx,'String',['X: ',num2str(x_e)]); else set(handles.cx,'String',['X: ',num2str(x_e,'%0.4e')]); end if abs(y_e) < 1e3 set(handles.cy,'String',['Y: ',num2str(y_e)]); else set(handles.cy,'String',['Y: ',num2str(y_e,'%0.4e')]); end [~,y_idx] = (min(abs(ydata - y_e))); y = zdata(:,y_idx); set(xline,'XData',xdata,'YData',y); y_ = y(~isnan(y)); if ~isempty(y_) ymax = max(y); ymin = min(y); if ymax > ymin yr = ymax - ymin; yaxr = [ymin-0.1*yr,ymax+0.1*yr]; set(handles.xsliceax,'YLim',yaxr,'YTick',linspace(yaxr(1),yaxr(end),4),'YGrid','on'); end end set(yhair,'XData',[x_e,x_e],'YData',[zdatamin,zdatamax]); [~,x_idx] = (min(abs(xdata - x_e))); x = zdata(x_idx,:); set(yline,'XData',x,'YData',ydata); x_ = x(~isnan(x)); if ~isempty(x_) xmax = max(x); xmin = min(x); if xmax > xmin xr = xmax - xmin; xaxr = [xmin-0.1*xr,xmax+0.1*xr]; set(handles.ysliceax,'XLim',xaxr,'XTick',linspace(xaxr(1),xaxr(end),4),'XGrid','on'); end end set(xhair,'XData',[zdatamin,zdatamax],'YData',[y_e,y_e]); z_e = zdata(x_idx,y_idx); if abs(y_e) < 1e3 set(handles.cz,'String',['Z: ',num2str(z_e)]); else set(handles.cz,'String',['Z: ',num2str(z_e,'%0.4e')]); end end set(handles.xsliceax,'XLim',XLim,'Ylim',[zdatamin,zdatamax],'YTick',SliceYTick); set(handles.ysliceax,'YLim',YLim,'Xlim',[zdatamin,zdatamax],'XTick',SliceYTick); drawnow; end function XYTrace(src,entdata) obj = get(get(src,'Parent'),'UserData'); if ~get(src,'Value') set(handles.xsliceax,'Visible','off'); set(handles.ysliceax,'Visible','off'); set(handles.mainax,'Position',mainaxfullpos); obj.uihandles.ColorBar = colorbar('peer',handles.mainax); set(obj.uihandles.ColorBar,'Units','characters','Position',colorbarpos); set(handles.dataviewwin,'WindowButtonMotionFcn',[]) hold(handles.xsliceax,'off'); hold(handles.ysliceax,'off'); set(handles.cx,'Visible','off'); set(handles.cy,'Visible','off'); set(handles.cz,'Visible','off'); return; end h = figure('Visible','off'); ax = axes('Parent',h); try idx = find(obj.previewfiles == obj.currentfile,1); data = obj.loadeddata{idx}; if obj.plotfunc == 1 if isfield(data,'Info') && isfield(data.Info,'plotfcn') && ~isempty(data.Info.plotfcn) &&... (ischar(data.Info.plotfcn) ||... isa(data.Info.plotfcn,'function_handle')) if ischar(data.Info.plotfcn) PlotFcn = str2func(data.Info.plotfcn); else PlotFcn = data.Info.plotfcn; end elseif isfield(data,'Config') && isfield(data.Config,'plotfcn') &&... ~isempty(data.Config.plotfcn) && (ischar(data.Config.plotfcn) ||... isa(data.Config.plotfcn,'function_handle')) if ischar(data.Config.plotfcn) PlotFcn = str2func(data.Config.plotfcn); else PlotFcn = data.Config.plotfcn; end else PlotFcn = @qes.util.plotfcn.OneMeas_Def; % default end else PlotFcn = str2func(['qes.util.plotfcn.',obj.availableplotfcns{obj.plotfunc}]); end [x,y,z] = feval(PlotFcn,data.Data, data.SweepVals,'',data.SwpMainParam,'',ax,true); delete(h); catch msgbox('Unable to extract data, make sure the selected plot function supports the currents data set and has data exportation functionality.','modal'); if ishghandle(h) delete(h); end set(src,'Value',0); return; end if isempty(z) msgbox('Extract line data is for 3D data only.','modal'); set(src,'Value',0); return; end if isempty(x) || isempty(y) msgbox('x data or y data empty.','modal'); set(src,'Value',0); return; elseif any(isnan(x)) || any(isnan(y)) msgbox('x data or y data contains empty data(NaN)','modal'); set(src,'Value',0); return; end xdata = x; ydata = y; if isreal(z) zdata = z; else if ~isempty(strfind(obj.availableplotfcns{obj.plotfunc},'Phase')) ||... ~isempty(strfind(obj.availableplotfcns{obj.plotfunc},'phase')) sz = size(z); z_ = NaN*zeros(sz); for ww = 1:sz(1) z(ww,:) = fixunknowns_ln(z(ww,:)); ang = unwrap(angle(z(ww,:))); z_(ww,:) = ang - linspace(ang(1),ang(end),length(ang)); end zdata = z_; else zdata = abs(z); end end zdatamin = min(min(zdata)); zdatamax = max(max(zdata)); zr = zdatamax - zdatamin; SliceYTick = linspace(zdatamin+0.1*zr,zdatamax-0.1*zr,3); set(handles.xsliceax,'Visible','on'); set(handles.ysliceax,'Visible','on'); set(handles.cx,'Visible','on'); set(handles.cy,'Visible','on'); set(handles.cz,'Visible','on'); set(handles.mainax,'Position',mainaxreducedpos); colorbar('off','peer',handles.mainax); XLim = get(handles.mainax,'XLim'); YLim = get(handles.mainax,'YLim'); hold(handles.xsliceax,'on'); xline = plot(handles.xsliceax,NaN,NaN,... 'Color',[0,0.3,1],'Marker','o','MarkerSize',3,'MarkerFaceColor',[0,0.3,1]); yhair = plot(handles.xsliceax,NaN,NaN,'Color',[0.8,0.8,0.8]); hold(handles.xsliceax,'off'); set(handles.xsliceax,'XTick',[]); hold(handles.ysliceax,'on'); yline = plot(handles.ysliceax,NaN,NaN,... 'Color',[1,0.3,0],'Marker','o','MarkerSize',3,'MarkerFaceColor',[1,0.3,0]); xhair = plot(handles.ysliceax,NaN,NaN,'Color',[0.8,0.8,0.8]); hold(handles.ysliceax,'off'); set(handles.ysliceax,'YTick',[]); set(handles.dataviewwin,'WindowButtonMotionFcn',@wbmcb) set(handles.mainax,'XLim',XLim,'YLim',YLim); end obj.uihandles = handles; set(handles.basepanel,'UserData',obj); obj.RefreshGUI(); function SelectFolderCallback(src,entdata) persistent lastselecteddir if isempty(lastselecteddir) || ~exist(lastselecteddir,'dir') lastselecteddir = pwd; end obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; datadir = uigetdir(lastselecteddir,'Select the data folder'); if ~ischar(datadir) return; end lastselecteddir = datadir; set(handles.DataFolder,'String',datadir); obj.datadir = datadir; % OpenFolder(datadir,src,entdata); obj.RefreshGUI(); end function RefreshFolderCallback(src,entdata) selection=get(handles.SelectData,'value'); dirstr = get(handles.DataFolder,'String'); if ~exist(dirstr,'dir') msgbox('Directory not exist!'); return; end obj.datadir = dirstr; % OpenFolder(obj.datadir,src,entdata); obj.RefreshGUI(); set(handles.SelectData,'value',selection) SelectDataCallback(src,entdata) end function OpenFolderCallback(src,entdata) winopen( get(handles.DataFolder,'String')) end set(handles.dataviewwin,'Visible','on'); end function PNPageBtnCallback(src,entdata,NorP) persistent lastFwdClick persistent lastBkwdClick obj = get(get(src,'Parent'),'UserData'); if NorP > 0 if ~isempty(lastFwdClick) && now - lastFwdClick < 6.941e-06 % 0.6 second obj.NextN(100); else obj.NextPage(); end lastFwdClick = now; lastBkwdClick = []; elseif NorP < 0 if ~isempty(lastBkwdClick) && now - lastBkwdClick < 6.941e-06 % 0.6 second obj.NextN(-100); else obj.PreviousPage(); end lastFwdClick = []; lastBkwdClick = now; end end function SelectPlotFcnCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; selection = get(handles.PlotFunction,'value'); obj.plotfunc = selection; end function SaveCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); obj.Save(); end function HideCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); obj.HideFile(); end function HighlightCallback(src,entdata) option=get(src,'Value'); obj = get(get(src,'Parent'),'UserData'); obj.HilightFile(option); end function SelectDataCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; selection = get(handles.SelectData,'value'); obj.SelectData(selection); obj.RefreshGUI(); end function ExtractLine(src,entdata) obj = get(get(src,'Parent'),'UserData'); obj.ExtractLine(); end function PreviewAXClickCallback(src,entdata) persistent clickcount temp = get(src,'UserData'); if isempty(clickcount) clickcount = zeros(2,2*temp(1)+1); end clickcount(:,1:2*temp(1)+1~=temp(2)) = 0; if clickcount(1,temp(2)) > 0 && now - clickcount(2,temp(2)) > 6.941e-06 % 0.6 second clickcount(1,temp(2)) = 0; end clickcount(1,temp(2)) = clickcount(1,temp(2)) + 1; clickcount(2,temp(2)) = now; if clickcount(1,temp(2)) < 2 return; end clickcount(temp(2)) = 0; obj = get(get(src,'Parent'),'UserData'); nextn = temp(2)-(temp(1)+1); if nextn ~= 0 obj.NextN(nextn); else % double click on the current data figure to edit obj = get(get(src,'Parent'),'UserData'); handles = obj.uihandles; h = figure('Units','normalized'); warning('off'); jf = get(h,'JavaFrame'); jf.setFigureIcon(javax.swing.ImageIcon(... im2java(qes.ui.icons.qos1_32by32()))); warning('on'); hax_new = copyobj(handles.mainax,h); set(hax_new,'Units','normalized','Position',[0.12,0.12,0.8,0.8]); end end function DeleteCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); obj.DeleteFile(); end function ExportDataCallback(src,entdata) obj = get(get(src,'Parent'),'UserData'); obj.ExportData(); end function GUIDeleteCallback(src,entdata) end
github
oiwic/QOS-master
Config2TableData.m
.m
QOS-master/qos/+qes/+app/@DataViewer/Config2TableData.m
2,031
utf_8
78e53a7e5b81e6784cd9b51dd5f754db
function table_data = Config2TableData(Config) % % Copyright 2017 Yulin Wu, USTC, China % [email protected]/[email protected] table_data = {}; if isfield(Config,'fcn') table_data = [table_data;{'function',Config.fcn}]; end if isfield(Config,'args') table_data = [table_data;Struct2TableData(Config.args,'args.')]; end if isfield(Config,'session_settings') table_data = [table_data;Struct2TableData(Config.session_settings,'s.')]; end if isfield(Config,'hw_settings') table_data = [table_data;Struct2TableData(Config.hw_settings,'hw.')]; end end function table_data = Struct2TableData(data,prefix) table_data = {}; fn = fieldnames(data); for ww = 1:numel(fn) Value = data.(fn{ww}); if isempty(Value) Value = ''; continue; end if isnumeric(Value) if numel(Value) == 1 Value = qes.util.num2strCompact(Value); else Value = 'numeric array or matrix'; end elseif islogical(Value) if numel(Value) == 1 if Value Value = 'true'; else Value = 'false'; end else Value = 'boolean array or matrix'; end elseif ischar(Value) % pass elseif isstruct(Value) if numel(Value) == 1 table_data_ = Struct2TableData(Value,[prefix,fn{ww},'.']); table_data = [table_data;table_data_]; continue; else Value = 'struct array or matrix'; end elseif iscell(Value) Value = 'cell'; else classname = class(Value(1)); if numel(Value) == 1 Value = ['''',classname, ''' class object']; else Value = ['''',classname, ''' class object array or matrix']; end end table_data = [table_data;{[prefix,fn{ww}],Value}]; end end
github
oiwic/QOS-master
Ginput.m
.m
QOS-master/qos/+qes/+app/@DataViewer/Ginput.m
7,888
utf_8
9b62ce36ea9d91f6759289880b144bdc
function [out1,out2,out3] = Ginput(arg1) %GINPUT Graphical input from mouse. % [X,Y] = GINPUT(N) gets N points from the current axes and returns % the X- and Y-coordinates in length N vectors X and Y. The cursor % can be positioned using a mouse. Data points are entered by pressing % a mouse button or any key on the keyboard except carriage return, % which terminates the input before N points are entered. % % [X,Y] = GINPUT gathers an unlimited number of points until the % return key is pressed. % % [X,Y,BUTTON] = GINPUT(N) returns a third result, BUTTON, that % contains a vector of integers specifying which mouse button was % used (1,2,3 from left) or ASCII numbers if a key on the keyboard % was used. % % Examples: % [x,y] = ginput; % % [x,y] = ginput(5); % % [x, y, button] = ginput(1); % % See also GTEXT, WAITFORBUTTONPRESS. % Copyright 1984-2013 The MathWorks, Inc. % a modified version of matlab ginput, by Yulin Wu out1 = []; out2 = []; out3 = []; y = []; if ~matlab.ui.internal.isFigureShowEnabled error(message('MATLAB:hg:NoDisplayNoFigureSupport', 'ginput')) end fig = gcf; figure(gcf); if nargin == 0 how_many = -1; b = []; else how_many = arg1; b = []; if ischar(how_many) ... || size(how_many,1) ~= 1 || size(how_many,2) ~= 1 ... || ~(fix(how_many) == how_many) ... || how_many < 0 error(message('MATLAB:ginput:NeedPositiveInt')) end if how_many == 0 % If input argument is equal to zero points, % give a warning and return empty for the outputs. warning (message('MATLAB:ginput:InputArgumentZero')); end end % Setup the figure to disable interactive modes and activate pointers. initialState = setupFcn(fig); % onCleanup object to restore everything to original state in event of % completion, closing of figure errors or ctrl+c. c = onCleanup(@() restoreFcn(initialState)); % We need to pump the event queue on unix % before calling WAITFORBUTTONPRESS drawnow char = 0; while how_many ~= 0 % Use no-side effect WAITFORBUTTONPRESS waserr = 0; try keydown = wfbp; catch %#ok<CTCH> waserr = 1; end if(waserr == 1) if(ishghandle(fig)) cleanup(c); error(message('MATLAB:ginput:Interrupted')); else cleanup(c); error(message('MATLAB:ginput:FigureDeletionPause')); end end % g467403 - ginput failed to discern clicks/keypresses on the figure it was % registered to operate on and any other open figures whose handle % visibility were set to off figchildren = allchild(0); if ~isempty(figchildren) ptr_fig = figchildren(1); else error(message('MATLAB:ginput:FigureUnavailable')); end % old code -> ptr_fig = get(0,'CurrentFigure'); Fails when the % clicked figure has handlevisibility set to callback if(ptr_fig == fig) if keydown char = get(fig, 'CurrentCharacter'); button = abs(get(fig, 'CurrentCharacter')); else button = get(fig, 'SelectionType'); if strcmp(button,'open') button = 1; elseif strcmp(button,'normal') button = 1; elseif strcmp(button,'extend') button = 2; elseif strcmp(button,'alt') button = 3; else error(message('MATLAB:ginput:InvalidSelection')) end end axes_handle = gca; drawnow; pt = get(axes_handle, 'CurrentPoint'); how_many = how_many - 1; if(char == 13) % & how_many ~= 0) % if the return key was pressed, char will == 13, % and that's our signal to break out of here whether % or not we have collected all the requested data % points. % If this was an early breakout, don't include % the <Return> key info in the return arrays. % We will no longer count it if it's the last input. break; end out1 = [out1;pt(1,1)]; %#ok<AGROW> y = [y;pt(1,2)]; %#ok<AGROW> b = [b;button]; %#ok<AGROW> end end % Cleanup and Restore cleanup(c); if nargout > 1 out2 = y; if nargout > 2 out3 = b; end else out1 = [out1 y]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = wfbp %WFBP Replacement for WAITFORBUTTONPRESS that has no side effects. fig = gcf; current_char = []; %#ok<NASGU> % Now wait for that buttonpress, and check for error conditions waserr = 0; try h=findall(fig,'Type','uimenu','Accelerator','C'); % Disabling ^C for edit menu so the only ^C is for set(h,'Accelerator',''); % interrupting the function. keydown = waitforbuttonpress; current_char = double(get(fig,'CurrentCharacter')); % Capturing the character. if~isempty(current_char) && (keydown == 1) % If the character was generated by the if(current_char == 3) % current keypress AND is ^C, set 'waserr'to 1 waserr = 1; % so that it errors out. end end set(h,'Accelerator','C'); % Set back the accelerator for edit menu. catch %#ok<CTCH> waserr = 1; end drawnow; if(waserr == 1) set(h,'Accelerator','C'); % Set back the accelerator if it errored out. error(message('MATLAB:ginput:Interrupted')); end if nargout>0, key = keydown; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end function initialState = setupFcn(fig) % Store Figure Handle. initialState.figureHandle = fig; % Suspend figure functions initialState.uisuspendState = uisuspend(fig); % Disable Plottools Buttons initialState.toolbar = findobj(allchild(fig),'flat','Type','uitoolbar'); if ~isempty(initialState.toolbar) initialState.ptButtons = [uigettool(initialState.toolbar,'Plottools.PlottoolsOff'), ... uigettool(initialState.toolbar,'Plottools.PlottoolsOn')]; initialState.ptState = get (initialState.ptButtons,'Enable'); set (initialState.ptButtons,'Enable','off'); end % Setup FullCrosshair Pointer without warning. oldwarnstate = warning('off', 'MATLAB:Figure:Pointer'); set(fig,'Pointer','crosshair'); warning(oldwarnstate); % Adding this to enable automatic updating of currentpoint on the figure set(fig,'WindowButtonMotionFcn',@(o,e) dummy()); % Get the initial Figure Units initialState.fig_units = get(fig,'Units'); end function restoreFcn(initialState) if ishghandle(initialState.figureHandle) % Figure Units set(initialState.figureHandle,'Units',initialState.fig_units); set(initialState.figureHandle,'WindowButtonMotionFcn',''); % Plottools Icons if ~isempty(initialState.toolbar) && ~isempty(initialState.ptButtons) set (initialState.ptButtons(1),'Enable',initialState.ptState{1}); set (initialState.ptButtons(2),'Enable',initialState.ptState{2}); end % UISUSPEND uirestore(initialState.uisuspendState); end end function dummy() % do nothing, this is there to update the GINPUT WindowButtonMotionFcn. end function cleanup(c) if isvalid(c) delete(c); end end
github
oiwic/QOS-master
TableData.m
.m
QOS-master/qos/+qes/+app/@RegEditor/TableData.m
9,719
utf_8
5fd6b62a84e1f68c46044bdcc454ab77
function table_data = TableData(obj,name,parentName) % % Copyright 2017 Yulin Wu, USTC % [email protected]/[email protected] switch parentName case 'hardware settings' s = obj.qs.loadHwSettings(name); anno = struct(); if isfield(obj.keyAnnotation.hardware,'comm') anno = obj.keyAnnotation.hardware.comm; end if isfield(obj.keyAnnotation.hardware,name) fname = fieldnames(obj.keyAnnotation.hardware.(name)); for ii = 1:numel(fname) anno.(fname{ii}) = obj.keyAnnotation.hardware.(name).(fname{ii}); end end case 'session settings' s = obj.qs.loadSSettings(name); anno = struct(); if isfield(s, 'type') && isfield(obj.keyAnnotation.qobject,s.type) if isfield(obj.keyAnnotation.qobject.(s.type),'comm') anno = obj.keyAnnotation.qobject.(s.type).comm; end if isfield(s, 'class') && isfield(obj.keyAnnotation.qobject.(s.type),s.class) fname = fieldnames(obj.keyAnnotation.qobject.(s.type).(s.class)); for ii = 1:numel(fname) anno.(fname{ii}) = obj.keyAnnotation.qobject.(s.type).(s.class).(fname{ii}); end end end otherwise throw(MException('QOS_RegEditor:unrecognizedInput',... '%s is an unrecognized parentName option.', parentName)); end table_data = Struct2TableData(s,anno,''); end function table_data = Struct2TableData(data,anno,prefix) table_data = {}; fn = fieldnames(data); for ww = 1:numel(fn) Value = data.(fn{ww}); if isempty(Value) key = [prefix,fn{ww}]; key_ = strrep(key,'.','__'); [startIndex,endIndex] = regexp(key_,'{\d+}'); startIndex = startIndex + 1; endIndex = endIndex - 1; key__ = regexprep(key_,'{\d+}',''); % the following is handle a bad settings design in ustcadda, may be removed in future versions if qes.util.startsWith(key__,'da_chnl_map__') key__ = 'da_chnl_map__'; elseif qes.util.startsWith(key__,'ad_chnl_map__') key__ = 'ad_chnl_map__'; end if isfield(anno,key__) annotation = anno.(key__); if ~isempty(startIndex) startIndex_ = strfind(annotation,'%s'); if numel(startIndex_) == numel(startIndex) switch numel(startIndex) case 1 annotation = sprintf(annotation,key_(startIndex(1):endIndex(1))); case 2 annotation = sprintf(annotation,... key_(startIndex(1):endIndex(1)),key_(startIndex(2):endIndex(2))); case 3 annotation = sprintf(annotation,... key_(startIndex(1):endIndex(1)),key_(startIndex(2):endIndex(2)),... key_(startIndex(3):endIndex(3))); case 4 annotation = sprintf(annotation,... key_(startIndex(1):endIndex(1)),key_(startIndex(2):endIndex(2)),... key_(startIndex(3):endIndex(3)),key_(startIndex(4):endIndex(4))); end end end else annotation = ''; end table_data = [table_data;{key,'',annotation}]; elseif isstruct(Value) numElements = numel(Value); if numElements == 1 table_data_ = Struct2TableData(Value,anno,[prefix,fn{ww},'.']); table_data = [table_data;table_data_]; else table_data_ = {}; for ii = 1:numel(Value) table_data_ = [table_data_;... Struct2TableData(Value(ii),anno,[prefix,fn{ww},... '(',num2str(ii,'%0.0f'),').'])]; end table_data = [table_data;table_data_]; end elseif iscell(Value) numElements = numel(Value); table_data_ = ''; for uu = 1:numElements if isstruct(Value{uu}) table_data_ = [table_data_; Struct2TableData(Value{uu},anno,... [prefix,fn{ww},'{',num2str(uu,'%0.0f'),'}.'])]; else key = [prefix,fn{ww},'{',num2str(uu,'%0.0f'),'}']; key_ = strrep(key,'.','__'); [startIndex,endIndex] = regexp(key_,'{\d+}'); startIndex = startIndex + 1; endIndex = endIndex - 1; key__ = regexprep(key_,'{\d+}',''); % the following is to handle a bad settings design in ustcadda, may be removed in future versions if qes.util.startsWith(key__,'da_chnl_map__') key__ = 'da_chnl_map__'; elseif qes.util.startsWith(key__,'ad_chnl_map__') key__ = 'ad_chnl_map__'; end if isfield(anno,key__) annotation = anno.(key__); if ~isempty(startIndex) startIndex_ = strfind(annotation,'%s'); if numel(startIndex_) == numel(startIndex) switch numel(startIndex) case 1 annotation = sprintf(annotation,key_(startIndex(1):endIndex(1))); case 2 annotation = sprintf(annotation,... key_(startIndex(1):endIndex(1)),key_(startIndex(2):endIndex(2))); case 3 annotation = sprintf(annotation,... key_(startIndex(1):endIndex(1)),key_(startIndex(2):endIndex(2)),... key_(startIndex(3):endIndex(3))); case 4 annotation = sprintf(annotation,... key_(startIndex(1):endIndex(1)),key_(startIndex(2):endIndex(2)),... key_(startIndex(3):endIndex(3)),key_(startIndex(4):endIndex(4))); end end end else annotation = ''; end % table_data_ = [table_data_;... % [{key},value2Str(Value{uu})]]; table_data_ = [table_data_;{key,value2Str(Value{uu}),annotation}]; end end table_data = [table_data;table_data_]; else key = [prefix,fn{ww}]; key_ = strrep(key,'.','__'); [startIndex,endIndex] = regexp(key_,'{\d+}'); startIndex = startIndex + 1; endIndex = endIndex - 1; key__ = regexprep(key_,'{\d+}',''); % the following is handle a bad settings design in ustcadda, may be removed in future versions if qes.util.startsWith(key__,'da_chnl_map__') key__ = 'da_chnl_map__'; elseif qes.util.startsWith(key__,'ad_chnl_map__') key__ = 'ad_chnl_map__'; end if isfield(anno,key__) annotation = anno.(key__); if ~isempty(startIndex) startIndex_ = strfind(annotation,'%s'); if numel(startIndex_) == numel(startIndex) switch numel(startIndex) case 1 annotation = sprintf(annotation,key_(startIndex(1):endIndex(1))); case 2 annotation = sprintf(annotation,... key_(startIndex(1):endIndex(1)),key_(startIndex(2):endIndex(2))); case 3 annotation = sprintf(annotation,... key_(startIndex(1):endIndex(1)),key_(startIndex(2):endIndex(2)),... key_(startIndex(3):endIndex(3))); case 4 annotation = sprintf(annotation,... key_(startIndex(1):endIndex(1)),key_(startIndex(2):endIndex(2)),... key_(startIndex(3):endIndex(3)),key_(startIndex(4):endIndex(4))); end end end else annotation = ''; end table_data = [table_data;{[prefix,fn{ww}],value2Str(Value),annotation}]; end end end function s = value2Str(Value) % Value: not struct, not cell if isempty(Value) s = ''; elseif ischar(Value) s = Value; elseif isnumeric(Value) if numel(Value) == 1 s = qes.util.num2strCompact(Value); else sz = size(Value); if numel(sz) > 2 || all(sz>1) s = 'numeric matrix'; else s = '['; for uu = 1:numel(Value) s = [s,',',qes.util.num2strCompact(Value(uu))]; end s = [s,']']; if numel(s)>2 s(2) = []; end end end elseif islogical(Value) if numel(Value) == 1 if Value s = 'true'; else s = 'false'; end else sz = size(Value); if numel(sz) > 2 || all(sz>1) s = 'logical matrix'; else ls = {'false','true'}; lsIdx = uint8(Value)+1; s = '['; for uu = 1:numel(Value) s = [s,',',ls{lsIdx(ii)}]; end s = [s,']']; end end elseif isstruct(Value) s = 'stuct or struct array.'; elseif iscell(Value) s = 'cell or cell array.'; else classname = class(Value(1)); if numel(Value) == 1 s = ['''',classname, ''' class object']; else s = ['''',classname, ''' class object array or matrix']; end end end