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
shangjingbo1226/DPPred-master
mrelnet.m
.m
DPPred-master/glmnet_matlab/mrelnet.m
2,585
utf_8
2f946c92aba76c5b8ef746baed5e437c
function fit = mrelnet(x,is_sparse,irs,pcs,y,weights,offset,parm,nobs,nvars,... jd,vp,cl,ne,nx,nlam,flmin,ulam,thresh,isd,jsd,intr,maxit,family) nr = size(y, 2); wym = wtmean(y, weights); nulldev = sum(wtmean(bsxfun(@minus,y,wym).^2,weights)*sum(weights)); if isempty(offset) offset = y * 0; is_offset = false; else if (size(offset) ~= size(y)) error('Offset must match dimension of y'); end is_offset = true; end if is_sparse task = 30; [lmu,a0,ca,ia,nin,rsq,alm,nlp,jerr] = glmnetMex(task,parm,x,y-offset,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,cl,intr,maxit,irs,pcs,jsd); else task = 31; [lmu,a0,ca,ia,nin,rsq,alm,nlp,jerr] = glmnetMex(task,parm,x,y-offset,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,cl,intr,maxit,jsd); end if (jerr ~= 0) errmsg = err(jerr,maxit,nx,family); if (errmsg.fatal) error(errmsg.msg); else warning(errmsg.msg); end end ninmax = max(nin); lam = alm; if (ulam == 0.0) lam = fix_lam(lam); % first lambda is infinity; changed to entry point end if (nr > 1) beta_list = {}; % a0 = a0 - repmat(mean(a0), nr, 1); do not center for mrelnet! dfmat=a0; dd=[nvars, lmu]; if ninmax > 0 ca = reshape(ca, nx, nr, lmu); ca = ca(1:ninmax,:,:); ja = ia(1:ninmax); [ja1,oja] = sort(ja); df = any(abs(ca) > 0, 2); df = sum(df, 1); df = df(:); for k=1:nr ca1 = reshape(ca(:,k,:), ninmax, lmu); cak = ca1(oja,:); dfmat(k,:) = sum(abs(cak) > 0, 1); beta = zeros(nvars, lmu); beta(ja1,:) = cak; beta_list{k} = beta; end else for k = 1:nr dfmat(k,:) = zeros(1,lmu); beta_list{k} = zeros(nvars, lmu); end df = zeros(1,lmu); end fit.beta = beta_list; fit.dfmat = dfmat; else dd=[nvars, lmu]; if ninmax > 0 ca = ca(1:ninmax,:); df = sum(abs(ca) > 0, 1); ja = ia(1:ninmax); [ja1,oja] = sort(ja); beta = zeros(nvars, lmu); beta (ja1, :) = ca(oja,:); else beta = zeros(nvars,lmu); df = zeros(1,lmu); end fit.beta = beta; end fit.a0 = a0; fit.dev = rsq; fit.nulldev = nulldev; fit.df = df'; fit.lambda = lam; fit.npasses = nlp; fit.jerr = jerr; fit.dim = dd; fit.offset = is_offset; fit.class = 'mrelnet'; function new_lam = fix_lam(lam) new_lam = lam; if (length(lam) > 2) llam=log(lam); new_lam(1)=exp(2*llam(2)-llam(3)); end
github
shangjingbo1226/DPPred-master
coxnet.m
.m
DPPred-master/glmnet_matlab/coxnet.m
1,563
utf_8
895747785766daa2c82975f3d019dd18
function fit = coxnet(x,is_sparse,irs,pcs,y,weights,offset,parm,nobs,nvars,... jd,vp,cl,ne,nx,nlam,flmin,ulam,thresh,isd,maxit,family) % Internal glmnet function. See also glmnet, cvglmnet. %time --- column 1 %status --- column 2 ty = y(:,1); tevent = y(:,2); if (any(ty <= 0)) error('negative event times encountered; not permitted for Cox family'); end if isempty(offset) offset = ty * 0; is_offset = false; else is_offset = true; end if (is_sparse) error('Cox model not implemented for sparse x in glmnet'); else task = 41; [lmu,ca,ia,nin,dev,alm,nlp,jerr,dev0,ot] = glmnetMex(task,parm,x,ty,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,tevent,cl,maxit,offset); end if (jerr ~= 0) errmsg = err(jerr,maxit,nx,family); if (errmsg.fatal) error(errmsg.msg); else warning(errmsg.msg); end end ninmax = max(nin); lam = alm; if (ulam == 0.0) lam = fix_lam(lam); % first lambda is infinity; changed to entry point end dd=[nvars, lmu]; if ninmax > 0 ca = ca(1:ninmax,:); df = sum(abs(ca) > 0, 1); ja = ia(1:ninmax); [ja1,oja] = sort(ja); beta = zeros(nvars, lmu); beta (ja1,:) = ca(oja,:); else beta = zeros(nvars,lmu); df = zeros(1,lmu); end fit.beta = beta; fit.dev = dev; fit.nulldev = dev0; fit.df = df'; fit.lambda = lam; fit.npasses = nlp; fit.jerr = jerr; fit.dim = dd; fit.offset = is_offset; fit.class = 'coxnet'; function new_lam = fix_lam(lam) new_lam = lam; if (length(lam) > 2) llam=log(lam); new_lam(1)=exp(2*llam(2)-llam(3)); end
github
shangjingbo1226/DPPred-master
err.m
.m
DPPred-master/glmnet_matlab/err.m
3,764
utf_8
eeab9274fcf914b604c55eb4ec2a867a
function output = err(n,maxit,pmax,family) if n==0 output.n=0; output.fatal=false; output.msg=''; else switch family case 'gaussian' output = err_elnet(n,maxit,pmax); case 'binomial' output = err_lognet(n,maxit,pmax); case 'multinomial' output = err_lognet(n,maxit,pmax); case 'poisson' output = err_fishnet(n,maxit,pmax); case 'cox' output = err_coxnet(n,maxit,pmax); case 'mrelnet' output = err_mrelnet(n,maxit,pmax); end output.msg = sprintf('from glmnet Fortran code (error code %d); %s', n, output.msg); end %------------------------------------------------------------------ % End private function err %------------------------------------------------------------------ function output = err_elnet(n,maxit,pmax) if (n > 0) %fatal error if (n < 7777) msg = 'Memory allocation error; contact package maintainer'; elseif (n == 7777) msg = 'All used predictors have zero variance'; elseif (n == 10000) msg = 'All penalty factors are <= 0'; else msg = 'Unknown error'; end output.n = n; output.fatal = true; output.msg = msg; elseif (n < 0) %non-fatal error if (n > -10000) msg = sprintf('Convergence for %dth lambda value not reached after maxit=%d iterations; solutions for larger lambdas returned',-n,maxit); end if (n < -10000) msg = sprintf('Number of nonzero coefficients along the path exceeds pmax=%d at %dth lambda value; solutions for larger lambdas returned',pmax,-n-10000); end output.n = n; output.fatal = false; output.msg = msg; end function output = err_lognet(n,maxit,pmax) output = err_elnet(n,maxit,pmax); if (n < -20000) output.msg = sprintf('Max(p(1-p),1.0e-6 at %dth value of lambda; solutions for larger values of lambda returned',-n-20000); end if ~strcmp(output.msg, 'Unknown error') return; end if (8000 < n) && (n < 9000) msg = sprintf('Null probability for class%d< 1.0e-5', n-8000); elseif (9000 < n) && (n < 10000) msg = sprintf('Null probability for class%d> 1.0 - 1.0e-5',n-9000); else msg = 'Unknown error'; end output.n = n; output.fatal = true; output.msg = msg; function output = err_fishnet(n,maxit,pmax) output = err_elnet(n,maxit,pmax); if ~strcmp(output.msg, 'Unknown error') return; end if (n == 8888) msg = 'Negative response values - should be counts'; elseif (n == 9999) msg = 'No positive observation weights'; else msg = 'Unknown error'; end output.n = n; output.fatal = true; output.msg = msg; function output = err_coxnet(n,maxit,pmax) if (n > 0) %fatal error output = err_elnet(n,maxit,pmax); if ~strcmp(msg, 'Unknown error') return; end if (n == 8888) msg = 'All observations censored - cannot proceed'; elseif (n == 9999) msg = 'No positive observation weights'; elseif (n == 20000) || (n == 30000) msg = 'Inititialization numerical error; probably too many censored observations'; else msg = 'Unknown error'; end output.n = n; output.fatal = true; output.msg = msg; elseif (n < 0) if (n <= -30000) msg = sprintf('Numerical error at %dth lambda value; solutions for larger values of lambda returned',-n-30000); output.n = n; output.fatal = false; output.msg = msg; else output = err_elnet(n,maxit,pmax); end end function output = err_mrelnet(n,maxit,pmax) if (n == 90000) msg = 'Newton stepping for bounded multivariate response did not converge'; output.n = n; output.fatal = false; output.msg = msg; else output = err_elnet(n,maxit,pmax); end
github
shangjingbo1226/DPPred-master
glmnetPlot.m
.m
DPPred-master/glmnet_matlab/glmnetPlot.m
7,609
utf_8
12fcbd8fb5cafce7d419403fcfab5649
function glmnetPlot( x, xvar, label, type, varargin ) %-------------------------------------------------------------------------- % glmnetPlot.m: plot coefficients from a "glmnet" object %-------------------------------------------------------------------------- % % DESCRIPTION: % Produces a coefficient profile plot fo the coefficient paths for a % fitted "glmnet" object. % % USAGE: % glmnetPlot(fit); % glmnetPlot(fit, xvar); % glmnetPlot(fit, xvar, label); % glmnetPlot(fit, xvar, label, type); % glmnetPlot(fit, xvar, label, type, ...); % (Use empty matrix [] to apply the default value, eg. glmnetPlot(fit, % [], [], type).) % % INPUT ARGUMENTS: % x fitted "glmnet" model. % xvar What is on the X-axis. 'norm' plots against the L1-norm of % the coefficients, 'lambda' against the log-lambda sequence, % and 'dev' against the percent deviance explained. % label If true, label the curves with variable sequence numbers. % type If type='2norm' then a single curve per variable, else % if type='coef', a coefficient plot per response. % varargin Other graphical parameters to plot. % % DETAILS: % A coefficient profile plot is produced. If x is a multinomial model, a % coefficient plot is produced for each class. % % LICENSE: GPL-2 % % DATE: 30 Aug 2013 % % AUTHORS: % Algorithm was designed by Jerome Friedman, Trevor Hastie and Rob Tibshirani % Fortran code was written by Jerome Friedman % R wrapper (from which the MATLAB wrapper was adapted) was written by Trevor Hasite % The original MATLAB wrapper was written by Hui Jiang (14 Jul 2009), % and was updated and maintained by Junyang Qian (30 Aug 2013) [email protected], % Department of Statistics, Stanford University, Stanford, California, USA. % % REFERENCES: % Friedman, J., Hastie, T. and Tibshirani, R. (2008) Regularization Paths for Generalized Linear Models via Coordinate Descent, % http://www.jstatsoft.org/v33/i01/ % Journal of Statistical Software, Vol. 33(1), 1-22 Feb 2010 % % Simon, N., Friedman, J., Hastie, T., Tibshirani, R. (2011) Regularization Paths for Cox's Proportional Hazards Model via Coordinate Descent, % http://www.jstatsoft.org/v39/i05/ % Journal of Statistical Software, Vol. 39(5) 1-13 % % Tibshirani, Robert., Bien, J., Friedman, J.,Hastie, T.,Simon, N.,Taylor, J. and Tibshirani, Ryan. (2010) Strong Rules for Discarding Predictors in Lasso-type Problems, % http://www-stat.stanford.edu/~tibs/ftp/strong.pdf % Stanford Statistics Technical Report % % SEE ALSO: % glmnet, glmnetSet, glmnetPrint, glmnetPredict and glmnetCoef. % % EXAMPLES: % x=randn(100,20); % y=randn(100,1); % g2=randsample(2,100,true); % g4=randsample(4,100,true); % fit1=glmnet(x,y); % glmnetPlot(fit1); % glmnetPlot(fit1, 'lambda', true); % fit3=glmnet(x,g4,'multinomial'); % glmnetPlot(fit3); % % DEVELOPMENT: % 14 Jul 2009: Original version of glmnet.m written. % 30 Aug 2013: Updated glmnet.m with more options and more models % (multi-response Gaussian, cox and Poisson models) supported. if nargin < 2 || isempty(xvar) xvar = 'norm'; end if nargin < 3 || isempty(label) label = false; end if nargin < 4 || isempty(type) type = 'coef'; end xvarbase = {'norm','lambda','dev'}; xvarind = find(strncmp(xvar,xvarbase,length(xvar)),1); if isempty(xvarind) error('xvar should be one of ''norm'', ''lambda'', ''dev'''); else xvar = xvarbase{xvarind}; end typebase = {'coef','2norm'}; typeind = find(strncmp(type,typebase,length(type)),1); if isempty(typeind) error('type should be one of ''coef'', ''2norm'''); else type = typebase{typeind}; end if any(strcmp(x.class,{'elnet','lognet','coxnet','fishnet'})) plotCoef(x.beta,[],x.lambda,x.df,x.dev,label,xvar,'','Coefficients',varargin{:}); end if strcmp(x.class,'multnet') || strcmp(x.class,'mrelnet') beta = x.beta; if strcmp(xvar,'norm') norm = 0; nzbeta = beta; for i=1:length(beta) which = nonzeroCoef(beta{i}); nzbeta{i} = beta{i}(which,:); norm = norm + sum(abs(nzbeta{i}),1); end else norm = 0; end if strcmp(type,'coef') ncl = size(x.dfmat,1); if strcmp(x.class,'multnet') for i = 1:ncl plotCoef(beta{i},norm,x.lambda,x.dfmat(i,:),x.dev,label,xvar,'',sprintf('Coefficients: Class %d', i),varargin{:}); end else for i = 1:ncl plotCoef(beta{i},norm,x.lambda,x.dfmat(i,:),x.dev,label,xvar,'',sprintf('Coefficients: Response %d', i),varargin{:}); end end else dfseq = round(mean(x.dfmat,1)); coefnorm = beta{1}*0; for i=1:length(beta) coefnorm = coefnorm + abs(beta{i}).^2; end coefnorm = sqrt(coefnorm); if strcmp(x.class,'multnet') plotCoef(coefnorm,norm,x.lambda,dfseq,x.dev,label,xvar,'',sprintf('Coefficient 2Norms'),varargin{:}); else plotCoef(coefnorm,norm,x.lambda,x.dfmat(1,:),x.dev,label,xvar,'',sprintf('Coefficient 2Norms'),varargin{:}); end end end %---------------------------------------------------------------- % End function glmnetPlot %---------------------------------------------------------------- function plotCoef(beta,norm,lambda,df,dev,label,xvar,xlab,ylab,varargin) which = nonzeroCoef(beta); idwhich = find(which); %row indices nwhich = length(idwhich); if nwhich == 0 error('No plot produced since all coefficients zero') end if nwhich == 1 warning('1 or less nonzero coefficients; glmnet plot is not meaningful'); end beta = beta(which,:); if strcmp(xvar, 'norm') if isempty(norm) index = sum(abs(beta),1); else index = norm; end iname = 'L1 Norm'; elseif strcmp(xvar, 'lambda') index=log(lambda); iname='Log Lambda'; elseif strcmp(xvar, 'dev') index=dev; iname='Fraction Deviance Explained'; end if isempty(xlab) xlab = iname; end %Prepare for the figure (especially for the df labels) clf; beta = transpose(beta); plot(index,beta,varargin{:}); axes1 = gca; axes; axes2 = gca; xlim1 = get(axes1,'XLim'); ylim1 = get(axes1,'YLim'); %idxrange = range(index); %atdf = linspace(min(index)+idxrange/12, max(index)-idxrange/12, 6); atdf = get(axes1,'XTick'); indat = ones(size(atdf)); if (index(end) >= index(1)) for j = length(index):-1:1 indat(atdf <= index(j)) = j; end else for j = 1:length(index) indat(atdf <= index(j)) = j; end end prettydf = df(indat); prettydf(end) = df(end); set(axes1,'box','off','XAxisLocation','bottom','YAxisLocation','left'); set(axes2,'XAxisLocation','top','YAxisLocation','right',... 'XLim',[min(index),max(index)],'XTick',atdf,'XTickLabel',prettydf,... 'YTick',[],'YTickLabel',[],'TickDir','out'); xlabel(axes2,'Degrees of Freedom') axes(axes1); line(xlim1,[ylim1(2),ylim1(2)],'Color','k'); line([xlim1(2),xlim1(2)],ylim1,'Color','k'); xlabel(xlab); ylabel(ylab); if (label) xpos = max(index); adjpos = 2; if strcmp(xvar,'lambda') xpos = min(index); adjpos = 1; end bsize = size(beta); for i = 1: bsize(2) text(1/2*xpos+1/2*xlim1(adjpos),beta(bsize(1),i),num2str(idwhich(i))); end end linkaxes([axes1 axes2],'x'); %---------------------------------------------------------------- % End private function plotCoef %----------------------------------------------------------------
github
shangjingbo1226/DPPred-master
glmnetPredict.m
.m
DPPred-master/glmnet_matlab/glmnetPredict.m
16,486
utf_8
58bccedbf1d9b31e6c7b0e05d2058f3d
function result = glmnetPredict(object, newx, s, type, exact, offset) %-------------------------------------------------------------------------- % glmnetPredict.m: make predictions from a "glmnet" object. %-------------------------------------------------------------------------- % % DESCRIPTION: % Similar to other predict methods, this functions predicts fitted % values, logits, coefficients and more from a fitted "glmnet" object. % % USAGE: % glmnetPredict(object, newx, s, type, exact, offset) % % Fewer input arguments(more often) are allowed in the call, but must % come in the order listed above. To set default values on the way, use % empty matrix []. % For example, pred=glmnetPredict(fit,[],[],'coefficients'). % % To make EXACT prediction, the input arguments originally passed to % "glmnet" MUST be VARIABLES (instead of expressions, or fields % extracted from some struct objects). Alternatively, users should % manually revise the "call" field in "object" (expressions or variable % names) to match the original call to glmnet in the parent environment. % % INPUT ARGUMENTS: % object Fitted "glmnet" model object. % s Value(s) of the penalty parameter lambda at which predictions % are required. Default is the entire sequence used to create % the model. % newx Matrix of new values for x at which predictions are to be % made. Must be a matrix; can be sparse. This argument is not % used for type='coefficients' or type='nonzero'. % type Type of prediction required. Type 'link' gives the linear % predictors for 'binomial', 'multinomial', 'poisson' or 'cox' % models; for 'gaussian' models it gives the fitted values. % Type 'response' gives the fitted probabilities for 'binomial' % or 'multinomial', fitted mean for 'poisson' and the fitted % relative-risk for 'cox'; for 'gaussian' type 'response' is % equivalent to type 'link'. Type 'coefficients' computes the % coefficients at the requested values for s. Note that for % 'binomial' models, results are returned only for the class % corresponding to the second level of the factor response. % Type 'class' applies only to 'binomial' or 'multinomial' % models, and produces the class label corresponding to the % maximum probability. Type 'nonzero' returns a matrix of % logical values with each column for each value of s, % indicating if the corresponding coefficient is nonzero or not. % exact If exact=true, and predictions are to made at values of s not % included in the original fit, these values of s are merged % with object.lambda, and the model is refit before predictions % are made. If exact=false (default), then the predict function % uses linear interpolation to make predictions for values of s % that do not coincide with those used in the fitting % algorithm. Note that exact=true is fragile when used inside a % nested sequence of function calls. glmnetPredict() needs to % update the model, and expects the data used to create it in % the parent environment. % offset If an offset is used in the fit, then one must be supplied % for making predictions (except for type='coefficients' or % type='nonzero') % % DETAILS: % The shape of the objects returned are different for "multinomial" % objects. glmnetCoef(fit, ...) is equivalent to % glmnetPredict(fit,[],[],'coefficients"). % % LICENSE: GPL-2 % % DATE: 30 Aug 2013 % % AUTHORS: % Algorithm was designed by Jerome Friedman, Trevor Hastie and Rob Tibshirani % Fortran code was written by Jerome Friedman % R wrapper (from which the MATLAB wrapper was adapted) was written by Trevor Hasite % The original MATLAB wrapper was written by Hui Jiang (14 Jul 2009), % and was updated and maintained by Junyang Qian (30 Aug 2013) [email protected], % Department of Statistics, Stanford University, Stanford, California, USA. % % REFERENCES: % Friedman, J., Hastie, T. and Tibshirani, R. (2008) Regularization Paths for Generalized Linear Models via Coordinate Descent, % http://www.jstatsoft.org/v33/i01/ % Journal of Statistical Software, Vol. 33(1), 1-22 Feb 2010 % % Simon, N., Friedman, J., Hastie, T., Tibshirani, R. (2011) Regularization Paths for Cox's Proportional Hazards Model via Coordinate Descent, % http://www.jstatsoft.org/v39/i05/ % Journal of Statistical Software, Vol. 39(5) 1-13 % % Tibshirani, Robert., Bien, J., Friedman, J.,Hastie, T.,Simon, N.,Taylor, J. and Tibshirani, Ryan. (2010) Strong Rules for Discarding Predictors in Lasso-type Problems, % http://www-stat.stanford.edu/~tibs/ftp/strong.pdf % Stanford Statistics Technical Report % % SEE ALSO: % glmnet, glmnetPrint, glmnetCoef, and cvglmnet. % % EXAMPLES: % x=randn(100,20); % y=randn(100,1); % g2=randsample(2,100,true); % g4=randsample(4,100,true); % fit1=glmnet(x,y); % glmnetPredict(fit1,x(1:5,:),[0.01,0.005]') % make predictions % glmnetPredict(fit1,[],[],'coefficients') % fit2=glmnet(x,g2,'binomial'); % glmnetPredict(fit2, x(2:5,:),[], 'response') % glmnetPredict(fit2, [], [], 'nonzero') % fit3=glmnet(x,g4,'multinomial'); % glmnetPredict(fit3, x(1:3,:), 0.01, 'response') % % DEVELOPMENT: % 14 Jul 2009: Original version of glmnet.m written. % 30 Aug 2013: Updated glmnet.m with more options and more models % (multi-response Gaussian, cox and Poisson models) supported. % OLDER UPDATES: % 20 Oct 2009: Fixed a bug in bionomial response, pointed out by Ramon % Casanov from Wake Forest University. % 26 Jan 2010: Fixed a bug in multinomial link and class, pointed out by % Peter Rijnbeek from Erasmus University. % 23 Jun 2010: Fixed a bug in multinomial with s, pointed out by % Robert Jacobsen from Aalborg University. if nargin < 2 || isempty(newx) newx = []; end if nargin < 3 s = []; end if nargin < 4 || isempty(type) type = 'link'; end if nargin < 5 || isempty(exact) exact = false; end if nargin < 6 offset = []; end typebase = {'link','response','coefficients','nonzero','class'}; typeind = find(strncmp(type,typebase,length(type)),1); type = typebase{typeind}; if isempty(newx) if ~strcmp(type, 'coefficients') && ~strcmp(type, 'nonzero') error('You need to supply a value for ''newx'''); end end %exact case: need to execute statements back in the parent environment if (exact && ~isempty(s)) which = ismember(s,object.lambda); if ~all(which) lambda = unique([object.lambda;reshape(s,length(s),1)]); %-----create a new variable in the parent environment vname = 'newlam'; expr = sprintf('any(strcmp(''%s'', who))',vname); newname = vname; i = 0; while (evalin('caller',expr)) i = i + 1; newname = [vname,num2str(i)]; expr = sprintf('any(strcmp(who,''%s''))',newname); end parlam = newname; %----- assignin('caller', parlam, lambda); vname = 'temp_opt'; expr = sprintf('any(strcmp(''%s'', who))',vname); newname = vname; i = 0; while (evalin('caller',expr)) i = i + 1; newname = [vname,num2str(i)]; expr = sprintf('any(strcmp(who,''%s''))',newname); end paropt = newname; if strcmp('[]',object.call{3}) famcall = object.call{3}; else famcall = sprintf('''%s''',object.call{3}); end if ~strcmp('[]', object.call{4}) evalin('caller', strcat(paropt,'=',object.call{4},';')); evalin('caller', strcat(paropt,'.lambda = ',parlam,';')); newcall = sprintf('glmnet(%s, %s, %s, %s)', ... object.call{1}, object.call{2}, famcall, paropt); object = evalin('caller', newcall); else evalin('caller', strcat(paropt,'.lambda = ',parlam,';')); newcall = sprintf('glmnet(%s, %s, %s, %s)', ... object.call{1}, object.call{2}, famcall, paropt); object = evalin('caller', newcall); end evalin('caller', sprintf('clearvars %s %s;',parlam,paropt)); end end if strcmp(object.class,'elnet') a0 = transpose(object.a0); nbeta=[a0; object.beta]; if (~isempty(s)) lambda=object.lambda; lamlist=lambda_interp(lambda,s); nbeta=nbeta(:,lamlist.left).*repmat(lamlist.frac',size(nbeta,1),1) +nbeta(:,lamlist.right).*(1-repmat(lamlist.frac',size(nbeta,1),1)); end if strcmp(type, 'coefficients') result = nbeta; return; end if strcmp(type, 'nonzero') result = nonzeroCoef(nbeta(2:size(nbeta,1),:), true); return; end result = [ones(size(newx,1),1), newx] * nbeta; if (object.offset) if isempty(offset) error('No offset provided for prediction, yet used in fit of glmnet'); end if (size(offset,2)==2) offset = offset(:,2); end result = result + repmat(offset, 1, size(result, 2)); end end if strcmp(object.class,'fishnet') a0 = transpose(object.a0); nbeta=[a0; object.beta]; if (~isempty(s)) lambda=object.lambda; lamlist=lambda_interp(lambda,s); nbeta=nbeta(:,lamlist.left).*repmat(lamlist.frac',size(nbeta,1),1) +nbeta(:,lamlist.right).*(1-repmat(lamlist.frac',size(nbeta,1),1)); end if strcmp(type, 'coefficients') result = nbeta; return; end if strcmp(type, 'nonzero') result = nonzeroCoef(nbeta(2:size(nbeta,1),:), true); return; end result = [ones(size(newx,1),1), newx] * nbeta; if (object.offset) if isempty(offset) error('No offset provided for prediction, yet used in fit of glmnet'); end if (size(offset,2) == 2) offset = offset(:, 2); end result = result + repmat(offset, 1, size(result,2)); end if strcmp(type, 'response') result = exp(result); end end if strcmp(object.class, 'lognet') a0 = object.a0; nbeta=[a0; object.beta]; if (~isempty(s)) lambda=object.lambda; lamlist=lambda_interp(lambda,s); nbeta=nbeta(:,lamlist.left).*repmat(lamlist.frac',size(nbeta,1),1) +nbeta(:,lamlist.right).*(1-repmat(lamlist.frac',size(nbeta,1),1)); end if strcmp(type, 'coefficients') result = nbeta; return; end if strcmp(type, 'nonzero') result = nonzeroCoef(nbeta(2:size(nbeta,1),:), true); return; end result = [ones(size(newx,1),1), newx] * nbeta; if (object.offset) if isempty(offset) error('No offset provided for prediction, yet used in fit of glmnet'); end if (size(offset,2)==2) offset = offset(:,2); end result = result + repmat(offset, 1, size(result, 2)); end switch type case 'response' pp = exp(-result); result = 1./ (1+pp); case 'class' result = (result > 0) * 2 + (result <= 0) * 1; result = object.label(result); end end if strcmp(object.class, 'multnet') || strcmp(object.class,'mrelnet') if strcmp(object.class,'mrelnet') if strcmp(type, 'response') type = 'link'; end object.grouped = true; end a0=object.a0; nbeta=object.beta; nclass=size(a0,1); nlambda=length(s); if (~isempty(s)) lambda=object.lambda; lamlist=lambda_interp(lambda,s); for i=1:nclass kbeta=[a0(i,:); nbeta{i}]; kbeta=kbeta(:,lamlist.left).*repmat(lamlist.frac',size(kbeta,1),1)+kbeta(:,lamlist.right).*(1-repmat(lamlist.frac',size(kbeta,1),1)); nbeta{i}=kbeta; end else for i=1:nclass nbeta{i} = [a0(i,:);nbeta{i}]; end nlambda = length(object.lambda); end if strcmp(type, 'coefficients') result = nbeta; return; end if strcmp(type, 'nonzero') if (object.grouped) result{1} = nonzeroCoef(nbeta{1}(2:size(nbeta{1},1),:),true); else for i=1:nclass result{i}=nonzeroCoef(nbeta{i}(2:size(nbeta{i},1),:),true); end end return; end npred=size(newx,1); dp = zeros(nclass,nlambda,npred); for i=1:nclass fitk = [ones(size(newx,1),1), newx] * nbeta{i}; dp(i,:,:)=dp(i,:,:)+reshape(transpose(fitk),1,nlambda,npred); end if (object.offset) if (isempty(offset)) error('No offset provided for prediction, yet used in fit of glmnet'); end if (size(offset,2) ~= nclass) error('Offset should be dimension%dx%d',npred,nclass) end toff = transpose(offset); for i = 1:nlambda dp(:,i,:) = dp(:,i,:) + toff; end end switch type case 'response' pp = exp(dp); psum = sum(pp,1); result = permute(pp./repmat(psum,nclass,1),[3,1,2]); case 'link' result=permute(dp,[3,1,2]); case 'class' dp=permute(dp,[3,1,2]); result = []; for i=1:size(dp,3) result = [result, object.label(softmax(dp(:,:,i)))]; end end end if strcmp(object.class,'coxnet') nbeta = object.beta; if (~isempty(s)) lambda=object.lambda; lamlist=lambda_interp(lambda,s); nbeta=nbeta(:,lamlist.left).*repmat(lamlist.frac',size(nbeta,1),1) +nbeta(:,lamlist.right).*(1-repmat(lamlist.frac',size(nbeta,1),1)); end if strcmp(type, 'coefficients') result = nbeta; return; end if strcmp(type, 'nonzero') result = nonzeroCoef(nbeta, true); return; end result = newx * nbeta; if (object.offset) if isempty(offset) error('No offset provided for prediction, yet used in fit of glmnet'); end result = result + repmat(offset, 1, size(result, 2)); end if strcmp(type, 'response') result = exp(result); end end %------------------------------------------------------------- % End private function glmnetPredict %------------------------------------------------------------- function result = lambda_interp(lambda,s) % lambda is the index sequence that is produced by the model % s is the new vector at which evaluations are required. % the value is a vector of left and right indices, and a vector of fractions. % the new values are interpolated bewteen the two using the fraction % Note: lambda decreases. you take: % sfrac*left+(1-sfrac*right) if length(lambda)==1 % degenerate case of only one lambda nums=length(s); left=ones(nums,1); right=left; sfrac=ones(nums,1); else s(s > max(lambda)) = max(lambda); s(s < min(lambda)) = min(lambda); k=length(lambda); sfrac =(lambda(1)-s)/(lambda(1) - lambda(k)); lambda = (lambda(1) - lambda)/(lambda(1) - lambda(k)); coord = interp1(lambda, 1:length(lambda), sfrac); left = floor(coord); right = ceil(coord); sfrac=(sfrac-lambda(right))./(lambda(left) - lambda(right)); sfrac(left==right)=1; end result.left = left; result.right = right; result.frac = sfrac; %------------------------------------------------------------- % End private function lambda_interp %------------------------------------------------------------- function result = softmax(x, gap) if nargin < 2 gap = false; end d = size(x); maxdist = x(:, 1); pclass = repmat(1, d(1), 1); for i =2:d(2) l = x(:, i) > maxdist; pclass(l) = i; maxdist(l) = x(l, i); end if gap x = abs(maxdist - x); x(1:d(1), pclass) = x * repmat(1, d(2)); gaps = pmin(x); end if gap result = {pclass, gaps}; else result = pclass; end %------------------------------------------------------------- % End private function softmax %-------------------------------------------------------------
github
shangjingbo1226/DPPred-master
fishnet.m
.m
DPPred-master/glmnet_matlab/fishnet.m
1,567
utf_8
a38133450377adad1e403b48017b5d9e
function fit = fishnet(x,is_sparse,irs,pcs,y,weights,offset,parm,nobs,nvars,... jd,vp,cl,ne,nx,nlam,flmin,ulam,thresh,isd,intr,maxit,family) if any(y < 0) error('negative responses encountered; not permitted for Poisson family'); end if isempty(offset) offset = y * 0; is_offset = false; else is_offset = true; end if (is_sparse) task = 50; [lmu,a0,ca,ia,nin,dev,alm,nlp,jerr,dev0,ot] = glmnetMex(task,parm,x,y,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,cl,intr,maxit,offset,irs,pcs); else task = 51; [lmu,a0,ca,ia,nin,dev,alm,nlp,jerr,dev0,ot] = glmnetMex(task,parm,x,y,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,cl,intr,maxit,offset); end if (jerr ~= 0) errmsg = err(jerr,maxit,nx,family); if (errmsg.fatal) error(errmsg.msg); else warning(errmsg.msg); end end ninmax = max(nin); lam = alm; if (ulam == 0.0) lam = fix_lam(lam); % first lambda is infinity; changed to entry point end dd=[nvars, lmu]; if ninmax > 0 ca = ca(1:ninmax,:); df = sum(abs(ca) > 0, 1); ja = ia(1:ninmax); [ja1,oja] = sort(ja); beta = zeros(nvars, lmu); beta (ja1, :) = ca(oja,:); else beta = zeros(nvars,lmu); df = zeros(1,lmu); end fit.a0 = a0; fit.beta = beta; fit.dev = dev; fit.nulldev = dev0; fit.df = df'; fit.lambda = lam; fit.npasses = nlp; fit.jerr = jerr; fit.dim = dd; fit.offset = is_offset; fit.class = 'fishnet'; function new_lam = fix_lam(lam) new_lam = lam; if (length(lam) > 2) llam=log(lam); new_lam(1)=exp(2*llam(2)-llam(3)); end
github
shangjingbo1226/DPPred-master
cvmrelnet.m
.m
DPPred-master/glmnet_matlab/cvmrelnet.m
2,101
utf_8
d369fd63346be95c8ff0d36501321ea1
function result = cvmrelnet(object, lambda, x, y, weights, offset, foldid, ... type, grouped, keep) if nargin < 10 || isempty(keep) keep = false; end typenames = struct('deviance','Mean-Squared Error','mse','Mean-Squared Error',... 'mae','Mean Absolute Error'); if strcmp(type,'default') type = 'mse'; end if ~any(strcmp(type,{'mse','mae','deviance'})) warning('Only ''mse'',''deviance'' or ''mae'' available for multiresponse Gaussian models; ''mse'' used'); type = 'mse'; end [nobs, nc] = size(y); if ~isempty(offset) y = y - offset; end predmat = NaN(nobs,nc,length(lambda)); nfolds = max(foldid); nlams = nfolds; for i = 1:nfolds which = foldid == i; fitobj = object{i}; fitobj.offset = false; preds = glmnetPredict(fitobj,x(which,:)); nlami = length(object{i}.lambda); predmat(which,:,1:nlami) = preds; nlams(i) = nlami; end N = nobs - reshape(sum(isnan(predmat(:,1,:)),1),1,[]); bigY = repmat(y, [1,1,length(lambda)]); switch type case 'mse' cvraw = squeeze(sum((bigY - predmat).^2, 2)); case 'mae' cvraw = squeeze(sum(abs(bigY - predmat), 2)); end if (nobs/nfolds < 3) && grouped warning('Option grouped=false enforced in cv.glmnet, since < 3 observations per fold'); grouped = false; end if (grouped) cvob = cvcompute(cvraw, weights, foldid, nlams); cvraw = cvob.cvraw; weights = cvob.weights; N = cvob.N; end % end cvm = wtmean(cvraw,weights); sqccv = (bsxfun(@minus,cvraw,cvm)).^2; cvsd = sqrt(wtmean(sqccv,weights)./(N-1)); result.cvm = cvm; result.cvsd = cvsd; result.name = typenames.(type); if (keep) result.fit_preval = predmat; end function result = glmnet_softmax(x) d = size(x); nas = any(isnan(x),2); if any(nas) pclass = NaN(d(1),1); if (sum(nas) < d(1)) pclass2 = glmnet_softmax(x(~nas,:)); pclass(~nas) = pclass2; result = pclass; end else maxdist = x(:,1); pclass = ones(d(1),1); for i = 2:d(2) l = x(:,i)>maxdist; pclass(l) = i; maxdist(l) = x(l,i); end result = pclass; end
github
shangjingbo1226/DPPred-master
cvmultnet.m
.m
DPPred-master/glmnet_matlab/cvmultnet.m
2,980
utf_8
245d373006161331bd149a8cc0756fcd
function result = cvmultnet(object, lambda, x, y, weights, offset, foldid, ... type, grouped, keep) if nargin < 10 || isempty(keep) keep = false; end typenames = struct('mse','Mean-Squared Error','mae','Mean Absolute Error',... 'deviance','Multinomial Deviance','class','Misclassification Error'); if strcmp(type,'default') type = 'deviance'; end if ~any(strcmp(type,{'mse','mae','deviance','class'})) warning('Only ''deviance'', ''class'', ''mse'' or ''mae'' available for multinomial models; ''deviance'' used'); type = 'deviance'; end prob_min = 1e-5; prob_max = 1 - prob_min; nc = size(y); if nc(2) == 1 [classes,~,sy] = unique(y); nc = length(classes); indexes = eye(nc); y = indexes(sy,:); else nc = nc(2); end is_offset = ~isempty(offset); predmat = NaN(size(y,1),nc,length(lambda)); nfolds = max(foldid); nlams = zeros(nfolds,1); for i = 1:nfolds which = foldid==i; fitobj = object{i}; if (is_offset) off_sub = offset(which,:); else off_sub = []; end preds = glmnetPredict(fitobj,x(which,:),[],'response',[],off_sub); nlami = length(object{i}.lambda); predmat(which,:,1:nlami) = preds; nlams(i) = nlami; end ywt = sum(y, 2); y = y ./ repmat(ywt,1,size(y,2)); weights = weights .* ywt; N = size(y,1) - sum(isnan(predmat(:,1,:)),1); bigY = repmat(y, [1,1,length(lambda)]); switch type case 'mse' cvraw = squeeze(sum((bigY - predmat).^2, 2)); case 'mae' cvraw = squeeze(sum(abs(bigY - predmat), 2)); case 'deviance' predmat = min(max(predmat,prob_min),prob_max); lp = bigY .* log(predmat); ly = bigY .* log(bigY); ly(bigY == 0) = 0; cvraw = squeeze(sum(2 * (ly - lp), 2)); case 'class' classid = NaN(size(y,1),length(lambda)); for i = 1:length(lambda) classid(:,i) = glmnet_softmax(predmat(:,:,i)); end classid = reshape(classid,[],1); yperm = reshape(permute(bigY, [1,3,2]),[],nc); idx = sub2ind(size(yperm), 1:length(classid), classid'); cvraw = reshape(1 - yperm(idx), [], length(lambda)); end if (grouped) cvob = cvcompute(cvraw, weights, foldid, nlams); cvraw = cvob.cvraw; weights = cvob.weights; N = cvob.N; end cvm = wtmean(cvraw,weights); sqccv = (bsxfun(@minus,cvraw,cvm)).^2; cvsd = sqrt(wtmean(sqccv,weights)./(N-1)); result.cvm = cvm; result.cvsd = cvsd; result.name = typenames.(type); if (keep) result.fit_preval = predmat; end function result = glmnet_softmax(x) d = size(x); nas = any(isnan(x),2); if any(nas) pclass = NaN(d(1),1); if (sum(nas) < d(1)) pclass2 = glmnet_softmax(x(~nas,:)); pclass(~nas) = pclass2; result = pclass; end else maxdist = x(:,1); pclass = ones(d(1),1); for i = 2:d(2) l = x(:,i)>maxdist; pclass(l) = i; maxdist(l) = x(l,i); end result = pclass; end
github
shangjingbo1226/DPPred-master
lognet.m
.m
DPPred-master/glmnet_matlab/lognet.m
4,177
utf_8
c749bb59e945862ae7b1962afc11fbfc
function fit = lognet(x,is_sparse,irs,pcs,y,weights,offset,parm,nobs,nvars,... jd,vp,cl,ne,nx,nlam,flmin,ulam,thresh,isd,intr,maxit,kopt,family) [noo,nc] = size(y); if noo ~= nobs error('x and y have different number of rows in call to glmnet'); end if nc == 1 [classes,~,sy] = unique(y); nc = length(classes); indexes = eye(nc); y = indexes(sy,:); else classes = 1: nc; end if strcmp(family, 'binomial') if nc > 2 error ('More than two classes; use multinomial family instead'); end nc = 1; % for calling binomial y = y(:,[2,1]); end o = []; if ~isempty(weights) % check if any are zero o = weights > 0; if ~all(o) %subset the data y = y(o,:); x = x(o,:); weights = weights(o); nobs = sum(o); else o = []; end [my,ny] = size(y); y = y .* repmat(weights,1,ny); end if isempty(offset) offset = y * 0; is_offset = false; else if ~isempty(o) offset = offset(o,:); end do = size(offset); if (do(1) ~= nobs) error('offset should have the same number of values as observations in binomial/multinomial call to glmnet'); end if (nc == 1) if (do(2) == 1) offset = cat(2,offset,-offset); end if (do(2) > 2) error('offset should have 1 or 2 columns in binomial call to glmnet'); end end if strcmp(family,'multinomial') && (do(2) ~= nc) error('offset should have same shape as y in multinomial call to glmnet'); end is_offset = true; end if (is_sparse) task = 20; [lmu,a0,ca,ia,nin,dev,alm,nlp,jerr,dev0,ot] = glmnetMex(task,parm,x,y,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,cl,intr,maxit,nc,kopt,offset,irs,pcs); else task = 21; [lmu,a0,ca,ia,nin,dev,alm,nlp,jerr,dev0,ot] = glmnetMex(task,parm,x,y,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,cl,intr,maxit,nc,kopt,offset); end if (jerr ~= 0) errmsg = err(jerr,maxit,nx,family); if (errmsg.fatal) error(errmsg.msg); else warning(errmsg.msg); end end ninmax = max(nin); lam = alm; if (ulam == 0.0) lam = fix_lam(lam); % first lambda is infinity; changed to entry point end if strcmp(family, 'multinomial') beta_list = {}; a0 = a0 - repmat(mean(a0), nc, 1); %multinomial: center the coefficients dfmat=a0; dd=[nvars, lmu]; if ninmax > 0 ca = reshape(ca, nx, nc, lmu); ca = ca(1:ninmax,:,:); ja = ia(1:ninmax); [ja1,oja] = sort(ja); df = any(abs(ca) > 0, 2); df = sum(df, 1); df = df(:)'; for k=1:nc ca1 = reshape(ca(:,k,:), ninmax, lmu); cak = ca1(oja,:); dfmat(k,:) = sum(abs(cak) > 0, 1); beta = zeros(nvars, lmu); beta(ja1,:) = cak; beta_list{k} = beta; end else for k = 1:nc dfmat(k,:) = zeros(1,lmu); beta_list{k} = zeros(nvars, lmu); end df = zeros(1,lmu); end fit.a0 = a0; fit.label = classes; fit.beta = beta_list; fit.dev = dev; fit.nulldev = dev0; fit.dfmat = dfmat; fit.df = df'; fit.lambda = lam; fit.npasses = nlp; fit.jerr = jerr; fit.dim = dd; if (kopt == 2) grouped = true; else grouped = false; end fit.grouped = grouped; fit.offset = is_offset; fit.class = 'multnet'; else dd=[nvars, lmu]; if ninmax > 0 ca = ca(1:ninmax,:); df = sum(abs(ca) > 0, 1); ja = ia(1:ninmax); [ja1,oja] = sort(ja); beta = zeros(nvars, lmu); beta (ja1, :) = ca(oja,:); else beta = zeros(nvars,lmu); df = zeros(1,lmu); end fit.a0 = a0; fit.label = classes; fit.beta = beta; %sign flips make 2 arget class fit.dev = dev; fit.nulldev = dev0; fit.df = df'; fit.lambda = lam; fit.npasses = nlp; fit.jerr = jerr; fit.dim = dd; fit.offset = is_offset; fit.class = 'lognet'; end function new_lam = fix_lam(lam) new_lam = lam; if (length(lam) > 2) llam=log(lam); new_lam(1)=exp(2*llam(2)-llam(3)); end
github
shangjingbo1226/DPPred-master
elnet.m
.m
DPPred-master/glmnet_matlab/elnet.m
1,671
utf_8
5e93be0d78726b154d27eed1f02e36be
function fit = elnet(x, is_sparse, irs, pcs, y, weights, offset, gtype, ... parm, lempty, nvars, jd, vp, cl, ne, nx, nlam, flmin, ulam, thresh, ... isd, intr, maxit, family) ybar = y' * weights/ sum(weights); nulldev = (y' - ybar).^2 * weights; ka = find(strncmp(gtype,{'covariance','naive'},length(gtype)),1); if isempty(ka) error('unrecognized type'); end if isempty(offset) offset = y * 0; is_offset = false; else is_offset = true; end if is_sparse task = 10; [lmu,a0,ca,ia,nin,rsq,alm,nlp,jerr] = glmnetMex(task,parm,x,y-offset,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,ka,cl,intr,maxit,irs,pcs); else task = 11; [lmu,a0,ca,ia,nin,rsq,alm,nlp,jerr] = glmnetMex(task,parm,x,y-offset,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,ka,cl,intr,maxit); end if (jerr ~= 0) errmsg = err(jerr,maxit,nx,family); if (errmsg.fatal) error(errmsg.msg); else warning(errmsg.msg); end end ninmax = max(nin); lam = alm; if lempty lam = fix_lam(lam); % first lambda is infinity; changed to entry point end dd=[nvars, lmu]; if ninmax > 0 ca = ca(1:ninmax,:); df = sum(abs(ca) > 0, 1); ja = ia(1:ninmax); [ja1,oja] = sort(ja); beta = zeros(nvars, lmu); beta (ja1, :) = ca(oja,:); else beta = zeros(nvars,lmu); df = zeros(1,lmu); end fit.a0 = a0; fit.beta = beta; fit.dev = rsq; fit.nulldev = nulldev; fit.df = df'; fit.lambda = lam; fit.npasses = nlp; fit.jerr = jerr; fit.dim = dd; fit.offset = is_offset; fit.class = 'elnet'; function new_lam = fix_lam(lam) new_lam = lam; if (length(lam) > 2) llam=log(lam); new_lam(1)=exp(2*llam(2)-llam(3)); end
github
shangjingbo1226/DPPred-master
cvcoxnet.m
.m
DPPred-master/glmnet_matlab/cvcoxnet.m
2,338
utf_8
eed15cafcfb188d8f0abde603f2b3ee9
function result = cvcoxnet(object, lambda, x, y, weights, offset, foldid, ... type, grouped, keep) % Internal glmnet function. See also cvglmnet. if nargin < 10 || isempty(keep) keep = false; end typenames = struct('deviance','Partial Likelihood Deviance'); if strcmp(type, 'default') type = 'deviance'; end if ~any(strcmp(type, {'deviance'})) warning('Only ''deviance'' available for Cox models; changed to type=''deviance'''); type = 'deviance'; end if isempty(offset) offset = zeros(size(x,1),1); end nfolds = max(foldid); if (length(weights)/nfolds < 10) && ~grouped warning('Option grouped=true enforced for cv.coxnet, since < 3 observations per fold'); grouped = true; end cvraw = NaN(nfolds,length(lambda)); for i = 1:nfolds which = foldid == i; fitobj = object{i}; coefmat = glmnetPredict(fitobj,[],[],'coefficients'); if (grouped) plfull = cox_deviance([],y,x,offset,weights,coefmat); plminusk = cox_deviance([],y(~which,:),x(~which,:),offset(~which),... weights(~which),coefmat); cvraw(i,1:length(plfull)) = plfull - plminusk; else plk = cox_deviance([],y(which,:),x(which,:),offset(which),... weights(which),coefmat); cvraw(i,1:length(plk)) = plk; end end status = y(:,2); N = nfolds - sum(isnan(cvraw),1); weights = accumarray(reshape(foldid,[],1),weights.*status); cvraw = bsxfun(@rdivide,cvraw,weights); %even some weight = 0 does matter because of adjustment in wtmean! cvm = wtmean(cvraw,weights); sqccv = (bsxfun(@minus,cvraw,cvm)).^2; cvsd = sqrt(wtmean(sqccv,weights)./(N-1)); result.cvm = cvm; result.cvsd = cvsd; result.name = typenames.(type); if (keep) warning('keep=TRUE not implemented for coxnet'); end function result = cox_deviance(pred, y, x, offset, weights, beta) ty = y(:,1); tevent = y(:,2); nobs = length(ty); nvars = size(x,2); if isempty(weights) weights = ones(nobs,1); end if isempty(offset) offset = zeros(nobs,1); end if isempty(beta) beta = []; nvec = 1; nvars = 0; else nvec = size(beta,2); end task = 42; [flog, jerr] = glmnetMex(task,x,ty,tevent,offset,weights,nvec,beta); if (jerr ~= 0) errmsg = err(jerr,0,0,'cox'); if (errmsg.fatal) error(errmsg.msg); else warning(errmsg.msg); end end result = -2 * flog;
github
shangjingbo1226/DPPred-master
cvfishnet.m
.m
DPPred-master/glmnet_matlab/cvfishnet.m
1,872
utf_8
d7cb4820ff676ff3db1adcb0418e402f
function result = cvfishnet(object,lambda,x,y,weights,offset,foldid,type,grouped,keep) % Internal glmnet function. See also cvglmnet. if nargin < 10 || isempty(keep) keep = false; end typenames = struct('mse','Mean-Squared Error','mae','Mean Absolute Error','deviance','Poisson Deviance'); if strcmp(type, 'default') type = 'deviance'; end if ~any(strcmp(type, {'mse','mae','deviance'})) warning('Only ''mse'', ''deviance'' or ''mae'' available for Poisson models; ''deviance'' used'); type = 'deviance'; end is_offset = ~isempty(offset); predmat = NaN(length(y),length(lambda)); nfolds = max(foldid); nlams = nfolds; for i = 1:nfolds which = foldid == i; fitobj = object{i}; if (is_offset) off_sub = offset(which); else off_sub = []; end preds = glmnetPredict(fitobj,x(which,:),[],[],[],off_sub); nlami = length(object{i}.lambda); predmat(which,1:nlami) = preds; nlams(i) = nlami; end N = size(y,1) - sum(isnan(predmat),1); yy = repmat(y, 1, length(lambda)); switch type case 'mse' cvraw = (yy - predmat).^2; case 'mae' cvraw = abs(yy - predmat); case 'deviance' cvraw = devi(yy, predmat); end if (length(y)/nfolds < 3) && grouped warning('Option grouped=false enforced in cv.glmnet, since < 3 observations per fold'); grouped = false; end if (grouped) cvob = cvcompute(cvraw,weights,foldid,nlams); cvraw = cvob.cvraw; weights = cvob.weights; N = cvob.N; end cvm = wtmean(cvraw,weights); sqccv = (bsxfun(@minus,cvraw,cvm)).^2; cvsd = sqrt(wtmean(sqccv,weights)./(N-1)); result.cvm = cvm; result.cvsd = cvsd; result.name = typenames.(type); if (keep) result.fit_preval = predmat; end function result = devi(yy, eta) deveta = yy .* eta - exp(eta); devy = yy .* log(yy) - yy; devy(yy == 0) = 0; result = 2 * (devy - deveta);
github
shangjingbo1226/DPPred-master
cvlognet.m
.m
DPPred-master/glmnet_matlab/cvlognet.m
4,184
utf_8
265205120a633a060736651a5eee583d
function result = cvlognet(object, lambda, x, y, weights, offset, foldid, ... type, grouped, keep) if nargin < 10 || isempty(keep) keep = false; end typenames = struct('mse','Mean-Squared Error','mae','Mean Absolute Error',... 'deviance','Binomial Deviance','auc','AUC','class','Misclassification Error'); if strcmp(type,'default') type = 'deviance'; end if ~any(strcmp(type,{'mse','mae','deviance','auc','class'})) warning('Only ''deviance'', ''class'', ''auc'', ''mse'' or ''mae'' available for binomial models; ''deviance'' used'); type = 'deviance'; end prob_min = 1e-5; prob_max = 1 - prob_min; nc = size(y); if nc(2) == 1 [classes,~,sy] = unique(y); nc = length(classes); indexes = eye(nc); y = indexes(sy,:); end N = size(y,1); nfolds = max(foldid); if (N/nfolds < 10) && strcmp(type,'auc') warning(strcat('Too few (< 10) observations per fold for type.measure=''auc'' in cv.lognet; ',... 'changed to type.measure=''deviance''. Alternatively, use smaller value for nfolds')); type = 'deviance'; end if (N/nfolds < 3) && grouped warning(strcat('Option grouped=FALSE enforced in cv.glmnet, ',... 'since < 3 observations per fold')); grouped = false; end is_offset = ~isempty(offset); predmat = NaN(size(y,1),length(lambda)); nlams = zeros(nfolds,1); for i = 1:nfolds which = foldid==i; fitobj = object{i}; if (is_offset) off_sub = offset(which,:); else off_sub = []; %a bit different from that in R end preds = glmnetPredict(fitobj,x(which,:),[],'response',[],off_sub); nlami = length(object{i}.lambda); predmat(which,1:nlami) = preds; nlams(i) = nlami; end if strcmp(type,'auc') cvraw = NaN(nfolds, length(lambda)); good = zeros(nfolds, length(lambda)); for i = 1:nfolds good(i,1:nlams(i)) = 1; which = foldid == i; for j = 1:nlams(i) cvraw(i,j) = auc_mat(y(which,:), predmat(which,j), weights(which)); end end N = sum(good,1); sweights = zeros(nfolds, 1); for i = 1:nfolds sweights(i) = sum(weights(foldid==i)); end weights = sweights; else ywt = sum(y, 2); y = y ./ repmat(ywt,1,size(y,2)); weights = weights .* ywt; N = size(y,1) - sum(isnan(predmat),1); yy1 = repmat(y(:,1),1,length(lambda)); yy2 = repmat(y(:,2),1,length(lambda)); switch type case 'mse' cvraw = (yy1 - (1 - predmat)).^2 + (yy2 - (1 - predmat)).^2; case 'mae' cvraw = abs(yy1 - (1 - predmat)) + abs(yy2 - (1 - predmat)); case 'deviance' predmat = min(max(predmat,prob_min),prob_max); lp = yy1.*log(1-predmat) + yy2.*log(predmat); ly = log(y); ly(y == 0) = 0; ly = (y.*ly) * [1;1]; cvraw = 2 * (repmat(ly,1,length(lambda)) - lp); case 'class' cvraw = yy1.*(predmat > 0.5) + yy2.*(predmat <= 0.5); end if (grouped) cvob = cvcompute(cvraw, weights, foldid, nlams); cvraw = cvob.cvraw; weights = cvob.weights; N = cvob.N; end end cvm = wtmean(cvraw,weights); sqccv = (bsxfun(@minus,cvraw,cvm)).^2; cvsd = sqrt(wtmean(sqccv,weights)./(N-1)); result.cvm = cvm; result.cvsd = cvsd; result.name = typenames.(type); if (keep) result.fit_preval = predmat; end function result = auc_mat(y, prob, weights) if nargin < 3 || isempty(weights) weights = ones(size(y,1),1); end Weights = bsxfun(@times,weights,y); Weights = Weights(:)'; ny = size(y,1); Y = [zeros(ny,1);ones(ny,1)]; Prob = [prob; prob]; result = auc(Y, Prob, Weights); function result = auc(y, prob, w) if isempty(w) mindiff = min(diff(unique(prob))); pert = unifrnd(0,mindiff/3,size(prob)); [~,~,rprob] = unique(prob+pert); n1 = sum(y); n0 = length(y) - n1; u = sum(rprob(y == 1)) - n1*(n1+1)/2; result = u / (n1*n0); else [~,op] = sort(prob); y = y(op); w = w(op); cw = cumsum(w); w1 = w(y == 1); cw1 = cumsum(w1); wauc = sum(w1.*(cw(y==1)-cw1)); sumw = cw1(length(cw1)); sumw = sumw * (cw(length(cw)) - sumw); result = wauc / sumw; end
github
FelixWinterstein/FPGA-shared-mem-master
generate_data_points.m
.m
FPGA-shared-mem-master/examples/filtering_algorithm/host/data/generate_data_points.m
2,172
utf_8
deb2eed5cac280eaf68b63d34bd507ca
%********************************************************************** % Felix Winterstein, Imperial College London, 2016 % % File: generate_data_points % % Revision 1.01 % Additional Comments: distributed under an Apache-2.0 license, see LICENSE % %********************************************************************** function generate_data_points clear; clc; %% config N=2^20; D=3; K=128; Knew =K; std_dev = 0.10; M=1; fractional_bits = 10; gbl_seed_offset = 0; for file_idx=1:M %% generate data points %rng(16221+gbl_seed_offset); rand('seed',16221+gbl_seed_offset+file_idx); centres = 5*(rand(K,D)-0.5); points=zeros(N,D); for I=1:K for II=1:D %rng(4567+gbl_seed_offset+10*I+II); randn('seed',4567+gbl_seed_offset+10*I+II+file_idx); points((I-1)*N/K+1:N/K*I,II) = centres(I,II)+std_dev*randn(N/K,1); end end tmp=max([abs(min(points(:,1))),abs(max(points(:,1))),abs(min(points(:,2))),abs(max(points(:,2)))]); points=points/tmp; centres = centres/tmp; points=round(points*2^fractional_bits); centres=round(centres*2^fractional_bits); %% save data points to file tmp_points=reshape(points,D*N,1); % append 2nd dim after 1st dim fid=fopen(['./data_points','_N',num2str(N),'_K',num2str(K),'_D',num2str(D),'_s',num2str(std_dev,'%.2f'),'.mat'],'w'); for I=1:D*N fprintf(fid,'%d\n',tmp_points(I)); end fclose(fid); %% generate new random centres (pick K data points randomly) and save to file new_centres = zeros(Knew,D); %rng(4567+gbl_seed_offset+10000+II); rand('seed', 4567+gbl_seed_offset+10000+file_idx); new_centres_idx= round(rand(N,1)*N); new_centres_idx = new_centres_idx(1:Knew); %new_centres = points(new_centres_idx,:); %tmp_new_centres=reshape(new_centres,D*Knew,1); % append 2nd dim after 1st dim fid=fopen(['./initial_centers','_N',num2str(N),'_K',num2str(Knew),'_D',num2str(D),'_s',num2str(std_dev,'%.2f'),'_',num2str(file_idx),'.mat'],'w'); for I=1:Knew fprintf(fid,'%d\n',new_centres_idx(I)); end fclose(fid); end end
github
FelixWinterstein/FPGA-shared-mem-master
generate_data_points.m
.m
FPGA-shared-mem-master/examples/filtering_algorithm_no_svm/host/data/generate_data_points.m
2,172
utf_8
68f8ffaf55695f8a76b472d1df424125
%********************************************************************** % Felix Winterstein, Imperial College London, 2016 % % File: generate_data_points % % Revision 1.01 % Additional Comments: distributed under an Apache-2.0 license, see LICENSE % %********************************************************************** function generate_data_points clear; clc; %% config N=2^10; D=3; K=128; Knew =K; std_dev = 0.10; M=1; fractional_bits = 10; gbl_seed_offset = 0; for file_idx=1:M %% generate data points %rng(16221+gbl_seed_offset); rand('seed',16221+gbl_seed_offset+file_idx); centres = 5*(rand(K,D)-0.5); points=zeros(N,D); for I=1:K for II=1:D %rng(4567+gbl_seed_offset+10*I+II); randn('seed',4567+gbl_seed_offset+10*I+II+file_idx); points((I-1)*N/K+1:N/K*I,II) = centres(I,II)+std_dev*randn(N/K,1); end end tmp=max([abs(min(points(:,1))),abs(max(points(:,1))),abs(min(points(:,2))),abs(max(points(:,2)))]); points=points/tmp; centres = centres/tmp; points=round(points*2^fractional_bits); centres=round(centres*2^fractional_bits); %% save data points to file tmp_points=reshape(points,D*N,1); % append 2nd dim after 1st dim fid=fopen(['./data_points','_N',num2str(N),'_K',num2str(K),'_D',num2str(D),'_s',num2str(std_dev,'%.2f'),'.mat'],'w'); for I=1:D*N fprintf(fid,'%d\n',tmp_points(I)); end fclose(fid); %% generate new random centres (pick K data points randomly) and save to file new_centres = zeros(Knew,D); %rng(4567+gbl_seed_offset+10000+II); rand('seed', 4567+gbl_seed_offset+10000+file_idx); new_centres_idx= round(rand(N,1)*N); new_centres_idx = new_centres_idx(1:Knew); %new_centres = points(new_centres_idx,:); %tmp_new_centres=reshape(new_centres,D*Knew,1); % append 2nd dim after 1st dim fid=fopen(['./initial_centers','_N',num2str(N),'_K',num2str(Knew),'_D',num2str(D),'_s',num2str(std_dev,'%.2f'),'_',num2str(file_idx),'.mat'],'w'); for I=1:Knew fprintf(fid,'%d\n',new_centres_idx(I)); end fclose(fid); end end
github
ewine-project/Flexible-GFDM-PHY-master
read_ini_file.m
.m
Flexible-GFDM-PHY-master/Host/Reader/read_ini_file.m
2,463
utf_8
e3cf1e3ecd343ec9b56afbd0fa088639
function [ini_struct] = read_ini_file(filename) ini_struct = struct(); if (~exist('filename', 'var')) filename = ''; end if isempty(filename) [filename, pathname] = uigetfile('*.ini', 'Select a ini file'); if isequal(filename,0) error('User selected Cancel!') else disp(['User selected ', fullfile(pathname, filename)]) filename = fullfile(pathname, filename); end end fid = fopen(filename); cnt = 0; while (1) tline = fgetl(fid); cnt = cnt + 1; if (~ischar(tline)) %End of file break; end if (strfind(tline, '#')) %skip line because of a comment continue; end if (~strfind(tline, '=')) %skip line because there is nothing to read continue; end %Remove whitespace tline = strrep(tline, ' ', ''); %Split line in variable and value strings = strtrim(strsplit(tline,'=')); if length(strings) ~= 2 %something is wrong with the line disp(['Something is missing in line ' num2str(cnt) ': ' tline]); continue; end %Split if array is present values = strtrim(strsplit(strings{2},';')); %Is the first character a string? if (isstrprop(values{1,1}, 'alpha')) [zeilen, spalten] = size(values); if (spalten > 1) ini_struct.(strings{1}) = values; else ini_struct.(strings{1}) = values{1}; end else ini_struct.(strings{1}) = string_to_number(values); end end fclose(fid); end function number = string_to_number(str) number = []; [zeilen, spalten] = size(str); for i = 1:spalten value = strtrim(str{:,i}); %Convert complex number in a similar writing style value = strrep(value, 'I', 'i'); value = strrep(value, 'J', 'j'); %+i5 doesnt work it has to be +i*5 value = strrep(value, '+i*', '+i'); value = strrep(value, '+i', '+i*'); number = [number str2double(value)]; end end
github
ewine-project/Flexible-GFDM-PHY-master
write_ini_file.m
.m
Flexible-GFDM-PHY-master/Host/Reader/write_ini_file.m
2,907
utf_8
1db51ea5f88734a1e7ea4742f0afe1f1
function [file_string] = write_ini_file(filename, ini_struct) if (~exist('filename', 'var')) filename = ''; end if (~exist('ini_struct', 'var')) error('No data to be saved!') end if isempty(filename) [filename, pathname] = uiputfile('*.ini', 'Select a ini file'); if isequal(filename,0) error('User selected Cancel!') else disp(['User selected ', fullfile(pathname, filename)]) filename = fullfile(pathname, filename); end end %This string is then written into the file file_string = {}; if (exist(filename, 'file')) %% Update existing file fid = fopen(filename); cnt = 0; while (1) tline = fgetl(fid); cnt = cnt + 1; if (~ischar(tline)) %End of file break; end if (strfind(tline, '#')) file_string = {file_string{:} tline}; %skip line because of a comment continue; end if (~strfind(tline, '=')) file_string = {file_string{:} tline}; %skip line because there is nothing to read continue; end %Remove whitespace tline = strrep(tline, ' ', ''); %Split line in variable and value strings = strtrim(strsplit(tline,'=')); %this variable exist in our struct? if isfield(ini_struct, strings{1}) value = ini_struct.(strings{1}); tline = [strings{1} '=' value_to_string(value)]; end file_string = {file_string{:} tline}; end fclose(fid); else %% Create a new file fields = fieldnames(ini_struct); for line = 1:numel(fields) value = ini_struct.(fields{line}); file_string = {file_string{:} [fields{line} '=' value_to_string(value)]}; end end %% (Over-)write string into file fileID = fopen(filename, 'w'); [zeilen, spalten] = size(file_string); for i = 1:spalten fprintf(fileID,'%s\r\n', file_string{i}); end fclose(fileID); end function str = value_to_string(value) [zeilen,spalten] = size(value); str = []; if isnumeric(value) for i = 1:numel(value) str = [str num2str(value(i))]; if i ~= numel(value) str = [str ';']; end end elseif iscellstr(value) for i = 1:length(value) str = [str value{i}]; if i ~= numel(value) str = [str ';']; end end else str = value; end end
github
tangzhenyu/Scene-Text-Understanding-master
predict_depth.m
.m
Scene-Text-Understanding-master/SynthText_Chinese/prep_scripts/predict_depth.m
3,416
utf_8
f03754d767f958f0bea597bd0c3564cc
% MATLAB script to regress a depth mask for an image. % uses: (1) https://bitbucket.org/fayao/dcnf-fcsp/ % (2) vlfeat % (3) matconvnet % Author: Ankush Gupta function predict_depth() % setup vlfeat %run( '../libs/vlfeat-0.9.18/toolbox/vl_setup'); run( '/home/yuz/lijiahui/fayao-dcnf-fcsp/libs/vlfeat-0.9.18/toolbox/vl_setup'); % setup matconvnet % dir_matConvNet='../libs/matconvnet/matlab/'; dir_matConvNet='/home/yuz/lijiahui/fayao-dcnf-fcsp/libs/matconvnet_20141015/matlab/'; addpath(genpath(dir_matConvNet)); run([dir_matConvNet 'vl_setupnn.m']); opts=[]; opts.useGpu=false; opts.inpaint = true; opts.normalize_depth = false; % limit depth to [0,1] %opts.imdir = '/path/to/image/dir'; opts.imdir = '/home/yuz/lijiahui/syntheticdata/SynthText/img_dir'; %opts.out_h5 = '/path/to/save/output/depth.h5'; opts.out_h5 = '/home/yuz/lijiahui/syntheticdata/depth.h5'; % these should point to the pre-trained models from: % https://bitbucket.org/fayao/dcnf-fcsp/ opts.model_file.indoor = '/home/yuz/lijiahui/fayao-dcnf-fcsp/model_trained/model_dcnf-fcsp_NYUD2.mat'; opts.model_file.outdoor = '/home/yuz/lijiahui/fayao-dcnf-fcsp/model_trained/model_dcnf-fcsp_Make3D.mat'; fprintf('\nloading trained model...\n\n'); mdl = load(opts.model_file.indoor); model.indoor = mdl.data_obj; mdl = load(opts.model_file.outdoor); model.outdoor = mdl.data_obj; %if gpuDeviceCount==0 % fprintf(' ** No GPU found. Using CPU...\n'); % opts.useGpu=false; %end imnames = dir(fullfile(opts.imdir),'*'); imnames = {imnames.name}; N = numel(imnames); for i = 1:N fprintf('%d of %d\n',i,N); imname = imnames{i}; imtype = 'outdoor'; img = read_img_rgb(fullfile(opts.imdir,imname)); if strcmp(imtype, 'outdoor') opts.sp_size=16; opts.max_edge=600; elseif strcmp(imtype, 'indoor') opts.sp_size=20; opts.max_edge=640; end depth = get_depth(img,model.(imtype),opts); save_depth(imname,depth,opts); end end function save_depth(imname,depth,opts) dset_name = ['/',imname]; h5create(opts.out_h5, dset_name, size(depth), 'Datatype', 'single'); h5write(opts.out_h5, dset_name, depth); end function depth = get_depth(im_rgb,model,opts) % limit the maximum edge size of the image: if ~isempty(opts.max_edge) sz = size(im_rgb); [~,max_dim] = max(sz(1:2)); osz = NaN*ones(1,2); osz(max_dim) = opts.max_edge; im_rgb = imresize(im_rgb, osz); end % do super-pixels: fprintf(' > super-pix\n'); supix = gen_supperpixel_info(im_rgb, opts.sp_size); pinfo = gen_feature_info_pairwise(im_rgb, supix); % build "data-set": ds=[]; ds.img_idxes = 1; ds.img_data = im_rgb; ds.sp_info{1} = supix; ds.pws_info = pinfo; ds.sp_num_imgs = supix.sp_num; % run cnn: fprintf(' > CNN\n'); depth = do_model_evaluate(model, ds, opts); if opts.inpaint fprintf(' > inpaint\n'); depth = do_inpainting(depth, im_rgb, supix); end if opts.normalize_depth d_min = min(depth(:)); d_max = max(depth(:)); depth = (depth-d_min) / (d_max-d_min); depth(depth<0) = 0; depth(depth>1) = 1; end end predict_depth()
github
tangzhenyu/Scene-Text-Understanding-master
classification_demo.m
.m
Scene-Text-Understanding-master/ctpn_crnn_ocr/CTPN/caffe/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
karthik-kk/Autoware-master
velCapture.m
.m
Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/velCapture.m
1,047
utf_8
994f8bb886b3e3ebef61b89d3c9c00a9
% Function to capture catvehicle velocity and plotting live graph function velCapture(ROS_IP, roboname) %If number of argument is not two, flag message and exit. if nargin < 2 disp('Uage: velocityProfiler(192.168.0.32, catvehicle)'); return; end close all; %rosshutdown; modelname = strcat('/',roboname); %Connect to ROS master master_uri= strcat('http://',ROS_IP); master_uri = strcat(master_uri,':11311'); %rosinit(master_uri); %get handle for /catvehicle/vel topic for subscribing to the data speedsub = rossubscriber(strcat(modelname,'/vel')); dt = datestr(now,'mmmm-dd-yyyy-HH-MM-SS'); sprintf('Velocity capture starts at %s',dt) t = 0:0.05:50; output = zeros(length(t),1); figure; grid on; title('Velocity [m/s]'); for i = 1:length(t) speedata = receive(speedsub,10); output(i) = speedata.Linear.X; plot([max(i-1,1),i], output([max(i-1,1),i]),'b-'); hold on; drawnow; end dt = datestr(now,'mmmm-dd-yyyy-HH-MM-SS'); file = strcat(dt,'.mat'); save(file, 'output'); grid on; title('Velocity [m/s]'); end
github
karthik-kk/Autoware-master
profileByMatrix.m
.m
Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/profileByMatrix.m
1,840
utf_8
f81181e46cb60adc3466c4779083ce0d
%Implementation of follower algorithm %Developed by Rahul Kumar Bhadani <[email protected]> %ROS_IP = IP Address of ROS Master %lead = name of the model of leader AV Car %follower = name of the model of follower car function profileByMatrix(ROS_IP, roboname, vel_input, time_input, tire_angle) %If number of argument is not two, flag message and exit. if nargin < 4 sprintf('Uage: velocityProfiler(192.168.0.32, catvehicle, velmatfile, timematfile)'); return; end if nargin < 5 tire_angle = 0.0; end rosshutdown; close all; modelname = strcat('/',roboname); %Connect to ROS master master_uri= strcat('http://',ROS_IP); master_uri = strcat(master_uri,':11311'); rosinit(master_uri); %get handle for /catvehicle/cmd_vel topic for publishing the data velpub = rospublisher(strcat(modelname,'/cmd_vel'),rostype.geometry_msgs_Twist); %get handle for /catvehicle/vel topic for subscribing to the data speedsub = rossubscriber(strcat(modelname,'/vel')); vmat = load(vel_input); tmat = load(time_input); t = tmat.t; %Velocity profile input = vmat.Vel; %Velocity profile will be sine %input = abs(2*sin(t)); %Variable to store output velocity output = zeros(length(t),1); %handle for rosmessage object for velpub topic velMsgs = rosmessage(velpub); for i=1:length(t) velMsgs.Linear.X = input(i); velMsgs.Angular.Z = tire_angle; %Publish on the topic /catvehicle/cmd_vel send(velpub, velMsgs); %Read from the topic /catvehicle/speed speedata = receive(speedsub,10); output(i) = speedata.Linear.X; pause(0.1); if i == 3000 break; end end %Plot the input and output velocity profile [n, p] = size(output); T = 1:n; plot(T, input'); hold on; plot(T, output); title('Original Data'); legend('Input function', 'Output response'); grid on; save input.mat input output
github
karthik-kk/Autoware-master
velocityProfiler.m
.m
Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/velocityProfiler.m
1,758
utf_8
d12bb47043d421e21fc4fd4fa8ce4b02
%Matlab scripto to publish velocity on /catvehicle/cmd_vel topic and %subscribe to catvehicle/speed topic %Developed by Rahul Kumar Bhadani <[email protected]> %ROS_IP = IP Address of ROS Master %roboname = name of the model function velocityProfiler(ROS_IP, roboname, tire_angle) %If number of argument is not two, flag message and exit. if nargin < 2 sprintf('Uage: velocityProfiler(192.168.0.32, catvehicle)'); return; end if nargin < 3 tire_angle = 0.0; end rosshutdown; close all; modelname = strcat('/',roboname); %Connect to ROS master master_uri= strcat('http://',ROS_IP); master_uri = strcat(master_uri,':11311'); rosinit(master_uri); %get handle for /catvehicle/cmd_vel topic for publishing the data velpub = rospublisher(strcat(modelname,'/cmd_vel'),rostype.geometry_msgs_Twist); %get handle for /catvehicle/vel topic for subscribing to the data speedsub = rossubscriber(strcat(modelname,'/vel')); %Discretize timestamp t = 0:0.01:150; v1 = 3; v2 = 6; v3 = 0; %Velocity profile input = v1.*(t<50) + v2.*(t>=50).*(t<100) + v3.*(t>= 100); %Velocity profile will be sine %input = abs(2*sin(t)); %Variable to store output velocity output = zeros(length(t),1); %handle for rosmessage object for velpub topic velMsgs = rosmessage(velpub); for i=1:length(t) velMsgs.Linear.X = input(i); velMsgs.Angular.Z = tire_angle; %Publish on the topic /catvehicle/cmd_vel send(velpub, velMsgs); %Read from the topic /catvehicle/speed speedata = receive(speedsub,10); output(i) = speedata.Linear.X; end %Plot the input and output velocity profile [n, p] = size(output); T = 1:n; plot(T, input'); hold on; plot(T, output); title('Original Data'); legend('Input function', 'Output response'); grid on;
github
karthik-kk/Autoware-master
follower_profile.m
.m
Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/follower_profile.m
2,381
utf_8
ea7d00e67f5e7709a2cd7287216af4af
%Implementation of follower algorithm %Developed by Rahul Kumar Bhadani <[email protected]> %ROS_IP = IP Address of ROS Master %lead = name of the model of leader AV Car %follower = name of the model of follower car function follower_profile(ROS_IP, lead, follower) %If number of argument is not two, flag message and exit. if nargin < 2 sprintf('Usage: velocityProfiler(192.168.0.32, catvehicle)'); return; end rosshutdown; close all; modelname1 = strcat('/',lead); modelname2 = strcat('/',follower); %Connect to ROS master master_uri= strcat('http://',ROS_IP); master_uri = strcat(master_uri,':11311'); rosinit(master_uri); %get handle for cmd_vel topic for publishing the data velpub1 = rospublisher(strcat(modelname1,'/cmd_vel'),rostype.geometry_msgs_Twist); velpub2 = rospublisher(strcat(modelname2,'/cmd_vel'),rostype.geometry_msgs_Twist); %get handle for speed topic for subscribing to the data speedsub1 = rossubscriber(strcat(modelname1,'/vel')); speedsub2 = rossubscriber(strcat(modelname2,'/vel')); %get handle for /DistanceEstimator distanceEstimaterSub = rossubscriber('/DistanceEstimator/dist'); %Discretize timestamp t = 0:0.05:150; v1 = 3; v2 = 6; v3 = 0; %Velocity profile input = v1.*(t<50) + v2.*(t>=50).*(t<100) + v3.*(t>= 100); %Velocity profile will be sine %input = abs(2*sin(t)); %Variable to store output velocity output1 = zeros(length(t),1); output2 = zeros(length(t),1); %handle for rosmessage object for velpub topic velMsgs1 = rosmessage(velpub1); velMsgs2 = rosmessage(velpub2); for i=1:length(t) velMsgs1.Linear.X = input(i); velMsgs1.Angular.Z = 0.0; %Publish on the topic /catvehicle/cmd_vel send(velpub1, velMsgs1); %Read from the topic /catvehicle/speed speedata1 = receive(speedsub1,10); distance = receive(distanceEstimaterSub,10); x = distance.Data; %Follower control rule velMsgs2.Linear.X = (1/30.*x + 2/3).*speedata1.Linear.X; velMsgs2.Angular.Z = 0.0; send(velpub2, velMsgs2); speedata2 = receive(speedsub2,10); output1(i) = speedata1.Linear.X; output2(i) = speedata2.Linear.X; end %Plot the input and output velocity profile [n, p] = size(output1); T = 1:n; plot(T, input'); hold on; plot(T, output1); plot(T, output2); title('Original Data'); legend('Input function', 'Output response of lead','Output response of follower'); grid on;
github
karthik-kk/Autoware-master
plotDisvout.m
.m
Autoware-master/ros/src/system/gazebo/catvehicle/simulink/plotDisvout.m
241
utf_8
241fa676f6444e00a60b8c69a5e19efd
% Author: Jonathan Sprinkle % plots the distance outputs from a data file function plotData( timeseries ) % this timeseries is what we have figure hold on plot(timeseries.Data); plot(timeseries.uVelOut); legend({'Distance','VelOut'}); end
github
karthik-kk/Autoware-master
plotData.m
.m
Autoware-master/ros/src/system/gazebo/catvehicle/simulink/plotData.m
350
utf_8
17951edcd31fa9c02deeb1c49a2e0d7b
% Author: Jonathan Sprinkle % plots the distance outputs from a data file function plotData( timeseries ) % this timeseries is what we have figure hold on plot(timeseries.dist); plot(timeseries.velConverted); plot(timeseries.vdot); plot(timeseries.vout); plot(timeseries.uTireAngle); legend({'dist','velConverted','vdot','vout','uTireAngle'}); end
github
karthik-kk/Autoware-master
plotDistances.m
.m
Autoware-master/ros/src/system/gazebo/catvehicle/simulink/plotDistances.m
288
utf_8
c0779b1561faff69c733c5ec8a3a9ac7
% Author: Jonathan Sprinkle % plots the distance outputs from a data file function plotDistances load distances.mat % this timeseries is what we have figure hold on plot(DistanceEstimator.Data__signal_1_); plot(DistanceEstimator.Data__signal_2_); legend({'Distance','Angle (rad)'}); end
github
rohinkumarreddy/Iris-Detection-master
hamdist.m
.m
Iris-Detection-master/hamdist.m
710
utf_8
bc94aff9c7917be49e3bb10e78a5e3e4
function hd = hamdist(template1, template2, scales) template1 = logical(template1); template2 = logical(template2); hd = NaN; % shift template left and right, use the lowest Hamming distance for shifts=-8:8 template1s = shiftbits(template1, shifts,scales); totalbits = (size(template1s,1)*size(template1s,2)); C = xor(template1s,template2); bitsdiff = sum(sum(C==1)); if totalbits == 0 hd = NaN; else hd1 = bitsdiff / totalbits; if hd1 < hd || isnan(hd) hd = hd1; end end end
github
YasaraPeiris/MNIST_Clusters-master
predict.m
.m
MNIST_Clusters-master/TestMNIST/MatlabCodes/predict.m
1,720
utf_8
b06e9988934fa4b78b42512d26371e90
function predict(layerset, dataSize) global weights numLayers layers; layers = [784, layerset, 10]; [~, numLayers] = size(layers); images = loadTrainImages(); labels = loadTrainLabels(); selected = find(labels == 5 | labels == 1); labels = labels(selected); images = images(:, selected); [~, c] = size(images); dataSize = min(c, dataSize); iterations = dataSize; testLabels = []; clusters = []; results = cell(numLayers); loadWeights(); p = 0.3; unclassified = 0; for r = 1 : iterations results{1} = normc(mat2gray(images(:, r))); %results{1} = sigmf(mat2gray(images(:, r)), [5.0 0.5]); for k = 1 : numLayers - 1 results{k + 1} = normc(weights{k} * results{k}); %results{k + 1} = sigmf(weights{k} * results{k}, [5.0 0.5]); end [m, i] = max(results{numLayers}); if(m >= p) testLabels = [testLabels; labels(r)]; clusters = [clusters; i]; else unclassified = unclassified + 1; end %{ temp = [temp, [results{numLayers} ; ones(3, 1)]]; c = c + 1; if mod(c, 100) == 0 disp(c); picMap = [picMap ; temp]; temp = []; c = 0; end %} end plotPerformance([1 : iterations]', [], testLabels, clusters, [2, 3]); disp(['Unclassified: ', int2str(unclassified), ' out of ', int2str(dataSize)]); function loadWeights() global weights layers; fileName = sprintf('%d_', layers); fileName = strcat(fileName(1 : end - 1), '.mat'); fileName = fullfile(fileparts(which(mfilename)), '..\WeightDatabase\Temp', fileName); if exist(fileName, 'file') == 2 load(fileName, 'weights'); else disp('Trained network not available'); exit; end
github
YasaraPeiris/MNIST_Clusters-master
trainModel_yas.m
.m
MNIST_Clusters-master/TestMNIST/MatlabCodes/trainModel_yas.m
1,924
utf_8
6c4950f15dc3468e591c1a2c5aab6d28
function trainModel_yas(layerset, dataSize) % Using Oja's rule trainingRatio = 0.8; p = 0; images = loadTrainImages(); labels = loadTrainLabels(); selected = find(labels == 0 | labels == 1 ); labels = labels(selected); images = images(:, selected'); [~, c] = size(images); dataSize = min(c, dataSize); iterations = dataSize; image_batch = 10; newIterations = fix(iterations/image_batch); testLabels = []; clusters = []; trainingSize = floor(double(dataSize) * trainingRatio)/image_batch; unclassified = 0; norms = []; updateTime = 0.0; net = Network_new([784, layerset, 2]); numLayers = net.numLayers; tempW = net.feedforwardConnections; %tempW = net.lateralConnections; temp = net.feedforwardConnections; for r= 1:newIterations images_new = []; for k=1:image_batch image_id = image_batch*(r-1)+k; images_new = [images_new mat2gray(images(:, image_id))]; end results = net.getOutput(images_new,r); if(r > trainingSize) for u=1:image_batch image_id = image_batch*(r-1)+u; [m, i] = max(results{numLayers}(:,u)); testLabels = [testLabels; labels(image_id)]; clusters = [clusters; i]; end end time = tic; net.STDP_update(results,r); updateTime = updateTime + toc(time); for u = 1 : image_batch norms = [norms; zeros(1, numLayers - 1)]; weights = net.feedforwardConnections; for k = 1 : numLayers - 1 norms(end, k) = norm(weights{k}(:,u) - tempW{k}(:,u),'fro') / numel(weights{k}(:,u)); tempW{k}(:,u) = weights{k}(:,u); end end end plotPerformance([1 : iterations]', norms, testLabels, clusters, [1, 2, 3]); showFinalImage(abs(weights{1} - temp{1}));
github
danielemarinazzo/GC_SS_PNAS-master
InstModelfilter.m
.m
GC_SS_PNAS-master/InstModelfilter.m
2,343
utf_8
9ec58f552064a96d14d59ba96f833baf
%% realization of the instantaneous model : U = L*W %%% OUTPUT % U: N*M matrix of filtered noises % INPUT % N data length % C: input covariance matrix (may be interpreted as Su or Sw, see above) % B0: M*M matrix of instantaneous effects (when relevant) % when flag='StrictlyCausal': % given Su, applies Cholesky decomposition to find L and Sw % then generates U = L*W, for a realization of gaussian W of variance Sw % when flag='ExtendedGauss': % given Sw and B(0), computes L=[I-B(0)]^(-1) % then generates U = L*W, for a realization of gaussian W of variance Sw % when flag='ExtendedNonGauss': % given Swand B(0), computes L=[I-B(0)]^(-1) % then generates U = L*W, for a realization of nongaussian W of variance Sw function U=InstModelfilter(N,C,flag,B0) error(nargchk(3,4,nargin));%min and max input arguments M=size(C,1); switch flag case {'StrictlyCausal'} % C is Su [L,Sw]=choldiag(C); W = randn(M,N); % W independent and gaussian for m=1:M % This normalizes W to have the appropriate variance (and zero mean) W(m,:)=sqrt(Sw(m,m))*(W(m,:)-mean(W(m,:)))/std(W(m,:)); end U=L*W; case {'ExtendedGauss'} % C is Sw invL=eye(M)-B0; if det(invL)==0, error('B0 is not invertible, ill-conditioned problem!'), end; L=inv(invL); W = randn(M,N); % W independent and gaussian for m=1:M % This normalizes W to have the appropriate variance (and zero mean) W(m,:)=sqrt(C(m,m))*(W(m,:)-mean(W(m,:)))/std(W(m,:)); end U=L*W; case {'ExtendedNonGauss'} % C is Sw invL=eye(M)-B0; if det(invL)==0, error('B0 is not invertible, ill-conditioned problem!'), end; L=inv(invL); %note: here we generate W independent but non-Gaussian % Nonlinearity exponent, selected to lie in [0.5, 0.8] or [1.2, 2.0]. (<1 gives subgaussian, >1 gives supergaussian) q = rand(M,1)*1.1+0.5; ind = find(q>0.8); q(ind) = q(ind)+0.4; % This generates the disturbance variables, which are mutually independent, and non-gaussian W = randn(M,N); W = sign(W).*(abs(W).^(q*ones(1,N))); % This normalizes the disturbance variables to have the appropriate scales W = W./( ( sqrt(mean((W').^2)') ./ sqrt(diag(C)) )*ones(1,N) ); U=L*W; end
github
danielemarinazzo/GC_SS_PNAS-master
MVARfilter.m
.m
GC_SS_PNAS-master/MVARfilter.m
614
utf_8
0290e5ff7f6435096eed5fecafbf75e9
%% FILTER A VECTOR NOISE WITH A SPECIFIED STRICTLY CAUSAL MVAR MODEL: Y(n)=A(1)Y(n-1)+...+A(p)Y(n-p)+U(n) %%% INPUT % A=[A(1)...A(p)]: M*pM matrix of the MVAR model coefficients (strictly causal model) % U: M*N matrix of innovations %%% OUTPUT % Y: M*N matrix of simulated time series function [Y]=MVARfilter(A,U) N=length(U); M=size(A,1); p=size(A,2)/M; % Y(n)=A(1)Y(n-1)+...+A(p)Y(n-p)+U(n) Y=zeros(M,N); for n=1:N for k=1:p if n-k<=0, break; end; % if n<=p, stop when k>=n Y(:,n)=Y(:,n) + ( A(:,(k-1)*M+(1:M)) * Y(:,n-k) ); end Y(:,n)=Y(:,n)+U(:,n); end
github
danielemarinazzo/GC_SS_PNAS-master
varma2iss.m
.m
GC_SS_PNAS-master/varma2iss.m
1,206
utf_8
200c8d913b3e3fe6f30cf6228c4453c9
%% VARMA with B0 term to (Innovations form) State Space parameters % computes innovations form parameters for a state space model from VARMA % parameters using Aoki's method - this version allows for zero-lag MA coefficients function [A,C,K,R,lambda0] = varma2iss(Am,Bm,V,B0) % INPUT: VARMA parameters Am, Bm, V=cov(U) % OUTPUT: innovations form SS parameters A, C, K, R %%%%% internal test %variables to be passed are Am, Bm, B0, V=Su % clear; close all; clc; % Am=[0.9 0 0 0.5; 0 0.6 0.2 0]; % Bm=[0.5 0; 0 0.5]; B0=Bm./5; % V=eye(2); % M = size(Am,1); %dimension of observed process p=floor(size(Am,2)/M); %number of AR lags q=floor(size(Bm,2)/M); %number of MA lags L=M*(p+q); % dimension of state process (SS order) C=[Am Bm]; R=B0*V*B0'; Ip=eye(M*p); Iq=eye(M*q); A11=[Am;Ip(1:end-M,:)]; if q==0 A=A11; K=[eye(M); zeros(M*(p-1),M)]; else A12=[Bm;zeros(M*(p-1),M*q)]; A21=zeros(M*q,M*p); A22=[zeros(M,M*q); Iq(1:end-M,:)]; A=[A11 A12; A21 A22]; K=[eye(M); zeros(M*(p-1),M); inv(B0); zeros(M*(q-1),M)]; end % determine the variance of the process lambda0=E[Yn Yn'] O=dlyap(A,K*R*K'); lambda0=C*O*C'+R; end
github
danielemarinazzo/GC_SS_PNAS-master
idMVAR.m
.m
GC_SS_PNAS-master/idMVAR.m
1,446
utf_8
02db6f116c8164266a38371b50da5231
%% IDENTIFICATION OF STRICTLY CAUSAL MVAR MODEL: Y(n)=A(1)Y(n-1)+...+A(p)Y(n-p)+U(n) % makes use of autocovariance method (vector least squares) %%% input: % Y, M*N matrix of time series (each time series is in a row) % p, model order % Mode, determines estimation algorithm (0:builtin least squares, else other methods [see mvar.m from biosig package]) %%% output: % Am=[A(1)...A(p)], M*pM matrix of the estimated MVAR model coefficients % S, estimated M*M input covariance matrix % Yp, estimated time series % Up, estimated residuals % Z, observation matrix (often optional, useful e.g. for resampling) function [Am,S,Yp,Up,Z,Yb]=idMVAR(Y,p,Mode) % error(nargchk(1,3,nargin)); % if nargin < 3, Mode=0; end % default use least squares estimate % if nargin < 2, p=10; end % default model order [M,N]=size(Y); %% IDENTIFICATION Z=NaN*ones(p*M,N-p); % observation matrix for j=1:p for i=1:M Z((j-1)*M+i,1:N-p)=Y(i, p+1-j:N-j); end end if Mode==0 Yb=NaN*ones(M,N-p); % Ybar for i=1:M Yb(i,1:N-p)=Y(i,p+1:N); end Am=Yb/Z; % least squares! % fprintf('using least squares\n'); else Am = mvar(Y', p, Mode); % estimates from biosig code % fprintf(['using biosig ' int2str(Mode) ' mode\n']); end Yp=Am*Z; Yp=[NaN*ones(M,p) Yp]; % Vector of predicted data Up=Y-Yp; Up=Up(:,p+1:N); % residuals of strictly causal model S=cov(Up');
github
danielemarinazzo/GC_SS_PNAS-master
block_fdMVAR.m
.m
GC_SS_PNAS-master/block_fdMVAR.m
5,321
utf_8
c0626e923c90c31b6156e254a5e1785f
%% FREQUENCY DOMAIN BLOCK MVAR ANALYSIS % References: % L.Faes and G. Nollo, "Measuring Frequency Domain Granger Causality for Multiple Blocks of Interacting Time Series", Biological Cybernetics 2013. DOI: 10.1007/s00422-013-0547-5 % L.Faes, S. Erla and G. Nollo, "Block Partial Directed Coherence: a New Tool for the Structural Analysis of Brain Networks", International Journal of Bioelectromagnetism, Vol. 14, No. 4, pp. 162 - 166, 2012 %%% inputs: % Am=[A(1)...A(p)]: Q*pQ matrix of the MVAR model coefficients (strictly causal model) % Su: Q*Q covariance matrix of the input noises % Mv: number of series in each block % N= number of points for calculation of the spectral functions (nfft) % Fs= sampling frequency %%% outputs: % bDC= block Directed Coherence (Eq. 14a) % bPDC= block Partial Directed Coherence (Eq. 14b) % mF= multivariate total causality (Eq. 13a) % mG= multivariate direct causality (Eq. 13b) % bS= block spectral density matrix (Eq. 12a) % bP= inverse block spectral density matrix (Eq. 12b) % bH= block transfer matrix % bAf= block spectral coefficient matrix % f= vector of frequencies function [bDC,bPDC,mF,mG,bS,bP,bH,bAf,f] = block_fdMVAR(Am,Su,Mv,N,Fs) % clear; close all; clc; % [Bm,B0,Sw]=simuMVARcoeff(1); % Am=Bm;Su=Sw; % Mv=[2 1 1]'; % vector of Mi (dimension of each block) % N=512; % Fs=1; % f = (0:N-1)*(Fs/(2*N)); %% Q= size(Am,1); % Am has dim Q*pQ M=length(Mv); p = size(Am,2)/Q; % p is the order of the MVAR model if nargin<5, Fs= 1; end; if nargin<4, N = 512; end; if all(size(N)==1), %if N is scalar f = (0:N-1)*(Fs/(2*N)); % frequency axis else % if N is a vector, we assume that it is the vector of the frequencies f = N; N = length(N); end; s = exp(sqrt(-1)*2*pi*f/Fs); % vector of complex exponentials z = sqrt(-1)*2*pi/Fs; %% Initializations: spectral matrices have M rows, M columns and are calculated at each of the N frequencies A = [eye(Q) -Am]; % matrix from which M*M blocks are selected to calculate spectral functions invSu=inv(Su); % i-j block of Su and Su^(-1) bSu=cell(M,M); binvSu=cell(M,M); for i=1:M for j=1:M i1=sum(Mv(1:i)); i0=i1-Mv(i)+1; j1=sum(Mv(1:j)); j0=j1-Mv(j)+1; bSu{i,j}=Su(i0:i1,j0:j1); binvSu{i,j}=invSu(i0:i1,j0:j1); end end % whole QxQ matrices Af=zeros(Q,Q,N); % Coefficient Matrix in the frequency domain (it is Abar(w)) H=zeros(Q,Q,N); % Transfer Matrix H(w) S=zeros(Q,Q,N); % Spectral Matrix S(w) P=zeros(Q,Q,N); % Inverse Spectral Matrix P(w) % corresponding cell array of matrices (blocks of size Mi x Mj) bAf=cell(M,M,N); bH=cell(M,M,N); bS=cell(M,M,N); bP=cell(M,M,N); % causality functions bDC=zeros(M,M,N); % block directed coherence bPDC=zeros(M,M,N); % block partial directed coherence mF=NaN*ones(M,M,N); % multivariate logarithmic causality f mG=NaN*ones(M,M,N); % multivariate logarithmic direct causality g %%% computation of spectral functions for n=1:N, % at each frequency %%% Coefficient matrix in the frequency domain As = zeros(Q,Q); % matrix As(z)=I-sum(A(k)) for k = 1:p+1, As = As + A(:,k*Q+(1-Q:0))*exp(-z*(k-1)*f(n)); %indicization (:,k*Q+(1-M:0)) extracts the k-th Q*Q block from the matrix B (A(1) is in the second block, and so on) end; Af(:,:,n) = As; %%% Coefficient matrix H(:,:,n) = inv(As); %%% Transfer matrix S(:,:,n) = H(:,:,n)*Su*H(:,:,n)'; %%% Spectral matrix - ' stands for Hermitian transpose P(:,:,n) = inv(S(:,:,n)); %%% Inverse Spectral matrix P(:,:,n) = As'*invSu*As; %%% extraction of blocks indexes for i=1:M for j=1:M %indexes of the i-j block i1=sum(Mv(1:i)); i0=i1-Mv(i)+1; j1=sum(Mv(1:j)); j0=j1-Mv(j)+1; % i-j block of all matrices of interest bAf{i,j,n}=Af(i0:i1,j0:j1,n); bH{i,j,n}=H(i0:i1,j0:j1,n); bS{i,j,n}=S(i0:i1,j0:j1,n); bP{i,j,n}=P(i0:i1,j0:j1,n); end end % computation of causality measures at frequency n for i=1:M for j=1:M % if det(bP{j,j,n}) < -0.000001, error('determinante negativo!'); end % if det(bS{i,i,n}) < -0.000001, error('determinante negativo!'); end % if det(bP{j,j,n} - bAf{i,j,n}'*binvSu{i,i}*bAf{i,j,n}) < -0.000001, error('determinante negativo!'); end % if det(bS{i,i,n} - bH{i,j,n}*bSu{j,j}*bH{i,j,n}') < -0.000001, error('determinante negativo!'); end bDC(i,j,n) = 1 - abs(det(bS{i,i,n} - bH{i,j,n}*bSu{j,j}*bH{i,j,n}')) / abs(det(bS{i,i,n})); bPDC(i,j,n) = 1 - abs(det(bP{j,j,n} - bAf{i,j,n}'*binvSu{i,i}*bAf{i,j,n})) / abs(det(bP{j,j,n})); if i~=j mF(i,j,n) = log( abs(det(bS{i,i,n})) / abs(det(bS{i,i,n} - bH{i,j,n}*bSu{j,j}*bH{i,j,n}')) ); mG(i,j,n) = log( abs(det(bP{j,j,n})) / abs(det(bP{j,j,n} - bAf{i,j,n}'*binvSu{i,i}*bAf{i,j,n})) ); end end end end;
github
bill-codes/netalign-master
bipartite_matching.m
.m
netalign-master/experiments/misc/gaimc/bipartite_matching.m
6,580
utf_8
bd3212ac06f51f9037ca7a7d80b45981
function [val m1 m2 mi]=bipartite_matching(varargin) % BIPARTITE_MATCHING Solve a maximum weight bipartite matching problem % % [val m1 m2]=bipartite_matching(A) for a rectangular matrix A % [val m1 m2 mi]=bipartite_matching(x,ei,ej,n,m) for a matrix stored % in triplet format. This call also returns a matching indicator mi so % that val = x'*mi. % % The maximum weight bipartite matching problem tries to pick out elements % from A such that each row and column get only a single non-zero but the % sum of all the chosen elements is as large as possible. % % This function is slightly atypical for a graph library, because it will % be primarily used on rectangular inputs. However, these rectangular % inputs model bipartite graphs and we take advantage of that stucture in % this code. The underlying graph adjency matrix is % G = spaugment(A,0); % where A is the rectangular input to the bipartite_matching function. % % Matlab already has the dmperm function that computes a maximum % cardinality matching between the rows and the columns. This function % gives us the maximum weight matching instead. For unweighted graphs, the % two functions are equivalent. % % Note: If ei and ej contain duplicate edges, the results of this function % are incorrect. % % See also DMPERM % % Example: % A = rand(10,8); % bipartite matching between random data % [val mi mj] = bipartite_matching(A); % val % David F. Gleich and Ying Wang % Copyright, Stanford University, 2008-2009 % Computational Approaches to Digital Stewardship % 2008-04-24: Initial coding (copy from Ying Wang matching_sparse_mex.cpp) % 2008-11-15: Added triplet input/output % 2009-04-30: Modified for gaimc library % 2009-05-15: Fixed error with empty inputs and triple added example. [rp ci ai tripi n m] = bipartite_matching_setup(varargin{:}); if isempty(tripi) error(nargoutchk(0,3,nargout,'struct')); else error(nargoutchk(0,4,nargout,'struct')); end if ~isempty(tripi) && nargout>3 [val m1 m2 mi] = bipartite_matching_primal_dual(rp, ci, ai, tripi, n, m); else [val m1 m2] = bipartite_matching_primal_dual(rp, ci, ai, tripi, n, m); end function [rp ci ai tripi n m]= bipartite_matching_setup(A,ei,ej,n,m) % convert the input if nargin == 1 if isstruct(A) [nzi nzj nzv]=csr_to_sparse(A.rp,A.ci,A.ai); else [nzi nzj nzv]=find(A); end [n m]=size(A); triplet = 0; elseif nargin >= 3 && nargin <= 5 nzi = ei; nzj = ej; nzv = A; if ~exist('n','var') || isempty(n), n = max(nzi); end if ~exist('m','var') || isempty(m), m = max(nzj); end triplet = 1; else error(nargchk(3,5,nargin,'struct')); end nedges = length(nzi); rp = ones(n+1,1); % csr matrix with extra edges ci = zeros(nedges+n,1); ai = zeros(nedges+n,1); if triplet, tripi = zeros(nedges+n,1); % triplet index else tripi = []; end % % 1. build csr representation with a set of extra edges from vertex i to % vertex m+i % rp(1)=0; for i=1:nedges rp(nzi(i)+1)=rp(nzi(i)+1)+1; end rp=cumsum(rp); for i=1:nedges if triplet, tripi(rp(nzi(i))+1)=i; end % triplet index ai(rp(nzi(i))+1)=nzv(i); ci(rp(nzi(i))+1)=nzj(i); rp(nzi(i))=rp(nzi(i))+1; end for i=1:n % add the extra edges if triplet, tripi(rp(i)+1)=-1; end % triplet index ai(rp(i)+1)=0; ci(rp(i)+1)=m+i; rp(i)=rp(i)+1; end % restore the row pointer array for i=n:-1:1 rp(i+1)=rp(i); end rp(1)=0; rp=rp+1; % % 1a. check for duplicates in the data % colind = false(m+n,1); for i=1:n for rpi=rp(i):rp(i+1)-1 if colind(ci(rpi)), error('bipartite_matching:duplicateEdge',... 'duplicate edge detected (%i,%i)',i,ci(rpi)); end colind(ci(rpi))=1; end for rpi=rp(i):rp(i+1)-1, colind(ci(rpi))=0; end % reset indicator end function [val m1 m2 mi]=bipartite_matching_primal_dual(... rp, ci, ai, tripi, n, m) % BIPARTITE_MATCHING_PRIMAL_DUAL alpha=zeros(n,1); % variables used for the primal-dual algorithm beta=zeros(n+m,1); queue=zeros(n,1); t=zeros(n+m,1); match1=zeros(n,1); match2=zeros(n+m,1); tmod = zeros(n+m,1); ntmod=0; % % initialize the primal and dual variables % for i=1:n for rpi=rp(i):rp(i+1)-1 if ai(rpi) > alpha(i), alpha(i)=ai(rpi); end end end % dual variables (beta) are initialized to 0 already % match1 and match2 are both 0, which indicates no matches i=1; while i<=n % repeat the problem for n stages % clear t(j) for j=1:ntmod, t(tmod(j))=0; end ntmod=0; % add i to the stack head=1; tail=1; queue(head)=i; % add i to the head of the queue while head <= tail && match1(i)==0 k=queue(head); for rpi=rp(k):rp(k+1)-1 j = ci(rpi); if ai(rpi) < alpha(k)+beta(j) - 1e-8, continue; end % skip if tight if t(j)==0, tail=tail+1; queue(tail)=match2(j); t(j)=k; ntmod=ntmod+1; tmod(ntmod)=j; if match2(j)<1, while j>0, match2(j)=t(j); k=t(j); temp=match1(k); match1(k)=j; j=temp; end break; % we found an alternating path end end end head=head+1; end if match1(i) < 1, % still not matched, so update primal, dual and repeat theta=inf; for j=1:head-1 t1=queue(j); for rpi=rp(t1):rp(t1+1)-1 t2=ci(rpi); if t(t2) == 0 && alpha(t1) + beta(t2) - ai(rpi) < theta, theta = alpha(t1) + beta(t2) - ai(rpi); end end end for j=1:head-1, alpha(queue(j)) = alpha(queue(j)) - theta; end for j=1:ntmod, beta(tmod(j)) = beta(tmod(j)) + theta; end continue; end i=i+1; % increment i end val=0; for i=1:n for rpi=rp(i):rp(i+1)-1 if ci(rpi)==match1(i), val=val+ai(rpi); end end end noute = 0; % count number of output edges for i=1:n if match1(i)<=m, noute=noute+1; end end m1=zeros(noute,1); m2=m1; % copy over the 0 array noute=1; for i=1:n if match1(i)<=m, m1(noute)=i; m2(noute)=match1(i);noute=noute+1; end end if nargout>3 mi= false(length(tripi)-n,1); for i=1:n for rpi=rp(i):rp(i+1)-1 if match1(i)<=m && ci(rpi)==match1(i), mi(tripi(rpi))=1; end end end end
github
bill-codes/netalign-master
graph_draw.m
.m
netalign-master/experiments/misc/gaimc/graph_draw.m
23,504
utf_8
83adf66de4bc94aea62f934d2e1e3da0
function h = graph_draw(adj, xy, varargin) % GRAPH_DRAW Draw a picture of a graph when the coordinates are known % % graph_draw(A, xy) draws a picture of graph A where node i is placed % at x = xy(i,1), y = xy(i,2). In the drawing, shaded nodes have % self loops. % % Some of the parameters of the drawing are controlled by specifying % optional parameters in the call graph_draw(A, xy, key, value). The keys % and default values are % 'linestyle' - default '-' % 'linewidth' - default .5 % 'linecolor' - default Black % 'fontsize' - fontsize for labels, default 8 % 'labels' - Cell array containing labels <Default : '1':'N'> % 'shapes' - 1 if node is a box, 0 if oval <Default : zeros> % % h = graph_draw(A,xy,...) returns a handle for each object. h(i,1) is % the text handle for vertex i, and h(i,2) is the circle handle for % vertex i. % % Originally written by Erik A. Johnson, Ali Taylan Cemgil, and Leon Peskin % Modified by David F. Gleich for gaimc package. % % See also GPLOT % % Example: % load_gaimc_graph('dfs_example'); % graph_draw(A,xy); % 2009-02-26 interface modified by David Gleich <[email protected]> % to remove automatic layout % 2009-05-15: Added example % 24 Feb 2004 cleaned up, optimized and corrected by Leon Peshkin pesha @ ai.mit.edu % Apr-2000 draw_graph Ali Taylan Cemgil <[email protected]> % 1995-1997 arrow Erik A. Johnson <[email protected]> linestyle = '-'; % -- -. linewidth = .5; % 2 linecolor = 'Black'; % Red fontsize = 8; N = size(adj,1); color = ones(N, 3); % colors of elipses around text labels = cellstr(int2str((1:N)')); % labels = cellstr(char(zeros(N,1)+double('+'))); node_t = zeros(N,1); % for i = 1:2:length(varargin) % get optional args switch varargin{i} case 'linestyle', linestyle = varargin{i+1}; case 'linewidth', linewidth = varargin{i+1}; case 'linecolor', linecolor = varargin{i+1}; case 'labels', labels = varargin{i+1}; case 'fontsize', fontsize = varargin{i+1}; case 'shapes', node_t = varargin{i+1}; node_t = node_t(:); end end x = xy(:,1); x = x - min(x); y = xy(:,2); y = y - min(y); % scale the graph so it's between 0 and 1 xrange = max(x); yrange = max(y); scalefactor = max(xrange,yrange); x = x/scalefactor; y = y/scalefactor; lp_ndx = find(diag(adj)); % recover from self-loops = diagonal ones color(lp_ndx,:) = repmat([.8 .8 .8],length(lp_ndx),1); % makes self-looped nodes blue adj = adj - diag(diag(adj)); % clean up the diagonal axis([-0.1 1.1 -0.1 1.1]); axis off; set(gcf,'Color',[1 1 1]); set(gca,'XTick',[], 'YTick',[], 'box','on'); % axis('square'); %colormap(flipud(gray)); idx1 = find(node_t == 0); wd1 = []; % Draw nodes if ~isempty(idx1), [h1 wd1] = textoval(x(idx1), y(idx1), labels(idx1), fontsize, color); end; idx2 = find(node_t ~= 0); wd2 = []; if ~isempty(idx2), [h2 wd2] = textbox(x(idx2), y(idx2), labels(idx2), color); end; wd = zeros(size(wd1,1) + size(wd2,1),2); if ~isempty(idx1), wd(idx1, :) = wd1; end; if ~isempty(idx2), wd(idx2, :) = wd2; end; for node = 1:N % Draw edges edges = find(adj(node,:) == 1); for node2 = edges sign = 1; if ((x(node2) - x(node)) == 0) if (y(node) > y(node2)), alpha = -pi/2; else alpha = pi/2; end; else alpha = atan((y(node2)-y(node))/(x(node2)-x(node))); if (x(node2) <= x(node)), sign = -1; end; end; dy1 = sign.*wd(node,2).*sin(alpha); dx1 = sign.*wd(node,1).*cos(alpha); dy2 = sign.*wd(node2,2).*sin(alpha); dx2 = sign.*wd(node2,1).*cos(alpha); if (adj(node2,node) == 0) % if directed edge my_arrow([x(node)+dx1 y(node)+dy1], [x(node2)-dx2 y(node2)-dy2]); else line([x(node)+dx1 x(node2)-dx2], [y(node)+dy1 y(node2)-dy2], ... 'Color', linecolor, 'LineStyle', linestyle, 'LineWidth', linewidth); adj(node2,node) = -1; % Prevent drawing lines twice end; end; end; if nargout > 2 h = zeros(length(wd),2); if ~isempty(idx1), h(idx1,:) = h1; end; if ~isempty(idx2), h(idx2,:) = h2; end; end; function [t, wd] = textoval(x, y, str, fontsize, c) % [t, wd] = textoval(x, y, str, fontsize) Draws an oval around text objects % INPUT: x, y - Coordinates % str - Strings % c - colors % OUTPUT: t - Object Handles % width - x and y width of ovals if ~isa(str,'cell'), str = cellstr(str); end; N = length(str); wd = zeros(N,2); temp = zeros(N,2); for i = 1:N, tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlign','middle','FontSize', fontsize); sz = get(tx, 'Extent'); wy = sz(4); wx = max(2/3*sz(3), wy); wx = 0.9 * wx; % might want to play with this .9 and .5 coefficients wy = 0.5 * wy; ptc = ellipse(x(i), y(i), wx, wy, c(i,:)); set(ptc, 'FaceColor', c(i,:)); % 'w' wd(i,:) = [wx wy]; delete(tx); tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlign','middle', 'FontSize', fontsize); temp(i,:) = [tx ptc]; end; t = temp; function [p] = ellipse(x, y, rx, ry, c) % [p] = ellipse(x, y, rx, ry) Draws Ellipse shaped patch objects % INPUT: x,y - N x 1 vectors of x and y coordinates % Rx, Ry - Radii % C - colors % OUTPUT: p - Handles of Ellipse shaped path objects if length(rx)== 1, rx = ones(size(x)).*rx; end; if length(ry)== 1, ry = ones(size(x)).*ry; end; N = length(x); p = zeros(size(x)); t = 0:pi/30:2*pi; for i = 1:N px = rx(i) * cos(t) + x(i); py = ry(i) * sin(t) + y(i); p(i) = patch(px, py, c(i,:)); end; function [h, wd] = textbox(x,y,str,c) % [h, wd] = textbox(x,y,str) draws a box around the text % INPUT: x, y - Coordinates % str - Strings % OUTPUT: h - Object Handles % wd - x and y Width of boxes if ~isa(str,'cell'), str=cellstr(str); end N = length(str); wd = zeros(N,2); h = zeros(N,2); for i = 1:N, tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlign','middle'); sz = get(tx, 'Extent'); wy = 2/3 * sz(4); wyB = y(i) - wy; wyT = y(i) + wy; wx = max(2/3 * sz(3), wy); wxL = x(i) - wx; wxR = x(i) + wx; ptc = patch([wxL wxR wxR wxL], [wyT wyT wyB wyB], c(i,:)); set(ptc, 'FaceColor', c(i,:)); % 'w' wd(i,:) = [wx wy]; delete(tx); tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlign','middle'); h(i,:) = [tx ptc]; end; function [h,yy,zz] = my_arrow(varargin) % [h,yy,zz] = my_arrow(varargin) Draw a line with an arrowhead. % A lot of the original code is removed and most of the remaining can probably go too % since it comes from a general use function only being called inone context. - Leon Peshkin % Copyright 1997, Erik A. Johnson <[email protected]>, 8/14/97 ax = []; % set values to empty matrices deflen = 12; % 16 defbaseangle = 45; % 90 deftipangle = 16; defwid = 0; defpage = 0; defends = 1; ArrowTag = 'Arrow'; % The 'Tag' we'll put on our arrows start = varargin{1}; % fill empty arguments stop = varargin{2}; crossdir = [NaN NaN NaN]; len = NaN; baseangle = NaN; tipangle = NaN; wid = NaN; page = 0; ends = NaN; start = [start NaN]; stop = [stop NaN]; o = 1; % expand single-column arguments ax = gca; % set up the UserData data (here so not corrupted by log10's and such) ud = [start stop len baseangle tipangle wid page crossdir ends]; % Get axes limits, range, min; correct for aspect ratio and log scale axm = zeros(3,1); axr = axm; axrev = axm; ap = zeros(2,1); xyzlog = axm; limmin = ap; limrange = ap; oldaxlims = zeros(1,7); oneax = 1; % all(ax==ax(1)); LPM if (oneax), T = zeros(4,4); invT = zeros(4,4); else T = zeros(16,1); invT = zeros(16,1); end axnotdone = 1; % logical(ones(size(ax))); LPM while (any(axnotdone)) ii = 1; % LPM min(find(axnotdone)); curax = ax(ii); curpage = page(ii); % get axes limits and aspect ratio axl = [get(curax,'XLim'); get(curax,'YLim'); get(curax,'ZLim')]; oldaxlims(find(oldaxlims(:,1)==0, 1),:) = [curax reshape(axl',1,6)]; % get axes size in pixels (points) u = get(curax,'Units'); axposoldunits = get(curax,'Position'); really_curpage = curpage & strcmp(u,'normalized'); if (really_curpage) curfig = get(curax,'Parent'); pu = get(curfig,'PaperUnits'); set(curfig,'PaperUnits','points'); pp = get(curfig,'PaperPosition'); set(curfig,'PaperUnits',pu); set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); set(curax,'Units','normalized'); curap = pp.*get(curax,'Position'); else set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); curap = curapscreen; end set(curax,'Units',u); set(curax,'Position',axposoldunits); % handle non-stretched axes position str_stretch = {'DataAspectRatioMode'; 'PlotBoxAspectRatioMode' ; 'CameraViewAngleMode' }; str_camera = {'CameraPositionMode' ; 'CameraTargetMode' ; ... 'CameraViewAngleMode' ; 'CameraUpVectorMode'}; notstretched = strcmp(get(curax,str_stretch),'manual'); manualcamera = strcmp(get(curax,str_camera),'manual'); if ~arrow_WarpToFill(notstretched,manualcamera,curax) % find the true pixel size of the actual axes texttmp = text(axl(1,[1 2 2 1 1 2 2 1]), ... axl(2,[1 1 2 2 1 1 2 2]), axl(3,[1 1 1 1 2 2 2 2]),''); set(texttmp,'Units','points'); textpos = get(texttmp,'Position'); delete(texttmp); textpos = cat(1,textpos{:}); textpos = max(textpos(:,1:2)) - min(textpos(:,1:2)); % adjust the axes position if (really_curpage) % adjust to printed size textpos = textpos * min(curap(3:4)./textpos); curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos]; else % adjust for pixel roundoff textpos = textpos * min(curapscreen(3:4)./textpos); curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos]; end end % adjust limits for log scale on axes curxyzlog = [strcmp(get(curax,'XScale'),'log'); ... strcmp(get(curax,'YScale'),'log'); strcmp(get(curax,'ZScale'),'log')]; if (any(curxyzlog)) ii = find([curxyzlog;curxyzlog]); if (any(axl(ii)<=0)) error([upper(mfilename) ' does not support non-positive limits on log-scaled axes.']); else axl(ii) = log10(axl(ii)); end end % correct for 'reverse' direction on axes; curreverse = [strcmp(get(curax,'XDir'),'reverse'); ... strcmp(get(curax,'YDir'),'reverse'); strcmp(get(curax,'ZDir'),'reverse')]; ii = find(curreverse); if ~isempty(ii) axl(ii,[1 2])=-axl(ii,[2 1]); end % compute the range of 2-D values curT = get(curax,'Xform'); lim = curT*[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1;0 0 0 0 1 1 1 1;1 1 1 1 1 1 1 1]; lim = lim(1:2,:)./([1;1]*lim(4,:)); curlimmin = min(lim,[],2); curlimrange = max(lim,[],2) - curlimmin; curinvT = inv(curT); if ~oneax curT = curT.'; curinvT = curinvT.'; curT = curT(:); curinvT = curinvT(:); end % check which arrows to which cur corresponds ii = find((ax==curax)&(page==curpage)); oo = ones(1,length(ii)); axr(:,ii) = diff(axl,1,2) * oo; axm(:,ii) = axl(:,1) * oo; axrev(:,ii) = curreverse * oo; ap(:,ii) = curap(3:4)' * oo; xyzlog(:,ii) = curxyzlog * oo; limmin(:,ii) = curlimmin * oo; limrange(:,ii) = curlimrange * oo; if (oneax), T = curT; invT = curinvT; else T(:,ii) = curT * oo; invT(:,ii) = curinvT * oo; end; axnotdone(ii) = zeros(1,length(ii)); end; oldaxlims(oldaxlims(:,1)==0,:) = []; % correct for log scales curxyzlog = xyzlog.'; ii = find(curxyzlog(:)); if ~isempty(ii) start(ii) = real(log10(start(ii))); stop(ii) = real(log10(stop(ii))); if (all(imag(crossdir)==0)) % pulled (ii) subscript on crossdir, 12/5/96 eaj crossdir(ii) = real(log10(crossdir(ii))); end end ii = find(axrev.'); % correct for reverse directions if ~isempty(ii) start(ii) = -start(ii); stop(ii) = -stop(ii); crossdir(ii) = -crossdir(ii); end start = start.'; stop = stop.'; % transpose start/stop values % take care of defaults, page was done above ii = find(isnan(start(:))); if ~isempty(ii), start(ii) = axm(ii)+axr(ii)/2; end; ii = find(isnan(stop(:))); if ~isempty(ii), stop(ii) = axm(ii)+axr(ii)/2; end; ii = find(isnan(crossdir(:))); if ~isempty(ii), crossdir(ii) = zeros(length(ii),1); end; ii = find(isnan(len)); if ~isempty(ii), len(ii) = ones(length(ii),1)*deflen; end; baseangle(ii) = ones(length(ii),1)*defbaseangle; tipangle(ii) = ones(length(ii),1)*deftipangle; wid(ii) = ones(length(ii),1) * defwid; ends(ii) = ones(length(ii),1) * defends; % transpose rest of values len = len.'; baseangle = baseangle.'; tipangle = tipangle.'; wid = wid.'; page = page.'; crossdir = crossdir.'; ends = ends.'; ax = ax.'; % for all points with start==stop, start=stop-(verysmallvalue)*(up-direction); ii = find(all(start==stop)); if ~isempty(ii) % find an arrowdir vertical on screen and perpendicular to viewer % transform to 2-D tmp1 = [(stop(:,ii)-axm(:,ii))./axr(:,ii);ones(1,length(ii))]; if (oneax), twoD=T*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); twoD=zeros(4,length(ii)); twoD(:)=sum(tmp2)'; end twoD=twoD./(ones(4,1)*twoD(4,:)); % move the start point down just slightly tmp1 = twoD + [0;-1/1000;0;0]*(limrange(2,ii)./ap(2,ii)); % transform back to 3-D if (oneax), threeD=invT*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); threeD=zeros(4,length(ii)); threeD(:)=sum(tmp2)'; end start(:,ii) = (threeD(1:3,:)./(ones(3,1)*threeD(4,:))).*axr(:,ii)+axm(:,ii); end; % compute along-arrow points % transform Start points tmp1 = [(start-axm)./axr; 1]; if (oneax), X0=T*tmp1; else tmp1 = [tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2 = zeros(4,4); tmp2(:)=tmp1(:); X0=zeros(4,1); X0(:)=sum(tmp2)'; end X0=X0./(ones(4,1)*X0(4,:)); % transform Stop points tmp1=[(stop-axm)./axr; 1]; if (oneax), Xf=T*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4); tmp2(:)=tmp1(:); Xf=zeros(4,1); Xf(:)=sum(tmp2)'; end Xf=Xf./(ones(4,1)*Xf(4,:)); % compute pixel distance between points D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*(ap./limrange)).^2)); % compute and modify along-arrow distances len1 = len; len2 = len - (len.*tan(tipangle/180*pi)-wid/2).*tan((90-baseangle)/180*pi); slen0 = 0; slen1 = len1 .* ((ends==2)|(ends==3)); slen2 = len2 .* ((ends==2)|(ends==3)); len0 = 0; len1 = len1 .* ((ends==1)|(ends==3)); len2 = len2 .* ((ends==1)|(ends==3)); ii = find((ends==1)&(D<len2)); % for no start arrowhead if ~isempty(ii), slen0(ii) = D(ii)-len2(ii); end; ii = find((ends==2)&(D<slen2)); % for no end arrowhead if ~isempty(ii), len0(ii) = D(ii)-slen2(ii); end; len1 = len1 + len0; len2 = len2 + len0; slen1 = slen1 + slen0; slen2 = slen2 + slen0; % note: the division by D below will probably not be accurate if both % of the following are true: % 1. the ratio of the line length to the arrowhead % length is large % 2. the view is highly perspective. % compute stoppoints tmp1 = X0.*(ones(4,1)*(len0./D))+Xf.*(ones(4,1)*(1-len0./D)); if (oneax), tmp3 = invT*tmp1; else tmp1 = [tmp1;tmp1;tmp1;tmp1]; tmp1 = invT.*tmp1; tmp2 = zeros(4,4); tmp2(:) = tmp1(:); tmp3 = zeros(4,1); tmp3(:) = sum(tmp2)'; end stoppoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute tippoints tmp1=X0.*(ones(4,1)*(len1./D))+Xf.*(ones(4,1)*(1-len1./D)); if (oneax), tmp3=invT*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4); tmp2(:)=tmp1(:); tmp3=zeros(4,1); tmp3(:)=sum(tmp2)'; end tippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute basepoints tmp1=X0.*(ones(4,1)*(len2./D))+Xf.*(ones(4,1)*(1-len2./D)); if (oneax), tmp3=invT*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4); tmp2(:)=tmp1(:); tmp3=zeros(4,1); tmp3(:)=sum(tmp2)'; end basepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute startpoints tmp1=X0.*(ones(4,1)*(1-slen0./D))+Xf.*(ones(4,1)*(slen0./D)); if (oneax), tmp3=invT*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4); tmp2(:) = tmp1(:); tmp3=zeros(4,1); tmp3(:) = sum(tmp2)'; end startpoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute stippoints tmp1=X0.*(ones(4,1)*(1-slen1./D))+Xf.*(ones(4,1)*(slen1./D)); if (oneax), tmp3=invT*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1 = invT.*tmp1; tmp2=zeros(4,4); tmp2(:)=tmp1(:); tmp3=zeros(4,1); tmp3(:)=sum(tmp2)'; end stippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute sbasepoints tmp1=X0.*(ones(4,1)*(1-slen2./D))+Xf.*(ones(4,1)*(slen2./D)); if (oneax), tmp3=invT*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4); tmp2(:)=tmp1(:); tmp3=zeros(4,1); tmp3(:)=sum(tmp2)'; end sbasepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute cross-arrow directions for arrows with NormalDir specified if (any(imag(crossdir(:))~=0)), ii = find(any(imag(crossdir)~=0)); crossdir(:,ii) = cross((stop(:,ii)-start(:,ii))./axr(:,ii), ... imag(crossdir(:,ii))).*axr(:,ii); end; basecross = crossdir + basepoint; % compute cross-arrow directions tipcross = crossdir + tippoint; sbasecross = crossdir + sbasepoint; stipcross = crossdir + stippoint; ii = find(all(crossdir==0)|any(isnan(crossdir))); if ~isempty(ii), numii = length(ii); % transform start points tmp1 = [basepoint(:,ii) tippoint(:,ii) sbasepoint(:,ii) stippoint(:,ii)]; tmp1 = (tmp1-axm(:,[ii ii ii ii])) ./ axr(:,[ii ii ii ii]); tmp1 = [tmp1; ones(1,4*numii)]; if (oneax), X0=T*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); X0=zeros(4,4*numii); X0(:)=sum(tmp2)'; end X0=X0./(ones(4,1)*X0(4,:)); % transform stop points tmp1 = [(2*stop(:,ii)-start(:,ii)-axm(:,ii))./axr(:,ii);ones(1,numii)]; tmp1 = [tmp1 tmp1 tmp1 tmp1]; if (oneax) Xf=T*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xf=zeros(4,4*numii); Xf(:)=sum(tmp2)'; end Xf=Xf./(ones(4,1)*Xf(4,:)); % compute perpendicular directions pixfact = ((limrange(1,ii)./limrange(2,ii)).*(ap(2,ii)./ap(1,ii))).^2; pixfact = [pixfact pixfact pixfact pixfact]; pixfact = [pixfact;1./pixfact]; [dummyval,jj] = max(abs(Xf(1:2,:)-X0(1:2,:))); jj1 = ((1:4)'*ones(1,length(jj))==ones(4,1)*jj); jj2 = ((1:4)'*ones(1,length(jj))==ones(4,1)*(3-jj)); jj3 = jj1(1:2,:); Xp = X0; Xp(jj2) = X0(jj2) + ones(sum(jj2(:)),1); Xp(jj1) = X0(jj1) - (Xf(jj2)-X0(jj2))./(Xf(jj1)-X0(jj1)) .* pixfact(jj3); % inverse transform the cross points if (oneax), Xp=invT*Xp; else, tmp1=[Xp;Xp;Xp;Xp]; tmp1=invT(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xp=zeros(4,4*numii); Xp(:)=sum(tmp2)'; end; Xp=(Xp(1:3,:)./(ones(3,1)*Xp(4,:))).*axr(:,[ii ii ii ii])+axm(:,[ii ii ii ii]); basecross(:,ii) = Xp(:,0*numii+(1:numii)); tipcross(:,ii) = Xp(:,1*numii+(1:numii)); sbasecross(:,ii) = Xp(:,2*numii+(1:numii)); stipcross(:,ii) = Xp(:,3*numii+(1:numii)); end; % compute all points % compute start points axm11 = [axm axm axm axm axm axm axm axm axm axm axm]; axr11 = [axr axr axr axr axr axr axr axr axr axr axr]; st = [stoppoint tippoint basepoint sbasepoint stippoint startpoint stippoint sbasepoint basepoint tippoint stoppoint]; tmp1 = (st - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), X0=T*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44); tmp2(:)=tmp1(:); X0=zeros(4,11); X0(:)=sum(tmp2)'; end X0=X0./(ones(4,1)*X0(4,:)); % compute stop points tmp1 = ([start tipcross basecross sbasecross stipcross stop stipcross sbasecross basecross tipcross start] ... - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), Xf=T*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44); tmp2(:)=tmp1(:); Xf=zeros(4,11); Xf(:)=sum(tmp2)'; end Xf=Xf./(ones(4,1)*Xf(4,:)); % compute lengths len0 = len.*((ends==1)|(ends==3)).*tan(tipangle/180*pi); slen0 = len.*((ends==2)|(ends==3)).*tan(tipangle/180*pi); le = [0 len0 wid/2 wid/2 slen0 0 -slen0 -wid/2 -wid/2 -len0 0]; aprange = ap./limrange; aprange = [aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange]; D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*aprange).^2)); Dii=find(D==0); if ~isempty(Dii), D=D+(D==0); le(Dii)=zeros(1,length(Dii)); end; tmp1 = X0.*(ones(4,1)*(1-le./D)) + Xf.*(ones(4,1)*(le./D)); % inverse transform if (oneax), tmp3=invT*tmp1; else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[invT invT invT invT invT invT invT invT invT invT invT].*tmp1; tmp2=zeros(4,44); tmp2(:)=tmp1(:); tmp3=zeros(4,11); tmp3(:)=sum(tmp2)'; end pts = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)) .* axr11 + axm11; % correct for ones where the crossdir was specified ii = find(~(all(crossdir==0)|any(isnan(crossdir)))); if ~isempty(ii), D1 = [pts(:,1+ii)-pts(:,9+ii) pts(:,2+ii)-pts(:,8+ii) ... pts(:,3+ii)-pts(:,7+ii) pts(:,4+ii)-pts(:,6+ii) ... pts(:,6+ii)-pts(:,4+ii) pts(:,7+ii)-pts(:,3+ii) ... pts(:,8+ii)-pts(:,2+ii) pts(:,9+ii)-pts(:,1+ii)]/2; ii = ii'*ones(1,8) + ones(length(ii),1)*[1:4 6:9]; ii = ii(:)'; pts(:,ii) = st(:,ii) + D1; end; % readjust for reverse directions iicols = (1:1)'; iicols = iicols(:,ones(1,11)); iicols = iicols(:).'; tmp1 = axrev(:,iicols); ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=-pts(ii); end; % readjust for log scale on axes tmp1 = xyzlog(:,iicols); ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=10.^pts(ii); end; % compute the x,y,z coordinates of the patches; ii = (0:10)' + ones(11,1); ii = ii(:)'; x = zeros(11,1); y = x; z = x; x(:) = pts(1,ii)'; y(:) = pts(2,ii)'; z(:) = pts(3,ii)'; % do the output % % create or modify the patches H = 0; % % make or modify the arrows if arrow_is2DXY(ax(1)), zz=[]; else zz=z(:,1); end; xyz = {'XData',x(:,1),'YData',y(:,1),'ZData',zz,'Tag',ArrowTag}; H(1) = patch(xyz{:}); % % additional properties set(H,'Clipping','off'); set(H,{'UserData'},num2cell(ud,2)); % make sure the axis limits did not change function [out,is2D] = arrow_is2DXY(ax) % check if axes are 2-D X-Y plots, may not work for modified camera angles, etc. out = zeros(size(ax)); % 2-D X-Y plots is2D = out; % any 2-D plots views = get(ax(:),{'View'}); views = cat(1,views{:}); out(:) = abs(views(:,2))==90; is2D(:) = out(:) | all(rem(views',90)==0)'; function out = arrow_WarpToFill(notstretched,manualcamera,curax) %#ok<INUSL> % check if we are in "WarpToFill" mode. out = strcmp(get(curax,'WarpToFill'),'on'); % 'WarpToFill' is undocumented, so may need to replace this by % out = ~( any(notstretched) & any(manualcamera) );
github
bill-codes/netalign-master
netalignmr2.m
.m
netalign-master/experiments/crystalize_mr/netalignmr2.m
6,168
utf_8
4973769c6f25dc607067664b4d9444ae
function [xbest,status,hist] = netalignmr(S,w,a,b,li,lj,gamma,stepm,rtype,maxiter,verbose) % NETALIGNMR Compute the matching relaxation heuristic for network alignment % % Given a network alignment problem, the matching heuristic solves a % sequence of matching problems to generate good upper and lower bounds on % the solutions. % % [xbest,status,hist] = netalignmr(S,w,a,b,li,lj,stepm,rtype, % maxiter,verbose) % fully specifies all inputs and outputs. % % Input % ----- % S : the complete set of squares % w : the matching weights for all edges in the link graph L % a : the value of alpha in the netalign objective % b : the value of beta in the netalign objective % li : the start point of each edge in L (a vertex number from graph A) % lj : the end point of each edge in L (a vertex number from graph B) % gamma : the starting step value (default = 0.5) % stepm : number of non-decreasing iterations adjusting the step length % (default = 100) % rtype : the rounding type (default = 1) % rtype = 1 : only consider the current matching % rtype = 2 : try enriching the matching with info from other squares % maxiter : maximum number of iterations to take (default = 1000) % verbose : output verbose information at each iteration (default = true) % % Output % ------ % xbest : the best heuristic solution, it may or may not be a matching % status : three values to describe the status of the solution % status(1) = 1 if the problem is solved to optimality, 0 otherwise % status(2) = best lower bound % status(3) = best upper bound % hist : the history of properties of each iteration % hist(k,) = % hist(k,) = best lower bound at iteration k % hist(k,) = best upper bound at iteration k % hist(k,) = current value at iteration k % hist(k,) = matching weight at iteration k % hist(k,) = matching cardinality at iteration k % hist(k,) = overlap at iteration k % % Example: % load('../data/natalie_graphs'); % netalignmr(S,w,0,1,li,lj); % David F. Gleich, Ying Wang, and Mohsen Bayati % Copyright, Stanford University, 2008-2009 % Computational Approaches to Digital Stewardship % 2009-06-11: Initial coding (David and Ying) % 2009-06-15: Cleanup and optimization (David) if ~exist('a','var') || isempty(a), a=1; end if ~exist('b','var') || isempty(b), b=1; end if ~exist('stepm','var') || isempty(stepm), stepm=25; end if ~exist('rtype','var') || isempty(rtype), rtype=1; end if ~exist('maxiter', 'var') || isempty(maxiter), maxiter=1000; end if ~exist('verbose', 'var') || isempty(verbose), verbose=1; end if ~exist('gamma', 'var') || isempty(gamma), gamma = 0.4; end m = max(li); n = max(lj); [rp ci ai tripi matn matm] = bipartite_matching_setup(w,li,lj,m,n); mperm = tripi(tripi>0); % a permutation for the matching problem S = double(S); U = sparse(size(S,1),size(S,2)); xbest = w; xbest(:) = 0; flower = 0; % best lower bound on the solution fupper = Inf; % best upper bound on the solution next_reduction_iteration = stepm; % reduce the step crystalize_phase = 0; % a variable to indicate we are in the crystalization phase crystalize_gamma = 1e-20; crystalize_stepm = 5; hist = zeros(maxiter,7); if verbose % print the header fprintf('%5s %4s %8s %7s %7s %7s %7s %7s %7s %7s\n', ... 'best', 'iter', 'norm-u', 'lower','upper', 'cur', 'obj', 'weight', 'card', 'overlap'); end for iter = 1:maxiter [q,SM] = maxrowmatch((b/2)*S + U-U',li,lj,m,n); x = a*w + q; %[val ma mb mi]= bipartite_matching(nw,li,lj,m,n); ai=zeros(length(tripi),1); ai(tripi>0)=x(mperm); [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm); % compute statistics matchval = mi'*w; overlap = mi'*S*mi/2; card = length(ma); f = a*matchval + b*overlap; if val<fupper fupper=val; if ~crystalize_phase next_reduction_iteration = iter+stepm; end end if f>flower flower=f; itermark = '*'; xbest = mi; else itermark = ' '; end if rtype==1 % no work elseif rtype==2 mw = S*x; mw = a*w + b/2*mw; ai=zeros(length(tripi),1); ai(tripi>0)=mw(mperm); [val ma mb mx] = bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm); card = length(ma); matchval = mx'*w; overlap = mx'*S*mx/2; f = a*matchval + b*overlap; if f>flower flower=f; itermark = '**'; mi = mx; xbest = mw; end end % report on current iter hist(iter,1:end) = [norm(nonzeros(U),1), flower, fupper, f, matchval, card, overlap]; if verbose fprintf('%5s %4i %8.1e %7g %7g %7g %7g %7g %7i %7i\n', ... itermark, iter, norm(nonzeros(U),1), ... flower, fupper, val, ... f, matchval, card, overlap); end if iter==next_reduction_iteration gamma = gamma*0.5; if verbose fprintf('%5s %4s reducing step to %g\n', '', '', gamma); end if gamma < 1e-24, break; end if crystalize_phase next_reduction_iteration = iter+crystalize_stepm; else next_reduction_iteration = iter+stepm; end end if (fupper-flower)<1e-2 break; end % check if we need to enter the crystalization phase num_crystalize_iters = crystalize_stepm*(log(crystalize_gamma)-log(gamma))/log(0.5); if ~crystalize_phase && num_crystalize_iters > maxiter - iter crystalize_phase = 1; next_reduction_iteration = iter+crystalize_stepm; fprintf('%5s %4s switching to crystalization phase\n', '', ''); end U = U - diag(sparse(gamma*mi))*triu(SM) + tril(SM)'*diag(sparse(gamma*mi)); U = bound(U, -.5, .5); end hist = hist(1:iter,:); status = zeros(1,3); status(1) = (fupper-flower)<1e-2; status(2) = flower; status(3) = fupper; function S=bound(S,a,b) S=spfun(@(x) min(max(x,a),b), S);
github
bill-codes/netalign-master
netalignbp_y.m
.m
netalign-master/experiments/old/rounding/netalignbp_y.m
6,447
utf_8
60b9cf0f094a4f2449195b5ec82a82d9
function [mbest hista histb] = netalignbp(S,w,a,b,li,lj,gamma,maxiter,verbose) % NETALIGNBP Solve the network alignment problem with Belief Propagation % % % David F. Gleich, Ying Wang, and Mohsen Bayati % Copyright, Stanford University, 2007-2008 % Computational Approaches to Digital Stewardship if ~exist('a','var') || isempty(a), a=1; end if ~exist('b','var') || isempty(b), b=1; end if ~exist('gamma','var') || isempty(gamma), gamma=0.85; end if ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end if ~exist('verbose', 'var') || isempty(verbose), verbose=1; end nedges = length(li); nsquares = nnz(S)/2; m = max(li); n = max(lj); % compute a vector that allows us to transpose data between squares. % Recall the BP algorithm requires edge(i,j) to send messages to edge(r,s) % when (i,j) and (r,s) form a square. However, edge(i,j) needs information % the information that (r,s) sent it from the previous iteraton. % If we imagine that each non-zero of S has a value, we want to tranpose % these values. [sui suj] = find(triu(S,1)); % only consider each square once. SI = sparse(sui,suj,1:length(sui),size(S,1),size(S,2)); % assign indices SI = SI + SI'; % SI now has symmetric indices [si sj sind] = find(SI); SP = sparse(si,sind,true,size(S,1),nsquares); % each column in SP has 2 nz [sij sijrs] = find(SP); sind = (1:nnz(SP))'; spair = sind; spair(1:2:end) = sind(2:2:end); spair(2:2:end) = sind(1:2:end); % sij, sijrs maps between rows and squares % spair is now an indexing vector that accomplishes what we need % Initialize the messages ma = zeros(nedges,1); mb = ma; ms = zeros(nnz(S),1); damping = gamma; curdamp = 1; iter = 1; alpha = a; beta = b; % Initialize history hista = zeros(maxiter,4); % history of messages from ei->a vertices histb = zeros(maxiter,4); % history of messages from ei->b vertices fbest = 0; fbestiter = 0; if verbose % print the header fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\n', ... 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ... 'obj_mb', 'wght_mb', 'card_mb', 'over_mb'); end % setup the matching problem once [rp ci ai tripi matn matm] = bipartite_matching_setup(... w,li,lj,m,n); clear ai; while iter<=maxiter prevma = ma; prevmb = mb; prevms = ms; curdamp = damping*curdamp; omaxb = othermaxplus(2,li,lj,mb,m,n); omaxa = othermaxplus(1,li,lj,ma,m,n); msflip = ms(spair); % swap ij->ijrs to rs->ijrs mymsflip = msflip+beta; mymsflip = min(beta,mymsflip); mymsflip = max(0,mymsflip); sums = accumarray(sij,mymsflip,[nedges 1],@sum,0); ma = alpha*w - omaxb + sums; mb = alpha*w - omaxa + sums; ms = alpha*w(sij)-(omaxb(sij) + omaxa(sij)); ms = ms + othersum(sij,sijrs,mymsflip,nedges,nsquares); ma = curdamp*(ma) + (1-curdamp)*(prevma); mb = curdamp*(mb) + (1-curdamp)*(prevmb); ms = curdamp*(ms) + (1-curdamp)*(prevms); % now compute the matchings sums1 = accumarray(sij,mymsflip,[nedges 1],@sum,0); sums2 = accumarray(sij,mymsflip,[nedges 1],@sum,0); hista(iter,:) = round_messages(alpha*w + beta*sums1,S,w,alpha,beta,rp,ci,tripi,matn,matm); histb(iter,:) = round_messages(alpha*w + beta*sums2,S,w,alpha,beta,rp,ci,tripi,matn,matm); if hista(iter,1)>fbest fbestiter=iter; mbest=sums1; fbest=hista(iter,1); end if histb(iter,1)>fbest fbestiter=-iter; mbest=sums2; fbest=histb(iter,1); end if verbose if fbestiter==iter, bestchar='*a'; elseif fbestiter==-iter, bestchar='*b'; else bestchar=''; end fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\n', ... bestchar, iter, hista(iter,:), histb(iter,:)); end iter=iter+1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m) ai=zeros(length(tripi),1); ai(tripi>0)=messages; [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m); matchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*mi))/2; f = alpha*matchweight + beta*overlap; info = [f matchweight cardinality overlap]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function omp=othermaxplus(dim,li,lj,lw,m,n) % OTHERMAXPLUS Apply the other-max-plus operator to a sparse matrix % % The other-max-plus operator applies the max-plus aggegration function % over the rows or columns of the matrix, where, for % each non-zeros, the non-zero itself cannot be the maximum. Consequently, % Hence, it's the max-plus of all the "other" elements in the row or column % (which is controlled by dim). % % omp=othermaxplus(dim,li,lj,lw,m,n) applies the other-max-plus operator % to the matrix sparse(li, lj, lw, m, n). The return value omp gives % the other-max-plus value for each non-zero element, e.g. the matrix % is sparse(li, lj, omp, m, n). if dim==1 % max-plus over cols i1 = lj; i2 = li; N = n; else % max-plus over rows i1 = li; i2 = lj; N = m; end % the output of the other-max-plus is either the maximum element % in the row or column (if the element itself isn't the maximum) or % the second largest element in the row or column (if the element itself % IS the maximum). dimmax1 =0*ones(N,1); % largest value dimmax2 = 0*ones(N,1); % second largest value, % this is correct because of the definition of the max-plus function. dimmaxind = zeros(N,1); % index of largest value nedges = length(li); for i=1:nedges if lw(i) > dimmax2(i1(i)) if lw(i) > dimmax1(i1(i)) dimmax2(i1(i)) = dimmax1(i1(i)); dimmax1(i1(i)) = lw(i); dimmaxind(i1(i)) = i2(i); else dimmax2(i1(i)) = lw(i); end end end omp = zeros(size(lw)); for i=1:nedges if i2(i) == dimmaxind(i1(i)) omp(i) = dimmax2(i1(i)); else omp(i) = dimmax1(i1(i)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function os=othersum(si,sj,s,m,n) %#ok<INUSD,INUSL> % OTHERSUM Compute the sum of each column of the matrix, without each % individual entry. This corresponds to a matrix where each entry is the % sum of each column but with each entry subtracted. rowsum=accumarray(si,s,[m,1]); os=rowsum(si)-s;
github
bill-codes/netalign-master
netalignbp_yz.m
.m
netalign-master/experiments/old/rounding/netalignbp_yz.m
6,465
utf_8
3bd7d5f146af758410916577c9f26650
function [mbest hista histb] = netalignbp(S,w,a,b,li,lj,gamma,maxiter,verbose) % NETALIGNBP Solve the network alignment problem with Belief Propagation % % % David F. Gleich, Ying Wang, and Mohsen Bayati % Copyright, Stanford University, 2007-2008 % Computational Approaches to Digital Stewardship if ~exist('a','var') || isempty(a), a=1; end if ~exist('b','var') || isempty(b), b=1; end if ~exist('gamma','var') || isempty(gamma), gamma=0.85; end if ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end if ~exist('verbose', 'var') || isempty(verbose), verbose=1; end nedges = length(li); nsquares = nnz(S)/2; m = max(li); n = max(lj); % compute a vector that allows us to transpose data between squares. % Recall the BP algorithm requires edge(i,j) to send messages to edge(r,s) % when (i,j) and (r,s) form a square. However, edge(i,j) needs information % the information that (r,s) sent it from the previous iteraton. % If we imagine that each non-zero of S has a value, we want to tranpose % these values. [sui suj] = find(triu(S,1)); % only consider each square once. SI = sparse(sui,suj,1:length(sui),size(S,1),size(S,2)); % assign indices SI = SI + SI'; % SI now has symmetric indices [si sj sind] = find(SI); SP = sparse(si,sind,true,size(S,1),nsquares); % each column in SP has 2 nz [sij sijrs] = find(SP); sind = (1:nnz(SP))'; spair = sind; spair(1:2:end) = sind(2:2:end); spair(2:2:end) = sind(1:2:end); % sij, sijrs maps between rows and squares % spair is now an indexing vector that accomplishes what we need % Initialize the messages ma = zeros(nedges,1); mb = ma; ms = zeros(nnz(S),1); damping = gamma; curdamp = 1; iter = 1; alpha = a; beta = b; % Initialize history hista = zeros(maxiter,4); % history of messages from ei->a vertices histb = zeros(maxiter,4); % history of messages from ei->b vertices fbest = 0; fbestiter = 0; if verbose % print the header fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\n', ... 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ... 'obj_mb', 'wght_mb', 'card_mb', 'over_mb'); end % setup the matching problem once [rp ci ai tripi matn matm] = bipartite_matching_setup(... w,li,lj,m,n); clear ai; while iter<=maxiter prevma = ma; prevmb = mb; prevms = ms; curdamp = damping*curdamp; omaxb = othermaxplus(2,li,lj,mb,m,n); omaxa = othermaxplus(1,li,lj,ma,m,n); msflip = ms(spair); % swap ij->ijrs to rs->ijrs mymsflip = msflip+beta; mymsflip = min(beta,mymsflip); mymsflip = max(0,mymsflip); sums = accumarray(sij,mymsflip,[nedges 1],@sum,0); ma = alpha*w - omaxb + sums; mb = alpha*w - omaxa + sums; ms = alpha*w(sij)-(omaxb(sij) + omaxa(sij)); ms = ms + othersum(sij,sijrs,mymsflip,nedges,nsquares); ma = curdamp*(ma) + (1-curdamp)*(prevma); mb = curdamp*(mb) + (1-curdamp)*(prevmb); ms = curdamp*(ms) + (1-curdamp)*(prevms); % now compute the matchings sums1 = accumarray(sij,mymsflip.*ma(sij),[nedges 1],@sum,0); sums2 = accumarray(sij,mymsflip.*ma(sij),[nedges 1],@sum,0); hista(iter,:) = round_messages(alpha*w + beta*sums1,S,w,alpha,beta,rp,ci,tripi,matn,matm); histb(iter,:) = round_messages(alpha*w + beta*sums2,S,w,alpha,beta,rp,ci,tripi,matn,matm); if hista(iter,1)>fbest fbestiter=iter; mbest=sums1; fbest=hista(iter,1); end if histb(iter,1)>fbest fbestiter=-iter; mbest=sums2; fbest=histb(iter,1); end if verbose if fbestiter==iter, bestchar='*a'; elseif fbestiter==-iter, bestchar='*b'; else bestchar=''; end fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\n', ... bestchar, iter, hista(iter,:), histb(iter,:)); end iter=iter+1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m) ai=zeros(length(tripi),1); ai(tripi>0)=messages; [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m); matchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*mi))/2; f = alpha*matchweight + beta*overlap; info = [f matchweight cardinality overlap]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function omp=othermaxplus(dim,li,lj,lw,m,n) % OTHERMAXPLUS Apply the other-max-plus operator to a sparse matrix % % The other-max-plus operator applies the max-plus aggegration function % over the rows or columns of the matrix, where, for % each non-zeros, the non-zero itself cannot be the maximum. Consequently, % Hence, it's the max-plus of all the "other" elements in the row or column % (which is controlled by dim). % % omp=othermaxplus(dim,li,lj,lw,m,n) applies the other-max-plus operator % to the matrix sparse(li, lj, lw, m, n). The return value omp gives % the other-max-plus value for each non-zero element, e.g. the matrix % is sparse(li, lj, omp, m, n). if dim==1 % max-plus over cols i1 = lj; i2 = li; N = n; else % max-plus over rows i1 = li; i2 = lj; N = m; end % the output of the other-max-plus is either the maximum element % in the row or column (if the element itself isn't the maximum) or % the second largest element in the row or column (if the element itself % IS the maximum). dimmax1 =0*ones(N,1); % largest value dimmax2 = 0*ones(N,1); % second largest value, % this is correct because of the definition of the max-plus function. dimmaxind = zeros(N,1); % index of largest value nedges = length(li); for i=1:nedges if lw(i) > dimmax2(i1(i)) if lw(i) > dimmax1(i1(i)) dimmax2(i1(i)) = dimmax1(i1(i)); dimmax1(i1(i)) = lw(i); dimmaxind(i1(i)) = i2(i); else dimmax2(i1(i)) = lw(i); end end end omp = zeros(size(lw)); for i=1:nedges if i2(i) == dimmaxind(i1(i)) omp(i) = dimmax2(i1(i)); else omp(i) = dimmax1(i1(i)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function os=othersum(si,sj,s,m,n) %#ok<INUSD,INUSL> % OTHERSUM Compute the sum of each column of the matrix, without each % individual entry. This corresponds to a matrix where each entry is the % sum of each column but with each entry subtracted. rowsum=accumarray(si,s,[m,1]); os=rowsum(si)-s;
github
bill-codes/netalign-master
netalignmr.m
.m
netalign-master/matlab/netalignmr.m
5,472
utf_8
3bba17d17e4d620f961d10dc0048c844
function [xbest,status,hist] = netalignmr(S,w,a,b,li,lj,gamma,stepm,rtype,maxiter,verbose) % NETALIGNMR Compute the matching relaxation heuristic for network alignment % % Given a network alignment problem, the matching heuristic solves a % sequence of matching problems to generate good upper and lower bounds on % the solutions. % % [xbest,status,hist] = netalignmr(S,w,a,b,li,lj,stepm,rtype, % maxiter,verbose) % fully specifies all inputs and outputs. % % Input % ----- % S : the complete set of squares % w : the matching weights for all edges in the link graph L % a : the value of alpha in the netalign objective % b : the value of beta in the netalign objective % li : the start point of each edge in L (a vertex number from graph A) % lj : the end point of each edge in L (a vertex number from graph B) % gamma : the starting step value (default = 0.5) % stepm : number of non-decreasing iterations adjusting the step length % (default = 100) % rtype : the rounding type (default = 1) % rtype = 1 : only consider the current matching % rtype = 2 : try enriching the matching with info from other squares % maxiter : maximum number of iterations to take (default = 1000) % verbose : output verbose information at each iteration (default = true) % % Output % ------ % xbest : the best heuristic solution, it may or may not be a matching % status : three values to describe the status of the solution % status(1) = 1 if the problem is solved to optimality, 0 otherwise % status(2) = best lower bound % status(3) = best upper bound % hist : the history of properties of each iteration % hist(k,) = % hist(k,) = best lower bound at iteration k % hist(k,) = best upper bound at iteration k % hist(k,) = current value at iteration k % hist(k,) = matching weight at iteration k % hist(k,) = matching cardinality at iteration k % hist(k,) = overlap at iteration k % % Example: % load('../data/natalie_graphs'); % netalignmr(S,w,0,1,li,lj); % David F. Gleich, Ying Wang, and Mohsen Bayati % Copyright, Stanford University, 2008-2009 % Computational Approaches to Digital Stewardship % 2009-06-11: Initial coding (David and Ying) % 2009-06-15: Cleanup and optimization (David) if ~exist('a','var') || isempty(a), a=1; end if ~exist('b','var') || isempty(b), b=1; end if ~exist('stepm','var') || isempty(stepm), stepm=25; end if ~exist('rtype','var') || isempty(rtype), rtype=1; end if ~exist('maxiter', 'var') || isempty(maxiter), maxiter=1000; end if ~exist('verbose', 'var') || isempty(verbose), verbose=1; end if ~exist('gamma', 'var') || isempty(gamma), gamma = 0.4; end m = max(li); n = max(lj); [rp ci ai tripi matn matm] = bipartite_matching_setup(w,li,lj,m,n); mperm = tripi(tripi>0); % a permutation for the matching problem S = double(S); U = sparse(size(S,1),size(S,2)); xbest = w; xbest(:) = 0; flower = 0; % best lower bound on the solution fupper = Inf; % best upper bound on the solution next_reduction_iteration = stepm; % reduce the step hist = zeros(maxiter,7); if verbose % print the header fprintf('%5s %4s %8s %7s %7s %7s %7s %7s %7s %7s\n', ... 'best', 'iter', 'norm-u', 'lower','upper', 'cur', 'obj', 'weight', 'card', 'overlap'); end for iter = 1:maxiter [q,SM] = maxrowmatch((b/2)*S + U-U',li,lj,m,n); x = a*w + q; %[val ma mb mi]= bipartite_matching(nw,li,lj,m,n); ai=zeros(length(tripi),1); ai(tripi>0)=x(mperm); [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm); % compute statistics matchval = mi'*w; overlap = mi'*S*mi/2; card = length(ma); f = a*matchval + b*overlap; if val<fupper fupper=val; next_reduction_iteration = iter+stepm; end if f>flower flower=f; itermark = '*'; xbest = mi; else itermark = ' '; end if rtype==1 % no work elseif rtype==2 mw = S*x; mw = a*w + b/2*mw; ai=zeros(length(tripi),1); ai(tripi>0)=mw(mperm); [val ma mb mx] = bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm); card = length(ma); matchval = mx'*w; overlap = mx'*S*mx/2; f = a*matchval + b*overlap; if f>flower flower=f; itermark = '**'; mi = mx; xbest = mw; end end % report on current iter hist(iter,1:end) = [norm(nonzeros(U),1), flower, fupper, f, matchval, card, overlap]; if verbose fprintf('%5s %4i %8.1e %7g %7g %7g %7g %7g %7i %7i\n', ... itermark, iter, norm(nonzeros(U),1), ... flower, fupper, val, ... f, matchval, card, overlap); end if iter==next_reduction_iteration gamma = gamma*0.5; if verbose fprintf('%5s %4s reducing step to %g\n', '', '', gamma); end if gamma < 1e-24, break; end next_reduction_iteration = iter+stepm; end if (fupper-flower)<1e-2 break; end U = U - diag(sparse(gamma*mi))*triu(SM) + tril(SM)'*diag(sparse(gamma*mi)); U = bound(U, -.5, .5); end hist = hist(1:iter,:); status = zeros(1,3); status(1) = (fupper-flower)<1e-2; status(2) = flower; status(3) = fupper; function S=bound(S,a,b) S=spfun(@(x) min(max(x,a),b), S);
github
bill-codes/netalign-master
netalignbp.m
.m
netalign-master/matlab/netalignbp.m
7,067
utf_8
366425d10c4e61e2ec0d1782c9ac8c30
function [mbest hista histb] = netalignbp(S,w,a,b,li,lj,gamma,dtype,maxiter,verbose) % NETALIGNBP Solve the network alignment problem with Belief Propagation % % % David F. Gleich, Ying Wang, and Mohsen Bayati % Copyright, Stanford University, 2007-2009 % Computational Approaches to Digital Stewardship % History % 2009-06-02: Implemented Mohsen's new updates to get a higher overlap if ~exist('a','var') || isempty(a), a=1; end if ~exist('b','var') || isempty(b), b=1; end if ~exist('gamma','var') || isempty(gamma), gamma=0.99; end if ~exist('dtype', 'var') || isempty(dtype), dtype=2; end if ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end if ~exist('verbose', 'var') || isempty(verbose), verbose=1; end nedges = length(li); nsquares = nnz(S)/2; m = max(li); n = max(lj); % compute a vector that allows us to transpose data between squares. % Recall the BP algorithm requires edge(i,j) to send messages to edge(r,s) % when (i,j) and (r,s) form a square. However, edge(i,j) needs information % the information that (r,s) sent it from the previous iteraton. % If we imagine that each non-zero of S has a value, we want to tranpose % these values. [sui suj] = find(triu(S,1)); % only consider each square once. SI = sparse(sui,suj,1:length(sui),size(S,1),size(S,2)); % assign indices SI = SI + SI'; % SI now has symmetric indices [si sj sind] = find(SI); SP = sparse(si,sind,true,size(S,1),nsquares); % each column in SP has 2 nz [sij sijrs] = find(SP); sind = (1:nnz(SP))'; spair = sind; spair(1:2:end) = sind(2:2:end); spair(2:2:end) = sind(1:2:end); % sij, sijrs maps between rows and squares % spair is now an indexing vector that accomplishes what we need % Initialize the messages ma = zeros(nedges,1); mb = ma; ms = zeros(nnz(S),1); sums = zeros(nedges,1); damping = gamma; curdamp = 1; iter = 1; alpha = a; beta = b; % Initialize history hista = zeros(maxiter,4); % history of messages from ei->a vertices histb = zeros(maxiter,4); % history of messages from ei->b vertices fbest = 0; fbestiter = 0; if verbose % print the header fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\n', ... 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ... 'obj_mb', 'wght_mb', 'card_mb', 'over_mb'); end % setup the matching problem once [rp ci ai tripi matn matm] = bipartite_matching_setup(... w,li,lj,m,n); mperm = tripi(tripi>0); % a permutation for the matching problem clear ai; while iter<=maxiter prevma = ma; prevmb = mb; prevms = ms; prevsums = sums; curdamp = damping*curdamp; omaxb = max(othermaxplus(2,li,lj,mb,m,n),0); omaxa = max(othermaxplus(1,li,lj,ma,m,n),0); msflip = ms(spair); % swap ij->ijrs to rs->ijrs mymsflip = msflip+beta; mymsflip = min(beta,mymsflip); mymsflip = max(0,mymsflip); sums = accumarray(sij,mymsflip,[nedges 1],@sum,0); ma = alpha*w - omaxb + sums; mb = alpha*w - omaxa + sums; ms = alpha*w(sij)-(omaxb(sij) + omaxa(sij)); ms = ms + othersum(sij,sijrs,mymsflip,nedges,nsquares); % Original updates if dtype==1 ma = curdamp*(ma) + (1-curdamp)*(prevma); mb = curdamp*(mb) + (1-curdamp)*(prevmb); ms = curdamp*(ms) + (1-curdamp)*(prevms); elseif dtype==2 ma = ma + (1-curdamp)*(prevma+prevmb-alpha*w+prevsums); mb = mb + (1-curdamp)*(prevmb+prevma-alpha*w+prevsums); ms = ms + (1-curdamp)*(prevms+prevms(spair)-beta); elseif dtype==3 ma = curdamp*ma + (1-curdamp)*(prevma+prevmb-alpha*w+prevsums); mb = curdamp*mb + (1-curdamp)*(prevmb+prevma-alpha*w+prevsums); ms = curdamp*ms + (1-curdamp)*(prevms+prevms(spair)-beta); end % now compute the matchings hista(iter,:) = round_messages(ma,S,w,alpha,beta,rp,ci,tripi,matn,matm,mperm); histb(iter,:) = round_messages(mb,S,w,alpha,beta,rp,ci,tripi,matn,matm,mperm); if hista(iter,1)>fbest fbestiter=iter; mbest=ma; fbest=hista(iter,1); end if histb(iter,1)>fbest fbestiter=-iter; mbest=mb; fbest=histb(iter,1); end if verbose if fbestiter==iter, bestchar='*a'; elseif fbestiter==-iter, bestchar='*b'; else bestchar=''; end fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\n', ... bestchar, iter, hista(iter,:), histb(iter,:)); end iter=iter+1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m,perm) ai=zeros(length(tripi),1); ai(tripi>0)=messages(perm); [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m); matchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*double(mi)))/2; f = alpha*matchweight + beta*overlap; info = [f matchweight cardinality overlap]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function omp=othermaxplus(dim,li,lj,lw,m,n) % OTHERMAXPLUS Apply the other-max-plus operator to a sparse matrix % % The other-max-plus operator applies the max-plus aggegration function % over the rows or columns of the matrix, where, for % each non-zeros, the non-zero itself cannot be the maximum. Consequently, % Hence, it's the max-plus of all the "other" elements in the row or column % (which is controlled by dim). % % omp=othermaxplus(dim,li,lj,lw,m,n) applies the other-max-plus operator % to the matrix sparse(li, lj, lw, m, n). The return value omp gives % the other-max-plus value for each non-zero element, e.g. the matrix % is sparse(li, lj, omp, m, n). if dim==1 % max-plus over cols i1 = lj; i2 = li; N = n; else % max-plus over rows i1 = li; i2 = lj; N = m; end % the output of the other-max-plus is either the maximum element % in the row or column (if the element itself isn't the maximum) or % the second largest element in the row or column (if the element itself % IS the maximum). dimmax1 =0*ones(N,1); % largest value dimmax2 = 0*ones(N,1); % second largest value, % this is correct because of the definition of the max-plus function. dimmaxind = zeros(N,1); % index of largest value nedges = length(li); for i=1:nedges if lw(i) > dimmax2(i1(i)) if lw(i) > dimmax1(i1(i)) dimmax2(i1(i)) = dimmax1(i1(i)); dimmax1(i1(i)) = lw(i); dimmaxind(i1(i)) = i2(i); else dimmax2(i1(i)) = lw(i); end end end omp = zeros(size(lw)); for i=1:nedges if i2(i) == dimmaxind(i1(i)) omp(i) = dimmax2(i1(i)); else omp(i) = dimmax1(i1(i)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function os=othersum(si,sj,s,m,n) %#ok<INUSD,INUSL> % OTHERSUM Compute the sum of each column of the matrix, without each % individual entry. This corresponds to a matrix where each entry is the % sum of each column but with each entry subtracted. rowsum=accumarray(si,s,[m,1]); os=rowsum(si)-s;
github
bill-codes/netalign-master
evaluate_alignment.m
.m
netalign-master/matlab/evaluate_alignment.m
4,797
utf_8
11f4dfb2cdec144b885fe302325fedc0
function [s Mcc]=evaluate_alignment(A,B,mi,li,lj) % EVALUATE_ALIGNMENT Report properties of the graph alignment % % evaluate_alignment(A,B,mi,li,lj) returns properties of an alignment % between graphs A and B. % evaluate_alignment(A,B,ma,mb) returns properties of an alignment % between graphs A and B. % % Edges - number of edges (2-cliques) preserved by the mapping % Triangles - number of triangles (3-cliques) preserved by the mapping % Largest Component - largest connected component with the mapping % % History % 2009-07-01: Initial coding if nargin==4 ma = mi; mb = li; % given as pairs X = sparse(ma,mb,1,size(A,1),size(B,1)); else % given as an indicator % make sure x is binary if any(logical(mi)~=mi) error('netalign:invalidMatching',... 'the matching indicator mi is not binary') end X = sparse(li,lj,mi,size(A,1),size(B,1)); end % make sure x is a matching s1 = sum(X,1); s2 = sum(X,2); if any(s1~=logical(s1)) || any(s2~=logical(s2)) error('netalign:invalidMatching',... 'the given alignment is not a matching'); end [rpA ciA] = sparse_to_csr(A); [rpB ciB] = sparse_to_csr(B); As = struct('rp',rpA,'ci',ciA); Bs = struct('rp',rpB,'ci',ciB); nA = length(rpA)-1; nB = length(rpB)-1; [ma mb] = find(X); % the overlapped graph [nedges,OA,OB]=count_overlap(As,Bs,[ma mb]); G = [OA X; X' OB]; [ci,sizes] = scomponents(G); [ma mb] = find(X); % create the output as a structure s = []; s.size = length(ma); [s.largest_component,max_ci] = max(sizes); s.edges = count_overlap(As,Bs,[ma mb]); s.triangles = count_triangle_overlap(As,Bs,[ma mb]); s.largest_component_A = sum(ci(1:nA)==max_ci); s.largest_component_B = sum(ci(nA+1:end)==max_ci); Mcc = sparse(find(ci(1:nA)==max_ci), find(ci(nA+1:end)==max_ci), 1, nA, nB); % display output unless requested if nargout == 0 fprintf('%25s %i\n', 'Size', s.size); fprintf('%25s %i\n', 'Edge Overlap', s.edges); fprintf('%25s %i\n', 'Triangle Overlap', s.triangles); fprintf('%25s %i\n', 'Largest Component', s.largest_component); fprintf('%25s %i\n', 'Largest Component (A)', s.largest_component_A); fprintf('%25s %i\n', 'Largest Component (B)', s.largest_component_B); end function [ntris]=count_triangle_overlap(A,B,m) if ~isstruct(A) [rpA ciA] = sparse_to_csr(A); else rpA = A.rp; ciA = A.ci; end if ~isstruct(B) [rpB ciB] = sparse_to_csr(B); else rpB = B.rp; ciB = B.ci; end nA = length(rpA)-1; nB = length(rpB)-1; % index the matches in a to b mAB = zeros(nA,1); mAB(m(:,1)) = m(:,2); mBA = zeros(nB,1); mBA(m(:,2)) = m(:,1); ntris = 0; nmatches = size(m,1); aindex = zeros(nA,1); bindex = zeros(nB,1); % bindex is a work vector for i=1:nmatches % count the number of triangles from this match va = m(i,1); vb = m(i,2); % index the neighbors in A for riA=rpA(va):rpA(va+1)-1 if ciA(riA)==va, continue; end % skip self loops aindex(ciA(riA))=1; end % index the edges in B for riB=rpB(vb):rpB(vb+1)-1 if ciB(riB)==vb, continue; end % skip self loops bindex(ciB(riB))=1; end % for all the edges in A, see if there is an edge in B too for riA=rpA(va):rpA(va+1)-1 % va2 is the neighbor of va va2 = ciA(riA); % skip self-loops if va2 == va, continue; end va2image = mAB(va2); % get the image if va2image if bindex(va2image) % let's see if we can complete a triangle in A from % this edge for riA2=rpA(va2):rpA(va2+1)-1 va3 = ciA(riA2); if va3 == va2, continue; end % skip self-loops if aindex(va3) % va,va2,va3 is a triangle and va,va2 is in b % so check if (va,va3) and (va2,va3) are % preserved by the mapping va3image = mAB(va3); if va3image && bindex(va3image) % (va,va3) is present, check (va2,va3) for riB=rpB(va2image):rpB(va2image+1)-1 b3 = ciB(riB); if mBA(b3)==va3 ntris = ntris + 1; end end end end end end end end % clear the index of edges in A for riA=rpA(va):rpA(va+1)-1 aindex(ciA(riA))=0; end % clear the index of edges in B for riB=rpB(vb):rpB(vb+1)-1 bindex(ciB(riB))=0; end end ntris = ntris/6;
github
bill-codes/netalign-master
netalign_lagrange.m
.m
netalign-master/matlab/netalign_lagrange.m
3,194
utf_8
c002a2f87068662095111cbc700b4541
function [xbest fupper hist] = netalign_lagrange(S,w,a,b,li,lj,stepm,rtype,maxiter,verbose) % NETALIGN_LAGRANGE Solve the network alignment problem % with Lagrangean relaxation % % David F. Gleich, Ying Wang, and Mohsen Bayati % Copyright, Stanford University, 2008-2009 % Computational Approaches to Digital Stewardship if ~exist('a','var') || isempty(a), a=1; end if ~exist('b','var') || isempty(b), b=1; end if ~exist('stepm','var') || isempty(stepm), stepm=100; end if ~exist('rtype','var') || isempty(rtype), rtype=1; end if ~exist('maxiter', 'var') || isempty(maxiter), maxiter=1000; end if ~exist('verbose', 'var') || isempty(verbose), verbose=1; end m = max(li); n = max(lj); [rp ci ai tripi matn matm] = bipartite_matching_setup(w,li,lj,m,n); mperm = tripi(tripi>0); % a permutation for the matching problem S = triu(S); S = double(S); U = sparse(size(S,1),size(S,2)); xbest = w; xbest(:) = 0; flower = 0; fupper = Inf; next_reduction_iteration = stepm; % reduce the step gamma = 1; hist = zeros(maxiter,7); if verbose % print the header fprintf('%5s %4s %8s %7s %7s %7s %7s %7s %7s\n', ... 'best', 'iter', 'norm-u', 'lower','upper', 'obj', 'weight', 'card', 'overlap'); end for iter = 1:maxiter nw = a * w + b * (sum(max(0, .5 * S + U), 2) + sum(max(0, .5 * S - U),1)'); %[val ma mb mi]= bipartite_matching(nw,li,lj,m,n); ai=zeros(length(tripi),1); ai(tripi>0)=nw(mperm); [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm); % compute statistics matchval = mi'*w; overlap = mi'*S*mi; % no divide by 2 is okay, because S = triu(S) :-). card = length(ma); f = a*matchval + b*overlap; if val<fupper fupper=val; next_reduction_iteration = iter+stepm; end if f>flower flower=f; itermark = '*'; xbest = mi; else itermark = ' '; end if rtype==1 % no work elseif rtype==2 mw = S*mi; mw = mw + S'*mi; mw = a*w + b/2*mw; ai=zeros(length(tripi),1); ai(tripi>0)=mw(mperm); [val ma mb mx] = bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm); card = length(ma); matchval = mx'*w; overlap = mx'*S*mx; f = a*matchval + b*overlap; if f>flower flower=f; itermark = '**'; mi = mx; xbest = mw; end end % report on current iter hist(iter,1:end) = [norm(nonzeros(U),1), flower, fupper, f, matchval, card, overlap]; if verbose fprintf('%5s %4i %8.1e %7g %7g %7g %7g %7i %7i\n', ... itermark, iter, norm(nonzeros(U),1), ... flower, fupper, ... f, matchval, card, overlap); end if iter==next_reduction_iteration gamma = gamma*0.5; if verbose fprintf('%5s %4s reducing step to %g\n', '', '', gamma); end next_reduction_iteration = iter+stepm; end U = bound(U - (diag(sparse(mi)) * S - S * diag(sparse(mi))) * gamma, -.5, .5); end function S=bound(S,a,b) S=spfun(@(x) min(max(x,a),b), S);
github
bill-codes/netalign-master
netalignbpmr.m
.m
netalign-master/matlab/netalignbpmr.m
4,762
utf_8
7286539d79a120310bfc2d322d442ccc
function [mbest hista histb] = netalignbpmr(S,w,a,b,li,lj,gamma,dtype,maxiter,verbose) % NETALIGNMBP Solve the network alignment problem with Belief Propagation % % This version of network alignment uses the matrix formulation of the % algorithm. % David F. Gleich, Ying Wang, and Mohsen Bayati % Copyright, Stanford University, 2007-2009 % Computational Approaches to Digital Stewardship if ~exist('a','var') || isempty(a), a=1; end if ~exist('b','var') || isempty(b), b=1; end if ~exist('gamma','var') || isempty(gamma), gamma=0.99; end if ~exist('dtype', 'var') || isempty(dtype), dtype=2; end if ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end if ~exist('verbose', 'var') || isempty(verbose), verbose=1; end nedges = length(li); nsquares = nnz(S)/2; m = max(li); n = max(lj); % the following is elegant, but inefficient :-( %Ar = sparse(li,1:nedges,1,m,nedges); [ari arj arv]=find(Ar'*Ar-speye(nedges)); %Ac = sparse(lj,1:nedges,1,n,nedges); [aci acj acv]=find(Ac'*Ac-speye(nedges)); % Initialize the messages y = zeros(nedges,1); z = y; Sk = 0*S; if dtype>1, d = y; end % needed for damping scheme % Initialize a few parameters damping = gamma; curdamp = 1; iter = 1; % Initialize history hista = zeros(maxiter,4); % history of messages from ei->a vertices histb = zeros(maxiter,4); % history of messages from ei->b vertices fbest = 0; fbestiter = 0; if verbose % print the header fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\n', ... 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ... 'obj_mb', 'wght_mb', 'card_mb', 'over_mb'); end % setup the matching problem once [rp ci ai tripi matn matm] = bipartite_matching_setup(... w,li,lj,m,n); mperm = tripi(tripi>0); while iter<=maxiter curdamp = damping*curdamp; %Sknew = bound(Sk' + b*S,0,b); if dtype>1, dold=d; end [d,SM] = maxrowmatch(Sk' + b*S,li,lj,matn,matm); SM = bound(SM,0,b); ynew = a*w - max(0,implicit_maxprod(m,li,z)) + d; znew = a*w - max(0,implicit_maxprod(n,lj,y)) + d; % NOTE in comparison netalignbp, othersum isn't needed because othersum % of Sknew = d*S - Sknew Skt = diag(sparse(ynew+znew-a*w-d))*S-SM; if dtype==1 Sk = curdamp*Skt+ (1-curdamp)*Sk; y = curdamp*ynew+(1-curdamp)*y; z = curdamp*znew+(1-curdamp)*z; elseif dtype==2 prev = (y+z-a*w+dold); y = ynew+(1-curdamp)*prev; z = znew+(1-curdamp)*prev; clear prev; Sk = Skt + (1-curdamp)*(Sk+Sk'-b*S); elseif dtype==3 prev = (y+z-a*w+dold); y = curdamp*ynew+(1-curdamp)*prev; z = curdamp*znew+(1-curdamp)*prev; clear prev; Sk = curdamp*Skt + (1-curdamp)*(Sk+Sk'-b*S); end hista(iter,:) = round_messages(y,S,w,a,b,rp,ci,tripi,matn,matm,mperm); histb(iter,:) = round_messages(z,S,w,a,b,rp,ci,tripi,matn,matm,mperm); if hista(iter,1)>fbest fbestiter=iter; mbest=y; fbest=hista(iter,1); end if histb(iter,1)>fbest fbestiter=-iter; mbest=z; fbest=histb(iter,1); end if verbose if fbestiter==iter, bestchar='*a'; elseif fbestiter==-iter, bestchar='*b'; else bestchar=''; end fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\n', ... bestchar, iter, hista(iter,:), histb(iter,:)); end iter=iter+1; end end function S=bound(S,a,b) S=spfun(@(x) min(b,max(x,a)),S); end function y=maxprod(ai,aj,av,m,x) y=-inf*ones(m,1); for i=1:numel(ai), y(ai(i)) = max(y(ai(i)),av(i)*x(aj(i))); end end function y=implicit_maxprod(n,ai,x) % implicitly compute % Ai=sparse(ai,1:length(ai),1,n,length(z)) % A=Ar'*Ar - speye(length(z)) % maxprod(A,x) % which has a very nice structure if you look at the actual summation % definition. It is just the maximum value N = length(ai); y=-inf*ones(N,1); max1 = -inf*ones(n,1); max2 = -inf*ones(n,1); max1ind = zeros(n,1); for i=1:N if x(i)>max2(ai(i)) if x(i)>max1(ai(i)) max2(ai(i)) = max1(ai(i)); max1(ai(i)) = x(i); max1ind(ai(i)) = i; else max2(ai(i)) = x(i); end end end for i=1:N if i==max1ind(ai(i)) y(i)=max2(ai(i)); else y(i)=max1(ai(i)); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m,perm) ai=zeros(length(tripi),1); ai(tripi>0)=messages(perm); [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m); matchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*double(mi)))/2; f = alpha*matchweight + beta*overlap; info = [f matchweight cardinality overlap]; end
github
bill-codes/netalign-master
netalignscbp.m
.m
netalign-master/matlab/netalignscbp.m
7,240
utf_8
4d86fc6727c6040b65240c5e0079a468
function [mbest hista histb Sk] = netalignscbp(S,w,a,b,li,lj,gamma,dtype,maxiter,verbose) % NETALIGNMPSC Solve the network alignment problem with message passing % % This version of network alignment uses the matrix formulation of the % algorithm. % David F. Gleich, Ying Wang, and Mohsen Bayati % Copyright, Stanford University, 2010 % Computational Approaches to Digital Stewardship if ~exist('a','var') || isempty(a), a=1; end if ~exist('b','var') || isempty(b), b=1; end if ~exist('gamma','var') || isempty(gamma), gamma=0.99; end if ~exist('dtype', 'var') || isempty(dtype), dtype=2; end if ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end if ~exist('verbose', 'var') || isempty(verbose), verbose=1; end nedges = length(li); nsquares = nnz(S); m = max(li); n = max(lj); % Initialize the messages y = zeros(nedges,1); z = y; % copy z as the same size Sk = zeros(nsquares, 1); % messages and their "reversed/transposed" copies Skt = zeros(nsquares, 1); Sw = b * ones(nsquares, 1); MSc = b * ones(nsquares, 4); MScnew = zeros(nsquares, 4); MP = zeros(nsquares, 4); if dtype>1, d = y; end % needed for damping scheme % Initialize a few parameters damping = gamma; curdamp = 1; iter = 1; % Initialize history hista = zeros(maxiter,4); % history of messages from ei->a vertices histb = zeros(maxiter,4); % history of messages from ei->b vertices fbest = 0; fbestiter = 0; if verbose % print the header fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\n', ... 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ... 'obj_mb', 'wght_mb', 'card_mb', 'over_mb'); end % setup the matching problem once [rp ci ai tripi matn matm] = bipartite_matching_setup(... w,li,lj,m,n); mperm = tripi(tripi>0); [rpS ciS] = sparse_to_csr(S); riS = zeros(nsquares, 1); for i=1:nedges for j=rpS(i):rpS(i+1)-1 riS(j) = i; end end Stmp = sparse(riS, ciS, [1:nsquares]'); [ti tj transmap] = find(Stmp); SC = findSC(S, li, lj); r = 1; while iter<=maxiter curdamp = damping*curdamp; if dtype>1, dold=d; end x = Sw; % updates for M_{ii'->f_i} and M_{ii'->g_{i'}}, y, z d = zeros(nedges, 1); Sk_tran = Sk(transmap); for i=1:nedges for j=rpS(i):rpS(i+1)-1 % d(i) = d(i) + max(0, b + Sk_tran(j)) - max(0, Sk_tran(j)); d(i) = d(i) + max(0, (r + 1) * Sw(j) + Sk_tran(j)) - max(0, r * Sw(j) + Sk_tran(j)); end end ynew = a*w - max(0,implicit_maxprod(m,li,z)) + d; znew = a*w - max(0,implicit_maxprod(n,lj,y)) + d; % updates for M_{ii'->h_{ii'jj'}}, Sk t = 0; for i=1:nedges t = ynew(i) + znew(i) - a*w(i) - d(i); for j=rpS(i):rpS(i+1)-1 % Skt(j) = t - max(0, b + Sk_tran(j)) + max(0, Sk_tran(j)); Skt(j) = t - max(0, (r + 1) * Sw(j) + Sk_tran(j)) - max(0, r * Sw(j) + Sk_tran(j)); end end St = Sk + Sk(transmap) + Sw; %updates for M_{ii'jj'->h_{ii'jj'}}, Sw for i=1:4 MP(:,i) = max(0, implicit_maxprod(max(SC(:,i)), SC(:,i), MSc(:, i))); end Sw = -(MP(:,1) + MP(:,2) + MP(:,3) + MP(:,4)) + b; %updates for M_{ii'jj'->d_{ii'j}}, MSc tmp = Sk + Sk(transmap); for i=1:4 MSc(:, i) = Sw + MP(:, i) + min(tmp, min(Sk, Sk(transmap)));; end if dtype==1 Sk = curdamp*Skt+ (1-curdamp)*Sk; y = curdamp*ynew+(1-curdamp)*y; z = curdamp*znew+(1-curdamp)*z; elseif dtype==2 prev = (y+z-a*w+dold); y = ynew+(1-curdamp)*prev; z = znew+(1-curdamp)*prev; clear prev; Sk = Skt + (1-curdamp)*St; Sw = Sw + (1-curdamp)*St; for i=1:4 MSc(:, i) = MSc(:, i) + (1-curdamp)*St; end elseif dtype==3 prev = (y+z-a*w+dold); y = curdamp*ynew+(1-curdamp)*prev; z = curdamp*znew+(1-curdamp)*prev; clear prev; Sk = curdamp * Skt + (1-curdamp)*St; Sw = curdamp * Sw + (1-curdamp)*St; for i=1:4 MSc(:, i) = curdamp * MSc(:, i) + (1-curdamp)*St; end end %tot = roundbyS(Sk, li, lj, riS, ciS, m, n); %tot2 = roundbyyz(S, y, z, li, lj, m, n); iter=iter+1; hista(iter,:) = round_messages(y,S,w,a,b,rp,ci,tripi,matn,matm,mperm); histb(iter,:) = round_messages(z,S,w,a,b,rp,ci,tripi,matn,matm,mperm); if hista(iter,1)>fbest fbestiter=iter; mbest=y; fbest=hista(iter,1); end if histb(iter,1)>fbest fbestiter=-iter; mbest=z; fbest=histb(iter,1); end %fbest = max(fbest, tot); %fbest = max(fbest, tot2); if verbose if fbestiter==iter, bestchar='*a'; elseif fbestiter==-iter, bestchar='*b'; else bestchar=''; end fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\n', ... bestchar, iter, hista(iter,:), histb(iter,:)); end end end function S=bound(S,a,b) S=spfun(@(x) max(b+x,a)-max(x,a),S); end function y=maxprod(ai,aj,av,m,x) y=-inf*ones(m,1); for i=1:numel(ai), y(ai(i)) = max(y(ai(i)),av(i)*x(aj(i))); end end function y=implicit_maxprod(n,ai,x) % implicitly compute % Ai=sparse(ai,1:length(ai),1,n,length(z)) % A=Ar'*Ar - speye(length(z)) % maxprod(A,x) % which has a very nice structure if you look at the actual summation % definition. It is just the maximum value N = length(ai); y=-inf*ones(N,1); max1 = -inf*ones(n,1); max2 = -inf*ones(n,1); max1ind = zeros(n,1); for i=1:N if x(i)>max2(ai(i)) if x(i)>max1(ai(i)) max2(ai(i)) = max1(ai(i)); max1(ai(i)) = x(i); max1ind(ai(i)) = i; else max2(ai(i)) = x(i); end end end for i=1:N if i==max1ind(ai(i)) y(i)=max2(ai(i)); else y(i)=max1(ai(i)); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m,perm) ai=zeros(length(tripi),1); ai(tripi>0)=messages(perm); [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m); matchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*double(mi)))/2; f = alpha*matchweight + beta*overlap; info = [f matchweight cardinality overlap]; end function tot=roundbyS(Sk, li, lj, ri, ci, m, n) [v ind] = sort(Sk, 'descend'); markA = zeros(m, 1); markB = zeros(n, 1); chosen = zeros(size(li, 1), 1); tot = 0; for i=1:size(Sk, 1) v1 = ri(ind(i)); v2 = ci(ind(i)); if (v1 > v2) continue; end if ((~chosen(v1) && (markA(li(v1)) || markB(lj(v1)))) || (~chosen(v2) && (markA(li(v2)) || markB(lj(v2))))) continue; end tot = tot + 1; chosen(v1) = 1; chosen(v2) = 1; markA(li(v1)) = 1; markA(li(v2)) = 1; markB(lj(v1)) = 1; markB(lj(v2)) = 1; end end function tot=roundbyyz(S, y, z, li, lj, m, n) [v ind] = sort(y+z, 'descend'); markA = zeros(m, 1); markB = zeros(n, 1); x = zeros(size(y)); for i=1:size(ind,1) if (~markA(li(ind(i))) && ~markB(lj(ind(i)))) x(ind(i)) = 1; markA(li(ind(i))) = 1; markB(lj(ind(i))) = 1; end end tot = x' * S * x / 2; end
github
bill-codes/netalign-master
expand_match.m
.m
netalign-master/matlab/expand_match.m
2,500
utf_8
f69e78b513c268f81a604be27667dd91
function L = expand_match(A,B,L) % EXPAND_MATCH Expand a set of possible matchings with breadth first search % % L2 = expand_match(A,B,L) returns a new sparse match matrix L2 for the % network alignment problem where L2 includes the neighbors of all existing % matchings. % % % David F. Gleich and Ying Wang % Copyright, Stanford University, 2009 % TODO Example % History % 2009-05-29 Initial coding, based on old c code nA = size(A,1); [rpB ciB vB] = sparse_to_csr(B); [lai laj lav] = compute_expanded_match(nA,rpB,ciB,vB,L); clear rpB ciB vB nB = size(B,1); [rpA ciA vA] = sparse_to_csr(A); [lbj lbi lbv] = compute_expanded_match(nB,rpA,ciA,vA,L'); clear rpA ciA vA lai = [lai; lbi]; laj = [laj; lbj]; lav = [lav; lbv]; clear lbi lbj lbv L = sparse(lai, laj, lav, nA, nB); function [l2i l2j l2v]=compute_expanded_match(nA,rpB,ciB,vB,L) % just do one step of bfs and expand the current match % allocate edges l2i = zeros(nnz(L),1); l2j = l2i; l2v = l2i; curedge = 0; % convert to CSR [rpAB ciAB vAB] = sparse_to_csr(L); nB = length(rpB)-1; % allocate temp arrays work = zeros(nB,1); work_used = zeros(nB,1); dwork = zeros(nB,1); for i=1:nA num_adj = 0; for ri=rpAB(i):rpAB(i+1)-1 j = ciAB(ri); deg_in_B = rpB(j+1)-rpB(j); for ri2=rpB(j):rpB(j+1)-1 k = ciB(ri2); if work(k) == 0 dwork(num_adj+1) = vAB(ri)/deg_in_B; work_used(num_adj+1) = k; work(k) = num_adj+1; num_adj = num_adj + 1; else dwork(work(k)) = max( dwork(work(k)), vAB(ri)/deg_in_B ); end end % make sure we include j if work(j) == 0 dwork(num_adj+1) = vAB(ri); work_used(num_adj+1) = j; work(j) = num_adj+1; num_adj = num_adj + 1; else dwork(work(k)) = max( dwork(work(k)), vAB(ri) ); end end % copy the data and reset the arrays % first check if there is enough space while curedge + num_adj > length(l2i) % double the arrays l2i = [l2i; l2i]; l2j = [l2j; l2j]; l2v = [l2v; l2v]; %#ok<AGROW> end for j=1:num_adj curedge = curedge + 1; l2i(curedge) = i; l2j(curedge) = work_used(j); l2v(curedge) = dwork(j); work(work_used(j)) = 0; work_used(j) = 0; dwork(j) = 0; end end % resize at the end l2i = l2i(1:curedge); l2j = l2j(1:curedge); l2v = l2v(1:curedge);
github
bill-codes/netalign-master
netalignmbp.m
.m
netalign-master/matlab/netalignmbp.m
4,716
utf_8
e294c5801bc3cd3fa0ee4deed6698ebf
function [mbest hista histb] = netalignmbp(S,w,a,b,li,lj,gamma,dtype,maxiter,verbose) % NETALIGNMBP Solve the network alignment problem with Belief Propagation % % This version of network alignment uses the matrix formulation of the % algorithm. % David F. Gleich, Ying Wang, and Mohsen Bayati % Copyright, Stanford University, 2007-2009 % Computational Approaches to Digital Stewardship if ~exist('a','var') || isempty(a), a=1; end if ~exist('b','var') || isempty(b), b=1; end if ~exist('gamma','var') || isempty(gamma), gamma=0.99; end if ~exist('dtype', 'var') || isempty(dtype), dtype=2; end if ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end if ~exist('verbose', 'var') || isempty(verbose), verbose=1; end nedges = length(li); nsquares = nnz(S)/2; m = max(li); n = max(lj); % the following is elegant, but inefficient :-( %Ar = sparse(li,1:nedges,1,m,nedges); [ari arj arv]=find(Ar'*Ar-speye(nedges)); %Ac = sparse(lj,1:nedges,1,n,nedges); [aci acj acv]=find(Ac'*Ac-speye(nedges)); % Initialize the messages y = zeros(nedges,1); z = y; Sk = 0*S; if dtype>1, d = y; end % needed for damping scheme % Initialize a few parameters damping = gamma; curdamp = 1; iter = 1; % Initialize history hista = zeros(maxiter,4); % history of messages from ei->a vertices histb = zeros(maxiter,4); % history of messages from ei->b vertices fbest = 0; fbestiter = 0; if verbose % print the header fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\n', ... 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ... 'obj_mb', 'wght_mb', 'card_mb', 'over_mb'); end % setup the matching problem once [rp ci ai tripi matn matm] = bipartite_matching_setup(... w,li,lj,m,n); mperm = tripi(tripi>0); while iter<=maxiter curdamp = damping*curdamp; Sknew = bound(Sk' + b*S,0,b); if dtype>1, dold=d; end d = sum(Sknew,2); ynew = a*w - max(0,implicit_maxprod(n,lj,z)) + d; znew = a*w - max(0,implicit_maxprod(m,li,y)) + d; % NOTE in comparison netalignbp, othersum isn't needed because othersum % of Sknew = d*S - Sknew Skt = diag(sparse(ynew+znew-a*w-d))*S-Sknew; if dtype==1 Sk = curdamp*Skt+ (1-curdamp)*Sk; y = curdamp*ynew+(1-curdamp)*y; z = curdamp*znew+(1-curdamp)*z; elseif dtype==2 prev = (y+z-a*w+dold); y = ynew+(1-curdamp)*prev; z = znew+(1-curdamp)*prev; clear prev; Sk = Skt + (1-curdamp)*(Sk+Sk'-b*S); elseif dtype==3 prev = (y+z-a*w+dold); y = curdamp*ynew+(1-curdamp)*prev; z = curdamp*znew+(1-curdamp)*prev; clear prev; Sk = curdamp*Skt + (1-curdamp)*(Sk+Sk'-b*S); end hista(iter,:) = round_messages(y,S,w,a,b,rp,ci,tripi,matn,matm,mperm); histb(iter,:) = round_messages(z,S,w,a,b,rp,ci,tripi,matn,matm,mperm); if hista(iter,1)>fbest fbestiter=iter; mbest=y; fbest=hista(iter,1); end if histb(iter,1)>fbest fbestiter=-iter; mbest=z; fbest=histb(iter,1); end if verbose if fbestiter==iter, bestchar='*a'; elseif fbestiter==-iter, bestchar='*b'; else bestchar=''; end fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\n', ... bestchar, iter, hista(iter,:), histb(iter,:)); end iter=iter+1; end end function S=bound(S,a,b) S=spfun(@(x) max(x+b,0) - max(x+a,0),S); end function y=maxprod(ai,aj,av,m,x) y=-inf*ones(m,1); for i=1:numel(ai), y(ai(i)) = max(y(ai(i)),av(i)*x(aj(i))); end end function y=implicit_maxprod(n,ai,x) % implicitly compute % Ai=sparse(ai,1:length(ai),1,n,length(z)) % A=Ar'*Ar - speye(length(z)) % maxprod(A,x) % which has a very nice structure if you look at the actual summation % definition. It is just the maximum value N = length(ai); y=-inf*ones(N,1); max1 = -inf*ones(n,1); max2 = -inf*ones(n,1); max1ind = zeros(n,1); for i=1:N if x(i)>max2(ai(i)) if x(i)>max1(ai(i)) max2(ai(i)) = max1(ai(i)); max1(ai(i)) = x(i); max1ind(ai(i)) = i; else max2(ai(i)) = x(i); end end end for i=1:N if i==max1ind(ai(i)) y(i)=max2(ai(i)); else y(i)=max1(ai(i)); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m,perm) ai=zeros(length(tripi),1); ai(tripi>0)=messages(perm); [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m); matchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*double(mi)))/2; f = alpha*matchweight + beta*overlap; info = [f matchweight cardinality overlap]; end
github
snipsco/kaldi-master
Generate_mcTrainData_cut.m
.m
kaldi-master/egs/reverb/s5/local/Generate_mcTrainData_cut.m
7,311
utf_8
f59dd892f0f8da04a515a2c58ff50a69
function Generate_mcTrainData_cut(WSJ_dir_name, save_dir) % % Input variables: % WSJ_dir_name: string name of user's clean wsjcam0 corpus directory % (*Directory structure for wsjcam0 corpushas to be kept as it is after obtaining it from LDC. % Otherwise this script does not work.) % % This function generates multi-condition traiing data % based on the following items: % 1. wsjcam0 corpus (distributed from the LDC) % 2. room impulse responses (ones under ./RIR/) % 3. noise (ones under ./NOISE/). % Generated data has the same directory structure as original wsjcam0 corpus. % if nargin<2 error('Usage: Generate_mcTrainData(WSJCAM0_data_path, save_dir) *Note that the input variable WSJCAM0_data_path should indicate the directory name of your clean WSJCAM0 corpus. '); end if exist([WSJ_dir_name,'/data/'])==0 error(['Could not find wsjcam0 corpus : Please confirm if ',WSJ_dir_name,' is a correct path to your clean WSJCAM0 corpus']); end if ~exist('save_dir', 'var') error('You have to set the save_dir variable in the code before running this script!') end display(['Name of directory for original wsjcam0: ',WSJ_dir_name]) display(['Name of directory to save generated multi-condition training data: ',save_dir]) unix(['chmod u+x sphere_to_wave.csh']); unix(['chmod u+x bin/*']); % Parameters related to acoustic conditions SNRdB=20; % List of WSJ speech data flist1='etc/audio_si_tr.lst'; % % List of RIRs % num_RIRvar=24; RIR_sim1='./RIR/RIR_SmallRoom1_near_AnglA.wav'; RIR_sim2='./RIR/RIR_SmallRoom1_near_AnglB.wav'; RIR_sim3='./RIR/RIR_SmallRoom1_far_AnglA.wav'; RIR_sim4='./RIR/RIR_SmallRoom1_far_AnglB.wav'; RIR_sim5='./RIR/RIR_MediumRoom1_near_AnglA.wav'; RIR_sim6='./RIR/RIR_MediumRoom1_near_AnglB.wav'; RIR_sim7='./RIR/RIR_MediumRoom1_far_AnglA.wav'; RIR_sim8='./RIR/RIR_MediumRoom1_far_AnglB.wav'; RIR_sim9='./RIR/RIR_LargeRoom1_near_AnglA.wav'; RIR_sim10='./RIR/RIR_LargeRoom1_near_AnglB.wav'; RIR_sim11='./RIR/RIR_LargeRoom1_far_AnglA.wav'; RIR_sim12='./RIR/RIR_LargeRoom1_far_AnglB.wav'; RIR_sim13='./RIR/RIR_SmallRoom2_near_AnglA.wav'; RIR_sim14='./RIR/RIR_SmallRoom2_near_AnglB.wav'; RIR_sim15='./RIR/RIR_SmallRoom2_far_AnglA.wav'; RIR_sim16='./RIR/RIR_SmallRoom2_far_AnglB.wav'; RIR_sim17='./RIR/RIR_MediumRoom2_near_AnglA.wav'; RIR_sim18='./RIR/RIR_MediumRoom2_near_AnglB.wav'; RIR_sim19='./RIR/RIR_MediumRoom2_far_AnglA.wav'; RIR_sim20='./RIR/RIR_MediumRoom2_far_AnglB.wav'; RIR_sim21='./RIR/RIR_LargeRoom2_near_AnglA.wav'; RIR_sim22='./RIR/RIR_LargeRoom2_near_AnglB.wav'; RIR_sim23='./RIR/RIR_LargeRoom2_far_AnglA.wav'; RIR_sim24='./RIR/RIR_LargeRoom2_far_AnglB.wav'; % % List of noise % num_NOISEvar=6; noise_sim1='./NOISE/Noise_SmallRoom1'; noise_sim2='./NOISE/Noise_MediumRoom1'; noise_sim3='./NOISE/Noise_LargeRoom1'; noise_sim4='./NOISE/Noise_SmallRoom2'; noise_sim5='./NOISE/Noise_MediumRoom2'; noise_sim6='./NOISE/Noise_LargeRoom2'; % % Start generating noisy reverberant data with creating new directories % fcount=1; rcount=1; ncount=1; if save_dir(end)=='/'; save_dir_tr=[save_dir,'data/mc_train/']; else save_dir_tr=[save_dir,'/data/mc_train/']; end mkdir([save_dir_tr]); %mkdir([save_dir,'/taskfiles/']) mic_idx=['A';'B';'C';'D';'E';'F';'G';'H']; prev_fname='dummy'; for nlist=1:1 % Open file list eval(['fid=fopen(flist',num2str(nlist),',''r'');']); while 1 % Set data file name fname=fgetl(fid); if ~ischar(fname); break; end idx1=find(fname=='/'); % Make directory if there isn't any if ~strcmp(prev_fname,fname(1:idx1(end))) mkdir([save_dir_tr fname(1:idx1(end))]) end prev_fname=fname(1:idx1(end)); % load (sphere format) speech signal x=read_sphere([WSJ_dir_name,'/data/', fname]); x=x/(2^15); % conversion from short-int to float % load RIR and noise for "THIS" utterance eval(['RIR=wavread(RIR_sim',num2str(rcount),');']); eval(['NOISE=wavread([noise_sim',num2str(ceil(rcount/4)),',''_',num2str(ncount),'.wav'']);']); % Generate 8ch noisy reverberant data y=gen_obs(x,RIR,NOISE,SNRdB); % cut to length of original signal y = y(1:size(x,2),:); % rotine to cyclicly switch RIRs and noise, utterance by utterance rcount=rcount+1; if rcount>num_RIRvar;rcount=1;ncount=ncount+1;end if ncount>10;ncount=1;end % save the data y=y/4; % common normalization to all the data to prevent clipping % denominator was decided experimentally for ch=1:8 eval(['wavwrite(y(:,',num2str(ch),'),16000,''',save_dir_tr fname,'_ch',num2str(ch),'.wav'');']); end display(['sentence ',num2str(fcount),' (out of 7861) finished! (Multi-condition training data)']) fcount=fcount+1; end end %%%% function [y]=gen_obs(x,RIR,NOISE,SNRdB) % function to generate noisy reverberant data x=x'; % calculate direct+early reflection signal for calculating SNR [val,delay]=max(RIR(:,1)); before_impulse=floor(16000*0.001); after_impulse=floor(16000*0.05); RIR_direct=RIR(delay-before_impulse:delay+after_impulse,1); direct_signal=fconv(x,RIR_direct); % obtain reverberant speech for ch=1:8 rev_y(:,ch)=fconv(x,RIR(:,ch)); end % normalize noise data according to the prefixed SNR value NOISE=NOISE(1:size(rev_y,1),:); NOISE_ref=NOISE(:,1); iPn = diag(1./mean(NOISE_ref.^2,1)); Px = diag(mean(direct_signal.^2,1)); Msnr = sqrt(10^(-SNRdB/10)*iPn*Px); scaled_NOISE = NOISE*Msnr; y = rev_y + scaled_NOISE; y = y(delay:end,:); %%%% function [y]=fconv(x, h) %FCONV Fast Convolution % [y] = FCONV(x, h) convolves x and h, and normalizes the output % to +-1. % % x = input vector % h = input vector % % See also CONV % % NOTES: % % 1) I have a short article explaining what a convolution is. It % is available at http://stevem.us/fconv.html. % % %Version 1.0 %Coded by: Stephen G. McGovern, 2003-2004. % %Copyright (c) 2003, Stephen McGovern %All rights reserved. % %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. Ly=length(x)+length(h)-1; % Ly2=pow2(nextpow2(Ly)); % Find smallest power of 2 that is > Ly X=fft(x, Ly2); % Fast Fourier transform H=fft(h, Ly2); % Fast Fourier transform Y=X.*H; % y=real(ifft(Y, Ly2)); % Inverse fast Fourier transform y=y(1:1:Ly); % Take just the first N elements
github
h-delgado/binary-key-diarizer-master
pdist22.m
.m
binary-key-diarizer-master/matlab/external/pdist22.m
5,461
utf_8
173103b09eefbe457c081a3d41cddd3d
% This function belongs to Piotr Dollar's Toolbox % http://vision.ucsd.edu/~pdollar/toolbox/doc/index.html % Please refer to the above web page for definitions and clarifications % % Calculates the distance between sets of vectors. % % Let X be an m-by-p matrix representing m points in p-dimensional space % and Y be an n-by-p matrix representing another set of points in the same % space. This function computes the m-by-n distance matrix D where D(i,j) % is the distance between X(i,:) and Y(j,:). This function has been % optimized where possible, with most of the distance computations % requiring few or no loops. % % The metric can be one of the following: % % 'euclidean' / 'sqeuclidean': % Euclidean / SQUARED Euclidean distance. Note that 'sqeuclidean' % is significantly faster. % % 'chisq' % The chi-squared distance between two vectors is defined as: % d(x,y) = sum( (xi-yi)^2 / (xi+yi) ) / 2; % The chi-squared distance is useful when comparing histograms. % % 'cosine' % Distance is defined as the cosine of the angle between two vectors. % % 'emd' % Earth Mover's Distance (EMD) between positive vectors (histograms). % Note for 1D, with all histograms having equal weight, there is a simple % closed form for the calculation of the EMD. The EMD between histograms % x and y is given by the sum(abs(cdf(x)-cdf(y))), where cdf is the % cumulative distribution function (computed simply by cumsum). % % 'L1' % The L1 distance between two vectors is defined as: sum(abs(x-y)); % % % USAGE % D = pdist2( X, Y, [metric] ) % % INPUTS % X - [m x p] matrix of m p-dimensional vectors % Y - [n x p] matrix of n p-dimensional vectors % metric - ['sqeuclidean'], 'chisq', 'cosine', 'emd', 'euclidean', 'L1' % % OUTPUTS % D - [m x n] distance matrix % % EXAMPLE % [X,IDX] = demoGenData(100,0,5,4,10,2,0); % D = pdist2( X, X, 'sqeuclidean' ); % distMatrixShow( D, IDX ); % % See also PDIST, DISTMATRIXSHOW % Piotr's Image&Video Toolbox Version 2.0 % Copyright (C) 2007 Piotr Dollar. [pdollar-at-caltech.edu] % Please email me if you find bugs, or have suggestions or questions! % Licensed under the Lesser GPL [see external/lgpl.txt] function D = pdist2( X, Y, metric ) if( nargin<3 || isempty(metric) ); metric=0; end; switch metric case {0,'sqeuclidean'} D = distEucSq( X, Y ); case 'euclidean' D = sqrt(distEucSq( X, Y )); case 'L1' D = distL1( X, Y ); case 'cosine' D = distCosine( X, Y ); case 'emd' D = distEmd( X, Y ); case 'chisq' D = distChiSq( X, Y ); otherwise error(['pdist2 - unknown metric: ' metric]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function D = distL1( X, Y ) m = size(X,1); n = size(Y,1); mOnes = ones(1,m); D = zeros(m,n); for i=1:n yi = Y(i,:); yi = yi( mOnes, : ); D(:,i) = sum( abs( X-yi),2 ); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function D = distCosine( X, Y ) if( ~isa(X,'double') || ~isa(Y,'double')) error( 'Inputs must be of type double'); end; p=size(X,2); XX = sqrt(sum(X.*X,2)); X = X ./ XX(:,ones(1,p)); YY = sqrt(sum(Y.*Y,2)); Y = Y ./ YY(:,ones(1,p)); D = 1 - X*Y'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function D = distEmd( X, Y ) Xcdf = cumsum(X,2); Ycdf = cumsum(Y,2); m = size(X,1); n = size(Y,1); mOnes = ones(1,m); D = zeros(m,n); for i=1:n ycdf = Ycdf(i,:); ycdfRep = ycdf( mOnes, : ); D(:,i) = sum(abs(Xcdf - ycdfRep),2); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function D = distChiSq( X, Y ) %%% supposedly it's possible to implement this without a loop! m = size(X,1); n = size(Y,1); mOnes = ones(1,m); D = zeros(m,n); for i=1:n yi = Y(i,:); yiRep = yi( mOnes, : ); s = yiRep + X; d = yiRep - X; D(:,i) = sum( d.^2 ./ (s+eps), 2 ); end D = D/2; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function D = distEucSq( X, Y ) %if( ~isa(X,'double') || ~isa(Y,'double')) % error( 'Inputs must be of type double'); end; m = size(X,1); n = size(Y,1); %Yt = Y'; XX = sum(X.*X,2); YY = sum(Y'.*Y',1); D = XX(:,ones(1,n)) + YY(ones(1,m),:) - 2*X*Y'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function D = distEucSq( X, Y ) %%%% code from Charles Elkan with variables renamed % m = size(X,1); n = size(Y,1); % D = sum(X.^2, 2) * ones(1,n) + ones(m,1) * sum(Y.^2, 2)' - 2.*X*Y'; %%% LOOP METHOD - SLOW % [m p] = size(X); % [n p] = size(Y); % % D = zeros(m,n); % onesM = ones(m,1); % for i=1:n % y = Y(i,:); % d = X - y(onesM,:); % D(:,i) = sum( d.*d, 2 ); % end %%% PARALLEL METHOD THAT IS SUPER SLOW (slower then loop)! % % From "MATLAB array manipulation tips and tricks" by Peter J. Acklam % Xb = permute(X, [1 3 2]); % Yb = permute(Y, [3 1 2]); % D = sum( (Xb(:,ones(1,n),:) - Yb(ones(1,m),:,:)).^2, 3); %%% USELESS FOR EVEN VERY LARGE ARRAYS X=16000x1000!! and Y=100x1000 % call recursively to save memory % if( (m+n)*p > 10^5 && (m>1 || n>1)) % if( m>n ) % X1 = X(1:floor(end/2),:); % X2 = X((floor(end/2)+1):end,:); % D1 = distEucSq( X1, Y ); % D2 = distEucSq( X2, Y ); % D = cat( 1, D1, D2 ); % else % Y1 = Y(1:floor(end/2),:); % Y2 = Y((floor(end/2)+1):end,:); % D1 = distEucSq( X, Y1 ); % D2 = distEucSq( X, Y2 ); % D = cat( 2, D1, D2 ); % end % return; % end
github
KGuo26/WADG_Matlab-master
bern_sem_basis.m
.m
WADG_Matlab-master/bern_sem_basis.m
1,476
utf_8
a00141b6425a6b137bfc093d5ed345aa
% wedge basis % function V = bern_sem_basis(N,r,s,t) % Vtri = bern_tri(N,r(:),s(:)); % % [r2D s2D] = Nodes2D(N); [r2D s2D] = xytors(r2D,s2D); % % VWB = Vandermonde2D(N,r2D,s2D); Vtri = Vandermonde2D(N,r(:),s(:))/VWB; % r1D = JacobiGL(0,0,N); % VSEM = Vandermonde1D(N,r1D(:)); % V1D = Vandermonde1D(N,t(:))/VSEM; % sem in vertical direction % % Np = (N+1)*(N+2)/2; % % sk = 1; % for i = 1:N+1 % for j = 1:Np % V(:,sk) = Vtri(:,j).*V1D(:,i); % sk = sk + 1; % end % end function [V Vr Vs Vt V1 V2 V3] = bern_sem_basis(N,r,s,t) % [Vtri Vrtri Vstri V1tri V2tri V3tri] = bern_tri(N,r(:),s(:)); [r2D s2D] = Nodes2D(N); [r2D s2D] = xytors(r2D,s2D); VWB = Vandermonde2D(N,r2D,s2D); Vtri = Vandermonde2D(N,r(:),s(:))/VWB; [Vrtri Vstri] = GradVandermonde2D(N,r(:),s(:)); Vrtri = Vrtri/VWB; Vstri = Vstri/VWB; V1tri = Vrtri*0; V2tri = Vrtri*0; V3tri = Vrtri*0; % dummy arrays r1D = JacobiGL(0,0,N); VSEM = Vandermonde1D(N,r1D(:)); V1D = Vandermonde1D(N,t(:))/VSEM; % sem in vertical direction Vt1D = GradVandermonde1D(N,t(:))/VSEM; % sem in vertical direction Nptri = (N+1)*(N+2)/2; sk = 1; for i = 1:N+1 for j = 1:Nptri V(:,sk) = Vtri(:,j).*V1D(:,i); Vr(:,sk) = Vrtri(:,j).*V1D(:,i); Vs(:,sk) = Vstri(:,j).*V1D(:,i); Vt(:,sk) = Vtri(:,j).*Vt1D(:,i); V1(:,sk) = V1tri(:,j).*V1D(:,i); V2(:,sk) = V2tri(:,j).*V1D(:,i); V3(:,sk) = V3tri(:,j).*V1D(:,i); sk = sk + 1; end end
github
KGuo26/WADG_Matlab-master
bern_basis_1D.m
.m
WADG_Matlab-master/bern_basis_1D.m
424
utf_8
d9d840acea7aa008762de1bb0bfe1d93
function [V Vr] = bern_basis_1D(N,r) r = (1+r)/2; % convert to unit for i = 0:N V(:,i+1) = bern_1D(N,i,r); Vr(:,i+1) = d_bern(N,i,r)*.5; % change of vars end function bi = bern_1D(N,i,r) bi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i); function dbi = d_bern(N,i,r) if (i==0) dbi = -N*(1-r).^(N-1); elseif (i==N) dbi = N*(r.^(N-1)); else dbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r); end
github
KGuo26/WADG_Matlab-master
bern_quad.m
.m
WADG_Matlab-master/bern_quad.m
689
utf_8
355d83ac78285e23030c96d0fadf8fcc
function [V Vr Vs] = bern_quad(N,r,s) r = (1+r)/2; % convert to unit s = (1+s)/2; % convert to unit V = zeros(length(r),(N+1)^2); Vr = zeros(length(r),(N+1)^2); Vs = zeros(length(r),(N+1)^2); sk = 1; for j = 0:N for i = 0:N V(:,sk) = bern_1D(N,i,r).*bern_1D(N,j,s); Vr(:,sk) = .5*d_bern_1D(N,i,r).*bern_1D(N,j,s); Vs(:,sk) = .5*bern_1D(N,i,r).*d_bern_1D(N,j,s); sk = sk + 1; end end function bi = bern_1D(N,i,r) bi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i); function dbi = d_bern_1D(N,i,r) if (i==0) dbi = -N*(1-r).^(N-1); elseif (i==N) dbi = N*(r.^(N-1)); else dbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r); end
github
KGuo26/WADG_Matlab-master
bern_basis_tet.m
.m
WADG_Matlab-master/bern_basis_tet.m
1,786
utf_8
402f402665ab18ed94d19eb13672619c
% V = VDM. Vrst = deriv matrices. V1-4 barycentric derivs. ids = % permutation to match equispaced node ordering on tet. function [V, Vr, Vs, Vt, V1, V2, V3, V4, id] = bern_basis_tet(N,r,s,t) %[L1 L2 L3 L4] = rsttobary(r,s,t); L1 = -(1+r+s+t)/2; L2 = (1+r)/2; L3 = (1+s)/2; L4 = (1+t)/2; dL1r = -.5; dL2r = .5; dL3r = 0; dL4r = 0; dL1s = -.5; dL2s = 0; dL3s = .5; dL4s = 0; dL1t = -.5; dL2t = 0; dL3t = 0; dL4t = .5; sk = 1; for l = 0:N for k = 0:N-l for j = 0:N-k-l; i = N-j-k-l; C=factorial(N)/(factorial(i)*factorial(j)*factorial(k)*factorial(l)); % C = 1; V(:,sk) = C*(L1.^i).*(L2.^j).*(L3.^k).*(L4.^l); dL1 = C*i*(L1.^(i-1)).*(L2.^j).*(L3.^k).*(L4.^l); dL2 = C*j*(L1.^(i)).*(L2.^(j-1)).*(L3.^k).*(L4.^l); dL3 = C*k*(L1.^(i)).*(L2.^j).*(L3.^(k-1)).*(L4.^l); dL4 = C*l*(L1.^(i)).*(L2.^j).*(L3.^k).*(L4.^(l-1)); if i==0 dL1 = zeros(size(dL1)); end if j==0 dL2 = zeros(size(dL1)); end if k ==0 dL3 = zeros(size(dL1)); end if l ==0 dL4 = zeros(size(dL1)); end Vr(:,sk) = dL1.*dL1r + dL2.*dL2r + dL3.*dL3r + dL4.*dL4r; Vs(:,sk) = dL1.*dL1s + dL2.*dL2s + dL3.*dL3s + dL4.*dL4s; Vt(:,sk) = dL1.*dL1t + dL2.*dL2t + dL3.*dL3t + dL4.*dL4t; V1(:,sk) = dL1; V2(:,sk) = dL2; V3(:,sk) = dL3; V4(:,sk) = dL4; sk = sk + 1; end end end function bi = bern(N,i,r) bi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i); function dbi = d_bern(N,i,r) dbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r);
github
KGuo26/WADG_Matlab-master
Wave3D.m
.m
WADG_Matlab-master/Wave3D.m
4,005
utf_8
61a2d10ebd5610a1443301f0f99b2ba0
clear Globals3D; N = 4; FinalTime = 1; cfun = @(x,y,z) ones(size(x)); %cfun = @(x,y,z) 1 + 0.5*sin(pi*x).*sin(pi*y).*sin(pi*z); % smooth velocity %cfun = @(x,y,z) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity %pfun = @(x,y,z,t) cos(pi*x).*cos(pi*y).*cos(pi*z).*cos(sqrt(3)*pi*t); pfun = @(x,y,z,t) sin(pi*x).*sin(pi*y).*sin(pi*z).*cos(pi*t); ufun = @(x,y,z,t) -cos(pi*x).*sin(pi*y).*sin(pi*z).*sin(pi*t); vfun = @(x,y,z,t) -sin(pi*x).*cos(pi*y).*sin(pi*z).*sin(pi*t); wfun = @(x,y,z,t) -sin(pi*x).*sin(pi*y).*cos(pi*z).*sin(pi*t); %ffun = @(x,y,z,t) sqrt(3)*pi*(1-1./cfun(x,y,z)).*cos(pi*x).*cos(pi*y).*cos(pi*z).*sin(sqrt(3)*pi*t); ffun = @(x,y,z,t) pi*2*sin(pi*x).*sin(pi*y).*sin(pi*z).*sin(pi*t); %generate 3D mesh [Nv, VX, VY, VZ, K, EToV] = MeshReaderGmsh3D('cube2.msh'); StartUp3D; Dr(abs(Dr)<1e-8) = 0; Nq = 2*N+1; [rq sq tq wq] = tet_cubature(Nq); % integrate u*v*c Vq = Vandermonde3D(N,rq,sq,tq)/V; xq = Vq*x; yq = Vq*y; zq=Vq*z; Pq=V*V'*Vq'*diag(wq); Cq = cfun(xq,yq,zq); Lift3D(N, r, s, t); % %% Adptive m on each element % VMq = Vandermonde3D(M,rq,sq,tq); % CqM = VMq*VMq'*diag(wq)*Cq; %% initial condition p = pfun(x,y,z,0); u = ufun(x,y,z,0); v = vfun(x,y,z,0); w = wfun(x,y,z,0); % p = pfun(x,y,z,0); % u = zeros(Np,K); % v = zeros(Np,K); % w = zeros(Np,K); %% time = 0; % Runge-Kutta residual storage resu = zeros(Np,K); resv = zeros(Np,K); resw = zeros(Np,K); resp = zeros(Np,K); CN = (N+1)*(N+2)*(N+3)/6; % trace inequality constant CNh = max(CN*max(Fscale(:))); dt = 2/CNh; %dt = 0.00390625; %coincide with the time step in occa % outer time step loop tstep = 0; while (time<FinalTime) if(time+dt>FinalTime), dt = FinalTime-time; end for INTRK = 1:5 timelocal = time + rk4c(INTRK)*dt; f=ffun(x,y,z,timelocal); [rhsp, rhsu, rhsv, rhsw] = acousticsRHS3D_WADG(p,u,v,w,f); % initiate and increment Runge-Kutta residuals resp = rk4a(INTRK)*resp + dt*rhsp; resu = rk4a(INTRK)*resu + dt*rhsu; resv = rk4a(INTRK)*resv + dt*rhsv; resw = rk4a(INTRK)*resw + dt*rhsw; % update fields u = u+rk4b(INTRK)*resu; v = v+rk4b(INTRK)*resv; w = w+rk4b(INTRK)*resw; p = p+rk4b(INTRK)*resp; end time = time+dt; tstep = tstep+1; end p_exact = pfun(x,y,z,FinalTime); p_exact_quadrature = pfun(xq,yq,zq,FinalTime); p_quadrature = Vq * p; [d1,d2]=size(p_quadrature); error_accumulation = 0; for j1=1:d2 for j2=1:d1 err = p_quadrature(j2,j1)-p_exact_quadrature(j2,j1); error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1); end end error_l2 = sqrt(error_accumulation) %error_fro = norm(p-p_exact,'fro'); function [rhsp, rhsu, rhsv, rhsw] = acousticsRHS3D_WADG(p,u,v,w,f) Globals3D; % Define field differences at faces dp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM); du = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM); dv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM); dw = zeros(Nfp*Nfaces,K); dw(:) = w(vmapP)-w(vmapM); % evaluate upwind fluxes ndotdU = nx.*du + ny.*dv + nz.*dw; % % Impose reflective boundary conditions (p+ = -p-) % ndotdU(mapB) = 0; % dp(mapB) = -2*p(vmapB); % Impose Dirichlet BCs ndotdU(mapB) = 0; p(vmapB) = 0; dp(mapB) = 0; tau = 1; fluxp = tau*dp - ndotdU; fluxu = (tau*ndotdU - dp).*nx; fluxv = (tau*ndotdU - dp).*ny; fluxw = (tau*ndotdU - dp).*nz; pr = Dr*p; ps = Ds*p; pt = Dt*p; dpdx = rx.*pr + sx.*ps + tx.*pt; dpdy = ry.*pr + sy.*ps + ty.*pt; dpdz = rz.*pr + sz.*ps + tz.*pt; divU = Dr*(u.*rx + v.*ry + w.*rz) + Ds*(u.*sx + v.*sy + w.*sz)+ Dt*(u.*tx + v.*ty + w.*tz); % compute right hand sides of the PDE's rhsp = -divU + f + LIFT*(Fscale.*fluxp)/2.0; rhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0; rhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0; rhsw = -dpdz + LIFT*(Fscale.*fluxw)/2.0; rhsp = Pq*(Cq.*(Vq*rhsp)); return; end
github
KGuo26/WADG_Matlab-master
bern_hex.m
.m
WADG_Matlab-master/bern_hex.m
930
utf_8
c1ba4aade744a74da97433f578142f21
function [V Vr Vs Vt] = bern_hex(N,r,s,t) r = (1+r)/2; % convert to unit s = (1+s)/2; % convert to unit t = (1+t)/2; % convert to unit Np = (N+1)^3; V = zeros(length(r),Np); Vr = zeros(length(r),Np); Vs = zeros(length(r),Np); Vt = zeros(length(r),Np); sk = 1; for k = 0:N for j = 0:N for i = 0:N V(:,sk) = bern_1D(N,i,r).*bern_1D(N,j,s).*bern_1D(N,k,t); Vr(:,sk) = .5*d_bern_1D(N,i,r).*bern_1D(N,j,s).*bern_1D(N,k,t); Vs(:,sk) = .5*bern_1D(N,i,r).*d_bern_1D(N,j,s).*bern_1D(N,k,t); Vt(:,sk) = .5*bern_1D(N,i,r).*bern_1D(N,j,s).*d_bern_1D(N,k,t); sk = sk + 1; end end end function bi = bern_1D(N,i,r) bi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i); function dbi = d_bern_1D(N,i,r) if (i==0) dbi = -N*(1-r).^(N-1); elseif (i==N) dbi = N*(r.^(N-1)); else dbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r); end
github
KGuo26/WADG_Matlab-master
bern_tet.m
.m
WADG_Matlab-master/bern_tet.m
2,132
utf_8
4dc141800a89b218f1b7dff33be86eef
% V = VDM. Vrst = deriv matrices. V1-4 barycentric derivs. ids = % permutation to match equispaced node ordering on tet. % function [V Vr Vs Vt V1 V2 V3 V4 id] = bern_basis_tet(N,r,s,t) % % % use equivalence between W&B and equispaced nodes - get ordering % [re se te] = EquiNodes3D(N); % Ve = bern_tet(N,re,se,te); % for i = 1:size(Ve,2) % [val iid] = max(Ve(:,i)); % id(i) = iid; % end % % [V Vr Vs Vt V1 V2 V3 V4] = bern_tet(N,r,s,t); % V = V(:,id); % Vr = Vr(:,id); % Vs = Vs(:,id); % Vt = Vt(:,id); % V1 = V1(:,id); % V2 = V2(:,id); % V3 = V3(:,id); % V4 = V4(:,id); function [V Vr Vs Vt V1 V2 V3 V4] = bern_tet(N,r,s,t) % [L1 L2 L3 L4] = rsttobary(r,s,t); L1 = -(1+r+s+t)/2; L2 = (1+r)/2; L3 = (1+s)/2; L4 = (1+t)/2; dL1r = -.5; dL2r = .5; dL3r = 0; dL4r = 0; dL1s = -.5; dL2s = 0; dL3s = .5; dL4s = 0; dL1t = -.5; dL2t = 0; dL3t = 0; dL4t = .5; sk = 1; % for i = 0:N % for j = 0:N-i % for k = 0:N-i-j % l = N-i-j-k; for l = 0:N for k = 0:N-l for j = 0:N-l-k i = N-j-k-l; C=factorial(N)/(factorial(i)*factorial(j)*factorial(k)*factorial(l)); V(:,sk) = C*(L1.^i).*(L2.^j).*(L3.^k).*(L4.^l); dL1 = C*i*(L1.^(i-1)).*(L2.^j).*(L3.^k).*(L4.^l); dL2 = C*j*(L1.^(i)).*(L2.^(j-1)).*(L3.^k).*(L4.^l); dL3 = C*k*(L1.^(i)).*(L2.^j).*(L3.^(k-1)).*(L4.^l); dL4 = C*l*(L1.^(i)).*(L2.^j).*(L3.^k).*(L4.^(l-1)); if i==0 dL1 = zeros(size(dL1)); end if j==0 dL2 = zeros(size(dL1)); end if k ==0 dL3 = zeros(size(dL1)); end if l ==0 dL4 = zeros(size(dL1)); end Vr(:,sk) = dL1.*dL1r + dL2.*dL2r + dL3.*dL3r + dL4.*dL4r; Vs(:,sk) = dL1.*dL1s + dL2.*dL2s + dL3.*dL3s + dL4.*dL4s; Vt(:,sk) = dL1.*dL1t + dL2.*dL2t + dL3.*dL3t + dL4.*dL4t; V1(:,sk) = dL1; V2(:,sk) = dL2; V3(:,sk) = dL3; V4(:,sk) = dL4; sk = sk + 1; end end end
github
KGuo26/WADG_Matlab-master
Wave2D_mesh_fullquadrature.m
.m
WADG_Matlab-master/Wave2D_mesh_fullquadrature.m
4,216
utf_8
8353d0375b964df4092a4909937506a5
clear Globals2D kd=[4 8 16 32]; h=2./kd; N = 4; M = 1; for i = 1:length(kd) K1D = kd(i); FinalTime = 1.0; [Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D); StartUp2D; %% Set up wavespeed function %cfun = @(x,y) ones(size(x)); cfun = @(x,y) 1+ sin(pi*x).*sin(pi*y); % smooth velocity %cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity %% generate quadrature points Nq = 2*N+1; [rq sq wq] = Cubature2D(Nq); % integrate u*v*c Vq = Vandermonde2D(N,rq,sq)/V; xq = Vq*x; yq = Vq*y; %% construct the projection matrix for nodal basis Pq Pq = V*V'*Vq'*diag(wq); %% construct matrix Cq Cq = cfun(xq,yq); %% construct the projection matrix for cfun to degree M VMq = Vandermonde2D(M,rq,sq); CqM = VMq*VMq'*diag(wq)*Cq; %% initial condition x0 = 0; y0 = .1; p = exp(-25*((x-x0).^2 + (y-y0).^2)); u = zeros(Np, K); v=zeros(Np,K); p_M = p; u_M = u; v_M = v; time = 0; %% Runge-Kutta residual storage resu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K); resu_M = resu; resv_M = resv; resp_M = resp; %% compute time step size CN = (N+1)*(N+2)/2; % trace inequality constant CNh = max(CN*max(Fscale(:))); dt = 2/CNh; %% outer time step loop tstep = 0; while (time<FinalTime) if(time+dt>FinalTime), dt = FinalTime-time; end for INTRK = 1:5 timelocal = time + rk4c(INTRK)*dt; [rhsp, rhsu, rhsv] = acousticsRHS2D_fullWADG(p,u,v); [rhsp_M, rhsu_M, rhsv_M] = acousticsRHS2D_adaptiveWADG(p_M,u_M,v_M); % initiate and increment Runge-Kutta residuals resp = rk4a(INTRK)*resp + dt*rhsp; resu = rk4a(INTRK)*resu + dt*rhsu; resv = rk4a(INTRK)*resv + dt*rhsv; resp_M = rk4a(INTRK)*resp_M + dt*rhsp_M; resu_M = rk4a(INTRK)*resu_M + dt*rhsu_M; resv_M = rk4a(INTRK)*resv_M + dt*rhsv_M; % update fields u = u+rk4b(INTRK)*resu; v = v+rk4b(INTRK)*resv; p = p+rk4b(INTRK)*resp; u_M = u_M + rk4b(INTRK)*resu_M; v_M = v_M + rk4b(INTRK)*resv_M; p_M = p_M + rk4b(INTRK)*resp_M; end % Increment time time = time+dt; tstep = tstep+1; end p_quadrature = Vq * p; p_M_quadrature = Vq * p_M; [d1,d2]=size(p_quadrature); error_accumulation = 0; for j1=1:d2 for j2=1:d1 err = p_quadrature(j2,j1)-p_M_quadrature(j2,j1); error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1); end end error_l2(i) = sqrt(error_accumulation); error_fro(i) = norm(p-p_M,'fro'); end function [rhsp, rhsu, rhsv] = acousticsRHS2D_adaptiveWADG(p,u,v) Globals2D; % Define field differences at faces dp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM); du = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM); dv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM); % evaluate upwind fluxes ndotdU = nx.*du + ny.*dv; % Impose reflective boundary conditions (p+ = -p-) ndotdU(mapB) = 0; dp(mapB) = -2*p(vmapB); tau = 1; fluxp = tau*dp - ndotdU; fluxu = (tau*ndotdU - dp).*nx; fluxv = (tau*ndotdU - dp).*ny; pr = Dr*p; ps = Ds*p; dpdx = rx.*pr + sx.*ps; dpdy = ry.*pr + sy.*ps; divU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy); % compute right hand sides of the PDE's rhsp = -divU + LIFT*(Fscale.*fluxp)/2.0; rhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0; rhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0; rhsp = Pq*(CqM.*(Vq*rhsp)); return; end function [rhsp, rhsu, rhsv] = acousticsRHS2D_fullWADG(p,u,v) Globals2D; % Define field differences at faces dp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM); du = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM); dv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM); % evaluate upwind fluxes ndotdU = nx.*du + ny.*dv; % Impose reflective boundary conditions (p+ = -p-) ndotdU(mapB) = 0; dp(mapB) = -2*p(vmapB); tau = 1; fluxp = tau*dp - ndotdU; fluxu = (tau*ndotdU - dp).*nx; fluxv = (tau*ndotdU - dp).*ny; pr = Dr*p; ps = Ds*p; dpdx = rx.*pr + sx.*ps; dpdy = ry.*pr + sy.*ps; divU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy); % compute right hand sides of the PDE's rhsp = -divU + LIFT*(Fscale.*fluxp)/2.0; rhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0; rhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0; rhsp = Pq*(Cq.*(Vq*rhsp)); return; end
github
KGuo26/WADG_Matlab-master
Wave2D_k_manufactured.m
.m
WADG_Matlab-master/Wave2D_k_manufactured.m
3,325
utf_8
0034b8526d028e8da590042ba197b35b
clear Globals2D k=[1 4 8 16] N = 4; M = 1 for i = 1:length(k) K1D = 32; FinalTime = 1.0; [Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D); StartUp2D; %% Set up wavespeed function %cfun = @(x,y) ones(size(x)); cfun = @(x,y) 1+ 0.5*sin(pi*x).*sin(pi*y); % smooth velocity %cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity %% Set periodic manufactured solution pfun = @(x,y,t) sin(k(i)*pi*x).*sin(k(i)*pi*y).*cos(k(i)*pi*t); ufun = @(x,y,t) -cos(k(i)*pi*x).*sin(k(i)*pi*y).*sin(k(i)*pi*t); vfun = @(x,y,t) -sin(k(i)*pi*x).*cos(k(i)*pi*y).*sin(k(i)*pi*t); ffun = @(x,y,t) k(i)*pi*(-1./(cfun(x,y))+2).*sin(k(i)*pi*x).*sin(k(i)*pi*y).*sin(k(i)*pi*t); %% generate quadrature points Nq = 2*N+1; [rq sq wq] = Cubature2D(Nq); % integrate u*v*c Vq = Vandermonde2D(N,rq,sq)/V; xq = Vq*x; yq = Vq*y; %% construct the projection matrix for nodal basis Pq Pq = V*V'*Vq'*diag(wq); %% construct matrix Cq Cq = cfun(xq,yq); %% construct the projection matrix for cfun to degree M VMq = Vandermonde2D(M,rq,sq); CqM = VMq*VMq'*diag(wq)*Cq; %% initial condition p = pfun(x,y,0); u = ufun(x,y,0); v = vfun(x,y,0); time = 0; %% Runge-Kutta residual storage resu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K); %% compute time step size CN = (N+1)*(N+2)/2; % trace inequality constant CNh = max(CN*max(Fscale(:))); dt = 2/CNh; %% outer time step loop tstep = 0; while (time<FinalTime) if(time+dt>FinalTime), dt = FinalTime-time; end for INTRK = 1:5 timelocal = time + rk4c(INTRK)*dt; f=ffun(x,y,timelocal); [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f); % initiate and increment Runge-Kutta residuals resp = rk4a(INTRK)*resp + dt*rhsp; resu = rk4a(INTRK)*resu + dt*rhsu; resv = rk4a(INTRK)*resv + dt*rhsv; % update fields u = u+rk4b(INTRK)*resu; v = v+rk4b(INTRK)*resv; p = p+rk4b(INTRK)*resp; end % Increment time time = time+dt; tstep = tstep+1; end p_exact = pfun(x,y,FinalTime); p_exact_quadrature = pfun(xq,yq,FinalTime); p_quadrature = Vq * p; [d1,d2]=size(p_quadrature); error_accumulation = 0; for j1=1:d2 for j2=1:d1 err = p_quadrature(j2,j1)-p_exact_quadrature(j2,j1); error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1); end end error_l2(i) = sqrt(error_accumulation); error_fro(i) = norm(p-p_exact,'fro'); end function [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f) Globals2D; % Define field differences at faces dp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM); du = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM); dv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM); % evaluate upwind fluxes ndotdU = nx.*du + ny.*dv; % Impose reflective boundary conditions (p+ = -p-) ndotdU(mapB) = 0; dp(mapB) = -2*p(vmapB); tau = 1; fluxp = tau*dp - ndotdU; fluxu = (tau*ndotdU - dp).*nx; fluxv = (tau*ndotdU - dp).*ny; pr = Dr*p; ps = Ds*p; dpdx = rx.*pr + sx.*ps; dpdy = ry.*pr + sy.*ps; divU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy); % compute right hand sides of the PDE's rhsp = -divU + f + LIFT*(Fscale.*fluxp)/2.0; rhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0; rhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0; rhsp = Pq*(CqM.*(Vq*rhsp)); return; end
github
KGuo26/WADG_Matlab-master
Wave2D_mesh_manufactured.m
.m
WADG_Matlab-master/Wave2D_mesh_manufactured.m
3,326
utf_8
322817f72f150c1acafea4eaefbd319b
clear Globals2D kd=[64] h=2./kd N = 4; M = 1; k = 16 for i = 1:length(kd) K1D = kd(i); FinalTime = 1.5; [Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D); StartUp2D; %% Set up wavespeed function %cfun = @(x,y) ones(size(x)); cfun = @(x,y) 1+ 0.5*sin(pi*x).*sin(pi*y); % smooth velocity %cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity %% Set periodic manufactured solution pfun = @(x,y,t) sin(k*pi*x).*sin(k*pi*y).*cos(k*pi*t); ufun = @(x,y,t) -cos(k*pi*x).*sin(k*pi*y).*sin(k*pi*t); vfun = @(x,y,t) -sin(k*pi*x).*cos(k*pi*y).*sin(k*pi*t); ffun = @(x,y,t) k*pi*(-1./(cfun(x,y))+2).*sin(k*pi*x).*sin(k*pi*y).*sin(k*pi*t); %% generate quadrature points Nq = 2*N+1; [rq sq wq] = Cubature2D(Nq); % integrate u*v*c Vq = Vandermonde2D(N,rq,sq)/V; xq = Vq*x; yq = Vq*y; %% construct the projection matrix for nodal basis Pq Pq = V*V'*Vq'*diag(wq); %% construct matrix Cq Cq = cfun(xq,yq); %% construct the projection matrix for cfun to degree M VMq = Vandermonde2D(M,rq,sq); CqM = VMq*VMq'*diag(wq)*Cq; %% initial condition p = pfun(x,y,0); u = ufun(x,y,0); v = vfun(x,y,0); time = 0; %% Runge-Kutta residual storage resu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K); %% compute time step size CN = (N+1)*(N+2)/2; % trace inequality constant CNh = max(CN*max(Fscale(:))); dt = 2/CNh; %% outer time step loop tstep = 0; while (time<FinalTime) if(time+dt>FinalTime), dt = FinalTime-time; end for INTRK = 1:5 timelocal = time + rk4c(INTRK)*dt; f=ffun(x,y,timelocal); [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f); % initiate and increment Runge-Kutta residuals resp = rk4a(INTRK)*resp + dt*rhsp; resu = rk4a(INTRK)*resu + dt*rhsu; resv = rk4a(INTRK)*resv + dt*rhsv; % update fields u = u+rk4b(INTRK)*resu; v = v+rk4b(INTRK)*resv; p = p+rk4b(INTRK)*resp; end % Increment time time = time+dt; tstep = tstep+1; end p_exact = pfun(x,y,FinalTime); p_exact_quadrature = pfun(xq,yq,FinalTime); p_quadrature = Vq * p; [d1,d2]=size(p_quadrature); error_accumulation = 0; for j1=1:d2 for j2=1:d1 err = p_quadrature(j2,j1)-p_exact_quadrature(j2,j1); error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1); end end error_l2(i) = sqrt(error_accumulation); error_fro(i) = norm(p-p_exact,'fro'); end function [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f) Globals2D; % Define field differences at faces dp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM); du = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM); dv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM); % evaluate upwind fluxes ndotdU = nx.*du + ny.*dv; % Impose reflective boundary conditions (p+ = -p-) ndotdU(mapB) = 0; dp(mapB) = -2*p(vmapB); tau = 1; fluxp = tau*dp - ndotdU; fluxu = (tau*ndotdU - dp).*nx; fluxv = (tau*ndotdU - dp).*ny; pr = Dr*p; ps = Ds*p; dpdx = rx.*pr + sx.*ps; dpdy = ry.*pr + sy.*ps; divU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy); % compute right hand sides of the PDE's rhsp = -divU + f + LIFT*(Fscale.*fluxp)/2.0; rhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0; rhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0; rhsp = Pq*(CqM.*(Vq*rhsp)); return; end
github
KGuo26/WADG_Matlab-master
bern_tri.m
.m
WADG_Matlab-master/bern_tri.m
1,444
utf_8
3a04a72548c550e48525a3a60987827c
% function [V Vr Vs V1 V2 V3 id] = bern_tri(N,r,s) % % % use equivalence between W&B and equispaced nodes - get ordering % [re se] = EquiNodes2D(N); [re se] = xytors(re,se); % Ve = bern_tri_b(N,re,se); % for i = 1:size(Ve,2) % [val iid] = max(Ve(:,i)); % id(i) = iid; % % id(i) = i; % end % % [V Vr Vs V1 V2 V3] = bern_tri_b(N,r,s); % V = V(:,id); % Vr = Vr(:,id); Vs = Vs(:,id); % V1 = V1(:,id); V2 = V2(:,id); V3 = V3(:,id); function [V Vr Vs VL1 VL2 VL3] = bern_tri(N,r,s) % barycentric version L1 = -(r+s)/2; L2 = (1+r)/2; L3 = (1+s)/2; dL1r = -.5; dL2r = .5; dL3r = 0; dL1s = -.5; dL2s = 0; dL3s = .5; sk = 1; % for i = 0:N % for j = 0:N-i % k = N-i-j; for k = 0:N for j = 0:N-k i = N-j-k; C=factorial(N)/(factorial(i)*factorial(j)*factorial(k)); V(:,sk) = C*(L1.^i).*(L2.^j).*(L3.^k); dL1 = C*i*(L1.^(i-1)).*(L2.^j).*(L3.^k); dL2 = C*j*(L1.^(i)).*(L2.^(j-1)).*(L3.^k); dL3 = C*k*(L1.^(i)).*(L2.^j).*(L3.^(k-1)); if i==0 dL1 = zeros(size(dL1)); end if j==0 dL2 = zeros(size(dL2)); end if k == 0 dL3 = zeros(size(dL3)); end Vr(:,sk) = dL1.*dL1r + dL2.*dL2r + dL3.*dL3r; Vs(:,sk) = dL1.*dL1s + dL2.*dL2s + dL3.*dL3s; VL1(:,sk) = dL1; VL2(:,sk) = dL2; VL3(:,sk) = dL3; sk = sk + 1; end end return
github
KGuo26/WADG_Matlab-master
Wave2D_modified.m
.m
WADG_Matlab-master/Wave2D_modified.m
2,725
utf_8
16165584c54009cc2f3f03cf162a8f73
Globals2D N = 4; K1D = 16; c_flag = 0; FinalTime = 0.5; %cfun = @(x,y) ones(size(x)); cfun = @(x,y) 1 + sin(pi*x).*sin(pi*y); % smooth velocity %cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity [Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D); StartUp2D; [rp sp] = EquiNodes2D(50); [rp sp] = xytors(rp,sp); Vp = Vandermonde2D(N,rp,sp)/V; xp = Vp*x; yp = Vp*y; Nq = 2*N+1; [rq sq wq] = Cubature2D(Nq); % integrate u*v*c Vq = Vandermonde2D(N,rq,sq)/V; xq = Vq*x; yq = Vq*y; %construct Pq Pq=V*V'*Vq'*diag(wq); %Pq is the projection matrix for Nodal Basis %construct the matrix C Cq=cfun(xq,yq); %% initial condition x0 = 0; y0 = .1; p = exp(-25*((x-x0).^2 + (y-y0).^2)); u = zeros(Np, K); v=zeros(Np,K); %% time = 0; % Runge-Kutta residual storage resu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K); % compute time step size CN = (N+1)*(N+2)/2; % trace inequality constant CNh = max(CN*max(Fscale(:))); dt = 2/CNh; % outer time step loop tstep = 0; while (time<FinalTime) if(time+dt>FinalTime), dt = FinalTime-time; end for INTRK = 1:5 timelocal = time + rk4c(INTRK)*dt; [rhsp, rhsu, rhsv] = acousticsRHS2D_WADG(p,u,v); % initiate and increment Runge-Kutta residuals %apply invM*M_c^2 resp = rk4a(INTRK)*resp + dt*rhsp; resu = rk4a(INTRK)*resu + dt*rhsu; resv = rk4a(INTRK)*resv + dt*rhsv; % update fields u = u+rk4b(INTRK)*resu; v = v+rk4b(INTRK)*resv; p = p+rk4b(INTRK)*resp; end; if 1 && nargin==0 && mod(tstep,10)==0 clf vv = Vp*p; plot3(xp,yp,vv,'.'); axis equal axis tight colorbar title(sprintf('time = %f',time)) drawnow end % Increment time time = time+dt; tstep = tstep+1; end function [rhsp, rhsu, rhsv] = acousticsRHS2D_WADG(p,u,v) Globals2D; % Define field differences at faces dp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM); du = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM); dv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM); % evaluate upwind fluxes ndotdU = nx.*du + ny.*dv; % Impose reflective boundary conditions (p+ = -p-) ndotdU(mapB) = 0; dp(mapB) = -2*p(vmapB); tau = 1; fluxp = tau*dp - ndotdU; fluxu = (tau*ndotdU - dp).*nx; fluxv = (tau*ndotdU - dp).*ny; pr = Dr*p; ps = Ds*p; dpdx = rx.*pr + sx.*ps; dpdy = ry.*pr + sy.*ps; divU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy); % compute right hand sides of the PDE's rhsp = -divU + LIFT*(Fscale.*fluxp)/2.0; rhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0; rhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0; rhsp = Pq*(Cq.*(Vq*rhsp)); return; end
github
KGuo26/WADG_Matlab-master
Wave2D_simple.m
.m
WADG_Matlab-master/Wave2D_simple.m
2,633
utf_8
977017e5edb69468778850473fbb3602
function Wave2D Globals2D N = 4; K1D = 16; c_flag = 0; FinalTime = 3; %cfun = @(x,y) ones(size(x)); cfun = @(x,y) .5*sin(pi*x).*sin(pi*y); % smooth velocity %cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity [Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D); StartUp2D; % plotting nodes [rp sp] = EquiNodes2D(50); [rp sp] = xytors(rp,sp); Vp = Vandermonde2D(N,rp,sp)/V; xp = Vp*x; yp = Vp*y; Nq = 2*N+1; [rq sq wq] = Cubature2D(Nq); % integrate u*v*c Vq = Vandermonde2D(N,rq,sq)/V; xq = Vq*x; yq = Vq*y; %% initial condition x0 = 0; y0 = .1; p = exp(-25*((x-x0).^2 + (y-y0).^2)); u = zeros(Np, K); v= zeros(Np,K); vv = Vp*p; color_line3(xp,yp,vv,vv) %% time = 0; % Runge-Kutta residual storage resu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K); % compute time step size CN = (N+1)*(N+2)/2; % trace inequality constant CNh = max(CN*max(Fscale(:))); dt = 2/CNh; % outer time step loop tstep = 0; figure while (time<FinalTime) if(time+dt>FinalTime), dt = FinalTime-time; end for INTRK = 1:5 timelocal = time + rk4c(INTRK)*dt; [rhsp, rhsu, rhsv] = acousticsRHS2D(p,u,v,timelocal); % initiate and increment Runge-Kutta residuals resp = rk4a(INTRK)*resp + dt*rhsp; resu = rk4a(INTRK)*resu + dt*rhsu; resv = rk4a(INTRK)*resv + dt*rhsv; % update fields u = u+rk4b(INTRK)*resu; v = v+rk4b(INTRK)*resv; p = p+rk4b(INTRK)*resp; end; if 1 && nargin==0 && mod(tstep,10)==0 clf vv = Vp*p; color_line3(xp,yp,vv,vv,'.'); axis equal axis tight colorbar title(sprintf('time = %f',time)) drawnow end % Increment time time = time+dt; tstep = tstep+1; end function [rhsp, rhsu, rhsv] = acousticsRHS2D(p,u,v,time) Globals2D; % Define field differences at faces dp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM); du = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM); dv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM); % evaluate upwind fluxes ndotdU = nx.*du + ny.*dv; % Impose reflective boundary conditions (p+ = -p-) ndotdU(mapB) = 0; dp(mapB) = -2*p(vmapB); tau = 1; fluxp = tau*dp - ndotdU; fluxu = (tau*ndotdU - dp).*nx; fluxv = (tau*ndotdU - dp).*ny; pr = Dr*p; ps = Ds*p; dpdx = rx.*pr + sx.*ps; dpdy = ry.*pr + sy.*ps; divU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy); % compute right hand sides of the PDE's rhsp = -divU + LIFT*(Fscale.*fluxp)/2.0; rhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0; rhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0; return;
github
KGuo26/WADG_Matlab-master
bern_pyr.m
.m
WADG_Matlab-master/bern_pyr.m
1,162
utf_8
e05be17e730cbb437109d06c7b108ec5
function [V Vr Vs Vt Va Vb Vc] = bern_pyr(N,r,s,t) a = 2*(r+1)./(1-t)-1; b = 2*(s+1)./(1-t)-1; c = t; ids = abs(t-1)<1e-8; a(ids) = -1; b(ids) = -1; dadr = 2./(1-t); dbds = 2./(1-t); dadt = (1+a)./(1-t); dbdt = (1+b)./(1-t); sk = 1; for k = 0:N for i = 0:N-k for j = 0:N-k V(:,sk) = bern(N-k,i,a).*bern(N-k,j,b).*bern(N,k,c); va = .5*d_bern(N-k,i,a).*bern(N-k,j,b).*bern(N,k,c); vb = .5*bern(N-k,i,a).*d_bern(N-k,j,b).*bern(N,k,c); vc = .5*bern(N-k,i,a).*bern(N-k,j,b).*d_bern(N,k,c); Vr(:,sk) = va.*dadr; Vs(:,sk) = vb.*dbds; Vt(:,sk) = va.*dadt + vb.*dbdt + vc; % for testing Va(:,sk) = va; Vb(:,sk) = vb; Vc(:,sk) = vc; sk = sk + 1; end end end function [bi] = bern(N,i,r) r = (1+r)/2; bi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i); % bi = (r.^i).*(1-r).^(N-i); function dbi = d_bern(N,i,r) if (i==0) dbi = -N*(1-r).^(N-1); elseif (i==N) dbi = N*(r.^(N-1)); else dbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r); end
github
KGuo26/WADG_Matlab-master
bern_basis_tri.m
.m
WADG_Matlab-master/bern_basis_tri.m
2,146
utf_8
b5c5ae2fee4e7f3bac98387d91b0b6d1
function [V Vr Vs V1 V2 V3 id] = bern_basis_tri(N,r,s) [V Vr Vs V1 V2 V3] = bern_tri(N,r,s); return % % % use equivalence between W&B and equispaced nodes - get ordering % [re se] = EquiNodes2D(N); [re se] = xytors(re,se); % Ve = bern_tri(N,re,se); % for i = 1:size(Ve,2) % [val iid] = max(Ve(:,i)); % id(i) = iid; % % id(i) = i; % end % % [V Vr Vs V1 V2 V3] = bern_tri(N,r,s); % V = V(:,id); % Vr = Vr(:,id); % Vs = Vs(:,id); % V1 = V1(:,id); % V2 = V2(:,id); % V3 = V3(:,id); function [V Vr Vs VL1 VL2 VL3] = bern_tri(N,r,s) % barycentric version L1 = -(r+s)/2; L2 = (1+r)/2; L3 = (1+s)/2; dL1r = -.5; dL2r = .5; dL3r = 0; dL1s = -.5; dL2s = 0; dL3s = .5; sk = 1; for k = 0:N for j = 0:N-k i = N-j-k; C=factorial(N)/(factorial(i)*factorial(j)*factorial(k)); V(:,sk) = C*(L1.^i).*(L2.^j).*(L3.^k); dL1 = C*i*(L1.^(i-1)).*(L2.^j).*(L3.^k); dL2 = C*j*(L1.^(i)).*(L2.^(j-1)).*(L3.^k); dL3 = C*k*(L1.^(i)).*(L2.^j).*(L3.^(k-1)); if i==0 dL1 = zeros(size(dL1)); end if j==0 dL2 = zeros(size(dL2)); end if k == 0 dL3 = zeros(size(dL3)); end Vr(:,sk) = dL1.*dL1r + dL2.*dL2r + dL3.*dL3r; Vs(:,sk) = dL1.*dL1s + dL2.*dL2s + dL3.*dL3s; VL1(:,sk) = dL1; VL2(:,sk) = dL2; VL3(:,sk) = dL3; sk = sk + 1; end end return % [a b] = rstoab(r,s); % a = .5*(a+1); % convert to unit % b = .5*(b+1); % convert to unit % be careful about derivatives at s = 1 a = .5*(r+1)./(1-.5*(s+1)); b = .5*(s+1); a(abs(1-s)<1e-8) = 0; dadr = 1./(1 - s); dads = (r+1)./((1-s).^2); dbds = .5; sk = 1; for i = 0:N for j = 0:N-i k = N-i-j; V(:,sk) = bern(N-k,i,a).*bern(N,k,b); Vr(:,sk) = d_bern(N-k,i,a).*bern(N,k,b).*dadr; Vs(:,sk) = d_bern(N-k,i,a).*bern(N,k,b).*dads + bern(N-k,i,a).*d_bern(N,k,b)*dbds; sk = sk + 1; end end function bi = bern(N,i,r) bi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i); function dbi = d_bern(N,i,r) dbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r);
github
KGuo26/WADG_Matlab-master
Sample2D.m
.m
WADG_Matlab-master/Sample2D.m
717
utf_8
be53a9f67b172f80cb774efda6b67d4b
function [sampleweights,sampletri] = Sample2D(xout, yout) % function [sampleweights,sampletri] = Sample2D(xout, yout) % purpose: input = coordinates of output data point % output = number of containing tri and interpolation weights % [ only works for straight sided triangles ] Globals2D; % find containing tri [sampletri,tribary] = ... tsearchn([VX', VY'], EToV, [xout,yout]); % Matlab barycentric coordinates -> biunit triangle coordinates sout = 2*tribary(:,3)-1; rout = 2*tribary(:,2)-1; % build generalized Vandermonde for the sample point Vout = Vandermonde2D(N, rout, sout); % build interpolation matrix for the sample point sampleweights = Vout*invV; return;
github
KGuo26/WADG_Matlab-master
tet_cubature.m
.m
WADG_Matlab-master/tet_cubature.m
103,616
utf_8
8f12d404868158cf03a4dc3cae2976bb
function [r s t w] = tet_cubature(N) % CubatureData3D_GX.cpp % database of precalculated cubature data % 2012/05/02 %--------------------------------------------------------- % % N [1 1 1] [2 2] [3 3] [4 % cubN 1 2 3 4 5 6 7 8 % Ncub 1 4 6 11 14 23 31 44 %--------------------------------------------------------- % % N 4 [5 5] [6 6] [7 7] % cubN 9 10 11 12 13 14 15 % Ncub 57 74 95 122 146 177 214 %--------------------------------------------------------- %---------------------- % N cubN Ncub %---------------------- % 1 ( 2, 3) [ 4, 6] % 2 ( 4, 5) [ 11, 14] % 3 ( 6, 7) [ 23, 31] % 4 ( 8, 9) [ 44, 57] % 5 (10,11) [ 74, 95] % 6 (12,13) [122,146] % 7 (14,15) [177,214] % 8 ( 15) [ 214] %---------------------- % NodeSet 1 1 TN2012_1 = [ % 1*4 0.000000000000000E+00, 0.000000000000000E+00, 0.000000000000000E+00, 0.942809041582063E+00 ]; % NodeSet 2 4 TN2012_2 = [ % 4*4 -.267702858591007E+00, 0.593901700619949E-01, -.396942694114215E+00, 0.283333858791636E+00, 0.151093184153314E+00, 0.435408773247631E+00, 0.215171925430692E+00, 0.262834019890433E+00, -.136769919523739E+00, -.328034111559041E+00, 0.295084651993713E+00, 0.300844647504794E+00, 0.806744930905196E+00, -.340097731428529E+00, -.343037895100255E+00, 0.957965153951996E-01 ]; % NodeSet 3 6 TN2012_3 = [ % 6*4 -.168503718027600E+00, 0.191091491627171E+00, -.389626731458516E+00, 0.124986334616479E+00, 0.278379942753442E-01, -.230493283883966E-01, 0.548135066324183E+00, 0.211580648438021E+00, -.351221617734345E+00, 0.183514402633999E+00, 0.514781533034353E-01, 0.120742171826672E+00, 0.430853246354904E+00, -.247471582318045E+00, -.168331564100703E+00, 0.237591631621872E+00, -.467676374796738E+00, -.423525082726438E+00, -.158697307788931E+00, 0.132581964894968E+00, 0.149283125384843E+00, 0.639784768516452E+00, -.108021925305539E+00, 0.115326290184051E+00 ]; % NodeSet 4 11 TN2012_4 = [ % 11*4 -.145961228097999E-01, 0.242656457919971E-02, 0.709356578010363E+00, 0.100379025241264E+00, -.293724489630999E+00, 0.176439650676461E+00, 0.110886049494113E+00, 0.103929831025446E+00, 0.323087833715827E+00, -.193207041095656E+00, 0.169542639670465E+00, 0.146112883409388E+00, -.881965417939658E-01, 0.231788427010598E-01, -.201181939132559E+00, 0.182349462340124E+00, 0.127020366331471E+00, 0.545141067721522E+00, 0.130950399075932E+00, 0.718068965649525E-01, -.441430768809118E+00, -.384822563159018E+00, 0.922542967916253E-01, 0.748841921109801E-01, 0.393941858963343E+00, 0.206874467063953E+00, -.311156042619824E+00, 0.654969120044006E-01, -.603446971461421E-01, -.457373907492708E+00, -.330221532932238E+00, 0.565055488469881E-01, -.891405983460118E-01, 0.726809265959946E+00, -.350793173736374E+00, 0.522257744237005E-01, 0.654521303360376E+00, -.397035624387057E+00, -.297042483395114E+00, 0.521122321989204E-01, -.730764225967786E+00, -.266942008864898E+00, -.386103757024185E+00, 0.370062834158988E-01 ]; % NodeSet 5 14 TN2012_5 = [ % 14*4 0.166418072157768E-15, 0.109436232414623E-15, 0.770436782529672E+00, 0.692899055434865E-01, 0.408992591748701E+00, -.236131982942675E+00, 0.333941052787584E+00, 0.401127730719707E-01, 0.633846727543000E-16, 0.472263965885350E+00, 0.333941052787583E+00, 0.401127730719707E-01, -.408992591748701E+00, -.236131982942675E+00, 0.333941052787583E+00, 0.401127730719708E-01, 0.372390093103578E-16, 0.354800148930181E-16, -.298278869430759E+00, 0.106243195244073E+00, -.243543677053202E+00, 0.140610007506098E+00, 0.994262898102530E-01, 0.106243195244073E+00, 0.771865760070526E-17, -.281220015012195E+00, 0.994262898102531E-01, 0.106243195244073E+00, 0.243543677053203E+00, 0.140610007506098E+00, 0.994262898102530E-01, 0.106243195244073E+00, 0.629058998756435E+00, -.363187382268184E+00, -.256812260843224E+00, 0.692899055434864E-01, -.629058998756435E+00, -.363187382268184E+00, -.256812260843224E+00, 0.692899055434865E-01, -.140776895379933E-15, 0.726374764536368E+00, -.256812260843224E+00, 0.692899055434864E-01, 0.408992591748701E+00, 0.236131982942675E+00, -.333941052787584E+00, 0.401127730719707E-01, -.104796521146490E-15, -.472263965885350E+00, -.333941052787583E+00, 0.401127730719707E-01, -.408992591748701E+00, 0.236131982942675E+00, -.333941052787584E+00, 0.401127730719707E-01 ]; % NodeSet 6 23 TN2012_6 = [ % 23*4 0.491994195152311E-02, -.139223850343092E-01, 0.106622826396772E+01, 0.668997954335606E-02, 0.341505806021954E-01, 0.254207383054340E+00, 0.631588696703923E+00, 0.297073565323308E-01, -.456119832861723E+00, -.311038544744538E+00, 0.230026765510699E+00, 0.228454763572233E-01, 0.214449922976949E+00, -.123490387324972E+00, 0.563235163630283E+00, 0.460940056044558E-01, -.154069305999594E+00, -.686521447230217E-01, 0.620626489628262E+00, 0.500002972857723E-01, 0.306452540322295E+00, 0.181849550192318E+00, 0.125468587644291E+00, 0.407663998761417E-01, -.130588295951477E-01, -.248889116907340E-01, -.335770592628266E+00, 0.632962545391904E-01, 0.153524468983807E-01, -.326114310053292E+00, 0.114778898592700E+00, 0.564001074548194E-01, -.156778448777534E+00, 0.252245430100092E+00, 0.214059780070552E+00, 0.590334934291369E-01, -.397361694050676E+00, -.197715908337850E+00, -.796336180288233E-01, 0.606546975975660E-01, 0.976488461664955E-02, 0.650418429113368E+00, 0.586844628157869E-02, 0.410974214177224E-01, -.522808798464745E+00, -.663505530412342E-01, 0.193427268845595E-02, 0.212751151391656E-01, 0.556560570221033E+00, -.318669005422011E+00, 0.137974025142484E-01, 0.439472843110177E-01, 0.842308197902346E-01, 0.213805982286452E-01, 0.319575612691255E-01, 0.106159736633763E+00, 0.217416609116024E+00, 0.459950700499800E+00, -.302723230375316E+00, 0.508504156781972E-01, 0.321215894522565E+00, -.426005242154505E+00, -.299485560260426E+00, 0.469223144374328E-01, -.259364807854540E+00, 0.385198021113758E+00, -.282519709925312E+00, 0.594595362053551E-01, 0.563645476720258E+00, -.111160622782170E+00, -.306814049530041E+00, 0.444515894220345E-01, -.641094964462573E+00, -.193431833850761E+00, -.366047360516159E+00, 0.240457075184084E-01, -.334415109058215E+00, -.449175869972365E+00, -.310242329274613E+00, 0.374428103418277E-01, -.189458838689202E-01, 0.901059945993096E+00, -.347395205043690E+00, 0.150146857671485E-01, -.821465589619935E+00, -.510986035935518E+00, -.263564524010136E+00, 0.982721516374585E-02, 0.859741547561566E+00, -.520808514122574E+00, -.360343258536933E+00, 0.682714132625144E-02 ]; % NodeSet 7 31 TN2012_7 = [ % 31*4 -.308252291356292E+00, -.197843287967888E+00, 0.655377140534142E+00, 0.726734289368660E-02, 0.323006856476517E+00, -.116660814480029E+00, 0.596321726821282E+00, 0.113172838083258E-01, 0.179003094309949E-02, 0.276022304167135E-02, 0.919167034243546E+00, 0.218890177509953E-01, -.174985856285022E+00, 0.149255307127258E+00, 0.516292138739824E+00, 0.211296379289743E-01, 0.351581822451223E-01, 0.322257000983196E+00, 0.549210359947022E+00, 0.219589530907310E-01, -.114891280250506E+00, 0.359815024699799E-01, -.388691765396646E+00, 0.257668903243402E-01, 0.108024261958047E+00, -.212321108274526E+00, 0.513821465706857E+00, 0.271493965375484E-01, 0.996088601920952E-01, 0.337060034616579E+00, -.273250222640217E+00, 0.405324562077599E-01, 0.255258965717304E+00, 0.234593138765271E-01, -.128926642642749E+00, 0.497630316079319E-01, 0.301897209396454E+00, -.279744081272853E+00, -.336815502815560E+00, 0.394457458861626E-01, -.363799525166287E-01, 0.678415814779263E+00, 0.496515459049994E-01, 0.195275383339862E-01, -.197974843267435E+00, -.109926012070685E+00, 0.368810136731088E+00, 0.568528141204943E-01, 0.170554760858719E+00, 0.585448114971668E-01, 0.324539845033623E+00, 0.628959292907061E-01, 0.538271457535773E+00, -.332620243815606E+00, 0.653099846338948E-01, 0.296146949713317E-01, -.582625595155966E+00, -.286639428866960E+00, 0.405007368919429E-01, 0.266935521529227E-01, -.663882748425514E-01, 0.339664373274517E+00, 0.433913762115470E-01, 0.629225940565768E-01, 0.139486545048336E+00, -.307850231836867E+00, -.855418822812698E-02, 0.605178177170064E-01, -.252544821156148E+00, -.968770785232076E-01, -.121223434312817E+00, 0.776291699936313E-01, -.336417947935678E+00, -.422280930562356E+00, 0.224493699213366E-01, 0.196789751488124E-01, 0.508817409509134E+00, -.460796001465295E-01, -.538915514978018E-01, 0.231576809797211E-01, -.399767677129958E+00, 0.169411793400156E+00, -.133176911076194E-01, 0.210705295411276E-01, 0.223357920899763E+00, 0.507026392231846E+00, -.399617306009708E-01, 0.209118054635657E-01, -.288768983232798E+00, -.432041161224173E+00, -.330437075713885E+00, 0.348234147884134E-01, 0.243005680598846E+00, 0.526215548808249E+00, -.363369754803439E+00, 0.157467976153176E-01, -.240245918466879E+00, 0.491923965978304E+00, -.318467007553824E+00, 0.318630473755232E-01, -.573712249516894E+00, -.745318233435191E-01, -.334800074141430E+00, 0.264563326318226E-01, 0.553074058634518E+00, -.335502653046674E-02, -.350744403540142E+00, 0.198864503476964E-01, 0.763216087154036E+00, -.434539428837598E+00, -.312047989157562E+00, 0.194127668598410E-01, 0.110832352531628E-02, 0.883581509323175E+00, -.315533688400763E+00, 0.181045845852361E-01, -.766658972551922E+00, -.454032742499625E+00, -.314870223157801E+00, 0.170243759166119E-01, 0.331437926843703E+00, -.541903403372277E+00, -.310441026876215E+00, 0.117984136552630E-01 ]; % NodeSet 8 44 TN2012_8 = [ % 44*4 -.161177255167053E-01, 0.799860011950070E-03, 0.114075012048065E+01, 0.164537481630632E-02, -.714882723684071E-02, 0.172391459500714E+00, 0.786069607279345E+00, 0.142022580708632E-01, 0.458992337208856E+00, -.174471635165123E+00, -.399143091233099E+00, 0.931166933355630E-02, -.452099049249418E+00, -.263294162907140E+00, 0.353609296024044E+00, 0.954963853667850E-02, 0.110956035643063E+00, -.629572037600564E-01, 0.818940414230147E+00, 0.166052583605351E-01, 0.182522429364889E+00, 0.167838281859336E+00, 0.476496271636175E+00, 0.147232729381889E-01, -.150748980541997E+00, -.782694187324931E-01, 0.762897429508123E+00, 0.169600880437266E-01, -.287732473487860E+00, -.123468697478364E+00, -.388005832381780E+00, 0.155840364711871E-01, 0.368074721237849E+00, -.216987676633974E+00, 0.399755369527441E+00, 0.212175082715303E-01, 0.478815642489051E+00, -.462943730059424E-01, 0.114465646499509E+00, 0.120673743703809E-01, -.347877936740082E+00, -.129563033616473E+00, 0.250917196877864E+00, 0.256962000267611E-01, -.354828586873474E-01, -.226810803130748E+00, 0.417461557834331E+00, 0.304461329840053E-01, 0.259165044293404E+00, 0.133007144302729E+00, -.274777834511803E+00, 0.265737195097187E-01, -.130503737894631E-02, 0.491940911589454E+00, 0.303192932475321E+00, 0.227767050847918E-01, -.349399607082860E-01, 0.300199516912219E+00, -.344250352423092E+00, 0.303973451645927E-01, -.166046285970730E+00, 0.140773645768751E+00, 0.397053743418083E+00, 0.344597559898010E-01, 0.101008552242243E+00, -.225925757531516E+00, -.307089325860143E+00, 0.391902057995841E-01, -.358746816360514E+00, -.108319979557346E+00, -.198990439690392E+00, 0.368286761285683E-01, -.347306756398568E+00, -.374230473903013E+00, 0.152625895856833E-01, 0.237013576444607E-01, -.863574112140118E-01, -.147806248208501E+00, -.154235018984395E-03, 0.498396471485484E-01, 0.290116820177849E+00, -.344951237372675E+00, 0.412102600131449E-01, 0.308555705439793E-01, 0.104209335515011E+00, 0.288367114168047E-01, 0.324891384827993E+00, 0.526016619480544E-01, -.641938745191836E-01, 0.255812557085304E+00, -.695790051538878E-01, 0.503024473506213E-01, -.201698697211897E+00, 0.440436807904118E+00, -.334098756487922E-01, 0.255666604695654E-01, 0.184617067735640E+00, 0.399856860528596E+00, -.130352743154576E-01, 0.378055160438833E-01, 0.378889395816016E+00, -.995658516281559E-01, -.839032251221259E-01, 0.488182976194162E-01, -.481871616316580E+00, -.150974738390975E-01, -.450140403133934E-01, 0.214429854534266E-01, 0.682171905077817E+00, -.395651861881759E+00, -.745152352274434E-01, 0.138780615762415E-01, 0.397864229301514E+00, 0.225661601324835E+00, -.399393902200914E+00, 0.650295778034312E-02, -.697588947015913E+00, -.389965102391845E+00, -.125421045820558E+00, 0.160043996273847E-01, 0.274296474933631E-02, 0.813499823087962E+00, -.141581579520532E+00, 0.163946974018378E-01, 0.164568786005099E-01, -.445103670029463E+00, -.185824429941080E+00, 0.212690542680105E-01, -.461834921478590E+00, -.453564747993794E+00, -.324551242480902E+00, 0.221549975797254E-01, 0.157509056839709E+00, 0.665014546017143E+00, -.331712100150823E+00, 0.189945011444925E-01, 0.539917520321524E+00, -.467462446997303E+00, -.316815950570112E+00, 0.193700460252858E-01, -.140390526208972E+00, 0.701265398375963E+00, -.337215023915009E+00, 0.168751540630192E-01, 0.445339657003786E-01, -.510724184730913E+00, -.395001367051171E+00, 0.709100855483249E-02, -.423436030210435E+00, 0.226332499768761E+00, -.333644400603587E+00, 0.206706155183819E-01, -.721417637689403E+00, -.272715517063635E+00, -.351939297000166E+00, 0.129502105610663E-01, 0.727811871619034E+00, -.286162780307073E+00, -.322616758291581E+00, 0.145083654707130E-01, 0.490189077970134E+00, 0.185630652333263E+00, -.278004232570757E+00, 0.111868259153756E-01, -.875888735250778E+00, -.556637467888742E+00, -.372057779910459E+00, 0.240124083764661E-02, 0.763237720561976E-02, 0.105605694666911E+01, -.397275100897422E+00, 0.196017972799913E-02, 0.931743114716919E+00, -.566424712470591E+00, -.382107361679063E+00, 0.142736140697601E-02 ]; % NodeSet 9 57 TN2012_9 = [ % 57*4 0.210805201710326E+00, -.895577604807597E-01, 0.773588207426104E+00, 0.551558344381980E-02, 0.128372935585005E-02, 0.612119775491147E-03, 0.102094083614009E+01, 0.668799331175713E-02, -.291873417501847E-01, 0.212275857965953E+00, 0.779935872338808E+00, 0.669939372222656E-02, -.435794929768927E+00, -.283935548031834E+00, 0.364437764378333E+00, 0.678802354666028E-02, -.179934163787020E+00, -.958255615202926E-01, 0.757204434805819E+00, 0.110898258011410E-01, 0.694222218620416E-01, -.139466668070751E+00, 0.705548760498302E+00, 0.118538505140399E-01, -.100564299113523E+00, 0.483639752826183E+00, -.407160361174579E+00, 0.742946816321177E-02, 0.190485569675336E+00, 0.324884395173882E+00, 0.278433783534254E+00, 0.926343928641625E-02, 0.323123885199655E+00, -.309109700213472E+00, 0.322000369135132E+00, 0.922010916817944E-02, 0.681998794334014E-01, -.179954101765636E+00, -.395513568317633E+00, 0.134505343605042E-01, 0.970813162355614E-01, 0.134669034127363E+00, 0.663220941750769E+00, 0.140436576643744E-01, 0.424623978805520E+00, -.197403745136440E+00, 0.367189752118327E+00, 0.109601109221468E-01, -.356966425620311E+00, 0.524066509488554E-01, -.374748135646347E+00, 0.125263969973275E-01, -.214575206114175E+00, 0.276138738286531E+00, 0.232593226318610E+00, 0.142541215309657E-01, -.481867430578161E-02, 0.484004124635174E+00, 0.348784030681802E+00, 0.148184854033573E-01, -.431495410462145E+00, -.397275228639652E+00, -.403570454197210E+00, 0.772943163310455E-02, -.131245356741703E+00, 0.756907618774431E-01, 0.537490019630355E+00, 0.247774861194694E-01, -.408355822291399E+00, -.123985974201377E+00, 0.265431810476576E+00, 0.187513504661882E-01, -.124561260584964E+00, -.234479030043771E+00, 0.369888302935578E+00, 0.248671432375052E-01, 0.113634878033089E+00, -.330547698703443E-01, 0.436987303689540E+00, 0.307730125976643E-01, 0.335166884632847E+00, 0.177062207282753E-01, 0.186039322023310E+00, 0.238461172482832E-01, 0.215958933320729E+00, 0.238524676460651E+00, -.347991118600472E+00, 0.239402893423799E-01, -.122863949389777E+00, 0.531376367885168E-01, -.273145041975343E+00, 0.332060763385794E-01, 0.138027624345606E+00, 0.734485926751206E-02, -.819386487269520E-01, 0.394804564434818E-01, 0.390531978382373E+00, -.243428663405389E+00, -.281292431872822E+00, 0.300240411183455E-01, -.458086784432454E+00, -.258955617426663E+00, -.254631379075299E+00, 0.265185960537560E-01, 0.231022856438977E+00, -.257836991797271E+00, 0.867803014584036E-01, 0.360351853787601E-01, 0.355406888461040E+00, 0.145836601896362E+00, -.142843849837899E+00, 0.241848262660195E-01, -.650524186104096E-01, -.319406461060356E+00, -.215662211604969E+00, 0.332617040610486E-01, -.178650654128820E+00, -.836129565920432E-01, 0.967490323299266E-01, 0.462939269977053E-01, 0.126510452153425E-01, 0.278960632394181E+00, 0.158303673718777E+00, 0.426257007495146E-01, -.457382782386756E+00, -.362054438107985E+00, -.237157888006631E-01, 0.216935544804701E-01, -.554273119987709E-01, 0.458349465064086E+00, -.208364056535059E+00, 0.336738699618573E-01, -.638763000006867E-01, -.411051272548540E+00, -.132770313096762E-01, 0.155331473891789E-01, -.341374973214618E+00, 0.145358665232317E+00, -.866448830311343E-01, 0.312268484322361E-01, 0.596607789097683E+00, -.281733562310855E+00, -.774827243010763E-01, 0.211007367041140E-01, 0.691731471051810E+00, -.424495189591718E+00, -.966950194712262E-02, 0.405144808936909E-02, 0.107828302200302E-01, 0.774068604209679E+00, -.631674539643141E-01, 0.122447617845554E-01, 0.183398357962906E+00, 0.509650173780726E+00, -.104199760560026E+00, 0.201330268431642E-01, -.156683210068974E+00, 0.587162777730252E+00, -.755800454786169E-01, 0.122331907698306E-01, -.721547519515627E+00, -.406928813430898E+00, -.799919904106300E-01, 0.664376101021386E-02, 0.563441810039983E+00, -.874528744803895E-01, -.375106925048635E+00, 0.972176210434993E-02, -.603817531772941E+00, -.160501116667620E+00, -.129922703170555E+00, 0.128950212070301E-01, 0.442461715547963E+00, -.465894984005083E+00, -.189272831033158E+00, 0.145039223723267E-01, 0.537695450854474E+00, -.482291905161232E+00, -.391061249617109E+00, 0.673169400168803E-02, 0.580167495141382E+00, -.263048745975854E-01, -.190776527382174E+00, 0.662950441786340E-02, 0.141863444388837E+00, 0.709313400805060E+00, -.347713452942033E+00, 0.123374761221794E-01, 0.380205280510817E-01, -.498131957310980E+00, -.347454353176202E+00, 0.125147680660765E-01, -.676654633827680E+00, -.160810255413913E+00, -.360647958818099E+00, 0.864102814374049E-02, -.148377942874081E+00, 0.747657811481758E+00, -.344049968649168E+00, 0.862346954119176E-02, 0.758853898498784E+00, -.286386495629028E+00, -.347456341168422E+00, 0.513516282754194E-02, -.400933270410922E+00, 0.318490934135072E+00, -.327689243668322E+00, 0.124744034495474E-01, 0.429402228177352E+00, 0.334245126683004E+00, -.354238091771872E+00, 0.622361500042201E-02, -.491182021838701E+00, -.525990681712148E+00, -.304001912945509E+00, 0.782176608831162E-02, -.823043669681940E+00, -.475229875889280E+00, -.344070595704639E+00, 0.756246981707266E-02, 0.830738527244245E+00, -.489448455641652E+00, -.329816063460246E+00, 0.635585327043357E-02, 0.284775635443480E-02, 0.980029354692865E+00, -.337801211308477E+00, 0.518644179936464E-02 ]; % NodeSet 10 74 TN2012_10 = [ % 74*4 0.413544192610844E+00, -.246750776531309E+00, -.224667871253980E-01, 0.194884222920563E-01, 0.692034457414863E-02, 0.481515164653911E+00, -.224667871255619E-01, 0.194884222920962E-01, -.420464537184973E+00, -.234764388122768E+00, -.224667871254998E-01, 0.194884222920930E-01, 0.121282701905074E+00, -.364557446136076E+00, -.367498543067273E+00, 0.116794850938757E-01, 0.255074658540227E+00, 0.287312623956679E+00, -.367498543067270E+00, 0.116794850938789E-01, -.376357360444638E+00, 0.772448221789755E-01, -.367498543067392E+00, 0.116794850938540E-01, -.479357881541579E-03, 0.110502360149269E+00, 0.916888476308096E+00, 0.624172197526661E-02, -.954581721268622E-01, -.556663161775985E-01, 0.916888476307731E+00, 0.624172197527072E-02, 0.959375300078558E-01, -.548360439716068E-01, 0.916888476308578E+00, 0.624172197526365E-02, 0.312630140117656E+00, 0.515676770951221E+00, -.355333655819841E+00, 0.578805012499284E-02, -.602904253843795E+00, 0.129072578554667E-01, -.355333655819819E+00, 0.578805012499533E-02, 0.290274113726703E+00, -.528584028806339E+00, -.355333655819835E+00, 0.578805012497432E-02, 0.179312496297470E+00, 0.282332460052200E+00, -.198316580827254E+00, 0.239540208326386E-01, -.334163330867068E+00, 0.141229469833529E-01, -.198316580827563E+00, 0.239540208326322E-01, 0.154850834569687E+00, -.296455407035973E+00, -.198316580827245E+00, 0.239540208326273E-01, 0.400666660401149E+00, 0.216199307780049E+00, -.144785840545057E+00, 0.118493333120654E-01, -.387567423018714E+00, 0.238887852466967E+00, -.144785840545187E+00, 0.118493333120532E-01, -.130992373825936E-01, -.455087160247049E+00, -.144785840545197E+00, 0.118493333120350E-01, -.115974989812532E+00, 0.793735571318706E+00, -.354239328110807E+00, 0.658548439060982E-02, -.629407673742435E+00, -.497305073040731E+00, -.354239328110752E+00, 0.658548439061438E-02, 0.745382663555392E+00, -.296430498277665E+00, -.354239328110759E+00, 0.658548439061556E-02, -.146516588784843E+00, 0.620735233485336E+00, -.125151192736591E+00, 0.123965418109180E-01, -.464314186829922E+00, -.437254704706162E+00, -.125151192736474E+00, 0.123965418109110E-01, 0.610830775614764E+00, -.183480528779117E+00, -.125151192736430E+00, 0.123965418109090E-01, 0.152677322698633E+00, 0.615349010913590E+00, -.138717779739843E+00, 0.129228051042385E-01, -.609246536994131E+00, -.175452065417948E+00, -.138717779739883E+00, 0.129228051042351E-01, 0.456569214295294E+00, -.439896945495579E+00, -.138717779739667E+00, 0.129228051042306E-01, -.234983628865204E+00, -.506023035146311E+00, -.354913786574649E+00, 0.861537010564474E-02, 0.555720617769565E+00, 0.495097255022037E-01, -.354913786574608E+00, 0.861537010564896E-02, -.320736988903808E+00, 0.456513309644504E+00, -.354913786574637E+00, 0.861537010565374E-02, 0.261719079216423E+00, 0.120684595399040E+00, 0.865913059621064E-01, 0.252926861510092E-01, -.235375465069513E+00, 0.166313073556813E+00, 0.865913059617144E-01, 0.252926861510152E-01, -.263436141471209E-01, -.286997668956207E+00, 0.865913059620792E-01, 0.252926861510182E-01, -.151870784241490E+00, 0.375380795135610E+00, 0.259768753032010E+00, 0.105992396528304E-01, -.249153912559676E+00, -.319214354813566E+00, 0.259768753032135E+00, 0.105992396528186E-01, 0.401024696800887E+00, -.561664403219833E-01, 0.259768753032231E+00, 0.105992396528257E-01, 0.210831894372952E+00, -.130924570230131E+00, 0.263063208114240E+00, 0.264859218837044E-01, 0.796805661212086E-02, 0.248048061569683E+00, 0.263063208114389E+00, 0.264859218837275E-01, -.218799950985084E+00, -.117123491339812E+00, 0.263063208114476E+00, 0.264859218837323E-01, -.645184534114996E+00, -.294850962306783E+00, -.345383308918403E+00, 0.117883930527143E-01, 0.577940690745812E+00, -.411320715519360E+00, -.345383308918355E+00, 0.117883930527001E-01, 0.672438433695747E-01, 0.706171677825659E+00, -.345383308918353E+00, 0.117883930527065E-01, -.111702700311124E+00, 0.378278113185099E+00, -.232788953429898E+00, 0.257606535268669E-01, -.271747105558396E+00, -.285876432733472E+00, -.232788953429742E+00, 0.257606535268701E-01, 0.383449805869739E+00, -.924016804521191E-01, -.232788953429680E+00, 0.257606535268793E-01, 0.235386463106491E+00, -.326349752361119E+00, 0.241526812057868E+00, 0.111411397385480E-01, 0.164933944510181E+00, 0.367025532937718E+00, 0.241526812057621E+00, 0.111411397385863E-01, -.400320407616776E+00, -.406757805765914E-01, 0.241526812057666E+00, 0.111411397385560E-01, 0.781386647435055E+00, -.452646852034879E+00, -.213306800322009E+00, 0.673992636364470E-02, 0.131034908770753E-02, 0.903024112874510E+00, -.213306800322442E+00, 0.673992636363803E-02, -.782696996523264E+00, -.450377260839599E+00, -.213306800322782E+00, 0.673992636364011E-02, -.144648648594220E+00, 0.855865956909313E-01, 0.605581650673550E+00, 0.157113747630530E-01, -.179584179474888E-02, -.168062702151182E+00, 0.605581650673681E+00, 0.157113747630306E-01, 0.146444490388834E+00, 0.824761064602773E-01, 0.605581650673770E+00, 0.157113747630343E-01, 0.566289741151568E+00, -.329071545508948E+00, 0.141413168417081E+00, 0.959306888489052E-02, 0.183944749757621E-02, 0.654957074494562E+00, 0.141413168416557E+00, 0.959306888489720E-02, -.568129188649652E+00, -.325885528985560E+00, 0.141413168416239E+00, 0.959306888489236E-02, 0.195995882040799E-02, 0.350093442409637E+00, 0.559353834699797E+00, 0.107406866856387E-01, -.304169794235504E+00, -.173349347076073E+00, 0.559353834699497E+00, 0.107406866856343E-01, 0.302209835414552E+00, -.176744095333465E+00, 0.559353834700328E+00, 0.107406866856401E-01, -.713806162729187E-01, 0.396304230394379E+00, -.396100787902427E+00, 0.774239246773105E-02, -.307519223012102E+00, -.259969542227603E+00, -.396100787902375E+00, 0.774239246774146E-02, 0.378899839285653E+00, -.136334688167220E+00, -.396100787902350E+00, 0.774239246774322E-02, -.318784852490390E-01, 0.106707438509449E+01, -.395074109048042E+00, 0.744912589128255E-03, -.908174282594812E+00, -.561144770606617E+00, -.395074109048246E+00, 0.744912589134030E-03, 0.940052767843358E+00, -.505929614487096E+00, -.395074109047602E+00, 0.744912589138556E-03, 0.997667683143875E-01, 0.947218006642626E+00, -.377949220857205E+00, 0.159576637662907E-02, -.870198240831572E+00, -.387208447506806E+00, -.377949220857219E+00, 0.159576637662087E-02, 0.770431472517722E+00, -.560009559135281E+00, -.377949220857186E+00, 0.159576637661854E-02, -.820775777814033E-14, -.146673911156923E-12, -.346454886778686E-01, 0.439146516704393E-01, -.347841759723423E-12, 0.241985437638784E-13, 0.120100985698529E+01, 0.360074156134488E-03, 0.479095201677494E-12, -.155248834093771E-12, 0.406812386591265E+00, 0.110828201197969E-01, 0.137478771276506E-12, -.230632360521964E-12, -.334140778607838E+00, 0.263152783811875E-01, 0.142035845739461E-12, -.170617436886576E-12, 0.569947520590082E+00, 0.107640257183785E-01 ]; % NodeSet 11 95 TN2012_11 = [ % 95*4 0.965117777689970E-01, 0.763379519383339E+00, -.186826886312270E+00, 0.600845159732900E-02, -.709361945399304E+00, -.298108108379529E+00, -.186826886312305E+00, 0.600845159733409E-02, 0.612850167629794E+00, -.465271411003715E+00, -.186826886311271E+00, 0.600845159734557E-02, -.452783642439655E-02, 0.535212668450515E+00, 0.419413645671028E+00, 0.137982881729824E-02, -.461243849092658E+00, -.271527555592882E+00, 0.419413645671752E+00, 0.137982881730247E-02, 0.465771685518937E+00, -.263685112857434E+00, 0.419413645671101E+00, 0.137982881724185E-02, 0.243865553143861E-01, -.385976677345993E+00, 0.503008658379878E-01, 0.920652231770260E-02, 0.322072330192304E+00, 0.214107715087058E+00, 0.503008658372996E-01, 0.920652231774636E-02, -.346458885508177E+00, 0.171868962258854E+00, 0.503008658370734E-01, 0.920652231767883E-02, -.126750066458516E+00, 0.693029111438289E+00, -.150595614519410E+00, 0.661716072025893E-02, -.536805782837873E+00, -.456283333203682E+00, -.150595614519024E+00, 0.661716072024581E-02, 0.663555849297038E+00, -.236745778234389E+00, -.150595614519243E+00, 0.661716072024213E-02, -.954797245177502E-01, 0.327297126599053E+00, -.172527578542390E+00, 0.185656100008145E-01, -.235707763961444E+00, -.246336430278646E+00, -.172527578542985E+00, 0.185656100007781E-01, 0.331187488479253E+00, -.809606963205869E-01, -.172527578541491E+00, 0.185656100009255E-01, -.790832808659181E-02, 0.911574214979798E+00, -.170981061542019E+00, 0.298677403005469E-02, -.785492263564104E+00, -.462635920514496E+00, -.170981061542179E+00, 0.298677403005462E-02, 0.793400591649882E+00, -.448938294464901E+00, -.170981061540804E+00, 0.298677403007424E-02, -.149464443207015E+00, 0.450624307688046E+00, 0.767474283940176E-01, 0.110287876790012E-01, -.315519876417291E+00, -.354752158623110E+00, 0.767474283947060E-01, 0.110287876790499E-01, 0.464984319623066E+00, -.958721490650558E-01, 0.767474283968136E-01, 0.110287876791503E-01, 0.116527686078558E+00, 0.399090383783252E+00, -.372013456992333E+00, 0.105992886100834E-01, -.403886253801475E+00, -.986292555028626E-01, -.372013456992289E+00, 0.105992886100787E-01, 0.287358567722714E+00, -.300461128279899E+00, -.372013456992142E+00, 0.105992886101145E-01, -.204775506709099E-02, 0.107474766209103E+00, 0.934296066501945E+00, 0.409142461938696E-02, -.920520002693779E-01, -.555107910131548E-01, 0.934296066502188E+00, 0.409142461937905E-02, 0.940997553396656E-01, -.519639751977071E-01, 0.934296066495320E+00, 0.409142461947846E-02, 0.346835457488581E+00, -.394508692759800E+00, -.361173628980284E-01, 0.117181969107905E-01, 0.168236821198931E+00, 0.497622663499452E+00, -.361173628986015E-01, 0.117181969107935E-01, -.515072278689013E+00, -.103113970739211E+00, -.361173628990288E-01, 0.117181969107802E-01, -.114431972741818E+00, 0.876715287683553E+00, -.353556036747552E+00, 0.250403187559638E-02, -.702041724648949E+00, -.537458639241080E+00, -.353556036747620E+00, 0.250403187561624E-02, 0.816473697390820E+00, -.339256648442110E+00, -.353556036747688E+00, 0.250403187560628E-02, -.304870256759300E+00, 0.362285109955623E+00, -.192611435219708E+00, 0.121611426335016E-01, -.161312980254746E+00, -.445167942189768E+00, -.192611435219803E+00, 0.121611426334971E-01, 0.466183237014652E+00, 0.828828322332235E-01, -.192611435219709E+00, 0.121611426335199E-01, 0.210164030825951E+00, -.499019487215612E+00, -.281852351964106E+00, 0.782992696918182E-02, 0.327081537499466E+00, 0.431517133264640E+00, -.281852351964309E+00, 0.782992696917981E-02, -.537245568325068E+00, 0.675023539512562E-01, -.281852351964830E+00, 0.782992696920705E-02, -.640407059904653E-01, 0.706921078951722E+00, -.388855276146498E+00, 0.484839331593464E-02, -.580191259847264E+00, -.408921417739124E+00, -.388855276146452E+00, 0.484839331594336E-02, 0.644231965837054E+00, -.297999661211961E+00, -.388855276145405E+00, 0.484839331606112E-02, 0.547000964710360E-02, 0.287534224296398E+00, 0.665484806312732E+00, 0.597173171055007E-02, -.251746947521409E+00, -.139029944834592E+00, 0.665484806313078E+00, 0.597173171055419E-02, 0.246276937877777E+00, -.148504279463874E+00, 0.665484806307889E+00, 0.597173171042218E-02, 0.100846198138096E-01, -.205752031778813E+00, 0.179468318187578E-01, 0.260067107585456E-01, 0.173144176492929E+00, 0.111609552836825E+00, 0.179468318197516E-01, 0.260067107585507E-01, -.183228796308316E+00, 0.941424789424061E-01, 0.179468318186687E-01, 0.260067107585578E-01, 0.174898207844580E+00, 0.337221337718768E+00, -.227279445343111E+00, 0.189036526144369E-01, -.379491349084951E+00, -.171443777901745E-01, -.227279445343298E+00, 0.189036526143951E-01, 0.204593141240706E+00, -.320076959928987E+00, -.227279445342920E+00, 0.189036526144052E-01, 0.106539163848767E-01, 0.392485195255571E+00, 0.807848010336490E-01, 0.204109886439253E-01, -.345229107893253E+00, -.187016035388081E+00, 0.807848010331957E-01, 0.204109886439160E-01, 0.334575191505824E+00, -.205469159866835E+00, 0.807848010360809E-01, 0.204109886439593E-01, -.708368682688562E-03, -.242259848811423E+00, 0.340611194255165E+00, 0.163646441659378E-01, 0.210157367729121E+00, 0.120516459131557E+00, 0.340611194255109E+00, 0.163646441658739E-01, -.209448999046689E+00, 0.121743389680979E+00, 0.340611194253702E+00, 0.163646441659038E-01, -.285127304889096E+00, 0.541912173452750E+00, -.354913123600949E+00, 0.572964737547824E-02, -.326746056385501E+00, -.517883576072872E+00, -.354913123601104E+00, 0.572964737548000E-02, 0.611873361274685E+00, -.240285973797814E-01, -.354913123601249E+00, 0.572964737546058E-02, -.232320939692072E-02, 0.251307339208139E+00, 0.421305767658705E+00, 0.164150916714920E-01, -.216476935213671E+00, -.127665627959789E+00, 0.421305767658474E+00, 0.164150916715063E-01, 0.218800144609601E+00, -.123641711247167E+00, 0.421305767661954E+00, 0.164150916714715E-01, -.205157790402930E-01, 0.655109849960249E+00, -.243025087375771E+00, 0.143350299742849E-01, -.557083882814730E+00, -.345322110807617E+00, -.243025087375512E+00, 0.143350299742910E-01, 0.577599661854348E+00, -.309787739152588E+00, -.243025087373678E+00, 0.143350299742819E-01, -.302645519699800E-02, -.166602186418557E+00, 0.693950700576721E+00, 0.678988863033392E-02, 0.145794953362658E+00, 0.806801061259830E-01, 0.693950700576845E+00, 0.678988863030666E-02, -.142768498166691E+00, 0.859220802934521E-01, 0.693950700575701E+00, 0.678988863030576E-02, -.197353854914094E+00, 0.296656144937577E+00, -.354789590718461E+00, 0.146915319740604E-01, -.158234830247364E+00, -.319241524359057E+00, -.354789590718600E+00, 0.146915319740350E-01, 0.355588685161490E+00, 0.225853794216406E-01, -.354789590718495E+00, 0.146915319740717E-01, 0.106885774436226E+00, 0.414728869215933E+00, 0.327363420469225E+00, 0.681230704214779E-02, -.412608623641975E+00, -.114798638643009E+00, 0.327363420469154E+00, 0.681230704214552E-02, 0.305722849205178E+00, -.299930230573075E+00, 0.327363420469785E+00, 0.681230704208426E-02, -.300336408294241E+00, -.288233526509174E+00, 0.379747909798793E+00, 0.482110236270034E-02, 0.399785760325697E+00, -.115982196008667E+00, 0.379747909801915E+00, 0.482110236255637E-02, -.994493520320316E-01, 0.404215722519396E+00, 0.379747909798407E+00, 0.482110236269031E-02, 0.122183524609399E-01, 0.100907701884453E+01, -.362667202068887E+00, 0.263398684352695E-02, -.879995508924978E+00, -.493957105798725E+00, -.362667202068938E+00, 0.263398684352256E-02, 0.867777156463928E+00, -.515119913045772E+00, -.362667202068643E+00, 0.263398684353644E-02, 0.153456883865012E+00, 0.748965017517851E+00, -.365662386060026E+00, 0.572950098933217E-02, -.725351173648843E+00, -.241584948946274E+00, -.365662386060004E+00, 0.572950098933272E-02, 0.571894289784060E+00, -.507380068571563E+00, -.365662386059841E+00, 0.572950098935171E-02, 0.223545621647398E-02, 0.666719280580741E+00, 0.105695336068241E+00, 0.851444680345821E-02, -.578513562284073E+00, -.331423678417813E+00, 0.105695336068278E+00, 0.851444680346480E-02, 0.576278106065851E+00, -.335295602162006E+00, 0.105695336070785E+00, 0.851444680349955E-02, 0.943641659215635E-01, -.515850141384783E+00, -.401512235299027E+00, 0.308329306953878E-02, 0.399557244024400E+00, 0.339646835586887E+00, -.401512235299043E+00, 0.308329306953569E-02, -.493921409945304E+00, 0.176203305798363E+00, -.401512235299548E+00, 0.308329306949863E-02, 0.157895181731732E-11, -.806952626522489E-12, 0.111822360907102E+01, 0.104767813052089E-02, -.723450889997721E-12, 0.459685166655004E-12, 0.666410458367556E+00, 0.169670060154491E-01, -.119501050305224E-12, 0.115625438680115E-12, -.380999085805230E+00, 0.109719477490228E-01, 0.127319386408849E-12, 0.576565413140336E-13, -.225394550268228E+00, 0.280623276941522E-01, -.139831304526210E-12, -.122619858793024E-12, 0.260494099975575E+00, 0.254827978128425E-01 ]; % NodeSet 12 122 TN2012_12 = [ % 122*4 0.395854409891267E+00, 0.333851555538772E+00, -.390557745165981E+00, 0.196698372273148E-02, -.487051133135165E+00, 0.175894197396554E+00, -.390557745165981E+00, 0.196698372273156E-02, 0.911967232438951E-01, -.509745752935337E+00, -.390557745165989E+00, 0.196698372273062E-02, -.592643180494659E+00, -.257532889411981E+00, -.419476157759784E-02, 0.593882685696330E-02, 0.519351614788115E+00, -.384477604981992E+00, -.419476157760429E-02, 0.593882685696352E-02, 0.732915657065390E-01, 0.642010494393973E+00, -.419476157758415E-02, 0.593882685696374E-02, -.454414185024514E-01, 0.344585845204826E+00, 0.187402702185600E+00, 0.123879940796820E-01, -.275699386480693E+00, -.211646345409540E+00, 0.187402702185615E+00, 0.123879940796815E-01, 0.321140804983144E+00, -.132939499795295E+00, 0.187402702185621E+00, 0.123879940796812E-01, -.341386063086216E+00, -.408973262387964E+00, -.307110201339023E+00, 0.809284187539252E-02, 0.524874266239694E+00, -.911623719366133E-01, -.307110201339028E+00, 0.809284187539236E-02, -.183488203153488E+00, 0.500135634324581E+00, -.307110201339028E+00, 0.809284187539222E-02, -.131972243113920E+00, -.243782408641952E+00, -.270196159791184E-01, 0.146386931024421E-01, 0.277107880436666E+00, 0.759988918990409E-02, -.270196159791151E-01, 0.146386931024407E-01, -.145135637322735E+00, 0.236182519452053E+00, -.270196159791055E-01, 0.146386931024392E-01, 0.291671915694103E+00, 0.572563599327284E+00, -.365022387456384E+00, 0.265528824562810E-02, -.641690580146739E+00, -.336865111020842E-01, -.365022387456384E+00, 0.265528824562798E-02, 0.350018664452620E+00, -.538877088225203E+00, -.365022387456383E+00, 0.265528824562834E-02, -.407043948553664E-01, 0.579489770656000E+00, -.861239200062299E-01, 0.112080999248455E-01, -.481500665193633E+00, -.324995925318421E+00, -.861239200062188E-01, 0.112080999248459E-01, 0.522205060049005E+00, -.254493845337578E+00, -.861239200062174E-01, 0.112080999248457E-01, -.982085654981925E-01, 0.550459421679584E+00, 0.107079122173015E+00, 0.695607989649797E-02, -.427607560177907E+00, -.360280823430456E+00, 0.107079122173020E+00, 0.695607989649740E-02, 0.525816125676105E+00, -.190178598249124E+00, 0.107079122173022E+00, 0.695607989649711E-02, 0.218408903368161E+00, 0.411598677519539E+00, 0.323037482249117E-01, 0.736054409846543E-02, -.465659362580079E+00, -.166516800302459E-01, 0.323037482249063E-01, 0.736054409846635E-02, 0.247250459211923E+00, -.394946997489293E+00, 0.323037482249106E-01, 0.736054409846627E-02, -.660677749114476E-02, -.143062077792866E+00, 0.328982719937537E+00, 0.183928475395296E-01, 0.127198782432377E+00, 0.658094017519560E-01, 0.328982719937527E+00, 0.183928475395297E-01, -.120592004941238E+00, 0.772526760409100E-01, 0.328982719937539E+00, 0.183928475395289E-01, -.186234667494277E+00, 0.234269739501763E+00, -.200232446998792E+00, 0.159414592319126E-01, -.109766211999345E+00, -.278418822866280E+00, -.200232446998804E+00, 0.159414592319108E-01, 0.296000879493631E+00, 0.441490833645066E-01, -.200232446998801E+00, 0.159414592319116E-01, -.589040275422118E+00, -.401755436436729E+00, -.277182597081116E+00, 0.819183899036344E-02, 0.642450551773759E+00, -.309246124149365E+00, -.277182597081118E+00, 0.819183899036412E-02, -.534102763516564E-01, 0.711001560586086E+00, -.277182597081118E+00, 0.819183899036391E-02, -.119640021030782E-01, 0.908525373598771E+00, -.379414595213076E+00, 0.294790999852269E-02, -.780824052467749E+00, -.464623816551583E+00, -.379414595213078E+00, 0.294790999852259E-02, 0.792788054570826E+00, -.443901557047195E+00, -.379414595213078E+00, 0.294790999852263E-02, 0.623523946168630E-01, 0.473029639538299E+00, 0.288759219788336E+00, 0.727501233383112E-02, -.440831881891602E+00, -.182516062044160E+00, 0.288759219788326E+00, 0.727501233383119E-02, 0.378479487274750E+00, -.290513577494149E+00, 0.288759219788326E+00, 0.727501233383113E-02, 0.223590386309356E+00, -.685745684803208E-01, 0.730795305056316E+00, 0.297359482938225E-02, -.524078747971530E-01, 0.227922238826041E+00, 0.730795305056320E+00, 0.297359482938299E-02, -.171182511512208E+00, -.159347670345715E+00, 0.730795305056314E+00, 0.297359482938252E-02, 0.166647705033182E+00, 0.219014023508552E+00, 0.412491824632861E+00, 0.859915960963346E-02, -.272995560660045E+00, 0.348141342868342E-01, 0.412491824632852E+00, 0.859915960963336E-02, 0.106347855626874E+00, -.253828157795390E+00, 0.412491824632853E+00, 0.859915960963354E-02, -.741504913903760E-01, -.425160033234697E-01, 0.983902012123622E+00, 0.298228147645889E-02, 0.738951846406989E-01, -.429582075854323E-01, 0.983902012123617E+00, 0.298228147645893E-02, 0.255306749680119E-03, 0.854742109088923E-01, 0.983902012123638E+00, 0.298228147645866E-02, 0.195590871722804E+00, -.244732213104454E+00, 0.682975149260760E-01, 0.177091390217947E-01, 0.114148877811455E+00, 0.291752770212531E+00, 0.682975149260640E-01, 0.177091390217942E-01, -.309739749534244E+00, -.470205571080570E-01, 0.682975149260745E-01, 0.177091390217946E-01, -.180268025859154E-01, 0.260028370424514E+00, 0.509026771210850E+00, 0.108911229551476E-01, -.216177773199345E+00, -.145625854200665E+00, 0.509026771210867E+00, 0.108911229551474E-01, 0.234204575785254E+00, -.114402516223841E+00, 0.509026771210866E+00, 0.108911229551477E-01, -.153261381170292E+00, 0.296445376975146E+00, 0.385161785525853E+00, 0.502733325550593E-02, -.180098536709772E+00, -.280950938000134E+00, 0.385161785525857E+00, 0.502733325550605E-02, 0.333359917880078E+00, -.154944389750067E-01, 0.385161785525851E+00, 0.502733325550543E-02, 0.577633666523352E-02, 0.777575919372589E+00, 0.234842077607212E-01, 0.314863068921769E-02, -.676288667880321E+00, -.383785505393390E+00, 0.234842077607121E-01, 0.314863068921804E-02, 0.670512331215088E+00, -.393790413979201E+00, 0.234842077607110E-01, 0.314863068921800E-02, -.830459079091334E-01, -.362439189266012E+00, 0.774728166241968E-01, 0.110344801019880E-01, 0.355404499185969E+00, 0.109299728703350E+00, 0.774728166242032E-01, 0.110344801019876E-01, -.272358591276836E+00, 0.253139460562663E+00, 0.774728166241957E-01, 0.110344801019877E-01, 0.542384531596793E+00, -.214582781999708E-01, -.163033856608466E+00, 0.793705941737894E-02, -.252608851755744E+00, 0.480447922082540E+00, -.163033856608472E+00, 0.793705941737921E-02, -.289775679841053E+00, -.458989643882559E+00, -.163033856608470E+00, 0.793705941737940E-02, 0.557343196731010E+00, 0.934213228803310E-01, -.358456239566711E+00, 0.396471418063503E-02, -.359576837235012E+00, 0.435962705555325E+00, -.358456239566711E+00, 0.396471418063520E-02, -.197766359495993E+00, -.529384028435640E+00, -.358456239566708E+00, 0.396471418063583E-02, 0.473136623876986E+00, -.250358512021129E+00, 0.369862621961321E+00, 0.303733516257231E-02, -.197514804745208E-01, 0.534927591748828E+00, 0.369862621961330E+00, 0.303733516257264E-02, -.453385143402462E+00, -.284569079727708E+00, 0.369862621961319E+00, 0.303733516257254E-02, 0.315321932442742E+00, -.153252510670659E+00, -.366729822887569E+00, 0.105027803145516E-01, -.249403987868362E-01, 0.349703059201127E+00, -.366729822887571E+00, 0.105027803145513E-01, -.290381533655895E+00, -.196450548530486E+00, -.366729822887572E+00, 0.105027803145511E-01, -.183165376400892E-01, 0.108643540500343E+01, -.379008133716638E+00, 0.476818959640627E-03, -.931722391483764E+00, -.559080289407412E+00, -.379008133716641E+00, 0.476818959640552E-03, 0.950038929123857E+00, -.527355115596027E+00, -.379008133716642E+00, 0.476818959640539E-03, -.669997455371388E+00, -.227798897754623E+00, -.219722706081442E+00, 0.784021930375232E-02, 0.532278360095291E+00, -.466335367945242E+00, -.219722706081443E+00, 0.784021930375221E-02, 0.137719095276097E+00, 0.694134265699857E+00, -.219722706081437E+00, 0.784021930375275E-02, 0.278278328278097E+00, 0.210817208106962E+00, -.365464586905286E+00, 0.108042147702591E-01, -.321712221914591E+00, 0.135587497558006E+00, -.365464586905286E+00, 0.108042147702593E-01, 0.434338936365029E-01, -.346404705664989E+00, -.365464586905287E+00, 0.108042147702594E-01, 0.974677087891540E-01, 0.374855937111035E+00, -.201472632623356E+00, 0.206967714188870E-01, -.373368618692161E+00, -.103018456695450E+00, -.201472632623353E+00, 0.206967714188874E-01, 0.275900909903009E+00, -.271837480415594E+00, -.201472632623350E+00, 0.206967714188872E-01, 0.108908146593124E-01, 0.940032615892273E+00, -.246440528575148E+00, 0.346740810672804E-02, -.819537533078310E+00, -.460584585783268E+00, -.246440528575155E+00, 0.346740810672790E-02, 0.808646718418997E+00, -.479448030109011E+00, -.246440528575156E+00, 0.346740810672803E-02, -.125193888603033E+00, 0.326782427510051E-01, 0.737539571985585E+00, 0.754303426952455E-02, 0.342967559281075E-01, -.124760209304291E+00, 0.737539571985584E+00, 0.754303426952443E-02, 0.908971326749169E-01, 0.920819665532847E-01, 0.737539571985590E+00, 0.754303426952452E-02, 0.486885272388682E+00, -.419470048425788E+00, -.368924026122376E+00, 0.739775920991071E-02, 0.119829081869080E+00, 0.631390038829989E+00, -.368924026122375E+00, 0.739775920991112E-02, -.606714354257758E+00, -.211919990404208E+00, -.368924026122375E+00, 0.739775920991109E-02, 0.338254046583528E+00, 0.336279909351889E+00, -.220250860026090E+00, 0.114614821427815E-01, -.460353967572830E+00, 0.124796642598277E+00, -.220250860026094E+00, 0.114614821427812E-01, 0.122099920989301E+00, -.461076551950167E+00, -.220250860026091E+00, 0.114614821427811E-01, -.948021074991389E-01, 0.799664327081630E+00, -.159472036609177E+00, 0.267380541702802E-02, -.645128568003312E+00, -.481933196967374E+00, -.159472036609172E+00, 0.267380541702784E-02, 0.739930675502450E+00, -.317731130114253E+00, -.159472036609174E+00, 0.267380541702784E-02, 0.114011306776160E+00, 0.921756734003682E+00, -.375888607361787E+00, 0.121571084356495E-02, -.855270401144653E+00, -.362141679015031E+00, -.375888607361789E+00, 0.121571084356478E-02, 0.741259094368485E+00, -.559615054988663E+00, -.375888607361789E+00, 0.121571084356474E-02, -.165842180155680E+00, 0.816962945157694E+00, -.354270062100271E+00, 0.197644247637581E-02, -.624589574379273E+00, -.552105013612662E+00, -.354270062100270E+00, 0.197644247637581E-02, 0.790431754534958E+00, -.264857931545035E+00, -.354270062100270E+00, 0.197644247637583E-02, 0.255741305649357E+00, -.185422039944996E+00, 0.689558909191225E+00, 0.209026833265583E-02, 0.327095441892273E-01, 0.314189487461839E+00, 0.689558909191237E+00, 0.209026833265534E-02, -.288450849838587E+00, -.128767447516842E+00, 0.689558909191228E+00, 0.209026833265520E-02, -.161315756957164E+00, 0.622400231722008E+00, -.407391669247035E+00, 0.246529805415523E-02, -.458356533514003E+00, -.450903659416629E+00, -.407391669247037E+00, 0.246529805415509E-02, 0.619672290471167E+00, -.171496572305384E+00, -.407391669247040E+00, 0.246529805415493E-02, 0.215699898765183E-14, -.174736370992125E-14, 0.648211705357551E+00, 0.104708231427821E-01, 0.215768577391029E-14, -.784133983875845E-14, 0.119860353953893E+01, 0.188750315664348E-03, 0.932976159332810E-14, -.103874241321632E-13, -.404150914547157E+00, 0.466026308255542E-02, -.193782609554479E-14, -.643408870516526E-14, -.271058498607272E+00, 0.240578023764951E-01, 0.511210059808282E-14, 0.851161159313764E-14, 0.875755507387370E-02, 0.278175500155602E-01 ]; % NodeSet 13 146 TN2012_13 = [ % 146*4 -.477738501746661E-01, 0.901553008435599E+00, -.232771532399634E+00, 0.200887673646286E-02, -.756880883076013E+00, -.492149872105709E+00, -.232771532399608E+00, 0.200887673646046E-02, 0.804654733250740E+00, -.409403136329800E+00, -.232771532399543E+00, 0.200887673646232E-02, 0.300590794496799E-01, 0.383606470976431E+00, 0.349676269655079E+00, 0.666306373868558E-02, -.347242488646652E+00, -.165771309070485E+00, 0.349676269654910E+00, 0.666306373869141E-02, 0.317183409197188E+00, -.217835161906151E+00, 0.349676269654956E+00, 0.666306373867523E-02, -.352982441311086E-01, 0.506449235044572E+00, 0.271798856540911E+00, 0.460737122110414E-02, -.420948781210288E+00, -.283793793648819E+00, 0.271798856540994E+00, 0.460737122109711E-02, 0.456247025341450E+00, -.222655441395830E+00, 0.271798856540755E+00, 0.460737122109625E-02, -.715353708088888E+00, -.278605040267896E+00, -.387412868821165E+00, 0.256268951692279E-02, 0.598955896538828E+00, -.480211963762482E+00, -.387412868821213E+00, 0.256268951691948E-02, 0.116397811550130E+00, 0.758817004030299E+00, -.387412868821203E+00, 0.256268951691991E-02, 0.371051945602552E-02, -.539347646199226E+00, -.378314593714867E+00, 0.235005654447042E-02, 0.465233503351929E+00, 0.272887227209696E+00, -.378314593714866E+00, 0.235005654446923E-02, -.468944022807853E+00, 0.266460418989514E+00, -.378314593714884E+00, 0.235005654447035E-02, -.359916057535362E-01, -.203223368274530E+00, -.390805436342884E+00, 0.527052754118289E-02, 0.193992402445282E+00, 0.704420392315130E-01, -.390805436342852E+00, 0.527052754118820E-02, -.158000796691468E+00, 0.132781329042865E+00, -.390805436342852E+00, 0.527052754118752E-02, -.216153735984865E-01, -.323838377680154E+00, 0.221462113265870E+00, 0.714961366974697E-02, 0.291259948590594E+00, 0.143199726191490E+00, 0.221462113265889E+00, 0.714961366974774E-02, -.269644574992100E+00, 0.180638651488654E+00, 0.221462113265882E+00, 0.714961366974817E-02, -.491357307496588E+00, 0.193872320289677E-01, -.533215602674804E-01, 0.448845818235097E-02, 0.228888818302316E+00, -.435221526641670E+00, -.533215602674484E-01, 0.448845818234801E-02, 0.262468489194418E+00, 0.415834294612734E+00, -.533215602674526E-01, 0.448845818235013E-02, -.142628109882219E+00, 0.442438151760315E+00, -.136612672009748E+00, 0.108071845189417E-01, -.311848624086726E+00, -.344738642331984E+00, -.136612672009748E+00, 0.108071845189381E-01, 0.454476733969026E+00, -.976995094284715E-01, -.136612672009781E+00, 0.108071845189454E-01, 0.761875476381042E+00, -.275635240194294E+00, -.340571881592319E+00, 0.293227202050287E-02, -.142230618004072E+00, 0.797621137163424E+00, -.340571881592331E+00, 0.293227202050352E-02, -.619644858376870E+00, -.521985896969213E+00, -.340571881592377E+00, 0.293227202050308E-02, 0.577689788002780E-01, -.167839657889956E+00, 0.248215855875381E+00, 0.145445430335915E-01, 0.116468918095072E+00, 0.133949232136841E+00, 0.248215855875382E+00, 0.145445430335873E-01, -.174237896895506E+00, 0.338904257531623E-01, 0.248215855875340E+00, 0.145445430335903E-01, -.141471914229626E+00, 0.454574639911821E+00, 0.149307855052120E+00, 0.637963291334823E-02, -.322937228965002E+00, -.349805591600753E+00, 0.149307855052161E+00, 0.637963291335070E-02, 0.464409143194571E+00, -.104769048311047E+00, 0.149307855052182E+00, 0.637963291335052E-02, -.139825817032614E+00, 0.669493017476507E+00, -.124686100142567E+00, 0.437334200450381E-02, -.509885052274530E+00, -.455839218393426E+00, -.124686100142531E+00, 0.437334200449979E-02, 0.649710869307182E+00, -.213653799083052E+00, -.124686100142451E+00, 0.437334200450373E-02, 0.361031892137155E+00, -.330220034803623E+00, -.880409067166617E-01, 0.120346556615560E-01, 0.105462992909919E+00, 0.477772807568843E+00, -.880409067166118E-01, 0.120346556615633E-01, -.466494885047039E+00, -.147552772765385E+00, -.880409067164646E-01, 0.120346556615583E-01, 0.245901346521248E-01, 0.814663848466296E+00, -.290390441652983E+00, 0.521154166200869E-02, -.717814655642789E+00, -.386036242942058E+00, -.290390441652948E+00, 0.521154166200641E-02, 0.693224520990723E+00, -.428627605524495E+00, -.290390441653070E+00, 0.521154166200487E-02, -.106559514117573E-01, 0.107045377333378E+01, -.358871681151519E+00, 0.613289703460351E-03, -.921712185578031E+00, -.544455211290932E+00, -.358871681151507E+00, 0.613289703461410E-03, 0.932368136989749E+00, -.525998562042731E+00, -.358871681151508E+00, 0.613289703462290E-03, -.411528552887236E+00, -.705388131299747E-01, 0.174864964482491E+00, 0.861854803007364E-02, 0.266852680566911E+00, -.321124774617904E+00, 0.174864964482526E+00, 0.861854803008962E-02, 0.144675872320202E+00, 0.391663587747994E+00, 0.174864964482476E+00, 0.861854803008200E-02, 0.157119041239772E-02, 0.790237540364792E-01, 0.100562602248012E+01, 0.209967579380148E-02, -.692221737042301E-01, -.381511862069326E-01, 0.100562602248007E+01, 0.209967579380181E-02, 0.676509832917168E-01, -.408725678295113E-01, 0.100562602248031E+01, 0.209967579379976E-02, -.299118986162933E+00, 0.316528443913753E+00, -.608536384527786E-01, 0.782057398216375E-02, -.124562180368101E+00, -.417308862728220E+00, -.608536384527546E-01, 0.782057398216339E-02, 0.423681166531102E+00, 0.100780418814494E+00, -.608536384527534E-01, 0.782057398216470E-02, 0.387169643039315E+00, -.396828227141254E+00, -.290741621266202E+00, 0.878729001495772E-02, 0.150078504123429E+00, 0.533712860016693E+00, -.290741621266215E+00, 0.878729001495983E-02, -.537248147162582E+00, -.136884632875611E+00, -.290741621266106E+00, 0.878729001496600E-02, -.806488630034254E-01, 0.605968663231696E+00, -.292867504968554E+00, 0.892969489447894E-02, -.484459824754277E+00, -.372828295763188E+00, -.292867504968491E+00, 0.892969489447761E-02, 0.565108687757774E+00, -.233140367468673E+00, -.292867504968617E+00, 0.892969489447887E-02, 0.670560385399325E+00, -.853449033898829E-01, -.398619038406075E+00, 0.134935598366959E-02, -.261369338280503E+00, 0.623394780222222E+00, -.398619038406084E+00, 0.134935598366930E-02, -.409191047118684E+00, -.538049876832367E+00, -.398619038406107E+00, 0.134935598366793E-02, -.299491486116021E+00, 0.481774501202084E+00, -.276300502881569E+00, 0.531065986285393E-02, -.267483213878585E+00, -.500254485794690E+00, -.276300502881583E+00, 0.531065986285184E-02, 0.566974699994646E+00, 0.184799845924988E-01, -.276300502881531E+00, 0.531065986285218E-02, 0.451014797342889E-01, -.276848279538879E+00, -.317113237361796E-01, 0.167538404905949E-01, 0.217206903207561E+00, 0.177483166967532E+00, -.317113237361369E-01, 0.167538404905937E-01, -.262308382941846E+00, 0.993651125712726E-01, -.317113237361872E-01, 0.167538404905924E-01, -.249578549272405E+00, 0.384862064401038E+00, -.367007292465087E+00, 0.653851943197237E-02, -.208511050088074E+00, -.408572396110129E+00, -.367007292465082E+00, 0.653851943197069E-02, 0.458089599360516E+00, 0.237103317090649E-01, -.367007292465064E+00, 0.653851943197134E-02, 0.270750482848970E+00, 0.400432634198050E+00, -.391896680938777E+00, 0.390584400794776E-02, -.482160075144301E+00, 0.342604791349208E-01, -.391896680938754E+00, 0.390584400795171E-02, 0.211409592295448E+00, -.434693113333112E+00, -.391896680938769E+00, 0.390584400794846E-02, -.455428038451468E-01, 0.949665213040168E+00, -.394511292898214E+00, 0.126416696275215E-02, -.799662797660556E+00, -.514273831609544E+00, -.394511292898228E+00, 0.126416696275155E-02, 0.845205601505644E+00, -.435391381430545E+00, -.394511292898271E+00, 0.126416696275047E-02, 0.202967443013410E-01, 0.911716011790729E+00, -.168981382745051E+00, 0.196895355148754E-02, -.799717599398493E+00, -.438280509716333E+00, -.168981382745087E+00, 0.196895355148876E-02, 0.779420855097189E+00, -.473435502074434E+00, -.168981382745058E+00, 0.196895355148764E-02, 0.144175623644654E+00, 0.715286661071672E+00, -.198845636085639E+00, 0.425246913479433E-02, -.691544231298561E+00, -.232783577853110E+00, -.198845636085654E+00, 0.425246913479412E-02, 0.547368607654000E+00, -.482503083218601E+00, -.198845636085661E+00, 0.425246913479049E-02, 0.352817051875322E-01, 0.362038483159059E+00, -.358178896668777E+00, 0.950473780765503E-02, -.331175376157013E+00, -.150464388598384E+00, -.358178896668761E+00, 0.950473780765618E-02, 0.295893670969645E+00, -.211574094560774E+00, -.358178896668728E+00, 0.950473780765759E-02, -.782783570176244E-02, -.314187622250228E+00, -.265257062498191E+00, 0.144822041368009E-01, 0.276008380274198E+00, 0.150314706550668E+00, -.265257062498142E+00, 0.144822041368032E-01, -.268180544572431E+00, 0.163872915699448E+00, -.265257062498143E+00, 0.144822041368031E-01, 0.680665560696609E-01, 0.650432218392058E+00, 0.912765565119796E-01, 0.370575350803494E-02, -.597324102602245E+00, -.266268742491591E+00, 0.912765565119247E-01, 0.370575350803537E-02, 0.529257546532531E+00, -.384163475900498E+00, 0.912765565120003E-01, 0.370575350803248E-02, -.968506766523193E-01, -.204999708658188E+00, 0.471202702836115E+00, 0.102317707080299E-01, 0.225960293792512E+00, 0.186247079744668E-01, 0.471202702836177E+00, 0.102317707080322E-01, -.129109617140210E+00, 0.186375000683749E+00, 0.471202702836125E+00, 0.102317707080311E-01, -.100170803050395E-01, 0.655925920233165E+00, -.478910143480145E-01, 0.910628443182790E-02, -.563039969770092E+00, -.336638006132562E+00, -.478910143480221E-01, 0.910628443182588E-02, 0.573057050075142E+00, -.319287914100737E+00, -.478910143480866E-01, 0.910628443182793E-02, 0.346592027383442E-01, 0.185240882398687E+00, 0.556207159853704E+00, 0.100491352093832E-01, -.177752911345817E+00, -.626046911530188E-01, 0.556207159853647E+00, 0.100491352093899E-01, 0.143093708607631E+00, -.122636191245806E+00, 0.556207159853335E+00, 0.100491352093963E-01, 0.728526373455930E-01, 0.969327921121760E+00, -.366690241113186E+00, 0.121714286187474E-02, -.875888922961818E+00, -.421571725886872E+00, -.366690241113209E+00, 0.121714286187342E-02, 0.803036285616261E+00, -.547756195234916E+00, -.366690241113219E+00, 0.121714286187213E-02, 0.134338966391803E+00, -.475379303136392E+00, -.250008196830234E+00, 0.740968779705143E-02, 0.344521069753589E+00, 0.354030609181593E+00, -.250008196830256E+00, 0.740968779705232E-02, -.478860036145387E+00, 0.121348693954736E+00, -.250008196830276E+00, 0.740968779705109E-02, -.134832131321742E-01, -.125546521197851E+00, 0.795391078104131E+00, 0.452696575771365E-02, 0.115468083280197E+00, 0.510964555018097E-01, 0.795391078104172E+00, 0.452696575771131E-02, -.101984870147968E+00, 0.744500656960183E-01, 0.795391078104141E+00, 0.452696575771781E-02, -.517684899030174E-01, 0.304239398243767E+00, 0.124629565419234E+00, 0.186866632090050E-01, -.237594802759713E+00, -.196952526493478E+00, 0.124629565419238E+00, 0.186866632089992E-01, 0.289363292662701E+00, -.107286871750370E+00, 0.124629565419295E+00, 0.186866632090069E-01, 0.172920747285736E-01, 0.496851984411353E+00, 0.443078043912414E+00, 0.208819700591201E-02, -.438932477785245E+00, -.233450616206588E+00, 0.443078043912445E+00, 0.208819700590994E-02, 0.421640403056608E+00, -.263401368204719E+00, 0.443078043912564E+00, 0.208819700591018E-02, -.391479177516457E-02, 0.268959581722058E+00, -.178919068738941E+00, 0.176310626798592E-01, -.230968434474979E+00, -.137870099988916E+00, -.178919068738866E+00, 0.176310626798622E-01, 0.234883226250137E+00, -.131089481733252E+00, -.178919068738862E+00, 0.176310626798593E-01, -.688114413871859E+00, -.954115384882857E-01, -.362175327735890E+00, 0.201431501028147E-02, 0.426686023080969E+00, -.548218793879157E+00, -.362175327735869E+00, 0.201431501027980E-02, 0.261428390790936E+00, 0.643630332367427E+00, -.362175327735871E+00, 0.201431501028021E-02, 0.496097300628823E-02, 0.243946308989103E+00, 0.759020162517206E+00, 0.374440493250076E-02, -.213744187247167E+00, -.117676825843630E+00, 0.759020162517164E+00, 0.374440493250154E-02, 0.208783214240776E+00, -.126269483145421E+00, 0.759020162517327E+00, 0.374440493250375E-02, -.732500606524927E-01, 0.349382220565785E+00, 0.538509761972580E+00, 0.227479774987694E-02, -.265948848314349E+00, -.238127523636683E+00, 0.538509761972521E+00, 0.227479774987930E-02, 0.339198908966867E+00, -.111254696929119E+00, 0.538509761972401E+00, 0.227479774988148E-02, -.467850148968266E-01, 0.651738267999512E+00, -.403488986368024E+00, 0.241377177692592E-02, -.541029389257572E+00, -.366386145416827E+00, -.403488986367984E+00, 0.241377177692877E-02, 0.587814404154349E+00, -.285352122582576E+00, -.403488986368072E+00, 0.241377177692253E-02, -.250040572172371E-01, 0.743479306138410E+00, 0.912948005084153E-01, 0.190144783329074E-02, -.631369937695251E+00, -.393393801816990E+00, 0.912948005084432E-01, 0.190144783329102E-02, 0.656373994912421E+00, -.350085504321367E+00, 0.912948005085045E-01, 0.190144783329226E-02, 0.136419956819384E+00, 0.267208504565108E+00, 0.507647600801933E+00, 0.302173714299617E-02, -.299619331470269E+00, -.154611040937976E-01, 0.507647600802004E+00, 0.302173714299884E-02, 0.163199374650976E+00, -.251747400471351E+00, 0.507647600801948E+00, 0.302173714299261E-02, 0.119874370298418E-12, -.619596764254606E-13, 0.758768636091968E+00, 0.813775298509852E-02, -.766297986304656E-13, 0.300237038819369E-13, 0.117406440316567E+01, 0.233872708824947E-03, -.482966202439009E-14, -.545779497913239E-13, -.291758813125291E+00, 0.160331113356838E-01, -.211105082999440E-13, 0.116449404211565E-12, 0.407285051280602E+00, 0.132371678104456E-01, -.127067102529756E-13, 0.312328335528596E-13, -.273797565167698E-02, 0.243467656337569E-01 ]; % NodeSet 14 177 TN2012_14 = [ % 177*4 -.575242283584180E+00, -.166133260583219E+00, -.300240841982295E+00, 0.407311106084951E-02, 0.431496765869180E+00, -.415107800624731E+00, -.300240841983309E+00, 0.407311106086412E-02, 0.143745517713982E+00, 0.581241061205346E+00, -.300240841983382E+00, 0.407311106089195E-02, -.330307698415517E+00, -.371209730161657E+00, -.236724353750048E+00, 0.631649202580972E-02, 0.486630905659552E+00, -.100449992815378E+00, -.236724353745667E+00, 0.631649202580268E-02, -.156323207242951E+00, 0.471659722975369E+00, -.236724353747098E+00, 0.631649202577768E-02, -.577016879846576E-02, 0.813563937154318E+00, -.112487413931976E-01, 0.146798867817842E-02, -.701681952778111E+00, -.411779081339492E+00, -.112487413914112E-01, 0.146798867823839E-02, 0.707452121577043E+00, -.401784855813232E+00, -.112487413918339E-01, 0.146798867814492E-02, -.303241671041222E+00, 0.445263691118857E+00, -.209120049193934E+00, 0.347291066290810E-02, -.233988832370200E+00, -.485246836167482E+00, -.209120049195121E+00, 0.347291066292713E-02, 0.537230503410457E+00, 0.399831450516860E-01, -.209120049194357E+00, 0.347291066293482E-02, 0.299584052599151E+00, 0.326484019886960E+00, -.387107016955792E+00, 0.327576451412751E-02, -.432535481452004E+00, 0.962053901756467E-01, -.387107016955722E+00, 0.327576451413050E-02, 0.132951428853400E+00, -.422689410063099E+00, -.387107016956188E+00, 0.327576451411143E-02, 0.231397850894255E+00, -.867100792961791E-01, 0.157675820557768E+00, 0.104553969408172E-01, -.406057940119166E-01, 0.243751456904555E+00, 0.157675820555718E+00, 0.104553969408347E-01, -.190792056880618E+00, -.157041377608727E+00, 0.157675820555330E+00, 0.104553969407382E-01, 0.119845996969304E+00, 0.564161674354201E+00, -.380499446663667E+00, 0.364986777096763E-02, -.548501340317717E+00, -.178291159259750E+00, -.380499446663128E+00, 0.364986777100916E-02, 0.428655343349320E+00, -.385870515093983E+00, -.380499446663405E+00, 0.364986777098790E-02, -.422306701845329E+00, 0.694637725684425E-02, -.256678512678140E+00, 0.806153706545878E-02, 0.205137611754242E+00, -.369201520613540E+00, -.256678512679293E+00, 0.806153706540727E-02, 0.217169090090457E+00, 0.362255143357407E+00, -.256678512678298E+00, 0.806153706547674E-02, -.199555205948733E+00, 0.500456231209974E+00, -.755044562352760E-02, 0.285738806924658E-02, -.333630206736558E+00, -.423047993414315E+00, -.755044562555918E-02, 0.285738806927622E-02, 0.533185412684041E+00, -.774082377944085E-01, -.755044562511435E-02, 0.285738806927797E-02, -.336236777595752E-02, 0.242407987544824E+00, 0.396668527152103E+00, 0.858697993389976E-02, -.208250291406449E+00, -.124115889683323E+00, 0.396668527146944E+00, 0.858697993385280E-02, 0.211612659183041E+00, -.118292097862163E+00, 0.396668527153668E+00, 0.858697993390625E-02, 0.390178919684306E+00, -.224793732281383E+00, 0.543629536874658E+00, 0.947585609194325E-03, -.412377074887698E-03, 0.450301722606289E+00, 0.543629536877204E+00, 0.947585609204924E-03, -.389766542603637E+00, -.225507990323973E+00, 0.543629536882427E+00, 0.947585609222194E-03, 0.544047552181209E-02, 0.651802390266920E+00, 0.210853397269185E+00, 0.194662998140932E-02, -.567197665975727E+00, -.321189605120733E+00, 0.210853397275583E+00, 0.194662998140232E-02, 0.561757190459366E+00, -.330612785144309E+00, 0.210853397266453E+00, 0.194662998141354E-02, 0.510990300967582E-01, 0.988055775141073E+00, -.384622763256674E+00, 0.941442850774455E-03, -.881230916676707E+00, -.449774829398800E+00, -.384622763256372E+00, 0.941442850786117E-03, 0.830131886579852E+00, -.538280945742860E+00, -.384622763257077E+00, 0.941442850768811E-03, -.333403339645188E+00, 0.248487410268569E+00, 0.432019915692715E-01, 0.189817372694094E-02, -.484947399918173E-01, -.412979466974262E+00, 0.432019915686436E-01, 0.189817372692919E-02, 0.381898079633772E+00, 0.164492056708287E+00, 0.432019915722213E-01, 0.189817372688908E-02, 0.296720921714769E+00, -.178610160343121E+00, -.394255226103660E+00, 0.358472221400519E-02, 0.632047537306693E-02, 0.346272936211606E+00, -.394255226103611E+00, 0.358472221400298E-02, -.303041397090647E+00, -.167662775869139E+00, -.394255226103512E+00, 0.358472221401662E-02, 0.394708154053029E+00, 0.115993706074013E+00, -.290082372165631E+00, 0.773951746082833E-02, -.297807573165452E+00, 0.283830435453547E+00, -.290082372165407E+00, 0.773951746077951E-02, -.969005808834108E-01, -.399824141528047E+00, -.290082372165008E+00, 0.773951746070415E-02, 0.460227742541093E+00, 0.332041729449580E-01, -.400195470090810E+00, 0.192176084759634E-02, -.258869528551988E+00, 0.381966830094237E+00, -.400195470090222E+00, 0.192176084765180E-02, -.201358213989841E+00, -.415171003039598E+00, -.400195470089365E+00, 0.192176084769918E-02, 0.432020401344211E+00, -.498688417766836E+00, -.251459996699954E+00, 0.359141808167828E-02, 0.215866637686716E+00, 0.623484851400748E+00, -.251459996700175E+00, 0.359141808170410E-02, -.647887039030433E+00, -.124796433632328E+00, -.251459996700565E+00, 0.359141808169343E-02, 0.324350258804347E-02, 0.939598309554684E+00, -.205299346524922E+00, 0.163835774237929E-02, -.815337756722135E+00, -.466990199139287E+00, -.205299346526383E+00, 0.163835774238299E-02, 0.812094254131555E+00, -.472608110414891E+00, -.205299346522325E+00, 0.163835774239529E-02, -.292963974805897E+00, 0.123680175760901E+00, 0.294659474040601E+00, 0.372396860339681E-02, 0.393718132485005E-01, -.315554332455396E+00, 0.294659474041647E+00, 0.372396860343135E-02, 0.253592161555488E+00, 0.191874156694664E+00, 0.294659474042561E+00, 0.372396860340175E-02, -.291171236420790E+00, -.345588148418140E+00, -.579522686235738E-01, 0.986772173845936E-02, 0.444873733985901E+00, -.793676133807912E-01, -.579522686212165E-01, 0.986772173839348E-02, -.153702497567287E+00, 0.424955761799258E+00, -.579522686218909E-01, 0.986772173843421E-02, 0.377057762840246E+00, 0.309639391945564E+00, -.221215714449003E+00, 0.511418213201809E-02, -.456684460855543E+00, 0.171721905344289E+00, -.221215714449280E+00, 0.511418213203137E-02, 0.796266980160928E-01, -.481361297286375E+00, -.221215714448616E+00, 0.511418213204769E-02, -.734356843870207E-03, 0.698468651280787E-01, 0.103191504161762E+01, 0.148408055902508E-02, -.601219811521234E-01, -.355594042455063E-01, 0.103191504162137E+01, 0.148408055898773E-02, 0.608563379984996E-01, -.342874608822615E-01, 0.103191504161585E+01, 0.148408055903742E-02, -.786061244475154E+00, -.362810988466514E+00, -.284366470168081E+00, 0.289589802390020E-02, 0.707234155023705E+00, -.499343512413032E+00, -.284366470169136E+00, 0.289589802389795E-02, 0.788270894528871E-01, 0.862154500880184E+00, -.284366470168453E+00, 0.289589802389629E-02, -.179807943025799E+00, 0.763907312527733E+00, -.391663270955190E+00, 0.142400302631111E-02, -.571659167272307E+00, -.537671902726336E+00, -.391663270955074E+00, 0.142400302631816E-02, 0.751467110298568E+00, -.226235409801304E+00, -.391663270955000E+00, 0.142400302631990E-02, 0.234912174928423E-01, 0.330303232304993E+00, -.585340450356535E-01, 0.141866307556572E-01, -.297796598875667E+00, -.144807625037826E+00, -.585340450333672E-01, 0.141866307556615E-01, 0.274305381381167E+00, -.185495607266993E+00, -.585340450347141E-01, 0.141866307557038E-01, -.350818590031590E+00, -.208653955178107E+00, 0.434903259331463E+00, 0.539971419326250E-02, 0.356108920801636E+00, -.199490833498607E+00, 0.434903259331847E+00, 0.539971419319880E-02, -.529033076836162E-02, 0.408144788676786E+00, 0.434903259332148E+00, 0.539971419323761E-02, -.479999707057395E+00, -.102130793619860E+00, -.716646932020444E-01, 0.946900966745673E-02, 0.328447715310549E+00, -.364626543310714E+00, -.716646932031980E-01, 0.946900966753316E-02, 0.151551991745061E+00, 0.466757336930631E+00, -.716646932016664E-01, 0.946900966753050E-02, 0.550374936239566E+00, -.174924988222624E+00, -.365102007850781E+00, 0.514867007981190E-02, -.123697984561225E+00, 0.564101170503260E+00, -.365102007850920E+00, 0.514867007976846E-02, -.426676951679799E+00, -.389176182278205E+00, -.365102007851096E+00, 0.514867007970910E-02, -.116091399601824E+00, -.736998279723331E-01, 0.666674160835910E+00, 0.692917641087077E-02, 0.121871623076646E+00, -.636881872281037E-01, 0.666674160842752E+00, 0.692917641083534E-02, -.578022347846076E-02, 0.137388015200055E+00, 0.666674160841551E+00, 0.692917641083512E-02, -.179596619245613E+00, 0.689296401321286E+00, -.285060798024655E+00, 0.384786348087887E-02, -.507149884659416E+00, -.500183435361117E+00, -.285060798024677E+00, 0.384786348087703E-02, 0.686746503903723E+00, -.189112965959864E+00, -.285060798023968E+00, 0.384786348091793E-02, -.473131159616946E-02, 0.798252844734476E+00, -.376713904904150E+00, 0.341675933601673E-02, -.688941586384925E+00, -.403223858402992E+00, -.376713904904145E+00, 0.341675933602221E-02, 0.693672897981391E+00, -.395028986330868E+00, -.376713904904146E+00, 0.341675933602166E-02, 0.183801975582644E+00, 0.750015934305411E+00, -.384732311329371E+00, 0.185506742588904E-02, -.741433840143401E+00, -.215830787033148E+00, -.384732311329466E+00, 0.185506742588527E-02, 0.557631864560502E+00, -.534185147273039E+00, -.384732311329474E+00, 0.185506742588539E-02, -.315748277890409E+00, 0.168599598023018E+00, -.143071179101490E-01, 0.108203755560910E-01, 0.118626039881620E-01, -.357745828865578E+00, -.143071179097027E-01, 0.108203755561398E-01, 0.303885673901511E+00, 0.189146230843338E+00, -.143071179104198E-01, 0.108203755560971E-01, -.376015684493240E+00, -.754120415611064E-01, 0.222689343484614E+00, 0.906808701359823E-02, 0.253316585990410E+00, -.287933114212501E+00, 0.222689343484401E+00, 0.906808701356199E-02, 0.122699098503781E+00, 0.363345155772191E+00, 0.222689343484860E+00, 0.906808701357411E-02, 0.313284788743724E-01, -.199122996930348E+00, 0.186136871843591E+00, 0.138609762453174E-01, 0.156781334383015E+00, 0.126692757030961E+00, 0.186136871841625E+00, 0.138609762453567E-01, -.188109813255554E+00, 0.724302398995938E-01, 0.186136871843113E+00, 0.138609762453960E-01, -.594039828858582E+00, -.438423888774048E+00, -.107279562274995E+00, 0.456878927721502E-02, 0.676706139733047E+00, -.295241638264149E+00, -.107279562274549E+00, 0.456878927727467E-02, -.826663108750434E-01, 0.733665527037704E+00, -.107279562274855E+00, 0.456878927726143E-02, 0.579906374949189E+00, -.424363651310160E+00, -.648551694854795E-01, 0.464900158014659E-02, 0.775565150022491E-01, 0.714395478178690E+00, -.648551694856163E-01, 0.464900158010975E-02, -.657462889952257E+00, -.290031826867551E+00, -.648551694856968E-01, 0.464900158010665E-02, 0.195928853192363E+00, -.216361578531986E+00, 0.572562269345945E+00, 0.326622940781702E-02, 0.894101968154995E-01, 0.277860153464154E+00, 0.572562269347270E+00, 0.326622940780099E-02, -.285339050008115E+00, -.614985749335604E-01, 0.572562269346011E+00, 0.326622940781070E-02, 0.293847693490531E+00, -.171985278472679E+00, -.279108711226420E+00, 0.124729622108709E-01, 0.201977348840127E-02, 0.340472206642557E+00, -.279108711226616E+00, 0.124729622108673E-01, -.295867466979937E+00, -.168486928169786E+00, -.279108711225454E+00, 0.124729622109326E-01, 0.365502052532130E+00, 0.437394577048286E+00, -.371415437111150E+00, 0.267294138131050E-02, -.561545841467734E+00, 0.978367741037638E-01, -.371415437111249E+00, 0.267294138129828E-02, 0.196043788935523E+00, -.535231351152352E+00, -.371415437111085E+00, 0.267294138131039E-02, -.570659524572094E-01, 0.923818279609940E+00, -.316173841712837E+00, 0.247104884668795E-02, -.771517122393903E+00, -.511329704323859E+00, -.316173841712279E+00, 0.247104884666643E-02, 0.828583074852206E+00, -.412488575286835E+00, -.316173841713480E+00, 0.247104884669676E-02, 0.101152805721060E+00, 0.630551067591309E-01, 0.837327710042496E+00, 0.296404318850117E-02, -.105183727153304E+00, 0.560733460392890E-01, 0.837327710042566E+00, 0.296404318841329E-02, 0.403092143123203E-02, -.119128452798902E+00, 0.837327710042031E+00, 0.296404318845359E-02, -.212419725843974E+00, -.293637332571483E+00, 0.249887391854507E+00, 0.860843027377963E-02, 0.360507252427238E+00, -.371422125585314E-01, 0.249887391855293E+00, 0.860843027375037E-02, -.148087526584551E+00, 0.330779545130526E+00, 0.249887391855666E+00, 0.860843027377383E-02, -.165178219962910E+00, 0.862687098105019E-01, 0.510890414043656E+00, 0.876808189201044E-02, 0.787821573356979E-02, -.186182889544598E+00, 0.510890414043511E+00, 0.876808189200772E-02, 0.157300004228448E+00, 0.999141797342290E-01, 0.510890414043504E+00, 0.876808189201718E-02, -.361792752561076E+00, 0.440883726379541E+00, -.370614775674016E+00, 0.290438401248579E-02, -.200920130878983E+00, -.533763577812893E+00, -.370614775674052E+00, 0.290438401246964E-02, 0.562712883440469E+00, 0.928798514331573E-01, -.370614775674048E+00, 0.290438401247830E-02, -.501582060028134E+00, -.189017523532352E+00, 0.243300456027558E+00, 0.214700460048371E-02, 0.414485007154890E+00, -.339874044299363E+00, 0.243300456030077E+00, 0.214700460050576E-02, 0.870970528739568E-01, 0.528891567831824E+00, 0.243300456029155E+00, 0.214700460053189E-02, 0.943406837211783E+00, -.549830207760000E+00, -.353870254501487E+00, 0.288727982779534E-03, 0.446350908212159E-02, 0.109192939101015E+01, -.353870254502128E+00, 0.288727982772595E-03, -.947870346296031E+00, -.542099183250677E+00, -.353870254502452E+00, 0.288727982759760E-03, 0.200575172082975E+00, 0.108858729355023E+00, -.358265174400078E+00, 0.890647160456436E-02, -.194562011087352E+00, 0.119273829713901E+00, -.358265174399951E+00, 0.890647160456416E-02, -.601316099752385E-02, -.228132559069674E+00, -.358265174400086E+00, 0.890647160457989E-02, -.125565833845857E-01, 0.546993463921740E+00, 0.875506297144548E-01, 0.949936126258408E-02, -.467431943769019E+00, -.284371052157281E+00, 0.875506297145599E-01, 0.949936126256084E-02, 0.479988527151917E+00, -.262622411764873E+00, 0.875506297137920E-01, 0.949936126260162E-02, -.171690873716897E-01, -.216015130934396E+00, -.139730799812637E+00, 0.168769172486876E-01, 0.195659134676586E+00, 0.931386996440844E-01, -.139730799812326E+00, 0.168769172486957E-01, -.178490047305620E+00, 0.122876431289901E+00, -.139730799812474E+00, 0.168769172486963E-01, -.546275791578987E-03, 0.667828701294578E+00, -.218376112477418E+00, 0.948331095626193E-02, -.578083482801784E+00, -.334387439360658E+00, -.218376112477213E+00, 0.948331095626163E-02, 0.578629758593253E+00, -.333441261934690E+00, -.218376112477671E+00, 0.948331095627096E-02, -.183387701321059E+00, -.219539988831699E+00, 0.576350781636215E+00, 0.291801565831253E-02, 0.281821058134979E+00, -.490484136690603E-01, 0.576350781636874E+00, 0.291801565829244E-02, -.984333568143726E-01, 0.268588402501900E+00, 0.576350781636510E+00, 0.291801565827458E-02, 0.191661789507546E+00, -.109745450674066E+00, 0.806220842543315E+00, 0.270440540659129E-02, -.788546520336479E-03, 0.220856703983877E+00, 0.806220842545406E+00, 0.270440540658569E-02, -.190873242983517E+00, -.111111253309189E+00, 0.806220842548502E+00, 0.270440540661825E-02, -.481389123117500E-01, 0.102301268899185E+01, -.404965878434928E+00, 0.364445038290711E-03, -.861885520903912E+00, -.553195865468262E+00, -.404965878433795E+00, 0.364445038304032E-03, 0.910024433217974E+00, -.469816823523960E+00, -.404965878436118E+00, 0.364445038271510E-03, -.442446287170860E+00, -.348710568478134E+00, 0.222570681379663E+00, 0.212760250081768E-02, 0.523215354454083E+00, -.208814440260071E+00, 0.222570681379047E+00, 0.212760250089270E-02, -.807690672840585E-01, 0.557525008738729E+00, 0.222570681380127E+00, 0.212760250085897E-02, 0.233016466910397E+00, 0.458660430488394E+00, -.409672523946633E-02, 0.245758502593965E-02, -.513719817967670E+00, -.275320353974866E-01, -.409672524092190E-02, 0.245758502598051E-02, 0.280703351056490E+00, -.431128395087878E+00, -.409672523825050E-02, 0.245758502598958E-02, 0.396708065400329E-12, 0.142484953050341E-12, -.259244781008597E+00, 0.140379841702619E-01, 0.172242545847118E-11, 0.416320752022618E-12, 0.119114912174165E+01, 0.125045207771754E-03, 0.350241037314071E-12, 0.256440763467915E-12, 0.412065312751145E+00, 0.152916747668899E-01, -.294794246186653E-11, -.948925382567767E-12, 0.843526260134419E+00, 0.448751025261868E-02, -.103209102664440E-11, 0.572570760190481E-12, -.400363967338670E+00, 0.271147435356790E-02, -.435939356582035E-12, -.430785817780272E-12, 0.332100254506089E-01, 0.179783863072324E-01 ]; % NodeSet 15 214 TN2012_15 = [ % 214*4 0.258152119478843E+00, 0.304175382366057E+00, 0.114941536929827E+00, 0.249094171140855E-02, -.392499668074282E+00, 0.714786023264670E-01, 0.114941536929798E+00, 0.249094171140690E-02, 0.134347548595462E+00, -.375653984692530E+00, 0.114941536929772E+00, 0.249094171140722E-02, 0.174793662760004E+00, 0.343502512582010E+00, -.142514196488796E+00, 0.652868546942704E-02, -.384878733539857E+00, -.203755039203169E-01, -.142514196488753E+00, 0.652868546942395E-02, 0.210085070779848E+00, -.323127008661698E+00, -.142514196488787E+00, 0.652868546942618E-02, -.268615838548664E+00, -.209746805323262E+00, -.389739165020216E+00, 0.299603045409476E-02, 0.315953981046930E+00, -.127754737380383E+00, -.389739165020212E+00, 0.299603045409517E-02, -.473381424982375E-01, 0.337501542703614E+00, -.389739165020218E+00, 0.299603045409458E-02, 0.535680841576558E-02, 0.968947530543105E-01, 0.742528316718603E+00, 0.431794709527661E-02, -.865917218463591E-01, -.438082443558939E-01, 0.742528316718619E+00, 0.431794709527601E-02, 0.812349134305405E-01, -.530865086984093E-01, 0.742528316718614E+00, 0.431794709527687E-02, -.814463113484512E+00, -.507805620316222E+00, -.285611224208266E+00, 0.115071789816229E-02, 0.847004124120622E+00, -.451442936564845E+00, -.285611224208270E+00, 0.115071789816230E-02, -.325410106361014E-01, 0.959248556881068E+00, -.285611224208257E+00, 0.115071789816246E-02, 0.224935844193548E+00, 0.715768558382950E+00, -.389186754644429E+00, 0.812146724356807E-03, -.732341676886575E+00, -.163084123898153E+00, -.389186754644439E+00, 0.812146724356529E-03, 0.507405832693028E+00, -.552684434484796E+00, -.389186754644434E+00, 0.812146724356482E-03, -.547357038434130E+00, -.243235419738212E+00, 0.184732558232411E+00, 0.181330436451233E-02, 0.484326571810546E+00, -.352407390355058E+00, 0.184732558232403E+00, 0.181330436451273E-02, 0.630304666235898E-01, 0.595642810093306E+00, 0.184732558232408E+00, 0.181330436451180E-02, -.237879144231129E-01, 0.246550698911715E+00, 0.580270468252207E+00, 0.414087152453678E-02, -.201625211366817E+00, -.143876287649317E+00, 0.580270468252226E+00, 0.414087152453607E-02, 0.225413125789895E+00, -.102674411262402E+00, 0.580270468252234E+00, 0.414087152453595E-02, -.739187181924076E-01, -.547727077011690E+00, -.391441391104918E+00, 0.100666812186601E-02, 0.511304922128929E+00, 0.209848050736021E+00, -.391441391104914E+00, 0.100666812186624E-02, -.437386203936511E+00, 0.337879026275675E+00, -.391441391104921E+00, 0.100666812186573E-02, -.296800453069907E+00, 0.321721626441848E-01, 0.406150067393071E+00, 0.281295627235464E-02, 0.120538316390380E+00, -.273122813535342E+00, 0.406150067393110E+00, 0.281295627235580E-02, 0.176262136679499E+00, 0.240950650891170E+00, 0.406150067393085E+00, 0.281295627235510E-02, -.424109825534735E-02, 0.416431076208372E+00, 0.580863239140085E+00, 0.964358972918426E-03, -.358519341794062E+00, -.211888436933256E+00, 0.580863239140087E+00, 0.964358972918691E-03, 0.362760440049413E+00, -.204542639275101E+00, 0.580863239140103E+00, 0.964358972918272E-03, 0.420238636403193E-02, -.208941903277785E-01, 0.112230077847980E+01, 0.288213892537120E-03, 0.159937064333278E-01, 0.140864685116470E-01, 0.112230077847979E+01, 0.288213892537525E-03, -.201960927973878E-01, 0.680772181611991E-02, 0.112230077847980E+01, 0.288213892536919E-03, -.538855127386786E-01, 0.841520524077910E+00, -.170238260141001E+00, 0.202238868092459E-02, -.701835395288124E+00, -.467426484966598E+00, -.170238260140992E+00, 0.202238868092480E-02, 0.755720908026795E+00, -.374094039111304E+00, -.170238260140987E+00, 0.202238868092491E-02, 0.364602780629829E-01, 0.711452204819021E+00, -.292851721446071E-01, 0.342986352626608E-02, -.634365821983225E+00, -.324150575377920E+00, -.292851721446072E-01, 0.342986352626522E-02, 0.597905543920261E+00, -.387301629441103E+00, -.292851721446004E-01, 0.342986352626463E-02, 0.125850346682288E-01, -.283649922521734E+00, -.237863927191367E-01, 0.956695562971094E-02, 0.239355521351163E+00, 0.152723920991028E+00, -.237863927191305E-01, 0.956695562971296E-02, -.251940556019402E+00, 0.130926001530681E+00, -.237863927191544E-01, 0.956695562971111E-02, 0.385162531779287E-02, -.179377244818765E+00, -.387600248278067E+00, 0.433604548796903E-02, 0.153419438215009E+00, 0.930242277804360E-01, -.387600248278066E+00, 0.433604548796935E-02, -.157271063532833E+00, 0.863530170383109E-01, -.387600248278063E+00, 0.433604548796941E-02, -.348530140993749E-02, -.185028244536387E+00, -.157327640046718E+00, 0.103356064299359E-01, 0.161981810891139E+00, 0.894957627073358E-01, -.157327640046750E+00, 0.103356064299294E-01, -.158496509481226E+00, 0.955324818290217E-01, -.157327640046750E+00, 0.103356064299327E-01, 0.530463511464713E-01, -.440073176598083E+00, -.984667765940366E-01, 0.423558626963751E-02, 0.354591374884810E+00, 0.265976075969954E+00, -.984667765940141E-01, 0.423558626963793E-02, -.407637726031304E+00, 0.174097100628107E+00, -.984667765940299E-01, 0.423558626963730E-02, 0.665392854648627E-01, 0.239078964888139E+00, 0.419574950888795E+00, 0.681046506781639E-02, -.240318099836065E+00, -.619147708818347E-01, 0.419574950888812E+00, 0.681046506781542E-02, 0.173778814371207E+00, -.177164194006293E+00, 0.419574950888816E+00, 0.681046506781649E-02, -.166734893106253E+00, 0.409621014869640E+00, 0.169870647828065E+00, 0.397039820954813E-02, -.271374758247967E+00, -.349207160562124E+00, 0.169870647828042E+00, 0.397039820954811E-02, 0.438109651354205E+00, -.604138543075271E-01, 0.169870647828062E+00, 0.397039820954754E-02, 0.949353282231965E-01, -.569687711930257E-01, 0.100104563339689E+01, 0.808994059895755E-03, 0.186873896394871E-02, 0.110700791554415E+00, 0.100104563339690E+01, 0.808994059895714E-03, -.968040671871328E-01, -.537320203613814E-01, 0.100104563339690E+01, 0.808994059895808E-03, -.510598172246801E-01, -.345927815689831E+00, 0.127825298661453E+00, 0.552735908612229E-02, 0.325112184875413E+00, 0.128744809015723E+00, 0.127825298661432E+00, 0.552735908612158E-02, -.274052367650716E+00, 0.217183006674084E+00, 0.127825298661416E+00, 0.552735908612256E-02, -.208024528677348E-01, 0.184883929787422E+00, 0.669985129294430E-01, 0.115934884219135E-01, -.149712953513427E+00, -.110457417538084E+00, 0.669985129295205E-01, 0.115934884219225E-01, 0.170515406381284E+00, -.744265122493089E-01, 0.669985129294305E-01, 0.115934884219135E-01, 0.292178123870944E+00, -.328160490412648E+00, 0.188860305200578E+00, 0.475283519793602E-02, 0.138106259280221E+00, 0.417113922908688E+00, 0.188860305200536E+00, 0.475283519793658E-02, -.430284383151197E+00, -.889534324959835E-01, 0.188860305200515E+00, 0.475283519793719E-02, -.878090582800034E-01, -.257954966189383E+00, 0.416231911745254E+00, 0.442753455264511E-02, 0.267300082892351E+00, 0.529326079418328E-01, 0.416231911745271E+00, 0.442753455264529E-02, -.179491024612372E+00, 0.205022358247536E+00, 0.416231911745261E+00, 0.442753455264571E-02, -.194458745679973E-01, 0.337200394761511E+00, -.142937741910735E+00, 0.108023951109223E-01, -.282301170745611E+00, -.185440818755414E+00, -.142937741910703E+00, 0.108023951109241E-01, 0.301747045313629E+00, -.151759576006076E+00, -.142937741910730E+00, 0.108023951109209E-01, -.731343132041161E-01, 0.646898497210061E+00, 0.752675747660435E-01, 0.285875163245338E-02, -.523663375651827E+00, -.386785421728115E+00, 0.752675747660487E-01, 0.285875163245380E-02, 0.596797688855938E+00, -.260113075481936E+00, 0.752675747660478E-01, 0.285875163245399E-02, -.376250705244884E+00, -.114322556557385E+00, 0.550225974563751E-01, 0.869361992936774E-02, 0.287131590826730E+00, -.268681390655231E+00, 0.550225974563902E-01, 0.869361992936585E-02, 0.891191144181605E-01, 0.383003947212582E+00, 0.550225974563760E-01, 0.869361992936762E-02, -.379789627183864E-01, 0.558964475667290E+00, -.378364573029073E+00, 0.383799020167440E-02, -.465087954381758E+00, -.312372984357168E+00, -.378364573029073E+00, 0.383799020167453E-02, 0.503066917100135E+00, -.246591491310175E+00, -.378364573029073E+00, 0.383799020167383E-02, 0.275055549348987E-02, 0.838751807936127E+00, -.355785818698930E-01, 0.139738389542722E-02, -.727755650889547E+00, -.416993853036175E+00, -.355785818698781E-01, 0.139738389542723E-02, 0.725005095396073E+00, -.421757954899949E+00, -.355785818698916E-01, 0.139738389542685E-02, 0.612300613856560E+00, -.215796645511508E+00, -.118009477093553E+00, 0.489300425975968E-02, -.119264929863829E+00, 0.638166209108364E+00, -.118009477093543E+00, 0.489300425975965E-02, -.493035683992722E+00, -.422369563596831E+00, -.118009477093543E+00, 0.489300425975971E-02, -.264572722008943E+00, 0.352599331047574E+00, -.163748002755720E+00, 0.739653306113128E-02, -.173073617040117E+00, -.405426363931915E+00, -.163748002755722E+00, 0.739653306113081E-02, 0.437646339049050E+00, 0.528270328843696E-01, -.163748002755714E+00, 0.739653306113117E-02, -.663096245113129E-01, 0.241883469905418E+00, 0.297745486047570E+00, 0.102352430507446E-01, -.176322417437979E+00, -.178367554294907E+00, 0.297745486047582E+00, 0.102352430507444E-01, 0.242632041949263E+00, -.635159156104787E-01, 0.297745486047567E+00, 0.102352430507450E-01, -.420038409319059E-02, 0.628132240414236E+00, 0.259671260459846E+00, 0.169108162235348E-02, -.541878285088164E+00, -.317703759537470E+00, 0.259671260459853E+00, 0.169108162235353E-02, 0.546078669181359E+00, -.310428480876762E+00, 0.259671260459848E+00, 0.169108162235344E-02, 0.539466322852269E-01, -.205235432096071E+00, 0.227150892695586E+00, 0.106870368988479E-01, 0.150765781809271E+00, 0.149336870055697E+00, 0.227150892695555E+00, 0.106870368988450E-01, -.204712414094495E+00, 0.558985620404097E-01, 0.227150892695570E+00, 0.106870368988473E-01, 0.101817142699943E+00, 0.564065898953328E+00, -.277992617897413E+00, 0.672536035459299E-02, -.539403969252066E+00, -.193856717357776E+00, -.277992617897385E+00, 0.672536035459384E-02, 0.437586826552127E+00, -.370209181595563E+00, -.277992617897412E+00, 0.672536035459328E-02, 0.124551330130348E+00, 0.673513833840005E+00, -.382343277722446E+00, 0.285456723044317E-02, -.645555754970877E+00, -.228892300951980E+00, -.382343277722440E+00, 0.285456723044365E-02, 0.521004424840520E+00, -.444621532888043E+00, -.382343277722447E+00, 0.285456723044297E-02, -.985592955579921E-01, 0.919835388841061E+00, -.377538632244491E+00, 0.106650111993310E-02, -.747321166257303E+00, -.545272548152855E+00, -.377538632244493E+00, 0.106650111993292E-02, 0.845880461815294E+00, -.374562840688214E+00, -.377538632244494E+00, 0.106650111993302E-02, -.175538802028308E+00, 0.715516618290424E+00, -.282968862701148E+00, 0.278412463006544E-02, -.531886167255290E+00, -.509779371051619E+00, -.282968862701149E+00, 0.278412463006510E-02, 0.707424969283603E+00, -.205737247238819E+00, -.282968862701154E+00, 0.278412463006522E-02, -.626762915722012E-02, -.729636607140934E-01, 0.926665990273565E+00, 0.255134087803697E-02, 0.663221983101268E-01, 0.310539042853938E-01, 0.926665990273561E+00, 0.255134087803699E-02, -.600545691528989E-01, 0.419097564287068E-01, 0.926665990273564E+00, 0.255134087803706E-02, -.202338110826756E+00, -.956595869654207E-02, 0.704240870816491E+00, 0.237978659265236E-02, 0.109453418656134E+00, -.170446964781441E+00, 0.704240870816488E+00, 0.237978659265308E-02, 0.928846921706177E-01, 0.180012923477980E+00, 0.704240870816478E+00, 0.237978659265341E-02, -.647349974357924E-01, 0.410863325711682E+00, 0.411688404749235E+00, 0.367154580391546E-02, -.323450578831780E+00, -.261493815149158E+00, 0.411688404749230E+00, 0.367154580391558E-02, 0.388185576267567E+00, -.149369510562525E+00, 0.411688404749235E+00, 0.367154580391620E-02, -.123302554542721E+00, 0.401932094350526E+00, 0.119096478781894E-01, 0.943568869218895E-02, -.286432127032441E+00, -.307749191760741E+00, 0.119096478782083E-01, 0.943568869219145E-02, 0.409734681575188E+00, -.941829025897397E-01, 0.119096478781972E-01, 0.943568869218898E-02, 0.198964891452639E+00, 0.504535085060002E+00, -.982488629629035E-01, 0.567510405577512E-02, -.536422646488850E+00, -.799588920708283E-01, -.982488629629094E-01, 0.567510405577412E-02, 0.337457755036191E+00, -.424576192989211E+00, -.982488629629237E-01, 0.567510405577405E-02, 0.217899163019504E-01, 0.613986541715491E+00, -.121007693279375E+00, 0.757232155064711E-02, -.542622900858349E+00, -.288122649793941E+00, -.121007693279352E+00, 0.757232155064673E-02, 0.520832984556400E+00, -.325863891921567E+00, -.121007693279350E+00, 0.757232155064802E-02, -.201452305982941E+00, 0.241132309402656E+00, -.297032331707505E+00, 0.926123494364474E-02, -.108100552624428E+00, -.295028969333504E+00, -.297032331707505E+00, 0.926123494364532E-02, 0.309552858607363E+00, 0.538966599308800E-01, -.297032331707501E+00, 0.926123494364516E-02, -.116956783563120E-01, -.138782984589614E+00, 0.582806521460454E+00, 0.628310692395311E-02, 0.126037429445771E+00, 0.592627377237619E-01, 0.582806521460435E+00, 0.628310692395284E-02, -.114341751089492E+00, 0.795202468658380E-01, 0.582806521460469E+00, 0.628310692395237E-02, 0.682968101095060E-01, 0.295112105963141E+00, -.301787657090746E+00, 0.950431568825956E-02, -.289722985783184E+00, -.884092804293167E-01, -.301787657090743E+00, 0.950431568825956E-02, 0.221426175673652E+00, -.206702825533833E+00, -.301787657090740E+00, 0.950431568826002E-02, -.429817500306839E+00, 0.445269831351928E-02, -.386224427799053E+00, 0.402949656022401E-02, 0.211052600298496E+00, -.374459223413599E+00, -.386224427799051E+00, 0.402949656022447E-02, 0.218764900008327E+00, 0.370006525100060E+00, -.386224427799052E+00, 0.402949656022438E-02, 0.657830714907697E+00, -.170942391383753E+00, -.380434630448314E+00, 0.272052467007333E-02, -.180874903931861E+00, 0.655169306191617E+00, -.380434630448313E+00, 0.272052467007334E-02, -.476955810975839E+00, -.484226914807891E+00, -.380434630448313E+00, 0.272052467007346E-02, -.370463073663661E+00, -.156950196432308E+00, 0.461451866783806E+00, 0.337227207067558E-02, 0.321154394071181E+00, -.242355334740639E+00, 0.461451866783823E+00, 0.337227207067548E-02, 0.493086795924882E-01, 0.399305531172947E+00, 0.461451866783816E+00, 0.337227207067610E-02, -.119300551780856E+00, 0.530641871747840E+00, -.266456779653053E+00, 0.791030849914603E-02, -.399899065354920E+00, -.368638244401638E+00, -.266456779653046E+00, 0.791030849914697E-02, 0.519199617135777E+00, -.162003627346192E+00, -.266456779653057E+00, 0.791030849914647E-02, -.150452055510191E+00, -.428194345553231E+00, -.383444021066624E+00, 0.398525303397504E-02, 0.446053208761040E+00, 0.838018706532008E-01, -.383444021066623E+00, 0.398525303397513E-02, -.295601153250867E+00, 0.344392474900012E+00, -.383444021066624E+00, 0.398525303397507E-02, 0.197583005475362E+00, 0.660682468125869E+00, -.280966074583490E+00, 0.356670706908016E-02, -.670959303969691E+00, -.159229331965177E+00, -.280966074583505E+00, 0.356670706907958E-02, 0.473376298494327E+00, -.501453136160682E+00, -.280966074583498E+00, 0.356670706907986E-02, -.746313738874201E-02, 0.490647384618176E+00, 0.184322542332287E+00, 0.717150418477603E-02, -.421181530685369E+00, -.251786958879662E+00, 0.184322542332289E+00, 0.717150418477588E-02, 0.428644668074081E+00, -.238860425738493E+00, 0.184322542332287E+00, 0.717150418477665E-02, 0.204947320088601E-02, 0.232828740261373E+00, 0.794993174564848E+00, 0.189617098059473E-02, -.202660340397914E+00, -.114639474274342E+00, 0.794993174564868E+00, 0.189617098059435E-02, 0.200610867197031E+00, -.118189265987027E+00, 0.794993174564855E+00, 0.189617098059462E-02, 0.715208601019793E-01, 0.842335952518595E+00, -.229601950404950E+00, 0.287078796909986E-02, -.765244763453047E+00, -.359229094510459E+00, -.229601950404950E+00, 0.287078796910012E-02, 0.693723903351066E+00, -.483106858008123E+00, -.229601950404941E+00, 0.287078796909986E-02, 0.216683910538321E+00, -.524509738082016E+00, -.376887329718436E+00, 0.235922503173230E-02, 0.345896802442191E+00, 0.449908640158552E+00, -.376887329718438E+00, 0.235922503173207E-02, -.562580712980498E+00, 0.746010979234869E-01, -.376887329718435E+00, 0.235922503173239E-02, 0.127985393998401E+00, -.429747975001943E+00, -.277974239042955E+00, 0.761112189683938E-02, 0.308179966577416E+00, 0.325712590016963E+00, -.277974239042960E+00, 0.761112189683879E-02, -.436165360575796E+00, 0.104035384984987E+00, -.277974239042955E+00, 0.761112189683944E-02, -.157781237450556E-01, 0.800916121480509E+00, -.308819906524061E+00, 0.464793323114600E-02, -.685724645630099E+00, -.414122316727537E+00, -.308819906524060E+00, 0.464793323114599E-02, 0.701502769375151E+00, -.386793804752983E+00, -.308819906524051E+00, 0.464793323114606E-02, -.710599623094926E-03, 0.106591769485371E+01, -.381979997324513E+00, 0.627729148172063E-03, -.922756502275117E+00, -.533574244752375E+00, -.381979997324512E+00, 0.627729148172069E-03, 0.923467101898213E+00, -.532343450101338E+00, -.381979997324515E+00, 0.627729148171996E-03, -.188295544778347E-01, 0.858949317087156E+00, -.401536179522233E+00, 0.106299368117930E-02, -.734457151921867E+00, -.445781531063333E+00, -.401536179522234E+00, 0.106299368117924E-02, 0.753286706399686E+00, -.413167786023834E+00, -.401536179522228E+00, 0.106299368117947E-02, -.337521729934930E+00, 0.430628148626658E+00, -.304570712968866E+00, 0.406209681264780E-02, -.204174051327885E+00, -.507616466766249E+00, -.304570712968861E+00, 0.406209681264790E-02, 0.541695781262815E+00, 0.769883181395793E-01, -.304570712968855E+00, 0.406209681264795E-02, 0.499679503802184E+00, -.443492590565618E+00, -.390575549112483E-01, 0.134809639348428E-02, 0.134236097918917E+00, 0.654481439325934E+00, -.390575549112718E-01, 0.134809639348326E-02, -.633915601721120E+00, -.210988848760292E+00, -.390575549112678E-01, 0.134809639348292E-02, 0.759640879950688E+00, -.534956023308264E+00, -.372610878453242E+00, 0.150236562849430E-02, 0.834650661171134E-01, 0.925346311444593E+00, -.372610878453244E+00, 0.150236562849425E-02, -.843105946067801E+00, -.390390288136326E+00, -.372610878453243E+00, 0.150236562849425E-02, -.882002742703712E+00, -.490456722855413E+00, -.257599002612332E+00, 0.509335150374114E-03, 0.865749352801516E+00, -.518608419961260E+00, -.257599002612346E+00, 0.509335150374126E-03, 0.162533899022075E-01, 0.100906514281669E+01, -.257599002612343E+00, 0.509335150373880E-03, 0.706774233459675E+00, -.891533208596826E-01, -.395467447120577E+00, 0.457728775377536E-03, -.276178076033606E+00, 0.656661101346199E+00, -.395467447120577E+00, 0.457728775377498E-03, -.430596157426042E+00, -.567507780486533E+00, -.395467447120585E+00, 0.457728775377089E-03, -.918645944644083E-01, 0.190304232329775E+00, 0.715850885984145E+00, 0.168397478196152E-02, -.118876002413072E+00, -.174709188679419E+00, 0.715850885984146E+00, 0.168397478196167E-02, 0.210740596877476E+00, -.155950436503571E-01, 0.715850885984132E+00, 0.168397478196237E-02, 0.540513301252501E+00, -.943860862874218E-02, -.914318710054978E-01, 0.213070712463987E-02, -.262082575777379E+00, 0.472817554282433E+00, -.914318710054964E-01, 0.213070712463992E-02, -.278430725475103E+00, -.463378945653674E+00, -.914318710054968E-01, 0.213070712464070E-02, 0.145805941349524E+00, -.526334554268467E+00, -.263961054397257E+00, 0.146222435997457E-02, 0.382916124211298E+00, 0.389438926365626E+00, -.263961054397247E+00, 0.146222435997416E-02, -.528722065560796E+00, 0.136895627902853E+00, -.263961054397253E+00, 0.146222435997499E-02, -.182315800139201E-13, -.173834348867150E-14, -.300394380298934E+00, 0.106049995563824E-01, -.169910697181091E-13, -.249020633102366E-15, 0.427541621225973E+00, 0.136188175091050E-01, 0.156992255283360E-12, 0.102872783354632E-12, 0.145464511562067E+00, 0.887275759574957E-02, 0.535998565692471E-13, 0.781044393753285E-13, -.107279857079785E+00, 0.855159201414087E-02 ]; maptorst = true; switch N case 1 rstw = TN2012_1; case 2 rstw = TN2012_2; case 3 rstw = TN2012_3; case 4 rstw = TN2012_4; case 5 rstw = TN2012_5; case 6 rstw = TN2012_6; case 7 rstw = TN2012_7; case 8 rstw = TN2012_8; case 9 rstw = TN2012_9; case 10 rstw = TN2012_10; case 11 rstw = TN2012_11; case 12 rstw = TN2012_12; case 13 rstw = TN2012_13; case 14 rstw = TN2012_14; case 15 rstw = TN2012_15; otherwise % error('Quadrature degree too high.') [r s t w] = tet_cubature_TP(ceil(N/2)); rstw = [r(:) s(:) t(:) w(:)]; maptorst = false; end r = rstw(:,1); s = rstw(:,2); t = rstw(:,3); if maptorst [r s t] = xyztorst(r,s,t); end w = rstw(:,4); w = (4/3)*w/sum(w); % integrates order (2*N+1) function [r s t w] = tet_cubature_TP(N) [ra wa] = JacobiGQ(0,0,N); [rb wb] = JacobiGQ(1,0,N); [rc wc] = JacobiGQ(2,0,N); [a b c] = meshgrid(ra, rb, rc); [wa wb wc] = meshgrid(wa,wb,wc); a = a(:); b = b(:); c = c(:); wa = wa(:); wb = wb(:); wc = wc(:); w = wa.*wb.*wc; w = (4/3)*w/sum(w); [r s t] = tet_abctorst(a,b,c);
github
KGuo26/WADG_Matlab-master
ElasticityAcoustic2D_unified.m
.m
WADG_Matlab-master/ElasticityAcoustic2D_unified.m
12,686
utf_8
a6984b83845491ed80d1ac4cd5a5ea33
% function ElasticAcoustic2D_unified clear all, clear % clear -global * Globals2D global tau1 tau2 global ue3 ue4 ue5 ua3 global fa1 fa2 fe1 fe2 K1D = 16; N = 4; c_flag = 0; FinalTime = 2.0; tau1 = 1; tau2 = 1; [Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D); StartUp2D; [rp sp] = EquiNodes2D(15); [rp sp] = xytors(rp,sp); Vp = Vandermonde2D(N,rp,sp)/V; xp = Vp*x; yp = Vp*y; Nq = 2*N; [rq sq wq] = Cubature2D(Nq); % integrate u*v*c Vq = Vandermonde2D(N,rq,sq)/V; Pq = V*V'*Vq'*diag(wq); % J's cancel out Mref = inv(V*V'); xq = Vq*x; yq = Vq*y; Jq = Vq*J; % partition mesh: y > 0 = acoustic global Ka Ke % Ke = 1:K; Ka = []; % Ka = 1:K; Ke = []; Ka = find(mean(y) > 0); Ke = find(mean(y) < 0); %% find dividing boundary global mapAM vmapAM mapAP vmapAP global mapEM vmapEM mapEP vmapEP mapAM = []; mapAP = []; vmapAM = []; vmapAP = []; mapEM = []; mapEP = []; vmapEM = []; vmapEP = []; if ~isempty(Ke) && ~isempty(Ka) mapAM = zeros(Nfp,K1D); mapAP = zeros(Nfp,K1D); vmapAM = zeros(Nfp,K1D); vmapAP = zeros(Nfp,K1D); mapEM = zeros(Nfp,K1D); mapEP = zeros(Nfp,K1D); vmapEM = zeros(Nfp,K1D); vmapEP = zeros(Nfp,K1D); yM = reshape(y(vmapM),Nfp*Nfaces,K); ska = 1; ske = 1; for e = 1:K yf = reshape(yM(:,e),Nfp,Nfaces); for f = 1:Nfaces if norm(yf(:,f))<1e-8 ids = (1:Nfp) + (f-1)*Nfp + (e-1)*Nfp*Nfaces; if ismember(e,Ka) % if in acoustic region mapAM(:,ska) = mapM(ids); mapAP(:,ska) = mapP(ids); vmapAM(:,ska) = vmapM(ids); vmapAP(:,ska) = vmapP(ids); ska = ska + 1; elseif ismember(e,Ke) % if in elastic region mapEM(:,ske) = mapM(ids); mapEP(:,ske) = mapP(ids); vmapEM(:,ske) = vmapM(ids); vmapEP(:,ske) = vmapP(ids); ske = ske + 1; else keyboard end end end end % keyboard end %% global Nfld mu lambda Vq Pq c2 Nfld = 5; %(u1,u2,sxx,syy,sxy) mu = ones(size(xq)); lambda = ones(size(xq)); c2 = ones(size(xq)); % k = 1; % mu = 1 + .5*cos(k*pi*xq).*cos(k*pi*yq); % c2 = 1 + .5*cos(k*pi*xq).*cos(k*pi*yq); % mu = V\(Pq*mu); % c2 = V\(Pq*c2); % mu = repmat(mu(1,:),length(wq),1)/sqrt(2); % c2 = repmat(c2(1,:),length(wq),1)/sqrt(2); % vv = Vp*Pq*c2; color_line3(xp,yp,vv,vv,'.');return % keyboard %% implement exact Scholte wave Scholte; %keyboard %% params setup x0 = 0; y0 = .1; pp = exp(-100^2*((x-x0).^2 + (y-y0).^2)); f0 = 10; t0 = 1/f0; % point source %global fsrc %fsrc = @(t) (t < t0).*(1-2*(pi*f0*(t-t0))^2)*exp(-(pi*f0*(t-t0)^2)).* (Pq * exp(-100^2*((xq-x0).^2 + (yq-y0).^2))); %fsrc = @(t) 0; y0 = -.25; %p = exp(-25^2*((x-x0).^2 + (y-y0).^2)); u = zeros(Np, K); %% set initial value using exact solution of scholte wave U{1}(:,Ka) = u1a(x(:,Ka),y(:,Ka),0); U{1}(:,Ke) = u1e(x(:,Ke),y(:,Ke),0); U{2}(:,Ka) = u2a(x(:,Ka),y(:,Ka),0); U{2}(:,Ke) = u2e(x(:,Ke),y(:,Ke),0); U{3}(:,Ka) = s1ax(x(:,Ka),y(:,Ka),0); U{3}(:,Ke) = s1ex(x(:,Ke),y(:,Ke),0); U{4}(:,Ka) = s2ay(x(:,Ka),y(:,Ka),0); U{4}(:,Ke) = s2ey(x(:,Ke),y(:,Ke),0); U{5}(:,Ka) = zeros(Np,length(Ka)); U{5}(:,Ke) = s12exy(x(:,Ke),y(:,Ke),0); % U{1} = u; % U{2} = u; % U{3} = u; % U{4} = u; % U{5} = u; %% test numerical stability if Nfld*Np*K < 2500 u = zeros(Nfld*Np*K,1); rhs = zeros(Nfld*Np*K,1); A = zeros(Nfld*Np*K); ids = 1:Np*K; for i = 1:Nfld*Np*K u(i) = 1; for fld = 1:Nfld U{fld} = reshape(u(ids + (fld-1)*Np*K),Np,K); end % ue1 = s1ex(x,y,0); % ue2 = s2ey(x,y,0); % ue3 = s12exy(x,y,0); % ua1 = s1ax(x,y,0); rE = ElasRHS2D(U,0); rA = AcousRHS2D(U,0); u(i) = 0; for fld = 1:Nfld rU = zeros(Np,K); rU(:,Ke) = rE{fld}(:,Ke); if fld <= 3 rU(:,Ka) = rA{fld}(:,Ka); end rhs(ids + (fld-1)*Np*K) = rU; end A(:,i) = rhs(:); if (mod(i,100)==0) disp(sprintf('on col %d out of %d\n',i,Np*K*Nfld)) end end lam = eig(A); plot(lam,'.','markersize',24) hold on title(sprintf('Largest real part = %g\n',max(real(lam)))) axis equal % drawnow max(abs(lam)) keyboard end %% time = 0; % Runge-Kutta residual storage for fld = 1:Nfld res{fld} = zeros(Np,K); %rhs{fld} = zeros(Np,K); end % compute time step size CN = (N+1)*(N+2)/3; % guessing... dt = 2/(max(2*mu(:)+lambda(:))*CN*max(Fscale(:))); Nsteps = ceil(FinalTime/dt); dt = FinalTime/Nsteps; % outer time step loop tstep = 0; M = inv(V*V'); wqJ = diag(wq)*(Vq*J); % figure % colormap(gray) % colormap(hot) for tstep = 1:Nsteps time = tstep*dt; for INTRK = 1:5 timeloc = time + rk4c(INTRK)*dt; ue3 = s1ex(x,y,timeloc); ue4 = s2ey(x,y,timeloc); ue5 = s12exy(x,y,timeloc); ua3 = s1ax(x,y,timeloc); %fa1 = f1a(x,y,timeloc); %fa2 = f2a(x,y,timeloc); %fe1 = f1e(x,y,timeloc); %fe2 = f2e(x,y,timeloc); rhsE = ElasRHS2D(U,timeloc); rhsA = AcousRHS2D(U,timeloc); % initiate and increment Runge-Kutta residuals for fld = 1:Nfld rhs = zeros(Np,K); if fld <= 3 rhs(:,Ka) = rhsA{fld}(:,Ka); end rhs(:,Ke) = rhsE{fld}(:,Ke); res{fld} = rk4a(INTRK)*res{fld} + dt*rhs; U{fld} = U{fld} + rk4b(INTRK)*res{fld}; end end if 1 && (mod(tstep,10)==0 || tstep==Nsteps) clf pe = (U{3} + U{4})/2; % average trace(S) % pe = U{3}; % average trace(S) %pa = (U{3} + U{4})/2; pa = U{3}; % average trace(S) p(:,Ke) = pe(:,Ke); p(:,Ka) = pa(:,Ka); vv = Vp*p; color_line3(xp,yp,vv,vv,'.'); axis tight title(sprintf('time = %f',time)); colorbar; drawnow p_exact(:,Ka) = s1ax(xq(:,Ka),yq(:,Ka),time); p_exact(:,Ke) = 0.5*s1ex(xq(:,Ke),yq(:,Ke),time)+0.5*s2ey(xq(:,Ke),yq(:,Ke),time); p_quadrature = Vq * p; [d1,d2]=size(p_quadrature); error_accumulation = 0; for j1=1:d2 for j2=1:d1 err = p_quadrature(j2,j1)-p_exact(j2,j1); error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1); end end error_l2 = sqrt(error_accumulation) end if mod(tstep,100)==0 disp(sprintf('On timestep %d out of %d\n',tstep,round(FinalTime/dt))) end end % keyboard set(gca,'fontsize',14) title('') axis tight p_exact(:,Ka) = s1ax(xq(:,Ka),yq(:,Ka),FinalTime); p_exact(:,Ke) = 0.5*s1ex(xq(:,Ke),yq(:,Ke),FinalTime)+0.5*s2ey(xq(:,Ke),yq(:,Ke),FinalTime); p_quadrature = Vq * p; [d1,d2]=size(p_quadrature); error_accumulation = 0; for j1=1:d2 for j2=1:d1 err = p_quadrature(j2,j1)-p_exact(j2,j1); error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1); end end error_l2 = sqrt(error_accumulation) function [rhs] = ElasRHS2D(U,time) % function [rhsu, rhsv, rhsp] = acousticsRHS2D(u,v,p) % Purpose : Evaluate RHS flux in 2D acoustics TM form Globals2D; global Nfld mu lambda Vq Pq tau1 tau2 useWADG global C11 C12 C13 C22 C23 C33 global ue3 ue4 ue5 ua3 global fa1 fa2 fe1 fe2 % Define field differences at faces for fld = 1:Nfld u = U{fld}; % compute jumps dU{fld} = zeros(Nfp*Nfaces,K); dU{fld}(:) = u(vmapP)-u(vmapM); ur = Dr*u; us = Ds*u; Ux{fld} = rx.*ur + sx.*us; Uy{fld} = ry.*ur + sy.*us; end divSx = Ux{3} + Uy{5}; % d(Sxx)dx + d(Sxy)dy divSy = Ux{5} + Uy{4}; % d(Sxy)dx + d(Syy)dy du1dx = Ux{1}; % du1dx du2dy = Uy{2}; % du2dy du12dxy = Ux{2} + Uy{1}; % du2dx + du1dy % velocity fluxes An^T*sigma nSx = nx.*dU{3} + ny.*dU{5}; nSy = nx.*dU{5} + ny.*dU{4}; % stress fluxes An*u nUx = dU{1}.*nx; nUy = dU{2}.*ny; nUxy = dU{2}.*nx + dU{1}.*ny; opt=1; if opt==1 % traction BCs % set traction equal to exact traction nSx(mapB) = -2*(nx(mapB).*U{3}(vmapB) + ny(mapB).*U{5}(vmapB)) + 2*(nx(mapB).*ue3(vmapB) + ny(mapB).*ue5(vmapB)); nSy(mapB) = -2*(nx(mapB).*U{5}(vmapB) + ny(mapB).*U{4}(vmapB)) + 2*(nx(mapB).*ue5(vmapB) + ny(mapB).*ue4(vmapB)); %nSx(mapB) = -2*(nx(mapB).*ue1(vmapB) + ny(mapB).*ue3(vmapB)); %nSy(mapB) = -2*(nx(mapB).*ue3(vmapB) + ny(mapB).*ue2(vmapB)); %nSx(mapB) = -2*(nx(mapB).*U{3}(vmapB) + ny(mapB).*U{5}(vmapB)); %nSy(mapB) = -2*(nx(mapB).*U{5}(vmapB) + ny(mapB).*U{4}(vmapB)); elseif opt==2 % basic ABCs nSx(mapB) = -(nx(mapB).*U{3}(vmapB) + ny(mapB).*U{5}(vmapB)); nSy(mapB) = -(nx(mapB).*U{5}(vmapB) + ny(mapB).*U{4}(vmapB)); dU{1}(mapB) = -U{1}(vmapB); dU{2}(mapB) = -U{2}(vmapB); elseif opt==3 % zero velocity dU{1}(mapB) = -2*U{1}(vmapB); dU{2}(mapB) = -2*U{2}(vmapB); end % coupling global mapEM vmapEM mapEP vmapEP nxf = nx(mapEM); nyf = ny(mapEM); u = U{1}(vmapEP); v = U{2}(vmapEP); p = U{3}(vmapEP); Snx = U{3}(vmapEM).*nxf + U{5}(vmapEM).*nyf; Sny = U{5}(vmapEM).*nxf + U{4}(vmapEM).*nyf; Un = u.*nxf + v.*nyf; dU1 = (Un.*nxf-U{1}(vmapEM)); dU2 = (Un.*nyf-U{2}(vmapEM)); UnM = (u-U{1}(vmapEM)).*nxf + (v-U{2}(vmapEM)).*nyf; dU1M = UnM.*nxf; dU2M = UnM.*nyf; nSx(mapEM) = (1*p.*nxf - Snx); nSy(mapEM) = (1*p.*nyf - Sny); nUx(mapEM) = dU1.*nxf; nUy(mapEM) = dU2.*nyf; nUxy(mapEM) = dU1.*nyf + dU2.*nxf; % evaluate central fluxes fc{1} = nSx; fc{2} = nSy; fc{3} = nUx; fc{4} = nUy; fc{5} = nUxy; % penalization terms - reapply An fp{1} = nx.*fc{3} + ny.*fc{5}; fp{2} = nx.*fc{5} + ny.*fc{4}; fp{1}(mapEM) = dU1M; fp{2}(mapEM) = dU2M; fp{3} = fc{1}.*nx; fp{4} = fc{2}.*ny; fp{5} = fc{2}.*nx + fc{1}.*ny; flux = cell(5,1); for fld = 1:2 flux{fld} = zeros(Nfp*Nfaces,K); flux{fld}(:) = fc{fld}(:) + tau1.*fp{fld}(:); end for fld = 3:5 flux{fld} = zeros(Nfp*Nfaces,K); flux{fld}(:) = fc{fld}(:) + tau2.*fp{fld}(:); end % compute right hand sides of the PDE's rr{1} = divSx + LIFT*(Fscale.*flux{1})/2.0; rr{2} = divSy + LIFT*(Fscale.*flux{2})/2.0; rr{3} = du1dx + LIFT*(Fscale.*flux{3})/2.0; rr{4} = du2dy + LIFT*(Fscale.*flux{4})/2.0; rr{5} = du12dxy + LIFT*(Fscale.*flux{5})/2.0; if 0 rhs{1} = rr{1}; rhs{2} = rr{2}; rhs{3} = (2*mu+lambda).*rr{3} + lambda.*rr{4}; rhs{4} = lambda.*rr{3} + (2*mu+lambda).*rr{4}; rhs{5} = (mu) .* rr{5}; else global Pq Vq rhs{1} = rr{1}; rhs{2} = rr{2}; rhs{3} = Pq*((2*mu+lambda).*(Vq*rr{3}) + lambda.*(Vq*rr{4})); rhs{4} = Pq*(lambda.*(Vq*rr{3}) + (2*mu+lambda).*(Vq*rr{4})); rhs{5} = Pq*(mu .* (Vq*rr{5})); end % global Ka % for fld = 1:5 % rhs{fld}(:,Ka) = 0; % end end function [rhs] = AcousRHS2D(U,time) % function [rhsu, rhsv, rhsp] = acousticsRHS2D(u,v,p) % Purpose : Evaluate RHS flux in 2D acoustics TM form Globals2D; global ua3 global fa1 fa2 fe1 fe2 u = U{1}; v = U{2}; p = U{3}; % should be same as U{4} % Define field differences at faces dp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM); du = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM); dv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM); % evaluate upwind fluxes ndotdU = nx.*du + ny.*dv; % Impose reflective boundary conditions (p+ = -p-) %ndotdU(mapB) = 0; % will not affect, naturally zero %dp(mapB) = -2*p(vmapB); dp(mapB) = -2*p(vmapB) + 2*ua3(vmapB); % elastic-acoustic coupling global mapAM vmapAM mapAP vmapAP nxf = nx(mapAM); nyf = ny(mapAM); v1 = U{1}(vmapAP); v2 = U{2}(vmapAP); sxx = U{3}(vmapAP); syy = U{4}(vmapAP); sxy = U{5}(vmapAP); Snx = sxx.*nxf + sxy.*nyf; Sny = sxy.*nxf + syy.*nyf; nSn = Snx.*nxf + Sny.*nyf; dU1 = (v1-u(vmapAM)); dU2 = (v2-v(vmapAM)); ndotdU(mapAM) = dU1.*nxf + dU2.*nyf; dp(mapAM) = nSn-1*p(vmapAM); global tau1 tau2; fluxp = tau2*dp + ndotdU; fluxu = (tau1*ndotdU + dp).*nx; fluxv = (tau1*ndotdU + dp).*ny; pr = Dr*p; ps = Ds*p; dpdx = rx.*pr + sx.*ps; dpdy = ry.*pr + sy.*ps; divU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy); % compute right hand sides of the PDE's rhs{1} = dpdx + LIFT*(Fscale.*fluxu)/2.0; rhs{2} = dpdy + LIFT*(Fscale.*fluxv)/2.0; rhs{3} = divU + LIFT*(Fscale.*fluxp)/2.0; if 0 global c2 Pq Vq %global fsrc %rhs{3} = rhs{3} + fsrc(time); rhs{3} = Pq*(c2.*(Vq*rhs{3})); end end
github
KGuo26/WADG_Matlab-master
Wave2D_M_manufactured.m
.m
WADG_Matlab-master/Wave2D_M_manufactured.m
3,244
utf_8
7f7a6ac983321b0bffeaf09bbd71fa7f
clear Globals2D N = 8; k=1 for M = 0:N K1D = 32; FinalTime = 1.0; [Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D); StartUp2D; %% Set up wavespeed function %cfun = @(x,y) ones(size(x)); cfun = @(x,y) 1+ 0.5*sin(k*pi*x).*sin(k*pi*y); % smooth velocity %cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity %% Set periodic manufactured solution pfun = @(x,y,t) sin(pi*x).*sin(pi*y).*cos(pi*t); ufun = @(x,y,t) -cos(pi*x).*sin(pi*y).*sin(pi*t); vfun = @(x,y,t) -sin(pi*x).*cos(pi*y).*sin(pi*t); ffun = @(x,y,t) pi*(-1./(cfun(x,y))+2).*sin(pi*x).*sin(pi*y).*sin(pi*t); %% generate quadrature points Nq = 2*N+1; [rq sq wq] = Cubature2D(Nq); % integrate u*v*c Vq = Vandermonde2D(N,rq,sq)/V; xq = Vq*x; yq = Vq*y; %% construct the projection matrix for nodal basis Pq Pq = V*V'*Vq'*diag(wq); %% construct matrix Cq Cq = cfun(xq,yq); %% construct the projection matrix for cfun to degree M VMq = Vandermonde2D(M,rq,sq); CqM = VMq*VMq'*diag(wq)*Cq; %% initial condition p = pfun(x,y,0); u = ufun(x,y,0); v = vfun(x,y,0); time = 0; %% Runge-Kutta residual storage resu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K); %% compute time step size CN = (N+1)*(N+2)/2; % trace inequality constant CNh = max(CN*max(Fscale(:))); dt = 2/CNh; %% outer time step loop tstep = 0; while (time<FinalTime) if(time+dt>FinalTime), dt = FinalTime-time; end for INTRK = 1:5 timelocal = time + rk4c(INTRK)*dt; f=ffun(x,y,timelocal); [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f); % initiate and increment Runge-Kutta residuals resp = rk4a(INTRK)*resp + dt*rhsp; resu = rk4a(INTRK)*resu + dt*rhsu; resv = rk4a(INTRK)*resv + dt*rhsv; % update fields u = u+rk4b(INTRK)*resu; v = v+rk4b(INTRK)*resv; p = p+rk4b(INTRK)*resp; end % Increment time time = time+dt; tstep = tstep+1; end p_exact = pfun(x,y,FinalTime); p_exact_quadrature = pfun(xq,yq,FinalTime); p_quadrature = Vq * p; [d1,d2]=size(p_quadrature); error_accumulation = 0; for j1=1:d2 for j2=1:d1 err = p_quadrature(j2,j1)-p_exact_quadrature(j2,j1); error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1); end end error_l2(M+1) = sqrt(error_accumulation); error_fro(M+1) = norm(p-p_exact,'fro'); end function [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f) Globals2D; % Define field differences at faces dp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM); du = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM); dv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM); % evaluate upwind fluxes ndotdU = nx.*du + ny.*dv; % Impose reflective boundary conditions (p+ = -p-) ndotdU(mapB) = 0; dp(mapB) = -2*p(vmapB); tau = 1; fluxp = tau*dp - ndotdU; fluxu = (tau*ndotdU - dp).*nx; fluxv = (tau*ndotdU - dp).*ny; pr = Dr*p; ps = Ds*p; dpdx = rx.*pr + sx.*ps; dpdy = ry.*pr + sy.*ps; divU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy); % compute right hand sides of the PDE's rhsp = -divU + f + LIFT*(Fscale.*fluxp)/2.0; rhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0; rhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0; rhsp = Pq*(CqM.*(Vq*rhsp)); return; end
github
caghangir/MATLAB-Grid-Search-for-Neural-Networks-master
gridSearchNN.m
.m
MATLAB-Grid-Search-for-Neural-Networks-master/gridSearchNN.m
2,393
utf_8
40eb11e58ad1cf4dfde388d97884b636
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Grid Search for Matlab % % % % Copyright (C) 2017 Cagatay Demirel. All rights reserved. % % [email protected] % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % **** Example (How to use function) ******* % % hidlaysize1 = [15 30 70]; % hidlaysize2 = [10 20 50]; % trainopt = {'traingd' 'traingda' 'traingdm' 'traingdx'}; % maxepoch = [10 20 40 90]; % transferfunc = {'logsig' 'tansig'}; % bestparameters = gridSearchNN(x_train',y_train',hidlaysize1,... % hidlaysize2,trainopt,maxepoch,transferfunc); function out = gridSearchNN(trainX,trainY,param1,param2,param3,param4,... param5,varargin) if(nargin > 4) [p,q,r,s,t] = ndgrid(param1,param2,1:length(param3),param4,1:length(param5)); pairs = [p(:) q(:) r(:) s(:) t(:)]; % scoreboard = cell(size(pairs,1),4); else [p,q] = meshgrid(param1,param2); pairs = [p(:) q(:)]; % scoreboard = cell(size(pairs,1),3); end valscores = zeros(size(pairs,1),1); for i=1:size(pairs,1) setdemorandstream(672880951) net = patternnet([pairs(i,1) pairs(i,2)]); net.trainFcn = param3{pairs(i,3)}; net.trainParam.epochs = pairs(i,4); net.layers{2}.transferFcn = param5{pairs(i,5)}; net.divideParam.trainRatio = 0.9; net.divideParam.valRatio = 0.1; net.divideParam.testRatio = 0; vals = crossval(@(XTRAIN, YTRAIN, XTEST, YTEST)NNtrain(XTRAIN, YTRAIN, XTEST, YTEST, net),... trainX, trainY); valscores(i) = mean(vals); % net = train(net,trainX,trainY); % y_pred = net(valX); % [~,indicesReal] = max(valY, [], 1); %336x1 matrix % [~, indicesPredicted] = max(y_pred,[],1); % valscores(i) = mean(double(indicesPredicted == indicesReal)); end [~,ind] = max(valscores); out = {pairs(ind,1) pairs(ind,2) param3{pairs(ind,3)} ... pairs(ind,4) param5{pairs(ind,5)}}; end function testval = NNtrain(XTRAIN, YTRAIN, XTEST, YTEST, net) net = train(net, XTRAIN', YTRAIN'); y_pred = net(XTEST'); [~,indicesReal] = max(YTEST',[],1); [~,indicesPredicted] = max(y_pred,[],1); testval = mean(double(indicesPredicted == indicesReal)); end
github
mrmushfiq/qalma-master
qalma.m
.m
qalma-master/qalma.m
5,230
utf_8
0e9226a0f71ab8eb22b7073be7ef050e
function varargout = qalma(varargin) % QALMA MATLAB code for qalma.fig % QALMA, by itself, creates a new QALMA or raises the existing % singleton*. % % H = QALMA returns the handle to a new QALMA or the handle to % the existing singleton*. % % QALMA('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in QALMA.M with the given input arguments. % % QALMA('Property','Value',...) creates a new QALMA or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before qalma_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to qalma_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help qalma % Last Modified by GUIDE v2.5 08-Jun-2017 23:41:29 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @qalma_OpeningFcn, ... 'gui_OutputFcn', @qalma_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before qalma is made visible. function qalma_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to qalma (see VARARGIN) % Choose default command line output for qalma handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes qalma wait for user response (see UIRESUME) % uiwait(handles.figure1); %set(handles.date_txt, 'String', date); % --- Outputs from this function are returned to the command line. function varargout = qalma_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in ss_button. function ss_button_Callback(hObject, eventdata, handles) % hObject handle to ss_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(qalma); run('star_shot'); % --- Executes on button press in pf_button. function pf_button_Callback(hObject, eventdata, handles) % hObject handle to pf_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(qalma); %run('./picket_panda8/picket_panda.m'); run('picket_panda'); % --- Executes on button press in wl_button. function wl_button_Callback(hObject, eventdata, handles) % hObject handle to wl_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(qalma); run('wl'); % --- Executes on button press in lr_button. function lr_button_Callback(hObject, eventdata, handles) % hObject handle to lr_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(qalma); run('ci'); % --- Executes on button press in lf_button. function lf_button_Callback(hObject, eventdata, handles) % hObject handle to lf_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(qalma); run('dynalog'); % --- Executes on button press in rotate_button. function rotate_button_Callback(hObject, eventdata, handles) % hObject handle to rotate_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in crop_button. function crop_button_Callback(hObject, eventdata, handles) % hObject handle to crop_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in invert_button. function invert_button_Callback(hObject, eventdata, handles) % hObject handle to invert_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)
github
mrmushfiq/qalma-master
star_shot.m
.m
qalma-master/star_shot/star_shot.m
26,383
utf_8
2b44cdb1fdf5db0023e49a8971a36020
% M. Mushfiqur Rahman % Florida Atlantic University % August, 2017 function varargout = star_shot(varargin) % STAR_SHOT MATLAB code for star_shot.fig % STAR_SHOT, by itself, creates a new STAR_SHOT or raises the existing % singleton*. % % H = STAR_SHOT returns the handle to a new STAR_SHOT or the handle to % the existing singleton*. % % STAR_SHOT('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in STAR_SHOT.M with the given input arguments. % % STAR_SHOT('Property','Value',...) creates a new STAR_SHOT or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before star_shot_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to star_shot_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help star_shot % Last Modified by GUIDE v2.5 25-Aug-2017 22:35:28 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @star_shot_OpeningFcn, ... 'gui_OutputFcn', @star_shot_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before star_shot is made visible. function star_shot_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to star_shot (see VARARGIN) % Choose default command line output for star_shot handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes star_shot wait for user response (see UIRESUME) % uiwait(handles.figure1); set(handles.axes1, 'box','off','XTickLabel',[],'xtick',[],'YTickLabel',[],'ytick',[]); %set(handles.num_arms_pop, 'String',{4:24}); set(handles.axes2, 'visible', 'off'); set(handles.axes3, 'visible', 'off'); set(handles.radius_name, 'visible', 'off'); set(handles.radius_txt, 'visible', 'off'); set(handles.comment_txt, 'visible', 'on'); set(handles.report_button, 'visible', 'on'); set(handles.mm_txt, 'visible', 'off'); set(handles.uitable1, 'visible', 'off'); set(handles.uitable1, 'Data', []); set(handles.uitable1, 'ColumnName', {'Image','Gantry','Couch', 'Collimator', 'Radius(mm)','Comment'}); set(handles.wiener_check, 'Value', 1); set(handles.w1_pop, 'String',{1:10}, 'Value', 8); set(handles.w2_pop, 'String',{1:10}, 'Value', 8); set(handles.avg_txt, 'String', '2'); set(handles.crop_check, 'Value', 1); set(handles.resolution_txt, 'String', '0.39'); set(handles.mag_factor_txt, 'String', '1'); set(handles.analyze_button, 'Enable', 'off'); set(handles.report_button, 'Enable', 'off'); set(handles.add_button, 'Enable', 'off'); warning('off','all') global analyzer; analyzer = 0; global c1; global c2; global c3; c1 = get(handles.gantry_check, 'Value'); c2 = get(handles.couch_check, 'Value'); c3 = get(handles.collimator_check, 'Value'); % --- Outputs from this function are returned to the command line. function varargout = star_shot_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in browse_button. function browse_button_Callback(hObject, eventdata, handles) % hObject handle to browse_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global img; global file_name; [f p] = uigetfile(... {'*.jpg; *.JPG; *.jpeg; *.JPEG; *.img; *.IMG; *.tif;*.png; *.TIF; *.tiff, *.TIFF','Supported Files (*.jpg,*.img,*.tiff,*.png)'; ... '*.jpg','jpg Files (*.jpg)';... '*.JPG','JPG Files (*.JPG)';... '*.jpeg','jpeg Files (*.jpeg)';... '*.JPEG','JPEG Files (*.JPEG)';... '*.img','img Files (*.img)';... '*.IMG','IMG Files (*.IMG)';... '*.tif','tif Files (*.tif)';... '*.TIF','TIF Files (*.TIF)';... '*.tiff','tiff Files (*.tiff)';... '*.TIFF','TIFF Files (*.TIFF)'},... 'MultiSelect', 'off'); try img_d = imread([p f]); img=im2double(img_d); img=uint8(255*mat2gray(img)); imshow(img,'Parent',handles.axes1); img = img_d; file_name = f; set(handles.analyze_button, 'Enable', 'on'); set(handles.report_button, 'Enable', 'on'); set(handles.add_button, 'Enable', 'on'); catch h = msgbox('Please upload an image'); end % --- Executes on button press in analyze_button. function analyze_button_Callback(hObject, eventdata, handles) % hObject handle to analyze_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.analyze_button, 'Enable', 'off'); global img; global file_name; global analyzer; analyzer = analyzer + 1; %starF(handles,img); [radii,pass] = starF(handles,img); if pass == 1 set(handles.browse_button, 'Visible', 'off'); setpixelposition(handles.uitable1,[65, 10, 490, 127]); set(handles.uitable1, 'visible', 'on'); global c1; global c2; global c3; c1 = get(handles.gantry_check, 'Value'); c2 = get(handles.couch_check, 'Value'); c3 = get(handles.collimator_check, 'Value'); D = get(handles.uitable1, 'Data'); [r,c] = size(D); D{r+1,1} = file_name; if c1==1 D{r+1,2} = ' X '; elseif c2 == 1 D{r+1,3} = ' X '; elseif c3 == 1 D{r+1,4} = ' X '; else h = msgbox({'Check at least one of the three components'}); pause(2) delete(h); end D{r+1,5} = get(handles.radius_txt, 'String'); % if pass == 1 % D{r+1,5} = get(handles.radius_txt, 'String'); % else % D{r+1,5} = '-'; % end D{r+1,6} = get(handles.comment_txt, 'String'); set(handles.uitable1, 'Data', D); set(handles.row_pop, 'String', {1:r+1}); end % --- Executes on selection change in num_arms_pop. function num_arms_pop_Callback(hObject, eventdata, handles) % hObject handle to num_arms_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns num_arms_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from num_arms_pop % --- Executes during object creation, after setting all properties. function num_arms_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to num_arms_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function radius_txt_Callback(hObject, eventdata, handles) % hObject handle to radius_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of radius_txt as text % str2double(get(hObject,'String')) returns contents of radius_txt as a double % --- Executes during object creation, after setting all properties. function radius_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to radius_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function comment_txt_Callback(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of comment_txt as text % str2double(get(hObject,'String')) returns contents of comment_txt as a double % --- Executes during object creation, after setting all properties. function comment_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in report_button. function report_button_Callback(hObject, eventdata, handles) % hObject handle to report_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) tc = get(handles.comment_txt, 'String'); tc = strcat('Comment:', tc); result = get(handles.radius_txt, 'String'); result = strcat('Radius: ',result); D = get(handles.uitable1, 'Data'); f2=figure t = uitable(f2,'Data',D,'Position',[20 60 500 300]); t.ColumnName = {'Image','Gantry','Couch', 'Collimator', 'Radius(mm)','Comment'} saveas(f2,'Star_Report.pdf'); % --- Executes on button press in add_button. function add_button_Callback(hObject, eventdata, handles) % hObject handle to add_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global img; global file_name; %set(handles.axes2, 'visible', 'off'); set(handles.axes2, 'Units', 'pixels', 'Position', [300, 300, 10, 10]); [f p] = uigetfile(... {'*.jpg; *.JPG; *.jpeg; *.JPEG; *.img; *.IMG; *.tif;*.png; *.TIF; *.tiff, *.TIFF','Supported Files (*.jpg,*.img,*.tiff,*.png)'; ... '*.jpg','jpg Files (*.jpg)';... '*.JPG','JPG Files (*.JPG)';... '*.jpeg','jpeg Files (*.jpeg)';... '*.JPEG','JPEG Files (*.JPEG)';... '*.img','img Files (*.img)';... '*.IMG','IMG Files (*.IMG)';... '*.tif','tif Files (*.tif)';... '*.TIF','TIF Files (*.TIF)';... '*.tiff','tiff Files (*.tiff)';... '*.TIFF','TIFF Files (*.TIFF)'},... 'MultiSelect', 'off'); try img_d = imread([p f]); img=im2double(img_d); img=uint8(255*mat2gray(img)); set(handles.axes1, 'Units', 'pixels', 'Position', [37, 99, 544, 397]); imshow(img,'Parent',handles.axes1); setpixelposition(handles.uitable1,[65, 10, 490, 70]); img = img_d; file_name = f; set(handles.analyze_button, 'Enable', 'on'); catch h = msgbox('Please upload an image'); end %imshow(img,'Parent',handles.axes1); % --- Executes on button press in gantry_check. function gantry_check_Callback(hObject, eventdata, handles) % hObject handle to gantry_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of gantry_check set(handles.couch_check,'Value',0); set(handles.collimator_check,'Value',0); % --- Executes on button press in couch_check. function couch_check_Callback(hObject, eventdata, handles) % hObject handle to couch_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of couch_check set(handles.gantry_check,'Value',0); set(handles.collimator_check,'Value',0); % --- Executes on button press in collimator_check. function collimator_check_Callback(hObject, eventdata, handles) % hObject handle to collimator_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of collimator_check set(handles.couch_check,'Value',0); set(handles.gantry_check,'Value',0); % --- Executes on button press in delete_row_button. function delete_row_button_Callback(hObject, eventdata, handles) % hObject handle to delete_row_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on selection change in row_pop. function row_pop_Callback(hObject, eventdata, handles) % hObject handle to row_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns row_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from row_pop % --- Executes during object creation, after setting all properties. function row_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to row_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in manual_check. function manual_check_Callback(hObject, eventdata, handles) % hObject handle to manual_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of manual_check function rotate_txt_Callback(hObject, eventdata, handles) % hObject handle to rotate_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of rotate_txt as text % str2double(get(hObject,'String')) returns contents of rotate_txt as a double % global img; % angle = str2num(get(handles.rotate_txt,'String')); % % if get(handles.manual_check, 'Value') == 1 % img = imrotate(img, angle); % imshow(img,'Parent',handles.axes2); % else % h = msgbox({'Please Activate Manual mode'}); % pause(1) % delete(h); % end % --- Executes during object creation, after setting all properties. function rotate_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to rotate_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in center_check. function center_check_Callback(hObject, eventdata, handles) % hObject handle to center_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of center_check % --- Executes on button press in invert_check. function invert_check_Callback(hObject, eventdata, handles) % hObject handle to invert_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of invert_check global img; v1 = get(handles.manual_check, 'Value'); v2 = get(handles.invert_check, 'Value'); if v1 == 1 & v2 == 1 img = imcomplement(img); imshow(img,'Parent',handles.axes1); end set(handles.invert_check, 'Value',0); % --- Executes on button press in analyze_button. function pushbutton8_Callback(hObject, eventdata, handles) % hObject handle to analyze_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) function avg_txt_Callback(hObject, eventdata, handles) % hObject handle to avg_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of avg_txt as text % str2double(get(hObject,'String')) returns contents of avg_txt as a double % --- Executes during object creation, after setting all properties. function avg_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to avg_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in w1_pop. function w1_pop_Callback(hObject, eventdata, handles) % hObject handle to w1_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns w1_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from w1_pop % --- Executes during object creation, after setting all properties. function w1_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to w1_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in w2_pop. function w2_pop_Callback(hObject, eventdata, handles) % hObject handle to w2_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns w2_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from w2_pop % --- Executes during object creation, after setting all properties. function w2_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to w2_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in delete_button. function delete_button_Callback(hObject, eventdata, handles) % hObject handle to delete_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) D = get(handles.uitable1, 'Data'); [r,c] = size(D); row = get(handles.row_pop, 'Value'); if r>0 D(row,:) = []; end set(handles.uitable1, 'Data', D); function edit9_Callback(hObject, eventdata, handles) % hObject handle to edit9 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit9 as text % str2double(get(hObject,'String')) returns contents of edit9 as a double % --- Executes during object creation, after setting all properties. function edit9_CreateFcn(hObject, eventdata, handles) % hObject handle to edit9 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in report_button. function pushbutton12_Callback(hObject, eventdata, handles) % hObject handle to report_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in wiener_check. function wiener_check_Callback(hObject, eventdata, handles) % hObject handle to wiener_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of wiener_check function edit10_Callback(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of comment_txt as text % str2double(get(hObject,'String')) returns contents of comment_txt as a double % --- Executes during object creation, after setting all properties. function edit10_CreateFcn(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function mag_factor_txt_Callback(hObject, eventdata, handles) % hObject handle to mag_factor_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of mag_factor_txt as text % str2double(get(hObject,'String')) returns contents of mag_factor_txt as a double % --- Executes during object creation, after setting all properties. function mag_factor_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to mag_factor_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function resolution_txt_Callback(hObject, eventdata, handles) % hObject handle to resolution_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of resolution_txt as text % str2double(get(hObject,'String')) returns contents of resolution_txt as a double % --- Executes during object creation, after setting all properties. function resolution_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to resolution_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in crop_check. function crop_check_Callback(hObject, eventdata, handles) % hObject handle to crop_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of crop_check % --- Executes on button press in home_button. function home_button_Callback(hObject, eventdata, handles) % hObject handle to home_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(star_shot); run('qalma'); % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: delete(hObject) closes the figure delete(hObject); if exist('starshot.png', 'file')==2 delete('starshot.png'); end if exist('starshot_zoomed.png', 'file')==2 delete('starshot_zoomed.png'); end clearvars;
github
mrmushfiq/qalma-master
picket_panda.m
.m
qalma-master/picket_fence/picket_panda.m
26,770
utf_8
d8e6b4b5b54d088f497dc1f0bef488f7
% M. Mushfiqur Rahman % Florida Atlantic University % August, 2017 function varargout = picket_panda(varargin) % PICKET_PANDA MATLAB code for picket_panda.fig % PICKET_PANDA, by itself, creates a new PICKET_PANDA or raises the existing % singleton*. % % H = PICKET_PANDA returns the handle to a new PICKET_PANDA or the handle to % the existing singleton*. % % PICKET_PANDA('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in PICKET_PANDA.M with the given input arguments. % % PICKET_PANDA('Property','Value',...) creates a new PICKET_PANDA or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before picket_panda_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to picket_panda_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help picket_panda % Last Modified by GUIDE v2.5 23-Aug-2017 18:14:46 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @picket_panda_OpeningFcn, ... 'gui_OutputFcn', @picket_panda_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before picket_panda is made visible. function picket_panda_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to picket_panda (see VARARGIN) % Choose default command line output for picket_panda handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes picket_panda wait for user response (see UIRESUME) % uiwait(handles.figure1); global count; count = 0; % go button click counter global mag_count; %mag button click counter mag_count = 0; set(handles.axes2, 'visible', 'off', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]); set(handles.axes1, 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]); set(handles.data_transfer_min, 'Data',[]); set(handles.smoothing_param,'string','3'); set(handles.picket_num_pop, 'String',{1:10}); set(handles.level_txt, 'String', '26'); set(handles.width_left_txt, 'String', '37'); set(handles.width_right_txt, 'String', '37'); set(handles.w1_pop, 'String', {1:10}); set(handles.w2_pop, 'String', {1:10}); % set(handles.w1_pop, 'Value', 3); % set(handles.w2_pop, 'Value', 2); set(handles.w1_pop, 'Value', 5); set(handles.w2_pop, 'Value', 5); set(handles.rotate_pop, 'String', [0,90,180,270,360]); set(handles.rotate_check, 'Value', 1); set(handles.rotate_pop, 'Value', 1); set(handles.profile_check, 'Value', 0); set(handles.wiener_check, 'Value',1); set(handles.mag_txt, 'String', '1.5'); set(handles.res_txt, 'String', '0.781'); set(handles.go_button, 'Enable', 'off'); set(handles.recalculate_button, 'Enable', 'off'); set(handles.plus_button, 'Enable', 'off'); set(handles.minus_button, 'Enable', 'off'); set(handles.column_mlc, 'Enable', 'off'); set(handles.select_line, 'Enable', 'off'); set(handles.report_button, 'Enable', 'off'); set(handles.rotate_pop, 'Enable', 'off'); set(handles.magnify_button, 'Enable', 'off'); set(handles.clear, 'Enable', 'off'); % --- Outputs from this function are returned to the command line. function varargout = picket_panda_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %...... %dicomF(handles); global img; [f p] = uigetfile({'*.dcm','DICOM Files'}); try img_d = dicomread([p f]); img=im2double(img_d); img=uint8(255*mat2gray(img)); %img = imrotate(img, 90); imshow(img,'Parent',handles.axes1); h = msgbox({'Please select the number of pickets and select the pickets'}); pause(2) delete(h); set(handles.go_button, 'Enable', 'on'); set(handles.rotate_pop, 'Enable', 'on'); set(handles.magnify_button, 'Enable', 'on'); set(handles.clear, 'Enable', 'on'); catch h = msgbox('Please upload an image'); end % --- Executes when entered data in editable cell(s) in data_transfer_min. function data_transfer_min_CellEditCallback(hObject, eventdata, handles) % hObject handle to data_transfer_min (see GCBO) % eventdata structure with the following fields (see MATLAB.UI.CONTROL.TABLE) % Indices: row and column indices of the cell(s) edited % PreviousData: previous data for the cell(s) edited % EditData: string(s) entered by the user % NewData: EditData or its converted form set on the Data property. Empty if Data was not changed % Error: error string when failed to convert EditData to appropriate value for Data % handles structure with handles and user data (see GUIDATA) % --- Executes on selection change in select_line. function select_line_Callback(hObject, eventdata, handles) % hObject handle to select_line (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns select_line contents as cell array % contents{get(hObject,'Value')} returns selected item from select_line set(handles.plus_button, 'Enable', 'on'); set(handles.minus_button, 'Enable', 'on'); % --- Executes during object creation, after setting all properties. function select_line_CreateFcn(hObject, eventdata, handles) % hObject handle to select_line (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in plus_button. function plus_button_Callback(hObject, eventdata, handles) % hObject handle to plus_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global img; moveF(handles,img,-1); %sign = -1 , one pixel movement %magnifier('aacircle', 20, 'current_positions.png'); set(handles.recalculate_button, 'Enable', 'on'); % --- Executes on button press in minus_button. function minus_button_Callback(hObject, eventdata, handles) % hObject handle to minus_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global img; moveF(handles,img,+1); set(handles.recalculate_button, 'Enable', 'on'); %sign = +1 , one pixel movement %magnifier('aacircle', 20, 'current_positions.png'); % --- Executes on button press in clear. function clear_Callback(hObject, eventdata, handles) % hObject handle to clear (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global img; imshow(img); h = msgbox({'Please select the number of pickets (or keep as it is) and select the pickets'}); pause(2) delete(h); set(handles.go_button, 'Enable', 'on'); set(handles.data_transfer_min, 'Data',[]); set(handles.column_mlc, 'Enable', 'off'); set(handles.select_line, 'Enable', 'off'); % --- Executes on selection change in column_mlc. function column_mlc_Callback(hObject, eventdata, handles) % hObject handle to column_mlc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns column_mlc contents as cell array % contents{get(hObject,'Value')} returns selected item from column_mlc set(handles.select_line, 'Enable', 'on'); global img; min_data = get(handles.data_transfer_min, 'Data'); [r,c]= size(min_data); column = get(handles.column_mlc, 'Value'); min = min_data(:,column); %just getting the column required my_line = get(handles.select_line,'Value'); xy = get(handles.xy_data,'Data'); x=xy(:,1); level = str2num(get(handles.level_txt, 'String')); %for i=my_line:length(min)-1 % min(i) = min(i) + 1; %end for i=1:length(min)-1 leafpos(i) = (min(i) + min(i+1))/2; end imshow(img); min_s = min; hold on p = column; col = num2str(p); text([round(x(p))+level],[0],col, 'Color','black') for j=1:length(leafpos) % line([round(x(1))-30 round(x(1))-20],[leafpos(j) leafpos(j)],'Color','r') name = num2str(j); text([round(x(p))],[leafpos(j)],name, 'Color','yellow') line([round(x(p))+level],[leafpos(j)],'Color','r','Marker','*', 'MarkerSize',3) end hold off hold on for j=1:length(min_s) line([round(x(p))+level-4 round(x(p))+level+11],[min_s(j) min_s(j)],'Color','g') end hold off % --- Executes during object creation, after setting all properties. function column_mlc_CreateFcn(hObject, eventdata, handles) % hObject handle to column_mlc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in magnify_button. function magnify_button_Callback(hObject, eventdata, handles) % hObject handle to magnify_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %im= getimage(handles.axes1); %magnifier('aacircle', 20, 'current_positions.png'); global mag_count; mag_count = mag_count + 1; while mag_count > 0 if mod(mag_count,2) == 0 set(handles.axes2, 'visible', 'off'); set(get(handles.axes2,'children'),'visible','off'); %delete(handles.axes2); axes(handles.axes1); %ginput(0); break; else %[x,y] = ginput; [x,y] = ginput(1); set(handles.axes2, 'visible', 'on'); frame = getframe(handles.axes1); im = frame2im(frame); [r,c] = size(im); %magnifier('aacircle', 20, im); imshow(im,'Parent',handles.axes2); axes(handles.axes2); zoom(3); axis([double(x+10) double(x + 110) double(y-40) double(y)]); set(handles.axes2, 'Units', 'pixels', 'Position', [x-3, r-y, 200, 140],... 'box','off','XTickLabel',[],'xtick',[],'YTickLabel',[],'ytick',[]); end end %mag_counter =0; % --- Executes on button press in recalculate_button. function recalculate_button_Callback(hObject, eventdata, handles) % hObject handle to recalculate_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.recalculate_button, 'Enable', 'off'); set(handles.plus_button, 'Enable', 'off'); set(handles.minus_button, 'Enable', 'off'); set(handles.select_line, 'Enable', 'on'); global img; recalcF(handles,img); % --- Executes on button press in report_button. function report_button_Callback(hObject, eventdata, handles) % hObject handle to report_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) f2 = figure f2.Position = [100, 100, 740, 900]; [snap,map1] = imread('current_positions.png'); [gaps,map2] = imread('edge_gaps.png'); title('Report'); subplot(8,10,1:30), imshow(snap,[]); axis equal; subplot(8,10,31:80),imshow(gaps,[]); axis equal; saveas(f2,'Picket_Report.pdf'); function smoothing_param_Callback(hObject, eventdata, handles) % hObject handle to smoothing_param (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of smoothing_param as text % str2double(get(hObject,'String')) returns contents of smoothing_param as a double % --- Executes during object creation, after setting all properties. function smoothing_param_CreateFcn(hObject, eventdata, handles) % hObject handle to smoothing_param (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in picket_num_pop. function picket_num_pop_Callback(hObject, eventdata, handles) % hObject handle to picket_num_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns picket_num_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from picket_num_pop v=get(handles.picket_num_pop, 'Value'); set(handles.column_mlc, 'String', {1:v}); % --- Executes during object creation, after setting all properties. function picket_num_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to picket_num_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in go_button. function go_button_Callback(hObject, eventdata, handles) % hObject handle to go_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.go_button, 'Enable', 'off'); set(handles.column_mlc, 'Enable', 'on'); set(handles.report_button, 'Enable', 'on'); global img; dicomF2(handles,img); min_data = get(handles.data_transfer_min, 'Data'); [r,c]= size(min_data); pickets = get(handles.picket_num_pop,'Value'); set(handles.column_mlc, 'String',{1:pickets}); set(handles.select_line, 'String',{1:r}); global count; count = count +1; function width_right_txt_Callback(hObject, eventdata, handles) % hObject handle to width_right_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of width_right_txt as text % str2double(get(hObject,'String')) returns contents of width_right_txt as a double % --- Executes during object creation, after setting all properties. function width_right_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to width_right_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function width_left_txt_Callback(hObject, eventdata, handles) % hObject handle to width_left_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of width_left_txt as text % str2double(get(hObject,'String')) returns contents of width_left_txt as a double % --- Executes during object creation, after setting all properties. function width_left_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to width_left_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in w2_pop. function w2_pop_Callback(hObject, eventdata, handles) % hObject handle to w2_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns w2_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from w2_pop % --- Executes during object creation, after setting all properties. function w2_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to w2_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in w1_pop. function w1_pop_Callback(hObject, eventdata, handles) % hObject handle to w1_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns w1_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from w1_pop % --- Executes during object creation, after setting all properties. function w1_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to w1_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in rotate_check. function rotate_check_Callback(hObject, eventdata, handles) % hObject handle to rotate_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of rotate_check % --- Executes on selection change in rotate_pop. function rotate_pop_Callback(hObject, eventdata, handles) % hObject handle to rotate_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns rotate_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from rotate_pop global img; v = get(handles.rotate_check, 'Value'); if v ==1 g = get(handles.rotate_pop, 'Value'); if g == 2 img = imrotate(img, 90); elseif g == 3 img = imrotate(img, 180); elseif g == 4 img = imrotate(img, 270); elseif g == 5 img = imrotate(img, 360); end end imshow(img,'Parent',handles.axes1); % --- Executes during object creation, after setting all properties. function rotate_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to rotate_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in profile_check. function profile_check_Callback(hObject, eventdata, handles) % hObject handle to profile_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of profile_check global count; if count > 0 & get(handles.profile_check,'Value')== 1 openfig('f_x.fig'); end % --- Executes on button press in wiener_check. function wiener_check_Callback(hObject, eventdata, handles) % hObject handle to wiener_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of wiener_check % --- Executes on button press in home_button. function home_button_Callback(hObject, eventdata, handles) % hObject handle to home_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(picket_panda); %run('../qalma.m'); run('qalma') function mag_txt_Callback(hObject, eventdata, handles) % hObject handle to mag_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of mag_txt as text % str2double(get(hObject,'String')) returns contents of mag_txt as a double % --- Executes during object creation, after setting all properties. function mag_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to mag_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function res_txt_Callback(hObject, eventdata, handles) % hObject handle to res_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of res_txt as text % str2double(get(hObject,'String')) returns contents of res_txt as a double % --- Executes during object creation, after setting all properties. function res_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to res_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function level_txt_Callback(hObject, eventdata, handles) % hObject handle to level_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of level_txt as text % str2double(get(hObject,'String')) returns contents of level_txt as a double % --- Executes during object creation, after setting all properties. function level_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to level_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in profile_v_check. function profile_v_check_Callback(hObject, eventdata, handles) % hObject handle to profile_v_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of profile_v_check global count; if count > 0 & get(handles.profile_v_check,'Value')== 1 if exist('f_y.fig', 'file')==2 openfig('f_y.fig'); end end % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: delete(hObject) closes the figure delete(hObject); if exist('f_x.fig', 'file')==2 delete('f_x.fig'); end if exist('f_y.fig', 'file')==2 delete('f_y.fig'); end if exist('f_x_s.fig', 'file')==2 delete('f_x_s.fig'); end if exist('f_x.fig', 'file')==2 delete('f_x.fig'); end if exist('edge_gaps.png', 'file')==2 delete('edge_gaps.png'); end if exist('current_positions.png', 'file')==2 delete('current_positions.png'); end clearvars;
github
mrmushfiq/qalma-master
dynalog.m
.m
qalma-master/dynalog/dynalog.m
7,639
utf_8
5c135192ef465a4baa5b642159850bd1
% M. Mushfiqur Rahman % Florida Atlantic University % August, 2017 function varargout = dynalog(varargin) % DYNALOG MATLAB code for dynalog.fig % DYNALOG, by itself, creates a new DYNALOG or raises the existing % singleton*. % % H = DYNALOG returns the handle to a new DYNALOG or the handle to % the existing singleton*. % % DYNALOG('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in DYNALOG.M with the given input arguments. % % DYNALOG('Property','Value',...) creates a new DYNALOG or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before dynalog_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to dynalog_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help dynalog % Last Modified by GUIDE v2.5 25-Aug-2017 22:37:45 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @dynalog_OpeningFcn, ... 'gui_OutputFcn', @dynalog_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before dynalog is made visible. function dynalog_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to dynalog (see VARARGIN) % Choose default command line output for dynalog handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes dynalog wait for user response (see UIRESUME) % uiwait(handles.figure1); set(handles.axes1,'visible','off'); set(handles.report_button,'visible','off'); set(handles.comment_txt,'visible','off'); set(handles.mag_panel, 'visible', 'off'); set(handles.axes2,'visible','off'); set(handles.axes3,'visible','off'); set(handles.axes4,'visible','off'); set(handles.mag_txt, 'String', '1'); % --- Outputs from this function are returned to the command line. function varargout = dynalog_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in a_button. function a_button_Callback(hObject, eventdata, handles) % hObject handle to a_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global f_a; global p_a; [f_a p_a] = uigetfile(... {'*.dlg'},... 'MultiSelect', 'off'); set(handles.file_a_txt, 'String', f_a); % --- Executes on button press in b_button. function b_button_Callback(hObject, eventdata, handles) % hObject handle to b_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global f_b; global p_b; [f_b p_b] = uigetfile(... {'*.dlg'},... 'MultiSelect', 'off'); set(handles.file_b_txt, 'String', f_b); % --- Executes on button press in dynalyze_button. function dynalyze_button_Callback(hObject, eventdata, handles) % hObject handle to dynalyze_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global f_a; global p_a; global f_b; global p_b; dynalogF(handles, f_a, f_b, p_a, p_b); % --- Executes on button press in report_button. function report_button_Callback(hObject, eventdata, handles) % hObject handle to report_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) tc = get(handles.comment_txt, 'String'); tc = strcat('Comment: ', tc); f2 = figure('Position', [100, 100, 724, 700]); [picket,map1] = imread('picket_dyn.png'); title('Dynalog Report'); h1=subplot(4,4,1:12); imshow(picket,[]); axis equal; h2=subplot(4,4,[14,15]); text(0.3,1,tc); axis off; saveas(f2,'Dynalog_Report.pdf'); function comment_txt_Callback(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of comment_txt as text % str2double(get(hObject,'String')) returns contents of comment_txt as a double % --- Executes during object creation, after setting all properties. function comment_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in home_button. function home_button_Callback(hObject, eventdata, handles) % hObject handle to home_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(dynalog); run('qalma'); function mag_txt_Callback(hObject, eventdata, handles) % hObject handle to mag_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of mag_txt as text % str2double(get(hObject,'String')) returns contents of mag_txt as a double % --- Executes during object creation, after setting all properties. function mag_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to mag_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: delete(hObject) closes the figure delete(hObject); if exist('picket_dyn.png', 'file')==2 delete('picket_dyn.png'); end clearvars;
github
mrmushfiq/qalma-master
wl.m
.m
qalma-master/winston_lutz/wl.m
21,479
utf_8
5c9533af6cf6ffa9e93af23d9a8cf14a
% M. Mushfiqur Rahman % Florida Atlantic University % August, 2017 function varargout = wl(varargin) % WL MATLAB code for wl.fig % WL, by itself, creates a new WL or raises the existing % singleton*. % % H = WL returns the handle to a new WL or the handle to % the existing singleton*. % % WL('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in WL.M with the given input arguments. % % WL('Property','Value',...) creates a new WL or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before wl_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to wl_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help wl % Last Modified by GUIDE v2.5 25-Aug-2017 22:33:26 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @wl_OpeningFcn, ... 'gui_OutputFcn', @wl_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before wl is made visible. function wl_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to wl (see VARARGIN) % Choose default command line output for wl handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes wl wait for user response (see UIRESUME) % uiwait(handles.figure1); global mag_count; mag_count = 0; set(handles.radiation_slider, 'Min',0,'Max',100,'Value', 14); set(handles.ball_slider,'Min',0,'Max',100,'Value', 13); set(handles.ball_txt, 'String', 13); set(handles.radiation_txt, 'String', 14); set(handles.axes1, 'Visible', 'off'); set(handles.axes2, 'Visible', 'off'); set(handles.axes3, 'Visible', 'off'); set(handles.radiation_slider, 'Visible', 'off'); set(handles.radiation_txt, 'Visible', 'off'); set(handles.ball_slider, 'Visible', 'off'); set(handles.ball_txt, 'Visible', 'off'); set(handles.text7, 'Visible', 'off'); set(handles.original_label, 'Visible', 'off'); set(handles.filter1_label, 'Visible', 'off'); set(handles.filter2_label, 'Visible', 'off'); set(handles.analyze_button, 'Visible', 'on'); set(handles.distance_label, 'Visible', 'off'); set(handles.distance_txt, 'Visible', 'off'); set(handles.report_button, 'Visible', 'on'); set(handles.uitable1, 'visible', 'off'); set(handles.uitable1, 'Data', []); set(handles.uitable1, 'ColumnName', {'Image', 'Distance(mm)', 'Comment'}); set(handles.mag_txt, 'String', '1'); set(handles.res_txt, 'String', '0.34'); set(handles.zoom_pop, 'String', {1:10}, 'Value', 6); set(handles.analyze_button, 'Enable', 'off'); set(handles.report_button, 'Enable', 'off'); set(handles.zoom_pop, 'Enable', 'off'); % --- Outputs from this function are returned to the command line. function varargout = wl_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on slider movement. function ball_slider_Callback(hObject, eventdata, handles) % hObject handle to ball_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider global img; global img_url; v = get(handles.ball_slider, 'Value'); set(handles.ball_txt, 'String', num2str(v)); wlF_loading(handles,img_url); % --- Executes during object creation, after setting all properties. function ball_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to ball_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function ball_txt_Callback(hObject, eventdata, handles) % hObject handle to ball_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of ball_txt as text % str2double(get(hObject,'String')) returns contents of ball_txt as a double global img; global img_url; s= get(handles.ball_txt, 'String'); set(handles.ball_slider, 'Value', str2num(s)); wlF_loading(handles,img_url); % --- Executes during object creation, after setting all properties. function ball_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to ball_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on slider movement. function radiation_slider_Callback(hObject, eventdata, handles) % hObject handle to radiation_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider global img; global img_url; v = get(handles.radiation_slider, 'Value'); set(handles.radiation_txt, 'String', num2str(v)); wlF_loading(handles,img_url); % --- Executes during object creation, after setting all properties. function radiation_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to radiation_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function radiation_txt_Callback(hObject, eventdata, handles) % hObject handle to radiation_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of radiation_txt as text % str2double(get(hObject,'String')) returns contents of radiation_txt as a double global img; global img_url; s = get(handles.radiation_txt, 'String'); set(handles.radiation_slider, 'Value', str2num(s)); wlF_loading(handles,img_url); % --- Executes during object creation, after setting all properties. function radiation_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to radiation_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in load_button. function load_button_Callback(hObject, eventdata, handles) % hObject handle to load_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global img; global file_name; global img_url; [f p] = uigetfile(... {'*.dcm','Supported Files (*.dcm)'; ... },... 'MultiSelect', 'off'); try %img_d = imread([p f]); img_d = dicomread([p f]); img=im2double(img_d); img=uint8(255*mat2gray(img)); file_name = f; set(handles.axes1, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]); set(handles.axes2, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]); set(handles.axes3, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]); set(handles.radiation_slider, 'Visible', 'on'); set(handles.radiation_txt, 'Visible', 'on'); set(handles.ball_slider, 'Visible', 'on'); set(handles.ball_txt, 'Visible', 'on'); set(handles.original_label, 'Visible', 'on'); set(handles.filter1_label, 'Visible', 'on'); set(handles.filter2_label, 'Visible', 'on'); set(handles.analyze_button, 'Visible', 'on'); set(handles.distance_label, 'Visible', 'on'); set(handles.distance_txt, 'Visible', 'on'); imshow(img,'Parent',handles.axes1); img_url = strcat(p,f); wlF_loading(handles,img_url); set(handles.analyze_button, 'Enable', 'on'); set(handles.zoom_pop, 'Enable', 'on'); catch h = msgbox('Please upload an image'); end % --- Executes on button press in analyze_button. function analyze_button_Callback(hObject, eventdata, handles) % hObject handle to analyze_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global img; global file_name; global img_url; set(handles.report_button, 'Visible', 'on'); wlF(handles,img_url); set(handles.uitable1, 'visible', 'on'); set(handles.load_button, 'Visible', 'off'); set(handles.text7, 'Visible', 'on'); set(handles.report_button, 'Enable', 'on'); D = get(handles.uitable1, 'Data'); [r,c] = size(D); D{r+1,1} = file_name; D{r+1,2} = get(handles.distance_txt, 'String'); D{r+1,3} = get(handles.comment_txt, 'String'); set(handles.uitable1, 'Data', D); set(handles.row_pop, 'String', {1:r+1}); % --- Executes on button press in instructions_button. function instructions_button_Callback(hObject, eventdata, handles) % hObject handle to instructions_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in report_button. function report_button_Callback(hObject, eventdata, handles) % hObject handle to report_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) frame = getframe(handles.axes1); imf = frame2im(frame); %imwrite(imf, 'wl_result.png'); tc = get(handles.comment_txt, 'String'); tc = strcat('Comment : ', tc); dist = get(handles.distance_txt, 'String'); dist = strcat('Distance between the centers : ', dist); texts = {dist,' ', tc}; D = get(handles.uitable1, 'Data'); f1=figure t = uitable(f1,'Data',D,'Position',[20 60 400 300]); t.ColumnName = {'Image','Distance(mm)','Comment'}; saveas(f1, 'wl_report.pdf') function comment_txt_Callback(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of comment_txt as text % str2double(get(hObject,'String')) returns contents of comment_txt as a double % --- Executes during object creation, after setting all properties. function comment_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in add_image. function add_image_Callback(hObject, eventdata, handles) % hObject handle to add_image (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global img; global file_name; global img_url; [f p] = uigetfile(... {'*.dcm','Supported Files (*.dcm)'; ... },... 'MultiSelect', 'off'); % [f p] = uigetfile(... % {'*.jpg; *.JPG; *.jpeg; *.JPEG; *.img; *.IMG; *.tif;*.png; .dcm;*.TIF; *.tiff, *.TIFF','Supported Files (*.dcm,*.jpg,*.img,*.tiff,*.png)'; ... % '*.jpg','jpg Files (*.jpg)';... % '*.JPG','JPG Files (*.JPG)';... % '*.jpeg','jpeg Files (*.jpeg)';... % '*.JPEG','JPEG Files (*.JPEG)';... % '*.img','img Files (*.img)';... % '*.IMG','IMG Files (*.IMG)';... % '*.tif','tif Files (*.tif)';... % '*.TIF','TIF Files (*.TIF)';... % '*.tiff','tiff Files (*.tiff)';... % '*.TIFF','TIFF Files (*.TIFF)'},... % 'MultiSelect', 'off'); try %img_d = imread([p f]); img_d = dicomread([p f]); img=im2double(img_d); img=uint8(255*mat2gray(img)); file_name = f; set(handles.axes1, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]); set(handles.axes2, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]); set(handles.axes3, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]); set(handles.radiation_slider, 'Visible', 'on'); set(handles.radiation_txt, 'Visible', 'on'); set(handles.ball_slider, 'Visible', 'on'); set(handles.ball_txt, 'Visible', 'on'); set(handles.original_label, 'Visible', 'on'); set(handles.filter1_label, 'Visible', 'on'); set(handles.filter2_label, 'Visible', 'on'); set(handles.analyze_button, 'Visible', 'on'); set(handles.distance_label, 'Visible', 'on'); set(handles.distance_txt, 'Visible', 'on'); imshow(img,'Parent',handles.axes1); img_url = strcat(p,f); wlF_loading(handles,img_url); set(handles.analyze_button, 'Enable', 'on'); set(handles.zoom_pop, 'Enable', 'on'); catch h = msgbox('Please upload an image'); end function res_txt_Callback(hObject, eventdata, handles) % hObject handle to res_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of res_txt as text % str2double(get(hObject,'String')) returns contents of res_txt as a double % --- Executes during object creation, after setting all properties. function res_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to res_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function mag_txt_Callback(hObject, eventdata, handles) % hObject handle to mag_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of mag_txt as text % str2double(get(hObject,'String')) returns contents of mag_txt as a double % --- Executes during object creation, after setting all properties. function mag_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to mag_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit8_Callback(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of comment_txt as text % str2double(get(hObject,'String')) returns contents of comment_txt as a double % --- Executes during object creation, after setting all properties. function edit8_CreateFcn(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in home_button. function home_button_Callback(hObject, eventdata, handles) % hObject handle to home_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(wl); run('qalma'); % --- Executes on selection change in zoom_pop. function zoom_pop_Callback(hObject, eventdata, handles) % hObject handle to zoom_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns zoom_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from zoom_pop global img; global img_url; wlF_loading(handles,img_url); % --- Executes during object creation, after setting all properties. function zoom_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to zoom_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton15. function pushbutton15_Callback(hObject, eventdata, handles) % hObject handle to pushbutton15 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in delete_button. function delete_button_Callback(hObject, eventdata, handles) % hObject handle to delete_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) D = get(handles.uitable1, 'Data'); [r,c] = size(D); row = get(handles.row_pop, 'Value'); if r>0 D(row,:) = []; end set(handles.uitable1, 'Data', D); % --- Executes on selection change in row_pop. function row_pop_Callback(hObject, eventdata, handles) % hObject handle to row_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns row_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from row_pop % --- Executes during object creation, after setting all properties. function row_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to row_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: delete(hObject) closes the figure delete(hObject); clearvars;
github
mrmushfiq/qalma-master
ci.m
.m
qalma-master/ci/ci.m
25,849
utf_8
bda1d740da1c89b97e876fc2f9ffe66e
% M. Mushfiqur Rahman % Florida Atlantic University % August, 2017 function varargout = ci(varargin) % CI MATLAB code for ci.fig % CI, by itself, creates a new CI or raises the existing % singleton*. % % H = CI returns the handle to a new CI or the handle to % the existing singleton*. % % CI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in CI.M with the given input arguments. % % CI('Property','Value',...) creates a new CI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before ci_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to ci_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help ci % Last Modified by GUIDE v2.5 31-Aug-2017 18:50:29 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @ci_OpeningFcn, ... 'gui_OutputFcn', @ci_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before ci is made visible. function ci_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to ci (see VARARGIN) % Choose default command line output for ci handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes ci wait for user response (see UIRESUME) % uiwait(handles.figure1); set(handles.bbs_txt, 'Visible', 'off'); setpixelposition(handles.radius1_pop,[3, 10, 70, 40]); setpixelposition(handles.radius2_pop,[87, 10, 70, 40]); setpixelposition(handles.w_1_pop,[79, 5, 70, 40]); setpixelposition(handles.w_2_pop,[153, 5, 70, 40]); set(handles.axes1,... 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]); set(handles.wiener_check,'Value', 1); set(handles.dark_check,'Value', 1); set(handles.w_1_pop, 'string', {1:10}, 'Value', 5); set(handles.w_2_pop, 'string', {1:10}, 'Value', 5); set(handles.radius1_pop, 'string', {1:20}, 'Value', 1, 'Visible' , 'on'); set(handles.radius2_pop, 'string', {1:20}, 'Value', 3, 'Visible' , 'on'); set(handles.sensitivity_slider, 'SliderStep', [0.01, 0.1], 'Value', 0.94); set(handles.threshold_slider, 'SliderStep', [0.01, 0.1], 'Value', 0.14); set(handles.sensitivity_txt, 'String', '0.94'); set(handles.threshold_txt, 'String', '0.14'); set(handles.contrast_low_slider,'Min', 0, 'Max', 1, 'SliderStep', [0.01, 0.1], 'Value', 0); set(handles.contrast_high_slider, 'Min', 0, 'Max', 1,'SliderStep', [0.01, 0.1], 'Value', 0.8); set(handles.contrast_low_txt, 'String', '0'); set(handles.contrast_high_txt, 'String', '0.8'); set(handles.contrast_low_txt, 'Enable', 'off'); set(handles.contrast_high_txt, 'Enable', 'off'); set(handles.contrast_low_slider, 'Enable', 'off'); set(handles.contrast_high_slider, 'Enable', 'off'); set(handles.sensitivity_txt, 'Enable', 'off'); set(handles.threshold_txt, 'Enable', 'off'); set(handles.sensitivity_slider, 'Enable', 'off'); set(handles.threshold_slider, 'Enable', 'off'); set(handles.radius1_pop, 'Enable', 'off'); set(handles.radius2_pop, 'Enable', 'off'); set(handles.dark_check,'Enable', 'off'); set(handles.bright_check,'Enable', 'off'); set(handles.analyze_button, 'Enable', 'off'); set(handles.add_button, 'Enable', 'off'); set(handles.wiener_check, 'Enable','off'); set(handles.w_1_pop, 'Enable','off'); set(handles.w_2_pop, 'Enable','off'); set(handles.manual_check, 'Enable','off'); set(handles.reset_button, 'Enable', 'off'); set(handles.text5, 'Visible', 'off'); set(handles.dice_txt, 'Visible', 'off'); % --- Outputs from this function are returned to the command line. function varargout = ci_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in load_button. function load_button_Callback(hObject, eventdata, handles) % hObject handle to load_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global img; global img_url; [f p] = uigetfile({'*.dcm','DICOM Files'}); try img_d = dicomread([p f]); img=im2double(img_d); img=uint8(255*mat2gray(img)); imshow(img,'Parent',handles.axes1); img_url = strcat(p,f); ci_loadingF(handles,img_url); set(handles.contrast_low_txt, 'Enable', 'on'); set(handles.contrast_high_txt, 'Enable', 'on'); set(handles.contrast_low_slider, 'Enable', 'on'); set(handles.contrast_high_slider, 'Enable', 'on'); set(handles.sensitivity_txt, 'Enable', 'on'); set(handles.threshold_txt, 'Enable', 'on'); set(handles.sensitivity_slider, 'Enable', 'on'); set(handles.threshold_slider, 'Enable', 'on'); set(handles.radius1_pop, 'Enable', 'on'); set(handles.radius2_pop, 'Enable', 'on'); set(handles.dark_check,'Enable', 'on'); set(handles.bright_check,'Enable', 'on'); set(handles.analyze_button, 'Enable', 'on'); set(handles.wiener_check, 'Enable','on'); set(handles.w_1_pop, 'Enable','on'); set(handles.w_2_pop, 'Enable','on'); set(handles.manual_check, 'Enable','on'); set(handles.reset_button, 'Enable', 'on'); set(handles.text5, 'Visible', 'off'); set(handles.dice_txt, 'Visible', 'off'); catch h = msgbox('Please upload an image'); end % --- Executes on button press in analyze_button. function analyze_button_Callback(hObject, eventdata, handles) % hObject handle to analyze_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.analyze_button, 'Enable', 'off'); global img_url; ciF(handles,img_url); set(handles.load_button, 'Visible', 'off'); set(handles.add_button, 'Enable', 'on'); set(handles.text5, 'Visible', 'on'); set(handles.dice_txt, 'Visible', 'on'); % --- Executes on button press in add_button. function add_button_Callback(hObject, eventdata, handles) % hObject handle to add_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global img; global img_url; [f p] = uigetfile({'*.dcm','DICOM Files'}); try img_d = dicomread([p f]); img=im2double(img_d); img=uint8(255*mat2gray(img)); imshow(img,'Parent',handles.axes1); img_url = strcat(p,f); ci_loadingF(handles,img_url); set(handles.analyze_button, 'Enable', 'on'); set(handles.text5, 'Visible', 'off'); set(handles.dice_txt, 'Visible', 'off'); catch h = msgbox('Please upload an image'); end % --- Executes on selection change in radius2_pop. function radius2_pop_Callback(hObject, eventdata, handles) % hObject handle to radius2_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns radius2_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from radius2_pop global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function radius2_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to radius2_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in radius1_pop. function radius1_pop_Callback(hObject, eventdata, handles) % hObject handle to radius1_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns radius1_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from radius1_pop global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function radius1_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to radius1_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function comment_txt_Callback(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of comment_txt as text % str2double(get(hObject,'String')) returns contents of comment_txt as a double % --- Executes during object creation, after setting all properties. function comment_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to comment_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on slider movement. function contrast_high_slider_Callback(hObject, eventdata, handles) % hObject handle to contrast_high_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a = get(handles.contrast_high_slider, 'Value'); set(handles.contrast_high_txt, 'String', num2str(a)); global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function contrast_high_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to contrast_high_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function contrast_high_txt_Callback(hObject, eventdata, handles) % hObject handle to contrast_high_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of contrast_high_txt as text % str2double(get(hObject,'String')) returns contents of contrast_high_txt as a double a = get(handles.contrast_high_txt, 'String'); set(handles.contrast_high_slider, 'Value', str2num(a)); global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function contrast_high_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to contrast_high_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in wiener_check. function wiener_check_Callback(hObject, eventdata, handles) % hObject handle to wiener_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of wiener_check global img_url; ci_loadingF(handles,img_url); % --- Executes on selection change in w_1_pop. function w_1_pop_Callback(hObject, eventdata, handles) % hObject handle to w_1_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns w_1_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from w_1_pop global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function w_1_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to w_1_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in w_2_pop. function w_2_pop_Callback(hObject, eventdata, handles) % hObject handle to w_2_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns w_2_pop contents as cell array % contents{get(hObject,'Value')} returns selected item from w_2_pop global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function w_2_pop_CreateFcn(hObject, eventdata, handles) % hObject handle to w_2_pop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on slider movement. function threshold_slider_Callback(hObject, eventdata, handles) % hObject handle to threshold_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a = get(handles.threshold_slider, 'Value'); set(handles.threshold_txt, 'String', num2str(a)); global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function threshold_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to threshold_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function threshold_txt_Callback(hObject, eventdata, handles) % hObject handle to threshold_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of threshold_txt as text % str2double(get(hObject,'String')) returns contents of threshold_txt as a double a = get(handles.threshold_txt, 'String'); set(handles.threshold_slider, 'Value', str2num(a)); global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function threshold_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to threshold_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on slider movement. function sensitivity_slider_Callback(hObject, eventdata, handles) % hObject handle to sensitivity_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a = get(handles.sensitivity_slider, 'Value'); set(handles.sensitivity_txt, 'String', num2str(a)); global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function sensitivity_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to sensitivity_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function sensitivity_txt_Callback(hObject, eventdata, handles) % hObject handle to sensitivity_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of sensitivity_txt as text % str2double(get(hObject,'String')) returns contents of sensitivity_txt as a double a = get(handles.sensitivity_txt,'String'); set(handles.sensitivity_slider, 'Value', str2num(a)); global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function sensitivity_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to sensitivity_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in dark_check. function dark_check_Callback(hObject, eventdata, handles) % hObject handle to dark_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of dark_check set(handles.bright_check, 'Value', 0); global img_url; ci_loadingF(handles,img_url); % --- Executes on button press in bright_check. function bright_check_Callback(hObject, eventdata, handles) % hObject handle to bright_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of bright_check set(handles.dark_check, 'Value', 0); global img_url; ci_loadingF(handles,img_url); % --- Executes on slider movement. function contrast_low_slider_Callback(hObject, eventdata, handles) % hObject handle to contrast_low_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider a = get(handles.contrast_low_slider, 'Value'); set(handles.contrast_low_txt, 'String', num2str(a)); global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function contrast_low_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to contrast_low_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function contrast_low_txt_Callback(hObject, eventdata, handles) % hObject handle to contrast_low_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of contrast_low_txt as text % str2double(get(hObject,'String')) returns contents of contrast_low_txt as a double a = get(handles.contrast_low_txt, 'String'); set(handles.contrast_low_slider, 'Value', str2num(a)); global img_url; ci_loadingF(handles,img_url); % --- Executes during object creation, after setting all properties. function contrast_low_txt_CreateFcn(hObject, eventdata, handles) % hObject handle to contrast_low_txt (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in home_button. function home_button_Callback(hObject, eventdata, handles) % hObject handle to home_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) close(ci); run('qalma'); % --- Executes on button press in manual_check. function manual_check_Callback(hObject, eventdata, handles) % hObject handle to manual_check (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of manual_check global img_url; if get(handles.manual_check, 'Value') == 1 h = msgbox('Please click on the BBs after clicking the analyze button'); try ci_loadingF(handles,img_url); catch h1 = msgbox('Please load an image first'); end else try ci_loadingF(handles,img_url); catch h1 = msgbox('Please load an image first'); end end % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: delete(hObject) closes the figure delete(hObject); clearvars; % --- Executes on button press in reset_button. function reset_button_Callback(hObject, eventdata, handles) % hObject handle to reset_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.wiener_check,'Value', 1); set(handles.dark_check,'Value', 1); set(handles.w_1_pop, 'string', {1:10}, 'Value', 5); set(handles.w_2_pop, 'string', {1:10}, 'Value', 5); set(handles.radius1_pop, 'string', {1:20}, 'Value', 1, 'Visible' , 'on'); set(handles.radius2_pop, 'string', {1:20}, 'Value', 3, 'Visible' , 'on'); set(handles.sensitivity_slider, 'SliderStep', [0.01, 0.1], 'Value', 0.94); set(handles.threshold_slider, 'SliderStep', [0.01, 0.1], 'Value', 0.14); set(handles.sensitivity_txt, 'String', '0.94'); set(handles.threshold_txt, 'String', '0.14'); set(handles.contrast_low_slider,'Min', 0, 'Max', 1, 'SliderStep', [0.01, 0.1], 'Value', 0); set(handles.contrast_high_slider, 'Min', 0, 'Max', 1,'SliderStep', [0.01, 0.1], 'Value', 0.8); set(handles.contrast_low_txt, 'String', '0'); set(handles.contrast_high_txt, 'String', '0.8'); set(handles.text5, 'Visible', 'off'); set(handles.dice_txt, 'Visible', 'off'); global img_url; ci_loadingF(handles,img_url);
github
andyzeng/arc-robot-vision-master
fill_depth_cross_bf.m
.m
arc-robot-vision-master/suction-based-grasping/external/bxf/fill_depth_cross_bf.m
1,990
utf_8
b7e5bbcb1bedcb7426978f7df1777af9
% In-paints the depth image using a cross-bilateral filter. The operation % is implemented via several filterings at various scales. The number of % scales is determined by the number of spacial and range sigmas provided. % 3 spacial/range sigmas translated into filtering at 3 scales. % % Args: % imgRgb - the RGB image, a uint8 HxWx3 matrix % imgDepthAbs - the absolute depth map, a HxW double matrix whose values % indicate depth in meters. % spaceSigmas - (optional) sigmas for the spacial gaussian term. % rangeSigmas - (optional) sigmas for the intensity gaussian term. % % Returns: % imgDepthAbs - the inpainted depth image. function imgDepthAbs = fill_depth_cross_bf(imgRgb, imgDepthAbs, ... spaceSigmas, rangeSigmas) error(nargchk(2,4,nargin)); assert(isa(imgRgb, 'uint8'), 'imgRgb must be uint8'); assert(isa(imgDepthAbs, 'double'), 'imgDepthAbs must be a double'); if nargin < 3 %spaceSigmas = [ 12]; spaceSigmas = [12 5 8]; end if nargin < 4 % rangeSigmas = [0.2]; rangeSigmas = [0.2 0.08 0.02]; end assert(numel(spaceSigmas) == numel(rangeSigmas)); assert(isa(rangeSigmas, 'double')); assert(isa(spaceSigmas, 'double')); % Create the 'noise' image and get the maximum observed depth. imgIsNoise = imgDepthAbs == 0 | imgDepthAbs == 10; maxDepthObs = max(imgDepthAbs(~imgIsNoise)); % If depth map is empty, exit function if isempty(maxDepthObs) return; end % Convert the depth image to uint8. imgDepth = imgDepthAbs ./ maxDepthObs; imgDepth(imgDepth > 1) = 1; imgDepth = uint8(imgDepth * 255); % Run the cross-bilateral filter. if ispc imgDepthAbs = mex_cbf_windows(imgDepth, rgb2gray(imgRgb), imgIsNoise, spaceSigmas(:), rangeSigmas(:)); else imgDepthAbs = mex_cbf(imgDepth, rgb2gray(imgRgb), imgIsNoise, spaceSigmas(:), rangeSigmas(:)); end % Convert back to absolute depth (meters). imgDepthAbs = im2double(imgDepthAbs) .* maxDepthObs; end
github
andyzeng/arc-robot-vision-master
sub2ind2d.m
.m
arc-robot-vision-master/parallel-jaw-grasping/baseline/sub2ind2d.m
135
utf_8
4970286e0c7d89b91364ca0d54668cff
% A faster version of sub2ind for 2D case function linIndex = sub2ind2d(sz, rowSub, colSub) linIndex = (colSub-1) * sz(1) + rowSub;
github
drbenvincent/darc-experiments-matlab-master
addSubFoldersToPath.m
.m
darc-experiments-matlab-master/darc-toolbox/addSubFoldersToPath.m
792
utf_8
1e9a817e1ab0ef5e56a1b36ec9f9397c
function addSubFoldersToPath() pathOfThisFunction = mfilename('fullpath'); [currentpath, ~, ~]= fileparts(pathOfThisFunction); allSubpaths = strsplit( genpath(currentpath) ,':'); blacklist={'.git','.ignore','.graffle','.'}; % '.' is any hidden folder pathsToAdd={}; for n=1:numel(allSubpaths) if shouldAddThisPath(allSubpaths{1,n},blacklist) pathsToAdd{end+1} = allSubpaths{n}; end end disp('Temporarily adding toolbox subdirecties to the path: ') fprintf('\t%s\n',pathsToAdd{:}) addpath( strjoin(pathsToAdd, ':') ) end function addThisPath = shouldAddThisPath(path,blacklist) addThisPath = true; for ignoreStr = blacklist if isStringMatch(path,ignoreStr{1}) addThisPath=false; end end end function matchFound = isStringMatch(str,pattern) matchFound = ~strfind(str,pattern); end
github
drbenvincent/darc-experiments-matlab-master
checkGitHubDependencies.m
.m
darc-experiments-matlab-master/darc-toolbox/checkGitHubDependencies.m
2,973
utf_8
30b69fd5ee94882628374c7dbfc419ea
function checkGitHubDependencies(dependencies) % This function takes a cell array of url's to hithub repositories, loop through % them and ensure they exist on the path, or clone them to your local machine. % % Example input: % % dependencies={... % 'https://github.com/drbenvincent/mcmc-utils-matlab',... % 'https://github.com/altmany/export_fig'}; assert(iscellstr(dependencies),'Input to function should be a cell array of url''s to github repositories') % ensure dependencies is a row if iscolumn(dependencies) dependencies = dependencies'; end assert(isrow(dependencies)) for url=dependencies processDependency(url{:}); end end function processDependency(url) displayDependencyToCommandWindow(url); repoName = getRepoNameFromUrl(url); if ~isRepoFolderOnPath(repoName) targetPath = fullfile(defineInstallPath(),repoName); targetPath = removeTrailingColon(targetPath); cloneGitHubRepo(url, repoName, targetPath); else updateGitHubRepo(defineInstallPath(),repoName); end end function displayDependencyToCommandWindow(url) disp( makeHyperlink(url, makeWeblinkCode(url)) ) end function repoName = getRepoNameFromUrl(url) [~,repoName] = fileparts(url); end function installPath = defineInstallPath() % installPath will be the Matlab userpath (eg /Users/Username/Documents/MATLAB) if isempty(userpath) userpath('reset') end installPath = userpath; % Fix the trailing ":" which only sometimes appears (or ";" on PC) installPath = removeTrailingColon(installPath); end function str = removeTrailingColon(str) if str(end)==systemDelimiter() str(end)=''; end end function onPath = isRepoFolderOnPath(repoName) onPath = exist(repoName,'dir')==7; end function cloneGitHubRepo(repoAddress, repoName, installPath) % ensure the folder exists %targetPath = removeTrailingColon(fullfile(defineInstallPath(),repoName)); ensureFolderExists(installPath); addpath(installPath); % do the cloning originalPath = cd; try cd(defineInstallPath()) command = sprintf('git clone %s.git', repoAddress); [status, cmdout] = system(command); catch ME rethrow(ME) end cd(originalPath) end function updateGitHubRepo(installPath,repoName) originalPath = cd; try cd(fullfile(installPath,repoName)) [status, cmdout] = system('git pull'); catch ME rethrow(ME) %warning('Unable to update GitHub repository') end cd(originalPath) end function weblinkCode = makeWeblinkCode(url) assert(ischar(url)) weblinkCode = sprintf('web(''%s'')', url); end function hyperlink = makeHyperlink(text, codeToRun) assert(ischar(text)) assert(ischar(codeToRun)) codeToRun = ['matlab: ' codeToRun]; hyperlink = sprintf('<a href="%s">%s</a>', codeToRun, text); end function delimiter = systemDelimiter() if ismac delimiter = ':'; elseif ispc delimiter = ';'; end end % TODO: Work out how to make this work in Matlab % function results = exectuteFunctionInPathProvided(func, targetPath) % originalPath = cd; % cd(targetPath) % results = func(); % cd(originalPath) % end
github
drbenvincent/darc-experiments-matlab-master
pdftops.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/pdftops.m
6,161
utf_8
5edac4bbbdae30223cb246a4ec7313d6
function varargout = pdftops(cmd) %PDFTOPS Calls a local pdftops executable with the input command % % Example: % [status result] = pdftops(cmd) % % Attempts to locate a pdftops executable, finally asking the user to % specify the directory pdftops was installed into. The resulting path is % stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have pdftops (from the Xpdf package) % installed on your system. You can download this from: % http://www.foolabs.com/xpdf % % IN: % cmd - Command string to be passed into pdftops (e.g. '-help'). % % OUT: % status - 0 iff command ran without problem. % result - Output from pdftops. % Copyright: Oliver Woodford, 2009-2010 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS. % Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path under linux. % 23/01/2014 - Add full path to pdftops.txt in warning. % 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation % 02/05/2016 - Added possible error explanation suggested by Michael Pacer (issue #137) % 02/05/2016 - Search additional possible paths suggested by Jonas Stein (issue #147) % 03/05/2016 - Display the specific error message if pdftops fails for some reason (issue #148) % Call pdftops [varargout{1:nargout}] = system([xpdf_command(xpdf_path()) cmd]); end function path_ = xpdf_path % Return a valid path % Start with the currently set path path_ = user_string('pdftops'); % Check the path works if check_xpdf_path(path_) return end % Check whether the binary is on the path if ispc bin = 'pdftops.exe'; else bin = 'pdftops'; end if check_store_xpdf_path(bin) path_ = bin; return end % Search the obvious places if ispc paths = {'C:\Program Files\xpdf\pdftops.exe', 'C:\Program Files (x86)\xpdf\pdftops.exe'}; else paths = {'/usr/bin/pdftops', '/usr/local/bin/pdftops'}; end for a = 1:numel(paths) path_ = paths{a}; if check_store_xpdf_path(path_) return end end % Ask the user to enter the path errMsg1 = 'Pdftops not found. Please locate the program, or install xpdf-tools from '; url1 = 'http://foolabs.com/xpdf'; fprintf(2, '%s\n', [errMsg1 '<a href="matlab:web(''-browser'',''' url1 ''');">' url1 '</a>']); errMsg1 = [errMsg1 url1]; %if strncmp(computer,'MAC',3) % Is a Mac % % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title % uiwait(warndlg(errMsg1)) %end % Provide an alternative possible explanation as per issue #137 errMsg2 = 'If you have pdftops installed, perhaps Matlab is shaddowing it as described in '; url2 = 'https://github.com/altmany/export_fig/issues/137'; fprintf(2, '%s\n', [errMsg2 '<a href="matlab:web(''-browser'',''' url2 ''');">issue #137</a>']); errMsg2 = [errMsg2 url1]; state = 0; while 1 if state option1 = 'Install pdftops'; else option1 = 'Issue #137'; end answer = questdlg({errMsg1,'',errMsg2},'Pdftops error',option1,'Locate pdftops','Cancel','Cancel'); drawnow; % prevent a Matlab hang: http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem switch answer case 'Install pdftops' web('-browser',url1); case 'Issue #137' web('-browser',url2); state = 1; case 'Locate pdftops' base = uigetdir('/', errMsg1); if isequal(base, 0) % User hit cancel or closed window break end base = [base filesep]; %#ok<AGROW> bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) path_ = [base bin_dir{a} bin]; if exist(path_, 'file') == 2 break end end if check_store_xpdf_path(path_) return end otherwise % User hit Cancel or closed window break end end error('pdftops executable not found.'); end function good = check_store_xpdf_path(path_) % Check the path is valid good = check_xpdf_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('pdftops', path_) warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt')); return end end function good = check_xpdf_path(path_) % Check the path is valid [good, message] = system([xpdf_command(path_) '-h']); %#ok<ASGLU> % system returns good = 1 even when the command runs % Look for something distinct in the help text good = ~isempty(strfind(message, 'PostScript')); % Display the error message if the pdftops executable exists but fails for some reason if ~good && exist(path_,'file') % file exists but generates an error fprintf('Error running %s:\n', path_); fprintf(2,'%s\n\n',message); end end function cmd = xpdf_command(path_) % Initialize any required system calls before calling ghostscript % TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh) shell_cmd = ''; if isunix % Avoids an error on Linux with outdated MATLAB lib files % R20XXa/bin/glnxa64/libtiff.so.X % R20XXa/sys/os/glnxa64/libstdc++.so.X shell_cmd = 'export LD_LIBRARY_PATH=""; '; end if ismac shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; end % Construct the command string cmd = sprintf('%s"%s" ', shell_cmd, path_); end
github
drbenvincent/darc-experiments-matlab-master
crop_borders.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/crop_borders.m
5,133
utf_8
b744bf935914cfa6d9ff82140b48291e
function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding, crop_amounts) %CROP_BORDERS Crop the borders of an image or stack of images % % [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding]) % %IN: % A - HxWxCxN stack of images. % bcol - Cx1 background colour vector. % padding - scalar indicating how much padding to have in relation to % the cropped-image-size (0<=padding<=1). Default: 0 % crop_amounts - 4-element vector of crop amounts: [top,right,bottom,left] % where NaN/Inf indicate auto-cropping, 0 means no cropping, % and any other value mean cropping in pixel amounts. % %OUT: % B - JxKxCxN cropped stack of images. % vA - coordinates in A that contain the cropped image % vB - coordinates in B where the cropped version of A is placed % bb_rel - relative bounding box (used for eps-cropping) %{ % 06/03/15: Improved image cropping thanks to Oscar Hartogensis % 08/06/15: Fixed issue #76: case of transparent figure bgcolor % 21/02/16: Enabled specifying non-automated crop amounts % 04/04/16: Fix per Luiz Carvalho for old Matlab releases % 23/10/16: Fixed issue #175: there used to be a 1px minimal padding in case of crop, now removed %} if nargin < 3 padding = 0; end if nargin < 4 crop_amounts = nan(1,4); % =auto-cropping end crop_amounts(end+1:4) = NaN; % fill missing values with NaN [h, w, c, n] = size(A); if isempty(bcol) % case of transparent bgcolor bcol = A(ceil(end/2),1,:,1); end if isscalar(bcol) bcol = bcol(ones(c, 1)); end % Crop margin from left if ~isfinite(crop_amounts(4)) bail = false; for l = 1:w for a = 1:c if ~all(col(A(:,l,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end else l = 1 + abs(crop_amounts(4)); end % Crop margin from right if ~isfinite(crop_amounts(2)) bcol = A(ceil(end/2),w,:,1); bail = false; for r = w:-1:l for a = 1:c if ~all(col(A(:,r,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end else r = w - abs(crop_amounts(2)); end % Crop margin from top if ~isfinite(crop_amounts(1)) bcol = A(1,ceil(end/2),:,1); bail = false; for t = 1:h for a = 1:c if ~all(col(A(t,:,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end else t = 1 + abs(crop_amounts(1)); end % Crop margin from bottom bcol = A(h,ceil(end/2),:,1); if ~isfinite(crop_amounts(3)) bail = false; for b = h:-1:t for a = 1:c if ~all(col(A(b,:,a,:)) == bcol(a)) bail = true; break; end end if bail break; end end else b = h - abs(crop_amounts(3)); end if padding == 0 % no padding % Issue #175: there used to be a 1px minimal padding in case of crop, now removed %{ if ~isequal([t b l r], [1 h 1 w]) % Check if we're actually croppping padding = 1; % Leave one boundary pixel to avoid bleeding on resize bcol(:) = nan; % make the 1px padding transparent end %} elseif abs(padding) < 1 % pad value is a relative fraction of image size padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING else % pad value is in units of 1/72" points padding = round(padding); % fix cases of non-integer pad value end if padding > 0 % extra padding % Create an empty image, containing the background color, that has the % cropped image size plus the padded border B = repmat(bcol,[(b-t)+1+padding*2,(r-l)+1+padding*2,1,n]); % Fix per Luiz Carvalho % vA - coordinates in A that contain the cropped image vA = [t b l r]; % vB - coordinates in B where the cropped version of A will be placed vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding]; % Place the original image in the empty image B(vB(1):vB(2), vB(3):vB(4), :, :) = A(vA(1):vA(2), vA(3):vA(4), :, :); A = B; else % extra cropping vA = [t-padding b+padding l-padding r+padding]; A = A(vA(1):vA(2), vA(3):vA(4), :, :); vB = [NaN NaN NaN NaN]; end % For EPS cropping, determine the relative BoundingBox - bb_rel bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h]; end function A = col(A) A = A(:); end
github
drbenvincent/darc-experiments-matlab-master
isolate_axes.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/isolate_axes.m
4,851
utf_8
611d9727e84ad6ba76dcb3543434d0ce
function fh = isolate_axes(ah, vis) %ISOLATE_AXES Isolate the specified axes in a figure on their own % % Examples: % fh = isolate_axes(ah) % fh = isolate_axes(ah, vis) % % This function will create a new figure containing the axes/uipanels % specified, and also their associated legends and colorbars. The objects % specified must all be in the same figure, but they will generally only be % a subset of the objects in the figure. % % IN: % ah - An array of axes and uipanel handles, which must come from the % same figure. % vis - A boolean indicating whether the new figure should be visible. % Default: false. % % OUT: % fh - The handle of the created figure. % Copyright (C) Oliver Woodford 2011-2013 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs % 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio % for pointing out that the function is also used in export_fig.m % 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it % 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!) % 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting % 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro % on FEX page as a comment on 24-Apr-2014); standardized indentation & help section % 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2 % Make sure we have an array of handles if ~all(ishandle(ah)) error('ah must be an array of handles'); end % Check that the handles are all for axes or uipanels, and are all in the same figure fh = ancestor(ah(1), 'figure'); nAx = numel(ah); for a = 1:nAx if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'}) error('All handles must be axes or uipanel handles.'); end if ~isequal(ancestor(ah(a), 'figure'), fh) error('Axes must all come from the same figure.'); end end % Tag the objects so we can find them in the copy old_tag = get(ah, 'Tag'); if nAx == 1 old_tag = {old_tag}; end set(ah, 'Tag', 'ObjectToCopy'); % Create a new figure exactly the same as the old one fh = copyfig(fh); %copyobj(fh, 0); if nargin < 2 || ~vis set(fh, 'Visible', 'off'); end % Reset the object tags for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Find the objects to save ah = findall(fh, 'Tag', 'ObjectToCopy'); if numel(ah) ~= nAx close(fh); error('Incorrect number of objects found.'); end % Set the axes tags to what they should be for a = 1:nAx set(ah(a), 'Tag', old_tag{a}); end % Keep any legends and colorbars which overlap the subplots % Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we % don't test for the type, only the tag (hopefully nobody but Matlab uses them!) lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar'); nLeg = numel(lh); if nLeg > 0 set([ah(:); lh(:)], 'Units', 'normalized'); try ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property catch ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition end if nAx > 1 ax_pos = cell2mat(ax_pos(:)); end ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2); try leg_pos = get(lh, 'OuterPosition'); catch leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1 end if nLeg > 1; leg_pos = cell2mat(leg_pos); end leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2); ax_pos = shiftdim(ax_pos, -1); % Overlap test M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ... bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ... bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ... bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2)); ah = [ah; lh(any(M, 2))]; end % Get all the objects in the figure axs = findall(fh); % Delete everything except for the input objects and associated items delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)]))); end function ah = allchildren(ah) ah = findall(ah); if iscell(ah) ah = cell2mat(ah); end ah = ah(:); end function ph = allancestors(ah) ph = []; for a = 1:numel(ah) h = get(ah(a), 'parent'); while h ~= 0 ph = [ph; h]; h = get(h, 'parent'); end end end
github
drbenvincent/darc-experiments-matlab-master
im2gif.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/im2gif.m
6,234
utf_8
8ee74d7d94e524410788276aa41dd5f1
%IM2GIF Convert a multiframe image to an animated GIF file % % Examples: % im2gif infile % im2gif infile outfile % im2gif(A, outfile) % im2gif(..., '-nocrop') % im2gif(..., '-nodither') % im2gif(..., '-ncolors', n) % im2gif(..., '-loops', n) % im2gif(..., '-delay', n) % % This function converts a multiframe image to an animated GIF. % % To create an animation from a series of figures, export to a multiframe % TIFF file using export_fig, then convert to a GIF, as follows: % % for a = 2 .^ (3:6) % peaks(a); % export_fig test.tif -nocrop -append % end % im2gif('test.tif', '-delay', 0.5); % %IN: % infile - string containing the name of the input image. % outfile - string containing the name of the output image (must have the % .gif extension). Default: infile, with .gif extension. % A - HxWxCxN array of input images, stacked along fourth dimension, to % be converted to gif. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -nodither - option indicating that dithering is not to be used when % converting the image. % -ncolors - option pair, the value of which indicates the maximum number % of colors the GIF can have. This can also be a quantization % tolerance, between 0 and 1. Default/maximum: 256. % -loops - option pair, the value of which gives the number of times the % animation is to be looped. Default: 65535. % -delay - option pair, the value of which gives the time, in seconds, % between frames. Default: 1/15. % Copyright (C) Oliver Woodford 2011 function im2gif(A, varargin) % Parse the input arguments [A, options] = parse_args(A, varargin{:}); if options.crop ~= 0 % Crop A = crop_borders(A, A(ceil(end/2),1,:,1)); end % Convert to indexed image [h, w, c, n] = size(A); A = reshape(permute(A, [1 2 4 3]), h, w*n, c); map = unique(reshape(A, h*w*n, c), 'rows'); if size(map, 1) > 256 dither_str = {'dither', 'nodither'}; dither_str = dither_str{1+(options.dither==0)}; if options.ncolors <= 1 [B, map] = rgb2ind(A, options.ncolors, dither_str); if size(map, 1) > 256 [B, map] = rgb2ind(A, 256, dither_str); end else [B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str); end else if max(map(:)) > 1 map = double(map) / 255; A = double(A) / 255; end B = rgb2ind(im2double(A), map); end B = reshape(B, h, w, 1, n); % Bug fix to rgb2ind map(B(1)+1,:) = im2double(A(1,1,:)); % Save as a gif imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay); end %% Parse the input arguments function [A, options] = parse_args(A, varargin) % Set the defaults options = struct('outfile', '', ... 'dither', true, ... 'crop', true, ... 'ncolors', 256, ... 'loops', 65535, ... 'delay', 1/15); % Go through the arguments a = 0; n = numel(varargin); while a < n a = a + 1; if ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' opt = lower(varargin{a}(2:end)); switch opt case 'nocrop' options.crop = false; case 'nodither' options.dither = false; otherwise if ~isfield(options, opt) error('Option %s not recognized', varargin{a}); end a = a + 1; if ischar(varargin{a}) && ~ischar(options.(opt)) options.(opt) = str2double(varargin{a}); else options.(opt) = varargin{a}; end end else options.outfile = varargin{a}; end end end if isempty(options.outfile) if ~ischar(A) error('No output filename given.'); end % Generate the output filename from the input filename [path, outfile] = fileparts(A); options.outfile = fullfile(path, [outfile '.gif']); end if ischar(A) % Read in the image A = imread_rgb(A); end end %% Read image to uint8 rgb array function [A, alpha] = imread_rgb(name) % Get file info info = imfinfo(name); % Special case formats switch lower(info(1).Format) case 'gif' [A, map] = imread(name, 'frames', 'all'); if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 A = permute(A, [1 2 5 4 3]); end case {'tif', 'tiff'} A = cell(numel(info), 1); for a = 1:numel(A) [A{a}, map] = imread(name, 'Index', a, 'Info', info); if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 end if size(A{a}, 3) == 4 % TIFF in CMYK colourspace - convert to RGB if isfloat(A{a}) A{a} = A{a} * 255; else A{a} = single(A{a}); end A{a} = 255 - A{a}; A{a}(:,:,4) = A{a}(:,:,4) / 255; A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4])); end end A = cat(4, A{:}); otherwise [A, map, alpha] = imread(name); A = A(:,:,:,1); % Keep only first frame of multi-frame files if ~isempty(map) map = uint8(map * 256 - 0.5); % Convert to uint8 for storage A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0 elseif size(A, 3) == 4 % Assume 4th channel is an alpha matte alpha = A(:,:,4); A = A(:,:,1:3); end end end
github
drbenvincent/darc-experiments-matlab-master
read_write_entire_textfile.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/read_write_entire_textfile.m
961
utf_8
775aa1f538c76516c7fb406a4f129320
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory % % Read or write an entire text file to/from memory, without leaving the % file open if an error occurs. % % Reading: % fstrm = read_write_entire_textfile(fname) % Writing: % read_write_entire_textfile(fname, fstrm) % %IN: % fname - Pathname of text file to be read in. % fstrm - String to be written to the file, including carriage returns. % %OUT: % fstrm - String read from the file. If an fstrm input is given the % output is the same as that input. function fstrm = read_write_entire_textfile(fname, fstrm) modes = {'rt', 'wt'}; writing = nargin > 1; fh = fopen(fname, modes{1+writing}); if fh == -1 error('Unable to open file %s.', fname); end try if writing fwrite(fh, fstrm, 'char*1'); else fstrm = fread(fh, '*char')'; end catch ex fclose(fh); rethrow(ex); end fclose(fh); end
github
drbenvincent/darc-experiments-matlab-master
pdf2eps.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/pdf2eps.m
1,522
utf_8
4c8f0603619234278ed413670d24bdb6
%PDF2EPS Convert a pdf file to eps format using pdftops % % Examples: % pdf2eps source dest % % This function converts a pdf file to eps format. % % This function requires that you have pdftops, from the Xpdf suite of % functions, installed on your system. This can be downloaded from: % http://www.foolabs.com/xpdf % %IN: % source - filename of the source pdf file to convert. The filename is % assumed to already have the extension ".pdf". % dest - filename of the destination eps file. The filename is assumed to % already have the extension ".eps". % Copyright (C) Oliver Woodford 2009-2010 % Thanks to Aldebaro Klautau for reporting a bug when saving to % non-existant directories. function pdf2eps(source, dest) % Construct the options string for pdftops options = ['-q -paper match -eps -level2 "' source '" "' dest '"']; % Convert to eps using pdftops [status, message] = pdftops(options); % Check for error if status % Report error if isempty(message) error('Unable to generate eps. Check destination directory is writable.'); else error(message); end end % Fix the DSC error created by pdftops fid = fopen(dest, 'r+'); if fid == -1 % Cannot open the file return end fgetl(fid); % Get the first line str = fgetl(fid); % Get the second line if strcmp(str(1:min(13, end)), '% Produced by') fseek(fid, -numel(str)-1, 'cof'); fwrite(fid, '%'); % Turn ' ' into '%' end fclose(fid); end
github
drbenvincent/darc-experiments-matlab-master
print2array.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/print2array.m
10,376
utf_8
a2022c32ae3efa6007a326692227bd39
function [A, bcol] = print2array(fig, res, renderer, gs_options) %PRINT2ARRAY Exports a figure to an image array % % Examples: % A = print2array % A = print2array(figure_handle) % A = print2array(figure_handle, resolution) % A = print2array(figure_handle, resolution, renderer) % A = print2array(figure_handle, resolution, renderer, gs_options) % [A bcol] = print2array(...) % % This function outputs a bitmap image of the given figure, at the desired % resolution. % % If renderer is '-painters' then ghostcript needs to be installed. This % can be downloaded from: http://www.ghostscript.com % % IN: % figure_handle - The handle of the figure to be exported. Default: gcf. % resolution - Resolution of the output, as a factor of screen % resolution. Default: 1. % renderer - string containing the renderer paramater to be passed to % print. Default: '-opengl'. % gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If % multiple options are needed, enclose in call array: {'-a','-b'} % % OUT: % A - MxNx3 uint8 image of the figure. % bcol - 1x3 uint8 vector of the background color % Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015- %{ % 05/09/11: Set EraseModes to normal when using opengl or zbuffer % renderers. Thanks to Pawel Kocieniewski for reporting the issue. % 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it. % 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size % and erasemode settings. Makes it a bit slower, but more reliable. % Thanks to Phil Trinh and Meelis Lootus for reporting the issues. % 09/12/11: Pass font path to ghostscript. % 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to % Ken Campbell for reporting it. % 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it. % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for % reporting the issue. % 26/02/15: If temp dir is not writable, use the current folder for temp % EPS/TIF files (Javier Paredes) % 27/02/15: Display suggested workarounds to internal print() error (issue #16) % 28/02/15: Enable users to specify optional ghostscript options (issue #36) % 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation % 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func) % 07/07/15: Fixed issue #83: use numeric handles in HG1 % 11/12/16: Fixed cropping issue reported by Harry D. %} % Generate default input arguments, if needed if nargin < 2 res = 1; if nargin < 1 fig = gcf; end end % Warn if output is large old_mode = get(fig, 'Units'); set(fig, 'Units', 'pixels'); px = get(fig, 'Position'); set(fig, 'Units', old_mode); npx = prod(px(3:4)*res)/1e6; if npx > 30 % 30M pixels or larger! warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx); end % Retrieve the background colour bcol = get(fig, 'Color'); % Set the resolution parameter res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))]; % Generate temporary file name tmp_nam = [tempname '.tif']; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(tmp_nam,'w'); fwrite(fid,1); fclose(fid); delete(tmp_nam); % cleanup isTempDirOk = true; catch % Temp dir is not writable, so use the current folder [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU> fpath = pwd; tmp_nam = fullfile(fpath,[fname fext]); isTempDirOk = false; end % Enable users to specify optional ghostscript options (issue #36) if nargin > 3 && ~isempty(gs_options) if iscell(gs_options) gs_options = sprintf(' %s',gs_options{:}); elseif ~ischar(gs_options) error('gs_options input argument must be a string or cell-array of strings'); else gs_options = [' ' gs_options]; end else gs_options = ''; end if nargin > 2 && strcmp(renderer, '-painters') % First try to print directly to tif file try % Print the file into a temporary TIF file and read it into array A [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam); if err, rethrow(ex); end catch % error - try to print to EPS and then using Ghostscript to TIF % Print to eps file if isTempDirOk tmp_eps = [tempname '.eps']; else tmp_eps = fullfile(fpath,[fname '.eps']); end print2eps(tmp_eps, fig, 0, renderer, '-loose'); try % Initialize the command to export to tiff using ghostscript cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc']; % Set the font path fp = font_path(); if ~isempty(fp) cmd_str = [cmd_str ' -sFONTPATH="' fp '"']; end % Add the filenames cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options]; % Execute the ghostscript command ghostscript(cmd_str); catch me % Delete the intermediate file delete(tmp_eps); rethrow(me); end % Delete the intermediate file delete(tmp_eps); % Read in the generated bitmap A = imread(tmp_nam); % Delete the temporary bitmap file delete(tmp_nam); end % Set border pixels to the correct colour if isequal(bcol, 'none') bcol = []; elseif isequal(bcol, [1 1 1]) bcol = uint8([255 255 255]); else for l = 1:size(A, 2) if ~all(reshape(A(:,l,:) == 255, [], 1)) break; end end for r = size(A, 2):-1:l if ~all(reshape(A(:,r,:) == 255, [], 1)) break; end end for t = 1:size(A, 1) if ~all(reshape(A(t,:,:) == 255, [], 1)) break; end end for b = size(A, 1):-1:t if ~all(reshape(A(b,:,:) == 255, [], 1)) break; end end bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1)); for c = 1:size(A, 3) A(:,[1:l-1, r+1:end],c) = bcol(c); A([1:t-1, b+1:end],:,c) = bcol(c); end end else if nargin < 3 renderer = '-opengl'; end % Print the file into a temporary TIF file and read it into array A [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam); % Throw any error that occurred if err % Display suggested workarounds to internal print() error (issue #16) fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n'); rethrow(ex); end % Set the background color if isequal(bcol, 'none') bcol = []; else bcol = bcol * 255; if isequal(bcol, round(bcol)) bcol = uint8(bcol); else bcol = squeeze(A(1,1,:)); end end end % Check the output size is correct if isequal(res, round(res)) px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below if ~isequal(size(A), px) % Correct the output size A = A(1:min(end,px(1)),1:min(end,px(2)),:); end end end % Function to create a TIF image of the figure and read it into an array function [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam) err = false; ex = []; % Temporarily set the paper size old_pos_mode = get(fig, 'PaperPositionMode'); old_orientation = get(fig, 'PaperOrientation'); set(fig, 'PaperPositionMode','auto', 'PaperOrientation','portrait'); try % Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function) fp = []; % in case we get an error below fp = findall(fig, 'Type','patch', 'LineWidth',0.75); set(fp, 'LineWidth',0.5); % Fix issue #83: use numeric handles in HG1 if ~using_hg2(fig), fig = double(fig); end % Print to tiff file print(fig, renderer, res_str, '-dtiff', tmp_nam); % Read in the printed file A = imread(tmp_nam); % Delete the temporary file delete(tmp_nam); catch ex err = true; end set(fp, 'LineWidth',0.75); % restore original figure appearance % Reset the paper size set(fig, 'PaperPositionMode',old_pos_mode, 'PaperOrientation',old_orientation); end % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); end
github
drbenvincent/darc-experiments-matlab-master
append_pdfs.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/append_pdfs.m
2,759
utf_8
9b52be41aff48bea6f27992396900640
%APPEND_PDFS Appends/concatenates multiple PDF files % % Example: % append_pdfs(output, input1, input2, ...) % append_pdfs(output, input_list{:}) % append_pdfs test.pdf temp1.pdf temp2.pdf % % This function appends multiple PDF files to an existing PDF file, or % concatenates them into a PDF file if the output file doesn't yet exist. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % % IN: % output - string of output file name (including the extension, .pdf). % If it exists it is appended to; if not, it is created. % input1 - string of an input file name (including the extension, .pdf). % All input files are appended in order. % input_list - cell array list of input file name strings. All input % files are appended in order. % Copyright: Oliver Woodford, 2011 % Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in % one go is much faster than appending them one at a time. % Thanks to Michael Teo for reporting the issue of a too long command line. % Issue resolved on 5/5/2011, by passing gs a command file. % Thanks to Martin Wittmann for pointing out the quality issue when % appending multiple bitmaps. % Issue resolved (to best of my ability) 1/6/2011, using the prepress % setting % 26/02/15: If temp dir is not writable, use the output folder for temp % files when appending (Javier Paredes); sanity check of inputs function append_pdfs(varargin) if nargin < 2, return; end % sanity check % Are we appending or creating a new file append = exist(varargin{1}, 'file') == 2; output = [tempname '.pdf']; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(output,'w'); fwrite(fid,1); fclose(fid); delete(output); isTempDirOk = true; catch % Temp dir is not writable, so use the output folder [dummy,fname,fext] = fileparts(output); %#ok<ASGLU> fpath = fileparts(varargin{1}); output = fullfile(fpath,[fname fext]); isTempDirOk = false; end if ~append output = varargin{1}; varargin = varargin(2:end); end % Create the command file if isTempDirOk cmdfile = [tempname '.txt']; else cmdfile = fullfile(fpath,[fname '.txt']); end fh = fopen(cmdfile, 'w'); fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output); fprintf(fh, ' "%s"', varargin{:}); fclose(fh); % Call ghostscript ghostscript(['@"' cmdfile '"']); % Delete the command file delete(cmdfile); % Rename the file if needed if append movefile(output, varargin{1}); end end
github
drbenvincent/darc-experiments-matlab-master
using_hg2.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/using_hg2.m
1,100
utf_8
47ca10d86740c27b9f6b397373ae16cd
%USING_HG2 Determine if the HG2 graphics engine is used % % tf = using_hg2(fig) % %IN: % fig - handle to the figure in question. % %OUT: % tf - boolean indicating whether the HG2 graphics engine is being used % (true) or not (false). % 19/06/2015 - Suppress warning in R2015b; cache result for improved performance % 06/06/2016 - Fixed issue #156 (bad return value in R2016b) function tf = using_hg2(fig) persistent tf_cached if isempty(tf_cached) try if nargin < 1, fig = figure('visible','off'); end oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval'); try % This generates a [supressed] warning in R2015b: tf = ~graphicsversion(fig, 'handlegraphics'); catch tf = ~verLessThan('matlab','8.4'); % =R2014b end warning(oldWarn); catch tf = false; end if nargin < 1, delete(fig); end tf_cached = tf; else tf = tf_cached; end end
github
drbenvincent/darc-experiments-matlab-master
eps2pdf.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/eps2pdf.m
8,793
utf_8
474e976cf6454d5d7850baf14494fedf
function eps2pdf(source, dest, crop, append, gray, quality, gs_options) %EPS2PDF Convert an eps file to pdf format using ghostscript % % Examples: % eps2pdf source dest % eps2pdf(source, dest, crop) % eps2pdf(source, dest, crop, append) % eps2pdf(source, dest, crop, append, gray) % eps2pdf(source, dest, crop, append, gray, quality) % eps2pdf(source, dest, crop, append, gray, quality, gs_options) % % This function converts an eps file to pdf format. The output can be % optionally cropped and also converted to grayscale. If the output pdf % file already exists then the eps file can optionally be appended as a new % page on the end of the eps file. The level of bitmap compression can also % optionally be set. % % This function requires that you have ghostscript installed on your % system. Ghostscript can be downloaded from: http://www.ghostscript.com % % Inputs: % source - filename of the source eps file to convert. The filename is % assumed to already have the extension ".eps". % dest - filename of the destination pdf file. The filename is assumed % to already have the extension ".pdf". % crop - boolean indicating whether to crop the borders off the pdf. % Default: true. % append - boolean indicating whether the eps should be appended to the % end of the pdf as a new page (if the pdf exists already). % Default: false. % gray - boolean indicating whether the output pdf should be grayscale % or not. Default: false. % quality - scalar indicating the level of image bitmap quality to % output. A larger value gives a higher quality. quality > 100 % gives lossless output. Default: ghostscript prepress default. % gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If % multiple options are needed, enclose in call array: {'-a','-b'} % Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015- % Suggestion of appending pdf files provided by Matt C at: % http://www.mathworks.com/matlabcentral/fileexchange/23629 % Thank you to Fabio Viola for pointing out compression artifacts, leading % to the quality setting. % Thank you to Scott for pointing out the subsampling of very small images, % which was fixed for lossless compression settings. % 9/12/2011 Pass font path to ghostscript. % 26/02/15: If temp dir is not writable, use the dest folder for temp % destination files (Javier Paredes) % 28/02/15: Enable users to specify optional ghostscript options (issue #36) % 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve % some /findfont errors according to James Rankin, FEX Comment 23/01/15) % 23/06/15: Added extra debug info in case of ghostscript error; code indentation % 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova) % 22/02/16: Bug fix from latest release of this file (workaround for issue #41) % 20/03/17: Added informational message in case of GS croak (issue #186) % Intialise the options string for ghostscript options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"']; % Set crop option if nargin < 3 || crop options = [options ' -dEPSCrop']; end % Set the font path fp = font_path(); if ~isempty(fp) options = [options ' -sFONTPATH="' fp '"']; end % Set the grayscale option if nargin > 4 && gray options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray']; end % Set the bitmap quality if nargin > 5 && ~isempty(quality) options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false']; if quality > 100 options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"']; else options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode']; v = 1 + (quality < 80); quality = 1 - quality / 100; s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v); options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s); end end % Enable users to specify optional ghostscript options (issue #36) if nargin > 6 && ~isempty(gs_options) if iscell(gs_options) gs_options = sprintf(' %s',gs_options{:}); elseif ~ischar(gs_options) error('gs_options input argument must be a string or cell-array of strings'); else gs_options = [' ' gs_options]; end options = [options gs_options]; end % Check if the output file exists if nargin > 3 && append && exist(dest, 'file') == 2 % File exists - append current figure to the end tmp_nam = tempname; try % Ensure that the temp dir is writable (Javier Paredes 26/2/15) fid = fopen(tmp_nam,'w'); fwrite(fid,1); fclose(fid); delete(tmp_nam); catch % Temp dir is not writable, so use the dest folder [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU> fpath = fileparts(dest); tmp_nam = fullfile(fpath,[fname fext]); end % Copy the file copyfile(dest, tmp_nam); % Add the output file names options = [options ' -f "' tmp_nam '" "' source '"']; try % Convert to pdf using ghostscript [status, message] = ghostscript(options); catch me % Delete the intermediate file delete(tmp_nam); rethrow(me); end % Delete the intermediate file delete(tmp_nam); else % File doesn't exist or should be over-written % Add the output file names options = [options ' -f "' source '"']; % Convert to pdf using ghostscript [status, message] = ghostscript(options); end % Check for error if status % Retry without the -sFONTPATH= option (this might solve some GS % /findfont errors according to James Rankin, FEX Comment 23/01/15) orig_options = options; if ~isempty(fp) options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' '); status = ghostscript(options); if ~status, return; end % hurray! (no error) end % Report error if isempty(message) error('Unable to generate pdf. Check destination directory is writable.'); elseif ~isempty(strfind(message,'/typecheck in /findfont')) % Suggest a workaround for issue #41 (missing font path) font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1')); fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name); fpath = fileparts(mfilename('fullpath')); gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt'); fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file); error('export_fig error'); else fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest); if ~isempty(gs_options) fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options); end fprintf(2, ' or maybe you have another gs executable in your system''s path\n'); fprintf(2, 'Ghostscript options: %s\n\n', orig_options); error(message); end end end % Function to return (and create, where necessary) the font path function fp = font_path() fp = user_string('gs_font_path'); if ~isempty(fp) return end % Create the path % Start with the default path fp = getenv('GS_FONTPATH'); % Add on the typical directories for a given OS if ispc if ~isempty(fp) fp = [fp ';']; end fp = [fp getenv('WINDIR') filesep 'Fonts']; else if ~isempty(fp) fp = [fp ':']; end fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; end user_string('gs_font_path', fp); end
github
drbenvincent/darc-experiments-matlab-master
export_fig.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/export_fig.m
64,681
utf_8
6eb52ba116cd2632d3e98cfafa45bca1
function [imageData, alpha] = export_fig(varargin) %EXPORT_FIG Exports figures in a publication-quality format % % Examples: % imageData = export_fig % [imageData, alpha] = export_fig % export_fig filename % export_fig filename -format1 -format2 % export_fig ... -nocrop % export_fig ... -c[<val>,<val>,<val>,<val>] % export_fig ... -transparent % export_fig ... -native % export_fig ... -m<val> % export_fig ... -r<val> % export_fig ... -a<val> % export_fig ... -q<val> % export_fig ... -p<val> % export_fig ... -d<gs_option> % export_fig ... -depsc % export_fig ... -<renderer> % export_fig ... -<colorspace> % export_fig ... -append % export_fig ... -bookmark % export_fig ... -clipboard % export_fig ... -update % export_fig ... -nofontswap % export_fig ... -font_space <char> % export_fig ... -linecaps % export_fig ... -noinvert % export_fig(..., handle) % % This function saves a figure or single axes to one or more vector and/or % bitmap file formats, and/or outputs a rasterized version to the workspace, % with the following properties: % - Figure/axes reproduced as it appears on screen % - Cropped borders (optional) % - Embedded fonts (vector formats) % - Improved line and grid line styles % - Anti-aliased graphics (bitmap formats) % - Render images at native resolution (optional for bitmap formats) % - Transparent background supported (pdf, eps, png, tiff) % - Semi-transparent patch objects supported (png, tiff) % - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff) % - Variable image compression, including lossless (pdf, eps, jpg) % - Optional rounded line-caps (pdf, eps) % - Optionally append to file (pdf, tiff) % - Vector formats: pdf, eps % - Bitmap formats: png, tiff, jpg, bmp, export to workspace % % This function is especially suited to exporting figures for use in % publications and presentations, because of the high quality and % portability of media produced. % % Note that the background color and figure dimensions are reproduced % (the latter approximately, and ignoring cropping & magnification) in the % output file. For transparent background (and semi-transparent patch % objects), use the -transparent option or set the figure 'Color' property % to 'none'. To make axes transparent set the axes 'Color' property to % 'none'. PDF, EPS, TIF & PNG are the only formats that support a transparent % background; only TIF & PNG formats support transparency of patch objects. % % The choice of renderer (opengl, zbuffer or painters) has a large impact % on the quality of output. The default value (opengl for bitmaps, painters % for vector formats) generally gives good results, but if you aren't % satisfied then try another renderer. Notes: 1) For vector formats (EPS, % PDF), only painters generates vector graphics. 2) For bitmaps, only % opengl can render transparent patch objects correctly. 3) For bitmaps, % only painters will correctly scale line dash and dot lengths when % magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when % using painters. % % When exporting to vector format (PDF & EPS) and bitmap format using the % painters renderer, this function requires that ghostscript is installed % on your system. You can download this from: % http://www.ghostscript.com % When exporting to eps it additionally requires pdftops, from the Xpdf % suite of functions. You can download this from: % http://www.foolabs.com/xpdf % % Inputs: % filename - string containing the name (optionally including full or % relative path) of the file the figure is to be saved as. If % a path is not specified, the figure is saved in the current % directory. If no name and no output arguments are specified, % the default name, 'export_fig_out', is used. If neither a % file extension nor a format are specified, a ".png" is added % and the figure saved in that format. % -format1, -format2, etc. - strings containing the extensions of the % file formats the figure is to be saved as. % Valid options are: '-pdf', '-eps', '-png', % '-tif', '-jpg' and '-bmp'. All combinations % of formats are valid. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -c[<val>,<val>,<val>,<val>] - option indicating crop amounts. Must be % a 4-element vector of numeric values: [top,right,bottom,left] % where NaN/Inf indicate auto-cropping, 0 means no cropping, % and any other value mean cropping in pixel amounts. % -transparent - option indicating that the figure background is to be % made transparent (png, pdf, tif and eps output only). % -m<val> - option where val indicates the factor to magnify the % on-screen figure pixel dimensions by when generating bitmap % outputs (does not affect vector formats). Default: '-m1'. % -r<val> - option val indicates the resolution (in pixels per inch) to % export bitmap and vector outputs at, keeping the dimensions % of the on-screen figure. Default: '-r864' (for vector output % only). Note that the -m option overides the -r option for % bitmap outputs only. % -native - option indicating that the output resolution (when outputting % a bitmap format) should be such that the vertical resolution % of the first suitable image found in the figure is at the % native resolution of that image. To specify a particular % image to use, give it the tag 'export_fig_native'. Notes: % This overrides any value set with the -m and -r options. It % also assumes that the image is displayed front-to-parallel % with the screen. The output resolution is approximate and % should not be relied upon. Anti-aliasing can have adverse % effects on image quality (disable with the -a1 option). % -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to % use for bitmap outputs. '-a1' means no anti- % aliasing; '-a4' is the maximum amount (default). % -<renderer> - option to force a particular renderer (painters, opengl or % zbuffer). Default value: opengl for bitmap formats or % figures with patches and/or transparent annotations; % painters for vector formats without patches/transparencies. % -<colorspace> - option indicating which colorspace color figures should % be saved in: RGB (default), CMYK or gray. CMYK is only % supported in pdf, eps and tiff output. % -q<val> - option to vary bitmap image quality (in pdf, eps and jpg % files only). Larger val, in the range 0-100, gives higher % quality/lower compression. val > 100 gives lossless % compression. Default: '-q95' for jpg, ghostscript prepress % default for pdf & eps. Note: lossless compression can % sometimes give a smaller file size than the default lossy % compression, depending on the type of images. % -p<val> - option to pad a border of width val to exported files, where % val is either a relative size with respect to cropped image % size (i.e. p=0.01 adds a 1% border). For EPS & PDF formats, % val can also be integer in units of 1/72" points (abs(val)>1). % val can be positive (padding) or negative (extra cropping). % If used, the -nocrop flag will be ignored, i.e. the image will % always be cropped and then padded. Default: 0 (i.e. no padding). % -append - option indicating that if the file (pdfs only) already % exists, the figure is to be appended as a new page, instead % of being overwritten (default). % -bookmark - option to indicate that a bookmark with the name of the % figure is to be created in the output file (pdf only). % -clipboard - option to save output as an image on the system clipboard. % Note: background transparency is not preserved in clipboard % -d<gs_option> - option to indicate a ghostscript setting. For example, % -dMaxBitmap=0 or -dNoOutputFonts (Ghostscript 9.15+). % -depsc - option to use EPS level-3 rather than the default level-2 print % device. This solves some bugs with Matlab's default -depsc2 device % such as discolored subplot lines on images (vector formats only). % -update - option to download and install the latest version of export_fig % -nofontswap - option to avoid font swapping. Font swapping is automatically % done in vector formats (only): 11 standard Matlab fonts are % replaced by the original figure fonts. This option prevents this. % -font_space <char> - option to set a spacer character for font-names that % contain spaces, used by EPS/PDF. Default: '' % -linecaps - option to create rounded line-caps (vector formats only). % -noinvert - option to avoid setting figure's InvertHardcopy property to % 'off' during output (this solves some problems of empty outputs). % handle - The handle of the figure, axes or uipanels (can be an array of % handles, but the objects must be in the same figure) to be % saved. Default: gcf. % % Outputs: % imageData - MxNxC uint8 image array of the exported image. % alpha - MxN single array of alphamatte values in the range [0,1], % for the case when the background is transparent. % % Some helpful examples and tips can be found at: % https://github.com/altmany/export_fig % % See also PRINT, SAVEAS, ScreenCapture (on the Matlab File Exchange) %{ % Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015- % The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG % (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782). % The idea for using pdftops came from the MATLAB newsgroup (id: 168171). % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928). % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id: % 20979). % The idea of appending figures in pdfs came from Matt C in comments on the % FEX (id: 23629) % Thanks to Roland Martin for pointing out the colour MATLAB % bug/feature with colorbar axes and transparent backgrounds. % Thanks also to Andrew Matthews for describing a bug to do with the figure % size changing in -nodisplay mode. I couldn't reproduce it, but included a % fix anyway. % Thanks to Tammy Threadgill for reporting a bug where an axes is not % isolated from gui objects. %} %{ % 23/02/12: Ensure that axes limits don't change during printing % 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for reporting it). % 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling bookmarking of figures in pdf files. % 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep tick marks fixed. % 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it. % 25/09/13: Add support for changing resolution in vector formats. Thanks to Jan Jaap Meijer for suggesting it. % 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner for suggesting it. % 24/02/15: Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual' % 25/02/15: Fix issue #4 (using HG2 on R2014a and earlier) % 25/02/15: Fix issue #21 (bold TeX axes labels/titles in R2014b) % 26/02/15: If temp dir is not writable, use the user-specified folder for temporary EPS/PDF files (Javier Paredes) % 27/02/15: Modified repository URL from github.com/ojwoodford to /altmany % Indented main function % Added top-level try-catch block to display useful workarounds % 28/02/15: Enable users to specify optional ghostscript options (issue #36) % 06/03/15: Improved image padding & cropping thanks to Oscar Hartogensis % 26/03/15: Fixed issue #49 (bug with transparent grayscale images); fixed out-of-memory issue % 26/03/15: Fixed issue #42: non-normalized annotations on HG1 % 26/03/15: Fixed issue #46: Ghostscript crash if figure units <> pixels % 27/03/15: Fixed issue #39: bad export of transparent annotations/patches % 28/03/15: Fixed issue #50: error on some Matlab versions with the fix for issue #42 % 29/03/15: Fixed issue #33: bugs in Matlab's print() function with -cmyk % 29/03/15: Improved processing of input args (accept space between param name & value, related to issue #51) % 30/03/15: When exporting *.fig files, then saveas *.fig if figure is open, otherwise export the specified fig file % 30/03/15: Fixed edge case bug introduced yesterday (commit #ae1755bd2e11dc4e99b95a7681f6e211b3fa9358) % 09/04/15: Consolidated header comment sections; initialize output vars only if requested (nargout>0) % 14/04/15: Workaround for issue #45: lines in image subplots are exported in invalid color % 15/04/15: Fixed edge-case in parsing input parameters; fixed help section to show the -depsc option (issue #45) % 21/04/15: Bug fix: Ghostscript croaks on % chars in output PDF file (reported by Sven on FEX page, 15-Jul-2014) % 22/04/15: Bug fix: Pdftops croaks on relative paths (reported by Tintin Milou on FEX page, 19-Jan-2015) % 04/05/15: Merged fix #63 (Kevin Mattheus Moerman): prevent tick-label changes during export % 07/05/15: Partial fix for issue #65: PDF export used painters rather than opengl renderer (thanks Nguyenr) % 08/05/15: Fixed issue #65: bad PDF append since commit #e9f3cdf 21/04/15 (thanks Robert Nguyen) % 12/05/15: Fixed issue #67: exponent labels cropped in export, since fix #63 (04/05/15) % 28/05/15: Fixed issue #69: set non-bold label font only if the string contains symbols (\beta etc.), followup to issue #21 % 29/05/15: Added informative error message in case user requested SVG output (issue #72) % 09/06/15: Fixed issue #58: -transparent removed anti-aliasing when exporting to PNG % 19/06/15: Added -update option to download and install the latest version of export_fig % 07/07/15: Added -nofontswap option to avoid font-swapping in EPS/PDF % 16/07/15: Fixed problem with anti-aliasing on old Matlab releases % 11/09/15: Fixed issue #103: magnification must never become negative; also fixed reported error msg in parsing input params % 26/09/15: Alert if trying to export transparent patches/areas to non-PNG outputs (issue #108) % 04/10/15: Do not suggest workarounds for certain errors that have already been handled previously % 01/11/15: Fixed issue #112: use same renderer in print2eps as export_fig (thanks to Jesús Pestana Puerta) % 10/11/15: Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX % 19/11/15: Fixed clipboard export in R2015b (thanks to Dan K via FEX) % 21/02/16: Added -c option for indicating specific crop amounts (idea by Cedric Noordam on FEX) % 08/05/16: Added message about possible error reason when groot.Units~=pixels (issue #149) % 17/05/16: Fixed case of image YData containing more than 2 elements (issue #151) % 08/08/16: Enabled exporting transparency to TIF, in addition to PNG/PDF (issue #168) % 11/12/16: Added alert in case of error creating output PDF/EPS file (issue #179) % 13/12/16: Minor fix to the commit for issue #179 from 2 days ago % 22/03/17: Fixed issue #187: only set manual ticks when no exponent is present % 09/04/17: Added -linecaps option (idea by Baron Finer, issue #192) % 15/09/17: Fixed issue #205: incorrect tick-labels when Ticks number don't match the TickLabels number % 15/09/17: Fixed issue #210: initialize alpha map to ones instead of zeros when -transparent is not used % 18/09/17: Added -font_space option to replace font-name spaces in EPS/PDF (workaround for issue #194) % 18/09/17: Added -noinvert option to solve some export problems with some graphic cards (workaround for issue #197) %} if nargout [imageData, alpha] = deal([]); end hadError = false; displaySuggestedWorkarounds = true; % Ensure the figure is rendered correctly _now_ so that properties like axes limits are up-to-date drawnow; pause(0.05); % this solves timing issues with Java Swing's EDT (http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem) % Parse the input arguments fig = get(0, 'CurrentFigure'); [fig, options] = parse_args(nargout, fig, varargin{:}); % Ensure that we have a figure handle if isequal(fig,-1) return; % silent bail-out elseif isempty(fig) error('No figure found'); end % Isolate the subplot, if it is one cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'})); if cls % Given handles of one or more axes, so isolate them from the rest fig = isolate_axes(fig); else % Check we have a figure if ~isequal(get(fig, 'Type'), 'figure') error('Handle must be that of a figure, axes or uipanel'); end % Get the old InvertHardcopy mode old_mode = get(fig, 'InvertHardcopy'); end % Hack the font units where necessary (due to a font rendering bug in print?). % This may not work perfectly in all cases. % Also it can change the figure layout if reverted, so use a copy. magnify = options.magnify * options.aa_factor; if isbitmap(options) && magnify ~= 1 fontu = findall(fig, 'FontUnits', 'normalized'); if ~isempty(fontu) % Some normalized font units found if ~cls fig = copyfig(fig); set(fig, 'Visible', 'off'); fontu = findall(fig, 'FontUnits', 'normalized'); cls = true; end set(fontu, 'FontUnits', 'points'); end end try % MATLAB "feature": axes limits and tick marks can change when printing Hlims = findall(fig, 'Type', 'axes'); if ~cls % Record the old axes limit and tick modes Xlims = make_cell(get(Hlims, 'XLimMode')); Ylims = make_cell(get(Hlims, 'YLimMode')); Zlims = make_cell(get(Hlims, 'ZLimMode')); Xtick = make_cell(get(Hlims, 'XTickMode')); Ytick = make_cell(get(Hlims, 'YTickMode')); Ztick = make_cell(get(Hlims, 'ZTickMode')); Xlabel = make_cell(get(Hlims, 'XTickLabelMode')); Ylabel = make_cell(get(Hlims, 'YTickLabelMode')); Zlabel = make_cell(get(Hlims, 'ZTickLabelMode')); end % Set all axes limit and tick modes to manual, so the limits and ticks can't change % Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual' set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual'); set_tick_mode(Hlims, 'X'); set_tick_mode(Hlims, 'Y'); if ~using_hg2(fig) set(Hlims,'ZLimMode', 'manual'); set_tick_mode(Hlims, 'Z'); end catch % ignore - fix issue #4 (using HG2 on R2014a and earlier) end % Fix issue #21 (bold TeX axes labels/titles in R2014b when exporting to EPS/PDF) try if using_hg2(fig) && isvector(options) % Set the FontWeight of axes labels/titles to 'normal' % Fix issue #69: set non-bold font only if the string contains symbols (\beta etc.) texLabels = findall(fig, 'type','text', 'FontWeight','bold'); symbolIdx = ~cellfun('isempty',strfind({texLabels.String},'\')); set(texLabels(symbolIdx), 'FontWeight','normal'); end catch % ignore end % Fix issue #42: non-normalized annotations on HG1 (internal Matlab bug) annotationHandles = []; try if ~using_hg2(fig) annotationHandles = findall(fig,'Type','hggroup','-and','-property','Units','-and','-not','Units','norm'); try % suggested by Jesús Pestana Puerta (jespestana) 30/9/2015 originalUnits = get(annotationHandles,'Units'); set(annotationHandles,'Units','norm'); catch end end catch % should never happen, but ignore in any case - issue #50 end % Fix issue #46: Ghostscript crash if figure units <> pixels oldFigUnits = get(fig,'Units'); set(fig,'Units','pixels'); % Set to print exactly what is there if options.invert_hardcopy set(fig, 'InvertHardcopy', 'off'); end % Set the renderer switch options.renderer case 1 renderer = '-opengl'; case 2 renderer = '-zbuffer'; case 3 renderer = '-painters'; otherwise renderer = '-opengl'; % Default for bitmaps end % Handle transparent patches hasTransparency = ~isempty(findall(fig,'-property','FaceAlpha','-and','-not','FaceAlpha',1)); hasPatches = ~isempty(findall(fig,'type','patch')); if hasTransparency % Alert if trying to export transparent patches/areas to non-supported outputs (issue #108) % http://www.mathworks.com/matlabcentral/answers/265265-can-export_fig-or-else-draw-vector-graphics-with-transparent-surfaces % TODO - use transparency when exporting to PDF by not passing via print2eps msg = 'export_fig currently supports transparent patches/areas only in PNG output. '; if options.pdf warning('export_fig:transparency', '%s\nTo export transparent patches/areas to PDF, use the print command:\n print(gcf, ''-dpdf'', ''%s.pdf'');', msg, options.name); elseif ~options.png && ~options.tif % issue #168 warning('export_fig:transparency', '%s\nTo export the transparency correctly, try using the ScreenCapture utility on the Matlab File Exchange: http://bit.ly/1QFrBip', msg); end end try % Do the bitmap formats first if isbitmap(options) if abs(options.bb_padding) > 1 displaySuggestedWorkarounds = false; error('For bitmap output (png,jpg,tif,bmp) the padding value (-p) must be between -1<p<1') end % Get the background colour if options.transparent && (options.png || options.alpha) % Get out an alpha channel % MATLAB "feature": black colorbar axes can change to white and vice versa! hCB = findall(fig, 'Type','axes', 'Tag','Colorbar'); if isempty(hCB) yCol = []; xCol = []; else yCol = get(hCB, 'YColor'); xCol = get(hCB, 'XColor'); if iscell(yCol) yCol = cell2mat(yCol); xCol = cell2mat(xCol); end yCol = sum(yCol, 2); xCol = sum(xCol, 2); end % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); % Set the background colour to black, and set size in case it was % changed internally tcol = get(fig, 'Color'); set(fig, 'Color', 'k', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==0), 'YColor', [0 0 0]); set(hCB(xCol==0), 'XColor', [0 0 0]); % The following code might cause out-of-memory errors try % Print large version to array B = print2array(fig, magnify, renderer); % Downscale the image B = downsize(single(B), options.aa_factor); catch % This is more conservative in memory, but kills transparency (issue #58) B = single(print2array(fig, magnify/options.aa_factor, renderer)); end % Set background to white (and set size) set(fig, 'Color', 'w', 'Position', pos); % Correct the colorbar axes colours set(hCB(yCol==3), 'YColor', [1 1 1]); set(hCB(xCol==3), 'XColor', [1 1 1]); % The following code might cause out-of-memory errors try % Print large version to array A = print2array(fig, magnify, renderer); % Downscale the image A = downsize(single(A), options.aa_factor); catch % This is more conservative in memory, but kills transparency (issue #58) A = single(print2array(fig, magnify/options.aa_factor, renderer)); end % Set the background colour (and size) back to normal set(fig, 'Color', tcol, 'Position', pos); % Compute the alpha map alpha = round(sum(B - A, 3)) / (255 * 3) + 1; A = alpha; A(A==0) = 1; A = B ./ A(:,:,[1 1 1]); clear B % Convert to greyscale if options.colourspace == 2 A = rgb2grey(A); end A = uint8(A); % Crop the background if options.crop %[alpha, v] = crop_borders(alpha, 0, 1, options.crop_amounts); %A = A(v(1):v(2),v(3):v(4),:); [alpha, vA, vB] = crop_borders(alpha, 0, options.bb_padding, options.crop_amounts); if ~any(isnan(vB)) % positive padding B = repmat(uint8(zeros(1,1,size(A,3))),size(alpha)); B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :); % ADDED BY OH A = B; else % negative padding A = A(vA(1):vA(2), vA(3):vA(4), :); end end if options.png % Compute the resolution res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; % Save the png imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); % Clear the png bit options.png = false; end % Return only one channel for greyscale if isbitmap(options) A = check_greyscale(A); end if options.alpha % Store the image imageData = A; % Clear the alpha bit options.alpha = false; end % Get the non-alpha image if isbitmap(options) alph = alpha(:,:,ones(1, size(A, 3))); A = uint8(single(A) .* alph + 255 * (1 - alph)); clear alph end if options.im % Store the new image imageData = A; end else % Print large version to array if options.transparent % MATLAB "feature": apparently figure size can change when changing % colour in -nodisplay mode pos = get(fig, 'Position'); tcol = get(fig, 'Color'); set(fig, 'Color', 'w', 'Position', pos); A = print2array(fig, magnify, renderer); set(fig, 'Color', tcol, 'Position', pos); tcol = 255; else [A, tcol] = print2array(fig, magnify, renderer); end % Crop the background if options.crop A = crop_borders(A, tcol, options.bb_padding, options.crop_amounts); end % Downscale the image A = downsize(A, options.aa_factor); if options.colourspace == 2 % Convert to greyscale A = rgb2grey(A); else % Return only one channel for greyscale A = check_greyscale(A); end % Outputs if options.im imageData = A; end if options.alpha imageData = A; alpha = ones(size(A, 1), size(A, 2), 'single'); end end % Save the images if options.png res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); end if options.bmp imwrite(A, [options.name '.bmp']); end % Save jpeg with given quality if options.jpg quality = options.quality; if isempty(quality) quality = 95; end if quality > 100 imwrite(A, [options.name '.jpg'], 'Mode', 'lossless'); else imwrite(A, [options.name '.jpg'], 'Quality', quality); end end % Save tif images in cmyk if wanted (and possible) if options.tif if options.colourspace == 1 && size(A, 3) == 3 A = double(255 - A); K = min(A, [], 3); K_ = 255 ./ max(255 - K, 1); C = (A(:,:,1) - K) .* K_; M = (A(:,:,2) - K) .* K_; Y = (A(:,:,3) - K) .* K_; A = uint8(cat(3, C, M, Y, K)); clear C M Y K K_ end append_mode = {'overwrite', 'append'}; imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1}); end end % Now do the vector formats if isvector(options) % Set the default renderer to painters if ~options.renderer if hasTransparency || hasPatches % This is *MUCH* slower, but more accurate for patches and transparent annotations (issue #39) renderer = '-opengl'; else renderer = '-painters'; end end options.rendererStr = renderer; % fix for issue #112 % Generate some filenames tmp_nam = [tempname '.eps']; try % Ensure that the temp dir is writable (Javier Paredes 30/1/15) fid = fopen(tmp_nam,'w'); fwrite(fid,1); fclose(fid); delete(tmp_nam); isTempDirOk = true; catch % Temp dir is not writable, so use the user-specified folder [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU> fpath = fileparts(options.name); tmp_nam = fullfile(fpath,[fname fext]); isTempDirOk = false; end if isTempDirOk pdf_nam_tmp = [tempname '.pdf']; else pdf_nam_tmp = fullfile(fpath,[fname '.pdf']); end if options.pdf pdf_nam = [options.name '.pdf']; try copyfile(pdf_nam, pdf_nam_tmp, 'f'); catch, end % fix for issue #65 else pdf_nam = pdf_nam_tmp; end % Generate the options for print p2eArgs = {renderer, sprintf('-r%d', options.resolution)}; if options.colourspace == 1 % CMYK % Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option %p2eArgs{end+1} = '-cmyk'; end if ~options.crop % Issue #56: due to internal bugs in Matlab's print() function, we can't use its internal cropping mechanism, % therefore we always use '-loose' (in print2eps.m) and do our own cropping (in crop_borders) %p2eArgs{end+1} = '-loose'; end if any(strcmpi(varargin,'-depsc')) % Issue #45: lines in image subplots are exported in invalid color. % The workaround is to use the -depsc parameter instead of the default -depsc2 p2eArgs{end+1} = '-depsc'; end try % Generate an eps print2eps(tmp_nam, fig, options, p2eArgs{:}); % Remove the background, if desired if options.transparent && ~isequal(get(fig, 'Color'), 'none') eps_remove_background(tmp_nam, 1 + using_hg2(fig)); end % Fix colorspace to CMYK, if requested (workaround for issue #33) if options.colourspace == 1 % CMYK % Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option change_rgb_to_cmyk(tmp_nam); end % Add a bookmark to the PDF if desired if options.bookmark fig_nam = get(fig, 'Name'); if isempty(fig_nam) warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.'); end add_bookmark(tmp_nam, fig_nam); end % Generate a pdf eps2pdf(tmp_nam, pdf_nam_tmp, 1, options.append, options.colourspace==2, options.quality, options.gs_options); % Ghostscript croaks on % chars in the output PDF file, so use tempname and then rename the file try % Rename the file (except if it is already the same) % Abbie K's comment on the commit for issue #179 (#commitcomment-20173476) if ~isequal(pdf_nam_tmp, pdf_nam) movefile(pdf_nam_tmp, pdf_nam, 'f'); end catch % Alert in case of error creating output PDF/EPS file (issue #179) if exist(pdf_nam_tmp, 'file') error(['Could not create ' pdf_nam ' - perhaps the folder does not exist, or you do not have write permissions']); else error('Could not generate the intermediary EPS file.'); end end catch ex % Delete the eps delete(tmp_nam); rethrow(ex); end % Delete the eps delete(tmp_nam); if options.eps || options.linecaps try % Generate an eps from the pdf % since pdftops can't handle relative paths (e.g., '..\'), use a temp file eps_nam_tmp = strrep(pdf_nam_tmp,'.pdf','.eps'); pdf2eps(pdf_nam, eps_nam_tmp); % Issue #192: enable rounded line-caps if options.linecaps fstrm = read_write_entire_textfile(eps_nam_tmp); fstrm = regexprep(fstrm, '[02] J', '1 J'); read_write_entire_textfile(eps_nam_tmp, fstrm); if options.pdf eps2pdf(eps_nam_tmp, pdf_nam, 1, options.append, options.colourspace==2, options.quality, options.gs_options); end end if options.eps movefile(eps_nam_tmp, [options.name '.eps'], 'f'); else % if options.pdf try delete(eps_nam_tmp); catch, end end catch ex if ~options.pdf % Delete the pdf delete(pdf_nam); end try delete(eps_nam_tmp); catch, end rethrow(ex); end if ~options.pdf % Delete the pdf delete(pdf_nam); end end end % Revert the figure or close it (if requested) if cls || options.closeFig % Close the created figure close(fig); else % Reset the hardcopy mode set(fig, 'InvertHardcopy', old_mode); % Reset the axes limit and tick modes for a = 1:numel(Hlims) try set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a},... 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a},... 'XTickLabelMode', Xlabel{a}, 'YTickLabelMode', Ylabel{a}, 'ZTickLabelMode', Zlabel{a}); catch % ignore - fix issue #4 (using HG2 on R2014a and earlier) end end % Revert the tex-labels font weights try set(texLabels, 'FontWeight','bold'); catch, end % Revert annotation units for handleIdx = 1 : numel(annotationHandles) try oldUnits = originalUnits{handleIdx}; catch oldUnits = originalUnits; end try set(annotationHandles(handleIdx),'Units',oldUnits); catch, end end % Revert figure units set(fig,'Units',oldFigUnits); end % Output to clipboard (if requested) if options.clipboard % Delete the output file if unchanged from the default name ('export_fig_out.png') if strcmpi(options.name,'export_fig_out') try fileInfo = dir('export_fig_out.png'); if ~isempty(fileInfo) timediff = now - fileInfo.datenum; ONE_SEC = 1/24/60/60; if timediff < ONE_SEC delete('export_fig_out.png'); end end catch % never mind... end end % Save the image in the system clipboard % credit: Jiro Doke's IMCLIPBOARD: http://www.mathworks.com/matlabcentral/fileexchange/28708-imclipboard try error(javachk('awt', 'export_fig -clipboard output')); catch warning('export_fig -clipboard output failed: requires Java to work'); return; end try % Import necessary Java classes import java.awt.Toolkit import java.awt.image.BufferedImage import java.awt.datatransfer.DataFlavor % Get System Clipboard object (java.awt.Toolkit) cb = Toolkit.getDefaultToolkit.getSystemClipboard(); % Add java class (ImageSelection) to the path if ~exist('ImageSelection', 'class') javaaddpath(fileparts(which(mfilename)), '-end'); end % Get image size ht = size(imageData, 1); wd = size(imageData, 2); % Convert to Blue-Green-Red format try imageData2 = imageData(:, :, [3 2 1]); catch % Probably gray-scaled image (2D, without the 3rd [RGB] dimension) imageData2 = imageData(:, :, [1 1 1]); end % Convert to 3xWxH format imageData2 = permute(imageData2, [3, 2, 1]); % Append Alpha data (unused - transparency is not supported in clipboard copy) alphaData2 = uint8(permute(255*alpha,[3,2,1])); %=255*ones(1,wd,ht,'uint8') imageData2 = cat(1, imageData2, alphaData2); % Create image buffer imBuffer = BufferedImage(wd, ht, BufferedImage.TYPE_INT_RGB); imBuffer.setRGB(0, 0, wd, ht, typecast(imageData2(:), 'int32'), 0, wd); % Create ImageSelection object from the image buffer imSelection = ImageSelection(imBuffer); % Set clipboard content to the image cb.setContents(imSelection, []); catch warning('export_fig -clipboard output failed: %s', lasterr); %#ok<LERR> end end % Don't output the data to console unless requested if ~nargout clear imageData alpha end catch err % Display possible workarounds before the error message if displaySuggestedWorkarounds && ~strcmpi(err.message,'export_fig error') if ~hadError, fprintf(2, 'export_fig error. '); end fprintf(2, 'Please ensure:\n'); fprintf(2, ' that you are using the <a href="https://github.com/altmany/export_fig/archive/master.zip">latest version</a> of export_fig\n'); if ismac fprintf(2, ' and that you have <a href="http://pages.uoregon.edu/koch">Ghostscript</a> installed\n'); else fprintf(2, ' and that you have <a href="http://www.ghostscript.com">Ghostscript</a> installed\n'); end try if options.eps fprintf(2, ' and that you have <a href="http://www.foolabs.com/xpdf">pdftops</a> installed\n'); end catch % ignore - probably an error in parse_args end fprintf(2, ' and that you do not have <a href="matlab:which export_fig -all">multiple versions</a> of export_fig installed by mistake\n'); fprintf(2, ' and that you did not made a mistake in the <a href="matlab:help export_fig">expected input arguments</a>\n'); try % Alert per issue #149 if ~strncmpi(get(0,'Units'),'pixel',5) fprintf(2, ' or try to set groot''s Units property back to its default value of ''pixels'' (<a href="matlab:web(''https://github.com/altmany/export_fig/issues/149'',''-browser'');">details</a>)\n'); end catch % ignore - maybe an old MAtlab release end fprintf(2, '\nIf the problem persists, then please <a href="https://github.com/altmany/export_fig/issues">report a new issue</a>.\n\n'); end rethrow(err) end end function options = default_options() % Default options used by export_fig options = struct(... 'name', 'export_fig_out', ... 'crop', true, ... 'crop_amounts', nan(1,4), ... % auto-crop all 4 image sides 'transparent', false, ... 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters 'pdf', false, ... 'eps', false, ... 'png', false, ... 'tif', false, ... 'jpg', false, ... 'bmp', false, ... 'clipboard', false, ... 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray 'append', false, ... 'im', false, ... 'alpha', false, ... 'aa_factor', 0, ... 'bb_padding', 0, ... 'magnify', [], ... 'resolution', [], ... 'bookmark', false, ... 'closeFig', false, ... 'quality', [], ... 'update', false, ... 'fontswap', true, ... 'font_space', '', ... 'linecaps', false, ... 'invert_hardcopy', true, ... 'gs_options', {{}}); end function [fig, options] = parse_args(nout, fig, varargin) % Parse the input arguments % Set the defaults native = false; % Set resolution to native of an image options = default_options(); options.im = (nout == 1); % user requested imageData output options.alpha = (nout == 2); % user requested alpha output % Go through the other arguments skipNext = false; for a = 1:nargin-2 if skipNext skipNext = false; continue; end if all(ishandle(varargin{a})) fig = varargin{a}; elseif ischar(varargin{a}) && ~isempty(varargin{a}) if varargin{a}(1) == '-' switch lower(varargin{a}(2:end)) case 'nocrop' options.crop = false; options.crop_amounts = [0,0,0,0]; case {'trans', 'transparent'} options.transparent = true; case 'opengl' options.renderer = 1; case 'zbuffer' options.renderer = 2; case 'painters' options.renderer = 3; case 'pdf' options.pdf = true; case 'eps' options.eps = true; case 'png' options.png = true; case {'tif', 'tiff'} options.tif = true; case {'jpg', 'jpeg'} options.jpg = true; case 'bmp' options.bmp = true; case 'rgb' options.colourspace = 0; case 'cmyk' options.colourspace = 1; case {'gray', 'grey'} options.colourspace = 2; case {'a1', 'a2', 'a3', 'a4'} options.aa_factor = str2double(varargin{a}(3)); case 'append' options.append = true; case 'bookmark' options.bookmark = true; case 'native' native = true; case 'clipboard' options.clipboard = true; options.im = true; options.alpha = true; case 'svg' msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\n' ... ' 1. saveas(gcf,''filename.svg'')\n' ... ' 2. plot2svg utility: http://github.com/jschwizer99/plot2svg\n' ... ' 3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\n']; error(sprintf(msg)); %#ok<SPERR> case 'update' % Download the latest version of export_fig into the export_fig folder try zipFileName = 'https://github.com/altmany/export_fig/archive/master.zip'; folderName = fileparts(which(mfilename('fullpath'))); targetFileName = fullfile(folderName, datestr(now,'yyyy-mm-dd.zip')); urlwrite(zipFileName,targetFileName); catch error('Could not download %s into %s\n',zipFileName,targetFileName); end % Unzip the downloaded zip file in the export_fig folder try unzip(targetFileName,folderName); catch error('Could not unzip %s\n',targetFileName); end case 'nofontswap' options.fontswap = false; case 'font_space' options.font_space = varargin{a+1}; skipNext = true; case 'linecaps' options.linecaps = true; case 'noinvert' options.invert_hardcopy = false; otherwise try wasError = false; if strcmpi(varargin{a}(1:2),'-d') varargin{a}(2) = 'd'; % ensure lowercase 'd' options.gs_options{end+1} = varargin{a}; elseif strcmpi(varargin{a}(1:2),'-c') if numel(varargin{a})==2 skipNext = true; vals = str2num(varargin{a+1}); %#ok<ST2NM> else vals = str2num(varargin{a}(3:end)); %#ok<ST2NM> end if numel(vals)~=4 wasError = true; error('option -c cannot be parsed: must be a 4-element numeric vector'); end options.crop_amounts = vals; options.crop = true; else % scalar parameter value val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match')); if isempty(val) || isnan(val) % Issue #51: improved processing of input args (accept space between param name & value) val = str2double(varargin{a+1}); if isscalar(val) && ~isnan(val) skipNext = true; end end if ~isscalar(val) || isnan(val) wasError = true; error('option %s is not recognised or cannot be parsed', varargin{a}); end switch lower(varargin{a}(2)) case 'm' % Magnification may never be negative if val <= 0 wasError = true; error('Bad magnification value: %g (must be positive)', val); end options.magnify = val; case 'r' options.resolution = val; case 'q' options.quality = max(val, 0); case 'p' options.bb_padding = val; end end catch err % We might have reached here by raising an intentional error if wasError % intentional raise rethrow(err) else % unintentional error(['Unrecognized export_fig input option: ''' varargin{a} '''']); end end end else [p, options.name, ext] = fileparts(varargin{a}); if ~isempty(p) options.name = [p filesep options.name]; end switch lower(ext) case {'.tif', '.tiff'} options.tif = true; case {'.jpg', '.jpeg'} options.jpg = true; case '.png' options.png = true; case '.bmp' options.bmp = true; case '.eps' options.eps = true; case '.pdf' options.pdf = true; case '.fig' % If no open figure, then load the specified .fig file and continue if isempty(fig) fig = openfig(varargin{a},'invisible'); varargin{a} = fig; options.closeFig = true; else % save the current figure as the specified .fig file and exit saveas(fig(1),varargin{a}); fig = -1; return end case '.svg' msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\n' ... ' 1. saveas(gcf,''filename.svg'')\n' ... ' 2. plot2svg utility: http://github.com/jschwizer99/plot2svg\n' ... ' 3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\n']; error(sprintf(msg)); %#ok<SPERR> otherwise options.name = varargin{a}; end end end end % Quick bail-out if no figure found if isempty(fig), return; end % Do border padding with repsect to a cropped image if options.bb_padding options.crop = true; end % Set default anti-aliasing now we know the renderer if options.aa_factor == 0 try isAA = strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on'); catch, isAA = false; end options.aa_factor = 1 + 2 * (~(using_hg2(fig) && isAA) | (options.renderer == 3)); end % Convert user dir '~' to full path if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\') options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end)); end % Compute the magnification and resolution if isempty(options.magnify) if isempty(options.resolution) options.magnify = 1; options.resolution = 864; else options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch'); end elseif isempty(options.resolution) options.resolution = 864; end % Set the default format if ~isvector(options) && ~isbitmap(options) options.png = true; end % Check whether transparent background is wanted (old way) if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none') options.transparent = true; end % If requested, set the resolution to the native vertical resolution of the % first suitable image found if native && isbitmap(options) % Find a suitable image list = findall(fig, 'Type','image', 'Tag','export_fig_native'); if isempty(list) list = findall(fig, 'Type','image', 'Visible','on'); end for hIm = list(:)' % Check height is >= 2 height = size(get(hIm, 'CData'), 1); if height < 2 continue end % Account for the image filling only part of the axes, or vice versa yl = get(hIm, 'YData'); if isscalar(yl) yl = [yl(1)-0.5 yl(1)+height+0.5]; else yl = [min(yl), max(yl)]; % fix issue #151 (case of yl containing more than 2 elements) if ~diff(yl) continue end yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1)); end hAx = get(hIm, 'Parent'); yl2 = get(hAx, 'YLim'); % Find the pixel height of the axes oldUnits = get(hAx, 'Units'); set(hAx, 'Units', 'pixels'); pos = get(hAx, 'Position'); set(hAx, 'Units', oldUnits); if ~pos(4) continue end % Found a suitable image % Account for stretch-to-fill being disabled pbar = get(hAx, 'PlotBoxAspectRatio'); pos = min(pos(4), pbar(2)*pos(3)/pbar(1)); % Set the magnification to give native resolution options.magnify = abs((height * diff(yl2)) / (pos * diff(yl))); % magnification must never be negative: issue #103 break end end end function A = downsize(A, factor) % Downsample an image if factor == 1 % Nothing to do return end try % Faster, but requires image processing toolbox A = imresize(A, 1/factor, 'bilinear'); catch % No image processing toolbox - resize manually % Lowpass filter - use Gaussian as is separable, so faster % Compute the 1d Gaussian filter filt = (-factor-1:factor+1) / (factor * 0.6); filt = exp(-filt .* filt); % Normalize the filter filt = single(filt / sum(filt)); % Filter the image padding = floor(numel(filt) / 2); for a = 1:size(A, 3) A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid'); end % Subsample A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:); end end function A = rgb2grey(A) A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); % #ok<ZEROLIKE> end function A = check_greyscale(A) % Check if the image is greyscale if size(A, 3) == 3 && ... all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ... all(reshape(A(:,:,2) == A(:,:,3), [], 1)) A = A(:,:,1); % Save only one channel for 8-bit output end end function eps_remove_background(fname, count) % Remove the background of an eps file % Open the file fh = fopen(fname, 'r+'); if fh == -1 error('Not able to open file %s.', fname); end % Read the file line by line while count % Get the next line l = fgets(fh); if isequal(l, -1) break; % Quit, no rectangle found end % Check if the line contains the background rectangle if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1) % Set the line to whitespace and quit l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' '; fseek(fh, -numel(l), 0); fprintf(fh, l); % Reduce the count count = count - 1; end end % Close the file fclose(fh); end function b = isvector(options) b = options.pdf || options.eps; end function b = isbitmap(options) b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha; end % Helper function function A = make_cell(A) if ~iscell(A) A = {A}; end end function add_bookmark(fname, bookmark_text) % Adds a bookmark to the temporary EPS file after %%EndPageSetup % Read in the file fh = fopen(fname, 'r'); if fh == -1 error('File %s not found.', fname); end try fstrm = fread(fh, '*char')'; catch ex fclose(fh); rethrow(ex); end fclose(fh); % Include standard pdfmark prolog to maximize compatibility fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse')); % Add page bookmark fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text)); % Write out the updated file fh = fopen(fname, 'w'); if fh == -1 error('Unable to open %s for writing.', fname); end try fwrite(fh, fstrm, 'char*1'); catch ex fclose(fh); rethrow(ex); end fclose(fh); end function set_tick_mode(Hlims, ax) % Set the tick mode of linear axes to manual % Leave log axes alone as these are tricky M = get(Hlims, [ax 'Scale']); if ~iscell(M) M = {M}; end %idx = cellfun(@(c) strcmp(c, 'linear'), M); idx = find(strcmp(M,'linear')); %set(Hlims(idx), [ax 'TickMode'], 'manual'); % issue #187 %set(Hlims(idx), [ax 'TickLabelMode'], 'manual'); % this hides exponent label in HG2! for idx2 = 1 : numel(idx) try % Fix for issue #187 - only set manual ticks when no exponent is present hAxes = Hlims(idx(idx2)); props = {[ax 'TickMode'],'manual', [ax 'TickLabelMode'],'manual'}; if isempty(strtrim(hAxes.([ax 'Ruler']).SecondaryLabel.String)) % Fix for issue #205 - only set manual ticks when the Ticks number match the TickLabels number if numel(hAxes.([ax 'Tick'])) == numel(hAxes.([ax 'TickLabel'])) set(hAxes, props{:}); % no exponent and matching ticks, so update both ticks and tick labels to manual end end catch % probably HG1 set(hAxes, props{:}); % revert back to old behavior end end end function change_rgb_to_cmyk(fname) % convert RGB => CMYK within an EPS file % Do post-processing on the eps file try % Read the EPS file into memory fstrm = read_write_entire_textfile(fname); % Replace all gray-scale colors fstrm = regexprep(fstrm, '\n([\d.]+) +GC\n', '\n0 0 0 ${num2str(1-str2num($1))} CC\n'); % Replace all RGB colors fstrm = regexprep(fstrm, '\n[0.]+ +[0.]+ +[0.]+ +RC\n', '\n0 0 0 1 CC\n'); % pure black fstrm = regexprep(fstrm, '\n([\d.]+) +([\d.]+) +([\d.]+) +RC\n', '\n${sprintf(''%.4g '',[1-[str2num($1),str2num($2),str2num($3)]/max([str2num($1),str2num($2),str2num($3)]),1-max([str2num($1),str2num($2),str2num($3)])])} CC\n'); % Overwrite the file with the modified contents read_write_entire_textfile(fname, fstrm); catch % never mind - leave as is... end end
github
drbenvincent/darc-experiments-matlab-master
ghostscript.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/ghostscript.m
7,902
utf_8
ff62a40d651197dbea5d3c39998b3bad
function varargout = ghostscript(cmd) %GHOSTSCRIPT Calls a local GhostScript executable with the input command % % Example: % [status result] = ghostscript(cmd) % % Attempts to locate a ghostscript executable, finally asking the user to % specify the directory ghostcript was installed into. The resulting path % is stored for future reference. % % Once found, the executable is called with the input command string. % % This function requires that you have Ghostscript installed on your % system. You can download this from: http://www.ghostscript.com % % IN: % cmd - Command string to be passed into ghostscript. % % OUT: % status - 0 iff command ran without problem. % result - Output from ghostscript. % Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015- %{ % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS. % Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems. % 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and % Shaun Kline for pointing out the issue % 04/05/11 - Thanks to David Chorlian for pointing out an alternative % location for gs on linux. % 12/12/12 - Add extra executable name on Windows. Thanks to Ratish % Punnoose for highlighting the issue. % 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick % Steinbring for proposing the fix. % 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes % for the fix. % 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen % Vermeer for raising the issue. % 27/02/15 - If Ghostscript croaks, display suggested workarounds % 30/03/15 - Improved performance by caching status of GS path check, if ok % 14/05/15 - Clarified warning message in case GS path could not be saved % 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74) % 10/11/15 - Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX %} try % Call ghostscript [varargout{1:nargout}] = system([gs_command(gs_path()) cmd]); catch err % Display possible workarounds for Ghostscript croaks url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12 url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20 hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1); if using_hg2 fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2); end fprintf('\n\n'); if ismac || isunix url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27 fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3); % issue #20 fpath = which(mfilename); if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath); end rethrow(err); end end function path_ = gs_path % Return a valid path % Start with the currently set path path_ = user_string('ghostscript'); % Check the path works if check_gs_path(path_) return end % Check whether the binary is on the path if ispc bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'}; else bin = {'gs'}; end for a = 1:numel(bin) path_ = bin{a}; if check_store_gs_path(path_) return end end % Search the obvious places if ispc default_location = 'C:\Program Files\gs\'; dir_list = dir(default_location); if isempty(dir_list) default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems dir_list = dir(default_location); end executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'}; ver_num = 0; % If there are multiple versions, use the newest for a = 1:numel(dir_list) ver_num2 = sscanf(dir_list(a).name, 'gs%g'); if ~isempty(ver_num2) && ver_num2 > ver_num for b = 1:numel(executable) path2 = [default_location dir_list(a).name executable{b}]; if exist(path2, 'file') == 2 path_ = path2; ver_num = ver_num2; end end end end if check_store_gs_path(path_) return end else executable = {'/usr/bin/gs', '/usr/local/bin/gs'}; for a = 1:numel(executable) path_ = executable{a}; if check_store_gs_path(path_) return end end end % Ask the user to enter the path while true if strncmp(computer, 'MAC', 3) % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg('Ghostscript not found. Please locate the program.')) end base = uigetdir('/', 'Ghostcript not found. Please locate the program.'); if isequal(base, 0) % User hit cancel or closed window break; end base = [base filesep]; %#ok<AGROW> bin_dir = {'', ['bin' filesep], ['lib' filesep]}; for a = 1:numel(bin_dir) for b = 1:numel(bin) path_ = [base bin_dir{a} bin{b}]; if exist(path_, 'file') == 2 if check_store_gs_path(path_) return end end end end end if ismac error('Ghostscript not found. Have you installed it (http://pages.uoregon.edu/koch)?'); else error('Ghostscript not found. Have you installed it from www.ghostscript.com?'); end end function good = check_store_gs_path(path_) % Check the path is valid good = check_gs_path(path_); if ~good return end % Update the current default path to the path found if ~user_string('ghostscript', path_) filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt'); warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_); return end end function good = check_gs_path(path_) persistent isOk if isempty(path_) isOk = false; elseif ~isequal(isOk,true) % Check whether the path is valid [status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU> isOk = status == 0; end good = isOk; end function cmd = gs_command(path_) % Initialize any required system calls before calling ghostscript % TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh) shell_cmd = ''; if isunix shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07 end if ismac shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07 end % Construct the command string cmd = sprintf('%s"%s" ', shell_cmd, path_); end
github
drbenvincent/darc-experiments-matlab-master
fix_lines.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/fix_lines.m
6,441
utf_8
ffda929ebad8144b1e72d528fa5d9460
%FIX_LINES Improves the line style of eps files generated by print % % Examples: % fix_lines fname % fix_lines fname fname2 % fstrm_out = fixlines(fstrm_in) % % This function improves the style of lines in eps files generated by % MATLAB's print function, making them more similar to those seen on % screen. Grid lines are also changed from a dashed style to a dotted % style, for greater differentiation from dashed lines. % % The function also places embedded fonts after the postscript header, in % versions of MATLAB which place the fonts first (R2006b and earlier), in % order to allow programs such as Ghostscript to find the bounding box % information. % %IN: % fname - Name or path of source eps file. % fname2 - Name or path of destination eps file. Default: same as fname. % fstrm_in - File contents of a MATLAB-generated eps file. % %OUT: % fstrm_out - Contents of the eps file with line styles fixed. % Copyright: (C) Oliver Woodford, 2008-2014 % The idea of editing the EPS file to change line styles comes from Jiro % Doke's FIXPSLINESTYLE (fex id: 17928) % The idea of changing dash length with line width came from comments on % fex id: 5743, but the implementation is mine :) % Thank you to Sylvain Favrot for bringing the embedded font/bounding box % interaction in older versions of MATLAB to my attention. % Thank you to D Ko for bringing an error with eps files with tiff previews % to my attention. % Thank you to Laurence K for suggesting the check to see if the file was % opened. % 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+) % 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39 function fstrm = fix_lines(fstrm, fname2) % Issue #20: warn users if using this function in HG2 (R2014b+) if using_hg2 warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.'); end if nargout == 0 || nargin > 1 if nargin < 2 % Overwrite the input file fname2 = fstrm; end % Read in the file fstrm = read_write_entire_textfile(fstrm); end % Move any embedded fonts after the postscript header if strcmp(fstrm(1:15), '%!PS-AdobeFont-') % Find the start and end of the header ind = regexp(fstrm, '[\n\r]%!PS-Adobe-'); [ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+'); % Put the header first if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1) fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]); end end % Make sure all line width commands come before the line style definitions, % so that dash lengths can be based on the correct widths % Find all line style sections ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes! regexp(fstrm, '[\n\r]DO[\n\r]'),... regexp(fstrm, '[\n\r]DA[\n\r]'),... regexp(fstrm, '[\n\r]DD[\n\r]')]; ind = sort(ind); % Find line width commands [ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]'); % Go through each line style section and swap with any line width commands % near by b = 1; m = numel(ind); n = numel(ind2); for a = 1:m % Go forwards width commands until we pass the current line style while b <= n && ind2(b) < ind(a) b = b + 1; end if b > n % No more width commands break; end % Check we haven't gone past another line style (including SO!) if a < m && ind2(b) > ind(a+1) continue; end % Are the commands close enough to be confident we can swap them? if (ind2(b) - ind(a)) > 8 continue; end % Move the line style command below the line width command fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)]; b = b + 1; end % Find any grid line definitions and change to GR format % Find the DO sections again as they may have moved ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]')); if ~isempty(ind) % Find all occurrences of what are believed to be axes and grid lines ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]')); if ~isempty(ind2) % Now see which DO sections come just before axes and grid lines ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]); ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right ind = ind(ind2); % Change any regions we believe to be grid lines to GR fstrm(ind+1) = 'G'; fstrm(ind+2) = 'R'; end end % Define the new styles, including the new GR format % Dot and dash lengths have two parts: a constant amount plus a line width % variable amount. The constant amount comes after dpi2point, and the % variable amount comes after currentlinewidth. If you want to change % dot/dash lengths for a one particular line style only, edit the numbers % in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and % /GR (grid lines) lines for the style you want to change. new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width '/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width '/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines '/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines '/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines '/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines '/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant % Construct the output % This is the original (memory-intensive) code: %first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section %[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/'); %[remaining, remaining] = strtok(remaining, '%'); %fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining]; fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']); % Write the output file if nargout == 0 || nargin > 1 read_write_entire_textfile(fname2, fstrm); end end
github
drbenvincent/darc-experiments-matlab-master
PosteriorPrediction1D.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/mcmc-utils-matlab/+mcmc/PosteriorPrediction1D.m
7,063
utf_8
3b31fa324f33b1e3af91b9ef1a04d68e
classdef PosteriorPrediction1D < handle %% PosteriorPrediction1D properties variableNames fh xInterp %samples Y nSamples samples ciType nExamples pointEstimateType pointEstimate shouldPlotData xData, yData ciWidth h % a structure containing handles to figure and plot objects end properties(Access = protected) end methods % Class constructor function obj=PosteriorPrediction1D(fh, varargin) p = inputParser; p.FunctionName = mfilename; p.addRequired('fh',@(x) isa(x,'function_handle')); p.addParameter('xInterp',[],@isvector); p.addParameter('samples',[],@ismatrix); p.addParameter('variableNames',{},@iscellstr); p.addParameter('ciType','examples',@(x)any(strcmp(x,{'examples','range','probMass'}))); p.addParameter('nExamples',100,@isscalar); p.addParameter('ciWidth',0.95,@isscalar); p.addParameter('pointEstimateType','mean',@isstr); p.addParameter('shouldPlotData',true,@islogical); p.addParameter('xData',[],@isvector); p.addParameter('yData',[],@isvector); p.addParameter('pointEstimate',[],@isvector);% if we have precomputed point estimate due to numerical problems (eg with log transformed data etc). p.parse(fh, varargin{:}); % add p.Results fields into obj fields = fieldnames(p.Results); for n=1:numel(fields) obj.(fields{n}) = p.Results.(fields{n}); end obj.nSamples= size(obj.samples,1); % predefine handles for point estimates obj.h.hPointEst=[]; if isempty(p.Results.pointEstimate) temp = mcmc.UnivariateDistribution(obj.samples,... 'shouldPlot',false,... 'pointEstimateType',p.Results.pointEstimateType); obj.pointEstimate = temp.(p.Results.pointEstimateType); end % High-level plotting commands if p.Results.shouldPlotData switch obj.ciType case{'examples'} obj.plotExamples(); case{'range'} obj.plotCI(); case{'probMass'} obj.plotProbMass(); end axis tight obj.plotPointEstimate(); obj.plotData(); end end function evaluateFunction(obj,ExamplesToPlot) % Evaluate the 1D function for the x-values specified and for % each of the MCMC samples. This will result in a matrix with: % rows = number of x-axis values % cols = number of MCMC samples %fprintf('Evaluating the function over %d MCMC samples...\n', numel(ExamplesToPlot)); if isempty(ExamplesToPlot) ExamplesToPlot = [1:obj.nSamples]; end try % If the function handle can deal with vectorised inputs % then this should compute much faster %obj.Y = obj.fh(obj.xInterp, obj.samples(:,:))'; obj.Y = obj.fh(obj.xInterp, obj.samples(ExamplesToPlot,:))'; catch % but if that fails, fall back on looping through mcmc % samples warning('*** SLOWNESS WARNING ***') warning('Recommend writing your function in a way that can handle vectorised inputs') Y = zeros(numel(obj.xInterp),numel(ExamplesToPlot)); for s=1:numel(ExamplesToPlot) obj.Y(:,s) = obj.fh(obj.xInterp, obj.samples(ExamplesToPlot(s),:)); end end end function obj = plotPointEstimate(obj) % Plot a single curve with the single set of parameters. These % might correspond to the mode of the MCMC parameters, for % example. % Calculate the y-values YpointEstimate = obj.fh(obj.xInterp, obj.pointEstimate); % plot the point estimate hold on hPointEst = plot(obj.xInterp, YpointEstimate,'k-', 'LineWidth', 3); % concatenate handle onto a list, so that we can plot multiple % point estimates and have handles to each if numel(obj.h.hPointEst)==0 obj.h.hPointEst = hPointEst; else obj.h.hPointEst = [obj.h.hPointEst hPointEst]; end end function obj = plotExamples(obj) % Plots a random set of example functions, each one corresponds % to a particular MCMC sample. % If we've asked for more examples, than MCMC samples, then % just plot all. if obj.nExamples > obj.nSamples obj.nExamples = obj.nSamples; end % shuffle the deck and pick the top nExamples shuffledExamples = randperm(obj.nSamples); ExamplesToPlot = shuffledExamples([1:obj.nExamples]); % Evaluate the function just for these examples obj.evaluateFunction(ExamplesToPlot); try hExamples = plot(obj.xInterp, obj.Y,'-',... 'Color',[0.5 0.5 0.5 0.1]); catch % backward compatability hExamples = plot(obj.xInterp, obj.Y,'-',... 'Color',[0.5 0.5 0.5]); end % hExamples = plot(obj.xInterp, obj.Y(:,ExamplesToPlot),'k-'); obj.h.Axis = gca; obj.h.hExamples = hExamples; formatAxes(obj) end function obj = plotCI(obj) obj.evaluateFunction([1:obj.nSamples]); % Plots shaded 95% vals = [(1-0.95)/2 1-((1-0.95)/2)].*100; CI = prctile(obj.Y',vals); % draw the shaded error bar zone x = [obj.xInterp,fliplr(obj.xInterp)]; y = [CI(2,:),fliplr(CI(1,:))]; hCI =patch(x,y,[0.8 0.8 0.8]); hCI.EdgeColor='none'; % save handle to CI obj.h.hCI = hCI; formatAxes(obj) end function obj = plotProbMass(obj) % Plots the posterior predictive distribution in the form of a % 2D probability mass function. obj.evaluateFunction([1:obj.nSamples]); yi = linspace( min(obj.Y(:)), max(obj.Y(:)), 100); [PM]=calcProbabilityMass(obj,yi); hProbMass=imagesc(obj.xInterp, yi, PM); axis xy % save handle to prob mass obj.h.hExamples = hProbMass; formatAxes(obj) end function obj = plotData(obj) hold on if isempty(obj.xData), return, end if isempty(obj.yData), return, end if ~obj.shouldPlotData, return, end hData=plot(obj.xData,obj.yData,... 'o',... 'MarkerSize',8,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','w'); % save handle to data points obj.h.hData = hData; formatAxes(obj) end end end %% Private functions function [PM]=calcProbabilityMass(obj,yi) % The matrix obj.Y has a number of rows equal to the number of x-axis % values that we are evaluating the function over, and has a number of % columns equal to the number of MCMC samples provided. What we do here is % to loop over the x-values and convert the set of samples into a % probability mass function by use of the hist function. We do this for the % y values specified in the vector yi. display('Calculating probability mass...') obj.evaluateFunction([1:obj.nSamples]); % preallocate PM = zeros(size(obj.Y,1), numel(yi)); % loop over x-values, calculating posterior mass for the corresponding % samples for x=1:size(obj.Y,1) PM(x,:) = hist( obj.Y(x,:) , yi ); % scale so the max of each column (x-value) is equal to 1 PM(x,:) =PM(x,:) / max(PM(x,:)); end PM=PM'; % transpose end function formatAxes(obj) if ~isempty(obj.xData) xlim([min(obj.xData) max(obj.xData)]) end % axes on top layer ah=gca; ah.Layer='top'; axis square box off if ~isempty(obj.variableNames) xlabel(obj.variableNames{1},'Interpreter','latex') ylabel(obj.variableNames{2},'Interpreter','latex') end end
github
drbenvincent/darc-experiments-matlab-master
kde.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/mcmc-utils-matlab/+mcmc/+kde/kde.m
5,689
utf_8
910728965b89850c5c417eef4698a074
function [bandwidth,density,xmesh,cdf]=kde(data,n,tstar_max,MIN,MAX) % Tom Edit: added a tstar_max to limit the bandwidth if desired. It is a % scaled value, default = inf; % % Reliable and extremely fast kernel density estimator for one-dimensional data; % Gaussian kernel is assumed and the bandwidth is chosen automatically; % Unlike many other implementations, this one is immune to problems % caused by multimodal densities with widely separated modes (see example). The % estimation does not deteriorate for multimodal densities, because we never assume % a parametric model for the data. % INPUTS: % data - a vector of data from which the density estimate is constructed; % n - the number of mesh points used in the uniform discretization of the % interval [MIN, MAX]; n has to be a power of two; if n is not a power of two, then % n is rounded up to the next power of two, i.e., n is set to n=2^ceil(log2(n)); % the default value of n is n=2^12; % MIN, MAX - defines the interval [MIN,MAX] on which the density estimate is constructed; % the default values of MIN and MAX are: % MIN=min(data)-Range/10 and MAX=max(data)+Range/10, where Range=max(data)-min(data); % OUTPUTS: % bandwidth - the optimal bandwidth (Gaussian kernel assumed); % density - column vector of length 'n' with the values of the density % estimate at the grid points; % xmesh - the grid over which the density estimate is computed; % - If no output is requested, then the code automatically plots a graph of % the density estimate. % cdf - column vector of length 'n' with the values of the cdf % Reference: % Kernel density estimation via diffusion % Z. I. Botev, J. F. Grotowski, and D. P. Kroese (2010) % Annals of Statistics, Volume 38, Number 5, pages 2916-2957. % % Example: % data=[randn(100,1);randn(100,1)*2+35 ;randn(100,1)+55]; % kde(data,2^14,min(data)-5,max(data)+5); if ~exist('tstar_max','var') tstar_max = inf; end data=data(:); %make data a column vector if nargin<2 % if n is not supplied switch to the default n=2^14; end n=2^ceil(log2(n)); % round up n to the next power of 2; if nargin<5 %define the default interval [MIN,MAX] minimum=min(data); maximum=max(data); Range=maximum-minimum; MIN=minimum-Range/2; MAX=maximum+Range/2; end % set up the grid over which the density estimate is computed; R=MAX-MIN; dx=R/(n-1); xmesh=MIN+[0:dx:R]; N=length(unique(data)); %bin the data uniformly using the grid defined above; initial_data=histc(data,xmesh)/N; initial_data=initial_data/sum(initial_data); a=dct1d(initial_data); % discrete cosine transform of initial data % now compute the optimal bandwidth^2 using the referenced method I=[1:n-1]'.^2; a2=(a(2:end)/2).^2; % use fzero to solve the equation t=zeta*gamma^[5](t) t_star=root(@(t)fixed_point(t,N,I,a2),N); t_star = min(t_star,tstar_max); % smooth the discrete cosine transform of initial data using t_star a_t=a.*exp(-[0:n-1]'.^2*pi^2*t_star/2); % now apply the inverse discrete cosine transform if (nargout>1)|(nargout==0) density=idct1d(a_t)/R; end % take the rescaling of the data into account bandwidth=sqrt(t_star)*R; density(density<0)=eps; % remove negatives due to round-off error if nargout==0 figure(1), plot(xmesh,density) end % for cdf estimation if nargout>3 f=2*pi^2*sum(I.*a2.*exp(-I*pi^2*t_star)); t_cdf=(sqrt(pi)*f*N)^(-2/3); % now get values of cdf on grid points using IDCT and cumsum function a_cdf=a.*exp(-[0:n-1]'.^2*pi^2*t_cdf/2); cdf=cumsum(idct1d(a_cdf))*(dx/R); % take the rescaling into account if the bandwidth value is required bandwidth_cdf=sqrt(t_cdf)*R; end end %################################################################ function out=fixed_point(t,N,I,a2) % this implements the function t-zeta*gamma^[l](t) l=7; f=2*pi^(2*l)*sum(I.^l.*a2.*exp(-I*pi^2*t)); for s=l-1:-1:2 K0=prod([1:2:2*s-1])/sqrt(2*pi); const=(1+(1/2)^(s+1/2))/3; time=(2*const*K0/N/f)^(2/(3+2*s)); f=2*pi^(2*s)*sum(I.^s.*a2.*exp(-I*pi^2*time)); end out=t-(2*N*sqrt(pi)*f)^(-2/5); end %############################################################## function out = idct1d(data) % computes the inverse discrete cosine transform [nrows,ncols]=size(data); % Compute weights weights = nrows*exp(i*(0:nrows-1)*pi/(2*nrows)).'; % Compute x tilde using equation (5.93) in Jain data = real(ifft(weights.*data)); % Re-order elements of each column according to equations (5.93) and % (5.94) in Jain out = zeros(nrows,1); out(1:2:nrows) = data(1:nrows/2); out(2:2:nrows) = data(nrows:-1:nrows/2+1); % Reference: % A. K. Jain, "Fundamentals of Digital Image % Processing", pp. 150-153. end %############################################################## function data=dct1d(data) % computes the discrete cosine transform of the column vector data [nrows,ncols]= size(data); % Compute weights to multiply DFT coefficients weight = [1;2*(exp(-i*(1:nrows-1)*pi/(2*nrows))).']; % Re-order the elements of the columns of x data = [ data(1:2:end,:); data(end:-2:2,:) ]; % Multiply FFT by weights: data= real(weight.* fft(data)); end function t=root(f,N) % try to find smallest root whenever there is more than one N=50*(N<=50)+1050*(N>=1050)+N*((N<1050)&(N>50)); tol=10^-12+0.01*(N-50)/1000; flag=0; while flag==0 try t=fzero(f,[0,tol]); flag=1; catch tol=min(tol*2,.1); % double search interval end if tol==.1 % if all else fails t=fminbnd(@(x)abs(f(x)),0,.1); flag=1; end end end
github
drbenvincent/darc-experiments-matlab-master
kde2d.m
.m
darc-experiments-matlab-master/darc-toolbox/dependencies/mcmc-utils-matlab/+mcmc/+kde2d/kde2d.m
7,506
utf_8
6d82435d2728e267990a5041d6b289b2
function [bandwidth,density,X,Y]=kde2d(data,n,MIN_XY,MAX_XY) % fast and accurate state-of-the-art % bivariate kernel density estimator % with diagonal bandwidth matrix. % The kernel is assumed to be Gaussian. % The two bandwidth parameters are % chosen optimally without ever % using/assuming a parametric model for the data or any "rules of thumb". % Unlike many other procedures, this one % is immune to accuracy failures in the estimation of % multimodal densities with widely separated modes (see examples). % INPUTS: data - an N by 2 array with continuous data % n - size of the n by n grid over which the density is computed % n has to be a power of 2, otherwise n=2^ceil(log2(n)); % the default value is 2^8; % MIN_XY,MAX_XY- limits of the bounding box over which the density is computed; % the format is: % MIN_XY=[lower_Xlim,lower_Ylim] % MAX_XY=[upper_Xlim,upper_Ylim]. % The dafault limits are computed as: % MAX=max(data,[],1); MIN=min(data,[],1); Range=MAX-MIN; % MAX_XY=MAX+Range/4; MIN_XY=MIN-Range/4; % OUTPUT: bandwidth - a row vector with the two optimal % bandwidths for a bivaroate Gaussian kernel; % the format is: % bandwidth=[bandwidth_X, bandwidth_Y]; % density - an n by n matrix containing the density values over the n by n grid; % density is not computed unless the function is asked for such an output; % X,Y - the meshgrid over which the variable "density" has been computed; % the intended usage is as follows: % surf(X,Y,density) % Example (simple Gaussian mixture) % clear all % % generate a Gaussian mixture with distant modes % data=[randn(500,2); % randn(500,1)+3.5, randn(500,1);]; % % call the routine % [bandwidth,density,X,Y]=kde2d(data); % % plot the data and the density estimate % contour3(X,Y,density,50), hold on % plot(data(:,1),data(:,2),'r.','MarkerSize',5) % % Example (Gaussian mixture with distant modes): % % clear all % % generate a Gaussian mixture with distant modes % data=[randn(100,1), randn(100,1)/4; % randn(100,1)+18, randn(100,1); % randn(100,1)+15, randn(100,1)/2-18;]; % % call the routine % [bandwidth,density,X,Y]=kde2d(data); % % plot the data and the density estimate % surf(X,Y,density,'LineStyle','none'), view([0,60]) % colormap hot, hold on, alpha(.8) % set(gca, 'color', 'blue'); % plot(data(:,1),data(:,2),'w.','MarkerSize',5) % % Example (Sinusoidal density): % % clear all % X=rand(1000,1); Y=sin(X*10*pi)+randn(size(X))/3; data=[X,Y]; % % apply routine % [bandwidth,density,X,Y]=kde2d(data); % % plot the data and the density estimate % surf(X,Y,density,'LineStyle','none'), view([0,70]) % colormap hot, hold on, alpha(.8) % set(gca, 'color', 'blue'); % plot(data(:,1),data(:,2),'w.','MarkerSize',5) % % Notes: If you have a more accurate density estimator % (as measured by which routine attains the smallest % L_2 distance between the estimate and the true density) or you have % problems running this code, please email me at [email protected] % Reference: Z. I. Botev, J. F. Grotowski and D. P. Kroese % "KERNEL DENSITY ESTIMATION VIA DIFFUSION" ,Submitted to the % Annals of Statistics, 2009 global N A2 I if nargin<2 n=2^8; end n=2^ceil(log2(n)); % round up n to the next power of 2; N=size(data,1); if nargin<3 MAX=max(data,[],1); MIN=min(data,[],1); Range=MAX-MIN; MAX_XY=MAX+Range/4; MIN_XY=MIN-Range/4; end scaling=MAX_XY-MIN_XY; if N<=size(data,2) error('data has to be an N by 2 array where each row represents a two dimensional observation') end transformed_data=(data-repmat(MIN_XY,N,1))./repmat(scaling,N,1); %bin the data uniformly using regular grid; initial_data=ndhist(transformed_data,n); % discrete cosine transform of initial data a= dct2d(initial_data); % now compute the optimal bandwidth^2 I=(0:n-1).^2; A2=a.^2; t_star=fzero( @(t)(t-evolve(t)),[0,0.1]); p_02=func([0,2],t_star);p_20=func([2,0],t_star); p_11=func([1,1],t_star); t_y=(p_02^(3/4)/(4*pi*N*p_20^(3/4)*(p_11+sqrt(p_20*p_02))))^(1/3); t_x=(p_20^(3/4)/(4*pi*N*p_02^(3/4)*(p_11+sqrt(p_20*p_02))))^(1/3); % smooth the discrete cosine transform of initial data using t_star a_t=exp(-(0:n-1)'.^2*pi^2*t_x/2)*exp(-(0:n-1).^2*pi^2*t_y/2).*a; % now apply the inverse discrete cosine transform if nargout>1 density=idct2d(a_t)*(numel(a_t)/prod(scaling)); [X,Y]=meshgrid(MIN_XY(1):scaling(1)/(n-1):MAX_XY(1),MIN_XY(2):scaling(2)/(n-1):MAX_XY(2)); end bandwidth=sqrt([t_x,t_y]).*scaling; end %####################################### function [out,time]=evolve(t) global N Sum_func = func([0,2],t) + func([2,0],t) + 2*func([1,1],t); time=(2*pi*N*Sum_func)^(-1/3); out=(t-time)/time; end %####################################### function out=func(s,t) global N if sum(s)<=4 Sum_func=func([s(1)+1,s(2)],t)+func([s(1),s(2)+1],t); const=(1+1/2^(sum(s)+1))/3; time=(-2*const*K(s(1))*K(s(2))/N/Sum_func)^(1/(2+sum(s))); out=psi(s,time); else out=psi(s,t); end end %####################################### function out=psi(s,Time) global I A2 % s is a vector w=exp(-I*pi^2*Time).*[1,.5*ones(1,length(I)-1)]; wx=w.*(I.^s(1)); wy=w.*(I.^s(2)); out=(-1)^sum(s)*(wy*A2*wx')*pi^(2*sum(s)); end %####################################### function out=K(s) out=(-1)^s*prod((1:2:2*s-1))/sqrt(2*pi); end %####################################### function data=dct2d(data) % computes the 2 dimensional discrete cosine transform of data % data is an nd cube [nrows,ncols]= size(data); if nrows~=ncols error('data is not a square array!') end % Compute weights to multiply DFT coefficients w = [1;2*(exp(-i*(1:nrows-1)*pi/(2*nrows))).']; weight=w(:,ones(1,ncols)); data=dct1d(dct1d(data)')'; function transform1d=dct1d(x) % Re-order the elements of the columns of x x = [ x(1:2:end,:); x(end:-2:2,:) ]; % Multiply FFT by weights: transform1d = real(weight.* fft(x)); end end %####################################### function data = idct2d(data) % computes the 2 dimensional inverse discrete cosine transform [nrows,ncols]=size(data); % Compute wieghts w = exp(i*(0:nrows-1)*pi/(2*nrows)).'; weights=w(:,ones(1,ncols)); data=idct1d(idct1d(data)'); function out=idct1d(x) y = real(ifft(weights.*x)); out = zeros(nrows,ncols); out(1:2:nrows,:) = y(1:nrows/2,:); out(2:2:nrows,:) = y(nrows:-1:nrows/2+1,:); end end %####################################### function binned_data=ndhist(data,M) % this function computes the histogram % of an n-dimensional data set; % 'data' is nrows by n columns % M is the number of bins used in each dimension % so that 'binned_data' is a hypercube with % size length equal to M; [nrows,ncols]=size(data); bins=zeros(nrows,ncols); for i=1:ncols [dum,bins(:,i)] = histc(data(:,i),[0:1/M:1],1); bins(:,i) = min(bins(:,i),M); end % Combine the vectors of 1D bin counts into a grid of nD bin % counts. binned_data = accumarray(bins(all(bins>0,2),:),1/nrows,M(ones(1,ncols))); end
github
drbenvincent/darc-experiments-matlab-master
my_shaded_errorbar_zone_UL.m
.m
darc-experiments-matlab-master/darc-toolbox/utils-plotting/my_shaded_errorbar_zone_UL.m
815
utf_8
5455a1384ba84136387029c983c8a775
function [h]=my_shaded_errorbar_zone_UL(x,upper,lower,col) % Plots a shaded region of error % % my_shaded_errorbar_zone_UL([-10:0.1:10],[-10:0.1:10]+1,[-10:0.1:10]-1,[0.7 0.7 0.7]) % % eg, my_shaded_errorbar_zone([-10:0.1:10],x,abs(randn(size(x)))+2,[0 0 1]) % %handle=patch([x max(x)-x+min(x)],[y+e flipud(y'-e')'],[0.8 0.8 0.8]); %handle=patch([x max(x)-x+min(x)],[upper flipud(lower')'],[0.8 0.8 0.8]); % % % written by: Benjamin T Vincent h = holdDecorator( plotErrorBarZone(x, upper, lower, col) ); end function h = plotErrorBarZone(x, upper, lower, col) % draw the shaded error bar zone x = [x, fliplr(x)]; y = [upper, fliplr(lower)]; h = patch(x, y, [0.8 0.8 0.8]); % formatting uistack(h,'bottom') set(h,'EdgeColor','none') set(h,'FaceColor',col) set(h,'FaceAlpha',0.5) end
github
drbenvincent/darc-experiments-matlab-master
plotUtilityFunction.m
.m
darc-experiments-matlab-master/darc-experiments/@Model/plotUtilityFunction.m
2,211
utf_8
e70f242efd3d46c6ec678cceec49d126
function plotUtilityFunction(obj, thetaStruct, varargin) p = inputParser; p.FunctionName = mfilename; p.addRequired('thetaStruct',@isstruct_or_table); % p.addParameter('xScale','linear',@(x)any(strcmp(x,{'linear','log'}))); p.addParameter('data',[],@istable); p.addParameter('pointEstimateType','mean',@isstr); % p.addParameter('maxDelay', [], @isscalar); p.addParameter('utility_func_function_handle','', @(x) isa(x,'function_handle')) p.parse(thetaStruct, varargin{:}); data = p.Results.data; plotCurve(data, thetaStruct, p.Results.utility_func_function_handle, p) %plotData(data); formatAxes(data, p); end function plotCurve(data, thetaStruct, utility_func_function_handle, p) % create set of rewards to calculate & plot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ xVals = linspace(-100, 100, 100); % evaluate and plot just the first N particles N = 200; fnames = fieldnames(thetaStruct); for n=1:numel(fnames) thetaStruct.(fnames{n}) = thetaStruct.(fnames{n})([1:N]); end % calculate discount fraction for the given theta samples ~~~~~~~~~~~~~~ prospect.reward = xVals; % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ utilityOfReward = utility_func_function_handle(prospect, thetaStruct); plot(xVals, utilityOfReward,... 'Color',[0 0.4 1 0.1]) hold on %% plot posterior median as black line for n=1:numel(fnames) thetaStruct.(fnames{n}) = median(thetaStruct.(fnames{n})); end prospect.reward = xVals; utilityOfReward = utility_func_function_handle(prospect, thetaStruct); plot(xVals, utilityOfReward,... 'Color', 'k',... 'LineWidth', 2) end function formatAxes(data, p) %opts = calc_opts(data, p); xlabel('$R$', 'interpreter','Latex') ylabel('$u(R)$', 'interpreter','Latex') set(gca,'XAxisLocation','origin',... 'YAxisLocation','origin',... 'box', 'off') % box off % a = get(gca,'YLim'); % if opts.maxX>0 % xlim( [0 opts.maxX] ) % end % ylim([0 min([a(2),10]) ]) drawnow end % function opts = calc_opts(data, p) % if ~isempty(data) % opts.maxlogB = max( abs(data.R_B) ); % opts.maxX = max( data.D_B ) *1.1; % else % opts.maxlogB = 1000; % opts.maxX = 20; % end % % if ~isempty(p.Results.maxDelay) % opts.maxX = p.Results.maxDelay; % end % end
github
drbenvincent/darc-experiments-matlab-master
plotProbFunction.m
.m
darc-experiments-matlab-master/darc-experiments/@Model/plotProbFunction.m
4,833
utf_8
2fd2b28515f7226b9bda9d45b14e68a6
function plotProbFunction(obj, thetaStruct, varargin) p = inputParser; p.FunctionName = mfilename; p.addRequired('thetaStruct',@isstruct_or_table); p.addParameter('xScale','linear',@(x)any(strcmp(x,{'linear','log'}))); p.addParameter('data',[],@istable); p.addParameter('pointEstimateType','mean',@isstr); p.addParameter('discounting_function_handle','', @(x) isa(x,'function_handle')) p.parse(thetaStruct, varargin{:}); data = p.Results.data; plotCurve(data, thetaStruct, p.Results.discounting_function_handle, p) plotData(data); formatAxes(data); end function plotCurve(data, thetaStruct, discounting_function_handle, p) switch p.Results.xScale case{'linear'} xProbVector = linspace(10^-4, 1, 1000); xOddsVector = prob2oddsagainst(xProbVector); % % create set of probs to calculate & plot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % if isempty(data) % xOddsVector = linspace(0,100,1000); % else % xOddsVector = linspace(0,100,1000); % % % zoom to data (only useful with the odds discounting type plot) % % xOddsVector = xOddsVector( xOddsVector < max(prob2oddsagainst(data.P_B))); % end % % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %% Plot calibration line for h = 1 = risk neutral risk_neutral = 1 ./ (1+1.*xOddsVector); % hyperbolic discounting function % converting x axis from odds to probability makes it like the % traditional "probability weighting plot", as opposed to the % "discounting of odds plot" plot(oddsagainst2prob(xOddsVector), risk_neutral, '--',... 'Color', [0.7 0.7 0.7],... 'LineWidth', 4) hold on % evaluate and plot just the first N particles N = 200; fnames = fieldnames(thetaStruct); for n=1:numel(fnames) thetaStruct.(fnames{n}) = thetaStruct.(fnames{n})([1:N]); end % calculate discount fraction for the given theta samples ~~~~~~~~~~~~~~ prospect.prob = xProbVector; % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ dF = discounting_function_handle(prospect, thetaStruct); plot(oddsagainst2prob(xOddsVector), dF,... 'Color',[0 0.4 1 0.1]) hold on %% plot posterior median as black line for n=1:numel(fnames) thetaStruct.(fnames{n}) = median(thetaStruct.(fnames{n})); end prospect.prob = xProbVector; utilityOfReward = discounting_function_handle(prospect, thetaStruct); plot(oddsagainst2prob(xOddsVector), utilityOfReward,... 'Color', 'k',... 'LineWidth', 2) case{'log'} error('not yet implemented plotting discount fractions with log x-axis') end end function plotData(data) if isempty(data) return end [x, y, markerCol, markerSize] = convertDataIntoMarkers(data); plotMarkers(oddsagainst2prob(x), y, markerCol, markerSize) end % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function [x, y, markerCol, markerSize] = convertDataIntoMarkers(data) % find unique experimental designs uniqueDesigns = [abs(data.R_A), abs(data.R_B), data.P_A, data.P_B, data.D_A, data.D_B]; [C, ia, ic] = unique(uniqueDesigns, 'rows'); %loop over unique designs (ic) for n=1:max(ic) % binary set of which trials this design was used on myset = ic==n; % Size = number of times this design has been run F(n) = sum(myset); % Colour = proportion of times that participant chose immediate % for that design markerCol(n) = sum(data.R(myset)==0) ./ F(n); markerSize(n) = F(n); x(n) = prob2oddsagainst(data.P_B( ia(n) )); y(n) = abs(data.R_A( ia(n) )) ./ abs(data.R_B( ia(n) )); end end % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function plotMarkers(x, y, markerCol, markerSize) hold on for i=1:max(numel(x)) h = plot(x(i), y(i),'o'); h.Color='k'; h.MarkerFaceColor=[1 1 1] .* (1-markerCol(i)); h.MarkerSize = markerSize(i)+4; hold on end end % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function formatAxes(data) opts = calc_opts(data); xlabel('odds against Prospect B', 'interpreter','Latex') xlabel('objective probability, $P$', 'interpreter','Latex') ylabel('$\pi(P)$', 'interpreter','Latex') box off % a = get(gca,'YLim'); % if opts.maxX > 0 % xlim( [0 opts.maxX*1.1] ) % else % x=get(gca,'XLim'); % xlim([0 a(2)]) % end xlim([0 1]) ylim([0 1]) %% Add descriptive helper text addTextToFigure('TL', 'risk seeking domain', 10) addTextToFigure('BR', 'risk avoidant domain', 10) drawnow end function opts = calc_opts(data) if ~isempty(data) opts.maxlogB = max( abs(data.R_B) ); opts.maxX = max( prob2oddsagainst(data.P_B) ); else opts.maxlogB = 1000; opts.maxX = 365; end end % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
github
drbenvincent/darc-experiments-matlab-master
plotDiscountFunction.m
.m
darc-experiments-matlab-master/darc-experiments/@Model/plotDiscountFunction.m
4,074
UNKNOWN
cd3e7d94e8978e564eef501175a3a9c6
function plotDiscountFunction(obj, thetaStruct, varargin) p = inputParser; p.FunctionName = mfilename; p.addRequired('thetaStruct',@isstruct_or_table); p.addParameter('xScale','linear',@(x)any(strcmp(x,{'linear','log'}))); p.addParameter('data',[],@istable); p.addParameter('pointEstimateType','mean',@isstr); p.addParameter('maxDelay', [], @isscalar); p.addParameter('discounting_function_handle','', @(x) isa(x,'function_handle')) p.parse(thetaStruct, varargin{:}); data = p.Results.data; plotCurve(data, thetaStruct, p.Results.discounting_function_handle, p) plotData(data); formatAxes(data, p); end function plotCurve(data, thetaStruct, discounting_function_handle, p) switch p.Results.xScale case{'linear'} % create set of delays to calculate & plot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ~isempty(p.Results.maxDelay) % if isempty(data) xVals = logspace(-3,3,1000); xVals = xVals(xVals<p.Results.maxDelay); else max_delay_of_data = max([ data.D_A; data.D_B]); xVals = logspace(-3,4,1000); xVals = xVals(xVals<max_delay_of_data); end % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % evaluate and plot just the first N particles N = 200; fnames = fieldnames(thetaStruct); for n=1:numel(fnames) thetaStruct.(fnames{n}) = thetaStruct.(fnames{n})([1:N]); end % calculate discount fraction for the given theta samples ~~~~~~~~~~~~~~ prospect.delay = xVals; % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ dF = discounting_function_handle(prospect, thetaStruct); plot(xVals, dF,... 'Color',[0 0.4 1 0.1]) hold on %% plot posterior median as black line for n=1:numel(fnames) thetaStruct.(fnames{n}) = median(thetaStruct.(fnames{n})); end prospect.reward = xVals; utilityOfReward = discounting_function_handle(prospect, thetaStruct); plot(xVals, utilityOfReward,... 'Color', 'k',... 'LineWidth', 2) case{'log'} error('not yet implemented plotting discount fractions with log x-axis') end end function plotData(data) if isempty(data) return end [x, y, markerCol, markerSize] = convertDataIntoMarkers(data); plotMarkers(x, y, markerCol, markerSize) end function [x, y, markerCol, markerSize] = convertDataIntoMarkers(data) % find unique experimental designs uniqueDesigns = [abs(data.R_A), abs(data.R_B), data.D_A, data.D_B, data.D_A, data.D_B]; [C, ia, ic] = unique(uniqueDesigns, 'rows'); %loop over unique designs (ic) for n=1:max(ic) % binary set of which trials this design was used on myset = ic==n; % Size = number of times this design has been run F(n) = sum(myset); % Colour = proportion of times that participant chose immediate % for that design markerCol(n) = sum(data.R(myset)==0) ./ F(n); markerSize(n) = F(n); x(n) = data.D_B( ia(n) ); % delay to get �R_B y(n) = abs(data.R_A( ia(n) )) ./ abs(data.R_B( ia(n) )); end end function plotMarkers(x, y, markerCol, markerSize) hold on for i=1:max(numel(x)) h = plot(x(i), y(i),'o'); h.Color='k'; h.MarkerFaceColor=[1 1 1] .* (1-markerCol(i)); h.MarkerSize = markerSize(i)+4; hold on end end % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function formatAxes(data, p) opts = calc_opts(data, p); xlabel('delay, $D^b$', 'interpreter','Latex') ylabel('$d(D)$', 'interpreter','Latex') box off a = get(gca,'YLim'); if opts.maxX>0 xlim( [0 opts.maxX] ) else x=get(gca,'XLim'); xlim([0 a(2)]) end ylim([0 min(10, max([a(2),1])) ]) %% Add descriptive helper text addTextToFigure('TR', 'choose immediate', 10, 'Color', [0.7 0.7 0.7]) addTextToFigure('BL', ' choose delayed', 10, 'Color', [0.7 0.7 0.7]) drawnow end function opts = calc_opts(data, p) if ~isempty(data) opts.maxlogB = max( abs(data.R_B) ); opts.maxX = max( data.D_B ) *1.1; else opts.maxlogB = 1000; opts.maxX = 20; end if ~isempty(p.Results.maxDelay) opts.maxX = p.Results.maxDelay; end end % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
github
drbenvincent/darc-experiments-matlab-master
plotDiscountSurface.m
.m
darc-experiments-matlab-master/darc-experiments/@Model_hyperbolic1_time_and_prob/plotDiscountSurface.m
4,143
UNKNOWN
09dea0179f9b5215e875502ae0b37f08
function plotDiscountSurface(obj, thetaStruct, varargin) % plots prob and time discount surface p = inputParser; p.FunctionName = mfilename; p.addRequired('thetaStruct',@isstruct); p.addParameter('xScale','linear',@(x)any(strcmp(x,{'linear','log'}))); p.addParameter('data',[],@isstruct_or_table) p.addParameter('pointEstimateType','mean',@isstr); p.addParameter('prob_discounting_function_handle','', @(x) isa(x,'function_handle')) p.addParameter('time_discounting_function_handle','', @(x) isa(x,'function_handle')) p.parse(thetaStruct, varargin{:}); data = p.Results.data; plotSurface(data, thetaStruct, p.Results.prob_discounting_function_handle, p.Results.time_discounting_function_handle, p) plotData(data) formatAxes(data); title({'P_A chance of �R_A in D_A days','P_B chance of �R_B in D_B days'}) end function plotSurface(data, thetaStruct, probDiscountingFunctionFH, timeDiscountingFunctionFH, p) % create set of delays to calculate & plot N_DELAYS = 10; N_ODDS = 12; if isempty(data) delays = linspace(0,365,N_DELAYS); else max_delay_of_data = max([ data.D_A; data.D_B]); delays = linspace(0, max_delay_of_data, N_DELAYS); end if isempty(data) odds = linspace(0, 20, N_ODDS); else odds = linspace(0, max(prob2oddsagainst(data.P_B)), N_ODDS); end % Evaluate only the posterior median fnames = fieldnames(thetaStruct); for n=1:numel(fnames) thetaStruct.(fnames{n}) = median(thetaStruct.(fnames{n})); end warning('CREATE THIS NESTED PARAMETER STRUCTURE AUTOMATICALLY') nestedParamStruct.prob.h = thetaStruct.h; nestedParamStruct.delay.logk = thetaStruct.logk; %opts = calc_opts(data); % create grid of values [odds_grid, delays_grid] = meshgrid(odds,delays); % create x,y (b,d) grid values warning('this is duplication of model.calcPresentSubjectiveValue()') prospect.reward = []; prospect.delay = delays_grid(:); prospect.prob = oddsagainst2prob(odds_grid(:)); V = ... probDiscountingFunctionFH(prospect, nestedParamStruct.prob) .* ... timeDiscountingFunctionFH(prospect, nestedParamStruct.delay); V = reshape(V, size(odds_grid)); %% PLOT hmesh = mesh(odds_grid, delays_grid, V); % shading hmesh.FaceColor ='w'; hmesh.FaceAlpha =0.7; % edges hmesh.MeshStyle ='both'; hmesh.EdgeColor ='k'; hmesh.EdgeAlpha =1; % plot isolines hold on [c,h] = contour3(odds_grid, delays_grid, V, [0.2:0.2:0.8]); h.LineColor = 'k'; h.LineWidth = 4; end function plotData(data) if isempty(data) return end [x,y,z,markerCol,markerSize] = convertDataIntoMarkers(data); plotMarkers(x, y, z, markerCol, markerSize) end function [x,y,z,markerCol,markerSize] = convertDataIntoMarkers(data) % find unique experimental designs uniqueDelays = [abs(data.R_A), abs(data.R_B), data.D_A, data.D_B, data.D_A, data.D_B]; [C, ia, ic] = unique(uniqueDelays,'rows'); % loop over unique designs (ic) for n=1:max(ic) % binary set of which trials this design was used on myset=ic==n; % markerSize = number of times this design has been run markerSize(n) = sum(myset); % Colour = proportion of times participant chose immediate for that design markerCol(n) = sum(data.R(myset)==0) ./ markerSize(n); x(n) = prob2oddsagainst( data.P_B( ia(n) ) ); % odds against y(n) = data.D_B( ia(n) ); % delay z(n) = abs(data.R_A(ia(n))) ./ abs(data.R_B( ia(n))); end end function plotMarkers(x, y, z, markerCol, markerSize) hold on for i=1:numel(x) h = stem3(x(i), y(i), z(i)); h.Color='k'; h.MarkerFaceColor=[1 1 1] .* (1-markerCol(i)); h.MarkerSize = markerSize(i)+4; hold on end end function formatAxes(data) %opts = calc_opts(data); xlabel('Odds against, $\frac{1-P^B}{P^B}$', 'interpreter','latex') ylabel('delay $D^B$', 'interpreter','latex') zlabel('discount factor (and $\frac{R_A}{R_B}$)', 'interpreter','latex') view([90+45, 20]) axis vis3d axis tight axis square zlim([0 1]) camproj('perspective') set(gca,'ZTick',[0:0.2:1]) end function opts = calc_opts(data) if ~isempty(data) opts.maxlogB = max( abs(data.R_B) ); opts.maxD = max( data.D_B ); else opts.maxlogB = 1000; opts.maxD = 365; end % what does this even do? opts.nIndifferenceLines = 10; pow=1; while opts.maxlogB > 10^pow; pow=pow+1; end opts.pow = pow; end