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
lijunzh/fd_elastic-master
L1GeneralOrthantWise.m
.m
fd_elastic-master/src/PQN/L1General/L1GeneralOrthantWise.m
5,512
utf_8
5e4e4772d674902f60c0bf7ef517fd4f
function [w,fEvals] = L1GeneralOrthantWise(gradFunc,w,lambda,params,varargin) % % computes argmin_w: gradFunc(w,varargin) + sum lambda.*abs(w) % % Method used: % Orthant-Wise Regression % % Parameters % gradFunc - function of the form gradFunc(w,varargin{:}) % w - initial guess % lambda - scale of L1 penalty on each variable % (set to 0 for unregularized variables) % options - user-modifiable parameters % varargin - parameters of gradFunc % % order: % 1: First-order % 2: Second-order % % Todo: take away partials for gradEvalTrace in line search if (d = 0) % Process input options [verbose,maxIter,optTol,threshold,order,adjustStep,corrections] = ... myProcessOptions(params,'verbose',1,'maxIter',250,... 'optTol',1e-6,'threshold',1e-4,'order',2,'adjustStep',1,'corrections',100); % Start log if verbose fprintf('%10s %10s %15s %15s %15s %8s %5s %5s\n','Iteration','FunEvals','Step Length','Function Val','Opt Cond','Non-Zero','dirPr','stpPr'); end p = length(w); d = zeros(p,1); xi = zeros(p,1); % Compute Evaluate Function if order == 2 [f,g,H] = pseudoGrad(w,gradFunc,lambda,varargin{:}); else [f,g] = pseudoGrad(w,gradFunc,lambda,varargin{:}); end fEvals = 1; % Check Optimality if sum(abs(g)) < optTol if verbose fprintf('First-Order Optimality Satisfied at Initial Point\n'); end return; end t = 1; f_prev = f; i = 1; while fEvals < maxIter w_old = w; f_old = f; xi_old = xi; if order == 2 d = solveNewton(g,H,1,verbose); elseif order == 1 if i == 1 B = eye(p); g_prev = g; w_prev = w; else [B,g_prev,w_prev] = bfgsUpdate(B,w,w_prev,g,g_prev,i==2); end d = -B\g; elseif order == -1 if i == 1 d = -g; old_dirs = zeros(p,0); old_stps = zeros(p,0); Hdiag = 1; else y = g-g_prev; s = w-w_prev; numCorrections = size(old_dirs,2); if numCorrections < corrections % Full Update old_dirs(:,numCorrections+1) = s; old_stps(:,numCorrections+1) = y; else % Limited-Memory Update old_dirs = [old_dirs(:,2:corrections) s]; old_stps = [old_stps(:,2:corrections) y]; end % Update scale of initial Hessian approximation Hdiag = (y'*s)/(y'*y); % Compute descent direction d = lbfgsC(-g,old_dirs,old_stps,Hdiag); end g_prev = g; w_prev = w; else assert(0,'Unrecognized value for variable order'); end dirProjections = sum(sign(d)~=sign(-g)); d(sign(d) ~= sign(-g)) = 0; xi = sign(w); xi(w==0) = sign(-g(w==0)); gtd = g'*d; if gtd > -optTol fprintf('Directional Derivative too small\n'); break; end [t,f_prev] = initialStepLength(i,adjustStep,order,f,g,gtd,t,f_prev); % Line Search if order == 2 [t,w,f,g,LSfunEvals,H] = ArmijoBacktrack(w,t,d,f,f,g,gtd,1e-4,2,optTol,... max(verbose-1,0),0,0,@constrainedPseudoGrad,xi,gradFunc,lambda,varargin{:}); else [t,w,f,g,LSfunEvals] = ArmijoBacktrack(w,t,d,f,f,g,gtd,1e-4,2,optTol,... max(verbose-1,0),0,1,@constrainedPseudoGrad,xi,gradFunc,lambda,varargin{:}); end fEvals = fEvals + LSfunEvals; % Count number of steps where we projected into the orthant stepProjections = sum(sign(w) ~= xi); % Project Step w(sign(w) ~= xi) = 0; % Update log if verbose fprintf('%10d %10d %15.5e %15.5e %15.5e %8d %5d %5d\n',i,fEvals,t,f,sum(abs(g)),sum(abs(w)>=threshold),dirProjections,stepProjections); end % Check Optimality if sum(abs(g)) < optTol if verbose fprintf('Solution Found\n'); end break; end if noProgress(t*d,f,f_old,optTol,verbose) break; end i = i +1; end if verbose && fEvals >= maxIter fprintf('Maximum Number of Iterations Exceeded\n'); end end function [nll,g,H] = pseudoGrad(w,gradFunc,lambda,varargin) p = length(w); if nargout == 1 [nll] = gradFunc(w,varargin{:}); elseif nargout == 2 [nll,g] = gradFunc(w,varargin{:}); else [nll,g,H] = gradFunc(w,varargin{:}); end nll = nll + sum(lambda.*abs(w)); if nargout > 1 if 0 % Implementation as described in Andrew & Gao gradNeg = g + lambda.*sign(w); gradPos = gradNeg; gradNeg(w==0) = g(w==0) - lambda(w==0); gradPos(w==0) = g(w==0) + lambda(w==0); pseudoGrad = zeros(p,1); pseudoGrad(gradNeg > 0) = gradNeg(gradNeg > 0); pseudoGrad(gradPos < 0) = gradPos(gradPos < 0); g = pseudoGrad; else % Equivalent way of doing it g = getSlope(w,lambda,g,1e-4); end end end function [nll,g,H] = constrainedPseudoGrad(w,xi,gradFunc,lambda,varargin) w(sign(w) ~= xi) = 0; if nargout == 1 [nll] = pseudoGrad(w,gradFunc,lambda,varargin{:}); elseif nargout == 2 [nll,g] = pseudoGrad(w,gradFunc,lambda,varargin{:}); else [nll,g,H] = pseudoGrad(w,gradFunc,lambda,varargin{:}); end end
github
lijunzh/fd_elastic-master
L1GeneralProjection.m
.m
fd_elastic-master/src/PQN/L1General/L1GeneralProjection.m
5,083
utf_8
268e1936eb38842e70a15acc9b06b47f
function [w,fEvals] = L1GeneralProjection(gradFunc,w,lambda,params,varargin) % % computes argmin_w: gradFunc(w,varargin) + sum lambda.*abs(w) % % Method used: % Two-Metric Projection method w/ non-negative variables % % Parameters % gradFunc - function of the form gradFunc(w,varargin{:}) % w - initial guess % lambda - scale of L1 penalty on each variable % (set to 0 for unregularized variables) % options - user-modifiable parameters % varargin - parameters of gradFunc % % order: % -1: First-order (limited-memory) % 1: First-order (full-memory) % 2: Second-order if nargin < 4 params = []; end % Process input options [verbose,maxIter,optTol,threshold,order,corrections,adjustStep] = ... myProcessOptions(params,'verbose',1,'maxIter',250,... 'optTol',1e-6,'threshold',1e-4,'order',2,'corrections',100,'adjustStep',0); % Start log if verbose fprintf('%10s %10s %15s %15s %15s %5s\n','Iteration','FunEvals','Step Length','Function Val','Opt Cond','Non-Zero'); end % Initialize w = [w.*(w >= 0);-w.*(w<=0)]; p = length(w); if order >= 2 [f,g,H] = nonNegGrad(w,lambda,gradFunc,varargin{:}); else [f,g] = nonNegGrad(w,lambda,gradFunc,varargin{:}); end fEvals = 1; % Compute free variables w(abs(w) < threshold) = 0; free = ones(p,1); free(w==0 & g >= 0) = 0; if sum(abs(g(free==1))) < optTol if verbose fprintf('Initial Point satisfies optTol\n'); end w = w(1:length(w)/2)-w(length(w)/2 + 1:end); return; end if sum(free==1) == 0 w = w(1:length(w)/2)-w(length(w)/2 + 1:end); return; end % Backtrack along projection arc pArc = 1; t = 1; f_prev = f; i = 1; while fEvals < maxIter w_old = w; f_old = f; % Compute step d = zeros(p,1); if order == 2 d(free==1) = solveNewton(g(free==1),H(free==1,free==1),1,verbose); elseif order == 1 % BFGS if i == 1 B = eye(p); g_prev = g; w_prev = w; else [B,g_prev,w_prev] = bfgsUpdate(B,w,w_prev,g,g_prev,i==2); end d(free==1) = -B(free==1,free==1)\g(free==1); elseif order == -1 % L-BFGS if i == 1 d(free==1) = -g(free==1); old_dirs = zeros(p,0); old_stps = zeros(p,0); Hdiag = 1; else y = g-g_prev; s = w-w_prev; numCorrections = size(old_dirs,2); if numCorrections < corrections % Full Update old_dirs(:,numCorrections+1) = s; old_stps(:,numCorrections+1) = y; else % Limited-Memory Update old_dirs = [old_dirs(:,2:corrections) s]; old_stps = [old_stps(:,2:corrections) y]; end % Update scale of initial Hessian approximation Hdiag = (y'*s)/(y'*y); % Find updates where curvature condition was satisfied curvSat = sum(old_dirs(free==1,:).*old_stps(free==1,:)) > 1e-10; % Compute descent direction d(free==1) = lbfgsC(-g(free==1),old_dirs(free==1,curvSat),old_stps(free==1,curvSat),Hdiag); end g_prev = g; w_prev = w; end gtd = g'*d; if gtd > -optTol if verbose fprintf('Directional Derivative too small\n'); end break; end if pArc == 0 d = max(w + d,0)-w; end [t,f_prev] = initialStepLength(i,adjustStep,order,f,g,gtd,t,f_prev); % Line Search if order >= 2 [t,w,f,g,LSfunEvals,H] = ArmijoBacktrack(w,t,d,f,f,g,gtd,1e-4,2,optTol,... max(verbose-1,0),0,0,@projNonNegGrad,lambda,gradFunc,varargin{:}); else [t,w,f,g,LSfunEvals] = ArmijoBacktrack(w,t,d,f,f,g,gtd,1e-4,2,optTol,... max(verbose-1,0),0,1,@projNonNegGrad,lambda,gradFunc,varargin{:}); end fEvals = fEvals + LSfunEvals; % Project Results into non-negative orthant if pArc == 1 w(w < 0) = 0; end % Compute free variables w(abs(w) < threshold) = 0; free = ones(p,1); free(w==0 & g >= 0) = 0; % Update log if verbose fprintf('%10d %10d %15.5e %15.5e %15.5e %5d\n',i,fEvals,t,f,sum(abs(g(free==1))),sum(abs(w(1:p/2)-w(p/2+1:end))>threshold)); end if sum(abs(g(free==1))) < optTol if verbose fprintf('Solution Found\n'); end break; end if sum(free==1) == 0 break; end if noProgress(t*d,f,f_old,optTol,verbose) break; end i = i +1; end w = w(1:length(w)/2)-w(length(w)/2 + 1:end); end function [f,g,H] = projNonNegGrad(w,lambda,gradFunc,varargin) w(w < 0) = 0; if nargout == 1 f = nonNegGrad(w,lambda,gradFunc,varargin{:}); elseif nargout == 2 [f,g] = nonNegGrad(w,lambda,gradFunc,varargin{:}); else [f,g,H] = nonNegGrad(w,lambda,gradFunc,varargin{:}); end end
github
lijunzh/fd_elastic-master
logdetFunction.m
.m
fd_elastic-master/src/PQN/GGM/logdetFunction.m
442
utf_8
e089e4642ff4aaaf50516b6488a257a1
function [f,g] = logdetFunction(w,sigma) n = size(sigma,1); w = reshape(w,[n,n]); f = -logdet(sigma + w,-Inf); if ~isinf(f) g = -inv(sigma + w); else g = zeros(size(sigma)); end g = g(:); global trace if trace == 1 global fValues fValues(end+1,1) = -f; drawnow end end function l = logdet(M,errorDet) [R,p] = chol(M); if p ~= 0 l = errorDet; else l = 2*sum(log(diag(R))); end end
github
lijunzh/fd_elastic-master
drawGraph.m
.m
fd_elastic-master/src/PQN/KPM/drawGraph.m
46,847
utf_8
d2429b94526ebcbca9649f90cd0a6b9d
function drawGraph(adj, varargin) % drawGraph Automatic graph layout: interface to Neato (see http://www.graphviz.org/) % % drawGraph(adjMat, ...) draws a graph in a matlab figure % % Optional arguments (string/value pair) [default in brackets] % % labels - labels{i} is a *string* for node i [1:n] % removeSelfLoops - [1] % removeIsolatedNodes - [1] % filename - name for postscript file [tmp.ps] % directed - [default: determine from symmetry of adj] % systemFolder - [defaults to location returned by graphvizRoot()] % % To set graphvizRoot, add the diectory where dot.exe lives % to your matlab path, and then store the following lines in a file % called 'graphvizRoot.m' in the same place: % function pathstr = graphvizRoot() % [pathstr, name, ext, ver] = fileparts(which('graphvizRoot')); % % This function writes files 'tmp.dot' and 'layout.dot' % to the specified system folder, so you need write permission. % If this folder is the location where the graphviz executables are, % it will automatically convert the .dot file to .ps. % Otherwise you must cd to that directory and type the following at a dos command prompt % dot tmp.dot -T ps -o tmp.ps % % Example % 1->2 3 4-5 % adj = zeros(5,5); % adj(1,2)=1; adj(4,5)=1; adj(5,4)=1; % adj(1,1) = 1; % clf;drawGraph(adj) % clf;drawGraph(adj, 'labels', {'a','bbbb','c','d','e'}) % clf;drawGraph(adj, 'removeIsolatedNodes', 0, 'removeSelfLoops', 0); % % Written by Leon Peshkin and Kevin Murphy % with contributions from Tom Minka, Alexi Savov % Contains arrow.m by Erik A. Johnson % Contains graph_draw by Ali Taylan Cemgil % % Last updated 7 June 2006 % if 0 adj = zeros(5,5); adj(1,2)=1; adj(4,5)=1; adj(5,4)=1; adj(1,1) = 1; clf;drawGraph(adj, 'filename', 'foo.ps') clf;drawGraph(adj) clf;drawGraph(adj, 'labels', {'a','bbbb','c','d','e'}) clf;drawGraph(adj, 'removeIsolatedNodes', 0, 'removeSelfLoops', 0); end if ~exist('graphvizRoot','file') systemFolder = []; str = sprintf('%s %s %s\n', ... 'warning: you should put the file graphvizRoot.m', ... 'into the graphviz/bin directory', ... 'if you want to convert to postscript'); %fprintf(str) else %'C:\Program Files\ATT\Graphviz\bin', ... systemFolder = graphvizRoot(); end [systemFolder, labels, removeSelfLoops, removeIsolatedNodes, filename, directed] = ... process_options(varargin, 'systemFolder', systemFolder, ... 'labels', [], 'removeSelfLoops', 1, ... 'removeIsolatedNodes', 1, 'filename', [], 'directed', []); if removeSelfLoops adj = setdiag(adj, 0); end [n,m] = size(adj); if n ~= m, warning('not a square adjacency matrix!'); end %if ~isequal(diag(adj),zeros(n,1)), warning('Self-loops in adjacency matrix!');end if isempty(labels) labels = cell(1,n); for i=1:n labels{i} = sprintf('%d', i); end end if removeIsolatedNodes isolated = []; for i=1:n nbrs = [find(adj(i,:)) find(adj(:,i))']; nbrs = setdiff(nbrs, i); if isempty(nbrs) isolated = [isolated i]; end end adj = removeRowsCols(adj, isolated, isolated); labels(isolated) = []; end if isempty(directed) %if isequal(triu(adj ,1),tril(adj,-1)'), directed = 0; else, directed = 1; end if isequal(adj,adj') directed = 0; else directed = 1; end end adj = double(adj > 0); % make sure it is a binary matrix cast to double type % to be platform independant no use of directories in temporary filenames %tmpDOTfile = '_GtDout.dot'; tmpLAYOUT = '_LAYout.dot'; tmpDOTfile = 'tmp.dot'; tmpLAYOUT = 'layout.dot'; % store graph in tmp.dot graph_to_dot(adj, 'directed', directed, ... 'filename', tmpDOTfile, 'node_label', labels); if ispc, shell = 'dos'; else, shell = 'unix'; end % Which OS ? cmnd = strcat(shell,'(''neato -V'')'); % request version to check NEATO is there status = eval(cmnd); if status == 1, warning('DOT/NEATO not accessible'); end % store layout information in layout.dot neato = '(''neato -Tdot -Gmaxiter=5000 -Gstart=7 -o'; % -Gstart="regular" -Gregular cmnd = strcat([shell neato tmpLAYOUT ' ' tmpDOTfile ''')']); % -x compact status = eval(cmnd); % get NEATO to layout % dot_to_graph fails on isolated vertices % so instead we just read in the position information from neato if 0 [trash, names, x, y] = dot_to_graph(tmpLAYOUT); % load NEATO layout [ignore,lbl_ndx] = sort(str2num(char(names))'); % recover from dot_to_graph node_ID permutation x = x(lbl_ndx); y = y(lbl_ndx); else % new labels may not be in 1:1 correspondence with node numbers [x, y, newLabels] = readCoordsFromDotFile(tmpLAYOUT, n); end % now pick a healthy font size and plot if n > 40, fontsz = 7; elseif n < 12, fontsz = 12; else fontsz = 9; end %figure; clf; axis square % now plot [x, y, h] = graph_draw(adj, 'node_labels', newLabels, 'fontsize', fontsz, ... 'node_shapes', zeros(size(x,2),1), 'X', x, 'Y', y); drawnow %delete(tmpLAYOUT); delete(tmpDOTfile); %%%%%%%%%%%%%% %%% Now convert .dot to .ps % This must be run inside the directory where dot.exe lives... if isempty(systemFolder), return; end currentDir = pwd; cd(systemFolder); try graph_to_dot(adj, 'directed', directed, ... 'filename', tmpDOTfile, 'node_label', labels); fprintf('converting to postscript\n'); % store postscript in tmp.ps - this does not work automatically... cmd = sprintf('dot -Tps tmp.dot -o tmp.ps', shell) status = system(cmd) %cmnd = strcat(shell,'(''dot -Tps tmp.dot -o tmp.os'')'); %status = eval(cmnd) %!dot -Tps tmp.dot -o tmp.ps if ~isempty(filename) %cmd = sprintf('move tmp.ps %s', fullfile(currentDir,filename)) cmd = sprintf('move tmp.ps %s', filename); system(cmd) end catch fprintf('sorry, cant convetr to postscript automatigcally\n'); end cd(currentDir) %%%%%%%%%%%%%%% function graph_to_dot(adj, varargin) % graph_to_dot(adj, VARARGIN) Creates a GraphViz (AT&T) format file representing % a graph given by an adjacency matrix. % Optional arguments should be passed as name/value pairs [default] % % 'filename' - if omitted, writes to 'tmp.dot' % 'arc_label' - arc_label{i,j} is a string attached to the i-j arc [""] % 'node_label' - node_label{i} is a string attached to the node i ["i"] % 'width' - width in inches [10] % 'height' - height in inches [10] % 'leftright' - 1 means layout left-to-right, 0 means top-to-bottom [0] % 'directed' - 1 means use directed arcs, 0 means undirected [1] % % For details on dotty, See http://www.research.att.com/sw/tools/graphviz % % by Dr. Leon Peshkin, Jan 2004 inspired by Kevin Murphy's BNT % pesha @ ai.mit.edu /~pesha node_label = []; arc_label = []; % set default args width = 10; height = 10; leftright = 0; directed = 1; filename = 'tmp.dot'; for i = 1:2:nargin-1 % get optional args switch varargin{i} case 'filename', filename = varargin{i+1}; case 'node_label', node_label = varargin{i+1}; case 'arc_label', arc_label = varargin{i+1}; case 'width', width = varargin{i+1}; case 'height', height = varargin{i+1}; case 'leftright', leftright = varargin{i+1}; case 'directed', directed = varargin{i+1}; end end fid = fopen(filename, 'w'); if fid==-1 error(sprintf('could not write to %s', filename)) end if directed fprintf(fid, 'digraph G {\n'); arctxt = '->'; if isempty(arc_label) labeltxt = ''; else labeltxt = '[label="%s"]'; end else fprintf(fid, 'graph G {\n'); arctxt = '--'; if isempty(arc_label) labeltxt = '[dir=none]'; else labeltext = '[label="%s",dir=none]'; end end fprintf(fid, 'center = 1;\n'); fprintf(fid, 'size=\"%d,%d\";\n', width, height); if leftright fprintf(fid, 'rankdir=LR;\n'); end Nnds = length(adj); for node = 1:Nnds % process NODEs if isempty(node_label) fprintf(fid, '%d;\n', node); else fprintf(fid, '%d [ label = "%s" ];\n', node, node_label{node}); end end edgeformat = strcat(['%d ',arctxt,' %d ',labeltxt,';\n']); for node1 = 1:Nnds % process ARCs if directed arcs = find(adj(node1,:)); % children(adj, node); else arcs = find(adj(node1,node1+1:Nnds)) + node1; % remove duplicate arcs end for node2 = arcs fprintf(fid, edgeformat, node1, node2); end end fprintf(fid, '}'); fclose(fid); function [x, y, label] = readCoordsFromDotFile(filename, Nvrt) % Given a file like this % % digraph G { % 1 [pos="28,31"]; % 2 [pos="74,87"]; % 1 -- 2 [pos="e,61,71 41,47 46,53 50,58 55,64"]; % % we return x=[28,74], y=[31,87] % We assume nodes are numbered, not named. % We assume all the coordinate information comes at the beginning of the file. % We terminate as soon as we have read coords for Nvrt nodes. % We do not read the graph structure information. % KPM 23 May 2006 lines = textread(filename,'%s','delimiter','\n','commentstyle','c'); % ignoring C-style comments dot_lines = strvcat(lines); if isempty(findstr(dot_lines(1,:), 'graph ')) error('* * * File does not appear to be in valid DOT format. * * *'); end; x = []; y = []; label = []; % in case there are no nodes... %x = zeros(1, Nvrt); %y = zeros(1, Nvrt); seenNode = zeros(1, Nvrt); line_ndx = 1; done = 0; while ~done if line_ndx > size(dot_lines, 1) | all(seenNode) break end line = dot_lines(line_ndx,:); if ~isempty(strfind(line, '->')) | ~isempty(strfind(line, '--')) %finished reading location information - quitting break end line_ndx = line_ndx + 1; if isempty(strfind(line, 'pos')) % skip header info continue; end str = line; %cells = regexp(str, '(\d+)\s+\[pos="(\d+),(\d+)', 'tokens'); %cells = regexp(str, '(\d+)\s+\[label=(\w+), pos="(\d+),(\d+)', 'tokens'); % fixed by David Duvenaud cells = regexp(str, '(\d+)\s+\[label=(\w+), pos="(\d+\.?\d+),(\d+\.?\d+)', 'tokens'); node = str2num(cells{1}{1}); %label(node) = str2num(cells{1}{2}); %label{node} = num2str(cells{1}{2}); label{node} = cells{1}{2}; xx = str2num(cells{1}{3}); yy = str2num(cells{1}{4}); x(node) = xx; y(node) = yy; %fprintf('n=%d,x=%d,y=%d,%s!\n', node, xx, yy, label{node}); seenNode(node) = 1; end x = .9*(x-min(x))/range(x)+.05; % normalise and push off margins if range(y) == 0, y = .5*ones(size(y)); else, y = .9*(y-min(y))/range(y)+.05; end %%%%%%%%%%%% function [Adj, labels, x, y] = dot_to_graph(filename) % [Adj, labels, x, y] = dot_to_graph(filename) % Extract an adjacency matrix, node labels, and layout (nodes coordinates) % from GraphViz file http://www.research.att.com/sw/tools/graphviz % % INPUT: 'filename' - the file in DOT format containing the graph layout. % OUTPUT: 'Adj' - an adjacency matrix with sequentially numbered edges; % 'labels' - a character array with the names of the nodes of the graph; % 'x' - a row vector with the x-coordinates of the nodes in 'filename'; % 'y' - a row vector with the y-coordinates of the nodes in 'filename'. % % WARNINGS: not guaranted to parse ANY GraphViz file. Debugged on undirected % sample graphs from GraphViz(Heawood, Petersen, ER, ngk10_4, process). % Complaines about RecursionLimit on huge graphs. % Ignores singletons (disjoint nodes). % Sample DOT code "ABC.dot", read by [Adj, labels, x, y] = dot_to_graph('ABC.dot') % Plot by draw_graph(adj>0, labels, zeros(size(x,2),1), x, y); % from BNT % digraph G { % A [pos="28,31"]; % B [pos="74,87"]; % A -- B [pos="e,61,71 41,47 46,53 50,58 55,64"]; % } % last modified: Jan 2004 % by Dr. Leon Peshkin: pesha @ ai.mit.edu | http://www.ai.mit.edu/~pesha % & Alexi Savov: asavov @ wustl.edu | http://artsci.wustl.edu/~azsavov % UNCOMMENT, but beware -- SLOW CHECK !!!! %if ~exist(filename) % Checks whether the specified file exists. % error('* * * File does not exist or could not be found. * * *'); return; %end; lines = textread(filename,'%s','delimiter','\n','commentstyle','c'); % Read file into cell array of lines dot_lines = strvcat(lines); % ignoring C-style comments if isempty(findstr(dot_lines(1,:), 'graph ')) % Is this a DOT file ? error('* * * File does not appear to be in valid DOT format. * * *'); return; end; Nlns = size(dot_lines,1); % The number of lines; labels = {}; unread = 1:Nlns; % 'unread' list of lines which has not been examined yet edge_id = 1; for line_ndx = 1:Nlns % This section sets the adjacency matrix entry A(Lnode,Rnode) = edge_id. line = dot_lines(line_ndx,:); Ddash_pos = strfind(line, ' -- ') + 1; % double dash positions arrow_pos = strfind(line, ' -> ') + 1; % arrow dash positions tokens = strread(line,'%s','delimiter',' "'); left_bound = 1; for dash_pos = [Ddash_pos arrow_pos]; % if empty - not a POS line Lnode = sscanf(line(left_bound:dash_pos -2), '%s'); Rnode = sscanf(line(dash_pos +3 : length(line)-1),'%s',1); Lndx = strmatch(Lnode, labels, 'exact'); Rndx = strmatch(Rnode, labels, 'exact'); if isempty(Lndx) % extend our list of labels labels{end+1} = Lnode; Lndx = length(labels); end if isempty(Rndx) labels{end+1} = Rnode; Rndx = length(labels); end Adj(Lndx, Rndx) = edge_id;; if ismember(dash_pos, Ddash_pos) % The edge is undirected, A(Rndx,LndxL) is also set to 1; Adj(Rndx, Lndx) = edge_id; end edge_id = edge_id + 1; left_bound = dash_pos + 3; unread = my_setdiff(unread, line_ndx); end end Nvrt = length(labels); % number of vertices we found [Do we ever have singleton vertices ???] % labels = strvcat(labels); % could convert to the searchable array x = zeros(1, Nvrt); y = zeros(1, Nvrt); lst_node = 0; % Find node's position coordinates if they are contained in 'filename'. for line_ndx = unread % Look for node's coordiantes among the 'unread' lines. line = dot_lines(line_ndx,:); bra_pos = strfind(line, '['); % has to have "[" if it has the lable pos_pos = strfind(line, 'pos'); % position of the "pos" for node = 1:Nvrt % look through the list of labels % THE NEXT STATEMENT we assume no label is substring of any other label lbl_pos = strfind(line, labels{node}); if ((~isempty(lbl_pos)) & (~isempty(bra_pos)) & (x(node) == 0)) % make sure we have not seen it if (lbl_pos(1) < bra_pos(1)) % label has to be to the left of braket lst_node = node; end end end if (~isempty(pos_pos) & lst_node) % this line contains SOME position [node_pos] = sscanf(line(pos_pos:length(line)), ' pos = "%d,%d"')'; x(lst_node) = node_pos(1); y(lst_node) = node_pos(2); lst_node = 0; % not to assign position several times end end if (isempty(find(x)) & (nargout > 2)) % If coordinates were requested, but not found in 'filename'. warning('File does not contain node coordinates.'); else x = .9*(x-min(x))/range(x)+.05; % normalise and push off margins if range(y) == 0, y = .5*ones(size(y)); else, y = .9*(y-min(y))/range(y)+.05; end end; if ~(size(Adj,1)==size(Adj,2)) % Make sure Adj is a square matrix. ? Adj = eye(max(size(Adj)),size(Adj,1))*Adj*eye(size(Adj,2),max(size(Adj))); end; %%%%%%%%%%%%%%%%%%%%% function [x, y, h] = graph_draw(adj, varargin) % [x, y, h] = graph_draw(adj, varargin) % % INPUTS: ADJ - Adjacency matrix (source, sink) % 'linestyle' - default '-' % 'linewidth' - default .5 % 'linecolor' - default Black % 'fontsize' - fontsize for labels, default 8 % 'node_labels' - Cell array containing labels <Default : '1':'N'> % 'node_shapes' - 1 if node is a box, 0 if oval <Default : zeros> % 'X' Coordinates of nodes on the unit square <Default : calls make_layout> % 'Y' % % OUTPUT: x, y - Coordinates of nodes on the unit square % h - Object handles [h(i,1) is the text handle - color % h(i,2) is the circle handle - facecolor] % % 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); labels = cellstr(int2str((1:N)')); % labels = cellstr(char(zeros(N,1)+double('+'))); node_t = zeros(N,1); % for i = 1:2:nargin-1 % 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 'node_labels', labels = varargin{i+1}; case 'fontsize', fontsize = varargin{i+1}; case 'node_shapes', node_t = varargin{i+1}; node_t = node_t(:); case 'X', x = varargin{i+1}; case 'Y', y = varargin{i+1}; end end axis([0 1 0 1]); set(gca,'XTick',[], 'YTick',[], 'box','on'); % axis('square'); %colormap(flipud(gray)); if (~exist('x','var') | ~exist('x','var')) [x y] = make_layout(adj); end; idx1 = find(node_t == 0); wd1 = []; if ~isempty(idx1), [h1 wd1] = textoval(x(idx1), y(idx1), labels(idx1), fontsize); end; idx2 = find(node_t ~= 0); wd2 = []; if ~isempty(idx2), [h2 wd2] = textbox(x(idx2), y(idx2), labels(idx2)); 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, 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) % [t, wd] = textoval(x, y, str, fontsize) Draws an oval around text objects % INPUT: x, y - Coordinates % str - Strings % OUTPUT: t - Object Handles % width - x and y width of ovals temp = []; if ~isa(str,'cell'), str = cellstr(str); end; N = length(str); wd = zeros(N,2); for i = 1:N, tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','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); set(ptc, 'FaceColor','w'); wd(i,:) = [wx wy]; delete(tx); tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlign','middle', 'FontSize',fontsize); temp = [temp; tx ptc]; end; t = temp; function [p] = ellipse(x, y, rx, ry) % [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 % OUTPUT: p - Handles of Ellipse shaped path objects c = ones(size(x)); 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) % [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 h = []; if ~isa(str,'cell') str=cellstr(str); end; N = length(str); for i = 1:N, tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','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],'w'); % draw_box(tx, x(i), y(i)); set(ptc, 'FaceColor','w'); wd(i,:) = [wx wy]; delete(tx); tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlign','middle'); h = [h; 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(min(find(oldaxlims(:,1)==0)),:) = [curax reshape(axl',1,6)]; % get axes size in pixels (points) u = get(curax,'Units'); axposoldunits = get(curax,'Position'); really_curpage = curpage & strcmp(u,'normalized'); if (really_curpage), curfig = get(curax,'Parent'); pu = get(curfig,'PaperUnits'); set(curfig,'PaperUnits','points'); pp = get(curfig,'PaperPosition'); set(curfig,'PaperUnits',pu); set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); set(curax,'Units','normalized'); curap = pp.*get(curax,'Position'); else, set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); curap = curapscreen; end; set(curax,'Units',u); set(curax,'Position',axposoldunits); % handle non-stretched axes position str_stretch = {'DataAspectRatioMode'; 'PlotBoxAspectRatioMode' ; 'CameraViewAngleMode' }; str_camera = {'CameraPositionMode' ; 'CameraTargetMode' ; ... 'CameraViewAngleMode' ; 'CameraUpVectorMode'}; notstretched = strcmp(get(curax,str_stretch),'manual'); manualcamera = strcmp(get(curax,str_camera),'manual'); if ~arrow_WarpToFill(notstretched,manualcamera,curax), % 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')'; curlimrange = max(lim')' - curlimmin; curinvT = inv(curT); if (~oneax), curT = curT.'; curinvT = curinvT.'; curT = curT(:); curinvT = curinvT(:); end; % check which arrows to which cur corresponds ii = find((ax==curax)&(page==curpage)); oo = ones(1,length(ii)); axr(:,ii) = diff(axl')' * oo; axm(:,ii) = axl(:,1) * oo; axrev(:,ii) = curreverse * oo; ap(:,ii) = curap(3:4)' * oo; xyzlog(:,ii) = curxyzlog * oo; limmin(:,ii) = curlimmin * oo; limrange(:,ii) = curlimrange * oo; if (oneax), T = curT; invT = curinvT; else, T(:,ii) = curT * oo; invT(:,ii) = curinvT * oo; end; axnotdone(ii) = zeros(1,length(ii)); end; oldaxlims(oldaxlims(:,1)==0,:) = []; % correct for log scales curxyzlog = xyzlog.'; ii = find(curxyzlog(:)); if ~isempty(ii), start(ii) = real(log10(start(ii))); stop(ii) = real(log10(stop(ii))); if (all(imag(crossdir)==0)), % pulled (ii) subscript on crossdir, 12/5/96 eaj crossdir(ii) = real(log10(crossdir(ii))); end; end; 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) % check if we are in "WarpToFill" mode. out = strcmp(get(curax,'WarpToFill'),'on'); % 'WarpToFill' is undocumented, so may need to replace this by % out = ~( any(notstretched) & any(manualcamera) ); %%%%%% function C = my_setdiff(A,B) % MYSETDIFF Set difference of two sets of positive integers (much faster than built-in setdiff) % C = my_setdiff(A,B) % C = A \ B = { things in A that are not in B } % by Leon Peshkin pesha at ai.mit.edu 2004, inspired by BNT of Kevin Murphy if isempty(A) C = []; return; elseif isempty(B) C = A; return; else % both non-empty bits = zeros(1, max(max(A), max(B))); bits(A) = 1; bits(B) = 0; C = A(logical(bits(A))); end %%%%%%%%%% % PROCESS_OPTIONS - Processes options passed to a Matlab function. % This function provides a simple means of % parsing attribute-value options. Each option is % named by a unique string and is given a default % value. % % Usage: [var1, var2, ..., varn[, unused]] = ... % process_options(args, ... % str1, def1, str2, def2, ..., strn, defn) % % Arguments: % args - a cell array of input arguments, such % as that provided by VARARGIN. Its contents % should alternate between strings and % values. % str1, ..., strn - Strings that are associated with a % particular variable % def1, ..., defn - Default values returned if no option % is supplied % % Returns: % var1, ..., varn - values to be assigned to variables % unused - an optional cell array of those % string-value pairs that were unused; % if this is not supplied, then a % warning will be issued for each % option in args that lacked a match. % % Examples: % % Suppose we wish to define a Matlab function 'func' that has % required parameters x and y, and optional arguments 'u' and 'v'. % With the definition % % function y = func(x, y, varargin) % % [u, v] = process_options(varargin, 'u', 0, 'v', 1); % % calling func(0, 1, 'v', 2) will assign 0 to x, 1 to y, 0 to u, and 2 % to v. The parameter names are insensitive to case; calling % func(0, 1, 'V', 2) has the same effect. The function call % % func(0, 1, 'u', 5, 'z', 2); % % will result in u having the value 5 and v having value 1, but % will issue a warning that the 'z' option has not been used. On % the other hand, if func is defined as % % function y = func(x, y, varargin) % % [u, v, unused_args] = process_options(varargin, 'u', 0, 'v', 1); % % then the call func(0, 1, 'u', 5, 'z', 2) will yield no warning, % and unused_args will have the value {'z', 2}. This behaviour is % useful for functions with options that invoke other functions % with options; all options can be passed to the outer function and % its unprocessed arguments can be passed to the inner function. % Copyright (C) 2002 Mark A. Paskin % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 % USA. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [varargout] = process_options(args, varargin) % Check the number of input arguments n = length(varargin); if (mod(n, 2)) error('Each option must be a string/value pair.'); end % Check the number of supplied output arguments if (nargout < (n / 2)) error('Insufficient number of output arguments given'); elseif (nargout == (n / 2)) warn = 1; nout = n / 2; else warn = 0; nout = n / 2 + 1; end % Set outputs to be defaults varargout = cell(1, nout); for i=2:2:n varargout{i/2} = varargin{i}; end % Now process all arguments nunused = 0; for i=1:2:length(args) found = 0; for j=1:2:n if strcmpi(args{i}, varargin{j}) varargout{(j + 1)/2} = args{i + 1}; found = 1; break; end end if (~found) if (warn) warning(sprintf('Option ''%s'' not used.', args{i})); args{i} else nunused = nunused + 1; unused{2 * nunused - 1} = args{i}; unused{2 * nunused} = args{i + 1}; end end end % Assign the unused arguments if (~warn) if (nunused) varargout{nout} = unused; else varargout{nout} = cell(0); end end %%%%%%%%%%%% function M = removeRowsCols(M, rows, cols) % Remove rows and columns from a matrix % Example % M = reshape(1:25,[5 5]) %> removeRowsCols(M, [2 3], 4) %ans = % 1 6 11 21 % 4 9 14 24 % 5 10 15 25 [nr nc] = size(M); ndx = []; for i=1:length(rows) tmp = repmat(rows(i), nc, 1); tmp2 = [tmp (1:nc)']; ndx = [ndx; tmp2]; end for i=1:length(cols) tmp = repmat(cols(i), nr, 1); tmp2 = [(1:nr)' tmp]; ndx = [ndx; tmp2]; end if isempty(ndx), return; end k = subv2ind([nr nc], ndx); M(k) = []; M = reshape(M, [nr-length(rows) nc-length(cols)]); %%%%%%%%% function M = setdiag(M, v) % SETDIAG Set the diagonal of a matrix to a specified scalar/vector. % M = set_diag(M, v) n = length(M); if length(v)==1 v = repmat(v, 1, n); end % e.g., for 3x3 matrix, elements are numbered % 1 4 7 % 2 5 8 % 3 6 9 % so diagnoal = [1 5 9] J = 1:n+1:n^2; M(J) = v; %M = triu(M,1) + tril(M,-1) + diag(v); %%%%%%%%%%% function ndx = subv2ind(siz, subv) % SUBV2IND Like the built-in sub2ind, but the subscripts are given as row vectors. % ind = subv2ind(siz,subv) % % siz can be a row or column vector of size d. % subv should be a collection of N row vectors of size d. % ind will be of size N * 1. % % Example: % subv = [1 1 1; % 2 1 1; % ... % 2 2 2]; % subv2ind([2 2 2], subv) returns [1 2 ... 8]' % i.e., the leftmost digit toggles fastest. % % See also IND2SUBV. if isempty(subv) ndx = []; return; end if isempty(siz) ndx = 1; return; end [ncases ndims] = size(subv); %if length(siz) ~= ndims % error('length of subscript vector and sizes must be equal'); %end if all(siz==2) %rbits = subv(:,end:-1:1)-1; % read from right to left, convert to 0s/1s %ndx = bitv2dec(rbits)+1; twos = pow2(0:ndims-1); ndx = ((subv-1) * twos(:)) + 1; %ndx = sum((subv-1) .* twos(ones(ncases,1), :), 2) + 1; % equivalent to matrix * vector %ndx = sum((subv-1) .* repmat(twos, ncases, 1), 2) + 1; % much slower than ones %ndx = ndx(:)'; else %siz = siz(:)'; cp = [1 cumprod(siz(1:end-1))]'; %ndx = ones(ncases, 1); %for i = 1:ndims % ndx = ndx + (subv(:,i)-1)*cp(i); %end ndx = (subv-1)*cp + 1; end %%%%%%%%%%% function d = bitv2dec(bits) % BITV2DEC Convert a bit vector to a decimal integer % d = butv2dec(bits) % % This is just like the built-in bin2dec, except the argument is a vector, not a string. % If bits is an array, each row will be converted. [m n] = size(bits); twos = pow2(n-1:-1:0); d = sum(bits .* twos(ones(m,1),:),2);
github
lijunzh/fd_elastic-master
process_options.m
.m
fd_elastic-master/src/PQN/KPM/process_options.m
4,394
utf_8
483b50d27e3bdb68fd2903a0cab9df44
% PROCESS_OPTIONS - Processes options passed to a Matlab function. % This function provides a simple means of % parsing attribute-value options. Each option is % named by a unique string and is given a default % value. % % Usage: [var1, var2, ..., varn[, unused]] = ... % process_options(args, ... % str1, def1, str2, def2, ..., strn, defn) % % Arguments: % args - a cell array of input arguments, such % as that provided by VARARGIN. Its contents % should alternate between strings and % values. % str1, ..., strn - Strings that are associated with a % particular variable % def1, ..., defn - Default values returned if no option % is supplied % % Returns: % var1, ..., varn - values to be assigned to variables % unused - an optional cell array of those % string-value pairs that were unused; % if this is not supplied, then a % warning will be issued for each % option in args that lacked a match. % % Examples: % % Suppose we wish to define a Matlab function 'func' that has % required parameters x and y, and optional arguments 'u' and 'v'. % With the definition % % function y = func(x, y, varargin) % % [u, v] = process_options(varargin, 'u', 0, 'v', 1); % % calling func(0, 1, 'v', 2) will assign 0 to x, 1 to y, 0 to u, and 2 % to v. The parameter names are insensitive to case; calling % func(0, 1, 'V', 2) has the same effect. The function call % % func(0, 1, 'u', 5, 'z', 2); % % will result in u having the value 5 and v having value 1, but % will issue a warning that the 'z' option has not been used. On % the other hand, if func is defined as % % function y = func(x, y, varargin) % % [u, v, unused_args] = process_options(varargin, 'u', 0, 'v', 1); % % then the call func(0, 1, 'u', 5, 'z', 2) will yield no warning, % and unused_args will have the value {'z', 2}. This behaviour is % useful for functions with options that invoke other functions % with options; all options can be passed to the outer function and % its unprocessed arguments can be passed to the inner function. % Copyright (C) 2002 Mark A. Paskin % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 % USA. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [varargout] = process_options(args, varargin) % Check the number of input arguments n = length(varargin); if (mod(n, 2)) error('Each option must be a string/value pair.'); end % Check the number of supplied output arguments if (nargout < (n / 2)) error('Insufficient number of output arguments given'); elseif (nargout == (n / 2)) warn = 1; nout = n / 2; else warn = 0; nout = n / 2 + 1; end % Set outputs to be defaults varargout = cell(1, nout); for i=2:2:n varargout{i/2} = varargin{i}; end % Now process all arguments nunused = 0; for i=1:2:length(args) found = 0; for j=1:2:n if strcmpi(args{i}, varargin{j}) varargout{(j + 1)/2} = args{i + 1}; found = 1; break; end end if (~found) if (warn) warning(sprintf('Option ''%s'' not used.', args{i})); args{i} else nunused = nunused + 1; unused{2 * nunused - 1} = args{i}; unused{2 * nunused} = args{i + 1}; end end end % Assign the unused arguments if (~warn) if (nunused) varargout{nout} = unused; else varargout{nout} = cell(0); end end
github
lijunzh/fd_elastic-master
UGM_Sample_Gibbs.m
.m
fd_elastic-master/src/PQN/UGM/sample/UGM_Sample_Gibbs.m
1,407
utf_8
ada59ec0acf3f3aa12d629909aa9ba4b
function [samples] = UGM_Sample_Gibbs(nodePot,edgePot,edgeStruct,burnIn,y) % Single Site Gibbs Sampling if nargin < 5 % Initialize [junk y] = max(nodePot,[],2); end if edgeStruct.useMex samples = UGM_Sample_GibbsC(nodePot,edgePot,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(edgeStruct.V),int32(edgeStruct.E),edgeStruct.maxIter,burnIn,int32(y)); else samples = Sample_Gibbs(nodePot,edgePot,edgeStruct,burnIn,y); end end function [samples] = Sample_Gibbs(nodePot,edgePot,edgeStruct,burnIn,y) [nNodes,maxStates] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; maxIter = edgeStruct.maxIter; samples = zeros(nNodes,0); for i = 1:burnIn+maxIter for n = 1:nNodes % Compute Node Potential pot = nodePot(n,1:nStates(n)); % Find Neighbors edges = E(V(n):V(n+1)-1); % Multiply Edge Potentials for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if n == edgeEnds(e,1) ep = edgePot(1:nStates(n1),y(n2),e)'; else ep = edgePot(y(n1),1:nStates(n2),e); end pot = pot .* ep; end % Sample State; y(n) = sampleDiscrete(pot./sum(pot)); end if i > burnIn samples(:,i-burnIn) = y; end end end
github
lijunzh/fd_elastic-master
UGM_Sample_Exact.m
.m
fd_elastic-master/src/PQN/UGM/sample/UGM_Sample_Exact.m
1,876
utf_8
3bca2622a6fc60f6cb4da8101e748893
function [samples] = UGM_Sample_Exact(nodePot,edgePot,edgeStruct) % Exact sampling [nNodes,maxState] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; nStates = edgeStruct.nStates; maxIter= edgeStruct.maxIter; samples = zeros(nNodes,0); Z = computeZ(nodePot,edgePot,edgeEnds,nStates); for s = 1:maxIter samples(:,s) = sampleY(nodePot,edgePot,edgeEnds,nStates,Z); end end function [Z] = computeZ(nodePot,edgePot,edgeEnds,nStates) nEdges = size(edgePot,3); [nNodes maxStates] = size(nodePot); y = ones(1,nNodes); Z = 0; while 1 pot = 1; % Nodes for n = 1:nNodes pot = pot*nodePot(n,y(n)); end % Edges for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); pot = pot*edgePot(y(n1),y(n2),e); end % Update Z Z = Z + pot; % Go to next y for yInd = 1:nNodes y(yInd) = y(yInd) + 1; if y(yInd) <= nStates(yInd) break; else y(yInd) = 1; end end % Stop when we are done all y combinations if sum(y==1) == nNodes break; end end end function [y] = sampleY(nodePot,edgePot,edgeEnds,nStates,Z) [nNodes,maxStates] = size(nodePot); nEdges = size(edgePot,3); y = ones(1,nNodes); cumulativePot = 0; U = rand; while 1 pot = 1; % Nodes for n = 1:nNodes pot = pot*nodePot(n,y(n)); end % Edges for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); pot = pot*edgePot(y(n1),y(n2),e); end % Update cumulative potential cumulativePot = cumulativePot + pot; if cumulativePot/Z > U % Take this y break; end % Go to next y for yInd = 1:nNodes y(yInd) = y(yInd) + 1; if y(yInd) <= nStates(yInd) break; else y(yInd) = 1; end end end end
github
lijunzh/fd_elastic-master
UGM_Infer_Exact.m
.m
fd_elastic-master/src/PQN/UGM/infer/UGM_Infer_Exact.m
1,746
utf_8
36e8e9290900e570414b692a29509b72
function [nodeBel, edgeBel, logZ] = UGM_Infer_Exact(nodePot, edgePot, edgeStruct) % INPUT % nodePot(node,class) % edgePot(class,class,edge) where e is referenced by V,E (must be the same % between feature engine and inference engine) % % OUTPUT % nodeBel(node,class) - marginal beliefs % edgeBel(class,class,e) - pairwise beliefs % logZ - negative of free energy if edgeStruct.useMex [nodeBel,edgeBel,logZ] = UGM_Infer_ExactC(nodePot,edgePot,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates)); else [nodeBel,edgeBel,logZ] = Infer_Exact(nodePot,edgePot,edgeStruct); end end function [nodeBel, edgeBel, logZ] = Infer_Exact(nodePot, edgePot, edgeStruct) [nNodes,maxStates] = size(nodePot); nEdges = size(edgePot,3); edgeEnds = edgeStruct.edgeEnds; nStates = edgeStruct.nStates; % Initialize nodeBel = zeros(size(nodePot)); edgeBel = zeros(size(edgePot)); y = ones(1,nNodes); Z = 0; i = 1; while 1 pot = UGM_ConfigurationPotential(y,nodePot,edgePot,edgeEnds); % Update nodeBel for n = 1:nNodes nodeBel(n,y(n)) = nodeBel(n,y(n))+pot; end % Update edgeBel for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); edgeBel(y(n1),y(n2),e) = edgeBel(y(n1),y(n2),e)+pot; end % Update Z Z = Z + pot; % Go to next y for yInd = 1:nNodes y(yInd) = y(yInd) + 1; if y(yInd) <= nStates(yInd) break; else y(yInd) = 1; end end % Stop when we are done all y combinations if yInd == nNodes && y(end) == 1 break; end end nodeBel = nodeBel./Z; edgeBel = edgeBel./Z; logZ = log(Z); end
github
lijunzh/fd_elastic-master
UGM_makeCRFedgePotentials.m
.m
fd_elastic-master/src/PQN/UGM/sub/UGM_makeCRFedgePotentials.m
1,989
utf_8
5ad22bbbc0fc345892b37a8ef4e8e102
function [edgePot] = UGM_makeEdgePotentials(Xedge,v,edgeStruct,infoStruct) % Makes pairwise class potentials for each node % % Xedge(1,feature,edge) % v(feature,variable,variable) - edge weights % nStates - number of States per node % % edgePot(class1,class2,edge) if edgeStruct.useMex % Mex Code edgePot = UGM_makeEdgePotentialsC(Xedge,v,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(infoStruct.tieEdges),int32(infoStruct.ising)); else % Matlab Code edgePot = makeEdgePotentials(Xedge,v,edgeStruct,infoStruct); end end function [edgePot] = makeEdgePotentials(Xedge,v,edgeStruct,infoStruct) nInstances = size(Xedge,1); nFeatures = size(Xedge,2); edgeEnds = edgeStruct.edgeEnds; nEdges = size(edgeEnds,1); tied = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; if tied ew = v; end % Compute Edge Potentials maxState = max(nStates); edgePot = zeros(maxState,maxState,nEdges,nInstances); for i = 1:nInstances for e = 1:nEdges if ~tied ew = v(:,:,e); end n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); ep = zeros(maxState); for s1 = 1:nStates(n1) for s2 = 1:nStates(n2) if ising == 2 if s1 == s2 ep(s1,s2) = exp(Xedge(i,:,e)*ew(:,s1)); else ep(s1,s2) = 1; end elseif ising if s1 == s2 ep(s1,s2) = exp(Xedge(i,:,e)*ew); else ep(s1,s2) = 1; end else if s1 == nStates(n1) && s2 == nStates(n2) ep(s1,s2) = 1; else s = (s2-1)*maxState + s1; % = sub2ind([maxState maxState],s1,s2); ep(s1,s2) = exp(Xedge(i,:,e)*ew(:,s)); end end end end edgePot(:,:,e,i) = ep; end end end
github
lijunzh/fd_elastic-master
UGM_makeCRFNodePotentials.m
.m
fd_elastic-master/src/PQN/UGM/sub/UGM_makeCRFNodePotentials.m
1,028
utf_8
6558b6ec74648c9b18d6851c2ae6f7ca
function [nodePot] = UGM_makeCRFnodePotentials(X,w,edgeStruct,infoStruct) % Makes class potentials for each node % % X(1,feature,node) % w(feature,variable,variable) - node weights % nStates - number of states per node % % nodePot(node,class) if edgeStruct.useMex % Mex Code nNodes = size(X,3); nStates = edgeStruct.nStates; nodePot = UGM_makeNodePotentialsC(X,w,int32(nStates),int32(infoStruct.tieNodes)); else % Matlab Code nodePot = makeNodePotentials(X,w,edgeStruct,infoStruct); end end % C code does the same as below: function [nodePot] = makeNodePotentials(X,w,edgeStruct,infoStruct) [nInstances,nFeatures,nNodes] = size(X); tied = infoStruct.tieNodes; nStates = edgeStruct.nStates; if tied nw = w; end % Compute Node Potentials nodePot = zeros(nNodes,max(nStates),nInstances); for i = 1:nInstances for n = 1:nNodes if ~tied nw = w(:,1:nStates(n)-1,n); end nodePot(n,1:nStates(n),i) = exp([X(i,:,n)*nw 0]); end end end
github
lijunzh/fd_elastic-master
UGM_initWeights.m
.m
fd_elastic-master/src/PQN/UGM/sub/UGM_initWeights.m
572
utf_8
b52adde4da67db63cf469d1eefd6d65f
function [w,v,wLinInd,vLinInd] = UGM_initWeights(infoStruct,initFunc) % [w,v,wLinInd,vLinInd] = UGM_initWeights(infoStruct,initFunc) % % Generates an initial weight vector % % X(instance,feature,node) % Xedge(instance,feature,edge) % infoStruct: structure containing nStates, tied, and ising % type - 'random' or 'zero' % % NOTE: initFunc used to be a string, now it is a function! if nargin < 2 initFunc = @zeros; end w = initFunc(infoStruct.wSize); v = initFunc(infoStruct.vSize); end function [r] = randomUnit(siz) r = sign(rand(siz)-.5).*(1+randn(siz)); end
github
lijunzh/fd_elastic-master
UGM_MRFLoss.m
.m
fd_elastic-master/src/PQN/UGM/train/UGM_MRFLoss.m
5,348
utf_8
23a3516c53c625c2451571adbbe4d5e7
function [f,g] = UGM_MRFLoss(wv,y,edgeStruct,infoStruct,inferFunc,varargin) % wv(variable) % X(instance,feature,node) % Xedge(instance,feature,edge) % y(instance,node) % edgeStruct % inferFunc % varargin - additional parameters of inferFunc nNodeFeatures = 1; nEdgeFeatures = 1; [nInstances,nNodes] = size(y); nFeatures = nNodeFeatures+nEdgeFeatures; edgeEnds = edgeStruct.edgeEnds; nEdges = size(edgeEnds,1); tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; maxState = max(nStates); X = ones(1,1,nNodes); Xedge = ones(1,1,nEdges); % Form weights [w,v] = UGM_splitWeights(wv,infoStruct); f = 0; if nargout > 1 gw = zeros(size(w)); gv = zeros(size(v)); end % Make Potentials nodePot = UGM_makeMRFnodePotentials(w,edgeStruct,infoStruct); if edgeStruct.useMex edgePot = UGM_makeEdgePotentialsC(Xedge,v,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(infoStruct.tieEdges),int32(infoStruct.ising)); else edgePot = UGM_makeMRFedgePotentials(v,edgeStruct,infoStruct); end % Check that potentials don't overflow if sum(nodePot(:))+sum(edgePot(:)) > 1e100 f = inf; if nargout > 1 gw = gw(infoStruct.wLinInd); gv = gv(infoStruct.vLinInd); g = [gw(:);gv(:)]; end return; end % Always use the same seed (makes learning w/ stochastic inference more robust) randState = rand('state'); rand('state',0); randnState= randn('state'); randn('state',0); % For MRFs, we only do inference once [nodeBel,edgeBel,logZ] = inferFunc(nodePot,edgePot,edgeStruct,varargin{:}); if edgeStruct.useMex % Set f to be the negative sum of the unnormalized potentials f = UGM_MRFLoss_subC(int32(y),nodePot,edgePot,int32(edgeEnds)); else f = -computeUnnormalizedPotentials(y,nodePot,edgePot,edgeEnds); end for i = 1:nInstances % Update objective based on this training example f = f + logZ; if nargout > 1 % Update gradient if edgeStruct.useMex % Update gw and gv in-place UGM_updateGradientC(gw,gv,X,Xedge,y(i,:),nodeBel,edgeBel,int32(nStates),int32(tieNodes),int32(tieEdges),int32(ising),int32(edgeEnds)); else [gw,gv] = updateGradient(gw,gv,X,Xedge,y(i,:),nodeBel,edgeBel,infoStruct,edgeStruct); end end end if nargout > 1 gw = gw(infoStruct.wLinInd); gv = gv(infoStruct.vLinInd); g = [gw(:);gv(:)]; end % Reset state rand('state',randState); randn('state',randnState); end function [f] = computeUnnormalizedPotentials(y,nodePot,edgePot,edgeEnds) [nInstances,nNodes] = size(y); nEdges = size(edgeEnds,1); f = 0; for i = 1:nInstances % Caculate Potential of Observed Labels pot = 0; for n = 1:nNodes pot = pot + log(nodePot(n,y(i,n))); end for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); pot = pot + log(edgePot(y(i,n1),y(i,n2),e)); end % Update based on this training example f = f + pot; end end function [gw,gv] = updateGradient(gw,gv,X,Xedge,y,nodeBel,edgeBel,infoStruct,edgeStruct) [nInstances nNodeFeatures nNodes] = size(X); nEdgeFeatures = size(Xedge,2); edgeEnds = edgeStruct.edgeEnds; nEdges = size(edgeEnds,1); tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; maxState = max(nStates); % Update gradient of node features for n = 1:nNodes for s = 1:nStates(n)-1 if s == y(1,n) O = X(1,:,n); else O = zeros(1,nNodeFeatures); end E = nodeBel(n,s)*X(1,:,n); if tieNodes gw(:,s) = gw(:,s) - (O - E)'; else gw(:,s,n) = gw(:,s,n) - (O - E)'; end end end % Update gradient of edge features for e = 1:nEdges n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if ising == 2 for s = 1:min(nStates(n1),nStates(n2)) if y(1,n1) == s && y(1,n2) == s O = Xedge(1,:,e); else O = zeros(1,nEdgeFeatures); end E = edgeBel(s,s,e)*Xedge(1,:,e); if tieEdges gv(:,s) = gv(:,s) - (O - E)'; else gv(:,s,e) = gv(:,s,e) - (O - E)'; end end elseif ising if y(1,n1)==y(1,n2) O = Xedge(1,:,e); else O = zeros(1,nEdgeFeatures); end E = (sum(diag(edgeBel(:,:,e))))*Xedge(1,:,e); if tieEdges gv = gv - (O - E)'; else gv(:,e) = gv(:,e) - (O - E)'; end else for s1 = 1:nStates(n1) for s2 = 1:nStates(n2) if s1 == nStates(n1) && s2 == nStates(n2) % This element is fixed at 0 continue; end if s1 == y(1,n1) && s2 == y(1,n2) O = Xedge(1,:,e); else O = zeros(1,nEdgeFeatures); end E = edgeBel(s1,s2,e)*Xedge(1,:,e); s = (s2-1)*maxState+s1; % = sub2ind([maxState maxState],s1,s2); if tieEdges gv(:,s) = gv(:,s) - (O-E)'; else gv(:,s,e) = gv(:,s,e) - (O-E)'; end end end end end end
github
lijunzh/fd_elastic-master
UGM_PseudoLoss.m
.m
fd_elastic-master/src/PQN/UGM/train/UGM_PseudoLoss.m
9,070
utf_8
fb2b963f6e701ed3ee560190279f043a
function [f,g,H] = UGM_loss(wv,X,Xedge,y,edgeStruct,infoStruct) % wv(variable) % X(instance,feature,node) % Xedge(instance,feature,edge) % y(instance,node) % edgeStruct % inferFunc % tied % Form weights [w,v] = UGM_splitWeights(wv,infoStruct); % Make Potentials nodePot = UGM_makeNodePotentials(X,w,edgeStruct,infoStruct); if edgeStruct.useMex edgePot = UGM_makeEdgePotentialsC(Xedge,v,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(infoStruct.tieEdges),int32(infoStruct.ising)); else edgePot = UGM_makeEdgePotentials(Xedge,v,edgeStruct,infoStruct); end if nargout >= 3 assert(all(edgeStruct.nStates==2) && infoStruct.ising==1 && infoStruct.tieNodes==infoStruct.tieEdges,... 'Pseudo-Hessian only implemented for 2 state Ising w/ fully tied/untied params'); end if edgeStruct.useMex edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; ising = infoStruct.ising; gw = zeros(size(w)); gv = zeros(size(v)); if nargout >= 3 tied = infoStruct.tieNodes; Hw = zeros(numel(w)); Hv = zeros(numel(v)); Hwv = zeros(numel(v),numel(w)); % gw,gv,Hw,Hv,Hwv are updated in place [f] = UGM_PseudoHessC(gw,gv,w,v,X,Xedge,int32(y),nodePot,edgePot,int32(edgeEnds),int32(V),int32(E),int32(tied),Hw,Hv,Hwv); else tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; % gw and gv are updated in place [f] = UGM_PseudoLossC(gw,gv,w,v,X,Xedge,int32(y),nodePot,edgePot,int32(edgeEnds),int32(V),int32(E),int32(nStates),int32(tieNodes),int32(tieEdges),int32(ising)); end else if nargout >= 3 [f,gw,gv,Hw,Hv,Hwv] = PseudoLoss(w,v,X,Xedge,y,nodePot,edgePot,edgeStruct,infoStruct); else [f,gw,gv] = PseudoLoss(w,v,X,Xedge,y,nodePot,edgePot,edgeStruct,infoStruct); end end gw = gw(infoStruct.wLinInd); gv = gv(infoStruct.vLinInd); g = [gw(:);gv(:)]; if nargout >= 3 Hw = Hw(infoStruct.wLinInd,infoStruct.wLinInd); Hv = Hv(infoStruct.vLinInd,infoStruct.vLinInd); H = [Hw Hwv' Hwv Hv]; end end %% Matlab version function [f,gw,gv,Hw,Hv,Hwv] = PseudoLoss(w,v,X,Xedge,y,nodePot,edgePot,edgeStruct,infoStruct) [nInstances,nNodeFeatures,nNodes] = size(X); nEdgeFeatures = size(Xedge,2); edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nEdges = size(edgeEnds,1); tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; maxState = max(nStates); showMM = 0; f = 0; gw = zeros(size(w)); gv = zeros(size(v)); if nargout > 3 Hw = zeros(numel(w)); Hv = zeros(numel(v)); Hwv = zeros(numel(v),numel(w)); end for i = 1:nInstances for n = 1:nNodes %% Update Objective % Find Neighbors edges = E(V(n):V(n+1)-1); % Compute Probability of Each State with Neighbors Fixed pot = nodePot(n,1:nStates(n),i); for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if n == edgeEnds(e,1) ep = edgePot(1:nStates(n),y(i,n2),e,i).'; else ep = edgePot(y(i,n1),1:nStates(n),e,i); end pot = pot .* ep; end % Update Objective f = f - log(pot(y(i,n))) + log(sum(pot)); %% Update Gradient if nargout > 1 nodeBel = pot/sum(pot); % Update Gradient of Node Weights for s = 1:nStates(n)-1 if s == y(i,n) Obs = X(i,:,n); else Obs = zeros(1,nNodeFeatures); end Exp = nodeBel(s)*X(i,:,n); if tieNodes gw(:,s) = gw(:,s) - (Obs - Exp).'; else gw(:,s,n) = gw(:,s,n) - (Obs - Exp).'; end end % Update Gradient of Edge Weights for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if ising if y(i,n1) == y(i,n2) Obs = Xedge(i,:,e); else Obs = zeros(1,nEdgeFeatures); end y_neigh = UGM_getNeighborState(i,n,e,y,edgeEnds); if y_neigh <= length(nodeBel) Exp = nodeBel(y_neigh)*Xedge(i,:,e); else Exp = zeros(1,nEdgeFeatures); end if tieEdges gv = gv - (Obs - Exp).'; else gv(:,e) = gv(:,e) - (Obs - Exp).'; end else for s = 1:nStates(n) if n == edgeEnds(e,1) neigh = n2; else neigh = n1; end if s == nStates(n) && y(i,neigh) == nStates(neigh) % This element is fixed at 0 continue; end if s == y(i,n) Obs = Xedge(i,:,e); else Obs = zeros(1,nEdgeFeatures); end Exp = nodeBel(s)*Xedge(i,:,e); if n == edgeEnds(e,1) s1 = s; s2 = y(i,neigh); else s1 = y(i,neigh); s2 = s; end sInd = (s2-1)*maxState+s1; if tieEdges gv(:,sInd) = gv(:,sInd) - (Obs - Exp).'; else gv(:,sInd,e) = gv(:,sInd,e) - (Obs - Exp).'; end end end end end %% Update Hessian % (only for binary, ising, and tieNodes==tieEdges) if nargout >= 4 % Update Hessian of node weights inner = nodeBel(1)*nodeBel(2); if tieNodes ind1 = 1:nNodeFeatures; ind2 = 1:nNodeFeatures; else ind1 = sub2ind(size(gw),1:nNodeFeatures,repmat(1,[1 nNodeFeatures]),repmat(n,[1 nNodeFeatures])); ind2 = sub2ind(size(gw),1:nNodeFeatures,repmat(1,[1 nNodeFeatures]),repmat(n,[1 nNodeFeatures])); end Hw(ind1,ind2) = Hw(ind1,ind2) + X(i,:,n)'*inner*X(i,:,n); % Update Hessian of edge weights wrt node/edge weights if tieEdges A = zeros(1,nEdgeFeatures); for e = edges(:)' y_neigh = UGM_getNeighborState(i,n,e,y,edgeEnds); if y_neigh == 1 A = A + Xedge(i,:,e); else A = A - Xedge(i,:,e); end end Hwv = Hwv + A'*inner*X(i,:,n); Hv = Hv + A'*inner*A; else % Untied Edges for e1 = edges(:)' y_neigh1 = UGM_getNeighborState(i,n,e1,y,edgeEnds); ind1 = sub2ind(size(gv),1:nEdgeFeatures,repmat(1,[1 nEdgeFeatures]),repmat(e1,[1 nEdgeFeatures])); ind2 = sub2ind(size(gw),1:nNodeFeatures,repmat(1,[1 nNodeFeatures]),repmat(n,[1 nNodeFeatures])); if y_neigh1 == 1 Hwv(ind1,ind2) = Hwv(ind1,ind2) + Xedge(i,:,e1)'*inner*X(i,:,n); else Hwv(ind1,ind2) = Hwv(ind1,ind2) - Xedge(i,:,e1)'*inner*X(i,:,n); end for e2 = edges(:)' y_neigh2 = UGM_getNeighborState(i,n,e2,y,edgeEnds); ind2 = sub2ind(size(gv),1:nEdgeFeatures,repmat(1,[1 nEdgeFeatures]),repmat(e2,[1 nEdgeFeatures])); if y_neigh1 == y_neigh2 Hv(ind1,ind2) = Hv(ind1,ind2) + Xedge(i,:,e1)'*inner*Xedge(i,:,e2); else Hv(ind1,ind2) = Hv(ind1,ind2) - Xedge(i,:,e1)'*inner*Xedge(i,:,e2); end end end end end if showMM nodeBel = pot./sum(pot); [junk mm(i,n)] = max(nodeBel); end end end if showMM sum(mm(:) ~= y(:))/numel(y) pause; end end function [y_neigh] = UGM_getNeighborState(i,n,e,y,edgeEnds) % Returns state of neighbor of node n along edge e if n == edgeEnds(e,1) y_neigh = y(i,edgeEnds(e,2)); else y_neigh = y(i,edgeEnds(e,1)); end end % pot: (e^(w*n)*e^(v*a)*e^(v*b)) % Z: e^(w*n)*e^(v*a)*e^(v*b) + e^(m*n)*e^(v*c)*e^(v*d)
github
lijunzh/fd_elastic-master
UGM_CRFpseudoLoss.m
.m
fd_elastic-master/src/PQN/UGM/train/UGM_CRFpseudoLoss.m
9,857
utf_8
4f2c7be5956dc41f8c3d0ffeb9e3cb83
function [f,g,H] = UGM_loss(wv,X,Xedge,y,edgeStruct,infoStruct) % wv(variable) % X(instance,feature,node) % Xedge(instance,feature,edge) % y(instance,node) % edgeStruct % inferFunc % tied % Form weights [w,v] = UGM_splitWeights(wv,infoStruct); % Make Potentials nodePot = UGM_makeCRFNodePotentials(X,w,edgeStruct,infoStruct); if edgeStruct.useMex edgePot = UGM_makeEdgePotentialsC(Xedge,v,int32(edgeStruct.edgeEnds),int32(edgeStruct.nStates),int32(infoStruct.tieEdges),int32(infoStruct.ising)); else edgePot = UGM_makeCRFEdgePotentials(Xedge,v,edgeStruct,infoStruct); end if nargout >= 3 assert(all(edgeStruct.nStates==2) && infoStruct.ising==1 && infoStruct.tieNodes==infoStruct.tieEdges,... 'Pseudo-Hessian only implemented for 2 state Ising w/ fully tied/untied params'); end if edgeStruct.useMex edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nStates = edgeStruct.nStates; ising = infoStruct.ising; gw = zeros(size(w)); gv = zeros(size(v)); if nargout >= 3 tied = infoStruct.tieNodes; Hw = zeros(numel(w)); Hv = zeros(numel(v)); Hwv = zeros(numel(v),numel(w)); % gw,gv,Hw,Hv,Hwv are updated in place [f] = UGM_PseudoHessC(gw,gv,w,v,X,Xedge,int32(y),nodePot,edgePot,int32(edgeEnds),int32(V),int32(E),int32(tied),Hw,Hv,Hwv); else tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; % gw and gv are updated in place [f] = UGM_PseudoLossC(gw,gv,w,v,X,Xedge,int32(y),nodePot,edgePot,int32(edgeEnds),int32(V),int32(E),int32(nStates),int32(tieNodes),int32(tieEdges),int32(ising)); end else if nargout >= 3 [f,gw,gv,Hw,Hv,Hwv] = PseudoLoss(w,v,X,Xedge,y,nodePot,edgePot,edgeStruct,infoStruct); else [f,gw,gv] = PseudoLoss(w,v,X,Xedge,y,nodePot,edgePot,edgeStruct,infoStruct); end end gw = gw(infoStruct.wLinInd); gv = gv(infoStruct.vLinInd); g = [gw(:);gv(:)]; if nargout >= 3 Hw = Hw(infoStruct.wLinInd,infoStruct.wLinInd); Hv = Hv(infoStruct.vLinInd,infoStruct.vLinInd); H = [Hw Hwv' Hwv Hv]; end end %% Matlab version function [f,gw,gv,Hw,Hv,Hwv] = PseudoLoss(w,v,X,Xedge,y,nodePot,edgePot,edgeStruct,infoStruct) [nInstances,nNodeFeatures,nNodes] = size(X); nEdgeFeatures = size(Xedge,2); edgeEnds = edgeStruct.edgeEnds; V = edgeStruct.V; E = edgeStruct.E; nEdges = size(edgeEnds,1); tieNodes = infoStruct.tieNodes; tieEdges = infoStruct.tieEdges; ising = infoStruct.ising; nStates = edgeStruct.nStates; maxState = max(nStates); showMM = 0; f = 0; gw = zeros(size(w)); gv = zeros(size(v)); if nargout > 3 Hw = zeros(numel(w)); Hv = zeros(numel(v)); Hwv = zeros(numel(v),numel(w)); end for i = 1:nInstances for n = 1:nNodes %% Update Objective % Find Neighbors edges = E(V(n):V(n+1)-1); % Compute Probability of Each State with Neighbors Fixed pot = nodePot(n,1:nStates(n),i); for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if n == edgeEnds(e,1) ep = edgePot(1:nStates(n),y(i,n2),e,i).'; else ep = edgePot(y(i,n1),1:nStates(n),e,i); end pot = pot .* ep; end % Update Objective f = f - log(pot(y(i,n))) + log(sum(pot)); %% Update Gradient if nargout > 1 nodeBel = pot/sum(pot); % Update Gradient of Node Weights for s = 1:nStates(n)-1 if s == y(i,n) Obs = X(i,:,n); else Obs = zeros(1,nNodeFeatures); end Exp = nodeBel(s)*X(i,:,n); if tieNodes gw(:,s) = gw(:,s) - (Obs - Exp).'; else gw(:,s,n) = gw(:,s,n) - (Obs - Exp).'; end end % Update Gradient of Edge Weights for e = edges(:)' n1 = edgeEnds(e,1); n2 = edgeEnds(e,2); if ising == 2 if y(i,n1) == y(i,n2) Obs = Xedge(i,:,e); else Obs = zeros(1,nEdgeFeatures); end y_neigh = UGM_getNeighborState(i,n,e,y,edgeEnds); if y_neigh <= length(nodeBel) Exp = nodeBel(y_neigh)*Xedge(i,:,e); else Exp = zeros(1,nEdgeFeatures); end if tieEdges gv(:,y_neigh) = gv(:,y_neigh) - (Obs - Exp).'; else gv(:,y_neigh,e) = gv(:,y_neigh,e) - (Obs - Exp).'; end elseif ising if y(i,n1) == y(i,n2) Obs = Xedge(i,:,e); else Obs = zeros(1,nEdgeFeatures); end y_neigh = UGM_getNeighborState(i,n,e,y,edgeEnds); if y_neigh <= length(nodeBel) Exp = nodeBel(y_neigh)*Xedge(i,:,e); else Exp = zeros(1,nEdgeFeatures); end if tieEdges gv = gv - (Obs - Exp).'; else gv(:,e) = gv(:,e) - (Obs - Exp).'; end else for s = 1:nStates(n) if n == edgeEnds(e,1) neigh = n2; else neigh = n1; end if s == nStates(n) && y(i,neigh) == nStates(neigh) % This element is fixed at 0 continue; end if s == y(i,n) Obs = Xedge(i,:,e); else Obs = zeros(1,nEdgeFeatures); end Exp = nodeBel(s)*Xedge(i,:,e); if n == edgeEnds(e,1) s1 = s; s2 = y(i,neigh); else s1 = y(i,neigh); s2 = s; end sInd = (s2-1)*maxState+s1; if tieEdges gv(:,sInd) = gv(:,sInd) - (Obs - Exp).'; else gv(:,sInd,e) = gv(:,sInd,e) - (Obs - Exp).'; end end end end end %% Update Hessian % (only for binary, ising, and tieNodes==tieEdges) if nargout >= 4 % Update Hessian of node weights inner = nodeBel(1)*nodeBel(2); if tieNodes ind1 = 1:nNodeFeatures; ind2 = 1:nNodeFeatures; else ind1 = sub2ind(size(gw),1:nNodeFeatures,repmat(1,[1 nNodeFeatures]),repmat(n,[1 nNodeFeatures])); ind2 = sub2ind(size(gw),1:nNodeFeatures,repmat(1,[1 nNodeFeatures]),repmat(n,[1 nNodeFeatures])); end Hw(ind1,ind2) = Hw(ind1,ind2) + X(i,:,n)'*inner*X(i,:,n); % Update Hessian of edge weights wrt node/edge weights if tieEdges A = zeros(1,nEdgeFeatures); for e = edges(:)' y_neigh = UGM_getNeighborState(i,n,e,y,edgeEnds); if y_neigh == 1 A = A + Xedge(i,:,e); else A = A - Xedge(i,:,e); end end Hwv = Hwv + A'*inner*X(i,:,n); Hv = Hv + A'*inner*A; else % Untied Edges for e1 = edges(:)' y_neigh1 = UGM_getNeighborState(i,n,e1,y,edgeEnds); ind1 = sub2ind(size(gv),1:nEdgeFeatures,repmat(1,[1 nEdgeFeatures]),repmat(e1,[1 nEdgeFeatures])); ind2 = sub2ind(size(gw),1:nNodeFeatures,repmat(1,[1 nNodeFeatures]),repmat(n,[1 nNodeFeatures])); if y_neigh1 == 1 Hwv(ind1,ind2) = Hwv(ind1,ind2) + Xedge(i,:,e1)'*inner*X(i,:,n); else Hwv(ind1,ind2) = Hwv(ind1,ind2) - Xedge(i,:,e1)'*inner*X(i,:,n); end for e2 = edges(:)' y_neigh2 = UGM_getNeighborState(i,n,e2,y,edgeEnds); ind2 = sub2ind(size(gv),1:nEdgeFeatures,repmat(1,[1 nEdgeFeatures]),repmat(e2,[1 nEdgeFeatures])); if y_neigh1 == y_neigh2 Hv(ind1,ind2) = Hv(ind1,ind2) + Xedge(i,:,e1)'*inner*Xedge(i,:,e2); else Hv(ind1,ind2) = Hv(ind1,ind2) - Xedge(i,:,e1)'*inner*Xedge(i,:,e2); end end end end end if showMM nodeBel = pot./sum(pot); [junk mm(i,n)] = max(nodeBel); end end end if showMM sum(mm(:) ~= y(:))/numel(y) pause; end end function [y_neigh] = UGM_getNeighborState(i,n,e,y,edgeEnds) % Returns state of neighbor of node n along edge e if n == edgeEnds(e,1) y_neigh = y(i,edgeEnds(e,2)); else y_neigh = y(i,edgeEnds(e,1)); end end % pot: (e^(w*n)*e^(v*a)*e^(v*b)) % Z: e^(w*n)*e^(v*a)*e^(v*b) + e^(m*n)*e^(v*c)*e^(v*d)
github
lijunzh/fd_elastic-master
UGM_makeNodePotentials.m
.m
fd_elastic-master/src/PQN/UGM/potentials/UGM_makeNodePotentials.m
1,046
utf_8
5a2e8c508b9eacbbf1d0dbcafff5fa91
function [nodePot] = makeNodePotentials(X,w,edgeStruct,infoStruct) % Makes class potentials for each node % % X(1,feature,node) % w(feature,variable,variable) - node weights % nStates - number of states per node % % nodePot(node,class) if edgeStruct.useMex % Mex Code nNodes = size(X,3); nStates = edgeStruct.nStates; nodePot = UGM_makeNodePotentialsC(X,w,int32(nStates),int32(infoStruct.tieNodes)); else % Matlab Code nodePot = makeNodePotentials(X,w,edgeStruct,infoStruct); end end % C code does the same as below (but over all instances): function [nodePot] = makeNodePotentials(X,w,edgeStruct,infoStruct) [nInstances,nFeatures,nNodes] = size(X); tied = infoStruct.tieNodes; nStates = edgeStruct.nStates; if tied nw = w; end % Compute Node Potentials nodePot = zeros(nNodes,max(nStates),nInstances); for i = 1:nInstances for n = 1:nNodes if ~tied nw = w(:,1:nStates(n)-1,n); end nodePot(n,1:nStates(n),i) = exp([X(i,:,n)*nw 0]); end end end
github
lijunzh/fd_elastic-master
WolfeLineSearch.m
.m
fd_elastic-master/src/PQN/minFunc/WolfeLineSearch.m
11,395
utf_8
3d2acf1139093fe11df95ccdf888aab8
function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(... x,t,d,f,g,gtd,c1,c2,LS,maxLS,tolX,debug,doPlot,saveHessianComp,funObj,varargin) % % Bracketing Line Search to Satisfy Wolfe Conditions % % Inputs: % x: starting location % t: initial step size % d: descent direction % f: function value at starting location % g: gradient at starting location % gtd: directional derivative at starting location % c1: sufficient decrease parameter % c2: curvature parameter % debug: display debugging information % LS: type of interpolation % maxLS: maximum number of iterations % tolX: minimum allowable step length % doPlot: do a graphical display of interpolation % funObj: objective function % varargin: parameters of objective function % % Outputs: % t: step length % f_new: function value at x+t*d % g_new: gradient value at x+t*d % funEvals: number function evaluations performed by line search % H: Hessian at initial guess (only computed if requested % Evaluate the Objective and Gradient at the Initial Step if nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x+t*d,varargin{:}); end funEvals = 1; gtd_new = g_new'*d; % Bracket an Interval containing a point satisfying the % Wolfe criteria LSiter = 0; t_prev = 0; f_prev = f; g_prev = g; gtd_prev = gtd; done = 0; while LSiter < maxLS %% Bracketing Phase if ~isLegal(f_new) || ~isLegal(g_new) if 0 if debug fprintf('Extrapolated into illegal region, Bisecting\n'); end t = (t + t_prev)/2; if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; continue; else if debug fprintf('Extrapolated into illegal region, switching to Armijo line-search\n'); end t = (t + t_prev)/2; % Do Armijo if nargout == 5 [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(... x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,... funObj,varargin{:}); else [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(... x,t,d,f,f,g,gtd,c1,max(0,min(LS-2,2)),tolX,debug,doPlot,saveHessianComp,... funObj,varargin{:}); end funEvals = funEvals + armijoFunEvals; return; end end if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev) bracket = [t_prev t]; bracketFval = [f_prev f_new]; bracketGval = [g_prev g_new]; break; elseif abs(gtd_new) <= -c2*gtd bracket = t; bracketFval = f_new; bracketGval = g_new; done = 1; break; elseif gtd_new >= 0 bracket = [t_prev t]; bracketFval = [f_prev f_new]; bracketGval = [g_prev g_new]; break; end temp = t_prev; t_prev = t; minStep = t + 0.01*(t-temp); maxStep = t*10; if LS == 3 if debug fprintf('Extending Braket\n'); end t = maxStep; elseif LS ==4 if debug fprintf('Cubic Extrapolation\n'); end t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep); else t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot); end f_prev = f_new; g_prev = g_new; gtd_prev = gtd_new; if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; end if LSiter == maxLS bracket = [0 t]; bracketFval = [f f_new]; bracketGval = [g g_new]; end %% Zoom Phase % We now either have a point satisfying the criteria, or a bracket % surrounding a point satisfying the criteria % Refine the bracket until we find a point satisfying the criteria insufProgress = 0; Tpos = 2; LOposRemoved = 0; while ~done && LSiter < maxLS % Find High and Low Points in bracket [f_LO LOpos] = min(bracketFval); HIpos = -LOpos + 3; % Compute new trial value if LS == 3 || ~isLegal(bracketFval) || ~isLegal(bracketGval) if debug fprintf('Bisecting\n'); end t = mean(bracket); elseif LS == 4 if debug fprintf('Grad-Cubic Interpolation\n'); end t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot); else % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nonTpos = -Tpos+3; if LOposRemoved == 0 oldLOval = bracket(nonTpos); oldLOFval = bracketFval(nonTpos); oldLOGval = bracketGval(:,nonTpos); end t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot); end % Test that we are making sufficient progress if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1 if debug fprintf('Interpolation close to boundary'); end if insufProgress || t>=max(bracket) || t <= min(bracket) if debug fprintf(', Evaluating at 0.1 away from boundary\n'); end if abs(t-max(bracket)) < abs(t-min(bracket)) t = max(bracket)-0.1*(max(bracket)-min(bracket)); else t = min(bracket)+0.1*(max(bracket)-min(bracket)); end insufProgress = 0; else if debug fprintf('\n'); end insufProgress = 1; end else insufProgress = 0; end % Evaluate new point if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; if f_new > f + c1*t*gtd || f_new >= f_LO % Armijo condition not satisfied or not lower than lowest % point bracket(HIpos) = t; bracketFval(HIpos) = f_new; bracketGval(:,HIpos) = g_new; Tpos = HIpos; else if abs(gtd_new) <= - c2*gtd % Wolfe conditions satisfied done = 1; elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0 % Old HI becomes new LO bracket(HIpos) = bracket(LOpos); bracketFval(HIpos) = bracketFval(LOpos); bracketGval(:,HIpos) = bracketGval(:,LOpos); if LS == 5 if debug fprintf('LO Pos is being removed!\n'); end LOposRemoved = 1; oldLOval = bracket(LOpos); oldLOFval = bracketFval(LOpos); oldLOGval = bracketGval(:,LOpos); end end % New point becomes new LO bracket(LOpos) = t; bracketFval(LOpos) = f_new; bracketGval(:,LOpos) = g_new; Tpos = LOpos; end if ~done && abs((bracket(1)-bracket(2))*gtd_new) < tolX if debug fprintf('Line Search can not make further progress\n'); end break; end end %% if LSiter == maxLS if debug fprintf('Line Search Exceeded Maximum Line Search Iterations\n'); end end [f_LO LOpos] = min(bracketFval); t = bracket(LOpos); f_new = bracketFval(LOpos); g_new = bracketGval(:,LOpos); % Evaluate Hessian at new point if nargout == 5 && funEvals > 1 && saveHessianComp [f_new,g_new,H] = funObj(x + t*d,varargin{:}); funEvals = funEvals + 1; end end %% function [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot); alpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep); alpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep); if alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1) if debug fprintf('Cubic Extrapolation\n'); end t = alpha_c; else if debug fprintf('Secant Extrapolation\n'); end t = alpha_s; end end %% function [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot); % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nonTpos = -Tpos+3; gtdT = bracketGval(:,Tpos)'*d; gtdNonT = bracketGval(:,nonTpos)'*d; oldLOgtd = oldLOGval'*d; if bracketFval(Tpos) > oldLOFval alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot); if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval) if debug fprintf('Cubic Interpolation\n'); end t = alpha_c; else if debug fprintf('Mixed Quad/Cubic Interpolation\n'); end t = (alpha_q + alpha_c)/2; end elseif gtdT'*oldLOgtd < 0 alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) sqrt(-1) gtdT],doPlot); if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos)) if debug fprintf('Cubic Interpolation\n'); end t = alpha_c; else if debug fprintf('Quad Interpolation\n'); end t = alpha_s; end elseif abs(gtdT) <= abs(oldLOgtd) alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],... doPlot,min(bracket),max(bracket)); alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],... doPlot,min(bracket),max(bracket)); if alpha_c > min(bracket) && alpha_c < max(bracket) if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos)) if debug fprintf('Bounded Cubic Extrapolation\n'); end t = alpha_c; else if debug fprintf('Bounded Secant Extrapolation\n'); end t = alpha_s; end else if debug fprintf('Bounded Secant Extrapolation\n'); end t = alpha_s; end if bracket(Tpos) > oldLOval t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t); else t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t); end else t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); end end
github
lijunzh/fd_elastic-master
minFunc_processInputOptions.m
.m
fd_elastic-master/src/PQN/minFunc/minFunc_processInputOptions.m
3,704
utf_8
b1c1b56fb4cf20e8a7b44b359a27a792
function [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,... corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,... HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,... DerivativeCheck,Damped,HvFunc,bbType,cycle,... HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ... minFunc_processInputOptions(o) % Constants SD = 0; CSD = 1; BB = 2; CG = 3; PCG = 4; LBFGS = 5; QNEWTON = 6; NEWTON0 = 7; NEWTON = 8; TENSOR = 9; verbose = 1; verboseI= 1; debug = 0; doPlot = 0; method = LBFGS; cgSolve = 0; o = toUpper(o); if isfield(o,'DISPLAY') switch(upper(o.DISPLAY)) case 0 verbose = 0; verboseI = 0; case 'FINAL' verboseI = 0; case 'OFF' verbose = 0; verboseI = 0; case 'NONE' verbose = 0; verboseI = 0; case 'FULL' debug = 1; case 'EXCESSIVE' debug = 1; doPlot = 1; end end LS_init = 0; c2 = 0.9; LS = 4; Fref = 1; Damped = 0; HessianIter = 1; if isfield(o,'METHOD') m = upper(o.METHOD); switch(m) case 'TENSOR' method = TENSOR; case 'NEWTON' method = NEWTON; case 'MNEWTON' method = NEWTON; HessianIter = 5; case 'PNEWTON0' method = NEWTON0; cgSolve = 1; case 'NEWTON0' method = NEWTON0; case 'QNEWTON' method = QNEWTON; Damped = 1; case 'LBFGS' method = LBFGS; case 'BB' method = BB; LS = 2; Fref = 20; case 'PCG' method = PCG; c2 = 0.2; LS_init = 2; case 'SCG' method = CG; c2 = 0.2; LS_init = 4; case 'CG' method = CG; c2 = 0.2; LS_init = 2; case 'CSD' method = CSD; c2 = 0.2; Fref = 10; LS_init = 2; case 'SD' method = SD; LS_init = 2; end end maxFunEvals = getOpt(o,'MAXFUNEVALS',1000); maxIter = getOpt(o,'MAXITER',500); tolFun = getOpt(o,'TOLFUN',1e-5); tolX = getOpt(o,'TOLX',1e-9); corrections = getOpt(o,'CORR',100); c1 = getOpt(o,'C1',1e-4); c2 = getOpt(o,'C2',c2); LS_init = getOpt(o,'LS_INIT',LS_init); LS = getOpt(o,'LS',LS); cgSolve = getOpt(o,'CGSOLVE',cgSolve); qnUpdate = getOpt(o,'QNUPDATE',1); cgUpdate = getOpt(o,'CGUPDATE',2); initialHessType = getOpt(o,'INITIALHESSTYPE',1); HessianModify = getOpt(o,'HESSIANMODIFY',0); Fref = getOpt(o,'FREF',Fref); useComplex = getOpt(o,'USECOMPLEX',0); numDiff = getOpt(o,'NUMDIFF',0); LS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1); DerivativeCheck = getOpt(o,'DERIVATIVECHECK',0); Damped = getOpt(o,'DAMPED',Damped); HvFunc = getOpt(o,'HVFUNC',[]); bbType = getOpt(o,'BBTYPE',0); cycle = getOpt(o,'CYCLE',3); HessianIter = getOpt(o,'HESSIANITER',HessianIter); outputFcn = getOpt(o,'OUTPUTFCN',[]); useMex = getOpt(o,'USEMEX',1); useNegCurv = getOpt(o,'USENEGCURV',1); precFunc = getOpt(o,'PRECFUNC',[]); end function [v] = getOpt(options,opt,default) if isfield(options,opt) if ~isempty(getfield(options,opt)) v = getfield(options,opt); else v = default; end else v = default; end end function [o] = toUpper(o) if ~isempty(o) fn = fieldnames(o); for i = 1:length(fn) o = setfield(o,upper(fn{i}),getfield(o,fn{i})); end end end
github
EdwardDixon/facenet-master
detect_face_v1.m
.m
facenet-master/tmp/detect_face_v1.m
7,954
utf_8
678c2105b8d536f8bbe08d3363b69642
% MIT License % % Copyright (c) 2016 Kaipeng Zhang % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, including without limitation the rights % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell % copies of the Software, and to permit persons to whom the Software is % furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER % LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, % OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE % SOFTWARE. function [total_boxes, points] = detect_face_v1(img,minsize,PNet,RNet,ONet,threshold,fastresize,factor) %im: input image %minsize: minimum of faces' size %pnet, rnet, onet: caffemodel %threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold %fastresize: resize img from last scale (using in high-resolution images) if fastresize==true factor_count=0; total_boxes=[]; points=[]; h=size(img,1); w=size(img,2); minl=min([w h]); img=single(img); if fastresize im_data=(single(img)-127.5)*0.0078125; end m=12/minsize; minl=minl*m; %creat scale pyramid scales=[]; while (minl>=12) scales=[scales m*factor^(factor_count)]; minl=minl*factor; factor_count=factor_count+1; end %first stage for j = 1:size(scales,2) scale=scales(j); hs=ceil(h*scale); ws=ceil(w*scale); if fastresize im_data=imResample(im_data,[hs ws],'bilinear'); else im_data=(imResample(img,[hs ws],'bilinear')-127.5)*0.0078125; end PNet.blobs('data').reshape([hs ws 3 1]); out=PNet.forward({im_data}); boxes=generateBoundingBox(out{2}(:,:,2),out{1},scale,threshold(1)); %inter-scale nms pick=nms(boxes,0.5,'Union'); boxes=boxes(pick,:); if ~isempty(boxes) total_boxes=[total_boxes;boxes]; end end numbox=size(total_boxes,1); if ~isempty(total_boxes) pick=nms(total_boxes,0.7,'Union'); total_boxes=total_boxes(pick,:); regw=total_boxes(:,3)-total_boxes(:,1); regh=total_boxes(:,4)-total_boxes(:,2); total_boxes=[total_boxes(:,1)+total_boxes(:,6).*regw total_boxes(:,2)+total_boxes(:,7).*regh total_boxes(:,3)+total_boxes(:,8).*regw total_boxes(:,4)+total_boxes(:,9).*regh total_boxes(:,5)]; total_boxes=rerec(total_boxes); total_boxes(:,1:4)=fix(total_boxes(:,1:4)); [dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h); end numbox=size(total_boxes,1); if numbox>0 %second stage tempimg=zeros(24,24,3,numbox); for k=1:numbox tmp=zeros(tmph(k),tmpw(k),3); tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:); if size(tmp,1)>0 && size(tmp,2)>0 || size(tmp,1)==0 && size(tmp,2)==0 tempimg(:,:,:,k)=imResample(tmp,[24 24],'bilinear'); else total_boxes = []; return; end; end tempimg=(tempimg-127.5)*0.0078125; RNet.blobs('data').reshape([24 24 3 numbox]); out=RNet.forward({tempimg}); score=squeeze(out{2}(2,:)); pass=find(score>threshold(2)); total_boxes=[total_boxes(pass,1:4) score(pass)']; mv=out{1}(:,pass); if size(total_boxes,1)>0 pick=nms(total_boxes,0.7,'Union'); total_boxes=total_boxes(pick,:); total_boxes=bbreg(total_boxes,mv(:,pick)'); total_boxes=rerec(total_boxes); end numbox=size(total_boxes,1); if numbox>0 %third stage total_boxes=fix(total_boxes); [dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h); tempimg=zeros(48,48,3,numbox); for k=1:numbox tmp=zeros(tmph(k),tmpw(k),3); tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:); if size(tmp,1)>0 && size(tmp,2)>0 || size(tmp,1)==0 && size(tmp,2)==0 tempimg(:,:,:,k)=imResample(tmp,[48 48],'bilinear'); else total_boxes = []; return; end; end tempimg=(tempimg-127.5)*0.0078125; ONet.blobs('data').reshape([48 48 3 numbox]); out=ONet.forward({tempimg}); score=squeeze(out{3}(2,:)); points=out{2}; pass=find(score>threshold(3)); points=points(:,pass); total_boxes=[total_boxes(pass,1:4) score(pass)']; mv=out{1}(:,pass); w=total_boxes(:,3)-total_boxes(:,1)+1; h=total_boxes(:,4)-total_boxes(:,2)+1; points(1:5,:)=repmat(w',[5 1]).*points(1:5,:)+repmat(total_boxes(:,1)',[5 1])-1; points(6:10,:)=repmat(h',[5 1]).*points(6:10,:)+repmat(total_boxes(:,2)',[5 1])-1; if size(total_boxes,1)>0 total_boxes=bbreg(total_boxes,mv(:,:)'); pick=nms(total_boxes,0.7,'Min'); total_boxes=total_boxes(pick,:); points=points(:,pick); end end end end function [boundingbox] = bbreg(boundingbox,reg) %calibrate bouding boxes if size(reg,2)==1 reg=reshape(reg,[size(reg,3) size(reg,4)])'; end w=[boundingbox(:,3)-boundingbox(:,1)]+1; h=[boundingbox(:,4)-boundingbox(:,2)]+1; boundingbox(:,1:4)=[boundingbox(:,1)+reg(:,1).*w boundingbox(:,2)+reg(:,2).*h boundingbox(:,3)+reg(:,3).*w boundingbox(:,4)+reg(:,4).*h]; end function [boundingbox reg] = generateBoundingBox(map,reg,scale,t) %use heatmap to generate bounding boxes stride=2; cellsize=12; boundingbox=[]; map=map'; dx1=reg(:,:,1)'; dy1=reg(:,:,2)'; dx2=reg(:,:,3)'; dy2=reg(:,:,4)'; [y x]=find(map>=t); a=find(map>=t); if size(y,1)==1 y=y';x=x';score=map(a)';dx1=dx1';dy1=dy1';dx2=dx2';dy2=dy2'; else score=map(a); end reg=[dx1(a) dy1(a) dx2(a) dy2(a)]; if isempty(reg) reg=reshape([],[0 3]); end boundingbox=[y x]; boundingbox=[fix((stride*(boundingbox-1)+1)/scale) fix((stride*(boundingbox-1)+cellsize-1+1)/scale) score reg]; end function pick = nms(boxes,threshold,type) %NMS if isempty(boxes) pick = []; return; end x1 = boxes(:,1); y1 = boxes(:,2); x2 = boxes(:,3); y2 = boxes(:,4); s = boxes(:,5); area = (x2-x1+1) .* (y2-y1+1); [vals, I] = sort(s); pick = s*0; counter = 1; while ~isempty(I) last = length(I); i = I(last); pick(counter) = i; counter = counter + 1; xx1 = max(x1(i), x1(I(1:last-1))); yy1 = max(y1(i), y1(I(1:last-1))); xx2 = min(x2(i), x2(I(1:last-1))); yy2 = min(y2(i), y2(I(1:last-1))); w = max(0.0, xx2-xx1+1); h = max(0.0, yy2-yy1+1); inter = w.*h; if strcmp(type,'Min') o = inter ./ min(area(i),area(I(1:last-1))); else o = inter ./ (area(i) + area(I(1:last-1)) - inter); end I = I(find(o<=threshold)); end pick = pick(1:(counter-1)); end function [dy edy dx edx y ey x ex tmpw tmph] = pad(total_boxes,w,h) %compute the padding coordinates (pad the bounding boxes to square) tmpw=total_boxes(:,3)-total_boxes(:,1)+1; tmph=total_boxes(:,4)-total_boxes(:,2)+1; numbox=size(total_boxes,1); dx=ones(numbox,1);dy=ones(numbox,1); edx=tmpw;edy=tmph; x=total_boxes(:,1);y=total_boxes(:,2); ex=total_boxes(:,3);ey=total_boxes(:,4); tmp=find(ex>w); edx(tmp)=-ex(tmp)+w+tmpw(tmp);ex(tmp)=w; tmp=find(ey>h); edy(tmp)=-ey(tmp)+h+tmph(tmp);ey(tmp)=h; tmp=find(x<1); dx(tmp)=2-x(tmp);x(tmp)=1; tmp=find(y<1); dy(tmp)=2-y(tmp);y(tmp)=1; end function [bboxA] = rerec(bboxA) %convert bboxA to square bboxB=bboxA(:,1:4); h=bboxA(:,4)-bboxA(:,2); w=bboxA(:,3)-bboxA(:,1); l=max([w h]')'; bboxA(:,1)=bboxA(:,1)+w.*0.5-l.*0.5; bboxA(:,2)=bboxA(:,2)+h.*0.5-l.*0.5; bboxA(:,3:4)=bboxA(:,1:2)+repmat(l,[1 2]); end
github
EdwardDixon/facenet-master
detect_face_v2.m
.m
facenet-master/tmp/detect_face_v2.m
9,016
utf_8
0c963a91d4e52c98604dd6ca7a99d837
% MIT License % % Copyright (c) 2016 Kaipeng Zhang % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, including without limitation the rights % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell % copies of the Software, and to permit persons to whom the Software is % furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER % LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, % OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE % SOFTWARE. function [total_boxes, points] = detect_face_v2(img,minsize,PNet,RNet,ONet,LNet,threshold,fastresize,factor) %im: input image %minsize: minimum of faces' size %pnet, rnet, onet: caffemodel %threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold %fastresize: resize img from last scale (using in high-resolution images) if fastresize==true factor_count=0; total_boxes=[]; points=[]; h=size(img,1); w=size(img,2); minl=min([w h]); img=single(img); if fastresize im_data=(single(img)-127.5)*0.0078125; end m=12/minsize; minl=minl*m; %creat scale pyramid scales=[]; while (minl>=12) scales=[scales m*factor^(factor_count)]; minl=minl*factor; factor_count=factor_count+1; end %first stage for j = 1:size(scales,2) scale=scales(j); hs=ceil(h*scale); ws=ceil(w*scale); if fastresize im_data=imResample(im_data,[hs ws],'bilinear'); else im_data=(imResample(img,[hs ws],'bilinear')-127.5)*0.0078125; end PNet.blobs('data').reshape([hs ws 3 1]); out=PNet.forward({im_data}); boxes=generateBoundingBox(out{2}(:,:,2),out{1},scale,threshold(1)); %inter-scale nms pick=nms(boxes,0.5,'Union'); boxes=boxes(pick,:); if ~isempty(boxes) total_boxes=[total_boxes;boxes]; end end numbox=size(total_boxes,1); if ~isempty(total_boxes) pick=nms(total_boxes,0.7,'Union'); total_boxes=total_boxes(pick,:); bbw=total_boxes(:,3)-total_boxes(:,1); bbh=total_boxes(:,4)-total_boxes(:,2); total_boxes=[total_boxes(:,1)+total_boxes(:,6).*bbw total_boxes(:,2)+total_boxes(:,7).*bbh total_boxes(:,3)+total_boxes(:,8).*bbw total_boxes(:,4)+total_boxes(:,9).*bbh total_boxes(:,5)]; total_boxes=rerec(total_boxes); total_boxes(:,1:4)=fix(total_boxes(:,1:4)); [dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h); end numbox=size(total_boxes,1); if numbox>0 %second stage tempimg=zeros(24,24,3,numbox); for k=1:numbox tmp=zeros(tmph(k),tmpw(k),3); tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:); tempimg(:,:,:,k)=imResample(tmp,[24 24],'bilinear'); end tempimg=(tempimg-127.5)*0.0078125; RNet.blobs('data').reshape([24 24 3 numbox]); out=RNet.forward({tempimg}); score=squeeze(out{2}(2,:)); pass=find(score>threshold(2)); total_boxes=[total_boxes(pass,1:4) score(pass)']; mv=out{1}(:,pass); if size(total_boxes,1)>0 pick=nms(total_boxes,0.7,'Union'); total_boxes=total_boxes(pick,:); total_boxes=bbreg(total_boxes,mv(:,pick)'); total_boxes=rerec(total_boxes); end numbox=size(total_boxes,1); if numbox>0 %third stage total_boxes=fix(total_boxes); [dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h); tempimg=zeros(48,48,3,numbox); for k=1:numbox tmp=zeros(tmph(k),tmpw(k),3); tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:); tempimg(:,:,:,k)=imResample(tmp,[48 48],'bilinear'); end tempimg=(tempimg-127.5)*0.0078125; ONet.blobs('data').reshape([48 48 3 numbox]); out=ONet.forward({tempimg}); score=squeeze(out{3}(2,:)); points=out{2}; pass=find(score>threshold(3)); points=points(:,pass); total_boxes=[total_boxes(pass,1:4) score(pass)']; mv=out{1}(:,pass); bbw=total_boxes(:,3)-total_boxes(:,1)+1; bbh=total_boxes(:,4)-total_boxes(:,2)+1; points(1:5,:)=repmat(bbw',[5 1]).*points(1:5,:)+repmat(total_boxes(:,1)',[5 1])-1; points(6:10,:)=repmat(bbh',[5 1]).*points(6:10,:)+repmat(total_boxes(:,2)',[5 1])-1; if size(total_boxes,1)>0 total_boxes=bbreg(total_boxes,mv(:,:)'); pick=nms(total_boxes,0.7,'Min'); total_boxes=total_boxes(pick,:); points=points(:,pick); end end numbox=size(total_boxes,1); %extended stage if numbox>0 tempimg=zeros(24,24,15,numbox); patchw=max([total_boxes(:,3)-total_boxes(:,1)+1 total_boxes(:,4)-total_boxes(:,2)+1]'); patchw=fix(0.25*patchw); tmp=find(mod(patchw,2)==1); patchw(tmp)=patchw(tmp)+1; pointx=ones(numbox,5); pointy=ones(numbox,5); for k=1:5 tmp=[points(k,:);points(k+5,:)]; x=fix(tmp(1,:)-0.5*patchw); y=fix(tmp(2,:)-0.5*patchw); [dy edy dx edx y ey x ex tmpw tmph]=pad([x' y' x'+patchw' y'+patchw'],w,h); for j=1:numbox tmpim=zeros(tmpw(j),tmpw(j),3); tmpim(dy(j):edy(j),dx(j):edx(j),:)=img(y(j):ey(j),x(j):ex(j),:); tempimg(:,:,(k-1)*3+1:(k-1)*3+3,j)=imResample(tmpim,[24 24],'bilinear'); end end LNet.blobs('data').reshape([24 24 15 numbox]); tempimg=(tempimg-127.5)*0.0078125; out=LNet.forward({tempimg}); score=squeeze(out{3}(2,:)); for k=1:5 tmp=[points(k,:);points(k+5,:)]; %do not make a large movement temp=find(abs(out{k}(1,:)-0.5)>0.35); if ~isempty(temp) l=length(temp); out{k}(:,temp)=ones(2,l)*0.5; end temp=find(abs(out{k}(2,:)-0.5)>0.35); if ~isempty(temp) l=length(temp); out{k}(:,temp)=ones(2,l)*0.5; end pointx(:,k)=(tmp(1,:)-0.5*patchw+out{k}(1,:).*patchw)'; pointy(:,k)=(tmp(2,:)-0.5*patchw+out{k}(2,:).*patchw)'; end for j=1:numbox points(:,j)=[pointx(j,:)';pointy(j,:)']; end end end end function [boundingbox] = bbreg(boundingbox,reg) %calibrate bouding boxes if size(reg,2)==1 reg=reshape(reg,[size(reg,3) size(reg,4)])'; end w=[boundingbox(:,3)-boundingbox(:,1)]+1; h=[boundingbox(:,4)-boundingbox(:,2)]+1; boundingbox(:,1:4)=[boundingbox(:,1)+reg(:,1).*w boundingbox(:,2)+reg(:,2).*h boundingbox(:,3)+reg(:,3).*w boundingbox(:,4)+reg(:,4).*h]; end function [boundingbox reg] = generateBoundingBox(map,reg,scale,t) %use heatmap to generate bounding boxes stride=2; cellsize=12; boundingbox=[]; map=map'; dx1=reg(:,:,1)'; dy1=reg(:,:,2)'; dx2=reg(:,:,3)'; dy2=reg(:,:,4)'; [y x]=find(map>=t); a=find(map>=t); if size(y,1)==1 y=y';x=x';score=map(a)';dx1=dx1';dy1=dy1';dx2=dx2';dy2=dy2'; else score=map(a); end reg=[dx1(a) dy1(a) dx2(a) dy2(a)]; if isempty(reg) reg=reshape([],[0 3]); end boundingbox=[y x]; boundingbox=[fix((stride*(boundingbox-1)+1)/scale) fix((stride*(boundingbox-1)+cellsize-1+1)/scale) score reg]; end function pick = nms(boxes,threshold,type) %NMS if isempty(boxes) pick = []; return; end x1 = boxes(:,1); y1 = boxes(:,2); x2 = boxes(:,3); y2 = boxes(:,4); s = boxes(:,5); area = (x2-x1+1) .* (y2-y1+1); [vals, I] = sort(s); pick = s*0; counter = 1; while ~isempty(I) last = length(I); i = I(last); pick(counter) = i; counter = counter + 1; xx1 = max(x1(i), x1(I(1:last-1))); yy1 = max(y1(i), y1(I(1:last-1))); xx2 = min(x2(i), x2(I(1:last-1))); yy2 = min(y2(i), y2(I(1:last-1))); w = max(0.0, xx2-xx1+1); h = max(0.0, yy2-yy1+1); inter = w.*h; if strcmp(type,'Min') o = inter ./ min(area(i),area(I(1:last-1))); else o = inter ./ (area(i) + area(I(1:last-1)) - inter); end I = I(find(o<=threshold)); end pick = pick(1:(counter-1)); end function [dy edy dx edx y ey x ex tmpw tmph] = pad(total_boxes,w,h) %compute the padding coordinates (pad the bounding boxes to square) tmpw=total_boxes(:,3)-total_boxes(:,1)+1; tmph=total_boxes(:,4)-total_boxes(:,2)+1; numbox=size(total_boxes,1); dx=ones(numbox,1);dy=ones(numbox,1); edx=tmpw;edy=tmph; x=total_boxes(:,1);y=total_boxes(:,2); ex=total_boxes(:,3);ey=total_boxes(:,4); tmp=find(ex>w); edx(tmp)=-ex(tmp)+w+tmpw(tmp);ex(tmp)=w; tmp=find(ey>h); edy(tmp)=-ey(tmp)+h+tmph(tmp);ey(tmp)=h; tmp=find(x<1); dx(tmp)=2-x(tmp);x(tmp)=1; tmp=find(y<1); dy(tmp)=2-y(tmp);y(tmp)=1; end function [bboxA] = rerec(bboxA) %convert bboxA to square bboxB=bboxA(:,1:4); h=bboxA(:,4)-bboxA(:,2); w=bboxA(:,3)-bboxA(:,1); l=max([w h]')'; bboxA(:,1)=bboxA(:,1)+w.*0.5-l.*0.5; bboxA(:,2)=bboxA(:,2)+h.*0.5-l.*0.5; bboxA(:,3:4)=bboxA(:,1:2)+repmat(l,[1 2]); end
github
nikos-kekatos/SpaceEx-tutorials-master
plotting_template_bball.m
.m
SpaceEx-tutorials-master/Files/Plotting/MATLAB/examples/Bouncing_Ball/plotting_template_bball.m
811
utf_8
95ab77bfe873660cdd96c11ff9c9fab8
% ======================================================================== % This example illustrates the use of Matlab functions for plotting % flowpipes obtained with SpaceEx. There are two functions: % % USAGE: % % >> addpath('../../src/') % >> plotting_template_bball('bball_timed.gen') % % If you want to use the simple SpaceEx script `plot_2d_vertices.m`, run: % % >> plot_2d_vertices('bball_timed.gen') % % ======================================================================== function plotting_template_bball(filename) if nargin == 0 % choose file name error('Select a GEN file'); end [filename_mat,options] = gen_to_mat(filename); % generate the plots : what are good 'jumps' depends on the model options.jump=[2]; % plot one every two polygons plot_flowpipe(filename_mat, options); end
github
nikos-kekatos/SpaceEx-tutorials-master
plotting_template_pendulum.m
.m
SpaceEx-tutorials-master/Files/Plotting/MATLAB/examples/pendulum/plotting_template_pendulum.m
2,716
utf_8
b469a023b66b8639d8cdcaa56d881595
% ======================================================================== % INTRODUCTION: % % This example illustrates the use of Matlab functions for plotting % flowpipes obtained with SpaceEx. There are two functions: % % (i) `gen_to_mat.m` : save the plot as a .mat file. % % (ii) `plot_flowpipe.m` : plot the flowpipe as a sequence of polygons in % the same pair of axes. % % MOTIVATION: % % The motivation is that often the for large files, visualization takes a % lot of time, because SpaceEx produces a flowpipe with a lot of accuracy % (huge number of polytopes, maybe hundreds of thousands). But for % visualization this is not actually needed, and if we include them, the % default plotting in SpaceEx web interface is slow. % % For example, a plot of all polygons in there can take take 45min - 1hr % for the examples in the paper synlin. Here we propose to do a sampling % of the polygons, which reduces the time to just a couple of minutes. % % The difficulty that we have to overcome is that often there are segments % when the polygons advance more fast (usually at the beginning), and % another places (usually at the end), when these accumulate. hence, it is % best to sample non-uniformly from different portions, based for instance % in the min-max of the x or y coordinate. % % NOTES: % % - Usually for large models, saving gen to mat is the most time consuming % part. % - The conversion .gen -> .mat needs to be done only once. % % TESTS: % % Testing the pendulum model (assuming that there is not MAT file):: % % >> example_plotting % The total number of lines in the GEN file is 163197. % % The total number of polytopes is 9262.0000. % The total elapsed time is 3.4814 seconds. % % % ans = % % pend.mat % % The total number of polytopes is 9262. % % The total elapsed time is 0.5294 seconds. % % If we run it for the second time, it runs faster:: % % >> close all; clear all; example_plotting % The total number of polytopes is 9262. % % The total elapsed time is 0.6148 seconds. % ======================================================================== function plotting_template_pendulum(filename) if nargin == 0 % choose file name error('Select a GEN file'); end % if it doesn't exist, generate .mat file containing the flowpipe filename_mat = strrep(filename, '.gen', '.mat'); if exist(filename_mat, 'file') == 2 % file exists else gen_to_mat(filename) end % generate the plots : what are good 'jumps' depends on the model options.verbose = 1; options.jump = [1 5 40 200 500 1000 2000 2500 3000 3500 5000]; %options.jump = [1 20]; options.color = 'k'; plot_flowpipe(filename_mat, options); end
github
nikos-kekatos/SpaceEx-tutorials-master
plot_flowpipe.m
.m
SpaceEx-tutorials-master/Files/Plotting/MATLAB/src/plot_flowpipe.m
4,462
utf_8
dc6dfc2df1f0aadd10e9543fa0596d96
function plot_flowpipe(fname, options) % PLOT_FLOWPIPE Approximate plot of a large sequence of polygons by % sampling. % % INPUT: % % "fname" - gen file name if it is in the same folder of this script, % or the full path otherwise. % % "options" - see the code. % % EXAMPLES: % % Export the gen data to a mat file: % >> gen_to_mat(...) % % Plot the resulting MAT file, with the standard options: % >> plot_flowpipe(fname, []); % % See also: gen_to_mat % ========================================================================= tic if nargin == 0 error('Filename not specified.'); end if nargin == 1 options.verbose = 1; options.jump = 1; options.color = 'b'; % blue end got_gen = false; got_mat = false; if ~isempty(strfind(fname, '.gen')) got_gen = true; elseif ~isempty(strfind(fname, '.mat')) got_mat = true; else error('Input file type not recognised, try with .gen or .mat') end if got_mat data = load(fname); fp = data.polygons_list; num_polygons = size(fp, 1); else error('Got gen file, but it is recommended to use mat files. Try using `gen_to_mat.m`') end if options.verbose fprintf('The total number of polytopes is %i. \r\n', num_polygons); end if ~isfield(options, 'save') options.save = 1; end % call the plotting function plot_sampling(fname, data, fp, num_polygons, options); end % -- end of plot_flowpipe function [varargout] = plot_sampling(fname, data, fp, num_polygons, options) % PLOT_SAMPLING Plot a sequence of polygons by sampling the given flowpipe. % % INPUT: % % "fname" - gen file name if it is in the same folder of this script, % or the full path otherwise. % % "options" - see the code. % % OUTPUT: % % "varargout" - variable number of arguments: name of the figure that % was generated; handle of the figure h1 (not used). % % ALGORITHM: % % The key parameter is options.jump, and it is interpreted in the following % way: % - if `jump` is a scalar, as in `options.jump = c`, then only multiples % of this value are plotted. % - if `jump` is a vector, as in `options.jump = [c1 c2 c3]`, then a % non-uniform separation is specified. Lengths different than 3 are % acceptable. % % Non-uniform separations are interpreted as follows. If there are N % polytopes, then roughly the first third floor(N/3) are plotted with % sparsity c1, the second third with c2, and the other piece with c3. % here, options. % % NOTES: % % The idea is to do this only once, and then for plotting go directly the .mat file and plot_flowpipe_mat. % The contents of the file "fname", which must be a two-column list of vertices separated by empty lines: % x11 y11 % x12 y12 % ... % x1n1 y1n1 % % x21 y21 % x22 y22 % ... % x2n2 y2n2 % % ... % % Each sequence of vertices defines a polygon. When an empty line is % encountered, a new polygon is started. % % EXAMPLES: % % Export the gen data to a mat file: % >> gen_to_mat(...) % % Plot the resulting MAT file, with the standard options: % >> plot_fp_mat(fname, []); % % TODO: % % - Add option field to export with custom file name or format. % ========================================================================= figure; chunks = length(options.jump); if chunks == 1 for i = 1:num_polygons if mod(i, options.jump) == 0 try if options.draw h1=patch(fp{i}.x, fp{i}.y, options.color); drawnow; else h1=patch(fp{i}.x, fp{i}.y, options.color); end catch warning('problem with "data" size. Extra check is needed.') end end end else size_chunks = floor(num_polygons/chunks); % we may miss at most one polygon for k = 1:chunks-1 ind_min = (k-1)*size_chunks + 1; ind_max = k*size_chunks; for i = ind_min:ind_max if mod(i, options.jump(k)) == 0 try patch(fp{i}.x, fp{i}.y, options.color); end end end end end fprintf('The total elapsed time is %.4f seconds. \r\n',toc) varargout = {}; if options.save filename_png = strrep(fname, '.mat', '.png'); saveas(gcf, filename_png) varargout{length(varargout)+1} = filename_png; end %varargout{length(varargout)+1} = h1; end % -- end of plot_sampling
github
ALandauer/qDIC-master
areaMapping_2D.m
.m
qDIC-master/areaMapping_2D.m
3,277
utf_8
20e26769dd3d161a11287ddad4a11366
function I = areaMapping_2D(varargin) % I = areaMapping(I0,m,u0) symmetrically warps undeformed % and deformed 2-D images by the displacement field from previous iteration % using trilinear interpolation. % % INPUTS % ------------------------------------------------------------------------- % I0: cell containing the undeformed, I0{1}, and deformed, I0{2} images % m: meshgrid of the displacement field % u0: displacement field vector defined at every meshgrid point with % spacing dm. Format: cell array, each containing a 2D matrix % (components in x,y,z) % u0{1} = displacement in x-direction % u0{2} = displacement in y-direction % u0{3} = magnitude % % OUTPUTS % ------------------------------------------------------------------------- % I: cell containing the symmetrically warped images of I0{1} and I0{2} % % NOTES % ------------------------------------------------------------------------- % if interp2FastMex and mirt2D-mexinterp are used to perform the interpolation % since they are faster and less memory demanding than MATLAB's interp3 % function. To run you need a compatible C compiler. Please see % (http://www.mathworks.com/support/compilers/R2014a/index.html) % % For more information please see section 2.2. % If used please cite: % Landauer, A.K., Patel, M., Henann, D.L. et al. Exp Mech (2018). % https://doi.org/10.1007/s11340-018-0377-4 interp_opt = 'spline'; inpaint_opt = 0; [I0,m0,u0] = parseInputs(varargin{:}); idx = cell(1,2); idx_u0 = cell(1,2); for i = 1:2 idx{i} = m0{i}(1):(m0{i}(end) - 1); % get index for valid indices of image idx_u0{i} = linspace(1,size(u0{1},i),length(idx{i})+1); % get index for displacement meshgrid idx_u0{i} = idx_u0{i}(1:length(idx{i})); u0{i} = double(u0{i}*0.5); end [m_u0{2}, m_u0{1}] = ndgrid(idx_u0{:}); [m{2}, m{1}] = ndgrid(idx{:}); u = cell(1,2); for i = 1:2 u{i} = interp2(u0{i},m_u0{1}, m_u0{2},interp_opt); %u{i} = mirt2D_mexinterp(u0{i}, m_u0{1}, m_u0{2}); %Uses cpp for %interpolation, minor %performance gain at %the cost of using a mex end %% Warp images (see eq. 8) mForward = cellfun(@(x,y) x + y, m, u, 'UniformOutput',false); mBackward = cellfun(@(x,y) x - y, m, u, 'UniformOutput',false); % interpolate images based on the deformation % I{1} = inpaint_nans(interp2(I0{1},mForward{1}, mForward{2},interp_opt),inpaint_opt); I{2} = inpaint_nans(interp2(I0{2},mBackward{1}, mBackward{2},interp_opt),inpaint_opt); % I{1} = (interp2(I0{1},mForward{1}, mForward{2},'cubic')); % I{2} = (interp2(I0{2},mBackward{1}, mBackward{2},'cubic')); %I{1} = mirt2D_mexinterp(I0{1}, mForward{1}, mForward{2}); %mex-interp fcns %I{2} = mirt2D_mexinterp(I0{2}, mBackward{1}, mBackward{2}); end %% ======================================================================== function varargout = parseInputs(varargin) I0 = varargin{1}; m = varargin{2}; u0 = varargin{3}; % convert I0 to double. Other datatypes will produce rounding errors I0 = cellfun(@double, I0, 'UniformOutput', false); varargout{ 1} = I0; varargout{end + 1} = m; varargout{end + 1} = u0; end
github
ALandauer/qDIC-master
flagOutliers_2D.m
.m
qDIC-master/flagOutliers_2D.m
3,702
utf_8
ddb4ec41cea2100a2ee76b4279621524
function [cc,normFluctValues] = flagOutliers_2D(u,cc,thr,epsilon) % u = flagOutliers(u,cc,thr,epsilon) removes outliers using the universal % outlier test based on % % J. Westerweel and F. Scarano. Universal outlier detection for PIV data. % Exp. Fluids, 39(6):1096{1100, August 2005. doi: 10.1007/s00348-005-0016-6 % % INPUTS % ------------------------------------------------------------------------- % u: cell containing the input displacement field. (u{1:3} = {u_x, u_y, % u_mag}) % cc: cross-correlation diagnostic struct % thr: theshold for passing residiual (default = 2) % epsilon: fluctuation level due to cross-correlation (default = 0.1) % % OUTPUTS % ------------------------------------------------------------------------- % cc: struct with flagged outliers in addition to diagnostics % normFluctValues: normalized fluctuation values based on the universal % outier test. % % NOTES % ------------------------------------------------------------------------- % % For more information please see section 2.2. % If used please cite: % Landauer, A.K., Patel, M., Henann, D.L. et al. Exp Mech (2018). % https://doi.org/10.1007/s11340-018-0377-4 % set default values if nargin < 3, epsilon = 0.1; end if nargin < 2, thr = 2; end if ~iscell(u), u = {u}; end medianU = cell(size(u)); normFluct = cell(size(u)); normFluctMag = zeros(size(u{1})); for i = 1:length(u) [medianU{i}, normFluct{i}] = funRemoveOutliers(u{i},epsilon); normFluctMag = normFluctMag + normFluct{i}.^2; end normFluctMag = sqrt(normFluctMag); outlierIdx = find(normFluctMag > thr); normFluctValues = normFluctMag(outlierIdx); %set up flags for outliers for i = 1:length(u) u_outlier{i} = zeros(1,size(normFluctMag,1)*size(normFluctMag,2)); u_outlier{i}(outlierIdx) = nan; cc.u_outlier{i} = reshape(u_outlier{i},size(cc.max)); end end %% ======================================================================== function [medianU, normFluct] = funRemoveOutliers(u,epsilon) inpaint_opt = 3; nSize = 2*[1 1]; skipIdx = ceil(prod(nSize)/2); padOption = 'symmetric'; u = inpaint_nans(double(u),inpaint_opt); medianU = medFilt2(u,nSize,padOption,skipIdx); fluct = u - medianU; medianRes = medFilt2(abs(fluct),nSize,padOption,skipIdx); normFluct = abs(fluct./(medianRes + epsilon)); end %% ======================================================================== function Vr = medFilt2(V0,nSize, padoption, skipIdx) % fast median filter for 2D data with extra options. if nargin < 4, skipIdx = 0; end if nargin < 3, padoption = 'symmetric'; end if nargin < 2, nSize = [2 2]; end nLength = prod(nSize); if mod(nLength,2) == 1, padSize = floor(nSize/2); elseif mod(nLength,2) == 0, padSize = [nSize(1)/2-1,nSize(2)/2]; end if strcmpi(padoption,'none') V = V0; else V = (padarray(V0,padSize(1)*[1,1],padoption,'pre')); V = (padarray(V,padSize(2)*[1,1],padoption,'post')); end S = size(V); nLength = prod(nSize)-sum(skipIdx>1); Vn = single(zeros(S(1)-(nSize(1)-1),S(2)-(nSize(2)-1),nLength)); % all the neighbor %% % build the neighborhood i = cell(1,nSize(1)); j = cell(1,nSize(2)); for m = 1:nSize(1), i{m} = m:(S(1)-(nSize(1)-m)); end for m = 1:nSize(2), j{m} = m:(S(2)-(nSize(2)-m)); end p = 1; for m = 1:nSize(1) for n = 1:nSize(2) if p ~= skipIdx || skipIdx == 0 Vn(:,:,p) = V(i{m},j{n}); end p = p + 1; end end if skipIdx ~= 0, Vn(:,:,skipIdx) = []; end % perform the processing Vn = sort(Vn,3); if mod(nLength,2) == 1 % if odd get the middle element Vr = Vn(:,:,ceil(nLength/2)); else % if even get the mean of the two middle elements Vr = mean(cat(3,Vn(:,:,nLength/2),Vn(:,:,nLength/2+1)),4); end end
github
ALandauer/qDIC-master
mirt2D_mexinterp.m
.m
qDIC-master/mirt2D_mexinterp.m
1,421
utf_8
dfd88fbc1da9b7dd1ebdebd7550e746e
%MIRT2D_MEXINTERP Fast 2D linear interpolation % % ZI = mirt2D_mexinterp(Z,XI,YI) interpolates 2D image Z at the points with coordinates XI,YI. % Z is assumed to be defined at regular spaced points 1:N, 1:M, where [M,N]=size(Z). % If XI,YI values are outside the image boundaries, put NaNs in ZI. % % The performance is similar to Matlab's ZI = INTERP2(Z,XI,YI,'linear',NaN). % If Z is a 3D matrix, then iteratively interpolates Z(:,:,1), Z(:,:,2),Z(:,:,3),.. etc. % This works faster than to interpolate each image independaently, such as % ZI(:,:,1) = INTERP2(Z(:,:,1),XI,YI); % ZI(:,:,2) = INTERP2(Z(:,:,2),XI,YI); % ZI(:,:,3) = INTERP2(Z(:,:,3),XI,YI); % % The speed gain is from the precomputation of coefficients for interpolation, which are the same for all images. % Interpolation of a set of images is useful, e.g. for image registration, when one has to interpolate image and its gradients % at the same positions. % % Andriy Myronenko, Feb 2008, email: [email protected], % homepage: http://www.bme.ogi.edu/~myron/ % The function below compiles the mirt2D_mexinterp.cpp file if you haven't done it yet. % It will be executed only once at the very first run. function Output_images = mirt2D_mexinterp(Input_images, XI,YI) pathtofile=which('mirt2D_mexinterp.cpp'); pathstr = fileparts(pathtofile); mex(pathtofile,'-outdir',pathstr); Output_images = mirt2D_mexinterp(Input_images, XI,YI); end
github
ALandauer/qDIC-master
funIDIC.m
.m
qDIC-master/funIDIC.m
6,999
utf_8
497a1c899f871561f66a8339663f6529
function [u, cc, dm, m, tSwitch] = funIDIC(varargin) % u = funIDIC(filename, sSize, sSizeMin, runMode) is the main function that performs % IDIC on a time series of images. % % INPUTS % ------------------------------------------------------------------------- % filename: string for the filename prefix for the images in % the current directory. % Input options: % --- If image is not within a cell) --- % 1) 'filename*.mat' or 'filename*' % % --- If image is within a cell that contains multichannels --- % 2) filename{1} = 'filename*.mat' or 'filename*' and % filename{2} = channel number containing images you want to % run IDIC on. % (if the channel is not provided, i.e. length(filename) = 1 % , then channel = 1 % % sSize: interrogation window (subset) size for the first iterations. % Must be, 32,64,96, or 128 pixels and a two column % array (one for each dimenision) or scalar (equal for all % dimensions). % sSizeMin: interrogation window (subset) minimum size. % % runMode: string that defines the method of running IDIC. Options: % cumulative (time0 -> time1, time0 -> time2, ...) % (Allowable inputs: 'c','cum','cumulative') % or % incremental (time0 -> time1, time1 -> time2, ...) % (Allowable inputs: 'i','inc','incremental') % or % hybrid % (Allowable inputs: 'h','hyb','hybrid') % % OUTPUTS % ------------------------------------------------------------------------- % u: displacement field vector defined at every meshgrid point with % spacing dm. Format: cell array, each containing a 3D matrix for each % time point % (components in x,y) % u{time}{1} = displacement in x-direction % u{time}{2} = displacement in y-direction % u{time}{3} = magnitude % cc: cross correlation metrics (warning, can be quite large) % dm: final meshgrid spacing (8 by default) % gridPoint: final meshgrid points % tSwitch: switching point chosen for hybrid scheme % % NOTES % ------------------------------------------------------------------------- % none % % For more information please see % Landauer, A.K., Patel, M., Henann, D.L. et al. Exp Mech (2018). % https://doi.org/10.1007/s11340-018-0377-4 %% ---- Opening & Reading the First Image into CPU Memory ---- [imgInfo, sSize0, sSizeMin, runMode, u_] = parseInputs(varargin{:}); if iscell(imgInfo) I{1} = imgInfo{1}; numImages = length(imgInfo); else I{1} = loadFile(imgInfo,1); numImages = length(imgInfo.filename); end %% ---- Opening and Reading Subsequent Images --- u = cell(numImages-1,1); cc = cell(numImages-1,1); for i = 2:numImages % Reads images starting on the second image tStart = tic; if iscell(imgInfo) I{2} = imgInfo{i}; fprintf('Current image: %i\n', i) else I{2} = loadFile(imgInfo,i); disp(['Current file: ' imgInfo.filename{i}]) end %Start DIC [u_,cc{i-1},dm,m,tSwitch(i-1)] = IDIC(I,sSize0,sSizeMin,u_); %Save iterations of DIC u{i-1}{1} = -u_{1}; u{i-1}{2} = -u_{2}; u{i-1}{3} = u_{3}; if strcmpi(runMode(1),'i') == 1 % Incremental mode I{1} = I{2}; % Update reference image u_ = num2cell(zeros(1,3)); % No predictor displacement in next time step end if strcmpi(runMode(1),'h') == 1 % If hybrid mode if tSwitch(end) == 1 disp('Updating reference image due to poor correlation.') disp('Rerunning DIC on the time step') if iscell(imgInfo) I{1} = imgInfo{i-1}; else I{1} = loadFile(imgInfo,i-1); %Update reference image end u_ = num2cell(zeros(1,3)); % No predictor displacement in next time step % Run DIC again on updated time step [u_,cc{i-1},dm,m,tSwitch(i-1)] = IDIC(I,sSize0,sSizeMin,u_); tSwitch(i-1) = tSwitch(i-1) + 1; %Save iterations of DIC u{i-1}{1} = -u_{1}; u{i-1}{2} = -u_{2}; u{i-1}{3} = u_{3}; end end end disp(['Elapsed Time for all iterations: ',num2str(toc(tStart))]); if strcmpi(runMode(1),'h') == 1 % Update displacement for to cumulative option = 'spline'; tStart = tic; disp('Update displacement for Hybrid mode'); [u] = FIDICinc2cum(u,tSwitch,dm,m,option); disp(['Elapsed Time for updating displacements: ',num2str(toc(tStart))]); end end %=================================================================== function I = loadFile(fileInfo,idx) I = load(fileInfo.filename{idx}); fieldName = fieldnames(I); I = getfield(I,fieldName{1}); if iscell(I) if numel(I), I = I{1}; else I = I{fileInfo.dataChannel}; end end end %================================================================ function varargout = parseInputs(varargin) % = parseInputs(filename, sSize, incORcum) if ~ischar(varargin{1}(1)) varargout{1} = varargin{1}; else % Parse filenames filename = varargin{1}; if iscell(filename) if length(filename) == 1 fileInfo.datachannel = 1; else fileInfo.datachannel = filename{2}; end filename = filename{1}; end [~,filename,~] = fileparts(filename); filename = dir([filename,'.mat']); fileInfo.filename = {filename.name}; if isempty(fileInfo), error('File name doesn''t exist'); end varargout{1} = fileInfo; end % Ensure dimensionality of the subset size sSize = varargin{2}; if numel(sSize) == 1 sSize = sSize*[1 1]; elseif numel(sSize) ~= 2 error('Subset size must be a scalar or a two column array'); end % Ensure range of subset size if min(sSize) < 32 || max(sSize > 128) error('Subset size must be within 32 and 128 pixels'); end % Ensure even subset size % if sum(mod(sSize,4)) > 0 % error('Subset size must be even'); % end if sum(mod(sSize,32)) ~= 0 error('Subset size must be 32, 64, 96, or 128 pixels in each dimension'); end % Minimum subset size sSizeMin = varargin{3}; % Check run method input runMode = varargin{4}; switch lower(runMode) case 'cum', runMode = 'cumulative'; case 'inc', runMode = 'incremental'; case 'c', runMode = 'cumulative'; case 'i', runMode = 'incremental'; case 'hybrid', runMode = 'hybrid'; case 'hyb', runMode = 'hybrid'; case 'h', runMode = 'hybrid'; case 'incremental', runMode = 'incremental'; case 'cumulative', runMode = 'incremental'; otherwise, error('Run method must be incremental or cumulative or hybrid'); end % Initial guess of displacement field = [0 0]; u0 = num2cell(zeros(1,2)); % Outputs varargout{end + 1} = sSize; varargout{end + 1} = sSizeMin; varargout{end + 1} = runMode; varargout{end + 1} = u0; end
github
ALandauer/qDIC-master
filterDisplacements_2D.m
.m
qDIC-master/filterDisplacements_2D.m
2,096
utf_8
4981dbc2aeac0aabf27a93a89aaf7701
function u = filterDisplacements_2D(u0,filterSize,z) % I = filterDisplacements(I0,filterSize,z) applies a low-pass convolution % filter to the displacement field to mitigate divergence based on % % F. F. J. Schrijer and F. Scarano. Effect of predictor corrector filtering % on the stability and spatial resolution of iterative PIV interrogation. % Exp. Fluids, 45(5):927{941, May 2008. doi: 10.1007/s00348-008-0511-7 % % INPUTS % ------------------------------------------------------------------------- % u0: displacement field vector defined at every meshgrid point with % spacing dm. Format: cell array, each containing a 3D matrix % (components in x,y,z) % u0{1} = displacement in x-direction % u0{2} = displacement in y-direction % u0{3} = magnitude % filterSize: size of the filter % z: filter strength % % OUTPUTS % ------------------------------------------------------------------------- % u: cell containing the filtered displacement field % % NOTES % ------------------------------------------------------------------------- % none % % For more information please see section 2.2. % If used please cite: % Landauer, A.K., Patel, M., Henann, D.L. et al. Exp Mech (2018). % https://doi.org/10.1007/s11340-018-0377-4 % Parse inputs and set defaults if nargin < 3, z = 0.0075; end if ~iscell(u0), u0 = {u0}; end u = cell(size(u0)); if z == 0 u = cellfun(@double, u0, 'UniformOutput',0); % no filter else rf = generateFilter(filterSize,z); % apply filter using convolution for i = 1:length(u0), u{i} = double(convn(u0{i}, rf,'same')); end end end %% ======================================================================== function rf = generateFilter(filterSize,z) % generates the filter convolution filter l = filterSize; [m{1}, m{2}] = ndgrid(-l(1)/2:l(1)/2,-l(2)/2:l(2)/2); m = cellfun(@abs, m, 'UniformOutput', 0); f1 = (l(1)/2)^z - (m{1}).^z; f2 = (l(2)/2)^z - (m{2}).^z; i{1} = (m{1} >= m{2});% ?? & m{1} >= m{3}); i{2} = (m{1} < m{2});% ?? & m{2} >= m{3}); rf0 = f1.*i{1}+f2.*i{2}; rf = rf0/sum(rf0(:)); end
github
ALandauer/qDIC-master
IDIC.m
.m
qDIC-master/IDIC.m
9,851
utf_8
b58b5a6a6108a0052bc17280a07fe1f1
function [u, cc, dm, mFinal, decorrFlag] = IDIC(varargin) % % INPUTS % ------------------------------------------------------------------------- % I0: cell containing the undeformed, I0{1}, and deformed, I0{2} images % sSize: interrogation window (subset) size % sSizeMin: interrogation window (subset) minimum size % u0: pre-estimated displacement field (typically zeros) % % OUTPUTS % ------------------------------------------------------------------------- % u: displacement field vector defined at every meshgrid point with % spacing dm. Format: cell array, each containing a 3D matrix % (components in x,y) % u{1} = displacement in x-direction % u{2} = displacement in y-direction % u{3} = magnitude % cc: peak values of the cross-correlation for each interrogation % dm: meshgrid spacing (8 by default) % m_final: final meshgrid % decorr_flag: flag indicating that decorrelation is occuring % % NOTES % ------------------------------------------------------------------------- % To run you may need a compatible C compiler. Please see % (http://www.mathworks.com/support/compilers/R2014a/index.html) % % If used please cite: % Landauer, A.K., Patel, M., Henann, D.L. et al. Exp Mech (2018). % https://doi.org/10.1007/s11340-018-0377-4 % PRESET CONSTANTS maxIterations = 9; % maximum number of iterations dm = 8; % desired output mesh spacing norm_xcc = 'n'; %switch to 'u' for un-normalized xcc - faster but less accurate convergenceCrit = [0.15, 0.25, 0.075]; % convergence criteria ccThreshold = 1e-4; % bad cross-correlation threshold (un-normalized) %[not used in norm version] sizeThresh = 196; %Threshold for maximum size of bad correlation regions percentThresh = 25; %Threshold for max % of total measurement pts failing q-factor testing stDevThresh = 0.15; %Threshold for max st. dev. of the fitted gaussian to the second peak cc = cell(1); cc{1} = struct('A',[],'max',[],'maxIdx',[],'qfactors',[],'q_thresh',[],... 'qfactors_accept',[]); [I0, sSize, sSizeMin, sSpacing, padSize, DICPadSize, u] = parseInputs(varargin{:}); % START ITERATING i = 2; converged01 = 0; SSE = []; I = I0; t0 = tic; while ~converged01 && i - 1 < maxIterations ti = tic; % Check for convergence [converged01, SSE(i-1) , sSize(i,:), sSpacing(i,:)] = ... checkConvergenceSSD_2D(I,SSE,sSize,sSizeMin,sSpacing,convergenceCrit); if ~converged01 finalSize = sSize(i,:); [I, m] = parseImages(I,sSize(i,:),sSpacing(i,:)); %warp images with displacement guess if a cumulative step if i == 2 %only on the first iteration if numel(u{1}) == 1 %on the first image the disp guess is zero u{1} = zeros(length(m{1}),length(m{2})); u{2} = zeros(length(m{1}),length(m{2})); end u{1} = inpaint_nans(u{1}); %inpaint nans from last time's edge pts u{2} = inpaint_nans(u{2}); I = areaMapping_2D(I,m,u); %otherwise map the images w/ the initial guess [I, m] = parseImages(I,sSize(i,:),sSpacing(i,:)); % u{1} = 0; %reset disp to zero % u{2} = 0; end % run cross-correlation to get an estimate of the displacements [du, cc{i-1}] = DIC(I,sSize,sSpacing(i,:),DICPadSize,ccThreshold,norm_xcc); % add the displacements from previous iteration to current [u, ~, cc{i-1}, mFinal] = addDisplacements_2D(u,du,cc{i-1},cc{i-1},m,dm); % filter the displacements using a predictor filter u = filterDisplacements_2D(u,sSize(i,:)/dm); cc{i-1} = flagOutliers_2D(u,cc{i-1},1.25,0.1); % remove questionable displacement points [u,cc{i-1}.alpha_mask,cc{i-1}.nan_mask,cc{i-1}.edge_pts] = replaceOutliers_2D(u,cc{i-1}); % mesh and pad images based on new subset size and spacing [I, m] = parseImages(I0,sSize(i,:),sSpacing(i,:)); % map areas based on displacment field I = areaMapping_2D(I,m,u); if sum(isnan(u{1}(:)+isnan(u{2}(:)))) > 0 || sum(isnan(I{1}(:)+isnan(I{2}(:)))) > 0 disp('nan found') end disp(['Elapsed time (iteration ',num2str(i-1),'): ',num2str(toc(ti))]); i = i + 1; end end %prepare outputs decorrFlag = decorrelationCheck(cc,sizeThresh,percentThresh,stDevThresh); u{1} = cc{end}.edge_pts.*u{1}; u{2} = cc{end}.edge_pts.*u{2}; [u,cc,mFinal] = parseOutputs(u,cc,finalSize,padSize,mFinal); disp(['Convergence at iteration ',num2str(i-1)]); disp(['Total time: ',num2str(toc(t0))]); end %% ======================================================================== function varargout = parseImages(varargin) % pads images and creates meshgrid I{1} = single(varargin{1}{1}); I{2} = single(varargin{1}{2}); sSize = varargin{2}; sSpacing = varargin{3}; prePad = sSize/2; postPad = sSize/2; sizeI = size(I{1}); I{1} = padarray(I{1},prePad,'replicate','pre'); I{1} = padarray(I{1},postPad,'replicate','post'); I{2} = padarray(I{2},prePad,'replicate','pre'); I{2} = padarray(I{2},postPad,'replicate','post'); idx = cell(1,2); for i = 1:2, idx{i} = (1:sSpacing(i):(sizeI(i) + 1)) + sSize(i)/2; end % [m{1},m{2}] = meshgrid(idx{:}); varargout{ 1} = I; varargout{end+1} = idx; end %% ======================================================================== function varargout = parseInputs(varargin) % parses inputs and pads images so that there is an divisable meshgrid number. I0{1} = single(varargin{1}{1}); I0{2} = single(varargin{1}{2}); % I0{1} = permute(I0{1},[2 1]); % I0{2} = permute(I0{2},[2 1]); sSize = varargin{2}; sSize = [sSize(2), sSize(1)]; sSizeMin = varargin{3}; sSpacing = sSize/2; u0_ = varargin{4}; u0 = u0_(1:2); DICPadSize = sSpacing/2; sizeI0 = size(I0{1}); sizeI = ceil(sizeI0./sSpacing).*sSpacing; prePad = ceil((sizeI - sizeI0)/2); postPad = floor((sizeI - sizeI0)/2); I{1} = padarray(I0{1},prePad,'replicate','pre'); I{1} = padarray(I{1},postPad,'replicate','post'); I{2} = padarray(I0{2},prePad,'replicate','pre'); I{2} = padarray(I{2},postPad,'replicate','post'); varargout{ 1} = I; varargout{end+1} = sSize; varargout{end+1} = sSizeMin; varargout{end+1} = sSpacing; varargout{end+1} = [prePad; postPad]; varargout{end+1} = DICPadSize; varargout{end+1} = u0; end function [u,cc,m] = parseOutputs(u,cc,sSize,padSize,m_) % parses outputs and unpads the displacment field and cc. for i = 1:2 m{i} = m_{i}-padSize(1,i)-sSize(i)/2; end u{3} = sqrt(u{1}.^2 + u{2}.^2); %remove the memory-intesive and generally unneeded parts of the cc struct for jj = 1:length(cc) cc{jj}.A = []; cc{jj}.max = []; end end function decorrFlag = decorrelationCheck(cc,sizeThresh,percentThresh,stDevThresh) %This function takes in a cc structure and checks the q-factor maps for %decorrelation indications. %Initilize decorrFlag = 0; if nargin < 4 stDevThresh = 0.13; elseif nargin < 3 percentThresh = 15; elseif nargin < 2 sizeThresh = 121; end trim_size = ceil((cc{end}.sSize/2)./cc{end}.sSpacing)+1; %get the q-factors maps, exclude boundary pixels since they are %reliably poor. qf1 = cc{end}.qfactors_accept{1}(1+trim_size(1):end-trim_size(1),... 1+trim_size(2):end-trim_size(2)); qf2 = cc{end}.qfactors_accept{2}(1+trim_size(1):end-trim_size(1),... 1+trim_size(2):end-trim_size(2)); %compute the % of bad correlation pts num_pts = numel(qf1)+numel(qf2); num_fail = sum(isnan(qf1(:))+isnan(qf2(:))); if num_fail/num_pts*100 >= percentThresh decorrFlag = 1; disp('percent decorr') end %binarize the qf maps qf1_bin = isnan(qf1); qf2_bin = isnan(qf2); %get connect regions qf1_connectivity = bwconncomp(qf1_bin,8); qf2_connectivity = bwconncomp(qf2_bin,8); %find the number of px in each connect region qf1_numPixels = cellfun(@numel,qf1_connectivity.PixelIdxList); qf2_numPixels = cellfun(@numel,qf2_connectivity.PixelIdxList); %find the largest area of the connected regions [~,idx1] = max(qf1_numPixels); [~,idx2] = max(qf2_numPixels); %compute the region properties for the largest region, normalized by is %eccentricity (since its harder to correctly predict far away from known data %with inpaint nans) if ~isempty(idx1) S1 = regionprops(qf1_connectivity,'Eccentricity','Area'); ecc(1) = S1(idx1).Eccentricity; area(1) = S1(idx1).Area; if ecc(1)+0.25 > 1 knockdown(1) = 1; else knockdown(1) = ecc(1)+0.25; end norm_area(1) = area(1)/knockdown(1); else norm_area(1) = 0; end if ~isempty(idx2) S2 = regionprops(qf2_connectivity,'Eccentricity','Area'); ecc(2) = S2(idx2).Eccentricity; area(2) = S2(idx2).Area; if ecc(2)+0.1 > 1 knockdown(2) = 1; else knockdown(2) = ecc(2)+0.1; end norm_area(2) = area(2)*knockdown(2); else norm_area(2) = 0; end % qf_holeSize(idx1) = 0; % [qf_second,idx2] = max([qf1_numPixels,qf2_numPixels]); % norm_area if max(norm_area(:)) > sizeThresh decorrFlag = 1; disp('size decorr') end % do the st dev based thresholding complete_qfactors = cc{end}.qfactors(3:4,:); for ii = 1:size(complete_qfactors,1) x = sort(complete_qfactors(ii,:)); %do the parameter estimation options = statset('MaxIter',2000, 'MaxFunEvals',4000); % options.FunValCheck = 'off'; % disp('Parameters estimated for single peak Gaussian') paramEsts = mle(x,'options',options);%,'optimfun','fmincon' paramEsts = [0.5,paramEsts(1),paramEsts(1),paramEsts(2),... paramEsts(2)]; qfactor_fit_means(ii) = paramEsts(3); qfactor_fit_stds(ii) = paramEsts(5); end if cc{end}.sSize(1) == 16 stDevThresh = stDevThresh + 0.01; elseif cc{end}.sSize(1) == 64 stDevThresh = stDevThresh - 0.01; end if qfactor_fit_stds(1) >= stDevThresh || qfactor_fit_stds(2) >= stDevThresh decorrFlag = 1; disp('stdev decorr') end end
github
ALandauer/qDIC-master
DIC.m
.m
qDIC-master/DIC.m
15,845
utf_8
c948e88b9c8f469ad981db5b79bd89cb
function [u, cc] = DIC(varargin) % [du, cc] = DIC(I,sSize,sSpacing,ccThreshold) estimates % displacements between two images through digital image % correlation. % % INPUTS % ------------------------------------------------------------------------- % I: cell containing the undeformed, I{1}, and deformed, I{2} 2-D images % sSize: interrogation window (subset) size % sSpacing: interrogation window (subset) spacing. Determines window % overlap factor % DICPadSize: padding arround the current window % ccThreshold: threshold values that define a bad cross-correlation % norm_xcc: flag for normalize cross-correlation cross-correlation % % OUTPUTS % ------------------------------------------------------------------------- % u: cell containing the displacement field (u{1:2} = {u_x, u_y}) % cc: cc space maps, q-factors, and diagnostic struct % % NOTES % ------------------------------------------------------------------------- % all functions are self contained % % If used please cite: % Landauer, A.K., Patel, M., Henann, D.L. et al. Exp Mech (2018). % https://doi.org/10.1007/s11340-018-0377-4 % Parse inputs and create meshgrid [I,m,mSize,sSize,sSizeFull,sSpacing,MTF,M,ccThreshold,norm_xcc] = ... parseInputs(varargin{:}); % Initialize variables mSize_ = prod(mSize); u12 = zeros(mSize_,2); % cc = zeros(mSize_,1); cc = struct('A',[],'max',[],'sSpacing',[],'sSize',[],'maxIdx',[],'qfactors',[],'q_thresh',[],... 'qfactors_accept',[]); %inject small noise to avoid flat subsets noise = rand(size(I{1}))/10000; I{1} = I{1}+noise; I{2} = I{2}+noise; A = cell(1,mSize_); if strcmp(norm_xcc,'n')||strcmp(norm_xcc,'norm')||strcmp(norm_xcc,'normalized') parfor k = 1:mSize_ %----------------------------------------------------------------------- % grab the moving subset from the images subst = I{1}(m{1}(k,:),m{2}(k,:)); B = I{2}(m{1}(k,:),m{2}(k,:)); % size_sbst = size(subst); % multiply by the modular transfer function to alter frequency content subst = MTF.*subst; B = MTF.*B; % run cross-correlation A_ = normxcorr2(subst,B); A_small = A_(size(B,1)/2:size(B,1)+size(B,1)/2-1, ... size(B,2)/2:size(B,2)+size(B,2)/2-1); A{k} = imrotate(A_small,180); % find maximum index of the cross-correlaiton [max_val(k), maxIdx{k}] = max(A{k}(:)); % compute pixel resolution displacements [u1, u2] = ind2sub(sSize,maxIdx{k}); % gather the 3x3 pixel neighborhood around the peak try xCorrPeak = reshape(A{k}(u1 + (-1:1), u2 + (-1:1)),9,1); % least squares fitting of the peak to calculate sub-pixel disp du12 = lsqPolyFit2(xCorrPeak, M{1}, M{2}); u12(k,:) = [u1 u2] + du12' - (sSize/2); %---------------------------------------------------------- catch u12(k,:) = nan; end end else parfor k = 1:mSize_ %----------------------------------------------------------------------- % grab the moving subset from the images subst = I{1}(m{1}(k,:),m{2}(k,:)); B = I{2}(m{1}(k,:),m{2}(k,:)); % size_sbst = size(subst); % multiply by the modular transfer function to alter frequency content subst = MTF.*subst; B = MTF.*B; A{k} = xCorr2(subst,B,sSize); %Custom fft-based correllation - fast, %but not normalized. Be careful using this %if there is a visable intensity gradient in %an image % find maximum index of the cross-correlaiton [max_val(k), maxIdx{k}] = max(A{k}(:)); % compute pixel resolution displacements [u1, u2] = ind2sub(sSize,maxIdx{k}); % gather the 3x3 pixel neighborhood around the peak try xCorrPeak = reshape(A{k}(u1 + (-1:1), u2 + (-1:1)),9,1); % least squares fitting of the peak to find sub-pixel disp du12 = lsqPolyFit2(xCorrPeak, M{1}, M{2}); u12(k,:) = [u1 u2] + du12' - (sSize/2) - 1; %-------------------------------------------------------------- catch u12(k,:) = nan; end end end cc.A = A; cc.maxIdx = maxIdx; cc.max = max_val; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Reshape displacements and discover bad correlation points if size(sSpacing,1) == 1 spacingChange = 1; elseif sSpacing(end,1) == sSpacing(end-1,1) spacingChange = 0; else spacingChange = 1; end cc.max = reshape(double(cc.max),mSize); cc.sSpacing = sSpacing(end,:); cc.sSize = sSize; [cc, ccMask_] = ... removeBadCorrelations(I,cc,ccThreshold,norm_xcc,spacingChange,mSize,mSize_); for ii = 1:2 ccMask{ii} = reshape(double(ccMask_(ii,:)),mSize); end u{1} = reshape(double(u12(:,2)),mSize);%.*ccMask{1}.*ccMask{2}; u{2} = reshape(double(u12(:,1)),mSize);%.*ccMask{1}.*ccMask{2}; end %% ======================================================================== function varargout = parseInputs(varargin) % Parse inputs and create meshgrid I{1} = varargin{1}{1}; I{2} = varargin{1}{2}; sSizeFull = varargin{2}; sSpacing = varargin{3}; padSize = varargin{4}; ccThreshold = varargin{5}; norm_xcc = varargin{6}; % cc = varargin{7}; % pad images with zeros so that we don't grab any subset outside of the image % domain. This would produce an error I{1} = padarray(I{1},padSize,'replicate','both'); I{2} = padarray(I{2},padSize,'replicate','both'); sizeV = size(I{1}); sSize = sSizeFull(end,:); % Initialize Mesh Variables idx = cell(1,2); for i = 1:2 idx{i} = (1+padSize(i)) : sSpacing(i) : (sizeV(i)-sSize(i)-padSize(i)+1); end [m{1},m{2}] = ndgrid(idx{:}); % sSize = [sSize(2) sSize(1)]; mSize = size(m{1}); mSize_ = prod(mSize); m_ = cell(1,2); for k = 1:2 m_{k} = zeros([mSize_,sSize(k)],'uint16'); repmat_ = repmat((1:sSize(k))-1,mSize_,1); m_{k} = bsxfun(@plus, repmat_,m{k}(:)); end % Initialize quadratic least squares fitting coefficients [mx, my] = meshgrid((-1:1),(-1:1)); m = [mx(:), my(:)]; M{1} = zeros(size(m,1),6); for i = 1:size(m,1) x = m(i,1); y = m(i,2); M{1}(i,:) = [1,x,y,x^2,x*y,y^2]; end M{2} = M{1}'*M{1}; % Generate Moduluar transfer function (see eq. 3) [~,~,MTF] = generateMTF(sSize); %% Parse outputs varargout{ 1} = I; varargout{end+1} = m_; varargout{end+1} = mSize; varargout{end+1} = sSize; varargout{end+1} = sSizeFull; varargout{end+1} = sSpacing; varargout{end+1} = MTF; varargout{end+1} = M; varargout{end+1} = ccThreshold; varargout{end+1} = norm_xcc; % varargout{end+1} = cc; end %% ======================================================================== function A = xCorr2(A,B,sSize) % performs fft based cross correlation of A and B (see equation 2) A = fftn(A,sSize); B = fftn(B,sSize); B = conj(B); A = A.*B; A = ifftn(A); A = real(A); A = fftshift(A); end %% ======================================================================== function duvw = lsqPolyFit2(b, M, trMM) % LeastSqPoly performs a polynomial fit in the least squares sense % Solves M*x = b, % trMM = transpose(M)*M % trMb = transpose(M)*b % % If you need to generate the coefficients then uncomment the following % [mx, my, mz] = meshgrid(-1:1,-1:1,-1:1); % m = [mx(:), my(:), mz(:)]; % % for i = 1:size(m,1) % x = m(i,1); y = m(i,2); z = m(i,3); % M1(i,:) = [1,x,y,z,x^2,x*y,x*z,y^2,y*z,z^2]; %3D case % 1 2 3 4 5 6 7 8 9 10 % M1(i,:) = [1,x,y,x^2,x*y,y^2]; %2D Case % 1 2 3 5 6 8 % 1 2 3 4 5 6 % end % % trMM1 = M'*M; % b = log(b); trMb = sum(bsxfun(@times, M, b)); x = trMM\trMb'; %solve for unknown coefficients A = [x(5), 2*x(4); 2*x(6), x(5)]; duvw = (A\(-x([2 3]))); end %% ======================================================================== function varargout = generateMTF(sSize) % MTF functions taken from % J. Nogueira, A Lecuona, P. A. Rodriguez, J. A. Alfaro, and A. Acosta. % Limits on the resolution of correlation PIV iterative methods. Practical % implementation and design of weighting functions. Exp. Fluids, % 39(2):314{321, July 2005. doi: 10.1007/s00348-005-1017-1 %% equation 4 if prod(single(sSize == 16)) || prod(single(sSize == 32)) || prod(single(sSize == 64)) sSize = sSize(1); x = cell(1,2); [x{1}, x{2}] = meshgrid(1:sSize,1:sSize); nu{1} = 1; for i = 1:2 x{i} = x{i} - sSize/2 - 0.5; x{i} = abs(x{i}/sSize); nu{1} = nu{1}.*(3*(4*x{i}.^2-4*x{i}+1)); end %% equation 5 [x{1}, x{2}] = meshgrid(1:sSize,1:sSize); for i = 1:2, x{i} = x{i} - sSize/2 - 0.5; end r = abs(sqrt(x{1}.^2 + x{2}.^2)/sSize); nu{2} = zeros(size(r)); nu{2}(r < 0.5) = 24/pi*(4*r(r < 0.5).^2-4*r(r < 0.5)+1); %% equation 6 [x{1}, x{2}] = meshgrid(1:sSize,1:sSize); nu{3} = 1; for i = 1:2 x{i} = x{i} - sSize/2 - 0.5; x{i} = (x{i}/sSize); nu{3} = nu{3}.*(12*abs(x{i}).^2 - 12*abs(x{i}) + 3 + ... 0.15*cos(4*pi*x{i}) + 0.20*cos(6*pi*x{i}) + ... 0.10*cos(8*pi*x{i}) + 0.05*cos(10*pi*x{i})); end nu{3}(nu{3} < 0) = 0; else nu{1} = ones(sSize(1),sSize(2)); nu{2} = nu{1}; nu{3} = nu{1}; %==== Based on the usage and the paper this comes from %nu should remain 3-dims even for the 2D case end nu = cellfun(@(x) x/sum(x(:)), nu, 'UniformOutput',0); nu = cellfun(@sqrt, nu, 'UniformOutput',0); varargout = nu; end %% ======================================================================== function [cc, ccMask] = ... removeBadCorrelations(I,cc,ccThreshold,norm_xcc,sizeChange,mSize,mSize_) % flag bad correlation points, using q-factor analysis if strcmp(norm_xcc,'n')||strcmp(norm_xcc,'norm')||strcmp(norm_xcc,'normalized') ccMask = ones(size(cc.max)); for k = 1:mSize_ cc_min = cc.A{k};% - min(cc.A{k}(:));, not needed since this is nxcc phi = sort(cc_min(:)); P_img = imregionalmax(cc_min); peaks = unique(cc_min(P_img)); %some can be non-unique, %but this means its a bad xcc %compute several quality metrics, as given in "Xue Z, Particle Image % Velocimetry Correlation Signal-to-noise Metrics, Particle Image % Pattern Mutual Information and Measurement uncertainty Quantification. % MS Thesis, Virginia Tech, 2014. try ppr = peaks(end)/peaks(end-1); %peak to second peak ratio (NOT USED) %min value = 1 (worst-case) catch ppr = 100; %a large value, since one peak only is good end prmsr = ((peaks(end)^2)/(rms(phi(phi<phi(end)/2))^2)); %peak to RMS ratio (NOT USED) %min value = 2; (worst case) %peak to corr. energy ratio pce = ((peaks(end)^2)/(1/numel(phi)*(sum(abs(phi(:).^2))))); %min value -> 1 (worst case) [cc_hist,~] = histcounts(cc_min,30); entropy = 0; for i = 1:30 p(i) = cc_hist(i)/sum(cc_hist); if p(i) == 0 entropy = entropy+p(i); else entropy = entropy+p(i)*log(1/p(i)); end end ppe = 1/entropy; %peak to cc (information) entropy %min value -> 0 (worst case) qfactors_(:,k) = [ppr,prmsr,pce,ppe]; end for k = 1:size(qfactors_,1) qf_ = (qfactors_(k,:)-min(qfactors_(k,:))); cc.qfactors(k,:) = qf_/max(qf_); end if sizeChange == 1 %recompute threshold, only use pce & ppe since these give the best %results emprically. stdev_prefact = 1.00; for ii = 1:2 [qf_para{ii},single_distro] = bimodal_gauss_fit(cc.qfactors(2+ii,:)); if single_distro == 0%(qf_para{ii}(2) + 2*qf_para{ii}(4)) < (qf_para{ii}(3) - 2*qf_para{ii}(5)) cc.q_thresh{ii} = qf_para{ii}(3) - stdev_prefact*qf_para{ii}(5); elseif single_distro == 1 cc.q_thresh{ii} = qf_para{ii}(3) - stdev_prefact*qf_para{ii}(5); else cc.q_thresh{ii} = qf_para{ii}(3) - stdev_prefact*qf_para{ii}(5); end end q_trim = [cc.q_thresh{1};cc.q_thresh{2}]; else q_trim = [cc.q_thresh{1};cc.q_thresh{2}]; end %NaN the qfactor values that are below the threshold temp = bsxfun(@le,cc.qfactors(3:4,:),q_trim); qfactors_accept = cc.qfactors(3:4,:); qfactors_accept(temp) = NaN; for ii = 1:2 cc.qfactors_accept{ii} = reshape(double(qfactors_accept(ii,:)),mSize); % cc.U95_accept{ii} = reshape(double(U95_accept(ii,:)),mSize); end ccMask = ones(size(qfactors_accept)) + ... zeros(size(qfactors_accept)).*qfactors_accept; else minOS = 1; for i = 1:2 zeroIdx = I{i} == 0; threshold = mean2(I{i}(~zeroIdx)); I_ = I{i}.*(I{i} < threshold); minOS = minOS*sum(I_(:))/sum(~zeroIdx(:)); end cc.max = cc.max - minOS; cc.max = cc.max/(max(I{1}(:))*max(I{2}(:))); ccMask = double(cc.max >= ccThreshold); CC = bwconncomp(~ccMask); if length(CC.PixelIdxList) > 0 [~,idx] = max(cellfun(@numel,CC.PixelIdxList)); ccMask(CC.PixelIdxList{idx}) = inf; end ccMask(cc.max == 0) = nan; ccMask(~isfinite(ccMask)) = 0; cc = cc.max.*ccMask; end end %% ======================================================================== function [paramEsts,single_distro] = bimodal_gauss_fit(x) %This function takes a dataset and fits a bimodal Gaussian distro to it. x = sort(x); %set function for bimodal Gaussian pdf_normmixture = @(x,p,mu1,mu2,sigma1,sigma2) ... p*normpdf(x,mu1,sigma1) + (1-p)*normpdf(x,mu2,sigma2); pdf_single = @(x,mu1,sigma1) ... normpdf(x,mu1,sigma1); %starting params, biased mixture toward "good" values, %centered at quartiles, equal std dev. pStart = 0.25; muStart = quantile(x,[.10 .75]); sigmaStart(1) = sqrt(var(x(1:round(length(x)/5)))); %- 0.25*diff(quantile(x,[0.01 0.25])).^2); sigmaStart(2) = sqrt(var(x(round(length(x)/10):round(3*length(x)/4)))); %... - 0.25*diff(quantile(x,[0.25 0.75])).^2);%1:round(length(x)/2) start = [pStart muStart sigmaStart]; %set lower and upper bounds lb = [0 -inf -inf 0.00001 0.00001]; ub = [1 inf inf inf inf]; %do the parameter estimation options = statset('MaxIter',2000, 'MaxFunEvals',4000); % options.FunValCheck = 'off'; try single_distro = 0; paramEsts = mle(x, 'pdf',pdf_normmixture, 'start',start, ... 'lower',lb, 'upper',ub, 'options',options);%,'optimfun','fmincon' if paramEsts(2)-paramEsts(4) >= paramEsts(3)+paramEsts(5) || ... paramEsts(2)+paramEsts(4) <= paramEsts(3)-paramEsts(5) single_distro = 1; % disp('Parameters estimated for single peak Gaussian') paramEsts = mle(x,'options',options);%,'optimfun','fmincon' paramEsts = [0.5,paramEsts(1),paramEsts(1),paramEsts(2),... paramEsts(2)]; end catch single_distro = 1; % disp('Parameters estimated for single peak Gaussian') paramEsts = mle(x,'options',options);%,'optimfun','fmincon' paramEsts = [0.5,paramEsts(1),paramEsts(1),paramEsts(2),... paramEsts(2)]; end % % %show the result % % figure % % % [~, bins] = % % histogram(x,100); % % % bins = -2.5:.5:7.5; % % % h = bar(bins,histc(x,bins)/(length(x)*0.5),'histc'); % % % histogram(x,100) % % % h.FaceColor = [0.9 0.9 0.9]; % % xgrid = linspace(1.1*min(x),1.1*max(x),200); % % pdfgrid = pdf_normmixture(xgrid,paramEsts(1),paramEsts(2),paramEsts(3),... % % paramEsts(4),paramEsts(5)); % % hold on % % plot((paramEsts(3) - 2*paramEsts(5)),pdfgrid,'or') % % plot((paramEsts(2) + 2*paramEsts(4)),pdfgrid,'*r') % % plot(xgrid,pdfgrid,'-b') % % hold off % % xlabel('x') % % ylabel('Probability Density') end
github
SwanLab/Swan-master
test3d_micro_cube.m
.m
Swan-master/test3d_micro_cube.m
203,004
utf_8
f411079847d1d58632af11c52d4c4fc2
%================================================================== % General Data File % Title: Default_title % Units: SI % Dimensions: 3D % Type of problem: Plane_Stress % Type of Phisics: ELASTIC % Micro/Macro: MICRO % %================================================================== clc close all clear %% Data Data_prb = { 'Default_title'; 'SI'; '3D'; 'Plane_Stress'; 'ELASTIC'; 'MICRO'; }; %% Coordinates % Node X Y Z gidcoord = [ 1 1 1 0 2 1 0.9 0 3 0.9 1 0 4 1 1 0.1 5 0.9 0.9 0 6 1 0.9 0.1 7 0.9 1 0.1 8 0.9 0.9 0.1 9 1 0.8 0 10 0.8 1 0 11 1 1 0.2 12 0.8 1 0.1 13 1 0.9 0.2 14 1 0.8 0.1 15 0.9 0.8 0 16 0.9 1 0.2 17 0.8 0.9 0 18 0.9 0.9 0.2 19 0.9 0.8 0.1 20 0.8 0.9 0.1 21 0.8 1 0.2 22 1 0.8 0.2 23 0.8 0.8 0 24 1 1 0.3 25 0.9 0.8 0.2 26 0.7 1 0 27 1 0.7 0 28 0.8 0.8 0.1 29 0.8 0.9 0.2 30 0.9 0.7 0 31 1 0.9 0.3 32 0.9 1 0.3 33 0.7 1 0.1 34 1 0.7 0.1 35 0.7 0.9 0 36 0.9 0.7 0.1 37 0.9 0.9 0.3 38 0.7 0.9 0.1 39 0.8 0.8 0.2 40 0.8 0.7 0 41 1 0.8 0.3 42 0.8 1 0.3 43 0.7 1 0.2 44 1 0.7 0.2 45 0.7 0.8 0 46 0.8 0.7 0.1 47 0.9 0.7 0.2 48 0.9 0.8 0.3 49 0.8 0.9 0.3 50 0.7 0.8 0.1 51 0.7 0.9 0.2 52 1 1 0.4 53 0.6 1 0 54 1 0.6 0 55 0.8 0.7 0.2 56 0.9 0.6 0 57 1 0.6 0.1 58 1 0.9 0.4 59 0.6 1 0.1 60 0.8 0.8 0.3 61 0.9 1 0.4 62 0.6 0.9 0 63 0.7 0.8 0.2 64 0.9 0.6 0.1 65 0.7 0.7 0 66 1 0.7 0.3 67 0.9 0.9 0.4 68 0.7 1 0.3 69 0.6 0.9 0.1 70 0.7 0.7 0.1 71 0.9 0.7 0.3 72 0.7 0.9 0.3 73 1 0.8 0.4 74 0.8 1 0.4 75 1 0.6 0.2 76 0.6 1 0.2 77 0.6 0.8 0 78 0.8 0.6 0 79 0.9 0.6 0.2 80 0.8 0.6 0.1 81 0.9 0.8 0.4 82 0.6 0.8 0.1 83 0.8 0.9 0.4 84 0.6 0.9 0.2 85 0.8 0.7 0.3 86 0.7 0.7 0.2 87 0.7 0.8 0.3 88 0.6 0.8 0.2 89 0.8 0.8 0.4 90 0.8 0.6 0.2 91 0.6 0.7 0 92 0.7 0.6 0 93 1 0.5 0 94 0.6 1 0.3 95 0.5 1 0 96 1 1 0.5 97 1 0.6 0.3 98 1 0.7 0.4 99 0.7 1 0.4 100 0.6 0.7 0.1 101 0.9 0.6 0.3 102 0.9 0.7 0.4 103 0.7 0.6 0.1 104 1 0.9 0.5 105 0.9 1 0.5 106 1 0.5 0.1 107 0.5 1 0.1 108 0.6 0.9 0.3 109 0.5 0.9 0 110 0.9 0.5 0 111 0.7 0.9 0.4 112 0.7 0.7 0.3 113 0.9 0.9 0.5 114 0.9 0.5 0.1 115 0.5 0.9 0.1 116 0.8 0.7 0.4 117 1 0.8 0.5 118 0.6 0.7 0.2 119 0.8 1 0.5 120 0.5 1 0.2 121 0.7 0.6 0.2 122 1 0.5 0.2 123 0.6 0.8 0.3 124 0.8 0.5 0 125 0.5 0.8 0 126 0.8 0.6 0.3 127 0.7 0.8 0.4 128 0.9 0.8 0.5 129 0.8 0.9 0.5 130 0.9 0.5 0.2 131 0.5 0.9 0.2 132 0.8 0.5 0.1 133 0.5 0.8 0.1 134 0.6 0.6 0 135 0.6 1 0.4 136 1 0.6 0.4 137 0.6 0.6 0.1 138 0.8 0.8 0.5 139 0.9 0.6 0.4 140 0.5 0.8 0.2 141 0.6 0.9 0.4 142 0.8 0.5 0.2 143 0.6 0.7 0.3 144 0.7 0.7 0.4 145 0.5 1 0.3 146 0.7 1 0.5 147 1 0.5 0.3 148 0.7 0.6 0.3 149 1 0.7 0.5 150 0.7 0.5 0 151 0.5 0.7 0 152 0.9 0.7 0.5 153 0.5 0.9 0.3 154 0.5 0.7 0.1 155 0.7 0.9 0.5 156 0.7 0.5 0.1 157 0.9 0.5 0.3 158 0.6 0.6 0.2 159 0.4 1 0 160 1 1 0.6 161 1 0.4 0 162 0.6 0.8 0.4 163 0.8 0.6 0.4 164 1 0.9 0.6 165 0.9 0.4 0 166 0.9 1 0.6 167 0.4 1 0.1 168 1 0.4 0.1 169 0.4 0.9 0 170 0.8 0.7 0.5 171 0.7 0.8 0.5 172 0.4 0.9 0.1 173 0.9 0.9 0.6 174 0.9 0.4 0.1 175 0.5 0.7 0.2 176 0.7 0.5 0.2 177 0.5 0.8 0.3 178 0.8 0.5 0.3 179 1 0.4 0.2 180 0.4 1 0.2 181 0.8 1 0.6 182 1 0.8 0.6 183 0.8 0.4 0 184 0.4 0.8 0 185 0.9 0.8 0.6 186 0.6 0.6 0.3 187 0.6 0.7 0.4 188 0.9 0.4 0.2 189 0.6 1 0.5 190 1 0.6 0.5 191 0.8 0.4 0.1 192 0.7 0.6 0.4 193 1 0.5 0.4 194 0.5 1 0.4 195 0.4 0.9 0.2 196 0.8 0.9 0.6 197 0.5 0.6 0 198 0.4 0.8 0.1 199 0.6 0.5 0 200 0.9 0.6 0.5 201 0.5 0.6 0.1 202 0.6 0.9 0.5 203 0.9 0.5 0.4 204 0.5 0.9 0.4 205 0.6 0.5 0.1 206 0.7 0.7 0.5 207 0.5 0.7 0.3 208 0.7 0.5 0.3 209 0.8 0.4 0.2 210 0.8 0.8 0.6 211 0.4 0.8 0.2 212 1 0.4 0.3 213 0.4 0.7 0 214 0.5 0.6 0.2 215 0.7 0.4 0 216 0.7 1 0.6 217 0.4 1 0.3 218 0.6 0.8 0.5 219 0.8 0.5 0.4 220 1 0.7 0.6 221 0.8 0.6 0.5 222 0.6 0.5 0.2 223 0.5 0.8 0.4 224 0.9 0.7 0.6 225 0.4 0.7 0.1 226 0.4 0.9 0.3 227 0.7 0.9 0.6 228 0.7 0.4 0.1 229 0.9 0.4 0.3 230 0.6 0.6 0.4 231 0.8 0.7 0.6 232 0.7 0.4 0.2 233 0.3 1 0 234 0.8 0.4 0.3 235 1 1 0.7 236 1 0.3 0 237 0.7 0.8 0.6 238 0.4 0.7 0.2 239 0.4 0.8 0.3 240 0.9 1 0.7 241 0.7 0.6 0.5 242 1 0.9 0.7 243 0.9 0.3 0 244 0.5 1 0.5 245 1 0.5 0.5 246 0.6 0.7 0.5 247 1 0.3 0.1 248 0.5 0.7 0.4 249 0.3 0.9 0 250 0.5 0.6 0.3 251 0.3 1 0.1 252 0.7 0.5 0.4 253 0.5 0.5 0 254 0.6 0.5 0.3 255 0.9 0.3 0.1 256 0.9 0.9 0.7 257 0.3 0.9 0.1 258 0.9 0.5 0.5 259 0.5 0.5 0.1 260 0.5 0.9 0.5 261 0.4 0.6 0 262 0.6 0.4 0 263 1 0.6 0.6 264 0.6 1 0.6 265 1 0.4 0.4 266 0.4 1 0.4 267 0.9 0.6 0.6 268 0.4 0.6 0.1 269 0.8 1 0.7 270 1 0.8 0.7 271 0.8 0.3 0 272 1 0.3 0.2 273 0.3 0.8 0 274 0.9 0.4 0.4 275 0.3 1 0.2 276 0.4 0.9 0.4 277 0.6 0.9 0.6 278 0.6 0.4 0.1 279 0.8 0.3 0.1 280 0.9 0.3 0.2 281 0.4 0.7 0.3 282 0.7 0.4 0.3 283 0.3 0.9 0.2 284 0.3 0.8 0.1 285 0.9 0.8 0.7 286 0.7 0.7 0.6 287 0.8 0.9 0.7 288 0.8 0.5 0.5 289 0.5 0.8 0.5 290 0.5 0.5 0.2 291 0.6 0.8 0.6 292 0.8 0.6 0.6 293 0.4 0.6 0.2 294 0.8 0.4 0.4 295 0.6 0.4 0.2 296 0.4 0.8 0.4 297 0.6 0.6 0.5 298 0.8 0.3 0.2 299 0.3 0.8 0.2 300 0.5 0.6 0.4 301 0.8 0.8 0.7 302 0.6 0.5 0.4 303 0.7 0.3 0 304 1 0.7 0.7 305 0.7 1 0.7 306 1 0.3 0.3 307 0.3 1 0.3 308 0.3 0.7 0 309 0.9 0.7 0.7 310 0.9 0.3 0.3 311 0.7 0.3 0.1 312 0.3 0.9 0.3 313 0.5 0.7 0.5 314 0.7 0.5 0.5 315 0.3 0.7 0.1 316 0.7 0.9 0.7 317 0.5 0.5 0.3 318 0.7 0.6 0.6 319 1 0.4 0.5 320 0.4 1 0.5 321 0.4 0.6 0.3 322 0.4 0.5 0 323 0.5 1 0.6 324 0.6 0.7 0.6 325 1 0.5 0.6 326 0.5 0.4 0 327 0.4 0.7 0.4 328 0.7 0.4 0.4 329 0.6 0.4 0.3 330 0.8 0.7 0.7 331 0.7 0.3 0.2 332 0.8 0.3 0.3 333 0.9 0.5 0.6 334 0.4 0.5 0.1 335 0.3 0.7 0.2 336 0.9 0.4 0.5 337 0.4 0.9 0.5 338 0.3 0.8 0.3 339 0.5 0.4 0.1 340 0.7 0.8 0.7 341 0.5 0.9 0.6 342 0.2 1 0 343 1 1 0.8 344 1 0.2 0 345 0.8 0.4 0.5 346 1 0.3 0.4 347 0.4 0.8 0.5 348 1 0.6 0.7 349 0.3 0.6 0 350 0.6 1 0.7 351 0.4 0.5 0.2 352 0.6 0.3 0 353 0.2 0.9 0 354 1 0.2 0.1 355 0.5 0.4 0.2 356 0.2 1 0.1 357 0.3 1 0.4 358 0.8 0.5 0.6 359 1 0.9 0.8 360 0.9 0.2 0 361 0.5 0.8 0.6 362 0.9 1 0.8 363 0.9 0.6 0.7 364 0.3 0.6 0.1 365 0.5 0.6 0.5 366 0.6 0.3 0.1 367 0.9 0.3 0.4 368 0.9 0.2 0.1 369 0.3 0.9 0.4 370 0.6 0.5 0.5 371 0.5 0.5 0.4 372 0.6 0.9 0.7 373 0.9 0.9 0.8 374 0.2 0.9 0.1 375 0.7 0.3 0.3 376 0.7 0.7 0.7 377 0.3 0.7 0.3 378 1 0.8 0.8 379 0.6 0.6 0.6 380 0.4 0.6 0.4 381 0.2 1 0.2 382 0.6 0.4 0.4 383 1 0.2 0.2 384 0.8 0.2 0 385 0.2 0.8 0 386 0.8 1 0.8 387 0.9 0.8 0.8 388 0.6 0.3 0.2 389 0.8 0.3 0.4 390 0.3 0.6 0.2 391 0.3 0.8 0.4 392 0.8 0.9 0.8 393 0.2 0.9 0.2 394 0.6 0.8 0.7 395 0.2 0.8 0.1 396 0.9 0.2 0.2 397 0.8 0.2 0.1 398 0.8 0.6 0.7 399 0.7 0.4 0.5 400 0.7 0.5 0.6 401 0.4 0.5 0.3 402 0.4 0.7 0.5 403 0.5 0.4 0.3 404 0.5 0.7 0.6 405 0.8 0.8 0.8 406 0.4 0.4 0 407 1 0.4 0.6 408 0.4 1 0.6 409 0.2 0.8 0.2 410 0.8 0.2 0.2 411 0.7 1 0.8 412 0.4 0.9 0.6 413 0.9 0.4 0.6 414 0.7 0.2 0 415 0.4 0.4 0.1 416 0.2 1 0.3 417 1 0.2 0.3 418 0.2 0.7 0 419 1 0.7 0.8 420 1 0.5 0.7 421 0.5 1 0.7 422 0.6 0.7 0.7 423 0.7 0.3 0.4 424 0.3 0.6 0.3 425 0.6 0.3 0.3 426 0.3 0.5 0 427 0.5 0.3 0 428 0.9 0.2 0.3 429 1 0.3 0.5 430 0.7 0.6 0.7 431 0.7 0.9 0.8 432 0.7 0.2 0.1 433 0.2 0.9 0.3 434 0.3 0.7 0.4 435 0.3 1 0.5 436 0.9 0.7 0.8 437 0.2 0.7 0.1 438 0.9 0.5 0.7 439 0.9 0.3 0.5 440 0.3 0.5 0.1 441 0.5 0.3 0.1 442 0.3 0.9 0.5 443 0.5 0.5 0.5 444 0.5 0.9 0.7 445 0.4 0.4 0.2 446 0.4 0.8 0.6 447 0.8 0.4 0.6 448 0.4 0.6 0.5 449 0.5 0.6 0.6 450 0.4 0.5 0.4 451 0.7 0.8 0.8 452 0.6 0.5 0.6 453 0.7 0.2 0.2 454 0.5 0.4 0.4 455 0.6 0.4 0.5 456 0.8 0.2 0.3 457 0.2 0.8 0.3 458 0.8 0.7 0.8 459 0.2 0.7 0.2 460 0.8 0.5 0.7 461 0.8 0.3 0.5 462 0.3 0.8 0.5 463 0.5 0.3 0.2 464 0.3 0.5 0.2 465 0.5 0.8 0.7 466 0.6 1 0.8 467 0.2 1 0.4 468 1 0.2 0.4 469 0.2 0.6 0 470 0.6 0.2 0 471 1 0.6 0.8 472 0.6 0.6 0.7 473 0.7 0.4 0.6 474 0.3 0.6 0.4 475 0.6 0.3 0.4 476 0.4 0.4 0.3 477 1 0.1 0 478 0.1 1 0 479 0.4 0.7 0.6 480 1 1 0.9 481 0.9 0.2 0.4 482 0.2 0.9 0.4 483 0.6 0.9 0.8 484 0.2 0.6 0.1 485 0.6 0.2 0.1 486 0.9 0.6 0.8 487 1 0.1 0.1 488 0.9 1 0.9 489 0.9 0.1 0 490 0.1 0.9 0 491 0.7 0.2 0.3 492 0.7 0.7 0.8 493 0.1 1 0.1 494 0.2 0.7 0.3 495 1 0.9 0.9 496 0.7 0.3 0.5 497 0.9 0.1 0.1 498 0.7 0.5 0.7 499 0.5 0.3 0.3 500 0.3 0.5 0.3 501 0.5 0.7 0.7 502 0.3 0.7 0.5 503 0.1 0.9 0.1 504 0.9 0.9 0.9 505 0.6 0.8 0.8 506 0.2 0.8 0.4 507 0.8 0.2 0.4 508 0.2 0.6 0.2 509 0.8 0.6 0.8 510 0.6 0.2 0.2 511 0.8 1 0.9 512 0.4 0.3 0 513 1 0.1 0.2 514 0.4 1 0.7 515 1 0.8 0.9 516 1 0.3 0.6 517 1 0.4 0.7 518 0.8 0.1 0 519 0.1 0.8 0 520 0.3 0.4 0 521 0.3 1 0.6 522 0.1 1 0.2 523 0.4 0.9 0.7 524 0.4 0.5 0.5 525 0.8 0.1 0.1 526 0.9 0.8 0.9 527 0.4 0.3 0.1 528 0.9 0.1 0.2 529 0.3 0.9 0.6 530 0.9 0.3 0.6 531 0.5 0.4 0.5 532 0.3 0.4 0.1 533 0.9 0.4 0.7 534 0.5 0.5 0.6 535 0.1 0.8 0.1 536 0.1 0.9 0.2 537 0.8 0.9 0.9 538 0.4 0.6 0.6 539 0.4 0.4 0.4 540 0.6 0.4 0.6 541 0.4 0.3 0.2 542 0.8 0.1 0.2 543 0.8 0.8 0.9 544 0.3 0.8 0.6 545 0.3 0.4 0.2 546 0.7 0.6 0.8 547 0.6 0.7 0.8 548 0.8 0.3 0.6 549 0.4 0.8 0.7 550 0.1 0.8 0.2 551 0.5 1 0.8 552 0.8 0.4 0.7 553 0.7 0.2 0.4 554 1 0.5 0.8 555 1 0.2 0.5 556 0.2 0.5 0 557 0.2 1 0.5 558 0.2 0.6 0.3 559 0.5 0.2 0 560 0.6 0.2 0.3 561 0.2 0.7 0.4 562 0.6 0.5 0.7 563 1 0.1 0.3 564 0.7 1 0.9 565 0.3 0.6 0.5 566 0.7 0.1 0 567 1 0.7 0.9 568 0.6 0.3 0.5 569 0.5 0.3 0.4 570 0.1 1 0.3 571 0.3 0.5 0.4 572 0.1 0.7 0 573 0.9 0.2 0.5 574 0.5 0.9 0.8 575 0.5 0.2 0.1 576 0.2 0.9 0.5 577 0.5 0.6 0.7 578 0.2 0.5 0.1 579 0.9 0.5 0.8 580 0.9 0.7 0.9 581 0.9 0.1 0.3 582 0.7 0.1 0.1 583 0.1 0.7 0.1 584 0.1 0.9 0.3 585 0.7 0.9 0.9 586 0.5 0.8 0.8 587 0.8 0.2 0.5 588 0.2 0.8 0.5 589 0.5 0.2 0.2 590 0.2 0.5 0.2 591 0.8 0.5 0.8 592 0.8 0.7 0.9 593 0.4 0.3 0.3 594 0.8 0.1 0.3 595 0.7 0.3 0.6 596 0.7 0.1 0.2 597 0.4 0.7 0.7 598 0.1 0.7 0.2 599 0.7 0.8 0.9 600 0.1 0.8 0.3 601 0.7 0.4 0.7 602 0.3 0.4 0.3 603 0.3 0.7 0.6 604 0.6 0.6 0.8 605 0.2 0.6 0.4 606 0.6 0.2 0.4 607 0.4 0.4 0.5 608 1 0.1 0.4 609 0.6 1 0.9 610 0.4 0.5 0.6 611 0.6 0.1 0 612 0.1 0.6 0 613 0.1 1 0.4 614 0.5 0.4 0.6 615 1 0.6 0.9 616 0.9 0.1 0.4 617 0.3 0.3 0 618 1 0.3 0.7 619 0.1 0.6 0.1 620 0.3 1 0.7 621 0.6 0.1 0.1 622 0.7 0.2 0.5 623 0.9 0.6 0.9 624 0.5 0.7 0.8 625 0.5 0.2 0.3 626 0.1 0.9 0.4 627 0.7 0.5 0.8 628 0.2 0.5 0.3 629 0.2 0.7 0.5 630 0.6 0.9 0.9 631 0.7 0.7 0.9 632 0.3 0.9 0.7 633 0.7 0.1 0.3 634 0.3 0.3 0.1 635 0.3 0.5 0.5 636 0.9 0.3 0.7 637 0.5 0.3 0.5 638 0.1 0.7 0.3 639 0.5 0.5 0.7 640 1 0.4 0.8 641 0 1 0 642 1 0.2 0.6 643 1 0 0 644 1 1 1 645 0.2 1 0.6 646 0.4 0.2 0 647 0.2 0.4 0 648 0.4 1 0.8 649 0.4 0.6 0.7 650 0.9 0.4 0.8 651 0.4 0.9 0.8 652 0.6 0.3 0.6 653 0.3 0.6 0.6 654 0.4 0.3 0.4 655 0.8 0.1 0.4 656 0.9 0.2 0.6 657 0.1 0.6 0.2 658 1 0 0.1 659 0.6 0.1 0.2 660 0 1 0.1 661 0.2 0.9 0.6 662 1 0.9 1 663 0.9 1 1 664 0.6 0.8 0.9 665 0 0.9 0 666 0.9 0 0 667 0.8 0.6 0.9 668 0.6 0.4 0.7 669 0.1 0.8 0.4 670 0.3 0.4 0.4 671 0.4 0.2 0.1 672 0.2 0.4 0.1 673 0.3 0.8 0.7 674 0.3 0.3 0.2 675 0.9 0 0.1 676 0.8 0.3 0.7 677 0.9 0.9 1 678 0 0.9 0.1 679 0.8 0.4 0.8 680 0.4 0.8 0.8 681 0 0.8 0 682 1 0.8 1 683 0.8 0 0 684 0 1 0.2 685 0.8 1 1 686 1 0 0.2 687 0.2 0.4 0.2 688 0.8 0.2 0.6 689 0.2 0.8 0.6 690 0.4 0.2 0.2 691 0 0.9 0.2 692 0.9 0 0.2 693 0.8 0 0.1 694 0 0.8 0.1 695 0.8 0.9 1 696 0.9 0.8 1 697 0.2 0.5 0.4 698 0.5 0.6 0.8 699 0.6 0.2 0.5 700 0.2 0.6 0.5 701 0.5 0.2 0.4 702 0.6 0.5 0.8 703 0.7 0.6 0.9 704 0.7 0.1 0.4 705 1 0.1 0.5 706 0.1 0.6 0.3 707 1 0.5 0.9 708 0.6 0.1 0.3 709 0.5 1 0.9 710 0.1 0.5 0 711 0.5 0.1 0 712 0.6 0.7 0.9 713 0.1 0.7 0.4 714 0.1 1 0.5 715 0.7 0.3 0.7 716 0.3 0.3 0.3 717 0.9 0.1 0.5 718 0.9 0.5 0.9 719 0.1 0.5 0.1 720 0.5 0.1 0.1 721 0.3 0.7 0.7 722 0.1 0.9 0.5 723 0.5 0.9 0.9 724 0 0.8 0.2 725 0.4 0.4 0.6 726 0.8 0 0.2 727 0.8 0.8 1 728 0.4 0.7 0.8 729 0.7 0.2 0.6 730 0 0.7 0 731 1 0 0.3 732 0 1 0.3 733 1 0.7 1 734 0.7 1 1 735 0.7 0 0 736 0.2 0.7 0.6 737 0.7 0.4 0.8 738 0.2 0.4 0.3 739 0.4 0.2 0.3 740 0.4 0.5 0.7 741 0.4 0.3 0.5 742 0.5 0.4 0.7 743 0.8 0.1 0.5 744 0 0.9 0.3 745 0.9 0 0.3 746 0.9 0.7 1 747 0.5 0.8 0.9 748 0.3 0.5 0.6 749 0.3 0.4 0.5 750 0.1 0.8 0.5 751 0.7 0 0.1 752 0.1 0.5 0.2 753 0.8 0.5 0.9 754 0.5 0.3 0.6 755 0 0.7 0.1 756 0.5 0.1 0.2 757 0.7 0.9 1 758 0.6 0.6 0.9 759 1 0.3 0.8 760 0.1 0.6 0.4 761 0.8 0 0.3 762 0.3 1 0.8 763 0.6 0.1 0.4 764 0.8 0.7 1 765 0.2 0.3 0 766 0 0.7 0.2 767 0.7 0 0.2 768 1 0.2 0.7 769 0 0.8 0.3 770 0.2 1 0.7 771 0.7 0.8 1 772 0.3 0.2 0 773 0.3 0.6 0.7 774 0.6 0.3 0.7 775 0.9 0.3 0.8 776 0.3 0.3 0.4 777 0.2 0.9 0.7 778 0.9 0.2 0.7 779 0.5 0.2 0.5 780 0.2 0.3 0.1 781 0.2 0.5 0.5 782 0.3 0.2 0.1 783 0.3 0.9 0.8 784 0.5 0.5 0.8 785 0.5 0.7 0.9 786 0.7 0.5 0.9 787 0.5 0.1 0.3 788 0.7 0.1 0.5 789 0.1 0.7 0.5 790 0.1 0.5 0.3 791 0 0.6 0 792 0.6 0.4 0.8 793 0.4 0.6 0.8 794 0.6 1 1 795 0 1 0.4 796 1 0.6 1 797 1 0 0.4 798 0.2 0.6 0.6 799 0.6 0 0 800 0.6 0.2 0.6 801 0.4 0.2 0.4 802 0.2 0.4 0.4 803 0.4 0.1 0 804 1 0.1 0.6 805 1 0.4 0.9 806 0.6 0 0.1 807 0 0.9 0.4 808 0.1 1 0.6 809 0.2 0.8 0.7 810 0.9 0 0.4 811 0.8 0.3 0.8 812 0.9 0.6 1 813 0.1 0.4 0 814 0 0.6 0.1 815 0.2 0.3 0.2 816 0.6 0.9 1 817 0.3 0.8 0.8 818 0.3 0.2 0.2 819 0.8 0.2 0.7 820 0.4 1 0.9 821 0.4 0.9 0.9 822 0.9 0.4 0.9 823 0.4 0.1 0.1 824 0.7 0.7 1 825 0.7 0 0.3 826 0.9 0.1 0.6 827 0 0.7 0.3 828 0.1 0.9 0.6 829 0.1 0.4 0.1 830 0.8 0 0.4 831 0.6 0 0.2 832 0 0.6 0.2 833 0.8 0.6 1 834 0 0.8 0.4 835 0.6 0.8 1 836 0.8 0.1 0.6 837 0.4 0.3 0.6 838 0.8 0.4 0.9 839 0.3 0.4 0.6 840 0.4 0.1 0.2 841 0.4 0.8 0.9 842 0.1 0.8 0.6 843 0.4 0.4 0.7 844 0.1 0.4 0.2 845 0.5 0.6 0.9 846 0.7 0.2 0.7 847 0.6 0.1 0.5 848 0.7 0.3 0.8 849 0.1 0.6 0.5 850 0.6 0.5 0.9 851 0.2 0.3 0.3 852 0.1 0.5 0.4 853 0.3 0.7 0.8 854 0.5 0.1 0.4 855 0.3 0.2 0.3 856 0.2 0.7 0.7 857 0.3 0.5 0.7 858 0.3 0.3 0.5 859 0.5 0.3 0.7 860 0.5 0 0 861 0 0.7 0.4 862 0.4 0.5 0.8 863 0 1 0.5 864 1 0.5 1 865 0.7 0 0.4 866 0 0.5 0 867 1 0 0.5 868 0 0.6 0.3 869 0.7 0.6 1 870 0.5 1 1 871 0.6 0.7 1 872 0.5 0.2 0.6 873 0.6 0 0.3 874 0.2 0.5 0.6 875 0.2 0.4 0.5 876 0.4 0.2 0.5 877 0.5 0.4 0.8 878 0.7 0.4 0.9 879 0.4 0.1 0.3 880 0.7 0.1 0.6 881 0.9 0 0.5 882 0.5 0 0.1 883 0.4 0.7 0.9 884 0 0.5 0.1 885 0 0.9 0.5 886 0.5 0.9 1 887 0.9 0.5 1 888 0.1 0.7 0.6 889 0.1 0.4 0.3 890 0.2 0.2 0 891 0.2 1 0.8 892 1 0.2 0.8 893 0.6 0.3 0.8 894 0.3 0.6 0.8 895 0.8 0.5 1 896 0.8 0 0.5 897 0.2 0.3 0.4 898 0.5 0 0.2 899 0 0.8 0.5 900 0 0.5 0.2 901 0.2 0.6 0.7 902 0.5 0.8 1 903 0.9 0.2 0.8 904 0.2 0.2 0.1 905 0.6 0.2 0.7 906 0.2 0.9 0.8 907 0.3 0.2 0.4 908 1 0.3 0.9 909 1 0.1 0.7 910 0.3 0.1 0 911 0.1 0.3 0 912 0.1 1 0.7 913 0.3 1 0.9 914 0.9 0.3 0.9 915 0.3 0.9 0.9 916 0.1 0.5 0.5 917 0.1 0.9 0.7 918 0.9 0.1 0.7 919 0.5 0.1 0.5 920 0.3 0.1 0.1 921 0.1 0.3 0.1 922 0.5 0.5 0.9 923 0.6 0.6 1 924 0.2 0.2 0.2 925 0 0.6 0.4 926 0.6 0 0.4 927 0.8 0.2 0.8 928 0.2 0.8 0.8 929 0.4 0.6 0.9 930 0.6 0.1 0.6 931 0.4 0.1 0.4 932 0.1 0.4 0.4 933 0.6 0.4 0.9 934 0.1 0.6 0.6 935 0.8 0.3 0.9 936 0.4 0.3 0.7 937 0.3 0.4 0.7 938 0.1 0.8 0.7 939 0.3 0.3 0.6 940 0.8 0.1 0.7 941 0 0.7 0.5 942 0.7 0.5 1 943 0.1 0.3 0.2 944 0.7 0 0.5 945 0 0.5 0.3 946 0.3 0.1 0.2 947 0.5 0 0.3 948 0.3 0.8 0.9 949 0.5 0.7 1 950 1 0.4 1 951 0.4 1 1 952 1 0 0.6 953 0.4 0 0 954 0 1 0.6 955 0 0.4 0 956 0.4 0.4 0.8 957 0.4 0.2 0.6 958 0.2 0.4 0.6 959 0 0.4 0.1 960 0.4 0 0.1 961 0.9 0.4 1 962 0 0.9 0.6 963 0.9 0 0.6 964 0.7 0.2 0.8 965 0.2 0.2 0.3 966 0.4 0.9 1 967 0.2 0.7 0.8 968 0.5 0.3 0.8 969 0.5 0.2 0.7 970 0.2 0.5 0.7 971 0.3 0.5 0.8 972 0.2 0.3 0.5 973 0.3 0.2 0.5 974 0.3 0.7 0.9 975 0.7 0.3 0.9 976 0.7 0.1 0.7 977 0.1 0.3 0.3 978 0.3 0.1 0.3 979 0.1 0.7 0.7 980 0.4 0 0.2 981 0.8 0 0.6 982 0 0.8 0.6 983 0 0.4 0.2 984 0.8 0.4 1 985 0.4 0.8 1 986 0 0.5 0.4 987 0.6 0 0.5 988 0.6 0.5 1 989 0.5 0.6 1 990 0 0.6 0.5 991 0.5 0 0.4 992 0.4 0.5 0.9 993 0.1 0.5 0.6 994 0.1 0.4 0.5 995 0.5 0.4 0.9 996 0.4 0.1 0.5 997 0.5 0.1 0.6 998 0.2 0.6 0.8 999 0.2 0.2 0.4 1000 0.6 0.2 0.8 1001 0.2 1 0.9 1002 0.4 0 0.3 1003 0.4 0.7 1 1004 0.7 0.4 1 1005 0 0.4 0.3 1006 1 0.1 0.8 1007 0.1 0.2 0 1008 0 0.7 0.6 1009 0.1 1 0.8 1010 0.7 0 0.6 1011 1 0.2 0.9 1012 0.2 0.1 0 1013 0.6 0.3 0.9 1014 0.3 0.6 0.9 1015 0.1 0.3 0.4 1016 0.2 0.9 0.9 1017 0.6 0.1 0.7 1018 0.3 0.1 0.4 1019 0.2 0.1 0.1 1020 0.9 0.2 0.9 1021 0.1 0.6 0.7 1022 0.1 0.2 0.1 1023 0.9 0.1 0.8 1024 0.1 0.9 0.8 1025 0.3 0.3 0.7 1026 0.2 0.8 0.9 1027 0.4 0.3 0.8 1028 0.1 0.8 0.8 1029 0 1 0.7 1030 1 0.3 1 1031 1 0 0.7 1032 0 0.3 0 1033 0.3 0 0 1034 0.3 1 1 1035 0.3 0.2 0.6 1036 0.8 0.2 0.9 1037 0.2 0.1 0.2 1038 0.2 0.4 0.7 1039 0.8 0.1 0.8 1040 0.3 0.4 0.8 1041 0.2 0.3 0.6 1042 0.1 0.2 0.2 1043 0.4 0.2 0.7 1044 0 0.9 0.7 1045 0.5 0 0.5 1046 0 0.5 0.5 1047 0.9 0 0.7 1048 0.9 0.3 1 1049 0.3 0 0.1 1050 0.3 0.9 1 1051 0.5 0.5 1 1052 0 0.3 0.1 1053 0.4 0.6 1 1054 0.6 0.4 1 1055 0.4 0 0.4 1056 0 0.4 0.4 1057 0 0.6 0.6 1058 0.6 0 0.6 1059 0.8 0.3 1 1060 0.4 0.1 0.6 1061 0.3 0.8 1 1062 0.3 0 0.2 1063 0.8 0 0.7 1064 0 0.8 0.7 1065 0 0.3 0.2 1066 0.2 0.2 0.5 1067 0.1 0.4 0.6 1068 0.4 0.4 0.9 1069 0.2 0.5 0.8 1070 0.5 0.2 0.8 1071 0.1 0.7 0.8 1072 0.2 0.1 0.3 1073 0.7 0.1 0.8 1074 0.1 0.2 0.3 1075 0.7 0.2 0.9 1076 0.2 0.7 0.9 1077 0.1 0.5 0.7 1078 0.5 0.3 0.9 1079 0.3 0.5 0.9 1080 0.5 0.1 0.7 1081 0.3 0.1 0.5 1082 0.1 0.3 0.5 1083 0.7 0.3 1 1084 0.3 0 0.3 1085 0.7 0 0.7 1086 0 0.3 0.3 1087 0 0.7 0.7 1088 0.3 0.7 1 1089 0 0.4 0.5 1090 0.1 0.6 0.8 1091 0.4 0 0.5 1092 0.4 0.5 1 1093 0 0.5 0.6 1094 0.5 0 0.6 1095 0.5 0.4 1 1096 0.2 0.6 0.9 1097 0.2 0.1 0.4 1098 0.1 0.2 0.4 1099 0.6 0.1 0.8 1100 0.6 0.2 0.9 1101 0.3 0.3 0.8 1102 1 0.1 0.9 1103 0.2 0.3 0.7 1104 0.1 0.1 0 1105 0.1 1 0.9 1106 0.3 0.2 0.7 1107 0.9 0.1 0.9 1108 0.1 0.9 0.9 1109 0.1 0.1 0.1 1110 0.2 1 1 1111 0.2 0.2 0.6 1112 0 0.2 0 1113 1 0.2 1 1114 0.2 0 0 1115 1 0 0.8 1116 0 1 0.8 1117 0.4 0.2 0.8 1118 0.2 0.4 0.8 1119 0.6 0.3 1 1120 0.3 0.6 1 1121 0.3 0 0.4 1122 0 0.6 0.7 1123 0.2 0 0.1 1124 0 0.2 0.1 1125 0.9 0.2 1 1126 0.2 0.9 1 1127 0.6 0 0.7 1128 0.9 0 0.8 1129 0 0.3 0.4 1130 0 0.9 0.8 1131 0.8 0.1 0.9 1132 0.4 0.3 0.9 1133 0.4 0.1 0.7 1134 0.1 0.8 0.9 1135 0.1 0.3 0.6 1136 0.3 0.1 0.6 1137 0.1 0.4 0.7 1138 0.1 0.1 0.2 1139 0.3 0.4 0.9 1140 0.8 0 0.8 1141 0 0.2 0.2 1142 0.2 0.8 1 1143 0.2 0 0.2 1144 0.8 0.2 1 1145 0 0.8 0.8 1146 0.2 0.5 0.9 1147 0.5 0.1 0.8 1148 0.1 0.5 0.8 1149 0.5 0.2 0.9 1150 0.1 0.2 0.5 1151 0.2 0.1 0.5 1152 0.7 0.1 0.9 1153 0.1 0.7 0.9 1154 0.1 0.1 0.3 1155 0.4 0 0.6 1156 0 0.4 0.6 1157 0.4 0.4 1 1158 0 0.7 0.8 1159 0.7 0.2 1 1160 0 0.2 0.3 1161 0.2 0 0.3 1162 0.7 0 0.8 1163 0.2 0.7 1 1164 0 0.5 0.7 1165 0.5 0 0.7 1166 0.3 0 0.5 1167 0.5 0.3 1 1168 0.3 0.5 1 1169 0 0.3 0.5 1170 0.2 0.2 0.7 1171 0.2 0.3 0.8 1172 0.3 0.2 0.8 1173 0.6 0.1 0.9 1174 0.1 0.6 0.9 1175 0.1 0.1 0.4 1176 0.3 0.3 0.9 1177 0.1 0.3 0.7 1178 0.3 0.1 0.7 1179 0 0.6 0.8 1180 0.2 0 0.4 1181 0.2 0.6 1 1182 0 0.2 0.4 1183 0.6 0.2 1 1184 0.6 0 0.8 1185 0 0.1 0 1186 0.1 0 0 1187 0 1 0.9 1188 1 0 0.9 1189 0.2 0.1 0.6 1190 0.1 0.2 0.6 1191 0.4 0.2 0.9 1192 1 0.1 1 1193 0.1 1 1 1194 0.4 0.1 0.8 1195 0.1 0.4 0.8 1196 0.2 0.4 0.9 1197 0.9 0.1 1 1198 0.1 0 0.1 1199 0 0.9 0.9 1200 0 0.1 0.1 1201 0.1 0.9 1 1202 0.9 0 0.9 1203 0.4 0.3 1 1204 0 0.8 0.9 1205 0.4 0 0.7 1206 0 0.4 0.7 1207 0.8 0 0.9 1208 0.1 0 0.2 1209 0.8 0.1 1 1210 0.3 0.4 1 1211 0 0.1 0.2 1212 0.1 0.8 1 1213 0.3 0 0.6 1214 0 0.3 0.6 1215 0.5 0.1 0.9 1216 0.1 0.5 0.9 1217 0.1 0.1 0.5 1218 0.5 0 0.8 1219 0 0.2 0.5 1220 0.2 0 0.5 1221 0 0.5 0.8 1222 0.2 0.5 1 1223 0.5 0.2 1 1224 0 0.7 0.9 1225 0.1 0 0.3 1226 0.7 0.1 1 1227 0.1 0.7 1 1228 0 0.1 0.3 1229 0.7 0 0.9 1230 0.2 0.2 0.8 1231 0.1 0.3 0.8 1232 0.2 0.1 0.7 1233 0.3 0.1 0.8 1234 0.1 0.2 0.7 1235 0.2 0.3 0.9 1236 0.3 0.2 0.9 1237 0.1 0 0.4 1238 0.6 0.1 1 1239 0.1 0.6 1 1240 0 0.6 0.9 1241 0 0.1 0.4 1242 0.6 0 0.9 1243 0.3 0.3 1 1244 0.3 0 0.7 1245 0.1 0.1 0.6 1246 0 0.3 0.7 1247 0.1 0.4 0.9 1248 0.4 0.1 0.9 1249 0.4 0 0.8 1250 0 0 0 1251 0 1 1 1252 0 0.2 0.6 1253 0.2 0.4 1 1254 1 0 1 1255 0.4 0.2 1 1256 0.2 0 0.6 1257 0 0.4 0.8 1258 0 0 0.1 1259 0.9 0 1 1260 0 0.9 1 1261 0 0 0.2 1262 0 0.8 1 1263 0.8 0 1 1264 0.5 0 0.9 1265 0.1 0 0.5 1266 0 0.5 0.9 1267 0.5 0.1 1 1268 0 0.1 0.5 1269 0.1 0.5 1 1270 0.1 0.2 0.8 1271 0.2 0.2 0.9 1272 0 0.7 1 1273 0 0 0.3 1274 0.2 0.1 0.8 1275 0.7 0 1 1276 0.1 0.1 0.7 1277 0.3 0.1 0.9 1278 0.1 0.3 0.9 1279 0 0.2 0.7 1280 0.2 0 0.7 1281 0.3 0 0.8 1282 0.2 0.3 1 1283 0 0.3 0.8 1284 0.3 0.2 1 1285 0 0.6 1 1286 0 0 0.4 1287 0.6 0 1 1288 0 0.1 0.6 1289 0.4 0.1 1 1290 0 0.4 0.9 1291 0.1 0 0.6 1292 0.1 0.4 1 1293 0.4 0 0.9 1294 0.5 0 1 1295 0 0 0.5 1296 0 0.5 1 1297 0.1 0.2 0.9 1298 0.2 0.1 0.9 1299 0.1 0.1 0.8 1300 0.2 0.2 1 1301 0 0.2 0.8 1302 0.2 0 0.8 1303 0.3 0 0.9 1304 0.1 0 0.7 1305 0 0.1 0.7 1306 0.1 0.3 1 1307 0.3 0.1 1 1308 0 0.3 0.9 1309 0 0 0.6 1310 0 0.4 1 1311 0.4 0 1 1312 0.1 0.1 0.9 1313 0 0.2 0.9 1314 0 0.1 0.8 1315 0.2 0 0.9 1316 0.2 0.1 1 1317 0.1 0 0.8 1318 0.1 0.2 1 1319 0 0 0.7 1320 0 0.3 1 1321 0.3 0 1 1322 0.1 0 0.9 1323 0 0.1 0.9 1324 0.1 0.1 1 1325 0 0.2 1 1326 0 0 0.8 1327 0.2 0 1 1328 0.1 0 1 1329 0 0.1 1 1330 0 0 0.9 1331 0 0 1 ]; %% Conectivities % Element Node(1) Node(2) Node(3) Node(4) Material gidlnods = [ 1 1186 1198 1109 1250 0 2 1250 1186 1104 1109 0 3 1258 1200 1109 1250 0 4 1250 1185 1200 1109 0 5 1250 1258 1198 1109 0 6 1185 1104 1109 1250 0 7 1114 1012 1104 1019 0 8 1019 1109 1104 1114 0 9 1186 1104 1109 1114 0 10 1114 1186 1198 1109 0 11 1114 1123 1019 1109 0 12 1123 1198 1109 1114 0 13 1033 910 1012 920 0 14 920 1019 1012 1033 0 15 1114 1012 1019 1033 0 16 1033 1114 1123 1019 0 17 1033 1049 920 1019 0 18 1049 1123 1019 1033 0 19 953 803 910 823 0 20 823 920 910 953 0 21 1033 910 920 953 0 22 953 1033 1049 920 0 23 953 960 823 920 0 24 960 1049 920 953 0 25 860 711 803 720 0 26 720 823 803 860 0 27 953 803 823 860 0 28 860 953 960 823 0 29 860 882 720 823 0 30 882 960 823 860 0 31 799 611 711 621 0 32 621 720 711 799 0 33 860 711 720 799 0 34 799 860 882 720 0 35 799 806 621 720 0 36 806 882 720 799 0 37 735 566 611 582 0 38 582 621 611 735 0 39 799 611 621 735 0 40 735 799 806 621 0 41 735 751 582 621 0 42 751 806 621 735 0 43 683 518 566 525 0 44 525 582 566 683 0 45 735 566 582 683 0 46 683 735 751 582 0 47 683 693 525 582 0 48 693 751 582 683 0 49 666 489 518 497 0 50 497 525 518 666 0 51 683 518 525 666 0 52 666 683 693 525 0 53 666 675 497 525 0 54 675 693 525 666 0 55 477 487 497 643 0 56 643 477 489 497 0 57 658 675 497 643 0 58 643 666 675 497 0 59 643 658 487 497 0 60 666 489 497 643 0 61 1198 1208 1138 1258 0 62 1258 1198 1109 1138 0 63 1261 1211 1138 1258 0 64 1258 1200 1211 1138 0 65 1258 1261 1208 1138 0 66 1200 1109 1138 1258 0 67 1123 1019 1109 1037 0 68 1037 1138 1109 1123 0 69 1198 1109 1138 1123 0 70 1123 1198 1208 1138 0 71 1123 1143 1037 1138 0 72 1143 1208 1138 1123 0 73 1049 920 1019 946 0 74 946 1037 1019 1049 0 75 1123 1019 1037 1049 0 76 1049 1123 1143 1037 0 77 1049 1062 946 1037 0 78 1062 1143 1037 1049 0 79 960 823 920 840 0 80 840 946 920 960 0 81 1049 920 946 960 0 82 960 1049 1062 946 0 83 960 980 840 946 0 84 980 1062 946 960 0 85 882 720 823 756 0 86 756 840 823 882 0 87 960 823 840 882 0 88 882 960 980 840 0 89 882 898 756 840 0 90 898 980 840 882 0 91 806 621 720 659 0 92 659 756 720 806 0 93 882 720 756 806 0 94 806 882 898 756 0 95 806 831 659 756 0 96 831 898 756 806 0 97 751 582 621 596 0 98 596 659 621 751 0 99 806 621 659 751 0 100 751 806 831 659 0 101 751 767 596 659 0 102 767 831 659 751 0 103 693 525 582 542 0 104 542 596 582 693 0 105 751 582 596 693 0 106 693 751 767 596 0 107 693 726 542 596 0 108 726 767 596 693 0 109 675 497 525 528 0 110 528 542 525 675 0 111 693 525 542 675 0 112 675 693 726 542 0 113 675 692 528 542 0 114 692 726 542 675 0 115 487 513 528 658 0 116 658 487 497 528 0 117 686 692 528 658 0 118 658 675 692 528 0 119 658 686 513 528 0 120 675 497 528 658 0 121 1208 1225 1154 1261 0 122 1261 1208 1138 1154 0 123 1273 1228 1154 1261 0 124 1261 1211 1228 1154 0 125 1261 1273 1225 1154 0 126 1211 1138 1154 1261 0 127 1143 1037 1138 1072 0 128 1072 1154 1138 1143 0 129 1208 1138 1154 1143 0 130 1143 1208 1225 1154 0 131 1143 1161 1072 1154 0 132 1161 1225 1154 1143 0 133 1062 946 1037 978 0 134 978 1072 1037 1062 0 135 1143 1037 1072 1062 0 136 1062 1143 1161 1072 0 137 1062 1084 978 1072 0 138 1084 1161 1072 1062 0 139 980 840 946 879 0 140 879 978 946 980 0 141 1062 946 978 980 0 142 980 1062 1084 978 0 143 980 1002 879 978 0 144 1002 1084 978 980 0 145 898 756 840 787 0 146 787 879 840 898 0 147 980 840 879 898 0 148 898 980 1002 879 0 149 898 947 787 879 0 150 947 1002 879 898 0 151 831 659 756 708 0 152 708 787 756 831 0 153 898 756 787 831 0 154 831 898 947 787 0 155 831 873 708 787 0 156 873 947 787 831 0 157 767 596 659 633 0 158 633 708 659 767 0 159 831 659 708 767 0 160 767 831 873 708 0 161 767 825 633 708 0 162 825 873 708 767 0 163 726 542 596 594 0 164 594 633 596 726 0 165 767 596 633 726 0 166 726 767 825 633 0 167 726 761 594 633 0 168 761 825 633 726 0 169 692 528 542 581 0 170 581 594 542 692 0 171 726 542 594 692 0 172 692 726 761 594 0 173 692 745 581 594 0 174 745 761 594 692 0 175 513 563 581 686 0 176 686 513 528 581 0 177 731 745 581 686 0 178 686 692 745 581 0 179 686 731 563 581 0 180 692 528 581 686 0 181 1225 1237 1175 1273 0 182 1273 1225 1154 1175 0 183 1286 1241 1175 1273 0 184 1273 1228 1241 1175 0 185 1273 1286 1237 1175 0 186 1228 1154 1175 1273 0 187 1161 1072 1154 1097 0 188 1097 1175 1154 1161 0 189 1225 1154 1175 1161 0 190 1161 1225 1237 1175 0 191 1161 1180 1097 1175 0 192 1180 1237 1175 1161 0 193 1084 978 1072 1018 0 194 1018 1097 1072 1084 0 195 1161 1072 1097 1084 0 196 1084 1161 1180 1097 0 197 1084 1121 1018 1097 0 198 1121 1180 1097 1084 0 199 1002 879 978 931 0 200 931 1018 978 1002 0 201 1084 978 1018 1002 0 202 1002 1084 1121 1018 0 203 1002 1055 931 1018 0 204 1055 1121 1018 1002 0 205 947 787 879 854 0 206 854 931 879 947 0 207 1002 879 931 947 0 208 947 1002 1055 931 0 209 947 991 854 931 0 210 991 1055 931 947 0 211 873 708 787 763 0 212 763 854 787 873 0 213 947 787 854 873 0 214 873 947 991 854 0 215 873 926 763 854 0 216 926 991 854 873 0 217 825 633 708 704 0 218 704 763 708 825 0 219 873 708 763 825 0 220 825 873 926 763 0 221 825 865 704 763 0 222 865 926 763 825 0 223 761 594 633 655 0 224 655 704 633 761 0 225 825 633 704 761 0 226 761 825 865 704 0 227 761 830 655 704 0 228 830 865 704 761 0 229 745 581 594 616 0 230 616 655 594 745 0 231 761 594 655 745 0 232 745 761 830 655 0 233 745 810 616 655 0 234 810 830 655 745 0 235 563 608 616 731 0 236 731 563 581 616 0 237 797 810 616 731 0 238 731 745 810 616 0 239 731 797 608 616 0 240 745 581 616 731 0 241 1237 1265 1217 1286 0 242 1286 1237 1175 1217 0 243 1295 1268 1217 1286 0 244 1286 1241 1268 1217 0 245 1286 1295 1265 1217 0 246 1241 1175 1217 1286 0 247 1180 1097 1175 1151 0 248 1151 1217 1175 1180 0 249 1237 1175 1217 1180 0 250 1180 1237 1265 1217 0 251 1180 1220 1151 1217 0 252 1220 1265 1217 1180 0 253 1121 1018 1097 1081 0 254 1081 1151 1097 1121 0 255 1180 1097 1151 1121 0 256 1121 1180 1220 1151 0 257 1121 1166 1081 1151 0 258 1166 1220 1151 1121 0 259 1055 931 1018 996 0 260 996 1081 1018 1055 0 261 1121 1018 1081 1055 0 262 1055 1121 1166 1081 0 263 1055 1091 996 1081 0 264 1091 1166 1081 1055 0 265 991 854 931 919 0 266 919 996 931 991 0 267 1055 931 996 991 0 268 991 1055 1091 996 0 269 991 1045 919 996 0 270 1045 1091 996 991 0 271 926 763 854 847 0 272 847 919 854 926 0 273 991 854 919 926 0 274 926 991 1045 919 0 275 926 987 847 919 0 276 987 1045 919 926 0 277 865 704 763 788 0 278 788 847 763 865 0 279 926 763 847 865 0 280 865 926 987 847 0 281 865 944 788 847 0 282 944 987 847 865 0 283 830 655 704 743 0 284 743 788 704 830 0 285 865 704 788 830 0 286 830 865 944 788 0 287 830 896 743 788 0 288 896 944 788 830 0 289 810 616 655 717 0 290 717 743 655 810 0 291 830 655 743 810 0 292 810 830 896 743 0 293 810 881 717 743 0 294 881 896 743 810 0 295 608 705 717 797 0 296 797 608 616 717 0 297 867 881 717 797 0 298 797 810 881 717 0 299 797 867 705 717 0 300 810 616 717 797 0 301 1265 1291 1245 1295 0 302 1295 1265 1217 1245 0 303 1309 1288 1245 1295 0 304 1295 1268 1288 1245 0 305 1295 1309 1291 1245 0 306 1268 1217 1245 1295 0 307 1220 1151 1217 1189 0 308 1189 1245 1217 1220 0 309 1265 1217 1245 1220 0 310 1220 1265 1291 1245 0 311 1220 1256 1189 1245 0 312 1256 1291 1245 1220 0 313 1166 1081 1151 1136 0 314 1136 1189 1151 1166 0 315 1220 1151 1189 1166 0 316 1166 1220 1256 1189 0 317 1166 1213 1136 1189 0 318 1213 1256 1189 1166 0 319 1091 996 1081 1060 0 320 1060 1136 1081 1091 0 321 1166 1081 1136 1091 0 322 1091 1166 1213 1136 0 323 1091 1155 1060 1136 0 324 1155 1213 1136 1091 0 325 1045 919 996 997 0 326 997 1060 996 1045 0 327 1091 996 1060 1045 0 328 1045 1091 1155 1060 0 329 1045 1094 997 1060 0 330 1094 1155 1060 1045 0 331 987 847 919 930 0 332 930 997 919 987 0 333 1045 919 997 987 0 334 987 1045 1094 997 0 335 987 1058 930 997 0 336 1058 1094 997 987 0 337 944 788 847 880 0 338 880 930 847 944 0 339 987 847 930 944 0 340 944 987 1058 930 0 341 944 1010 880 930 0 342 1010 1058 930 944 0 343 896 743 788 836 0 344 836 880 788 896 0 345 944 788 880 896 0 346 896 944 1010 880 0 347 896 981 836 880 0 348 981 1010 880 896 0 349 881 717 743 826 0 350 826 836 743 881 0 351 896 743 836 881 0 352 881 896 981 836 0 353 881 963 826 836 0 354 963 981 836 881 0 355 705 804 826 867 0 356 867 705 717 826 0 357 952 963 826 867 0 358 867 881 963 826 0 359 867 952 804 826 0 360 881 717 826 867 0 361 1291 1304 1276 1309 0 362 1309 1291 1245 1276 0 363 1319 1305 1276 1309 0 364 1309 1288 1305 1276 0 365 1309 1319 1304 1276 0 366 1288 1245 1276 1309 0 367 1256 1189 1245 1232 0 368 1232 1276 1245 1256 0 369 1291 1245 1276 1256 0 370 1256 1291 1304 1276 0 371 1256 1280 1232 1276 0 372 1280 1304 1276 1256 0 373 1213 1136 1189 1178 0 374 1178 1232 1189 1213 0 375 1256 1189 1232 1213 0 376 1213 1256 1280 1232 0 377 1213 1244 1178 1232 0 378 1244 1280 1232 1213 0 379 1155 1060 1136 1133 0 380 1133 1178 1136 1155 0 381 1213 1136 1178 1155 0 382 1155 1213 1244 1178 0 383 1155 1205 1133 1178 0 384 1205 1244 1178 1155 0 385 1094 997 1060 1080 0 386 1080 1133 1060 1094 0 387 1155 1060 1133 1094 0 388 1094 1155 1205 1133 0 389 1094 1165 1080 1133 0 390 1165 1205 1133 1094 0 391 1058 930 997 1017 0 392 1017 1080 997 1058 0 393 1094 997 1080 1058 0 394 1058 1094 1165 1080 0 395 1058 1127 1017 1080 0 396 1127 1165 1080 1058 0 397 1010 880 930 976 0 398 976 1017 930 1010 0 399 1058 930 1017 1010 0 400 1010 1058 1127 1017 0 401 1010 1085 976 1017 0 402 1085 1127 1017 1010 0 403 981 836 880 940 0 404 940 976 880 981 0 405 1010 880 976 981 0 406 981 1010 1085 976 0 407 981 1063 940 976 0 408 1063 1085 976 981 0 409 963 826 836 918 0 410 918 940 836 963 0 411 981 836 940 963 0 412 963 981 1063 940 0 413 963 1047 918 940 0 414 1047 1063 940 963 0 415 804 909 918 952 0 416 952 804 826 918 0 417 1031 1047 918 952 0 418 952 963 1047 918 0 419 952 1031 909 918 0 420 963 826 918 952 0 421 1304 1317 1299 1319 0 422 1319 1304 1276 1299 0 423 1326 1314 1299 1319 0 424 1319 1305 1314 1299 0 425 1319 1326 1317 1299 0 426 1305 1276 1299 1319 0 427 1280 1232 1276 1274 0 428 1274 1299 1276 1280 0 429 1304 1276 1299 1280 0 430 1280 1304 1317 1299 0 431 1280 1302 1274 1299 0 432 1302 1317 1299 1280 0 433 1244 1178 1232 1233 0 434 1233 1274 1232 1244 0 435 1280 1232 1274 1244 0 436 1244 1280 1302 1274 0 437 1244 1281 1233 1274 0 438 1281 1302 1274 1244 0 439 1205 1133 1178 1194 0 440 1194 1233 1178 1205 0 441 1244 1178 1233 1205 0 442 1205 1244 1281 1233 0 443 1205 1249 1194 1233 0 444 1249 1281 1233 1205 0 445 1165 1080 1133 1147 0 446 1147 1194 1133 1165 0 447 1205 1133 1194 1165 0 448 1165 1205 1249 1194 0 449 1165 1218 1147 1194 0 450 1218 1249 1194 1165 0 451 1127 1017 1080 1099 0 452 1099 1147 1080 1127 0 453 1165 1080 1147 1127 0 454 1127 1165 1218 1147 0 455 1127 1184 1099 1147 0 456 1184 1218 1147 1127 0 457 1085 976 1017 1073 0 458 1073 1099 1017 1085 0 459 1127 1017 1099 1085 0 460 1085 1127 1184 1099 0 461 1085 1162 1073 1099 0 462 1162 1184 1099 1085 0 463 1063 940 976 1039 0 464 1039 1073 976 1063 0 465 1085 976 1073 1063 0 466 1063 1085 1162 1073 0 467 1063 1140 1039 1073 0 468 1140 1162 1073 1063 0 469 1047 918 940 1023 0 470 1023 1039 940 1047 0 471 1063 940 1039 1047 0 472 1047 1063 1140 1039 0 473 1047 1128 1023 1039 0 474 1128 1140 1039 1047 0 475 909 1006 1023 1031 0 476 1031 909 918 1023 0 477 1115 1128 1023 1031 0 478 1031 1047 1128 1023 0 479 1031 1115 1006 1023 0 480 1047 918 1023 1031 0 481 1317 1322 1312 1326 0 482 1326 1317 1299 1312 0 483 1330 1323 1312 1326 0 484 1326 1314 1323 1312 0 485 1326 1330 1322 1312 0 486 1314 1299 1312 1326 0 487 1302 1274 1299 1298 0 488 1298 1312 1299 1302 0 489 1317 1299 1312 1302 0 490 1302 1317 1322 1312 0 491 1302 1315 1298 1312 0 492 1315 1322 1312 1302 0 493 1281 1233 1274 1277 0 494 1277 1298 1274 1281 0 495 1302 1274 1298 1281 0 496 1281 1302 1315 1298 0 497 1281 1303 1277 1298 0 498 1303 1315 1298 1281 0 499 1249 1194 1233 1248 0 500 1248 1277 1233 1249 0 501 1281 1233 1277 1249 0 502 1249 1281 1303 1277 0 503 1249 1293 1248 1277 0 504 1293 1303 1277 1249 0 505 1218 1147 1194 1215 0 506 1215 1248 1194 1218 0 507 1249 1194 1248 1218 0 508 1218 1249 1293 1248 0 509 1218 1264 1215 1248 0 510 1264 1293 1248 1218 0 511 1184 1099 1147 1173 0 512 1173 1215 1147 1184 0 513 1218 1147 1215 1184 0 514 1184 1218 1264 1215 0 515 1184 1242 1173 1215 0 516 1242 1264 1215 1184 0 517 1162 1073 1099 1152 0 518 1152 1173 1099 1162 0 519 1184 1099 1173 1162 0 520 1162 1184 1242 1173 0 521 1162 1229 1152 1173 0 522 1229 1242 1173 1162 0 523 1140 1039 1073 1131 0 524 1131 1152 1073 1140 0 525 1162 1073 1152 1140 0 526 1140 1162 1229 1152 0 527 1140 1207 1131 1152 0 528 1207 1229 1152 1140 0 529 1128 1023 1039 1107 0 530 1107 1131 1039 1128 0 531 1140 1039 1131 1128 0 532 1128 1140 1207 1131 0 533 1128 1202 1107 1131 0 534 1202 1207 1131 1128 0 535 1006 1102 1107 1115 0 536 1115 1006 1023 1107 0 537 1188 1202 1107 1115 0 538 1115 1128 1202 1107 0 539 1115 1188 1102 1107 0 540 1128 1023 1107 1115 0 541 1323 1329 1331 1312 0 542 1312 1323 1330 1331 0 543 1324 1328 1331 1312 0 544 1312 1322 1328 1331 0 545 1312 1324 1329 1331 0 546 1322 1330 1331 1312 0 547 1327 1316 1298 1324 0 548 1324 1312 1298 1327 0 549 1315 1298 1312 1327 0 550 1327 1315 1322 1312 0 551 1327 1328 1324 1312 0 552 1328 1322 1312 1327 0 553 1321 1307 1277 1316 0 554 1316 1298 1277 1321 0 555 1303 1277 1298 1321 0 556 1321 1303 1315 1298 0 557 1321 1327 1316 1298 0 558 1327 1315 1298 1321 0 559 1311 1289 1248 1307 0 560 1307 1277 1248 1311 0 561 1293 1248 1277 1311 0 562 1311 1293 1303 1277 0 563 1311 1321 1307 1277 0 564 1321 1303 1277 1311 0 565 1294 1267 1215 1289 0 566 1289 1248 1215 1294 0 567 1264 1215 1248 1294 0 568 1294 1264 1293 1248 0 569 1294 1311 1289 1248 0 570 1311 1293 1248 1294 0 571 1287 1238 1173 1267 0 572 1267 1215 1173 1287 0 573 1242 1173 1215 1287 0 574 1287 1242 1264 1215 0 575 1287 1294 1267 1215 0 576 1294 1264 1215 1287 0 577 1275 1226 1152 1238 0 578 1238 1173 1152 1275 0 579 1229 1152 1173 1275 0 580 1275 1229 1242 1173 0 581 1275 1287 1238 1173 0 582 1287 1242 1173 1275 0 583 1263 1209 1131 1226 0 584 1226 1152 1131 1263 0 585 1207 1131 1152 1263 0 586 1263 1207 1229 1152 0 587 1263 1275 1226 1152 0 588 1275 1229 1152 1263 0 589 1259 1197 1107 1209 0 590 1209 1131 1107 1259 0 591 1202 1107 1131 1259 0 592 1259 1202 1207 1131 0 593 1259 1263 1209 1131 0 594 1263 1207 1131 1259 0 595 1202 1259 1254 1107 0 596 1107 1202 1188 1254 0 597 1197 1192 1254 1107 0 598 1107 1102 1192 1254 0 599 1107 1197 1259 1254 0 600 1102 1188 1254 1107 0 601 1104 1109 1022 1185 0 602 1185 1104 1007 1022 0 603 1200 1124 1022 1185 0 604 1185 1112 1124 1022 0 605 1185 1200 1109 1022 0 606 1112 1007 1022 1185 0 607 1012 1019 904 1104 0 608 1104 1012 890 904 0 609 1109 1022 904 1104 0 610 1104 1007 1022 904 0 611 1104 1109 1019 904 0 612 1007 890 904 1104 0 613 910 920 782 1012 0 614 1012 910 772 782 0 615 1019 904 782 1012 0 616 1012 890 904 782 0 617 1012 1019 920 782 0 618 890 772 782 1012 0 619 803 823 671 910 0 620 910 803 646 671 0 621 920 782 671 910 0 622 910 772 782 671 0 623 910 920 823 671 0 624 772 646 671 910 0 625 711 720 575 803 0 626 803 711 559 575 0 627 823 671 575 803 0 628 803 646 671 575 0 629 803 823 720 575 0 630 646 559 575 803 0 631 611 621 485 711 0 632 711 611 470 485 0 633 720 575 485 711 0 634 711 559 575 485 0 635 711 720 621 485 0 636 559 470 485 711 0 637 566 582 432 611 0 638 611 566 414 432 0 639 621 485 432 611 0 640 611 470 485 432 0 641 611 621 582 432 0 642 470 414 432 611 0 643 518 525 397 566 0 644 566 518 384 397 0 645 582 432 397 566 0 646 566 414 432 397 0 647 566 582 525 397 0 648 414 384 397 566 0 649 489 497 368 518 0 650 518 489 360 368 0 651 525 397 368 518 0 652 518 384 397 368 0 653 518 525 497 368 0 654 384 360 368 518 0 655 344 360 489 368 0 656 368 497 489 344 0 657 477 489 497 344 0 658 344 477 487 497 0 659 344 354 368 497 0 660 354 487 497 344 0 661 1109 1138 1042 1200 0 662 1200 1109 1022 1042 0 663 1211 1141 1042 1200 0 664 1200 1124 1141 1042 0 665 1200 1211 1138 1042 0 666 1124 1022 1042 1200 0 667 1019 1037 924 1109 0 668 1109 1019 904 924 0 669 1138 1042 924 1109 0 670 1109 1022 1042 924 0 671 1109 1138 1037 924 0 672 1022 904 924 1109 0 673 920 946 818 1019 0 674 1019 920 782 818 0 675 1037 924 818 1019 0 676 1019 904 924 818 0 677 1019 1037 946 818 0 678 904 782 818 1019 0 679 823 840 690 920 0 680 920 823 671 690 0 681 946 818 690 920 0 682 920 782 818 690 0 683 920 946 840 690 0 684 782 671 690 920 0 685 720 756 589 823 0 686 823 720 575 589 0 687 840 690 589 823 0 688 823 671 690 589 0 689 823 840 756 589 0 690 671 575 589 823 0 691 621 659 510 720 0 692 720 621 485 510 0 693 756 589 510 720 0 694 720 575 589 510 0 695 720 756 659 510 0 696 575 485 510 720 0 697 582 596 453 621 0 698 621 582 432 453 0 699 659 510 453 621 0 700 621 485 510 453 0 701 621 659 596 453 0 702 485 432 453 621 0 703 525 542 410 582 0 704 582 525 397 410 0 705 596 453 410 582 0 706 582 432 453 410 0 707 582 596 542 410 0 708 432 397 410 582 0 709 497 528 396 525 0 710 525 497 368 396 0 711 542 410 396 525 0 712 525 397 410 396 0 713 525 542 528 396 0 714 397 368 396 525 0 715 354 368 497 396 0 716 396 528 497 354 0 717 487 497 528 354 0 718 354 487 513 528 0 719 354 383 396 528 0 720 383 513 528 354 0 721 1138 1154 1074 1211 0 722 1211 1138 1042 1074 0 723 1228 1160 1074 1211 0 724 1211 1141 1160 1074 0 725 1211 1228 1154 1074 0 726 1141 1042 1074 1211 0 727 1037 1072 965 1138 0 728 1138 1037 924 965 0 729 1154 1074 965 1138 0 730 1138 1042 1074 965 0 731 1138 1154 1072 965 0 732 1042 924 965 1138 0 733 946 978 855 1037 0 734 1037 946 818 855 0 735 1072 965 855 1037 0 736 1037 924 965 855 0 737 1037 1072 978 855 0 738 924 818 855 1037 0 739 840 879 739 946 0 740 946 840 690 739 0 741 978 855 739 946 0 742 946 818 855 739 0 743 946 978 879 739 0 744 818 690 739 946 0 745 756 787 625 840 0 746 840 756 589 625 0 747 879 739 625 840 0 748 840 690 739 625 0 749 840 879 787 625 0 750 690 589 625 840 0 751 659 708 560 756 0 752 756 659 510 560 0 753 787 625 560 756 0 754 756 589 625 560 0 755 756 787 708 560 0 756 589 510 560 756 0 757 596 633 491 659 0 758 659 596 453 491 0 759 708 560 491 659 0 760 659 510 560 491 0 761 659 708 633 491 0 762 510 453 491 659 0 763 542 594 456 596 0 764 596 542 410 456 0 765 633 491 456 596 0 766 596 453 491 456 0 767 596 633 594 456 0 768 453 410 456 596 0 769 528 581 428 542 0 770 542 528 396 428 0 771 594 456 428 542 0 772 542 410 456 428 0 773 542 594 581 428 0 774 410 396 428 542 0 775 383 396 528 428 0 776 428 581 528 383 0 777 513 528 581 383 0 778 383 513 563 581 0 779 383 417 428 581 0 780 417 563 581 383 0 781 1154 1175 1098 1228 0 782 1228 1154 1074 1098 0 783 1241 1182 1098 1228 0 784 1228 1160 1182 1098 0 785 1228 1241 1175 1098 0 786 1160 1074 1098 1228 0 787 1072 1097 999 1154 0 788 1154 1072 965 999 0 789 1175 1098 999 1154 0 790 1154 1074 1098 999 0 791 1154 1175 1097 999 0 792 1074 965 999 1154 0 793 978 1018 907 1072 0 794 1072 978 855 907 0 795 1097 999 907 1072 0 796 1072 965 999 907 0 797 1072 1097 1018 907 0 798 965 855 907 1072 0 799 879 931 801 978 0 800 978 879 739 801 0 801 1018 907 801 978 0 802 978 855 907 801 0 803 978 1018 931 801 0 804 855 739 801 978 0 805 787 854 701 879 0 806 879 787 625 701 0 807 931 801 701 879 0 808 879 739 801 701 0 809 879 931 854 701 0 810 739 625 701 879 0 811 708 763 606 787 0 812 787 708 560 606 0 813 854 701 606 787 0 814 787 625 701 606 0 815 787 854 763 606 0 816 625 560 606 787 0 817 633 704 553 708 0 818 708 633 491 553 0 819 763 606 553 708 0 820 708 560 606 553 0 821 708 763 704 553 0 822 560 491 553 708 0 823 594 655 507 633 0 824 633 594 456 507 0 825 704 553 507 633 0 826 633 491 553 507 0 827 633 704 655 507 0 828 491 456 507 633 0 829 581 616 481 594 0 830 594 581 428 481 0 831 655 507 481 594 0 832 594 456 507 481 0 833 594 655 616 481 0 834 456 428 481 594 0 835 417 428 581 481 0 836 481 616 581 417 0 837 563 581 616 417 0 838 417 563 608 616 0 839 417 468 481 616 0 840 468 608 616 417 0 841 1175 1217 1150 1241 0 842 1241 1175 1098 1150 0 843 1268 1219 1150 1241 0 844 1241 1182 1219 1150 0 845 1241 1268 1217 1150 0 846 1182 1098 1150 1241 0 847 1097 1151 1066 1175 0 848 1175 1097 999 1066 0 849 1217 1150 1066 1175 0 850 1175 1098 1150 1066 0 851 1175 1217 1151 1066 0 852 1098 999 1066 1175 0 853 1018 1081 973 1097 0 854 1097 1018 907 973 0 855 1151 1066 973 1097 0 856 1097 999 1066 973 0 857 1097 1151 1081 973 0 858 999 907 973 1097 0 859 931 996 876 1018 0 860 1018 931 801 876 0 861 1081 973 876 1018 0 862 1018 907 973 876 0 863 1018 1081 996 876 0 864 907 801 876 1018 0 865 854 919 779 931 0 866 931 854 701 779 0 867 996 876 779 931 0 868 931 801 876 779 0 869 931 996 919 779 0 870 801 701 779 931 0 871 763 847 699 854 0 872 854 763 606 699 0 873 919 779 699 854 0 874 854 701 779 699 0 875 854 919 847 699 0 876 701 606 699 854 0 877 704 788 622 763 0 878 763 704 553 622 0 879 847 699 622 763 0 880 763 606 699 622 0 881 763 847 788 622 0 882 606 553 622 763 0 883 655 743 587 704 0 884 704 655 507 587 0 885 788 622 587 704 0 886 704 553 622 587 0 887 704 788 743 587 0 888 553 507 587 704 0 889 616 717 573 655 0 890 655 616 481 573 0 891 743 587 573 655 0 892 655 507 587 573 0 893 655 743 717 573 0 894 507 481 573 655 0 895 468 481 616 573 0 896 573 717 616 468 0 897 608 616 717 468 0 898 468 608 705 717 0 899 468 555 573 717 0 900 555 705 717 468 0 901 1217 1245 1190 1268 0 902 1268 1217 1150 1190 0 903 1288 1252 1190 1268 0 904 1268 1219 1252 1190 0 905 1268 1288 1245 1190 0 906 1219 1150 1190 1268 0 907 1151 1189 1111 1217 0 908 1217 1151 1066 1111 0 909 1245 1190 1111 1217 0 910 1217 1150 1190 1111 0 911 1217 1245 1189 1111 0 912 1150 1066 1111 1217 0 913 1081 1136 1035 1151 0 914 1151 1081 973 1035 0 915 1189 1111 1035 1151 0 916 1151 1066 1111 1035 0 917 1151 1189 1136 1035 0 918 1066 973 1035 1151 0 919 996 1060 957 1081 0 920 1081 996 876 957 0 921 1136 1035 957 1081 0 922 1081 973 1035 957 0 923 1081 1136 1060 957 0 924 973 876 957 1081 0 925 919 997 872 996 0 926 996 919 779 872 0 927 1060 957 872 996 0 928 996 876 957 872 0 929 996 1060 997 872 0 930 876 779 872 996 0 931 847 930 800 919 0 932 919 847 699 800 0 933 997 872 800 919 0 934 919 779 872 800 0 935 919 997 930 800 0 936 779 699 800 919 0 937 788 880 729 847 0 938 847 788 622 729 0 939 930 800 729 847 0 940 847 699 800 729 0 941 847 930 880 729 0 942 699 622 729 847 0 943 743 836 688 788 0 944 788 743 587 688 0 945 880 729 688 788 0 946 788 622 729 688 0 947 788 880 836 688 0 948 622 587 688 788 0 949 717 826 656 743 0 950 743 717 573 656 0 951 836 688 656 743 0 952 743 587 688 656 0 953 743 836 826 656 0 954 587 573 656 743 0 955 555 573 717 656 0 956 656 826 717 555 0 957 705 717 826 555 0 958 555 705 804 826 0 959 555 642 656 826 0 960 642 804 826 555 0 961 1245 1276 1234 1288 0 962 1288 1245 1190 1234 0 963 1305 1279 1234 1288 0 964 1288 1252 1279 1234 0 965 1288 1305 1276 1234 0 966 1252 1190 1234 1288 0 967 1189 1232 1170 1245 0 968 1245 1189 1111 1170 0 969 1276 1234 1170 1245 0 970 1245 1190 1234 1170 0 971 1245 1276 1232 1170 0 972 1190 1111 1170 1245 0 973 1136 1178 1106 1189 0 974 1189 1136 1035 1106 0 975 1232 1170 1106 1189 0 976 1189 1111 1170 1106 0 977 1189 1232 1178 1106 0 978 1111 1035 1106 1189 0 979 1060 1133 1043 1136 0 980 1136 1060 957 1043 0 981 1178 1106 1043 1136 0 982 1136 1035 1106 1043 0 983 1136 1178 1133 1043 0 984 1035 957 1043 1136 0 985 997 1080 969 1060 0 986 1060 997 872 969 0 987 1133 1043 969 1060 0 988 1060 957 1043 969 0 989 1060 1133 1080 969 0 990 957 872 969 1060 0 991 930 1017 905 997 0 992 997 930 800 905 0 993 1080 969 905 997 0 994 997 872 969 905 0 995 997 1080 1017 905 0 996 872 800 905 997 0 997 880 976 846 930 0 998 930 880 729 846 0 999 1017 905 846 930 0 1000 930 800 905 846 0 1001 930 1017 976 846 0 1002 800 729 846 930 0 1003 836 940 819 880 0 1004 880 836 688 819 0 1005 976 846 819 880 0 1006 880 729 846 819 0 1007 880 976 940 819 0 1008 729 688 819 880 0 1009 826 918 778 836 0 1010 836 826 656 778 0 1011 940 819 778 836 0 1012 836 688 819 778 0 1013 836 940 918 778 0 1014 688 656 778 836 0 1015 642 656 826 778 0 1016 778 918 826 642 0 1017 804 826 918 642 0 1018 642 804 909 918 0 1019 642 768 778 918 0 1020 768 909 918 642 0 1021 1276 1299 1270 1305 0 1022 1305 1276 1234 1270 0 1023 1314 1301 1270 1305 0 1024 1305 1279 1301 1270 0 1025 1305 1314 1299 1270 0 1026 1279 1234 1270 1305 0 1027 1232 1274 1230 1276 0 1028 1276 1232 1170 1230 0 1029 1299 1270 1230 1276 0 1030 1276 1234 1270 1230 0 1031 1276 1299 1274 1230 0 1032 1234 1170 1230 1276 0 1033 1178 1233 1172 1232 0 1034 1232 1178 1106 1172 0 1035 1274 1230 1172 1232 0 1036 1232 1170 1230 1172 0 1037 1232 1274 1233 1172 0 1038 1170 1106 1172 1232 0 1039 1133 1194 1117 1178 0 1040 1178 1133 1043 1117 0 1041 1233 1172 1117 1178 0 1042 1178 1106 1172 1117 0 1043 1178 1233 1194 1117 0 1044 1106 1043 1117 1178 0 1045 1080 1147 1070 1133 0 1046 1133 1080 969 1070 0 1047 1194 1117 1070 1133 0 1048 1133 1043 1117 1070 0 1049 1133 1194 1147 1070 0 1050 1043 969 1070 1133 0 1051 1017 1099 1000 1080 0 1052 1080 1017 905 1000 0 1053 1147 1070 1000 1080 0 1054 1080 969 1070 1000 0 1055 1080 1147 1099 1000 0 1056 969 905 1000 1080 0 1057 976 1073 964 1017 0 1058 1017 976 846 964 0 1059 1099 1000 964 1017 0 1060 1017 905 1000 964 0 1061 1017 1099 1073 964 0 1062 905 846 964 1017 0 1063 940 1039 927 976 0 1064 976 940 819 927 0 1065 1073 964 927 976 0 1066 976 846 964 927 0 1067 976 1073 1039 927 0 1068 846 819 927 976 0 1069 918 1023 903 940 0 1070 940 918 778 903 0 1071 1039 927 903 940 0 1072 940 819 927 903 0 1073 940 1039 1023 903 0 1074 819 778 903 940 0 1075 768 778 918 903 0 1076 903 1023 918 768 0 1077 909 918 1023 768 0 1078 768 909 1006 1023 0 1079 768 892 903 1023 0 1080 892 1006 1023 768 0 1081 1299 1312 1297 1314 0 1082 1314 1299 1270 1297 0 1083 1323 1313 1297 1314 0 1084 1314 1301 1313 1297 0 1085 1314 1323 1312 1297 0 1086 1301 1270 1297 1314 0 1087 1274 1298 1271 1299 0 1088 1299 1274 1230 1271 0 1089 1312 1297 1271 1299 0 1090 1299 1270 1297 1271 0 1091 1299 1312 1298 1271 0 1092 1270 1230 1271 1299 0 1093 1233 1277 1236 1274 0 1094 1274 1233 1172 1236 0 1095 1298 1271 1236 1274 0 1096 1274 1230 1271 1236 0 1097 1274 1298 1277 1236 0 1098 1230 1172 1236 1274 0 1099 1194 1248 1191 1233 0 1100 1233 1194 1117 1191 0 1101 1277 1236 1191 1233 0 1102 1233 1172 1236 1191 0 1103 1233 1277 1248 1191 0 1104 1172 1117 1191 1233 0 1105 1147 1215 1149 1194 0 1106 1194 1147 1070 1149 0 1107 1248 1191 1149 1194 0 1108 1194 1117 1191 1149 0 1109 1194 1248 1215 1149 0 1110 1117 1070 1149 1194 0 1111 1099 1173 1100 1147 0 1112 1147 1099 1000 1100 0 1113 1215 1149 1100 1147 0 1114 1147 1070 1149 1100 0 1115 1147 1215 1173 1100 0 1116 1070 1000 1100 1147 0 1117 1073 1152 1075 1099 0 1118 1099 1073 964 1075 0 1119 1173 1100 1075 1099 0 1120 1099 1000 1100 1075 0 1121 1099 1173 1152 1075 0 1122 1000 964 1075 1099 0 1123 1039 1131 1036 1073 0 1124 1073 1039 927 1036 0 1125 1152 1075 1036 1073 0 1126 1073 964 1075 1036 0 1127 1073 1152 1131 1036 0 1128 964 927 1036 1073 0 1129 1023 1107 1020 1039 0 1130 1039 1023 903 1020 0 1131 1131 1036 1020 1039 0 1132 1039 927 1036 1020 0 1133 1039 1131 1107 1020 0 1134 927 903 1020 1039 0 1135 892 903 1023 1020 0 1136 1020 1107 1023 892 0 1137 1006 1023 1107 892 0 1138 892 1006 1102 1107 0 1139 892 1011 1020 1107 0 1140 1011 1102 1107 892 0 1141 1313 1325 1329 1297 0 1142 1297 1313 1323 1329 0 1143 1318 1324 1329 1297 0 1144 1297 1312 1324 1329 0 1145 1297 1318 1325 1329 0 1146 1312 1323 1329 1297 0 1147 1297 1318 1324 1271 0 1148 1271 1297 1312 1324 0 1149 1300 1316 1324 1271 0 1150 1271 1298 1316 1324 0 1151 1271 1300 1318 1324 0 1152 1298 1312 1324 1271 0 1153 1271 1300 1316 1236 0 1154 1236 1271 1298 1316 0 1155 1284 1307 1316 1236 0 1156 1236 1277 1307 1316 0 1157 1236 1284 1300 1316 0 1158 1277 1298 1316 1236 0 1159 1236 1284 1307 1191 0 1160 1191 1236 1277 1307 0 1161 1255 1289 1307 1191 0 1162 1191 1248 1289 1307 0 1163 1191 1255 1284 1307 0 1164 1248 1277 1307 1191 0 1165 1191 1255 1289 1149 0 1166 1149 1191 1248 1289 0 1167 1223 1267 1289 1149 0 1168 1149 1215 1267 1289 0 1169 1149 1223 1255 1289 0 1170 1215 1248 1289 1149 0 1171 1149 1223 1267 1100 0 1172 1100 1149 1215 1267 0 1173 1183 1238 1267 1100 0 1174 1100 1173 1238 1267 0 1175 1100 1183 1223 1267 0 1176 1173 1215 1267 1100 0 1177 1100 1183 1238 1075 0 1178 1075 1100 1173 1238 0 1179 1159 1226 1238 1075 0 1180 1075 1152 1226 1238 0 1181 1075 1159 1183 1238 0 1182 1152 1173 1238 1075 0 1183 1075 1159 1226 1036 0 1184 1036 1075 1152 1226 0 1185 1144 1209 1226 1036 0 1186 1036 1131 1209 1226 0 1187 1036 1144 1159 1226 0 1188 1131 1152 1226 1036 0 1189 1036 1144 1209 1020 0 1190 1020 1036 1131 1209 0 1191 1125 1197 1209 1020 0 1192 1020 1107 1197 1209 0 1193 1020 1125 1144 1209 0 1194 1107 1131 1209 1020 0 1195 1113 1125 1020 1197 0 1196 1197 1107 1020 1113 0 1197 1011 1020 1107 1113 0 1198 1113 1011 1102 1107 0 1199 1113 1192 1197 1107 0 1200 1192 1102 1107 1113 0 1201 1007 1022 921 1112 0 1202 1112 1007 911 921 0 1203 1124 1052 921 1112 0 1204 1112 1032 1052 921 0 1205 1112 1124 1022 921 0 1206 1032 911 921 1112 0 1207 890 904 780 1007 0 1208 1007 890 765 780 0 1209 1022 921 780 1007 0 1210 1007 911 921 780 0 1211 1007 1022 904 780 0 1212 911 765 780 1007 0 1213 772 782 634 890 0 1214 890 772 617 634 0 1215 904 780 634 890 0 1216 890 765 780 634 0 1217 890 904 782 634 0 1218 765 617 634 890 0 1219 646 671 527 772 0 1220 772 646 512 527 0 1221 782 634 527 772 0 1222 772 617 634 527 0 1223 772 782 671 527 0 1224 617 512 527 772 0 1225 559 575 441 646 0 1226 646 559 427 441 0 1227 671 527 441 646 0 1228 646 512 527 441 0 1229 646 671 575 441 0 1230 512 427 441 646 0 1231 470 485 366 559 0 1232 559 470 352 366 0 1233 575 441 366 559 0 1234 559 427 441 366 0 1235 559 575 485 366 0 1236 427 352 366 559 0 1237 414 432 311 470 0 1238 470 414 303 311 0 1239 485 366 311 470 0 1240 470 352 366 311 0 1241 470 485 432 311 0 1242 352 303 311 470 0 1243 384 397 279 414 0 1244 414 384 271 279 0 1245 432 311 279 414 0 1246 414 303 311 279 0 1247 414 432 397 279 0 1248 303 271 279 414 0 1249 360 368 255 384 0 1250 384 360 243 255 0 1251 397 279 255 384 0 1252 384 271 279 255 0 1253 384 397 368 255 0 1254 271 243 255 384 0 1255 236 243 360 255 0 1256 255 368 360 236 0 1257 344 360 368 236 0 1258 236 344 354 368 0 1259 236 247 255 368 0 1260 247 354 368 236 0 1261 1022 1042 943 1124 0 1262 1124 1022 921 943 0 1263 1141 1065 943 1124 0 1264 1124 1052 1065 943 0 1265 1124 1141 1042 943 0 1266 1052 921 943 1124 0 1267 904 924 815 1022 0 1268 1022 904 780 815 0 1269 1042 943 815 1022 0 1270 1022 921 943 815 0 1271 1022 1042 924 815 0 1272 921 780 815 1022 0 1273 782 818 674 904 0 1274 904 782 634 674 0 1275 924 815 674 904 0 1276 904 780 815 674 0 1277 904 924 818 674 0 1278 780 634 674 904 0 1279 671 690 541 782 0 1280 782 671 527 541 0 1281 818 674 541 782 0 1282 782 634 674 541 0 1283 782 818 690 541 0 1284 634 527 541 782 0 1285 575 589 463 671 0 1286 671 575 441 463 0 1287 690 541 463 671 0 1288 671 527 541 463 0 1289 671 690 589 463 0 1290 527 441 463 671 0 1291 485 510 388 575 0 1292 575 485 366 388 0 1293 589 463 388 575 0 1294 575 441 463 388 0 1295 575 589 510 388 0 1296 441 366 388 575 0 1297 432 453 331 485 0 1298 485 432 311 331 0 1299 510 388 331 485 0 1300 485 366 388 331 0 1301 485 510 453 331 0 1302 366 311 331 485 0 1303 397 410 298 432 0 1304 432 397 279 298 0 1305 453 331 298 432 0 1306 432 311 331 298 0 1307 432 453 410 298 0 1308 311 279 298 432 0 1309 368 396 280 397 0 1310 397 368 255 280 0 1311 410 298 280 397 0 1312 397 279 298 280 0 1313 397 410 396 280 0 1314 279 255 280 397 0 1315 247 255 368 280 0 1316 280 396 368 247 0 1317 354 368 396 247 0 1318 247 354 383 396 0 1319 247 272 280 396 0 1320 272 383 396 247 0 1321 1042 1074 977 1141 0 1322 1141 1042 943 977 0 1323 1160 1086 977 1141 0 1324 1141 1065 1086 977 0 1325 1141 1160 1074 977 0 1326 1065 943 977 1141 0 1327 924 965 851 1042 0 1328 1042 924 815 851 0 1329 1074 977 851 1042 0 1330 1042 943 977 851 0 1331 1042 1074 965 851 0 1332 943 815 851 1042 0 1333 818 855 716 924 0 1334 924 818 674 716 0 1335 965 851 716 924 0 1336 924 815 851 716 0 1337 924 965 855 716 0 1338 815 674 716 924 0 1339 690 739 593 818 0 1340 818 690 541 593 0 1341 855 716 593 818 0 1342 818 674 716 593 0 1343 818 855 739 593 0 1344 674 541 593 818 0 1345 589 625 499 690 0 1346 690 589 463 499 0 1347 739 593 499 690 0 1348 690 541 593 499 0 1349 690 739 625 499 0 1350 541 463 499 690 0 1351 510 560 425 589 0 1352 589 510 388 425 0 1353 625 499 425 589 0 1354 589 463 499 425 0 1355 589 625 560 425 0 1356 463 388 425 589 0 1357 453 491 375 510 0 1358 510 453 331 375 0 1359 560 425 375 510 0 1360 510 388 425 375 0 1361 510 560 491 375 0 1362 388 331 375 510 0 1363 410 456 332 453 0 1364 453 410 298 332 0 1365 491 375 332 453 0 1366 453 331 375 332 0 1367 453 491 456 332 0 1368 331 298 332 453 0 1369 396 428 310 410 0 1370 410 396 280 310 0 1371 456 332 310 410 0 1372 410 298 332 310 0 1373 410 456 428 310 0 1374 298 280 310 410 0 1375 272 280 396 310 0 1376 310 428 396 272 0 1377 383 396 428 272 0 1378 272 383 417 428 0 1379 272 306 310 428 0 1380 306 417 428 272 0 1381 1074 1098 1015 1160 0 1382 1160 1074 977 1015 0 1383 1182 1129 1015 1160 0 1384 1160 1086 1129 1015 0 1385 1160 1182 1098 1015 0 1386 1086 977 1015 1160 0 1387 965 999 897 1074 0 1388 1074 965 851 897 0 1389 1098 1015 897 1074 0 1390 1074 977 1015 897 0 1391 1074 1098 999 897 0 1392 977 851 897 1074 0 1393 855 907 776 965 0 1394 965 855 716 776 0 1395 999 897 776 965 0 1396 965 851 897 776 0 1397 965 999 907 776 0 1398 851 716 776 965 0 1399 739 801 654 855 0 1400 855 739 593 654 0 1401 907 776 654 855 0 1402 855 716 776 654 0 1403 855 907 801 654 0 1404 716 593 654 855 0 1405 625 701 569 739 0 1406 739 625 499 569 0 1407 801 654 569 739 0 1408 739 593 654 569 0 1409 739 801 701 569 0 1410 593 499 569 739 0 1411 560 606 475 625 0 1412 625 560 425 475 0 1413 701 569 475 625 0 1414 625 499 569 475 0 1415 625 701 606 475 0 1416 499 425 475 625 0 1417 491 553 423 560 0 1418 560 491 375 423 0 1419 606 475 423 560 0 1420 560 425 475 423 0 1421 560 606 553 423 0 1422 425 375 423 560 0 1423 456 507 389 491 0 1424 491 456 332 389 0 1425 553 423 389 491 0 1426 491 375 423 389 0 1427 491 553 507 389 0 1428 375 332 389 491 0 1429 428 481 367 456 0 1430 456 428 310 367 0 1431 507 389 367 456 0 1432 456 332 389 367 0 1433 456 507 481 367 0 1434 332 310 367 456 0 1435 306 310 428 367 0 1436 367 481 428 306 0 1437 417 428 481 306 0 1438 306 417 468 481 0 1439 306 346 367 481 0 1440 346 468 481 306 0 1441 1098 1150 1082 1182 0 1442 1182 1098 1015 1082 0 1443 1219 1169 1082 1182 0 1444 1182 1129 1169 1082 0 1445 1182 1219 1150 1082 0 1446 1129 1015 1082 1182 0 1447 999 1066 972 1098 0 1448 1098 999 897 972 0 1449 1150 1082 972 1098 0 1450 1098 1015 1082 972 0 1451 1098 1150 1066 972 0 1452 1015 897 972 1098 0 1453 907 973 858 999 0 1454 999 907 776 858 0 1455 1066 972 858 999 0 1456 999 897 972 858 0 1457 999 1066 973 858 0 1458 897 776 858 999 0 1459 801 876 741 907 0 1460 907 801 654 741 0 1461 973 858 741 907 0 1462 907 776 858 741 0 1463 907 973 876 741 0 1464 776 654 741 907 0 1465 701 779 637 801 0 1466 801 701 569 637 0 1467 876 741 637 801 0 1468 801 654 741 637 0 1469 801 876 779 637 0 1470 654 569 637 801 0 1471 606 699 568 701 0 1472 701 606 475 568 0 1473 779 637 568 701 0 1474 701 569 637 568 0 1475 701 779 699 568 0 1476 569 475 568 701 0 1477 553 622 496 606 0 1478 606 553 423 496 0 1479 699 568 496 606 0 1480 606 475 568 496 0 1481 606 699 622 496 0 1482 475 423 496 606 0 1483 507 587 461 553 0 1484 553 507 389 461 0 1485 622 496 461 553 0 1486 553 423 496 461 0 1487 553 622 587 461 0 1488 423 389 461 553 0 1489 481 573 439 507 0 1490 507 481 367 439 0 1491 587 461 439 507 0 1492 507 389 461 439 0 1493 507 587 573 439 0 1494 389 367 439 507 0 1495 346 367 481 439 0 1496 439 573 481 346 0 1497 468 481 573 346 0 1498 346 468 555 573 0 1499 346 429 439 573 0 1500 429 555 573 346 0 1501 1150 1190 1135 1219 0 1502 1219 1150 1082 1135 0 1503 1252 1214 1135 1219 0 1504 1219 1169 1214 1135 0 1505 1219 1252 1190 1135 0 1506 1169 1082 1135 1219 0 1507 1066 1111 1041 1150 0 1508 1150 1066 972 1041 0 1509 1190 1135 1041 1150 0 1510 1150 1082 1135 1041 0 1511 1150 1190 1111 1041 0 1512 1082 972 1041 1150 0 1513 973 1035 939 1066 0 1514 1066 973 858 939 0 1515 1111 1041 939 1066 0 1516 1066 972 1041 939 0 1517 1066 1111 1035 939 0 1518 972 858 939 1066 0 1519 876 957 837 973 0 1520 973 876 741 837 0 1521 1035 939 837 973 0 1522 973 858 939 837 0 1523 973 1035 957 837 0 1524 858 741 837 973 0 1525 779 872 754 876 0 1526 876 779 637 754 0 1527 957 837 754 876 0 1528 876 741 837 754 0 1529 876 957 872 754 0 1530 741 637 754 876 0 1531 699 800 652 779 0 1532 779 699 568 652 0 1533 872 754 652 779 0 1534 779 637 754 652 0 1535 779 872 800 652 0 1536 637 568 652 779 0 1537 622 729 595 699 0 1538 699 622 496 595 0 1539 800 652 595 699 0 1540 699 568 652 595 0 1541 699 800 729 595 0 1542 568 496 595 699 0 1543 587 688 548 622 0 1544 622 587 461 548 0 1545 729 595 548 622 0 1546 622 496 595 548 0 1547 622 729 688 548 0 1548 496 461 548 622 0 1549 573 656 530 587 0 1550 587 573 439 530 0 1551 688 548 530 587 0 1552 587 461 548 530 0 1553 587 688 656 530 0 1554 461 439 530 587 0 1555 429 439 573 530 0 1556 530 656 573 429 0 1557 555 573 656 429 0 1558 429 555 642 656 0 1559 429 516 530 656 0 1560 516 642 656 429 0 1561 1190 1234 1177 1252 0 1562 1252 1190 1135 1177 0 1563 1279 1246 1177 1252 0 1564 1252 1214 1246 1177 0 1565 1252 1279 1234 1177 0 1566 1214 1135 1177 1252 0 1567 1111 1170 1103 1190 0 1568 1190 1111 1041 1103 0 1569 1234 1177 1103 1190 0 1570 1190 1135 1177 1103 0 1571 1190 1234 1170 1103 0 1572 1135 1041 1103 1190 0 1573 1035 1106 1025 1111 0 1574 1111 1035 939 1025 0 1575 1170 1103 1025 1111 0 1576 1111 1041 1103 1025 0 1577 1111 1170 1106 1025 0 1578 1041 939 1025 1111 0 1579 957 1043 936 1035 0 1580 1035 957 837 936 0 1581 1106 1025 936 1035 0 1582 1035 939 1025 936 0 1583 1035 1106 1043 936 0 1584 939 837 936 1035 0 1585 872 969 859 957 0 1586 957 872 754 859 0 1587 1043 936 859 957 0 1588 957 837 936 859 0 1589 957 1043 969 859 0 1590 837 754 859 957 0 1591 800 905 774 872 0 1592 872 800 652 774 0 1593 969 859 774 872 0 1594 872 754 859 774 0 1595 872 969 905 774 0 1596 754 652 774 872 0 1597 729 846 715 800 0 1598 800 729 595 715 0 1599 905 774 715 800 0 1600 800 652 774 715 0 1601 800 905 846 715 0 1602 652 595 715 800 0 1603 688 819 676 729 0 1604 729 688 548 676 0 1605 846 715 676 729 0 1606 729 595 715 676 0 1607 729 846 819 676 0 1608 595 548 676 729 0 1609 656 778 636 688 0 1610 688 656 530 636 0 1611 819 676 636 688 0 1612 688 548 676 636 0 1613 688 819 778 636 0 1614 548 530 636 688 0 1615 516 530 656 636 0 1616 636 778 656 516 0 1617 642 656 778 516 0 1618 516 642 768 778 0 1619 516 618 636 778 0 1620 618 768 778 516 0 1621 1234 1270 1231 1279 0 1622 1279 1234 1177 1231 0 1623 1301 1283 1231 1279 0 1624 1279 1246 1283 1231 0 1625 1279 1301 1270 1231 0 1626 1246 1177 1231 1279 0 1627 1170 1230 1171 1234 0 1628 1234 1170 1103 1171 0 1629 1270 1231 1171 1234 0 1630 1234 1177 1231 1171 0 1631 1234 1270 1230 1171 0 1632 1177 1103 1171 1234 0 1633 1106 1172 1101 1170 0 1634 1170 1106 1025 1101 0 1635 1230 1171 1101 1170 0 1636 1170 1103 1171 1101 0 1637 1170 1230 1172 1101 0 1638 1103 1025 1101 1170 0 1639 1043 1117 1027 1106 0 1640 1106 1043 936 1027 0 1641 1172 1101 1027 1106 0 1642 1106 1025 1101 1027 0 1643 1106 1172 1117 1027 0 1644 1025 936 1027 1106 0 1645 969 1070 968 1043 0 1646 1043 969 859 968 0 1647 1117 1027 968 1043 0 1648 1043 936 1027 968 0 1649 1043 1117 1070 968 0 1650 936 859 968 1043 0 1651 905 1000 893 969 0 1652 969 905 774 893 0 1653 1070 968 893 969 0 1654 969 859 968 893 0 1655 969 1070 1000 893 0 1656 859 774 893 969 0 1657 846 964 848 905 0 1658 905 846 715 848 0 1659 1000 893 848 905 0 1660 905 774 893 848 0 1661 905 1000 964 848 0 1662 774 715 848 905 0 1663 819 927 811 846 0 1664 846 819 676 811 0 1665 964 848 811 846 0 1666 846 715 848 811 0 1667 846 964 927 811 0 1668 715 676 811 846 0 1669 778 903 775 819 0 1670 819 778 636 775 0 1671 927 811 775 819 0 1672 819 676 811 775 0 1673 819 927 903 775 0 1674 676 636 775 819 0 1675 618 636 778 775 0 1676 775 903 778 618 0 1677 768 778 903 618 0 1678 618 768 892 903 0 1679 618 759 775 903 0 1680 759 892 903 618 0 1681 1270 1297 1278 1301 0 1682 1301 1270 1231 1278 0 1683 1313 1308 1278 1301 0 1684 1301 1283 1308 1278 0 1685 1301 1313 1297 1278 0 1686 1283 1231 1278 1301 0 1687 1230 1271 1235 1270 0 1688 1270 1230 1171 1235 0 1689 1297 1278 1235 1270 0 1690 1270 1231 1278 1235 0 1691 1270 1297 1271 1235 0 1692 1231 1171 1235 1270 0 1693 1172 1236 1176 1230 0 1694 1230 1172 1101 1176 0 1695 1271 1235 1176 1230 0 1696 1230 1171 1235 1176 0 1697 1230 1271 1236 1176 0 1698 1171 1101 1176 1230 0 1699 1117 1191 1132 1172 0 1700 1172 1117 1027 1132 0 1701 1236 1176 1132 1172 0 1702 1172 1101 1176 1132 0 1703 1172 1236 1191 1132 0 1704 1101 1027 1132 1172 0 1705 1070 1149 1078 1117 0 1706 1117 1070 968 1078 0 1707 1191 1132 1078 1117 0 1708 1117 1027 1132 1078 0 1709 1117 1191 1149 1078 0 1710 1027 968 1078 1117 0 1711 1000 1100 1013 1070 0 1712 1070 1000 893 1013 0 1713 1149 1078 1013 1070 0 1714 1070 968 1078 1013 0 1715 1070 1149 1100 1013 0 1716 968 893 1013 1070 0 1717 964 1075 975 1000 0 1718 1000 964 848 975 0 1719 1100 1013 975 1000 0 1720 1000 893 1013 975 0 1721 1000 1100 1075 975 0 1722 893 848 975 1000 0 1723 927 1036 935 964 0 1724 964 927 811 935 0 1725 1075 975 935 964 0 1726 964 848 975 935 0 1727 964 1075 1036 935 0 1728 848 811 935 964 0 1729 903 1020 914 927 0 1730 927 903 775 914 0 1731 1036 935 914 927 0 1732 927 811 935 914 0 1733 927 1036 1020 914 0 1734 811 775 914 927 0 1735 759 775 903 914 0 1736 914 1020 903 759 0 1737 892 903 1020 759 0 1738 759 892 1011 1020 0 1739 759 908 914 1020 0 1740 908 1011 1020 759 0 1741 1308 1320 1325 1278 0 1742 1278 1308 1313 1325 0 1743 1306 1318 1325 1278 0 1744 1278 1297 1318 1325 0 1745 1278 1306 1320 1325 0 1746 1297 1313 1325 1278 0 1747 1278 1306 1318 1235 0 1748 1235 1278 1297 1318 0 1749 1282 1300 1318 1235 0 1750 1235 1271 1300 1318 0 1751 1235 1282 1306 1318 0 1752 1271 1297 1318 1235 0 1753 1235 1282 1300 1176 0 1754 1176 1235 1271 1300 0 1755 1243 1284 1300 1176 0 1756 1176 1236 1284 1300 0 1757 1176 1243 1282 1300 0 1758 1236 1271 1300 1176 0 1759 1176 1243 1284 1132 0 1760 1132 1176 1236 1284 0 1761 1203 1255 1284 1132 0 1762 1132 1191 1255 1284 0 1763 1132 1203 1243 1284 0 1764 1191 1236 1284 1132 0 1765 1132 1203 1255 1078 0 1766 1078 1132 1191 1255 0 1767 1167 1223 1255 1078 0 1768 1078 1149 1223 1255 0 1769 1078 1167 1203 1255 0 1770 1149 1191 1255 1078 0 1771 1078 1167 1223 1013 0 1772 1013 1078 1149 1223 0 1773 1119 1183 1223 1013 0 1774 1013 1100 1183 1223 0 1775 1013 1119 1167 1223 0 1776 1100 1149 1223 1013 0 1777 1013 1119 1183 975 0 1778 975 1013 1100 1183 0 1779 1083 1159 1183 975 0 1780 975 1075 1159 1183 0 1781 975 1083 1119 1183 0 1782 1075 1100 1183 975 0 1783 975 1083 1159 935 0 1784 935 975 1075 1159 0 1785 1059 1144 1159 935 0 1786 935 1036 1144 1159 0 1787 935 1059 1083 1159 0 1788 1036 1075 1159 935 0 1789 935 1059 1144 914 0 1790 914 935 1036 1144 0 1791 1048 1125 1144 914 0 1792 914 1020 1125 1144 0 1793 914 1048 1059 1144 0 1794 1020 1036 1144 914 0 1795 1030 1048 914 1125 0 1796 1125 1020 914 1030 0 1797 908 914 1020 1030 0 1798 1030 908 1011 1020 0 1799 1030 1113 1125 1020 0 1800 1113 1011 1020 1030 0 1801 911 921 829 1032 0 1802 1032 911 813 829 0 1803 1052 959 829 1032 0 1804 1032 955 959 829 0 1805 1032 1052 921 829 0 1806 955 813 829 1032 0 1807 765 780 672 911 0 1808 911 765 647 672 0 1809 921 829 672 911 0 1810 911 813 829 672 0 1811 911 921 780 672 0 1812 813 647 672 911 0 1813 617 634 532 765 0 1814 765 617 520 532 0 1815 780 672 532 765 0 1816 765 647 672 532 0 1817 765 780 634 532 0 1818 647 520 532 765 0 1819 512 527 415 617 0 1820 617 512 406 415 0 1821 634 532 415 617 0 1822 617 520 532 415 0 1823 617 634 527 415 0 1824 520 406 415 617 0 1825 427 441 339 512 0 1826 512 427 326 339 0 1827 527 415 339 512 0 1828 512 406 415 339 0 1829 512 527 441 339 0 1830 406 326 339 512 0 1831 352 366 278 427 0 1832 427 352 262 278 0 1833 441 339 278 427 0 1834 427 326 339 278 0 1835 427 441 366 278 0 1836 326 262 278 427 0 1837 303 311 228 352 0 1838 352 303 215 228 0 1839 366 278 228 352 0 1840 352 262 278 228 0 1841 352 366 311 228 0 1842 262 215 228 352 0 1843 271 279 191 303 0 1844 303 271 183 191 0 1845 311 228 191 303 0 1846 303 215 228 191 0 1847 303 311 279 191 0 1848 215 183 191 303 0 1849 243 255 174 271 0 1850 271 243 165 174 0 1851 279 191 174 271 0 1852 271 183 191 174 0 1853 271 279 255 174 0 1854 183 165 174 271 0 1855 161 165 243 174 0 1856 174 255 243 161 0 1857 236 243 255 161 0 1858 161 236 247 255 0 1859 161 168 174 255 0 1860 168 247 255 161 0 1861 921 943 844 1052 0 1862 1052 921 829 844 0 1863 1065 983 844 1052 0 1864 1052 959 983 844 0 1865 1052 1065 943 844 0 1866 959 829 844 1052 0 1867 780 815 687 921 0 1868 921 780 672 687 0 1869 943 844 687 921 0 1870 921 829 844 687 0 1871 921 943 815 687 0 1872 829 672 687 921 0 1873 634 674 545 780 0 1874 780 634 532 545 0 1875 815 687 545 780 0 1876 780 672 687 545 0 1877 780 815 674 545 0 1878 672 532 545 780 0 1879 527 541 445 634 0 1880 634 527 415 445 0 1881 674 545 445 634 0 1882 634 532 545 445 0 1883 634 674 541 445 0 1884 532 415 445 634 0 1885 441 463 355 527 0 1886 527 441 339 355 0 1887 541 445 355 527 0 1888 527 415 445 355 0 1889 527 541 463 355 0 1890 415 339 355 527 0 1891 366 388 295 441 0 1892 441 366 278 295 0 1893 463 355 295 441 0 1894 441 339 355 295 0 1895 441 463 388 295 0 1896 339 278 295 441 0 1897 311 331 232 366 0 1898 366 311 228 232 0 1899 388 295 232 366 0 1900 366 278 295 232 0 1901 366 388 331 232 0 1902 278 228 232 366 0 1903 279 298 209 311 0 1904 311 279 191 209 0 1905 331 232 209 311 0 1906 311 228 232 209 0 1907 311 331 298 209 0 1908 228 191 209 311 0 1909 255 280 188 279 0 1910 279 255 174 188 0 1911 298 209 188 279 0 1912 279 191 209 188 0 1913 279 298 280 188 0 1914 191 174 188 279 0 1915 168 174 255 188 0 1916 188 280 255 168 0 1917 247 255 280 168 0 1918 168 247 272 280 0 1919 168 179 188 280 0 1920 179 272 280 168 0 1921 943 977 889 1065 0 1922 1065 943 844 889 0 1923 1086 1005 889 1065 0 1924 1065 983 1005 889 0 1925 1065 1086 977 889 0 1926 983 844 889 1065 0 1927 815 851 738 943 0 1928 943 815 687 738 0 1929 977 889 738 943 0 1930 943 844 889 738 0 1931 943 977 851 738 0 1932 844 687 738 943 0 1933 674 716 602 815 0 1934 815 674 545 602 0 1935 851 738 602 815 0 1936 815 687 738 602 0 1937 815 851 716 602 0 1938 687 545 602 815 0 1939 541 593 476 674 0 1940 674 541 445 476 0 1941 716 602 476 674 0 1942 674 545 602 476 0 1943 674 716 593 476 0 1944 545 445 476 674 0 1945 463 499 403 541 0 1946 541 463 355 403 0 1947 593 476 403 541 0 1948 541 445 476 403 0 1949 541 593 499 403 0 1950 445 355 403 541 0 1951 388 425 329 463 0 1952 463 388 295 329 0 1953 499 403 329 463 0 1954 463 355 403 329 0 1955 463 499 425 329 0 1956 355 295 329 463 0 1957 331 375 282 388 0 1958 388 331 232 282 0 1959 425 329 282 388 0 1960 388 295 329 282 0 1961 388 425 375 282 0 1962 295 232 282 388 0 1963 298 332 234 331 0 1964 331 298 209 234 0 1965 375 282 234 331 0 1966 331 232 282 234 0 1967 331 375 332 234 0 1968 232 209 234 331 0 1969 280 310 229 298 0 1970 298 280 188 229 0 1971 332 234 229 298 0 1972 298 209 234 229 0 1973 298 332 310 229 0 1974 209 188 229 298 0 1975 179 188 280 229 0 1976 229 310 280 179 0 1977 272 280 310 179 0 1978 179 272 306 310 0 1979 179 212 229 310 0 1980 212 306 310 179 0 1981 977 1015 932 1086 0 1982 1086 977 889 932 0 1983 1129 1056 932 1086 0 1984 1086 1005 1056 932 0 1985 1086 1129 1015 932 0 1986 1005 889 932 1086 0 1987 851 897 802 977 0 1988 977 851 738 802 0 1989 1015 932 802 977 0 1990 977 889 932 802 0 1991 977 1015 897 802 0 1992 889 738 802 977 0 1993 716 776 670 851 0 1994 851 716 602 670 0 1995 897 802 670 851 0 1996 851 738 802 670 0 1997 851 897 776 670 0 1998 738 602 670 851 0 1999 593 654 539 716 0 2000 716 593 476 539 0 2001 776 670 539 716 0 2002 716 602 670 539 0 2003 716 776 654 539 0 2004 602 476 539 716 0 2005 499 569 454 593 0 2006 593 499 403 454 0 2007 654 539 454 593 0 2008 593 476 539 454 0 2009 593 654 569 454 0 2010 476 403 454 593 0 2011 425 475 382 499 0 2012 499 425 329 382 0 2013 569 454 382 499 0 2014 499 403 454 382 0 2015 499 569 475 382 0 2016 403 329 382 499 0 2017 375 423 328 425 0 2018 425 375 282 328 0 2019 475 382 328 425 0 2020 425 329 382 328 0 2021 425 475 423 328 0 2022 329 282 328 425 0 2023 332 389 294 375 0 2024 375 332 234 294 0 2025 423 328 294 375 0 2026 375 282 328 294 0 2027 375 423 389 294 0 2028 282 234 294 375 0 2029 310 367 274 332 0 2030 332 310 229 274 0 2031 389 294 274 332 0 2032 332 234 294 274 0 2033 332 389 367 274 0 2034 234 229 274 332 0 2035 212 229 310 274 0 2036 274 367 310 212 0 2037 306 310 367 212 0 2038 212 306 346 367 0 2039 212 265 274 367 0 2040 265 346 367 212 0 2041 1015 1082 994 1129 0 2042 1129 1015 932 994 0 2043 1169 1089 994 1129 0 2044 1129 1056 1089 994 0 2045 1129 1169 1082 994 0 2046 1056 932 994 1129 0 2047 897 972 875 1015 0 2048 1015 897 802 875 0 2049 1082 994 875 1015 0 2050 1015 932 994 875 0 2051 1015 1082 972 875 0 2052 932 802 875 1015 0 2053 776 858 749 897 0 2054 897 776 670 749 0 2055 972 875 749 897 0 2056 897 802 875 749 0 2057 897 972 858 749 0 2058 802 670 749 897 0 2059 654 741 607 776 0 2060 776 654 539 607 0 2061 858 749 607 776 0 2062 776 670 749 607 0 2063 776 858 741 607 0 2064 670 539 607 776 0 2065 569 637 531 654 0 2066 654 569 454 531 0 2067 741 607 531 654 0 2068 654 539 607 531 0 2069 654 741 637 531 0 2070 539 454 531 654 0 2071 475 568 455 569 0 2072 569 475 382 455 0 2073 637 531 455 569 0 2074 569 454 531 455 0 2075 569 637 568 455 0 2076 454 382 455 569 0 2077 423 496 399 475 0 2078 475 423 328 399 0 2079 568 455 399 475 0 2080 475 382 455 399 0 2081 475 568 496 399 0 2082 382 328 399 475 0 2083 389 461 345 423 0 2084 423 389 294 345 0 2085 496 399 345 423 0 2086 423 328 399 345 0 2087 423 496 461 345 0 2088 328 294 345 423 0 2089 367 439 336 389 0 2090 389 367 274 336 0 2091 461 345 336 389 0 2092 389 294 345 336 0 2093 389 461 439 336 0 2094 294 274 336 389 0 2095 265 274 367 336 0 2096 336 439 367 265 0 2097 346 367 439 265 0 2098 265 346 429 439 0 2099 265 319 336 439 0 2100 319 429 439 265 0 2101 1082 1135 1067 1169 0 2102 1169 1082 994 1067 0 2103 1214 1156 1067 1169 0 2104 1169 1089 1156 1067 0 2105 1169 1214 1135 1067 0 2106 1089 994 1067 1169 0 2107 972 1041 958 1082 0 2108 1082 972 875 958 0 2109 1135 1067 958 1082 0 2110 1082 994 1067 958 0 2111 1082 1135 1041 958 0 2112 994 875 958 1082 0 2113 858 939 839 972 0 2114 972 858 749 839 0 2115 1041 958 839 972 0 2116 972 875 958 839 0 2117 972 1041 939 839 0 2118 875 749 839 972 0 2119 741 837 725 858 0 2120 858 741 607 725 0 2121 939 839 725 858 0 2122 858 749 839 725 0 2123 858 939 837 725 0 2124 749 607 725 858 0 2125 637 754 614 741 0 2126 741 637 531 614 0 2127 837 725 614 741 0 2128 741 607 725 614 0 2129 741 837 754 614 0 2130 607 531 614 741 0 2131 568 652 540 637 0 2132 637 568 455 540 0 2133 754 614 540 637 0 2134 637 531 614 540 0 2135 637 754 652 540 0 2136 531 455 540 637 0 2137 496 595 473 568 0 2138 568 496 399 473 0 2139 652 540 473 568 0 2140 568 455 540 473 0 2141 568 652 595 473 0 2142 455 399 473 568 0 2143 461 548 447 496 0 2144 496 461 345 447 0 2145 595 473 447 496 0 2146 496 399 473 447 0 2147 496 595 548 447 0 2148 399 345 447 496 0 2149 439 530 413 461 0 2150 461 439 336 413 0 2151 548 447 413 461 0 2152 461 345 447 413 0 2153 461 548 530 413 0 2154 345 336 413 461 0 2155 319 336 439 413 0 2156 413 530 439 319 0 2157 429 439 530 319 0 2158 319 429 516 530 0 2159 319 407 413 530 0 2160 407 516 530 319 0 2161 1135 1177 1137 1214 0 2162 1214 1135 1067 1137 0 2163 1246 1206 1137 1214 0 2164 1214 1156 1206 1137 0 2165 1214 1246 1177 1137 0 2166 1156 1067 1137 1214 0 2167 1041 1103 1038 1135 0 2168 1135 1041 958 1038 0 2169 1177 1137 1038 1135 0 2170 1135 1067 1137 1038 0 2171 1135 1177 1103 1038 0 2172 1067 958 1038 1135 0 2173 939 1025 937 1041 0 2174 1041 939 839 937 0 2175 1103 1038 937 1041 0 2176 1041 958 1038 937 0 2177 1041 1103 1025 937 0 2178 958 839 937 1041 0 2179 837 936 843 939 0 2180 939 837 725 843 0 2181 1025 937 843 939 0 2182 939 839 937 843 0 2183 939 1025 936 843 0 2184 839 725 843 939 0 2185 754 859 742 837 0 2186 837 754 614 742 0 2187 936 843 742 837 0 2188 837 725 843 742 0 2189 837 936 859 742 0 2190 725 614 742 837 0 2191 652 774 668 754 0 2192 754 652 540 668 0 2193 859 742 668 754 0 2194 754 614 742 668 0 2195 754 859 774 668 0 2196 614 540 668 754 0 2197 595 715 601 652 0 2198 652 595 473 601 0 2199 774 668 601 652 0 2200 652 540 668 601 0 2201 652 774 715 601 0 2202 540 473 601 652 0 2203 548 676 552 595 0 2204 595 548 447 552 0 2205 715 601 552 595 0 2206 595 473 601 552 0 2207 595 715 676 552 0 2208 473 447 552 595 0 2209 530 636 533 548 0 2210 548 530 413 533 0 2211 676 552 533 548 0 2212 548 447 552 533 0 2213 548 676 636 533 0 2214 447 413 533 548 0 2215 407 413 530 533 0 2216 533 636 530 407 0 2217 516 530 636 407 0 2218 407 516 618 636 0 2219 407 517 533 636 0 2220 517 618 636 407 0 2221 1177 1231 1195 1246 0 2222 1246 1177 1137 1195 0 2223 1283 1257 1195 1246 0 2224 1246 1206 1257 1195 0 2225 1246 1283 1231 1195 0 2226 1206 1137 1195 1246 0 2227 1103 1171 1118 1177 0 2228 1177 1103 1038 1118 0 2229 1231 1195 1118 1177 0 2230 1177 1137 1195 1118 0 2231 1177 1231 1171 1118 0 2232 1137 1038 1118 1177 0 2233 1025 1101 1040 1103 0 2234 1103 1025 937 1040 0 2235 1171 1118 1040 1103 0 2236 1103 1038 1118 1040 0 2237 1103 1171 1101 1040 0 2238 1038 937 1040 1103 0 2239 936 1027 956 1025 0 2240 1025 936 843 956 0 2241 1101 1040 956 1025 0 2242 1025 937 1040 956 0 2243 1025 1101 1027 956 0 2244 937 843 956 1025 0 2245 859 968 877 936 0 2246 936 859 742 877 0 2247 1027 956 877 936 0 2248 936 843 956 877 0 2249 936 1027 968 877 0 2250 843 742 877 936 0 2251 774 893 792 859 0 2252 859 774 668 792 0 2253 968 877 792 859 0 2254 859 742 877 792 0 2255 859 968 893 792 0 2256 742 668 792 859 0 2257 715 848 737 774 0 2258 774 715 601 737 0 2259 893 792 737 774 0 2260 774 668 792 737 0 2261 774 893 848 737 0 2262 668 601 737 774 0 2263 676 811 679 715 0 2264 715 676 552 679 0 2265 848 737 679 715 0 2266 715 601 737 679 0 2267 715 848 811 679 0 2268 601 552 679 715 0 2269 636 775 650 676 0 2270 676 636 533 650 0 2271 811 679 650 676 0 2272 676 552 679 650 0 2273 676 811 775 650 0 2274 552 533 650 676 0 2275 517 533 636 650 0 2276 650 775 636 517 0 2277 618 636 775 517 0 2278 517 618 759 775 0 2279 517 640 650 775 0 2280 640 759 775 517 0 2281 1231 1278 1247 1283 0 2282 1283 1231 1195 1247 0 2283 1308 1290 1247 1283 0 2284 1283 1257 1290 1247 0 2285 1283 1308 1278 1247 0 2286 1257 1195 1247 1283 0 2287 1171 1235 1196 1231 0 2288 1231 1171 1118 1196 0 2289 1278 1247 1196 1231 0 2290 1231 1195 1247 1196 0 2291 1231 1278 1235 1196 0 2292 1195 1118 1196 1231 0 2293 1101 1176 1139 1171 0 2294 1171 1101 1040 1139 0 2295 1235 1196 1139 1171 0 2296 1171 1118 1196 1139 0 2297 1171 1235 1176 1139 0 2298 1118 1040 1139 1171 0 2299 1027 1132 1068 1101 0 2300 1101 1027 956 1068 0 2301 1176 1139 1068 1101 0 2302 1101 1040 1139 1068 0 2303 1101 1176 1132 1068 0 2304 1040 956 1068 1101 0 2305 968 1078 995 1027 0 2306 1027 968 877 995 0 2307 1132 1068 995 1027 0 2308 1027 956 1068 995 0 2309 1027 1132 1078 995 0 2310 956 877 995 1027 0 2311 893 1013 933 968 0 2312 968 893 792 933 0 2313 1078 995 933 968 0 2314 968 877 995 933 0 2315 968 1078 1013 933 0 2316 877 792 933 968 0 2317 848 975 878 893 0 2318 893 848 737 878 0 2319 1013 933 878 893 0 2320 893 792 933 878 0 2321 893 1013 975 878 0 2322 792 737 878 893 0 2323 811 935 838 848 0 2324 848 811 679 838 0 2325 975 878 838 848 0 2326 848 737 878 838 0 2327 848 975 935 838 0 2328 737 679 838 848 0 2329 775 914 822 811 0 2330 811 775 650 822 0 2331 935 838 822 811 0 2332 811 679 838 822 0 2333 811 935 914 822 0 2334 679 650 822 811 0 2335 640 650 775 822 0 2336 822 914 775 640 0 2337 759 775 914 640 0 2338 640 759 908 914 0 2339 640 805 822 914 0 2340 805 908 914 640 0 2341 1290 1310 1320 1247 0 2342 1247 1290 1308 1320 0 2343 1292 1306 1320 1247 0 2344 1247 1278 1306 1320 0 2345 1247 1292 1310 1320 0 2346 1278 1308 1320 1247 0 2347 1247 1292 1306 1196 0 2348 1196 1247 1278 1306 0 2349 1253 1282 1306 1196 0 2350 1196 1235 1282 1306 0 2351 1196 1253 1292 1306 0 2352 1235 1278 1306 1196 0 2353 1196 1253 1282 1139 0 2354 1139 1196 1235 1282 0 2355 1210 1243 1282 1139 0 2356 1139 1176 1243 1282 0 2357 1139 1210 1253 1282 0 2358 1176 1235 1282 1139 0 2359 1139 1210 1243 1068 0 2360 1068 1139 1176 1243 0 2361 1157 1203 1243 1068 0 2362 1068 1132 1203 1243 0 2363 1068 1157 1210 1243 0 2364 1132 1176 1243 1068 0 2365 1068 1157 1203 995 0 2366 995 1068 1132 1203 0 2367 1095 1167 1203 995 0 2368 995 1078 1167 1203 0 2369 995 1095 1157 1203 0 2370 1078 1132 1203 995 0 2371 995 1095 1167 933 0 2372 933 995 1078 1167 0 2373 1054 1119 1167 933 0 2374 933 1013 1119 1167 0 2375 933 1054 1095 1167 0 2376 1013 1078 1167 933 0 2377 933 1054 1119 878 0 2378 878 933 1013 1119 0 2379 1004 1083 1119 878 0 2380 878 975 1083 1119 0 2381 878 1004 1054 1119 0 2382 975 1013 1119 878 0 2383 878 1004 1083 838 0 2384 838 878 975 1083 0 2385 984 1059 1083 838 0 2386 838 935 1059 1083 0 2387 838 984 1004 1083 0 2388 935 975 1083 838 0 2389 838 984 1059 822 0 2390 822 838 935 1059 0 2391 961 1048 1059 822 0 2392 822 914 1048 1059 0 2393 822 961 984 1059 0 2394 914 935 1059 822 0 2395 950 961 822 1048 0 2396 1048 914 822 950 0 2397 805 822 914 950 0 2398 950 805 908 914 0 2399 950 1030 1048 914 0 2400 1030 908 914 950 0 2401 813 829 719 955 0 2402 955 813 710 719 0 2403 959 884 719 955 0 2404 955 866 884 719 0 2405 955 959 829 719 0 2406 866 710 719 955 0 2407 647 672 578 813 0 2408 813 647 556 578 0 2409 829 719 578 813 0 2410 813 710 719 578 0 2411 813 829 672 578 0 2412 710 556 578 813 0 2413 520 532 440 647 0 2414 647 520 426 440 0 2415 672 578 440 647 0 2416 647 556 578 440 0 2417 647 672 532 440 0 2418 556 426 440 647 0 2419 406 415 334 520 0 2420 520 406 322 334 0 2421 532 440 334 520 0 2422 520 426 440 334 0 2423 520 532 415 334 0 2424 426 322 334 520 0 2425 326 339 259 406 0 2426 406 326 253 259 0 2427 415 334 259 406 0 2428 406 322 334 259 0 2429 406 415 339 259 0 2430 322 253 259 406 0 2431 262 278 205 326 0 2432 326 262 199 205 0 2433 339 259 205 326 0 2434 326 253 259 205 0 2435 326 339 278 205 0 2436 253 199 205 326 0 2437 215 228 156 262 0 2438 262 215 150 156 0 2439 278 205 156 262 0 2440 262 199 205 156 0 2441 262 278 228 156 0 2442 199 150 156 262 0 2443 183 191 132 215 0 2444 215 183 124 132 0 2445 228 156 132 215 0 2446 215 150 156 132 0 2447 215 228 191 132 0 2448 150 124 132 215 0 2449 165 174 114 183 0 2450 183 165 110 114 0 2451 191 132 114 183 0 2452 183 124 132 114 0 2453 183 191 174 114 0 2454 124 110 114 183 0 2455 93 110 165 114 0 2456 114 174 165 93 0 2457 161 165 174 93 0 2458 93 161 168 174 0 2459 93 106 114 174 0 2460 106 168 174 93 0 2461 829 844 752 959 0 2462 959 829 719 752 0 2463 983 900 752 959 0 2464 959 884 900 752 0 2465 959 983 844 752 0 2466 884 719 752 959 0 2467 672 687 590 829 0 2468 829 672 578 590 0 2469 844 752 590 829 0 2470 829 719 752 590 0 2471 829 844 687 590 0 2472 719 578 590 829 0 2473 532 545 464 672 0 2474 672 532 440 464 0 2475 687 590 464 672 0 2476 672 578 590 464 0 2477 672 687 545 464 0 2478 578 440 464 672 0 2479 415 445 351 532 0 2480 532 415 334 351 0 2481 545 464 351 532 0 2482 532 440 464 351 0 2483 532 545 445 351 0 2484 440 334 351 532 0 2485 339 355 290 415 0 2486 415 339 259 290 0 2487 445 351 290 415 0 2488 415 334 351 290 0 2489 415 445 355 290 0 2490 334 259 290 415 0 2491 278 295 222 339 0 2492 339 278 205 222 0 2493 355 290 222 339 0 2494 339 259 290 222 0 2495 339 355 295 222 0 2496 259 205 222 339 0 2497 228 232 176 278 0 2498 278 228 156 176 0 2499 295 222 176 278 0 2500 278 205 222 176 0 2501 278 295 232 176 0 2502 205 156 176 278 0 2503 191 209 142 228 0 2504 228 191 132 142 0 2505 232 176 142 228 0 2506 228 156 176 142 0 2507 228 232 209 142 0 2508 156 132 142 228 0 2509 174 188 130 191 0 2510 191 174 114 130 0 2511 209 142 130 191 0 2512 191 132 142 130 0 2513 191 209 188 130 0 2514 132 114 130 191 0 2515 106 114 174 130 0 2516 130 188 174 106 0 2517 168 174 188 106 0 2518 106 168 179 188 0 2519 106 122 130 188 0 2520 122 179 188 106 0 2521 844 889 790 983 0 2522 983 844 752 790 0 2523 1005 945 790 983 0 2524 983 900 945 790 0 2525 983 1005 889 790 0 2526 900 752 790 983 0 2527 687 738 628 844 0 2528 844 687 590 628 0 2529 889 790 628 844 0 2530 844 752 790 628 0 2531 844 889 738 628 0 2532 752 590 628 844 0 2533 545 602 500 687 0 2534 687 545 464 500 0 2535 738 628 500 687 0 2536 687 590 628 500 0 2537 687 738 602 500 0 2538 590 464 500 687 0 2539 445 476 401 545 0 2540 545 445 351 401 0 2541 602 500 401 545 0 2542 545 464 500 401 0 2543 545 602 476 401 0 2544 464 351 401 545 0 2545 355 403 317 445 0 2546 445 355 290 317 0 2547 476 401 317 445 0 2548 445 351 401 317 0 2549 445 476 403 317 0 2550 351 290 317 445 0 2551 295 329 254 355 0 2552 355 295 222 254 0 2553 403 317 254 355 0 2554 355 290 317 254 0 2555 355 403 329 254 0 2556 290 222 254 355 0 2557 232 282 208 295 0 2558 295 232 176 208 0 2559 329 254 208 295 0 2560 295 222 254 208 0 2561 295 329 282 208 0 2562 222 176 208 295 0 2563 209 234 178 232 0 2564 232 209 142 178 0 2565 282 208 178 232 0 2566 232 176 208 178 0 2567 232 282 234 178 0 2568 176 142 178 232 0 2569 188 229 157 209 0 2570 209 188 130 157 0 2571 234 178 157 209 0 2572 209 142 178 157 0 2573 209 234 229 157 0 2574 142 130 157 209 0 2575 122 130 188 157 0 2576 157 229 188 122 0 2577 179 188 229 122 0 2578 122 179 212 229 0 2579 122 147 157 229 0 2580 147 212 229 122 0 2581 889 932 852 1005 0 2582 1005 889 790 852 0 2583 1056 986 852 1005 0 2584 1005 945 986 852 0 2585 1005 1056 932 852 0 2586 945 790 852 1005 0 2587 738 802 697 889 0 2588 889 738 628 697 0 2589 932 852 697 889 0 2590 889 790 852 697 0 2591 889 932 802 697 0 2592 790 628 697 889 0 2593 602 670 571 738 0 2594 738 602 500 571 0 2595 802 697 571 738 0 2596 738 628 697 571 0 2597 738 802 670 571 0 2598 628 500 571 738 0 2599 476 539 450 602 0 2600 602 476 401 450 0 2601 670 571 450 602 0 2602 602 500 571 450 0 2603 602 670 539 450 0 2604 500 401 450 602 0 2605 403 454 371 476 0 2606 476 403 317 371 0 2607 539 450 371 476 0 2608 476 401 450 371 0 2609 476 539 454 371 0 2610 401 317 371 476 0 2611 329 382 302 403 0 2612 403 329 254 302 0 2613 454 371 302 403 0 2614 403 317 371 302 0 2615 403 454 382 302 0 2616 317 254 302 403 0 2617 282 328 252 329 0 2618 329 282 208 252 0 2619 382 302 252 329 0 2620 329 254 302 252 0 2621 329 382 328 252 0 2622 254 208 252 329 0 2623 234 294 219 282 0 2624 282 234 178 219 0 2625 328 252 219 282 0 2626 282 208 252 219 0 2627 282 328 294 219 0 2628 208 178 219 282 0 2629 229 274 203 234 0 2630 234 229 157 203 0 2631 294 219 203 234 0 2632 234 178 219 203 0 2633 234 294 274 203 0 2634 178 157 203 234 0 2635 147 157 229 203 0 2636 203 274 229 147 0 2637 212 229 274 147 0 2638 147 212 265 274 0 2639 147 193 203 274 0 2640 193 265 274 147 0 2641 932 994 916 1056 0 2642 1056 932 852 916 0 2643 1089 1046 916 1056 0 2644 1056 986 1046 916 0 2645 1056 1089 994 916 0 2646 986 852 916 1056 0 2647 802 875 781 932 0 2648 932 802 697 781 0 2649 994 916 781 932 0 2650 932 852 916 781 0 2651 932 994 875 781 0 2652 852 697 781 932 0 2653 670 749 635 802 0 2654 802 670 571 635 0 2655 875 781 635 802 0 2656 802 697 781 635 0 2657 802 875 749 635 0 2658 697 571 635 802 0 2659 539 607 524 670 0 2660 670 539 450 524 0 2661 749 635 524 670 0 2662 670 571 635 524 0 2663 670 749 607 524 0 2664 571 450 524 670 0 2665 454 531 443 539 0 2666 539 454 371 443 0 2667 607 524 443 539 0 2668 539 450 524 443 0 2669 539 607 531 443 0 2670 450 371 443 539 0 2671 382 455 370 454 0 2672 454 382 302 370 0 2673 531 443 370 454 0 2674 454 371 443 370 0 2675 454 531 455 370 0 2676 371 302 370 454 0 2677 328 399 314 382 0 2678 382 328 252 314 0 2679 455 370 314 382 0 2680 382 302 370 314 0 2681 382 455 399 314 0 2682 302 252 314 382 0 2683 294 345 288 328 0 2684 328 294 219 288 0 2685 399 314 288 328 0 2686 328 252 314 288 0 2687 328 399 345 288 0 2688 252 219 288 328 0 2689 274 336 258 294 0 2690 294 274 203 258 0 2691 345 288 258 294 0 2692 294 219 288 258 0 2693 294 345 336 258 0 2694 219 203 258 294 0 2695 193 203 274 258 0 2696 258 336 274 193 0 2697 265 274 336 193 0 2698 193 265 319 336 0 2699 193 245 258 336 0 2700 245 319 336 193 0 2701 994 1067 993 1089 0 2702 1089 994 916 993 0 2703 1156 1093 993 1089 0 2704 1089 1046 1093 993 0 2705 1089 1156 1067 993 0 2706 1046 916 993 1089 0 2707 875 958 874 994 0 2708 994 875 781 874 0 2709 1067 993 874 994 0 2710 994 916 993 874 0 2711 994 1067 958 874 0 2712 916 781 874 994 0 2713 749 839 748 875 0 2714 875 749 635 748 0 2715 958 874 748 875 0 2716 875 781 874 748 0 2717 875 958 839 748 0 2718 781 635 748 875 0 2719 607 725 610 749 0 2720 749 607 524 610 0 2721 839 748 610 749 0 2722 749 635 748 610 0 2723 749 839 725 610 0 2724 635 524 610 749 0 2725 531 614 534 607 0 2726 607 531 443 534 0 2727 725 610 534 607 0 2728 607 524 610 534 0 2729 607 725 614 534 0 2730 524 443 534 607 0 2731 455 540 452 531 0 2732 531 455 370 452 0 2733 614 534 452 531 0 2734 531 443 534 452 0 2735 531 614 540 452 0 2736 443 370 452 531 0 2737 399 473 400 455 0 2738 455 399 314 400 0 2739 540 452 400 455 0 2740 455 370 452 400 0 2741 455 540 473 400 0 2742 370 314 400 455 0 2743 345 447 358 399 0 2744 399 345 288 358 0 2745 473 400 358 399 0 2746 399 314 400 358 0 2747 399 473 447 358 0 2748 314 288 358 399 0 2749 336 413 333 345 0 2750 345 336 258 333 0 2751 447 358 333 345 0 2752 345 288 358 333 0 2753 345 447 413 333 0 2754 288 258 333 345 0 2755 245 258 336 333 0 2756 333 413 336 245 0 2757 319 336 413 245 0 2758 245 319 407 413 0 2759 245 325 333 413 0 2760 325 407 413 245 0 2761 1067 1137 1077 1156 0 2762 1156 1067 993 1077 0 2763 1206 1164 1077 1156 0 2764 1156 1093 1164 1077 0 2765 1156 1206 1137 1077 0 2766 1093 993 1077 1156 0 2767 958 1038 970 1067 0 2768 1067 958 874 970 0 2769 1137 1077 970 1067 0 2770 1067 993 1077 970 0 2771 1067 1137 1038 970 0 2772 993 874 970 1067 0 2773 839 937 857 958 0 2774 958 839 748 857 0 2775 1038 970 857 958 0 2776 958 874 970 857 0 2777 958 1038 937 857 0 2778 874 748 857 958 0 2779 725 843 740 839 0 2780 839 725 610 740 0 2781 937 857 740 839 0 2782 839 748 857 740 0 2783 839 937 843 740 0 2784 748 610 740 839 0 2785 614 742 639 725 0 2786 725 614 534 639 0 2787 843 740 639 725 0 2788 725 610 740 639 0 2789 725 843 742 639 0 2790 610 534 639 725 0 2791 540 668 562 614 0 2792 614 540 452 562 0 2793 742 639 562 614 0 2794 614 534 639 562 0 2795 614 742 668 562 0 2796 534 452 562 614 0 2797 473 601 498 540 0 2798 540 473 400 498 0 2799 668 562 498 540 0 2800 540 452 562 498 0 2801 540 668 601 498 0 2802 452 400 498 540 0 2803 447 552 460 473 0 2804 473 447 358 460 0 2805 601 498 460 473 0 2806 473 400 498 460 0 2807 473 601 552 460 0 2808 400 358 460 473 0 2809 413 533 438 447 0 2810 447 413 333 438 0 2811 552 460 438 447 0 2812 447 358 460 438 0 2813 447 552 533 438 0 2814 358 333 438 447 0 2815 325 333 413 438 0 2816 438 533 413 325 0 2817 407 413 533 325 0 2818 325 407 517 533 0 2819 325 420 438 533 0 2820 420 517 533 325 0 2821 1137 1195 1148 1206 0 2822 1206 1137 1077 1148 0 2823 1257 1221 1148 1206 0 2824 1206 1164 1221 1148 0 2825 1206 1257 1195 1148 0 2826 1164 1077 1148 1206 0 2827 1038 1118 1069 1137 0 2828 1137 1038 970 1069 0 2829 1195 1148 1069 1137 0 2830 1137 1077 1148 1069 0 2831 1137 1195 1118 1069 0 2832 1077 970 1069 1137 0 2833 937 1040 971 1038 0 2834 1038 937 857 971 0 2835 1118 1069 971 1038 0 2836 1038 970 1069 971 0 2837 1038 1118 1040 971 0 2838 970 857 971 1038 0 2839 843 956 862 937 0 2840 937 843 740 862 0 2841 1040 971 862 937 0 2842 937 857 971 862 0 2843 937 1040 956 862 0 2844 857 740 862 937 0 2845 742 877 784 843 0 2846 843 742 639 784 0 2847 956 862 784 843 0 2848 843 740 862 784 0 2849 843 956 877 784 0 2850 740 639 784 843 0 2851 668 792 702 742 0 2852 742 668 562 702 0 2853 877 784 702 742 0 2854 742 639 784 702 0 2855 742 877 792 702 0 2856 639 562 702 742 0 2857 601 737 627 668 0 2858 668 601 498 627 0 2859 792 702 627 668 0 2860 668 562 702 627 0 2861 668 792 737 627 0 2862 562 498 627 668 0 2863 552 679 591 601 0 2864 601 552 460 591 0 2865 737 627 591 601 0 2866 601 498 627 591 0 2867 601 737 679 591 0 2868 498 460 591 601 0 2869 533 650 579 552 0 2870 552 533 438 579 0 2871 679 591 579 552 0 2872 552 460 591 579 0 2873 552 679 650 579 0 2874 460 438 579 552 0 2875 420 438 533 579 0 2876 579 650 533 420 0 2877 517 533 650 420 0 2878 420 517 640 650 0 2879 420 554 579 650 0 2880 554 640 650 420 0 2881 1195 1247 1216 1257 0 2882 1257 1195 1148 1216 0 2883 1290 1266 1216 1257 0 2884 1257 1221 1266 1216 0 2885 1257 1290 1247 1216 0 2886 1221 1148 1216 1257 0 2887 1118 1196 1146 1195 0 2888 1195 1118 1069 1146 0 2889 1247 1216 1146 1195 0 2890 1195 1148 1216 1146 0 2891 1195 1247 1196 1146 0 2892 1148 1069 1146 1195 0 2893 1040 1139 1079 1118 0 2894 1118 1040 971 1079 0 2895 1196 1146 1079 1118 0 2896 1118 1069 1146 1079 0 2897 1118 1196 1139 1079 0 2898 1069 971 1079 1118 0 2899 956 1068 992 1040 0 2900 1040 956 862 992 0 2901 1139 1079 992 1040 0 2902 1040 971 1079 992 0 2903 1040 1139 1068 992 0 2904 971 862 992 1040 0 2905 877 995 922 956 0 2906 956 877 784 922 0 2907 1068 992 922 956 0 2908 956 862 992 922 0 2909 956 1068 995 922 0 2910 862 784 922 956 0 2911 792 933 850 877 0 2912 877 792 702 850 0 2913 995 922 850 877 0 2914 877 784 922 850 0 2915 877 995 933 850 0 2916 784 702 850 877 0 2917 737 878 786 792 0 2918 792 737 627 786 0 2919 933 850 786 792 0 2920 792 702 850 786 0 2921 792 933 878 786 0 2922 702 627 786 792 0 2923 679 838 753 737 0 2924 737 679 591 753 0 2925 878 786 753 737 0 2926 737 627 786 753 0 2927 737 878 838 753 0 2928 627 591 753 737 0 2929 650 822 718 679 0 2930 679 650 579 718 0 2931 838 753 718 679 0 2932 679 591 753 718 0 2933 679 838 822 718 0 2934 591 579 718 679 0 2935 554 579 650 718 0 2936 718 822 650 554 0 2937 640 650 822 554 0 2938 554 640 805 822 0 2939 554 707 718 822 0 2940 707 805 822 554 0 2941 1266 1296 1310 1216 0 2942 1216 1266 1290 1310 0 2943 1269 1292 1310 1216 0 2944 1216 1247 1292 1310 0 2945 1216 1269 1296 1310 0 2946 1247 1290 1310 1216 0 2947 1216 1269 1292 1146 0 2948 1146 1216 1247 1292 0 2949 1222 1253 1292 1146 0 2950 1146 1196 1253 1292 0 2951 1146 1222 1269 1292 0 2952 1196 1247 1292 1146 0 2953 1146 1222 1253 1079 0 2954 1079 1146 1196 1253 0 2955 1168 1210 1253 1079 0 2956 1079 1139 1210 1253 0 2957 1079 1168 1222 1253 0 2958 1139 1196 1253 1079 0 2959 1079 1168 1210 992 0 2960 992 1079 1139 1210 0 2961 1092 1157 1210 992 0 2962 992 1068 1157 1210 0 2963 992 1092 1168 1210 0 2964 1068 1139 1210 992 0 2965 992 1092 1157 922 0 2966 922 992 1068 1157 0 2967 1051 1095 1157 922 0 2968 922 995 1095 1157 0 2969 922 1051 1092 1157 0 2970 995 1068 1157 922 0 2971 922 1051 1095 850 0 2972 850 922 995 1095 0 2973 988 1054 1095 850 0 2974 850 933 1054 1095 0 2975 850 988 1051 1095 0 2976 933 995 1095 850 0 2977 850 988 1054 786 0 2978 786 850 933 1054 0 2979 942 1004 1054 786 0 2980 786 878 1004 1054 0 2981 786 942 988 1054 0 2982 878 933 1054 786 0 2983 786 942 1004 753 0 2984 753 786 878 1004 0 2985 895 984 1004 753 0 2986 753 838 984 1004 0 2987 753 895 942 1004 0 2988 838 878 1004 753 0 2989 753 895 984 718 0 2990 718 753 838 984 0 2991 887 961 984 718 0 2992 718 822 961 984 0 2993 718 887 895 984 0 2994 822 838 984 718 0 2995 864 887 718 961 0 2996 961 822 718 864 0 2997 707 718 822 864 0 2998 864 707 805 822 0 2999 864 950 961 822 0 3000 950 805 822 864 0 3001 710 719 619 866 0 3002 866 710 612 619 0 3003 884 814 619 866 0 3004 866 791 814 619 0 3005 866 884 719 619 0 3006 791 612 619 866 0 3007 556 578 484 710 0 3008 710 556 469 484 0 3009 719 619 484 710 0 3010 710 612 619 484 0 3011 710 719 578 484 0 3012 612 469 484 710 0 3013 426 440 364 556 0 3014 556 426 349 364 0 3015 578 484 364 556 0 3016 556 469 484 364 0 3017 556 578 440 364 0 3018 469 349 364 556 0 3019 322 334 268 426 0 3020 426 322 261 268 0 3021 440 364 268 426 0 3022 426 349 364 268 0 3023 426 440 334 268 0 3024 349 261 268 426 0 3025 253 259 201 322 0 3026 322 253 197 201 0 3027 334 268 201 322 0 3028 322 261 268 201 0 3029 322 334 259 201 0 3030 261 197 201 322 0 3031 199 205 137 253 0 3032 253 199 134 137 0 3033 259 201 137 253 0 3034 253 197 201 137 0 3035 253 259 205 137 0 3036 197 134 137 253 0 3037 150 156 103 199 0 3038 199 150 92 103 0 3039 205 137 103 199 0 3040 199 134 137 103 0 3041 199 205 156 103 0 3042 134 92 103 199 0 3043 124 132 80 150 0 3044 150 124 78 80 0 3045 156 103 80 150 0 3046 150 92 103 80 0 3047 150 156 132 80 0 3048 92 78 80 150 0 3049 110 114 64 124 0 3050 124 110 56 64 0 3051 132 80 64 124 0 3052 124 78 80 64 0 3053 124 132 114 64 0 3054 78 56 64 124 0 3055 54 56 110 64 0 3056 64 114 110 54 0 3057 93 110 114 54 0 3058 54 93 106 114 0 3059 54 57 64 114 0 3060 57 106 114 54 0 3061 719 752 657 884 0 3062 884 719 619 657 0 3063 900 832 657 884 0 3064 884 814 832 657 0 3065 884 900 752 657 0 3066 814 619 657 884 0 3067 578 590 508 719 0 3068 719 578 484 508 0 3069 752 657 508 719 0 3070 719 619 657 508 0 3071 719 752 590 508 0 3072 619 484 508 719 0 3073 440 464 390 578 0 3074 578 440 364 390 0 3075 590 508 390 578 0 3076 578 484 508 390 0 3077 578 590 464 390 0 3078 484 364 390 578 0 3079 334 351 293 440 0 3080 440 334 268 293 0 3081 464 390 293 440 0 3082 440 364 390 293 0 3083 440 464 351 293 0 3084 364 268 293 440 0 3085 259 290 214 334 0 3086 334 259 201 214 0 3087 351 293 214 334 0 3088 334 268 293 214 0 3089 334 351 290 214 0 3090 268 201 214 334 0 3091 205 222 158 259 0 3092 259 205 137 158 0 3093 290 214 158 259 0 3094 259 201 214 158 0 3095 259 290 222 158 0 3096 201 137 158 259 0 3097 156 176 121 205 0 3098 205 156 103 121 0 3099 222 158 121 205 0 3100 205 137 158 121 0 3101 205 222 176 121 0 3102 137 103 121 205 0 3103 132 142 90 156 0 3104 156 132 80 90 0 3105 176 121 90 156 0 3106 156 103 121 90 0 3107 156 176 142 90 0 3108 103 80 90 156 0 3109 114 130 79 132 0 3110 132 114 64 79 0 3111 142 90 79 132 0 3112 132 80 90 79 0 3113 132 142 130 79 0 3114 80 64 79 132 0 3115 57 64 114 79 0 3116 79 130 114 57 0 3117 106 114 130 57 0 3118 57 106 122 130 0 3119 57 75 79 130 0 3120 75 122 130 57 0 3121 752 790 706 900 0 3122 900 752 657 706 0 3123 945 868 706 900 0 3124 900 832 868 706 0 3125 900 945 790 706 0 3126 832 657 706 900 0 3127 590 628 558 752 0 3128 752 590 508 558 0 3129 790 706 558 752 0 3130 752 657 706 558 0 3131 752 790 628 558 0 3132 657 508 558 752 0 3133 464 500 424 590 0 3134 590 464 390 424 0 3135 628 558 424 590 0 3136 590 508 558 424 0 3137 590 628 500 424 0 3138 508 390 424 590 0 3139 351 401 321 464 0 3140 464 351 293 321 0 3141 500 424 321 464 0 3142 464 390 424 321 0 3143 464 500 401 321 0 3144 390 293 321 464 0 3145 290 317 250 351 0 3146 351 290 214 250 0 3147 401 321 250 351 0 3148 351 293 321 250 0 3149 351 401 317 250 0 3150 293 214 250 351 0 3151 222 254 186 290 0 3152 290 222 158 186 0 3153 317 250 186 290 0 3154 290 214 250 186 0 3155 290 317 254 186 0 3156 214 158 186 290 0 3157 176 208 148 222 0 3158 222 176 121 148 0 3159 254 186 148 222 0 3160 222 158 186 148 0 3161 222 254 208 148 0 3162 158 121 148 222 0 3163 142 178 126 176 0 3164 176 142 90 126 0 3165 208 148 126 176 0 3166 176 121 148 126 0 3167 176 208 178 126 0 3168 121 90 126 176 0 3169 130 157 101 142 0 3170 142 130 79 101 0 3171 178 126 101 142 0 3172 142 90 126 101 0 3173 142 178 157 101 0 3174 90 79 101 142 0 3175 75 79 130 101 0 3176 101 157 130 75 0 3177 122 130 157 75 0 3178 75 122 147 157 0 3179 75 97 101 157 0 3180 97 147 157 75 0 3181 790 852 760 945 0 3182 945 790 706 760 0 3183 986 925 760 945 0 3184 945 868 925 760 0 3185 945 986 852 760 0 3186 868 706 760 945 0 3187 628 697 605 790 0 3188 790 628 558 605 0 3189 852 760 605 790 0 3190 790 706 760 605 0 3191 790 852 697 605 0 3192 706 558 605 790 0 3193 500 571 474 628 0 3194 628 500 424 474 0 3195 697 605 474 628 0 3196 628 558 605 474 0 3197 628 697 571 474 0 3198 558 424 474 628 0 3199 401 450 380 500 0 3200 500 401 321 380 0 3201 571 474 380 500 0 3202 500 424 474 380 0 3203 500 571 450 380 0 3204 424 321 380 500 0 3205 317 371 300 401 0 3206 401 317 250 300 0 3207 450 380 300 401 0 3208 401 321 380 300 0 3209 401 450 371 300 0 3210 321 250 300 401 0 3211 254 302 230 317 0 3212 317 254 186 230 0 3213 371 300 230 317 0 3214 317 250 300 230 0 3215 317 371 302 230 0 3216 250 186 230 317 0 3217 208 252 192 254 0 3218 254 208 148 192 0 3219 302 230 192 254 0 3220 254 186 230 192 0 3221 254 302 252 192 0 3222 186 148 192 254 0 3223 178 219 163 208 0 3224 208 178 126 163 0 3225 252 192 163 208 0 3226 208 148 192 163 0 3227 208 252 219 163 0 3228 148 126 163 208 0 3229 157 203 139 178 0 3230 178 157 101 139 0 3231 219 163 139 178 0 3232 178 126 163 139 0 3233 178 219 203 139 0 3234 126 101 139 178 0 3235 97 101 157 139 0 3236 139 203 157 97 0 3237 147 157 203 97 0 3238 97 147 193 203 0 3239 97 136 139 203 0 3240 136 193 203 97 0 3241 852 916 849 986 0 3242 986 852 760 849 0 3243 1046 990 849 986 0 3244 986 925 990 849 0 3245 986 1046 916 849 0 3246 925 760 849 986 0 3247 697 781 700 852 0 3248 852 697 605 700 0 3249 916 849 700 852 0 3250 852 760 849 700 0 3251 852 916 781 700 0 3252 760 605 700 852 0 3253 571 635 565 697 0 3254 697 571 474 565 0 3255 781 700 565 697 0 3256 697 605 700 565 0 3257 697 781 635 565 0 3258 605 474 565 697 0 3259 450 524 448 571 0 3260 571 450 380 448 0 3261 635 565 448 571 0 3262 571 474 565 448 0 3263 571 635 524 448 0 3264 474 380 448 571 0 3265 371 443 365 450 0 3266 450 371 300 365 0 3267 524 448 365 450 0 3268 450 380 448 365 0 3269 450 524 443 365 0 3270 380 300 365 450 0 3271 302 370 297 371 0 3272 371 302 230 297 0 3273 443 365 297 371 0 3274 371 300 365 297 0 3275 371 443 370 297 0 3276 300 230 297 371 0 3277 252 314 241 302 0 3278 302 252 192 241 0 3279 370 297 241 302 0 3280 302 230 297 241 0 3281 302 370 314 241 0 3282 230 192 241 302 0 3283 219 288 221 252 0 3284 252 219 163 221 0 3285 314 241 221 252 0 3286 252 192 241 221 0 3287 252 314 288 221 0 3288 192 163 221 252 0 3289 203 258 200 219 0 3290 219 203 139 200 0 3291 288 221 200 219 0 3292 219 163 221 200 0 3293 219 288 258 200 0 3294 163 139 200 219 0 3295 136 139 203 200 0 3296 200 258 203 136 0 3297 193 203 258 136 0 3298 136 193 245 258 0 3299 136 190 200 258 0 3300 190 245 258 136 0 3301 916 993 934 1046 0 3302 1046 916 849 934 0 3303 1093 1057 934 1046 0 3304 1046 990 1057 934 0 3305 1046 1093 993 934 0 3306 990 849 934 1046 0 3307 781 874 798 916 0 3308 916 781 700 798 0 3309 993 934 798 916 0 3310 916 849 934 798 0 3311 916 993 874 798 0 3312 849 700 798 916 0 3313 635 748 653 781 0 3314 781 635 565 653 0 3315 874 798 653 781 0 3316 781 700 798 653 0 3317 781 874 748 653 0 3318 700 565 653 781 0 3319 524 610 538 635 0 3320 635 524 448 538 0 3321 748 653 538 635 0 3322 635 565 653 538 0 3323 635 748 610 538 0 3324 565 448 538 635 0 3325 443 534 449 524 0 3326 524 443 365 449 0 3327 610 538 449 524 0 3328 524 448 538 449 0 3329 524 610 534 449 0 3330 448 365 449 524 0 3331 370 452 379 443 0 3332 443 370 297 379 0 3333 534 449 379 443 0 3334 443 365 449 379 0 3335 443 534 452 379 0 3336 365 297 379 443 0 3337 314 400 318 370 0 3338 370 314 241 318 0 3339 452 379 318 370 0 3340 370 297 379 318 0 3341 370 452 400 318 0 3342 297 241 318 370 0 3343 288 358 292 314 0 3344 314 288 221 292 0 3345 400 318 292 314 0 3346 314 241 318 292 0 3347 314 400 358 292 0 3348 241 221 292 314 0 3349 258 333 267 288 0 3350 288 258 200 267 0 3351 358 292 267 288 0 3352 288 221 292 267 0 3353 288 358 333 267 0 3354 221 200 267 288 0 3355 190 200 258 267 0 3356 267 333 258 190 0 3357 245 258 333 190 0 3358 190 245 325 333 0 3359 190 263 267 333 0 3360 263 325 333 190 0 3361 993 1077 1021 1093 0 3362 1093 993 934 1021 0 3363 1164 1122 1021 1093 0 3364 1093 1057 1122 1021 0 3365 1093 1164 1077 1021 0 3366 1057 934 1021 1093 0 3367 874 970 901 993 0 3368 993 874 798 901 0 3369 1077 1021 901 993 0 3370 993 934 1021 901 0 3371 993 1077 970 901 0 3372 934 798 901 993 0 3373 748 857 773 874 0 3374 874 748 653 773 0 3375 970 901 773 874 0 3376 874 798 901 773 0 3377 874 970 857 773 0 3378 798 653 773 874 0 3379 610 740 649 748 0 3380 748 610 538 649 0 3381 857 773 649 748 0 3382 748 653 773 649 0 3383 748 857 740 649 0 3384 653 538 649 748 0 3385 534 639 577 610 0 3386 610 534 449 577 0 3387 740 649 577 610 0 3388 610 538 649 577 0 3389 610 740 639 577 0 3390 538 449 577 610 0 3391 452 562 472 534 0 3392 534 452 379 472 0 3393 639 577 472 534 0 3394 534 449 577 472 0 3395 534 639 562 472 0 3396 449 379 472 534 0 3397 400 498 430 452 0 3398 452 400 318 430 0 3399 562 472 430 452 0 3400 452 379 472 430 0 3401 452 562 498 430 0 3402 379 318 430 452 0 3403 358 460 398 400 0 3404 400 358 292 398 0 3405 498 430 398 400 0 3406 400 318 430 398 0 3407 400 498 460 398 0 3408 318 292 398 400 0 3409 333 438 363 358 0 3410 358 333 267 363 0 3411 460 398 363 358 0 3412 358 292 398 363 0 3413 358 460 438 363 0 3414 292 267 363 358 0 3415 263 267 333 363 0 3416 363 438 333 263 0 3417 325 333 438 263 0 3418 263 325 420 438 0 3419 263 348 363 438 0 3420 348 420 438 263 0 3421 1077 1148 1090 1164 0 3422 1164 1077 1021 1090 0 3423 1221 1179 1090 1164 0 3424 1164 1122 1179 1090 0 3425 1164 1221 1148 1090 0 3426 1122 1021 1090 1164 0 3427 970 1069 998 1077 0 3428 1077 970 901 998 0 3429 1148 1090 998 1077 0 3430 1077 1021 1090 998 0 3431 1077 1148 1069 998 0 3432 1021 901 998 1077 0 3433 857 971 894 970 0 3434 970 857 773 894 0 3435 1069 998 894 970 0 3436 970 901 998 894 0 3437 970 1069 971 894 0 3438 901 773 894 970 0 3439 740 862 793 857 0 3440 857 740 649 793 0 3441 971 894 793 857 0 3442 857 773 894 793 0 3443 857 971 862 793 0 3444 773 649 793 857 0 3445 639 784 698 740 0 3446 740 639 577 698 0 3447 862 793 698 740 0 3448 740 649 793 698 0 3449 740 862 784 698 0 3450 649 577 698 740 0 3451 562 702 604 639 0 3452 639 562 472 604 0 3453 784 698 604 639 0 3454 639 577 698 604 0 3455 639 784 702 604 0 3456 577 472 604 639 0 3457 498 627 546 562 0 3458 562 498 430 546 0 3459 702 604 546 562 0 3460 562 472 604 546 0 3461 562 702 627 546 0 3462 472 430 546 562 0 3463 460 591 509 498 0 3464 498 460 398 509 0 3465 627 546 509 498 0 3466 498 430 546 509 0 3467 498 627 591 509 0 3468 430 398 509 498 0 3469 438 579 486 460 0 3470 460 438 363 486 0 3471 591 509 486 460 0 3472 460 398 509 486 0 3473 460 591 579 486 0 3474 398 363 486 460 0 3475 348 363 438 486 0 3476 486 579 438 348 0 3477 420 438 579 348 0 3478 348 420 554 579 0 3479 348 471 486 579 0 3480 471 554 579 348 0 3481 1148 1216 1174 1221 0 3482 1221 1148 1090 1174 0 3483 1266 1240 1174 1221 0 3484 1221 1179 1240 1174 0 3485 1221 1266 1216 1174 0 3486 1179 1090 1174 1221 0 3487 1069 1146 1096 1148 0 3488 1148 1069 998 1096 0 3489 1216 1174 1096 1148 0 3490 1148 1090 1174 1096 0 3491 1148 1216 1146 1096 0 3492 1090 998 1096 1148 0 3493 971 1079 1014 1069 0 3494 1069 971 894 1014 0 3495 1146 1096 1014 1069 0 3496 1069 998 1096 1014 0 3497 1069 1146 1079 1014 0 3498 998 894 1014 1069 0 3499 862 992 929 971 0 3500 971 862 793 929 0 3501 1079 1014 929 971 0 3502 971 894 1014 929 0 3503 971 1079 992 929 0 3504 894 793 929 971 0 3505 784 922 845 862 0 3506 862 784 698 845 0 3507 992 929 845 862 0 3508 862 793 929 845 0 3509 862 992 922 845 0 3510 793 698 845 862 0 3511 702 850 758 784 0 3512 784 702 604 758 0 3513 922 845 758 784 0 3514 784 698 845 758 0 3515 784 922 850 758 0 3516 698 604 758 784 0 3517 627 786 703 702 0 3518 702 627 546 703 0 3519 850 758 703 702 0 3520 702 604 758 703 0 3521 702 850 786 703 0 3522 604 546 703 702 0 3523 591 753 667 627 0 3524 627 591 509 667 0 3525 786 703 667 627 0 3526 627 546 703 667 0 3527 627 786 753 667 0 3528 546 509 667 627 0 3529 579 718 623 591 0 3530 591 579 486 623 0 3531 753 667 623 591 0 3532 591 509 667 623 0 3533 591 753 718 623 0 3534 509 486 623 591 0 3535 471 486 579 623 0 3536 623 718 579 471 0 3537 554 579 718 471 0 3538 471 554 707 718 0 3539 471 615 623 718 0 3540 615 707 718 471 0 3541 1240 1285 1296 1174 0 3542 1174 1240 1266 1296 0 3543 1239 1269 1296 1174 0 3544 1174 1216 1269 1296 0 3545 1174 1239 1285 1296 0 3546 1216 1266 1296 1174 0 3547 1174 1239 1269 1096 0 3548 1096 1174 1216 1269 0 3549 1181 1222 1269 1096 0 3550 1096 1146 1222 1269 0 3551 1096 1181 1239 1269 0 3552 1146 1216 1269 1096 0 3553 1096 1181 1222 1014 0 3554 1014 1096 1146 1222 0 3555 1120 1168 1222 1014 0 3556 1014 1079 1168 1222 0 3557 1014 1120 1181 1222 0 3558 1079 1146 1222 1014 0 3559 1014 1120 1168 929 0 3560 929 1014 1079 1168 0 3561 1053 1092 1168 929 0 3562 929 992 1092 1168 0 3563 929 1053 1120 1168 0 3564 992 1079 1168 929 0 3565 929 1053 1092 845 0 3566 845 929 992 1092 0 3567 989 1051 1092 845 0 3568 845 922 1051 1092 0 3569 845 989 1053 1092 0 3570 922 992 1092 845 0 3571 845 989 1051 758 0 3572 758 845 922 1051 0 3573 923 988 1051 758 0 3574 758 850 988 1051 0 3575 758 923 989 1051 0 3576 850 922 1051 758 0 3577 758 923 988 703 0 3578 703 758 850 988 0 3579 869 942 988 703 0 3580 703 786 942 988 0 3581 703 869 923 988 0 3582 786 850 988 703 0 3583 703 869 942 667 0 3584 667 703 786 942 0 3585 833 895 942 667 0 3586 667 753 895 942 0 3587 667 833 869 942 0 3588 753 786 942 667 0 3589 667 833 895 623 0 3590 623 667 753 895 0 3591 812 887 895 623 0 3592 623 718 887 895 0 3593 623 812 833 895 0 3594 718 753 895 623 0 3595 796 812 623 887 0 3596 887 718 623 796 0 3597 615 623 718 796 0 3598 796 615 707 718 0 3599 796 864 887 718 0 3600 864 707 718 796 0 3601 612 619 583 791 0 3602 791 612 572 583 0 3603 814 755 583 791 0 3604 791 730 755 583 0 3605 791 814 619 583 0 3606 730 572 583 791 0 3607 469 484 437 612 0 3608 612 469 418 437 0 3609 619 583 437 612 0 3610 612 572 583 437 0 3611 612 619 484 437 0 3612 572 418 437 612 0 3613 349 364 315 469 0 3614 469 349 308 315 0 3615 484 437 315 469 0 3616 469 418 437 315 0 3617 469 484 364 315 0 3618 418 308 315 469 0 3619 261 268 225 349 0 3620 349 261 213 225 0 3621 364 315 225 349 0 3622 349 308 315 225 0 3623 349 364 268 225 0 3624 308 213 225 349 0 3625 197 201 154 261 0 3626 261 197 151 154 0 3627 268 225 154 261 0 3628 261 213 225 154 0 3629 261 268 201 154 0 3630 213 151 154 261 0 3631 134 137 100 197 0 3632 197 134 91 100 0 3633 201 154 100 197 0 3634 197 151 154 100 0 3635 197 201 137 100 0 3636 151 91 100 197 0 3637 92 103 70 134 0 3638 134 92 65 70 0 3639 137 100 70 134 0 3640 134 91 100 70 0 3641 134 137 103 70 0 3642 91 65 70 134 0 3643 78 80 46 92 0 3644 92 78 40 46 0 3645 103 70 46 92 0 3646 92 65 70 46 0 3647 92 103 80 46 0 3648 65 40 46 92 0 3649 56 64 36 78 0 3650 78 56 30 36 0 3651 80 46 36 78 0 3652 78 40 46 36 0 3653 78 80 64 36 0 3654 40 30 36 78 0 3655 27 30 56 36 0 3656 36 64 56 27 0 3657 54 56 64 27 0 3658 27 54 57 64 0 3659 27 34 36 64 0 3660 34 57 64 27 0 3661 619 657 598 814 0 3662 814 619 583 598 0 3663 832 766 598 814 0 3664 814 755 766 598 0 3665 814 832 657 598 0 3666 755 583 598 814 0 3667 484 508 459 619 0 3668 619 484 437 459 0 3669 657 598 459 619 0 3670 619 583 598 459 0 3671 619 657 508 459 0 3672 583 437 459 619 0 3673 364 390 335 484 0 3674 484 364 315 335 0 3675 508 459 335 484 0 3676 484 437 459 335 0 3677 484 508 390 335 0 3678 437 315 335 484 0 3679 268 293 238 364 0 3680 364 268 225 238 0 3681 390 335 238 364 0 3682 364 315 335 238 0 3683 364 390 293 238 0 3684 315 225 238 364 0 3685 201 214 175 268 0 3686 268 201 154 175 0 3687 293 238 175 268 0 3688 268 225 238 175 0 3689 268 293 214 175 0 3690 225 154 175 268 0 3691 137 158 118 201 0 3692 201 137 100 118 0 3693 214 175 118 201 0 3694 201 154 175 118 0 3695 201 214 158 118 0 3696 154 100 118 201 0 3697 103 121 86 137 0 3698 137 103 70 86 0 3699 158 118 86 137 0 3700 137 100 118 86 0 3701 137 158 121 86 0 3702 100 70 86 137 0 3703 80 90 55 103 0 3704 103 80 46 55 0 3705 121 86 55 103 0 3706 103 70 86 55 0 3707 103 121 90 55 0 3708 70 46 55 103 0 3709 64 79 47 80 0 3710 80 64 36 47 0 3711 90 55 47 80 0 3712 80 46 55 47 0 3713 80 90 79 47 0 3714 46 36 47 80 0 3715 34 36 64 47 0 3716 47 79 64 34 0 3717 57 64 79 34 0 3718 34 57 75 79 0 3719 34 44 47 79 0 3720 44 75 79 34 0 3721 657 706 638 832 0 3722 832 657 598 638 0 3723 868 827 638 832 0 3724 832 766 827 638 0 3725 832 868 706 638 0 3726 766 598 638 832 0 3727 508 558 494 657 0 3728 657 508 459 494 0 3729 706 638 494 657 0 3730 657 598 638 494 0 3731 657 706 558 494 0 3732 598 459 494 657 0 3733 390 424 377 508 0 3734 508 390 335 377 0 3735 558 494 377 508 0 3736 508 459 494 377 0 3737 508 558 424 377 0 3738 459 335 377 508 0 3739 293 321 281 390 0 3740 390 293 238 281 0 3741 424 377 281 390 0 3742 390 335 377 281 0 3743 390 424 321 281 0 3744 335 238 281 390 0 3745 214 250 207 293 0 3746 293 214 175 207 0 3747 321 281 207 293 0 3748 293 238 281 207 0 3749 293 321 250 207 0 3750 238 175 207 293 0 3751 158 186 143 214 0 3752 214 158 118 143 0 3753 250 207 143 214 0 3754 214 175 207 143 0 3755 214 250 186 143 0 3756 175 118 143 214 0 3757 121 148 112 158 0 3758 158 121 86 112 0 3759 186 143 112 158 0 3760 158 118 143 112 0 3761 158 186 148 112 0 3762 118 86 112 158 0 3763 90 126 85 121 0 3764 121 90 55 85 0 3765 148 112 85 121 0 3766 121 86 112 85 0 3767 121 148 126 85 0 3768 86 55 85 121 0 3769 79 101 71 90 0 3770 90 79 47 71 0 3771 126 85 71 90 0 3772 90 55 85 71 0 3773 90 126 101 71 0 3774 55 47 71 90 0 3775 44 47 79 71 0 3776 71 101 79 44 0 3777 75 79 101 44 0 3778 44 75 97 101 0 3779 44 66 71 101 0 3780 66 97 101 44 0 3781 706 760 713 868 0 3782 868 706 638 713 0 3783 925 861 713 868 0 3784 868 827 861 713 0 3785 868 925 760 713 0 3786 827 638 713 868 0 3787 558 605 561 706 0 3788 706 558 494 561 0 3789 760 713 561 706 0 3790 706 638 713 561 0 3791 706 760 605 561 0 3792 638 494 561 706 0 3793 424 474 434 558 0 3794 558 424 377 434 0 3795 605 561 434 558 0 3796 558 494 561 434 0 3797 558 605 474 434 0 3798 494 377 434 558 0 3799 321 380 327 424 0 3800 424 321 281 327 0 3801 474 434 327 424 0 3802 424 377 434 327 0 3803 424 474 380 327 0 3804 377 281 327 424 0 3805 250 300 248 321 0 3806 321 250 207 248 0 3807 380 327 248 321 0 3808 321 281 327 248 0 3809 321 380 300 248 0 3810 281 207 248 321 0 3811 186 230 187 250 0 3812 250 186 143 187 0 3813 300 248 187 250 0 3814 250 207 248 187 0 3815 250 300 230 187 0 3816 207 143 187 250 0 3817 148 192 144 186 0 3818 186 148 112 144 0 3819 230 187 144 186 0 3820 186 143 187 144 0 3821 186 230 192 144 0 3822 143 112 144 186 0 3823 126 163 116 148 0 3824 148 126 85 116 0 3825 192 144 116 148 0 3826 148 112 144 116 0 3827 148 192 163 116 0 3828 112 85 116 148 0 3829 101 139 102 126 0 3830 126 101 71 102 0 3831 163 116 102 126 0 3832 126 85 116 102 0 3833 126 163 139 102 0 3834 85 71 102 126 0 3835 66 71 101 102 0 3836 102 139 101 66 0 3837 97 101 139 66 0 3838 66 97 136 139 0 3839 66 98 102 139 0 3840 98 136 139 66 0 3841 760 849 789 925 0 3842 925 760 713 789 0 3843 990 941 789 925 0 3844 925 861 941 789 0 3845 925 990 849 789 0 3846 861 713 789 925 0 3847 605 700 629 760 0 3848 760 605 561 629 0 3849 849 789 629 760 0 3850 760 713 789 629 0 3851 760 849 700 629 0 3852 713 561 629 760 0 3853 474 565 502 605 0 3854 605 474 434 502 0 3855 700 629 502 605 0 3856 605 561 629 502 0 3857 605 700 565 502 0 3858 561 434 502 605 0 3859 380 448 402 474 0 3860 474 380 327 402 0 3861 565 502 402 474 0 3862 474 434 502 402 0 3863 474 565 448 402 0 3864 434 327 402 474 0 3865 300 365 313 380 0 3866 380 300 248 313 0 3867 448 402 313 380 0 3868 380 327 402 313 0 3869 380 448 365 313 0 3870 327 248 313 380 0 3871 230 297 246 300 0 3872 300 230 187 246 0 3873 365 313 246 300 0 3874 300 248 313 246 0 3875 300 365 297 246 0 3876 248 187 246 300 0 3877 192 241 206 230 0 3878 230 192 144 206 0 3879 297 246 206 230 0 3880 230 187 246 206 0 3881 230 297 241 206 0 3882 187 144 206 230 0 3883 163 221 170 192 0 3884 192 163 116 170 0 3885 241 206 170 192 0 3886 192 144 206 170 0 3887 192 241 221 170 0 3888 144 116 170 192 0 3889 139 200 152 163 0 3890 163 139 102 152 0 3891 221 170 152 163 0 3892 163 116 170 152 0 3893 163 221 200 152 0 3894 116 102 152 163 0 3895 98 102 139 152 0 3896 152 200 139 98 0 3897 136 139 200 98 0 3898 98 136 190 200 0 3899 98 149 152 200 0 3900 149 190 200 98 0 3901 849 934 888 990 0 3902 990 849 789 888 0 3903 1057 1008 888 990 0 3904 990 941 1008 888 0 3905 990 1057 934 888 0 3906 941 789 888 990 0 3907 700 798 736 849 0 3908 849 700 629 736 0 3909 934 888 736 849 0 3910 849 789 888 736 0 3911 849 934 798 736 0 3912 789 629 736 849 0 3913 565 653 603 700 0 3914 700 565 502 603 0 3915 798 736 603 700 0 3916 700 629 736 603 0 3917 700 798 653 603 0 3918 629 502 603 700 0 3919 448 538 479 565 0 3920 565 448 402 479 0 3921 653 603 479 565 0 3922 565 502 603 479 0 3923 565 653 538 479 0 3924 502 402 479 565 0 3925 365 449 404 448 0 3926 448 365 313 404 0 3927 538 479 404 448 0 3928 448 402 479 404 0 3929 448 538 449 404 0 3930 402 313 404 448 0 3931 297 379 324 365 0 3932 365 297 246 324 0 3933 449 404 324 365 0 3934 365 313 404 324 0 3935 365 449 379 324 0 3936 313 246 324 365 0 3937 241 318 286 297 0 3938 297 241 206 286 0 3939 379 324 286 297 0 3940 297 246 324 286 0 3941 297 379 318 286 0 3942 246 206 286 297 0 3943 221 292 231 241 0 3944 241 221 170 231 0 3945 318 286 231 241 0 3946 241 206 286 231 0 3947 241 318 292 231 0 3948 206 170 231 241 0 3949 200 267 224 221 0 3950 221 200 152 224 0 3951 292 231 224 221 0 3952 221 170 231 224 0 3953 221 292 267 224 0 3954 170 152 224 221 0 3955 149 152 200 224 0 3956 224 267 200 149 0 3957 190 200 267 149 0 3958 149 190 263 267 0 3959 149 220 224 267 0 3960 220 263 267 149 0 3961 934 1021 979 1057 0 3962 1057 934 888 979 0 3963 1122 1087 979 1057 0 3964 1057 1008 1087 979 0 3965 1057 1122 1021 979 0 3966 1008 888 979 1057 0 3967 798 901 856 934 0 3968 934 798 736 856 0 3969 1021 979 856 934 0 3970 934 888 979 856 0 3971 934 1021 901 856 0 3972 888 736 856 934 0 3973 653 773 721 798 0 3974 798 653 603 721 0 3975 901 856 721 798 0 3976 798 736 856 721 0 3977 798 901 773 721 0 3978 736 603 721 798 0 3979 538 649 597 653 0 3980 653 538 479 597 0 3981 773 721 597 653 0 3982 653 603 721 597 0 3983 653 773 649 597 0 3984 603 479 597 653 0 3985 449 577 501 538 0 3986 538 449 404 501 0 3987 649 597 501 538 0 3988 538 479 597 501 0 3989 538 649 577 501 0 3990 479 404 501 538 0 3991 379 472 422 449 0 3992 449 379 324 422 0 3993 577 501 422 449 0 3994 449 404 501 422 0 3995 449 577 472 422 0 3996 404 324 422 449 0 3997 318 430 376 379 0 3998 379 318 286 376 0 3999 472 422 376 379 0 4000 379 324 422 376 0 4001 379 472 430 376 0 4002 324 286 376 379 0 4003 292 398 330 318 0 4004 318 292 231 330 0 4005 430 376 330 318 0 4006 318 286 376 330 0 4007 318 430 398 330 0 4008 286 231 330 318 0 4009 267 363 309 292 0 4010 292 267 224 309 0 4011 398 330 309 292 0 4012 292 231 330 309 0 4013 292 398 363 309 0 4014 231 224 309 292 0 4015 220 224 267 309 0 4016 309 363 267 220 0 4017 263 267 363 220 0 4018 220 263 348 363 0 4019 220 304 309 363 0 4020 304 348 363 220 0 4021 1021 1090 1071 1122 0 4022 1122 1021 979 1071 0 4023 1179 1158 1071 1122 0 4024 1122 1087 1158 1071 0 4025 1122 1179 1090 1071 0 4026 1087 979 1071 1122 0 4027 901 998 967 1021 0 4028 1021 901 856 967 0 4029 1090 1071 967 1021 0 4030 1021 979 1071 967 0 4031 1021 1090 998 967 0 4032 979 856 967 1021 0 4033 773 894 853 901 0 4034 901 773 721 853 0 4035 998 967 853 901 0 4036 901 856 967 853 0 4037 901 998 894 853 0 4038 856 721 853 901 0 4039 649 793 728 773 0 4040 773 649 597 728 0 4041 894 853 728 773 0 4042 773 721 853 728 0 4043 773 894 793 728 0 4044 721 597 728 773 0 4045 577 698 624 649 0 4046 649 577 501 624 0 4047 793 728 624 649 0 4048 649 597 728 624 0 4049 649 793 698 624 0 4050 597 501 624 649 0 4051 472 604 547 577 0 4052 577 472 422 547 0 4053 698 624 547 577 0 4054 577 501 624 547 0 4055 577 698 604 547 0 4056 501 422 547 577 0 4057 430 546 492 472 0 4058 472 430 376 492 0 4059 604 547 492 472 0 4060 472 422 547 492 0 4061 472 604 546 492 0 4062 422 376 492 472 0 4063 398 509 458 430 0 4064 430 398 330 458 0 4065 546 492 458 430 0 4066 430 376 492 458 0 4067 430 546 509 458 0 4068 376 330 458 430 0 4069 363 486 436 398 0 4070 398 363 309 436 0 4071 509 458 436 398 0 4072 398 330 458 436 0 4073 398 509 486 436 0 4074 330 309 436 398 0 4075 304 309 363 436 0 4076 436 486 363 304 0 4077 348 363 486 304 0 4078 304 348 471 486 0 4079 304 419 436 486 0 4080 419 471 486 304 0 4081 1090 1174 1153 1179 0 4082 1179 1090 1071 1153 0 4083 1240 1224 1153 1179 0 4084 1179 1158 1224 1153 0 4085 1179 1240 1174 1153 0 4086 1158 1071 1153 1179 0 4087 998 1096 1076 1090 0 4088 1090 998 967 1076 0 4089 1174 1153 1076 1090 0 4090 1090 1071 1153 1076 0 4091 1090 1174 1096 1076 0 4092 1071 967 1076 1090 0 4093 894 1014 974 998 0 4094 998 894 853 974 0 4095 1096 1076 974 998 0 4096 998 967 1076 974 0 4097 998 1096 1014 974 0 4098 967 853 974 998 0 4099 793 929 883 894 0 4100 894 793 728 883 0 4101 1014 974 883 894 0 4102 894 853 974 883 0 4103 894 1014 929 883 0 4104 853 728 883 894 0 4105 698 845 785 793 0 4106 793 698 624 785 0 4107 929 883 785 793 0 4108 793 728 883 785 0 4109 793 929 845 785 0 4110 728 624 785 793 0 4111 604 758 712 698 0 4112 698 604 547 712 0 4113 845 785 712 698 0 4114 698 624 785 712 0 4115 698 845 758 712 0 4116 624 547 712 698 0 4117 546 703 631 604 0 4118 604 546 492 631 0 4119 758 712 631 604 0 4120 604 547 712 631 0 4121 604 758 703 631 0 4122 547 492 631 604 0 4123 509 667 592 546 0 4124 546 509 458 592 0 4125 703 631 592 546 0 4126 546 492 631 592 0 4127 546 703 667 592 0 4128 492 458 592 546 0 4129 486 623 580 509 0 4130 509 486 436 580 0 4131 667 592 580 509 0 4132 509 458 592 580 0 4133 509 667 623 580 0 4134 458 436 580 509 0 4135 419 436 486 580 0 4136 580 623 486 419 0 4137 471 486 623 419 0 4138 419 471 615 623 0 4139 419 567 580 623 0 4140 567 615 623 419 0 4141 1224 1272 1285 1153 0 4142 1153 1224 1240 1285 0 4143 1227 1239 1285 1153 0 4144 1153 1174 1239 1285 0 4145 1153 1227 1272 1285 0 4146 1174 1240 1285 1153 0 4147 1153 1227 1239 1076 0 4148 1076 1153 1174 1239 0 4149 1163 1181 1239 1076 0 4150 1076 1096 1181 1239 0 4151 1076 1163 1227 1239 0 4152 1096 1174 1239 1076 0 4153 1076 1163 1181 974 0 4154 974 1076 1096 1181 0 4155 1088 1120 1181 974 0 4156 974 1014 1120 1181 0 4157 974 1088 1163 1181 0 4158 1014 1096 1181 974 0 4159 974 1088 1120 883 0 4160 883 974 1014 1120 0 4161 1003 1053 1120 883 0 4162 883 929 1053 1120 0 4163 883 1003 1088 1120 0 4164 929 1014 1120 883 0 4165 883 1003 1053 785 0 4166 785 883 929 1053 0 4167 949 989 1053 785 0 4168 785 845 989 1053 0 4169 785 949 1003 1053 0 4170 845 929 1053 785 0 4171 785 949 989 712 0 4172 712 785 845 989 0 4173 871 923 989 712 0 4174 712 758 923 989 0 4175 712 871 949 989 0 4176 758 845 989 712 0 4177 712 871 923 631 0 4178 631 712 758 923 0 4179 824 869 923 631 0 4180 631 703 869 923 0 4181 631 824 871 923 0 4182 703 758 923 631 0 4183 631 824 869 592 0 4184 592 631 703 869 0 4185 764 833 869 592 0 4186 592 667 833 869 0 4187 592 764 824 869 0 4188 667 703 869 592 0 4189 592 764 833 580 0 4190 580 592 667 833 0 4191 746 812 833 580 0 4192 580 623 812 833 0 4193 580 746 764 833 0 4194 623 667 833 580 0 4195 733 746 580 812 0 4196 812 623 580 733 0 4197 567 580 623 733 0 4198 733 567 615 623 0 4199 733 796 812 623 0 4200 796 615 623 733 0 4201 572 583 535 730 0 4202 730 572 519 535 0 4203 755 694 535 730 0 4204 730 681 694 535 0 4205 730 755 583 535 0 4206 681 519 535 730 0 4207 418 437 395 572 0 4208 572 418 385 395 0 4209 583 535 395 572 0 4210 572 519 535 395 0 4211 572 583 437 395 0 4212 519 385 395 572 0 4213 308 315 284 418 0 4214 418 308 273 284 0 4215 437 395 284 418 0 4216 418 385 395 284 0 4217 418 437 315 284 0 4218 385 273 284 418 0 4219 213 225 198 308 0 4220 308 213 184 198 0 4221 315 284 198 308 0 4222 308 273 284 198 0 4223 308 315 225 198 0 4224 273 184 198 308 0 4225 151 154 133 213 0 4226 213 151 125 133 0 4227 225 198 133 213 0 4228 213 184 198 133 0 4229 213 225 154 133 0 4230 184 125 133 213 0 4231 91 100 82 151 0 4232 151 91 77 82 0 4233 154 133 82 151 0 4234 151 125 133 82 0 4235 151 154 100 82 0 4236 125 77 82 151 0 4237 65 70 50 91 0 4238 91 65 45 50 0 4239 100 82 50 91 0 4240 91 77 82 50 0 4241 91 100 70 50 0 4242 77 45 50 91 0 4243 40 46 28 65 0 4244 65 40 23 28 0 4245 70 50 28 65 0 4246 65 45 50 28 0 4247 65 70 46 28 0 4248 45 23 28 65 0 4249 30 36 19 40 0 4250 40 30 15 19 0 4251 46 28 19 40 0 4252 40 23 28 19 0 4253 40 46 36 19 0 4254 23 15 19 40 0 4255 9 15 30 19 0 4256 19 36 30 9 0 4257 27 30 36 9 0 4258 9 27 34 36 0 4259 9 14 19 36 0 4260 14 34 36 9 0 4261 583 598 550 755 0 4262 755 583 535 550 0 4263 766 724 550 755 0 4264 755 694 724 550 0 4265 755 766 598 550 0 4266 694 535 550 755 0 4267 437 459 409 583 0 4268 583 437 395 409 0 4269 598 550 409 583 0 4270 583 535 550 409 0 4271 583 598 459 409 0 4272 535 395 409 583 0 4273 315 335 299 437 0 4274 437 315 284 299 0 4275 459 409 299 437 0 4276 437 395 409 299 0 4277 437 459 335 299 0 4278 395 284 299 437 0 4279 225 238 211 315 0 4280 315 225 198 211 0 4281 335 299 211 315 0 4282 315 284 299 211 0 4283 315 335 238 211 0 4284 284 198 211 315 0 4285 154 175 140 225 0 4286 225 154 133 140 0 4287 238 211 140 225 0 4288 225 198 211 140 0 4289 225 238 175 140 0 4290 198 133 140 225 0 4291 100 118 88 154 0 4292 154 100 82 88 0 4293 175 140 88 154 0 4294 154 133 140 88 0 4295 154 175 118 88 0 4296 133 82 88 154 0 4297 70 86 63 100 0 4298 100 70 50 63 0 4299 118 88 63 100 0 4300 100 82 88 63 0 4301 100 118 86 63 0 4302 82 50 63 100 0 4303 46 55 39 70 0 4304 70 46 28 39 0 4305 86 63 39 70 0 4306 70 50 63 39 0 4307 70 86 55 39 0 4308 50 28 39 70 0 4309 36 47 25 46 0 4310 46 36 19 25 0 4311 55 39 25 46 0 4312 46 28 39 25 0 4313 46 55 47 25 0 4314 28 19 25 46 0 4315 14 19 36 25 0 4316 25 47 36 14 0 4317 34 36 47 14 0 4318 14 34 44 47 0 4319 14 22 25 47 0 4320 22 44 47 14 0 4321 598 638 600 766 0 4322 766 598 550 600 0 4323 827 769 600 766 0 4324 766 724 769 600 0 4325 766 827 638 600 0 4326 724 550 600 766 0 4327 459 494 457 598 0 4328 598 459 409 457 0 4329 638 600 457 598 0 4330 598 550 600 457 0 4331 598 638 494 457 0 4332 550 409 457 598 0 4333 335 377 338 459 0 4334 459 335 299 338 0 4335 494 457 338 459 0 4336 459 409 457 338 0 4337 459 494 377 338 0 4338 409 299 338 459 0 4339 238 281 239 335 0 4340 335 238 211 239 0 4341 377 338 239 335 0 4342 335 299 338 239 0 4343 335 377 281 239 0 4344 299 211 239 335 0 4345 175 207 177 238 0 4346 238 175 140 177 0 4347 281 239 177 238 0 4348 238 211 239 177 0 4349 238 281 207 177 0 4350 211 140 177 238 0 4351 118 143 123 175 0 4352 175 118 88 123 0 4353 207 177 123 175 0 4354 175 140 177 123 0 4355 175 207 143 123 0 4356 140 88 123 175 0 4357 86 112 87 118 0 4358 118 86 63 87 0 4359 143 123 87 118 0 4360 118 88 123 87 0 4361 118 143 112 87 0 4362 88 63 87 118 0 4363 55 85 60 86 0 4364 86 55 39 60 0 4365 112 87 60 86 0 4366 86 63 87 60 0 4367 86 112 85 60 0 4368 63 39 60 86 0 4369 47 71 48 55 0 4370 55 47 25 48 0 4371 85 60 48 55 0 4372 55 39 60 48 0 4373 55 85 71 48 0 4374 39 25 48 55 0 4375 22 25 47 48 0 4376 48 71 47 22 0 4377 44 47 71 22 0 4378 22 44 66 71 0 4379 22 41 48 71 0 4380 41 66 71 22 0 4381 638 713 669 827 0 4382 827 638 600 669 0 4383 861 834 669 827 0 4384 827 769 834 669 0 4385 827 861 713 669 0 4386 769 600 669 827 0 4387 494 561 506 638 0 4388 638 494 457 506 0 4389 713 669 506 638 0 4390 638 600 669 506 0 4391 638 713 561 506 0 4392 600 457 506 638 0 4393 377 434 391 494 0 4394 494 377 338 391 0 4395 561 506 391 494 0 4396 494 457 506 391 0 4397 494 561 434 391 0 4398 457 338 391 494 0 4399 281 327 296 377 0 4400 377 281 239 296 0 4401 434 391 296 377 0 4402 377 338 391 296 0 4403 377 434 327 296 0 4404 338 239 296 377 0 4405 207 248 223 281 0 4406 281 207 177 223 0 4407 327 296 223 281 0 4408 281 239 296 223 0 4409 281 327 248 223 0 4410 239 177 223 281 0 4411 143 187 162 207 0 4412 207 143 123 162 0 4413 248 223 162 207 0 4414 207 177 223 162 0 4415 207 248 187 162 0 4416 177 123 162 207 0 4417 112 144 127 143 0 4418 143 112 87 127 0 4419 187 162 127 143 0 4420 143 123 162 127 0 4421 143 187 144 127 0 4422 123 87 127 143 0 4423 85 116 89 112 0 4424 112 85 60 89 0 4425 144 127 89 112 0 4426 112 87 127 89 0 4427 112 144 116 89 0 4428 87 60 89 112 0 4429 71 102 81 85 0 4430 85 71 48 81 0 4431 116 89 81 85 0 4432 85 60 89 81 0 4433 85 116 102 81 0 4434 60 48 81 85 0 4435 41 48 71 81 0 4436 81 102 71 41 0 4437 66 71 102 41 0 4438 41 66 98 102 0 4439 41 73 81 102 0 4440 73 98 102 41 0 4441 713 789 750 861 0 4442 861 713 669 750 0 4443 941 899 750 861 0 4444 861 834 899 750 0 4445 861 941 789 750 0 4446 834 669 750 861 0 4447 561 629 588 713 0 4448 713 561 506 588 0 4449 789 750 588 713 0 4450 713 669 750 588 0 4451 713 789 629 588 0 4452 669 506 588 713 0 4453 434 502 462 561 0 4454 561 434 391 462 0 4455 629 588 462 561 0 4456 561 506 588 462 0 4457 561 629 502 462 0 4458 506 391 462 561 0 4459 327 402 347 434 0 4460 434 327 296 347 0 4461 502 462 347 434 0 4462 434 391 462 347 0 4463 434 502 402 347 0 4464 391 296 347 434 0 4465 248 313 289 327 0 4466 327 248 223 289 0 4467 402 347 289 327 0 4468 327 296 347 289 0 4469 327 402 313 289 0 4470 296 223 289 327 0 4471 187 246 218 248 0 4472 248 187 162 218 0 4473 313 289 218 248 0 4474 248 223 289 218 0 4475 248 313 246 218 0 4476 223 162 218 248 0 4477 144 206 171 187 0 4478 187 144 127 171 0 4479 246 218 171 187 0 4480 187 162 218 171 0 4481 187 246 206 171 0 4482 162 127 171 187 0 4483 116 170 138 144 0 4484 144 116 89 138 0 4485 206 171 138 144 0 4486 144 127 171 138 0 4487 144 206 170 138 0 4488 127 89 138 144 0 4489 102 152 128 116 0 4490 116 102 81 128 0 4491 170 138 128 116 0 4492 116 89 138 128 0 4493 116 170 152 128 0 4494 89 81 128 116 0 4495 73 81 102 128 0 4496 128 152 102 73 0 4497 98 102 152 73 0 4498 73 98 149 152 0 4499 73 117 128 152 0 4500 117 149 152 73 0 4501 789 888 842 941 0 4502 941 789 750 842 0 4503 1008 982 842 941 0 4504 941 899 982 842 0 4505 941 1008 888 842 0 4506 899 750 842 941 0 4507 629 736 689 789 0 4508 789 629 588 689 0 4509 888 842 689 789 0 4510 789 750 842 689 0 4511 789 888 736 689 0 4512 750 588 689 789 0 4513 502 603 544 629 0 4514 629 502 462 544 0 4515 736 689 544 629 0 4516 629 588 689 544 0 4517 629 736 603 544 0 4518 588 462 544 629 0 4519 402 479 446 502 0 4520 502 402 347 446 0 4521 603 544 446 502 0 4522 502 462 544 446 0 4523 502 603 479 446 0 4524 462 347 446 502 0 4525 313 404 361 402 0 4526 402 313 289 361 0 4527 479 446 361 402 0 4528 402 347 446 361 0 4529 402 479 404 361 0 4530 347 289 361 402 0 4531 246 324 291 313 0 4532 313 246 218 291 0 4533 404 361 291 313 0 4534 313 289 361 291 0 4535 313 404 324 291 0 4536 289 218 291 313 0 4537 206 286 237 246 0 4538 246 206 171 237 0 4539 324 291 237 246 0 4540 246 218 291 237 0 4541 246 324 286 237 0 4542 218 171 237 246 0 4543 170 231 210 206 0 4544 206 170 138 210 0 4545 286 237 210 206 0 4546 206 171 237 210 0 4547 206 286 231 210 0 4548 171 138 210 206 0 4549 152 224 185 170 0 4550 170 152 128 185 0 4551 231 210 185 170 0 4552 170 138 210 185 0 4553 170 231 224 185 0 4554 138 128 185 170 0 4555 117 128 152 185 0 4556 185 224 152 117 0 4557 149 152 224 117 0 4558 117 149 220 224 0 4559 117 182 185 224 0 4560 182 220 224 117 0 4561 888 979 938 1008 0 4562 1008 888 842 938 0 4563 1087 1064 938 1008 0 4564 1008 982 1064 938 0 4565 1008 1087 979 938 0 4566 982 842 938 1008 0 4567 736 856 809 888 0 4568 888 736 689 809 0 4569 979 938 809 888 0 4570 888 842 938 809 0 4571 888 979 856 809 0 4572 842 689 809 888 0 4573 603 721 673 736 0 4574 736 603 544 673 0 4575 856 809 673 736 0 4576 736 689 809 673 0 4577 736 856 721 673 0 4578 689 544 673 736 0 4579 479 597 549 603 0 4580 603 479 446 549 0 4581 721 673 549 603 0 4582 603 544 673 549 0 4583 603 721 597 549 0 4584 544 446 549 603 0 4585 404 501 465 479 0 4586 479 404 361 465 0 4587 597 549 465 479 0 4588 479 446 549 465 0 4589 479 597 501 465 0 4590 446 361 465 479 0 4591 324 422 394 404 0 4592 404 324 291 394 0 4593 501 465 394 404 0 4594 404 361 465 394 0 4595 404 501 422 394 0 4596 361 291 394 404 0 4597 286 376 340 324 0 4598 324 286 237 340 0 4599 422 394 340 324 0 4600 324 291 394 340 0 4601 324 422 376 340 0 4602 291 237 340 324 0 4603 231 330 301 286 0 4604 286 231 210 301 0 4605 376 340 301 286 0 4606 286 237 340 301 0 4607 286 376 330 301 0 4608 237 210 301 286 0 4609 224 309 285 231 0 4610 231 224 185 285 0 4611 330 301 285 231 0 4612 231 210 301 285 0 4613 231 330 309 285 0 4614 210 185 285 231 0 4615 182 185 224 285 0 4616 285 309 224 182 0 4617 220 224 309 182 0 4618 182 220 304 309 0 4619 182 270 285 309 0 4620 270 304 309 182 0 4621 979 1071 1028 1087 0 4622 1087 979 938 1028 0 4623 1158 1145 1028 1087 0 4624 1087 1064 1145 1028 0 4625 1087 1158 1071 1028 0 4626 1064 938 1028 1087 0 4627 856 967 928 979 0 4628 979 856 809 928 0 4629 1071 1028 928 979 0 4630 979 938 1028 928 0 4631 979 1071 967 928 0 4632 938 809 928 979 0 4633 721 853 817 856 0 4634 856 721 673 817 0 4635 967 928 817 856 0 4636 856 809 928 817 0 4637 856 967 853 817 0 4638 809 673 817 856 0 4639 597 728 680 721 0 4640 721 597 549 680 0 4641 853 817 680 721 0 4642 721 673 817 680 0 4643 721 853 728 680 0 4644 673 549 680 721 0 4645 501 624 586 597 0 4646 597 501 465 586 0 4647 728 680 586 597 0 4648 597 549 680 586 0 4649 597 728 624 586 0 4650 549 465 586 597 0 4651 422 547 505 501 0 4652 501 422 394 505 0 4653 624 586 505 501 0 4654 501 465 586 505 0 4655 501 624 547 505 0 4656 465 394 505 501 0 4657 376 492 451 422 0 4658 422 376 340 451 0 4659 547 505 451 422 0 4660 422 394 505 451 0 4661 422 547 492 451 0 4662 394 340 451 422 0 4663 330 458 405 376 0 4664 376 330 301 405 0 4665 492 451 405 376 0 4666 376 340 451 405 0 4667 376 492 458 405 0 4668 340 301 405 376 0 4669 309 436 387 330 0 4670 330 309 285 387 0 4671 458 405 387 330 0 4672 330 301 405 387 0 4673 330 458 436 387 0 4674 301 285 387 330 0 4675 270 285 309 387 0 4676 387 436 309 270 0 4677 304 309 436 270 0 4678 270 304 419 436 0 4679 270 378 387 436 0 4680 378 419 436 270 0 4681 1071 1153 1134 1158 0 4682 1158 1071 1028 1134 0 4683 1224 1204 1134 1158 0 4684 1158 1145 1204 1134 0 4685 1158 1224 1153 1134 0 4686 1145 1028 1134 1158 0 4687 967 1076 1026 1071 0 4688 1071 967 928 1026 0 4689 1153 1134 1026 1071 0 4690 1071 1028 1134 1026 0 4691 1071 1153 1076 1026 0 4692 1028 928 1026 1071 0 4693 853 974 948 967 0 4694 967 853 817 948 0 4695 1076 1026 948 967 0 4696 967 928 1026 948 0 4697 967 1076 974 948 0 4698 928 817 948 967 0 4699 728 883 841 853 0 4700 853 728 680 841 0 4701 974 948 841 853 0 4702 853 817 948 841 0 4703 853 974 883 841 0 4704 817 680 841 853 0 4705 624 785 747 728 0 4706 728 624 586 747 0 4707 883 841 747 728 0 4708 728 680 841 747 0 4709 728 883 785 747 0 4710 680 586 747 728 0 4711 547 712 664 624 0 4712 624 547 505 664 0 4713 785 747 664 624 0 4714 624 586 747 664 0 4715 624 785 712 664 0 4716 586 505 664 624 0 4717 492 631 599 547 0 4718 547 492 451 599 0 4719 712 664 599 547 0 4720 547 505 664 599 0 4721 547 712 631 599 0 4722 505 451 599 547 0 4723 458 592 543 492 0 4724 492 458 405 543 0 4725 631 599 543 492 0 4726 492 451 599 543 0 4727 492 631 592 543 0 4728 451 405 543 492 0 4729 436 580 526 458 0 4730 458 436 387 526 0 4731 592 543 526 458 0 4732 458 405 543 526 0 4733 458 592 580 526 0 4734 405 387 526 458 0 4735 378 387 436 526 0 4736 526 580 436 378 0 4737 419 436 580 378 0 4738 378 419 567 580 0 4739 378 515 526 580 0 4740 515 567 580 378 0 4741 1204 1262 1272 1134 0 4742 1134 1204 1224 1272 0 4743 1212 1227 1272 1134 0 4744 1134 1153 1227 1272 0 4745 1134 1212 1262 1272 0 4746 1153 1224 1272 1134 0 4747 1134 1212 1227 1026 0 4748 1026 1134 1153 1227 0 4749 1142 1163 1227 1026 0 4750 1026 1076 1163 1227 0 4751 1026 1142 1212 1227 0 4752 1076 1153 1227 1026 0 4753 1026 1142 1163 948 0 4754 948 1026 1076 1163 0 4755 1061 1088 1163 948 0 4756 948 974 1088 1163 0 4757 948 1061 1142 1163 0 4758 974 1076 1163 948 0 4759 948 1061 1088 841 0 4760 841 948 974 1088 0 4761 985 1003 1088 841 0 4762 841 883 1003 1088 0 4763 841 985 1061 1088 0 4764 883 974 1088 841 0 4765 841 985 1003 747 0 4766 747 841 883 1003 0 4767 902 949 1003 747 0 4768 747 785 949 1003 0 4769 747 902 985 1003 0 4770 785 883 1003 747 0 4771 747 902 949 664 0 4772 664 747 785 949 0 4773 835 871 949 664 0 4774 664 712 871 949 0 4775 664 835 902 949 0 4776 712 785 949 664 0 4777 664 835 871 599 0 4778 599 664 712 871 0 4779 771 824 871 599 0 4780 599 631 824 871 0 4781 599 771 835 871 0 4782 631 712 871 599 0 4783 599 771 824 543 0 4784 543 599 631 824 0 4785 727 764 824 543 0 4786 543 592 764 824 0 4787 543 727 771 824 0 4788 592 631 824 543 0 4789 543 727 764 526 0 4790 526 543 592 764 0 4791 696 746 764 526 0 4792 526 580 746 764 0 4793 526 696 727 764 0 4794 580 592 764 526 0 4795 682 696 526 746 0 4796 746 580 526 682 0 4797 515 526 580 682 0 4798 682 515 567 580 0 4799 682 733 746 580 0 4800 733 567 580 682 0 4801 519 535 503 681 0 4802 681 519 490 503 0 4803 694 678 503 681 0 4804 681 665 678 503 0 4805 681 694 535 503 0 4806 665 490 503 681 0 4807 385 395 374 519 0 4808 519 385 353 374 0 4809 535 503 374 519 0 4810 519 490 503 374 0 4811 519 535 395 374 0 4812 490 353 374 519 0 4813 273 284 257 385 0 4814 385 273 249 257 0 4815 395 374 257 385 0 4816 385 353 374 257 0 4817 385 395 284 257 0 4818 353 249 257 385 0 4819 184 198 172 273 0 4820 273 184 169 172 0 4821 284 257 172 273 0 4822 273 249 257 172 0 4823 273 284 198 172 0 4824 249 169 172 273 0 4825 125 133 115 184 0 4826 184 125 109 115 0 4827 198 172 115 184 0 4828 184 169 172 115 0 4829 184 198 133 115 0 4830 169 109 115 184 0 4831 77 82 69 125 0 4832 125 77 62 69 0 4833 133 115 69 125 0 4834 125 109 115 69 0 4835 125 133 82 69 0 4836 109 62 69 125 0 4837 45 50 38 77 0 4838 77 45 35 38 0 4839 82 69 38 77 0 4840 77 62 69 38 0 4841 77 82 50 38 0 4842 62 35 38 77 0 4843 23 28 20 45 0 4844 45 23 17 20 0 4845 50 38 20 45 0 4846 45 35 38 20 0 4847 45 50 28 20 0 4848 35 17 20 45 0 4849 15 19 8 23 0 4850 23 15 5 8 0 4851 28 20 8 23 0 4852 23 17 20 8 0 4853 23 28 19 8 0 4854 17 5 8 23 0 4855 2 5 15 8 0 4856 8 19 15 2 0 4857 9 15 19 2 0 4858 2 9 14 19 0 4859 2 6 8 19 0 4860 6 14 19 2 0 4861 535 550 536 694 0 4862 694 535 503 536 0 4863 724 691 536 694 0 4864 694 678 691 536 0 4865 694 724 550 536 0 4866 678 503 536 694 0 4867 395 409 393 535 0 4868 535 395 374 393 0 4869 550 536 393 535 0 4870 535 503 536 393 0 4871 535 550 409 393 0 4872 503 374 393 535 0 4873 284 299 283 395 0 4874 395 284 257 283 0 4875 409 393 283 395 0 4876 395 374 393 283 0 4877 395 409 299 283 0 4878 374 257 283 395 0 4879 198 211 195 284 0 4880 284 198 172 195 0 4881 299 283 195 284 0 4882 284 257 283 195 0 4883 284 299 211 195 0 4884 257 172 195 284 0 4885 133 140 131 198 0 4886 198 133 115 131 0 4887 211 195 131 198 0 4888 198 172 195 131 0 4889 198 211 140 131 0 4890 172 115 131 198 0 4891 82 88 84 133 0 4892 133 82 69 84 0 4893 140 131 84 133 0 4894 133 115 131 84 0 4895 133 140 88 84 0 4896 115 69 84 133 0 4897 50 63 51 82 0 4898 82 50 38 51 0 4899 88 84 51 82 0 4900 82 69 84 51 0 4901 82 88 63 51 0 4902 69 38 51 82 0 4903 28 39 29 50 0 4904 50 28 20 29 0 4905 63 51 29 50 0 4906 50 38 51 29 0 4907 50 63 39 29 0 4908 38 20 29 50 0 4909 19 25 18 28 0 4910 28 19 8 18 0 4911 39 29 18 28 0 4912 28 20 29 18 0 4913 28 39 25 18 0 4914 20 8 18 28 0 4915 6 8 19 18 0 4916 18 25 19 6 0 4917 14 19 25 6 0 4918 6 14 22 25 0 4919 6 13 18 25 0 4920 13 22 25 6 0 4921 550 600 584 724 0 4922 724 550 536 584 0 4923 769 744 584 724 0 4924 724 691 744 584 0 4925 724 769 600 584 0 4926 691 536 584 724 0 4927 409 457 433 550 0 4928 550 409 393 433 0 4929 600 584 433 550 0 4930 550 536 584 433 0 4931 550 600 457 433 0 4932 536 393 433 550 0 4933 299 338 312 409 0 4934 409 299 283 312 0 4935 457 433 312 409 0 4936 409 393 433 312 0 4937 409 457 338 312 0 4938 393 283 312 409 0 4939 211 239 226 299 0 4940 299 211 195 226 0 4941 338 312 226 299 0 4942 299 283 312 226 0 4943 299 338 239 226 0 4944 283 195 226 299 0 4945 140 177 153 211 0 4946 211 140 131 153 0 4947 239 226 153 211 0 4948 211 195 226 153 0 4949 211 239 177 153 0 4950 195 131 153 211 0 4951 88 123 108 140 0 4952 140 88 84 108 0 4953 177 153 108 140 0 4954 140 131 153 108 0 4955 140 177 123 108 0 4956 131 84 108 140 0 4957 63 87 72 88 0 4958 88 63 51 72 0 4959 123 108 72 88 0 4960 88 84 108 72 0 4961 88 123 87 72 0 4962 84 51 72 88 0 4963 39 60 49 63 0 4964 63 39 29 49 0 4965 87 72 49 63 0 4966 63 51 72 49 0 4967 63 87 60 49 0 4968 51 29 49 63 0 4969 25 48 37 39 0 4970 39 25 18 37 0 4971 60 49 37 39 0 4972 39 29 49 37 0 4973 39 60 48 37 0 4974 29 18 37 39 0 4975 13 18 25 37 0 4976 37 48 25 13 0 4977 22 25 48 13 0 4978 13 22 41 48 0 4979 13 31 37 48 0 4980 31 41 48 13 0 4981 600 669 626 769 0 4982 769 600 584 626 0 4983 834 807 626 769 0 4984 769 744 807 626 0 4985 769 834 669 626 0 4986 744 584 626 769 0 4987 457 506 482 600 0 4988 600 457 433 482 0 4989 669 626 482 600 0 4990 600 584 626 482 0 4991 600 669 506 482 0 4992 584 433 482 600 0 4993 338 391 369 457 0 4994 457 338 312 369 0 4995 506 482 369 457 0 4996 457 433 482 369 0 4997 457 506 391 369 0 4998 433 312 369 457 0 4999 239 296 276 338 0 5000 338 239 226 276 0 5001 391 369 276 338 0 5002 338 312 369 276 0 5003 338 391 296 276 0 5004 312 226 276 338 0 5005 177 223 204 239 0 5006 239 177 153 204 0 5007 296 276 204 239 0 5008 239 226 276 204 0 5009 239 296 223 204 0 5010 226 153 204 239 0 5011 123 162 141 177 0 5012 177 123 108 141 0 5013 223 204 141 177 0 5014 177 153 204 141 0 5015 177 223 162 141 0 5016 153 108 141 177 0 5017 87 127 111 123 0 5018 123 87 72 111 0 5019 162 141 111 123 0 5020 123 108 141 111 0 5021 123 162 127 111 0 5022 108 72 111 123 0 5023 60 89 83 87 0 5024 87 60 49 83 0 5025 127 111 83 87 0 5026 87 72 111 83 0 5027 87 127 89 83 0 5028 72 49 83 87 0 5029 48 81 67 60 0 5030 60 48 37 67 0 5031 89 83 67 60 0 5032 60 49 83 67 0 5033 60 89 81 67 0 5034 49 37 67 60 0 5035 31 37 48 67 0 5036 67 81 48 31 0 5037 41 48 81 31 0 5038 31 41 73 81 0 5039 31 58 67 81 0 5040 58 73 81 31 0 5041 669 750 722 834 0 5042 834 669 626 722 0 5043 899 885 722 834 0 5044 834 807 885 722 0 5045 834 899 750 722 0 5046 807 626 722 834 0 5047 506 588 576 669 0 5048 669 506 482 576 0 5049 750 722 576 669 0 5050 669 626 722 576 0 5051 669 750 588 576 0 5052 626 482 576 669 0 5053 391 462 442 506 0 5054 506 391 369 442 0 5055 588 576 442 506 0 5056 506 482 576 442 0 5057 506 588 462 442 0 5058 482 369 442 506 0 5059 296 347 337 391 0 5060 391 296 276 337 0 5061 462 442 337 391 0 5062 391 369 442 337 0 5063 391 462 347 337 0 5064 369 276 337 391 0 5065 223 289 260 296 0 5066 296 223 204 260 0 5067 347 337 260 296 0 5068 296 276 337 260 0 5069 296 347 289 260 0 5070 276 204 260 296 0 5071 162 218 202 223 0 5072 223 162 141 202 0 5073 289 260 202 223 0 5074 223 204 260 202 0 5075 223 289 218 202 0 5076 204 141 202 223 0 5077 127 171 155 162 0 5078 162 127 111 155 0 5079 218 202 155 162 0 5080 162 141 202 155 0 5081 162 218 171 155 0 5082 141 111 155 162 0 5083 89 138 129 127 0 5084 127 89 83 129 0 5085 171 155 129 127 0 5086 127 111 155 129 0 5087 127 171 138 129 0 5088 111 83 129 127 0 5089 81 128 113 89 0 5090 89 81 67 113 0 5091 138 129 113 89 0 5092 89 83 129 113 0 5093 89 138 128 113 0 5094 83 67 113 89 0 5095 58 67 81 113 0 5096 113 128 81 58 0 5097 73 81 128 58 0 5098 58 73 117 128 0 5099 58 104 113 128 0 5100 104 117 128 58 0 5101 750 842 828 899 0 5102 899 750 722 828 0 5103 982 962 828 899 0 5104 899 885 962 828 0 5105 899 982 842 828 0 5106 885 722 828 899 0 5107 588 689 661 750 0 5108 750 588 576 661 0 5109 842 828 661 750 0 5110 750 722 828 661 0 5111 750 842 689 661 0 5112 722 576 661 750 0 5113 462 544 529 588 0 5114 588 462 442 529 0 5115 689 661 529 588 0 5116 588 576 661 529 0 5117 588 689 544 529 0 5118 576 442 529 588 0 5119 347 446 412 462 0 5120 462 347 337 412 0 5121 544 529 412 462 0 5122 462 442 529 412 0 5123 462 544 446 412 0 5124 442 337 412 462 0 5125 289 361 341 347 0 5126 347 289 260 341 0 5127 446 412 341 347 0 5128 347 337 412 341 0 5129 347 446 361 341 0 5130 337 260 341 347 0 5131 218 291 277 289 0 5132 289 218 202 277 0 5133 361 341 277 289 0 5134 289 260 341 277 0 5135 289 361 291 277 0 5136 260 202 277 289 0 5137 171 237 227 218 0 5138 218 171 155 227 0 5139 291 277 227 218 0 5140 218 202 277 227 0 5141 218 291 237 227 0 5142 202 155 227 218 0 5143 138 210 196 171 0 5144 171 138 129 196 0 5145 237 227 196 171 0 5146 171 155 227 196 0 5147 171 237 210 196 0 5148 155 129 196 171 0 5149 128 185 173 138 0 5150 138 128 113 173 0 5151 210 196 173 138 0 5152 138 129 196 173 0 5153 138 210 185 173 0 5154 129 113 173 138 0 5155 104 113 128 173 0 5156 173 185 128 104 0 5157 117 128 185 104 0 5158 104 117 182 185 0 5159 104 164 173 185 0 5160 164 182 185 104 0 5161 842 938 917 982 0 5162 982 842 828 917 0 5163 1064 1044 917 982 0 5164 982 962 1044 917 0 5165 982 1064 938 917 0 5166 962 828 917 982 0 5167 689 809 777 842 0 5168 842 689 661 777 0 5169 938 917 777 842 0 5170 842 828 917 777 0 5171 842 938 809 777 0 5172 828 661 777 842 0 5173 544 673 632 689 0 5174 689 544 529 632 0 5175 809 777 632 689 0 5176 689 661 777 632 0 5177 689 809 673 632 0 5178 661 529 632 689 0 5179 446 549 523 544 0 5180 544 446 412 523 0 5181 673 632 523 544 0 5182 544 529 632 523 0 5183 544 673 549 523 0 5184 529 412 523 544 0 5185 361 465 444 446 0 5186 446 361 341 444 0 5187 549 523 444 446 0 5188 446 412 523 444 0 5189 446 549 465 444 0 5190 412 341 444 446 0 5191 291 394 372 361 0 5192 361 291 277 372 0 5193 465 444 372 361 0 5194 361 341 444 372 0 5195 361 465 394 372 0 5196 341 277 372 361 0 5197 237 340 316 291 0 5198 291 237 227 316 0 5199 394 372 316 291 0 5200 291 277 372 316 0 5201 291 394 340 316 0 5202 277 227 316 291 0 5203 210 301 287 237 0 5204 237 210 196 287 0 5205 340 316 287 237 0 5206 237 227 316 287 0 5207 237 340 301 287 0 5208 227 196 287 237 0 5209 185 285 256 210 0 5210 210 185 173 256 0 5211 301 287 256 210 0 5212 210 196 287 256 0 5213 210 301 285 256 0 5214 196 173 256 210 0 5215 164 173 185 256 0 5216 256 285 185 164 0 5217 182 185 285 164 0 5218 164 182 270 285 0 5219 164 242 256 285 0 5220 242 270 285 164 0 5221 938 1028 1024 1064 0 5222 1064 938 917 1024 0 5223 1145 1130 1024 1064 0 5224 1064 1044 1130 1024 0 5225 1064 1145 1028 1024 0 5226 1044 917 1024 1064 0 5227 809 928 906 938 0 5228 938 809 777 906 0 5229 1028 1024 906 938 0 5230 938 917 1024 906 0 5231 938 1028 928 906 0 5232 917 777 906 938 0 5233 673 817 783 809 0 5234 809 673 632 783 0 5235 928 906 783 809 0 5236 809 777 906 783 0 5237 809 928 817 783 0 5238 777 632 783 809 0 5239 549 680 651 673 0 5240 673 549 523 651 0 5241 817 783 651 673 0 5242 673 632 783 651 0 5243 673 817 680 651 0 5244 632 523 651 673 0 5245 465 586 574 549 0 5246 549 465 444 574 0 5247 680 651 574 549 0 5248 549 523 651 574 0 5249 549 680 586 574 0 5250 523 444 574 549 0 5251 394 505 483 465 0 5252 465 394 372 483 0 5253 586 574 483 465 0 5254 465 444 574 483 0 5255 465 586 505 483 0 5256 444 372 483 465 0 5257 340 451 431 394 0 5258 394 340 316 431 0 5259 505 483 431 394 0 5260 394 372 483 431 0 5261 394 505 451 431 0 5262 372 316 431 394 0 5263 301 405 392 340 0 5264 340 301 287 392 0 5265 451 431 392 340 0 5266 340 316 431 392 0 5267 340 451 405 392 0 5268 316 287 392 340 0 5269 285 387 373 301 0 5270 301 285 256 373 0 5271 405 392 373 301 0 5272 301 287 392 373 0 5273 301 405 387 373 0 5274 287 256 373 301 0 5275 242 256 285 373 0 5276 373 387 285 242 0 5277 270 285 387 242 0 5278 242 270 378 387 0 5279 242 359 373 387 0 5280 359 378 387 242 0 5281 1028 1134 1108 1145 0 5282 1145 1028 1024 1108 0 5283 1204 1199 1108 1145 0 5284 1145 1130 1199 1108 0 5285 1145 1204 1134 1108 0 5286 1130 1024 1108 1145 0 5287 928 1026 1016 1028 0 5288 1028 928 906 1016 0 5289 1134 1108 1016 1028 0 5290 1028 1024 1108 1016 0 5291 1028 1134 1026 1016 0 5292 1024 906 1016 1028 0 5293 817 948 915 928 0 5294 928 817 783 915 0 5295 1026 1016 915 928 0 5296 928 906 1016 915 0 5297 928 1026 948 915 0 5298 906 783 915 928 0 5299 680 841 821 817 0 5300 817 680 651 821 0 5301 948 915 821 817 0 5302 817 783 915 821 0 5303 817 948 841 821 0 5304 783 651 821 817 0 5305 586 747 723 680 0 5306 680 586 574 723 0 5307 841 821 723 680 0 5308 680 651 821 723 0 5309 680 841 747 723 0 5310 651 574 723 680 0 5311 505 664 630 586 0 5312 586 505 483 630 0 5313 747 723 630 586 0 5314 586 574 723 630 0 5315 586 747 664 630 0 5316 574 483 630 586 0 5317 451 599 585 505 0 5318 505 451 431 585 0 5319 664 630 585 505 0 5320 505 483 630 585 0 5321 505 664 599 585 0 5322 483 431 585 505 0 5323 405 543 537 451 0 5324 451 405 392 537 0 5325 599 585 537 451 0 5326 451 431 585 537 0 5327 451 599 543 537 0 5328 431 392 537 451 0 5329 387 526 504 405 0 5330 405 387 373 504 0 5331 543 537 504 405 0 5332 405 392 537 504 0 5333 405 543 526 504 0 5334 392 373 504 405 0 5335 359 373 387 504 0 5336 504 526 387 359 0 5337 378 387 526 359 0 5338 359 378 515 526 0 5339 359 495 504 526 0 5340 495 515 526 359 0 5341 1199 1260 1262 1108 0 5342 1108 1199 1204 1262 0 5343 1201 1212 1262 1108 0 5344 1108 1134 1212 1262 0 5345 1108 1201 1260 1262 0 5346 1134 1204 1262 1108 0 5347 1108 1201 1212 1016 0 5348 1016 1108 1134 1212 0 5349 1126 1142 1212 1016 0 5350 1016 1026 1142 1212 0 5351 1016 1126 1201 1212 0 5352 1026 1134 1212 1016 0 5353 1016 1126 1142 915 0 5354 915 1016 1026 1142 0 5355 1050 1061 1142 915 0 5356 915 948 1061 1142 0 5357 915 1050 1126 1142 0 5358 948 1026 1142 915 0 5359 915 1050 1061 821 0 5360 821 915 948 1061 0 5361 966 985 1061 821 0 5362 821 841 985 1061 0 5363 821 966 1050 1061 0 5364 841 948 1061 821 0 5365 821 966 985 723 0 5366 723 821 841 985 0 5367 886 902 985 723 0 5368 723 747 902 985 0 5369 723 886 966 985 0 5370 747 841 985 723 0 5371 723 886 902 630 0 5372 630 723 747 902 0 5373 816 835 902 630 0 5374 630 664 835 902 0 5375 630 816 886 902 0 5376 664 747 902 630 0 5377 630 816 835 585 0 5378 585 630 664 835 0 5379 757 771 835 585 0 5380 585 599 771 835 0 5381 585 757 816 835 0 5382 599 664 835 585 0 5383 585 757 771 537 0 5384 537 585 599 771 0 5385 695 727 771 537 0 5386 537 543 727 771 0 5387 537 695 757 771 0 5388 543 599 771 537 0 5389 537 695 727 504 0 5390 504 537 543 727 0 5391 677 696 727 504 0 5392 504 526 696 727 0 5393 504 677 695 727 0 5394 526 543 727 504 0 5395 662 677 504 696 0 5396 696 526 504 662 0 5397 495 504 526 662 0 5398 662 495 515 526 0 5399 662 682 696 526 0 5400 682 515 526 662 0 5401 665 678 503 641 0 5402 641 665 490 503 0 5403 660 493 503 641 0 5404 641 478 493 503 0 5405 641 660 678 503 0 5406 478 490 503 641 0 5407 490 503 374 478 0 5408 478 490 353 374 0 5409 493 356 374 478 0 5410 478 342 356 374 0 5411 478 493 503 374 0 5412 342 353 374 478 0 5413 353 374 257 342 0 5414 342 353 249 257 0 5415 356 251 257 342 0 5416 342 233 251 257 0 5417 342 356 374 257 0 5418 233 249 257 342 0 5419 249 257 172 233 0 5420 233 249 169 172 0 5421 251 167 172 233 0 5422 233 159 167 172 0 5423 233 251 257 172 0 5424 159 169 172 233 0 5425 169 172 115 159 0 5426 159 169 109 115 0 5427 167 107 115 159 0 5428 159 95 107 115 0 5429 159 167 172 115 0 5430 95 109 115 159 0 5431 109 115 69 95 0 5432 95 109 62 69 0 5433 107 59 69 95 0 5434 95 53 59 69 0 5435 95 107 115 69 0 5436 53 62 69 95 0 5437 62 69 38 53 0 5438 53 62 35 38 0 5439 59 33 38 53 0 5440 53 26 33 38 0 5441 53 59 69 38 0 5442 26 35 38 53 0 5443 35 38 20 26 0 5444 26 35 17 20 0 5445 33 12 20 26 0 5446 26 10 12 20 0 5447 26 33 38 20 0 5448 10 17 20 26 0 5449 17 20 8 10 0 5450 10 17 5 8 0 5451 12 7 8 10 0 5452 10 3 7 8 0 5453 10 12 20 8 0 5454 3 5 8 10 0 5455 3 7 8 1 0 5456 1 3 5 8 0 5457 4 6 8 1 0 5458 1 2 6 8 0 5459 1 4 7 8 0 5460 2 5 8 1 0 5461 678 691 536 660 0 5462 660 678 503 536 0 5463 684 522 536 660 0 5464 660 493 522 536 0 5465 660 684 691 536 0 5466 493 503 536 660 0 5467 503 536 393 493 0 5468 493 503 374 393 0 5469 522 381 393 493 0 5470 493 356 381 393 0 5471 493 522 536 393 0 5472 356 374 393 493 0 5473 374 393 283 356 0 5474 356 374 257 283 0 5475 381 275 283 356 0 5476 356 251 275 283 0 5477 356 381 393 283 0 5478 251 257 283 356 0 5479 257 283 195 251 0 5480 251 257 172 195 0 5481 275 180 195 251 0 5482 251 167 180 195 0 5483 251 275 283 195 0 5484 167 172 195 251 0 5485 172 195 131 167 0 5486 167 172 115 131 0 5487 180 120 131 167 0 5488 167 107 120 131 0 5489 167 180 195 131 0 5490 107 115 131 167 0 5491 115 131 84 107 0 5492 107 115 69 84 0 5493 120 76 84 107 0 5494 107 59 76 84 0 5495 107 120 131 84 0 5496 59 69 84 107 0 5497 69 84 51 59 0 5498 59 69 38 51 0 5499 76 43 51 59 0 5500 59 33 43 51 0 5501 59 76 84 51 0 5502 33 38 51 59 0 5503 38 51 29 33 0 5504 33 38 20 29 0 5505 43 21 29 33 0 5506 33 12 21 29 0 5507 33 43 51 29 0 5508 12 20 29 33 0 5509 20 29 18 12 0 5510 12 20 8 18 0 5511 21 16 18 12 0 5512 12 7 16 18 0 5513 12 21 29 18 0 5514 7 8 18 12 0 5515 7 16 18 4 0 5516 4 7 8 18 0 5517 11 13 18 4 0 5518 4 6 13 18 0 5519 4 11 16 18 0 5520 6 8 18 4 0 5521 691 744 584 684 0 5522 684 691 536 584 0 5523 732 570 584 684 0 5524 684 522 570 584 0 5525 684 732 744 584 0 5526 522 536 584 684 0 5527 536 584 433 522 0 5528 522 536 393 433 0 5529 570 416 433 522 0 5530 522 381 416 433 0 5531 522 570 584 433 0 5532 381 393 433 522 0 5533 393 433 312 381 0 5534 381 393 283 312 0 5535 416 307 312 381 0 5536 381 275 307 312 0 5537 381 416 433 312 0 5538 275 283 312 381 0 5539 283 312 226 275 0 5540 275 283 195 226 0 5541 307 217 226 275 0 5542 275 180 217 226 0 5543 275 307 312 226 0 5544 180 195 226 275 0 5545 195 226 153 180 0 5546 180 195 131 153 0 5547 217 145 153 180 0 5548 180 120 145 153 0 5549 180 217 226 153 0 5550 120 131 153 180 0 5551 131 153 108 120 0 5552 120 131 84 108 0 5553 145 94 108 120 0 5554 120 76 94 108 0 5555 120 145 153 108 0 5556 76 84 108 120 0 5557 84 108 72 76 0 5558 76 84 51 72 0 5559 94 68 72 76 0 5560 76 43 68 72 0 5561 76 94 108 72 0 5562 43 51 72 76 0 5563 51 72 49 43 0 5564 43 51 29 49 0 5565 68 42 49 43 0 5566 43 21 42 49 0 5567 43 68 72 49 0 5568 21 29 49 43 0 5569 29 49 37 21 0 5570 21 29 18 37 0 5571 42 32 37 21 0 5572 21 16 32 37 0 5573 21 42 49 37 0 5574 16 18 37 21 0 5575 16 32 37 11 0 5576 11 16 18 37 0 5577 24 31 37 11 0 5578 11 13 31 37 0 5579 11 24 32 37 0 5580 13 18 37 11 0 5581 744 807 626 732 0 5582 732 744 584 626 0 5583 795 613 626 732 0 5584 732 570 613 626 0 5585 732 795 807 626 0 5586 570 584 626 732 0 5587 584 626 482 570 0 5588 570 584 433 482 0 5589 613 467 482 570 0 5590 570 416 467 482 0 5591 570 613 626 482 0 5592 416 433 482 570 0 5593 433 482 369 416 0 5594 416 433 312 369 0 5595 467 357 369 416 0 5596 416 307 357 369 0 5597 416 467 482 369 0 5598 307 312 369 416 0 5599 312 369 276 307 0 5600 307 312 226 276 0 5601 357 266 276 307 0 5602 307 217 266 276 0 5603 307 357 369 276 0 5604 217 226 276 307 0 5605 226 276 204 217 0 5606 217 226 153 204 0 5607 266 194 204 217 0 5608 217 145 194 204 0 5609 217 266 276 204 0 5610 145 153 204 217 0 5611 153 204 141 145 0 5612 145 153 108 141 0 5613 194 135 141 145 0 5614 145 94 135 141 0 5615 145 194 204 141 0 5616 94 108 141 145 0 5617 108 141 111 94 0 5618 94 108 72 111 0 5619 135 99 111 94 0 5620 94 68 99 111 0 5621 94 135 141 111 0 5622 68 72 111 94 0 5623 72 111 83 68 0 5624 68 72 49 83 0 5625 99 74 83 68 0 5626 68 42 74 83 0 5627 68 99 111 83 0 5628 42 49 83 68 0 5629 49 83 67 42 0 5630 42 49 37 67 0 5631 74 61 67 42 0 5632 42 32 61 67 0 5633 42 74 83 67 0 5634 32 37 67 42 0 5635 32 61 67 24 0 5636 24 32 37 67 0 5637 52 58 67 24 0 5638 24 31 58 67 0 5639 24 52 61 67 0 5640 31 37 67 24 0 5641 807 885 722 795 0 5642 795 807 626 722 0 5643 863 714 722 795 0 5644 795 613 714 722 0 5645 795 863 885 722 0 5646 613 626 722 795 0 5647 626 722 576 613 0 5648 613 626 482 576 0 5649 714 557 576 613 0 5650 613 467 557 576 0 5651 613 714 722 576 0 5652 467 482 576 613 0 5653 482 576 442 467 0 5654 467 482 369 442 0 5655 557 435 442 467 0 5656 467 357 435 442 0 5657 467 557 576 442 0 5658 357 369 442 467 0 5659 369 442 337 357 0 5660 357 369 276 337 0 5661 435 320 337 357 0 5662 357 266 320 337 0 5663 357 435 442 337 0 5664 266 276 337 357 0 5665 276 337 260 266 0 5666 266 276 204 260 0 5667 320 244 260 266 0 5668 266 194 244 260 0 5669 266 320 337 260 0 5670 194 204 260 266 0 5671 204 260 202 194 0 5672 194 204 141 202 0 5673 244 189 202 194 0 5674 194 135 189 202 0 5675 194 244 260 202 0 5676 135 141 202 194 0 5677 141 202 155 135 0 5678 135 141 111 155 0 5679 189 146 155 135 0 5680 135 99 146 155 0 5681 135 189 202 155 0 5682 99 111 155 135 0 5683 111 155 129 99 0 5684 99 111 83 129 0 5685 146 119 129 99 0 5686 99 74 119 129 0 5687 99 146 155 129 0 5688 74 83 129 99 0 5689 83 129 113 74 0 5690 74 83 67 113 0 5691 119 105 113 74 0 5692 74 61 105 113 0 5693 74 119 129 113 0 5694 61 67 113 74 0 5695 61 105 113 52 0 5696 52 61 67 113 0 5697 96 104 113 52 0 5698 52 58 104 113 0 5699 52 96 105 113 0 5700 58 67 113 52 0 5701 885 962 828 863 0 5702 863 885 722 828 0 5703 954 808 828 863 0 5704 863 714 808 828 0 5705 863 954 962 828 0 5706 714 722 828 863 0 5707 722 828 661 714 0 5708 714 722 576 661 0 5709 808 645 661 714 0 5710 714 557 645 661 0 5711 714 808 828 661 0 5712 557 576 661 714 0 5713 576 661 529 557 0 5714 557 576 442 529 0 5715 645 521 529 557 0 5716 557 435 521 529 0 5717 557 645 661 529 0 5718 435 442 529 557 0 5719 442 529 412 435 0 5720 435 442 337 412 0 5721 521 408 412 435 0 5722 435 320 408 412 0 5723 435 521 529 412 0 5724 320 337 412 435 0 5725 337 412 341 320 0 5726 320 337 260 341 0 5727 408 323 341 320 0 5728 320 244 323 341 0 5729 320 408 412 341 0 5730 244 260 341 320 0 5731 260 341 277 244 0 5732 244 260 202 277 0 5733 323 264 277 244 0 5734 244 189 264 277 0 5735 244 323 341 277 0 5736 189 202 277 244 0 5737 202 277 227 189 0 5738 189 202 155 227 0 5739 264 216 227 189 0 5740 189 146 216 227 0 5741 189 264 277 227 0 5742 146 155 227 189 0 5743 155 227 196 146 0 5744 146 155 129 196 0 5745 216 181 196 146 0 5746 146 119 181 196 0 5747 146 216 227 196 0 5748 119 129 196 146 0 5749 129 196 173 119 0 5750 119 129 113 173 0 5751 181 166 173 119 0 5752 119 105 166 173 0 5753 119 181 196 173 0 5754 105 113 173 119 0 5755 105 166 173 96 0 5756 96 105 113 173 0 5757 160 164 173 96 0 5758 96 104 164 173 0 5759 96 160 166 173 0 5760 104 113 173 96 0 5761 962 1044 917 954 0 5762 954 962 828 917 0 5763 1029 912 917 954 0 5764 954 808 912 917 0 5765 954 1029 1044 917 0 5766 808 828 917 954 0 5767 828 917 777 808 0 5768 808 828 661 777 0 5769 912 770 777 808 0 5770 808 645 770 777 0 5771 808 912 917 777 0 5772 645 661 777 808 0 5773 661 777 632 645 0 5774 645 661 529 632 0 5775 770 620 632 645 0 5776 645 521 620 632 0 5777 645 770 777 632 0 5778 521 529 632 645 0 5779 529 632 523 521 0 5780 521 529 412 523 0 5781 620 514 523 521 0 5782 521 408 514 523 0 5783 521 620 632 523 0 5784 408 412 523 521 0 5785 412 523 444 408 0 5786 408 412 341 444 0 5787 514 421 444 408 0 5788 408 323 421 444 0 5789 408 514 523 444 0 5790 323 341 444 408 0 5791 341 444 372 323 0 5792 323 341 277 372 0 5793 421 350 372 323 0 5794 323 264 350 372 0 5795 323 421 444 372 0 5796 264 277 372 323 0 5797 277 372 316 264 0 5798 264 277 227 316 0 5799 350 305 316 264 0 5800 264 216 305 316 0 5801 264 350 372 316 0 5802 216 227 316 264 0 5803 227 316 287 216 0 5804 216 227 196 287 0 5805 305 269 287 216 0 5806 216 181 269 287 0 5807 216 305 316 287 0 5808 181 196 287 216 0 5809 196 287 256 181 0 5810 181 196 173 256 0 5811 269 240 256 181 0 5812 181 166 240 256 0 5813 181 269 287 256 0 5814 166 173 256 181 0 5815 166 240 256 160 0 5816 160 166 173 256 0 5817 235 242 256 160 0 5818 160 164 242 256 0 5819 160 235 240 256 0 5820 164 173 256 160 0 5821 1044 1130 1024 1029 0 5822 1029 1044 917 1024 0 5823 1116 1009 1024 1029 0 5824 1029 912 1009 1024 0 5825 1029 1116 1130 1024 0 5826 912 917 1024 1029 0 5827 917 1024 906 912 0 5828 912 917 777 906 0 5829 1009 891 906 912 0 5830 912 770 891 906 0 5831 912 1009 1024 906 0 5832 770 777 906 912 0 5833 777 906 783 770 0 5834 770 777 632 783 0 5835 891 762 783 770 0 5836 770 620 762 783 0 5837 770 891 906 783 0 5838 620 632 783 770 0 5839 632 783 651 620 0 5840 620 632 523 651 0 5841 762 648 651 620 0 5842 620 514 648 651 0 5843 620 762 783 651 0 5844 514 523 651 620 0 5845 523 651 574 514 0 5846 514 523 444 574 0 5847 648 551 574 514 0 5848 514 421 551 574 0 5849 514 648 651 574 0 5850 421 444 574 514 0 5851 444 574 483 421 0 5852 421 444 372 483 0 5853 551 466 483 421 0 5854 421 350 466 483 0 5855 421 551 574 483 0 5856 350 372 483 421 0 5857 372 483 431 350 0 5858 350 372 316 431 0 5859 466 411 431 350 0 5860 350 305 411 431 0 5861 350 466 483 431 0 5862 305 316 431 350 0 5863 316 431 392 305 0 5864 305 316 287 392 0 5865 411 386 392 305 0 5866 305 269 386 392 0 5867 305 411 431 392 0 5868 269 287 392 305 0 5869 287 392 373 269 0 5870 269 287 256 373 0 5871 386 362 373 269 0 5872 269 240 362 373 0 5873 269 386 392 373 0 5874 240 256 373 269 0 5875 240 362 373 235 0 5876 235 240 256 373 0 5877 343 359 373 235 0 5878 235 242 359 373 0 5879 235 343 362 373 0 5880 242 256 373 235 0 5881 1130 1199 1108 1116 0 5882 1116 1130 1024 1108 0 5883 1187 1105 1108 1116 0 5884 1116 1009 1105 1108 0 5885 1116 1187 1199 1108 0 5886 1009 1024 1108 1116 0 5887 1024 1108 1016 1009 0 5888 1009 1024 906 1016 0 5889 1105 1001 1016 1009 0 5890 1009 891 1001 1016 0 5891 1009 1105 1108 1016 0 5892 891 906 1016 1009 0 5893 906 1016 915 891 0 5894 891 906 783 915 0 5895 1001 913 915 891 0 5896 891 762 913 915 0 5897 891 1001 1016 915 0 5898 762 783 915 891 0 5899 783 915 821 762 0 5900 762 783 651 821 0 5901 913 820 821 762 0 5902 762 648 820 821 0 5903 762 913 915 821 0 5904 648 651 821 762 0 5905 651 821 723 648 0 5906 648 651 574 723 0 5907 820 709 723 648 0 5908 648 551 709 723 0 5909 648 820 821 723 0 5910 551 574 723 648 0 5911 574 723 630 551 0 5912 551 574 483 630 0 5913 709 609 630 551 0 5914 551 466 609 630 0 5915 551 709 723 630 0 5916 466 483 630 551 0 5917 483 630 585 466 0 5918 466 483 431 585 0 5919 609 564 585 466 0 5920 466 411 564 585 0 5921 466 609 630 585 0 5922 411 431 585 466 0 5923 431 585 537 411 0 5924 411 431 392 537 0 5925 564 511 537 411 0 5926 411 386 511 537 0 5927 411 564 585 537 0 5928 386 392 537 411 0 5929 392 537 504 386 0 5930 386 392 373 504 0 5931 511 488 504 386 0 5932 386 362 488 504 0 5933 386 511 537 504 0 5934 362 373 504 386 0 5935 362 488 504 343 0 5936 343 362 373 504 0 5937 480 495 504 343 0 5938 343 359 495 504 0 5939 343 480 488 504 0 5940 359 373 504 343 0 5941 1105 1193 1251 1108 0 5942 1108 1105 1187 1251 0 5943 1201 1260 1251 1108 0 5944 1108 1199 1260 1251 0 5945 1108 1201 1193 1251 0 5946 1199 1187 1251 1108 0 5947 1001 1110 1193 1016 0 5948 1016 1001 1105 1193 0 5949 1126 1201 1193 1016 0 5950 1016 1108 1201 1193 0 5951 1016 1126 1110 1193 0 5952 1108 1105 1193 1016 0 5953 913 1034 1110 915 0 5954 915 913 1001 1110 0 5955 1050 1126 1110 915 0 5956 915 1016 1126 1110 0 5957 915 1050 1034 1110 0 5958 1016 1001 1110 915 0 5959 820 951 1034 821 0 5960 821 820 913 1034 0 5961 966 1050 1034 821 0 5962 821 915 1050 1034 0 5963 821 966 951 1034 0 5964 915 913 1034 821 0 5965 709 870 951 723 0 5966 723 709 820 951 0 5967 886 966 951 723 0 5968 723 821 966 951 0 5969 723 886 870 951 0 5970 821 820 951 723 0 5971 609 794 870 630 0 5972 630 609 709 870 0 5973 816 886 870 630 0 5974 630 723 886 870 0 5975 630 816 794 870 0 5976 723 709 870 630 0 5977 564 734 794 585 0 5978 585 564 609 794 0 5979 757 816 794 585 0 5980 585 630 816 794 0 5981 585 757 734 794 0 5982 630 609 794 585 0 5983 511 685 734 537 0 5984 537 511 564 734 0 5985 695 757 734 537 0 5986 537 585 757 734 0 5987 537 695 685 734 0 5988 585 564 734 537 0 5989 488 663 685 504 0 5990 504 488 511 685 0 5991 677 695 685 504 0 5992 504 537 695 685 0 5993 504 677 663 685 0 5994 537 511 685 504 0 5995 495 662 644 504 0 5996 504 495 480 644 0 5997 677 663 644 504 0 5998 504 488 663 644 0 5999 504 677 662 644 0 6000 488 480 644 504 0 ]; %% Variable Prescribed % Node Dimension Value % lnodes = [ % ]; % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % vertices = get_vertices(gidcoord); dirichlet_data = [ ]; for i = 1:length(vertices) verticeNumber = vertices(i,1); for j = 1:3 dirichlet_data = [dirichlet_data;[verticeNumber j 0]]; end end % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % dirichlet_data = [ ]; ?? % lnodes2 = [ 1 1 0 % 1 2 0 % 1 3 0 % 1538 1 0 % 1538 2 0 % 1538 3 0 % 1539 1 0 % 1539 2 0 % 1539 3 0 % 1540 1 0 % 1540 2 0 % 1540 3 0 % 2927 1 0 % 2927 2 0 % 2927 3 0 % 2928 1 0 % 2928 2 0 % 2928 3 0 % 2929 1 0 % 2929 2 0 % 2929 3 0 % 3080 1 0 % 3080 2 0 % 3080 3 0 % ]; %% Force Prescribed % Node Dimension Value pointload_complete = [ ]; %% Volumetric Force % Element Dim Force_Dim Vol_force = [ ]; %% Group Elements % Element Group_num Group = [ ]; %% Initial Holes % Elements that are considered holes initially % Element Initial_holes = [ ]; %% Boundary Elements % Elements that can not be removed % Element Boundary_elements = [ ]; %% Micro gauss post % % Element Micro_gauss_post = [ ]; %% Micro Slave-Master % Nodes that are Slaves % Nodes Value (1-Slave,0-Master) % Micro_slave = get_MasterSlave(gidcoord,vertices); % Micro_slave = [ % ]; %% Nodes solid % Nodes that must remain % Nodes % nodesolid = unique(pointload_complete(:,1)); %% External border Elements % Detect the elements that define the edge of the domain % Element Node(1) Node(2) External_border_elements = [ ]; %% External border Nodes % Detect the nodes that define the edge of the domain % Node External_border_nodes = [ ]; %% Materials % Materials that have been used % Material_Num Mat_density Young_Modulus Poisson Materials = [ ]; %% FUNCTIONS (passar a classes!) function vertices = get_vertices(gidcoord) vertices = []; for i = 1:length(gidcoord) nodeGID = gidcoord(i,:); nodeCoords = gidcoord(i,2:4); if (isequal(nodeCoords, [0,0,0]) || isequal(nodeCoords, [0,0,1]) || ... isequal(nodeCoords, [0,1,0]) || isequal(nodeCoords, [1,0,0]) || ... isequal(nodeCoords, [0,1,1]) || isequal(nodeCoords, [1,0,1]) || ... isequal(nodeCoords, [1,1,0]) || isequal(nodeCoords, [1,1,1])) vertices = [vertices; nodeGID]; end end end function MS = get_MasterSlave(gidcoord,vertices) MS = [ ]; for i = 1:length(gidcoord) nodeCoords = gidcoord(i,2:4); if ismember(gidcoord(i,:),vertices,'rows') else % if node is not a vertice if any(nodeCoords==0) xCoord = gidcoord(i,2); yCoord = gidcoord(i,3); zCoord = gidcoord(i,4); if xCoord==0 for j = 1:length(gidcoord) nodeCompared = gidcoord(j,2:4); nodeSuposed = [xCoord+1,yCoord,zCoord]; if (isequal(nodeCompared,nodeSuposed)) MS = [MS; [gidcoord(i,1) gidcoord(j,1)]]; end end end if yCoord==0 for j = 1:length(gidcoord) nodeCompared = gidcoord(j,2:4); nodeSuposed = [xCoord,yCoord+1,zCoord]; if (isequal(nodeCompared,nodeSuposed)) MS = [MS; [gidcoord(i,1) gidcoord(j,1)]]; end end end if zCoord==0 for j = 1:length(gidcoord) nodeCompared = gidcoord(j,2:4); nodeSuposed = [xCoord,yCoord,zCoord+1]; if (isequal(nodeCompared,nodeSuposed)) MS = [MS; [gidcoord(i,1) gidcoord(j,1)]]; end end end end end end end
github
SwanLab/Swan-master
PlaneOfResiduals.m
.m
Swan-master/Vigdergauz/Understunding/PlaneOfResiduals.m
1,518
utf_8
1ef438b0307f2ba91420175d20cca1a9
function PlaneOfResiduals rhoOptimal = 0.2;%0.61; tanXiV = tan(20*pi/80); %tanXiV = 0.9; r1_0 = 0.97; r2_0 = 0.99; r2o = 0.998709640937773; r1o = 0.998709640937773; r0 = [r2o;r1o] computeResidual(r0,rhoOptimal,tanXiV) eps = 1e-13; n1 = 20; n2 = 20; r1V = linspace(0.8,1-eps,n1); r2V = linspace(0.8,1-eps,n2); for i = 1:n1 for j = 1:n2 r1 = r1V(i); r2 = r2V(j); res = computeResidual([r1,r2],rhoOptimal,tanXiV); ResTxi(i,j) = abs(res(1)); ResRho(i,j) = abs(res(2)); end i end figure(1) surf(r1V,r2V,ResTxi') figure(2) contour(r1V,r2V,ResTxi,50) figure(3) surf(r1V,r2V,ResRho') figure(4) contour(r1V,r2V,ResRho,50) end function res = computeResidual(r,rhoOptimal,tanXiV) res(1) = computeTxi(r,tanXiV); res(2) = computeRho(r,rhoOptimal); end function [res,dres] = computeTxi(r,tanXiV) r = real(r); r1 = r(1); r2 = r(2:end); R = (1-r1).*(1-r2)./(r1.*r2); F = @(x,k) ellipticF(asin(x),k); f = @(r) F(sqrt(1-R),r); s = @(r) f(r)./F(1,r); t = @(r) F(1,1-r)./F(1,r); s1 = s(r1); s2 = s(r2); t1 = t(r1); t2 = t(r2); m1 = (1-t1)./(1-t1.*t2).*s1; m2 = (1-t2)./(1-t1.*t2).*s2; tanXi = (1-t1)./(1-t2).*s1./s2; %res = tan(txiV) - tanXi; res = tanXiV - tanXi; dres = []; end function [res,dres] = computeRho(r,rhoV) r = real(r); r1 = r(1:end-1); r2 = r(end); F = @(x,k) ellipticF(asin(x),k); t = @(r) F(1,1-r)./F(1,r); t1 = t(r1); t2 = t(r2); rho = 1 - (t1.*(1-t2) + t2.*(1 - t1))./(1-t1.*t2); res = rho - rhoV; res = real(res); dres = []; end
github
SwanLab/Swan-master
understundingVigdergauz.m
.m
Swan-master/Vigdergauz/Understunding/understundingVigdergauz.m
7,777
utf_8
d1788294d4b548df453add891f916e25
function understundingVigdergauz x0 = [0.8,0.8]; fun = @(x) computeEquations(x); mesh = createMesh; % problem.objective = fun; % problem.x0 = x0; % problem.solver = 'fsolve'; % problem.lb = [0,0]; % problem.ub = [1,1]; % problem.options = optimset('Display','iter'); % % [x,fsol] = fsolve(problem) r2o = 0.998709640937773; r1o = 0.998709640937773; r0 = [r1o,r2o]; res1 = computeTxi(r0); res2 = computeRho(r0); eps = 0.05; r1 = 0.97; r2 = 0.99;%z2new = r2; TOL = 1e-12; %[r,error1] = solveCase1(r1,r2,TOL); [r,error2] = solveCase2(r1,r2,TOL,mesh); %[r,error3] = solveCase3(r1,r2,TOL); figure(1) semilogy(error1(1:2:end,1)) hold on semilogy(error2(1:2:end,1)) %hold on %semilogy(error3(1:2:end,1)) end function m = createMesh() [coord,connec] = readFile(); s.coord = coord(:,2:3); s.connec = connec(:,2:4); m = Mesh().create(s); end function [coord,connec] = readFile() run('test2d_micro'); end function [z,error] = solveCase1(z1,z2,TOL) error = 1; i = 1; while error(i) > TOL [x1new,x2new] = resolvent1(z1,z2); z1new = 0.5*(x1new + z1); z2new = 0.5*(x2new + z2); i = i+1; error(i,1) = computeError([z1new,z2new]); [x1newnew,x2newnew] = resolvent2(z1new,z2new); z1newnew = 0.5*(x1newnew + z1new); z2newnew = 0.5*(x2newnew + z2new); z1 = z1newnew; z2 = z2newnew; i = i+1; error(i,1) = computeError([z1,z2]); end z = [z1,z2]; end function [z,error] = solveCase2(z1,z2,TOL,m) error = 1; i = 1; z = [z1,z2]; zT(1,:) = z; plotImages(zT,z,error,m) a = 2; b = -1; eps = 1e-12; while error(i) > TOL xNew = resolvent2(z); % z1new = z1; % z2new = z2; %zNew(:) = min(1-eps,max(0.8,a*xNew + b*z)); % c = 0.5; % cNew = 0.5; % c = 0; % cNew = 1; % c = -1; cNew = 2; zNew = (cNew*xNew + c*z); % z1new = x1new; % z2new = x2new; i = i+1; zT(i,:) = zNew; error(i,1) = computeError(zNew); plotImages(zT,zNew,error,m) xNewNew = resolvent1(zNew); cNew = 0; cNewNew = 1; % cNew = 0.5; % cNewNew = 0.5; % % cNew = -1; % cNewNew = 2; zNewNew = cNewNew*xNewNew + cNew*zNew; %zNewNew(:) = min(1-eps,max(0.8,a*xNewNew + b*zNew)); % z1newnew = (x1newnew ); % z2newnew = (x2newnew ); i = i+1; zT(i,:) = zNewNew; error(i,1) = computeError(zNewNew); plotImages(zT,zNewNew,error,m) % c = 0; % cNew = 0; % cNewNew = 1; c = 1; cNew = 0; cNewNew = 1; d = -1; z = cNewNew*zNewNew + cNew*zNew + c*z + d*xNew; end z = [z1,z2]; end function plotImages(zT,zNew,error,m) figure(1) delete(gca) plot(zT(:,1),zT(:,2),'-+') axis([0.8 1 0.8 1]) %error(1:2:end) figure(2) semilogy(error(1:end,1)) drawnow ls = computeLevelSet(m.coord,zNew); s.meshBackground = m; s.unfittedType = 'INTERIOR'; figure(3) delete(gca) uM = UnfittedMesh(s); uM.compute(ls); uM.plot() drawnow end function [z,error] = solveCase3(z1,z2,TOL) error = 1; i = 1; z = [z1,z2]'; while error(i) > TOL xnew = projection2(z); znew = 0.5*(xnew + z); i = i+1; error(i,1) = computeError(znew); [xnewnew] = projection1(znew); znewnew = 0.5*(xnewnew + znew); z = znewnew; i = i+1; error(i,1) = computeError(z); end end function xNew = resolvent2(x) x1 = x(1); x2 = x(2); func2 = @(z2) computeTxi([x1,z2]); x2new = solveF(func2,x2); x1new = x1; xNew = [x1new,x2new]; end function xNew = resolvent1(x) x1 = x(1); x2 = x(2); func = @(z1) computeRho([z1,x2]); x1new = solveF(func,x1); x2new = x2; xNew = [x1new,x2new]; end function xnew = projection2(x) func = @(z2) computeTxi([x(1), z2]); xnew(2,1) = projection(func,x(2)); xnew(1,1) = x(2); end function xnew = projection1(x) func = @(z1) computeRho([z1, x(2)]); xnew(1,1) = projection(func,x(1)); xnew(2,1) = x(1); end function [x,f] = projection(myFunc,x0) % xB = linspace(0.01,1,100); % Interval To Evaluate Over % x = sort([xB,x0]); % fx = myFunc(x); % fxC = circshift(fx,-1,2);% Function Evaluated Over ‘x’ % cs = fx.*fxC; % Product Negative At Zero-Crossings % % % ind = find(cs(1:end-1) <= 0); % xc = x(ind); % Values Of ‘x’ Near Zero Crossings % % [~,it] = min(abs(fx(ind))); % % x0 = [x(ind(it)),x(ind(it) + 1)]; problem.objective = @(x) myFunc(x); problem.x0 = x0; problem.solver = 'fsolve'; TOL = 1e-12; problem.options = optimset('Display','iter','TolFun',TOL); [x,f] = fsolve(problem); x = real(x); end function er = computeError(r) err(1) = computeRho(r); err(2) = computeTxi(r); er = norm(err); end function [x,f] = solveF(func,x0) %[ub,lb] = findRbounds(x0,func); %lb = max(0,lb); %ub = min(1,ub); eps = 1e-13; xmin = 0+eps; xmax = 1-eps; %[lb,ub] = findBounds2(func,xmax,xmin,x0); lb = xmin; ub = xmax; problem.objective = @(x)abs(func(x)); %problem.x0 = x0; problem.solver = 'fminbnd'; problem.x1 = lb; problem.x2 = ub; %problem.options = optimset('Display','iter','TolFun',1e-15); TOL = 1e-12; problem.options = optimset('Display','iter','TolFun',TOL,'TolX',1e-14); [x,f] = fminbnd(problem); end function [lb,ub] = findBounds2(myFunc,xmax,xmin,x0) xB = linspace(xmin,xmax,100); % Interval To Evaluate Over x = sort([xB,x0]); fx = myFunc(x); fxC = circshift(fx,-1,2);% Function Evaluated Over ‘x’ cs = fx.*fxC; % Product Negative At Zero-Crossings ind = find(cs(1:end-1) <= 0); if isempty(ind) ind = true(size(cs)); end xc = x(ind); % Values Of ‘x’ Near Zero Crossings [~,it] = min(abs(fx(ind))); x0 = [x(ind(it)),x(ind(it) + 1)]; lb = x(ind(it)); ub = x(ind(it) + 1); end function [rub,rlb] = findRbounds(r0,F) F0 = F(r0); eps = 10^(-12); if F0 >= 0 r1 = r0 - eps; F1 = F(r1); while F1 >= 0 rnew = newPointBySecant(r0,r1,F0,F1); r0 = r1; F0 = F1; r1 = rnew; F1 = F(r1); end rub = r1; rlb = r0; else r1 = r0 - eps; F1 = F(r1); while F1 <= 0 rnew = newPointBySecant(r0,r1,F0,F1); r0 = r1; F0 = F1; r1 = min(1,rnew); F1 = F(r1); end rub = r0; rlb = r1; end end function x2 = newPointBySecant(x0,x1,f0,f1) x2 = x1 - (x1-x0)/(f1 - f0)*f1; end function ls = computeLevelSet(coord,r) y1 = coord(:,1) - 0.5; y2 = coord(:,2) - 0.5; [f1,f2,m1,m2,R] = computeParameters(r); ye1 = ellipj(y1*f1/(m1/2),r(1)); ye2 = ellipj(y2*f2/(m2/2),r(2)); ls(:,1) = (1-ye1.^2).*(1-ye2.^2) - R; isSmallerM1 = abs(y1) < m1/2; isSmallerM2 = abs(y2) < m2/2; isIn = isSmallerM1 & isSmallerM2; isOut = ~isIn; ls(isOut) = -abs(ls(isOut)); end function [f1,f2,m1,m2,R] = computeParameters(r) r1 = r(1); r2 = r(2); R = (1-r1)*(1-r2)/(r1*r2); F = @(x,k) ellipticF(asin(x),k); f = @(r) F(sqrt(1-R),r); s = @(r) f(r)/F(1,r); t = @(r) F(1,1-r)/F(1,r); f1 = f(r1); f2 = f(r2); s1 = s(r1); s2 = s(r2); t1 = t(r1); t2 = t(r2); m1 = (1-t1)/(1-t1*t2)*s1; m2 = (1-t2)/(1-t1*t2)*s2; end function [res,dres] = computeTxi(r) r = real(r); r1 = r(1); r2 = r(2:end); tanXiV = tan(20*pi/80); %tanXiV = 1; R = (1-r1).*(1-r2)./(r1.*r2); F = @(x,k) ellipticF(asin(x),k); f = @(r) F(sqrt(1-R),r); s = @(r) f(r)./F(1,r); t = @(r) F(1,1-r)./F(1,r); s1 = s(r1); s2 = s(r2); t1 = t(r1); t2 = t(r2); m1 = (1-t1)./(1-t1.*t2).*s1; m2 = (1-t2)./(1-t1.*t2).*s2; tanXi = (1-t1)./(1-t2).*s1./s2; %res = tan(txiV) - tanXi; res = (tanXiV - tanXi); dres = []; end function [res,dres] = computeRho(r) r = real(r); rhoV = 0.2; r1 = r(1:end-1); r2 = r(end); F = @(x,k) ellipticF(asin(x),k); t = @(r) F(1,1-r)./F(1,r); t1 = t(r1); t2 = t(r2); rho = 1 - (t1.*(1-t2) + t2.*(1 - t1))./(1-t1.*t2); res = (rho - rhoV); %res = real(res); dres = []; end
github
SwanLab/Swan-master
interpolate3mat.m
.m
Swan-master/Multimaterial/interpolate3mat.m
1,386
utf_8
ac8bc29cc989139c740e7a48298013b5
function interpolate3mat X(:,1) = [1 0 0]; X(:,2) = [0 1 0]; X(:,3) = [0 0 1]; xi1Init = 0.4; xi2Init = 0.01; alpha1Init = 17; alpha2Init = 2; alpha3Init = 4; rho(1,1) = xi1Init; rho(2,1) = xi2Init; rho(3,1) = 1 - rho(1) - rho(2); gamma(1,1) = alpha1Init; gamma(2,1) = alpha2Init; gamma(3,1) = alpha3Init; figure('color','w') hold on for k=1:15 plotTriangle(X) eta12 = rho(1) / (rho(1)+rho(2)); eta21 = rho(2) / (rho(1)+rho(2)); eta13 = rho(1) / (rho(1)+rho(3)); eta31 = rho(3) / (rho(1)+rho(3)); eta23 = rho(2) / (rho(2)+rho(3)); eta32 = rho(3) / (rho(2)+rho(3)); B = [0 eta23 eta32;... eta13 0 eta31; ... eta12 eta21 0]; %interpolation gamma = B*gamma; X = B*X H = 0.5*[0 1 1;... 1 0 1;... 1 1 0]; rho = H*rho end % % alpha1 % alpha2 % alpha3 gamma %linear interpolation should give the same as the following: xi1Init * alpha1Init + xi2Init * alpha2Init + (1-xi1Init-xi2Init) * alpha3Init end function plotTriangle(p) p1=p(1,:); p2=p(2,:); p3=p(3,:); % Plot trianle using 'patch' h=patch('Faces',1:3,'Vertices',[p1;p2;p3]); set(h,'FaceColor','r','EdgeColor','k','LineWidth',2,'FaceAlpha',0.5) axis equal vis3d view([45 25 45]) xlabel('x','FontSize',20) ylabel('y','FontSize',20) zlabel('z','FontSize',20) end
github
SwanLab/Swan-master
ExperimentingGraph.m
.m
Swan-master/Graph/ExperimentingGraph.m
1,017
utf_8
7bdb9a17e749e4ee39708c048c0d1f4f
function ExperimentingGraph nmax = 280; G = graph(); G = addnode(G,nmax); plot(G) allEdges = nchoosek(1:nmax,2); allEdgesN = allEdges; nEdgeMax = size(allEdges,1); sparsity = 0.05; nEdge = round(sparsity*nEdgeMax); for i = 1:nEdge nPosibleEdges = size(allEdgesN,1); newEdge = randi(nPosibleEdges); edge = allEdgesN(newEdge,:); allEdgesN(edge,:) = []; G = addedge(G,edge(1),edge(2)); if mod(i,round(nEdge/100)) == 0 figure(1) clf subplot(4,1,1) plot(G) d = centrality(G,'degree'); subplot(4,1,2) histogram(d) xlim([0 0.02*nEdge]) subplot(4,1,3) t = computeTriangularValues(G); histogram(t) C = computeTransition(d,t); subplot(4,1,4) histogram(C) drawnow end end end function t = computeTriangularValues(G) A = G.adjacency; A3 = A^3; t = (diag(A3)/2); end function C = computeTransition(d,t) C = 2*t./(d.*(d-1)); mean(C) isCNan = isnan(C); C(isCNan) = 0; end
github
SwanLab/Swan-master
compareInterations.m
.m
Swan-master/Topology Optimization/Applications/compareInterations.m
1,267
utf_8
898b2a9d8cf583ae62e1bffeb21a0298
function compareInterations fCase{1} = 'LatticeExperimentInputCantileverSymmetricMeshSuperEllipsePDE'; folder{1} = '/media/alex/My Passport/LatticeResults/CantileverSymmetricMeshSuperEllipsePDEGradientEpsilonH'; fCase{2} = 'LatticeExperimentInputCantileverSymmetricMeshSuperEllipsePDE'; folder{2} = '/media/alex/My Passport/LatticeResults/CantileverSymmetricMeshSuperEllipsePDEEpsilonEhGradient2000'; fCase{3} = 'LatticeExperimentInputCantileverSymmetricMeshSuperEllipsePDE'; folder{3} = '/media/alex/My Passport/LatticeResults/CantileverSymmetricMeshSuperEllipsePDE10000iteration'; f = figure(); hold on it = 1; for iPlot = 1:numel(fCase) fName = fullfile(folder{iPlot},fCase{iPlot}); [xV,yV,cV] = getCostFunctions(fName); for iline = 1:size(yV,2) p{it} = plot(xV,yV(:,iline),'Color',cV(:,iline)); it = it + 1; end end pr = plotPrinter(f,p); pr.print(fullfile('/home/alex/Dropbox/GregMeeting30Octubre',['Iterations'])); end function [xV,yV,cV] = getCostFunctions(fName) fNameMon = fullfile([fName,'CostVsLinf.fig']); h = openfig(fNameMon); handles = findobj(h,'Type','line'); xV = get(handles(1),'Xdata'); for i = 1:numel(handles) yV(:,i) = get(handles(i),'Ydata'); cV(:,i) = get(handles(i),'Color') ; end close(h) end
github
SwanLab/Swan-master
compareInterations2.m
.m
Swan-master/Topology Optimization/Applications/compareInterations2.m
1,151
utf_8
08f836d5383d17f1087d9a83511f384e
function compareInterations2 fCase{1} = 'ExperimentingPlot'; folder{1} = '/media/alex/My Passport/LatticeResults/StressNormSuperEllipseRotation'; fCase{2} = 'ExperimentingPlot'; folder{2} = '/media/alex/My Passport/LatticeResults/StressNormRectangleRotation'; %fCase{3} = 'LatticeExperimentInputCantileverSymmetricMeshSuperEllipsePDE'; %folder{3} = '/media/alex/My Passport/LatticeResults/CantileverSymmetricMeshSuperEllipsePDE10000iteration'; f = figure(); hold on it = 1; for iPlot = 1:numel(fCase) fName = fullfile(folder{iPlot},fCase{iPlot}); [xV,yV,cV] = getCostFunctions(folder{iPlot}); % for iline = 1:size(yV,2) p{it} = plot(xV,yV(:,5)); it = it + 1; % end end legend('SuperEllipse','Rectangle') pr = plotPrinter(f,p); pr.print(fullfile('/home/alex/Dropbox/GregMeeting30Octubre',['Iterations3'])); end function [xV,yV,cV] = getCostFunctions(fName) fNameMon = fullfile([fName,'/Monitoring.fig']); h = openfig(fNameMon); handles = findobj(h,'Type','line'); xV = get(handles(1),'Xdata'); for i = 1:numel(handles) yV(:,i) = get(handles(i),'Ydata'); cV(:,i) = get(handles(i),'Color') ; end close(h) end
github
SwanLab/Swan-master
PlottinMaxWithPNorm.m
.m
Swan-master/Topology Optimization/Applications/LatticeExperiments/PlottinMaxWithPNorm.m
2,404
utf_8
3e3e82396177aa8ba1af2ed9930eaf55
function PlottinMaxWithPNorm p = 64; %nIteration = 498; %fCase = 'ExperimentingPlot'; %folder = ['/home/alex/git-repos/Swan/Output/',fCase]; %nIteration = 545; %fCase = 'LatticeExperimentInputCantileverSymmetricMeshSuperEllipsePDE'; %folder = '/media/alex/My Passport/LatticeResults/CantileverSymmetricMeshSuperEllipsePDEEpsilonEhGradient2000'; nIteration = 235; fCase = 'LatticeExperimentInputCantileverSymmetricMeshSuperEllipsePDE'; folder = '/media/alex/My Passport/LatticeResults/CantileverSymmetricMeshSuperEllipsePDEGradientEpsilonH'; %nIteration = 2362; %fCase = 'LatticeExperimentInputCantileverSymmetricMeshSuperEllipsePDE'; %folder = '/media/alex/My Passport/LatticeResults/CantileverSymmetricMeshSuperEllipsePDE10000iteration'; for iter = 1:nIteration s.fileName = [fCase,num2str(iter)]; s.folderPath = fullfile(folder); wM = WrapperMshResFiles(s); wM.compute(); mesh = wM.mesh; quad = Quadrature.set(mesh.type); quad.computeQuadrature('CONSTANT'); dvolum = mesh.computeDvolume(quad); sl2Norm = wM.dataRes.StressNormGauss; sl2NormP = (sl2Norm).^(p); int = sl2NormP.*dvolum'; intOpt = int(:); stressNorml2LpNorm = sum(intOpt); stresLpNorm(iter) = stressNorml2LpNorm.^(1/p); stressMax(iter) = max(abs(sl2Norm)); iter if iter == 1 || iter/10 == floor(iter/10) print(folder,fCase,stresLpNorm,stressMax,iter) end end print(folder,fCase,stresLpNorm,stressMax,iter) end function print(folder,fCase,stresLpNorm,stressMax,nIteration) fid = fopen(fullfile(folder,[fCase,'.txt'])); tLine = textscan(fid,'%s','delimiter','\n', 'headerlines',0); a = tLine{1}; costA = a(end-9,1); costAs = split(costA); costAt = str2double(costAs(2)); a = tLine{1}; costR = a(end,1); costRs = split(costR); costRt = str2double(costRs(2)); const = costRt/costAt; fNameMon = fullfile(folder,'Monitoring.fig'); h = openfig(fNameMon); handles = findobj(h,'Type','line'); iterC = get(handles(5),'Xdata'); cost = get(handles(5),'Ydata'); close all f = figure(); pN{1} = plot(iterC,cost*const); hold on pN{2} = plot(1:nIteration,stresLpNorm); hold on pN{3} = plot(1:nIteration,stressMax); leg = legend({'Cost function','L^{64}(\Omega) norm','max norm'}); set(leg); savefig(f,fullfile(folder,[fCase,'CostVsLinf.fig'])) p = plotPrinter(f,pN); p.print(fullfile(folder,[fCase,'Cost'])); end
github
SwanLab/Swan-master
plotSuperVsRectangleOptim.m
.m
Swan-master/Topology Optimization/Applications/LatticeExperiments/plotSuperVsRectangleOptim.m
1,157
utf_8
67ddc0dd208b2a5f59f6e43def2d9d02
function plotSuperVsRectangleOptim mCase = 'Middle'; folderR = ['/home/alex/Desktop/ExperimentingPlotRectangle',mCase,'/']; [iter,cost,maxStress] = obtainCostShapes(folderR); f = figure(); h{1} = plot(iter,[cost;maxStress]','b'); hline = findobj(gcf, 'type', 'line'); set(hline(1),'LineStyle','--') folderS = ['/home/alex/Desktop/ExperimentingPlotSuperEllipse',mCase,'/']; [iter,costS,maxStressS] = obtainCostShapes(folderS); hold on h{2} = plot(iter,[costS;maxStressS]','r'); hline = findobj(gcf, 'type', 'line'); set(hline(1),'LineStyle','--') leg = {'Rectangle Amplified Stress p', 'Amplified Stress max',... 'Superellipse Amplified Stress p', 'Superellipse Stress max'}; legend(leg) printer = plotPrinter(f,h); path = '/home/alex/Dropbox/GregoireMeetings/GregoireMeeting25Janvier'; output = fullfile(path,['Convergence',mCase]); printer.print(output) end function [iter,stress,maxStress] = obtainCostShapes(folder) fNameMon = fullfile(folder,'Monitoring.fig'); h = openfig(fNameMon); handles = findobj(h,'Type','line'); iter = get(handles(5),'Xdata'); stress = get(handles(11),'Ydata'); maxStress = get(handles(4),'Ydata'); close(h) end
github
SwanLab/Swan-master
plotPerimeterComplianceCost.m
.m
Swan-master/Topology Optimization/Applications/PerimeterExperiments/plotPerimeterComplianceCost.m
992
utf_8
1541075216b1ca60d25a199b97dc5dec
function plotPerimeterComplianceCost %perCase = 'Total'; perCase = 'Relative'; plotCost(perCase); end function plotCost(perCase) folder = ['/media/alex/My Passport/PerimeterResults/FineMesh/',perCase,'Perimeter01/']; [iter,compliance,perimeter] = obtainCostShapes(folder); f = figure(); hold on pN{1} = plot(iter,0.1*perimeter); pN{2} = plot(iter,0.4*ones(size(iter))); yyaxis right pN{3} = plot(iter,compliance); leg = legend({['$\textrm{',perCase,' perimeter } \alpha \textrm{Per}^{T}_{\varepsilon}(\Omega)$'],'$\textrm{Volume }\textrm{V}(\Omega)$','$ \textrm{Compliance } \textrm{C}(\Omega) $'}); set(leg,'Interpreter','latex') p = plotPrinter(f,pN); p.print(fullfile(folder,['Cost'])); end function [iter,compliance,perimeter] = obtainCostShapes(folder) fNameMon = fullfile(folder,'Monitoring.fig'); h = openfig(fNameMon); handles = findobj(h,'Type','line'); iter = get(handles(5),'Xdata'); compliance = get(handles(6),'Ydata'); perimeter = get(handles(5),'Ydata'); close all end
github
SwanLab/Swan-master
MaterialDesignApproachComparison.m
.m
Swan-master/Topology Optimization/Applications/MaterialDesign/MaterialDesignApproachComparison.m
1,242
utf_8
24c6edbd0f8363c1de5fc2ae22889c67
function MaterialDesignApproachComparison matCase = 'Horizontal'; path = '/media/alex/My Passport/MaterialDesign/'; element = {'Tri','Quad'}; desVar = {'Density','LevelSet'}; filter = {'P1';'PDE'}; fCase{1} = 'CompositeMaterialDesign'; folder{1} = fullfile(path,matCase,element,desVar,filter); fCase{2} = 'CompositeMaterialDesign'; folder{2} = '/media/alex/My Passport/MaterialDesign/Quadrilater/Horizontal/Density'; %fCase{2} = 'ExperimentingPlot'; %folder{2} = '/media/alex/My Passport/LatticeResults/StressNormRectangleRotation'; f = figure(); hold on it = 1; for iPlot = 1:numel(fCase) % fName = fullfile(folder{iPlot},fCase{iPlot}); [xV,yV,cV] = getCostFunctions(folder{iPlot}); % for iline = 1:size(yV,2) p{it} = plot(xV,yV(:,7)); it = it + 1; % end end legend('LevelSet','Density') pr = plotPrinter(f,p); pr.print(fullfile('/home/alex/Dropbox/MaterialDesign',['HorizontalQuadrilater'])); end function [xV,yV,cV] = getCostFunctions(fName) fNameMon = fullfile([fName,'/Monitoring.fig']); h = openfig(fNameMon); handles = findobj(h,'Type','line'); xV = get(handles(1),'Xdata'); for i = 1:numel(handles) yV(:,i) = get(handles(i),'Ydata'); cV(:,i) = get(handles(i),'Color') ; end close(h) end
github
SwanLab/Swan-master
fixIndex.m
.m
Swan-master/Topology Optimization/Benchmarks/Maintenance/fixIndex.m
583
utf_8
7d0f4e250640e6f9903ef1790848a787
function new_name = fixIndex(name,destination_folderpath) index = 1; list = updateList(destination_folderpath); try_name = assembleName(name,index); for i = 1:length(list) if strcmpi(try_name,list(i).name) index = index + 1; try_name = assembleName(name,index); end end new_name = try_name; end function new_name = assembleName(name,index) us = strfind(name,'_'); dots = strfind(name,'.'); name(us(end)+1:dots(end)-1)=[]; new_name = [name(1:us(end)), num2str(index), name(us(end)+1:end)]; end
github
SwanLab/Swan-master
ImportCases.m
.m
Swan-master/Topology Optimization/Benchmarks/Maintenance/ImportCases.m
1,368
utf_8
e7755aeae6ea77e29d878e9c8f55f7f4
clear; close all; clc; %% *************************** IMPORT CASES **************************** %% % Move cases from an origin folder to a destination folder considering case % indexes. origin_folderpath = uigetdir; destination_superfolderpath = uigetdir; list = updateList(origin_folderpath); for i = 1:length(list) old_name = list(i).name; destination_folderpath = findDestinationFolder(old_name,destination_superfolderpath); new_name = fixIndex(old_name,destination_folderpath); if ~exist(destination_folderpath,'dir') mkdir(destination_folderpath); end movefile(fullfile(origin_folderpath,old_name),fullfile(destination_folderpath,new_name)); end function destination_folderpath = findDestinationFolder(name,destination_superfolderpath) if contains(name,'Bridge','IgnoreCase',true) destination_folderpath = fullfile(destination_superfolderpath,'Bridge'); elseif contains(name,'Cantilever','IgnoreCase',true) destination_folderpath = fullfile(destination_superfolderpath,'Cantilever'); elseif contains(name,'Throne','IgnoreCase',true) destination_folderpath = fullfile(destination_superfolderpath,'Throne'); elseif contains(name,'Chair','IgnoreCase',true) destination_folderpath = fullfile(destination_superfolderpath,'Chair'); else error('NOT FOUND') end end
github
SwanLab/Swan-master
removePatternFromFilename.m
.m
Swan-master/Topology Optimization/Benchmarks/Maintenance/removePatternFromFilename.m
746
utf_8
eb96fd35e0b68d8987eefe0d32fbb89c
clear; close all; clc; %% ***************** REMOVE PATTERN FROM FILENAME CASES **************** %% % Remove a certain pattern from the name of a file. folderpath = uigetdir; list = updateList(folderpath); pattern_to_remove = 'ORIOL_'; for i = 1:length(list) old_name = list(i).name; if contains(old_name,pattern_to_remove) new_name = getNewName(old_name,pattern_to_remove); new_name = fixIndex(new_name,folderpath); movefile(fullfile(folderpath,old_name),fullfile(folderpath,new_name)); list2 = updateList(folderpath); end end function new_name = getNewName(old_name,pattern_to_remove) pos = strfind(old_name,pattern_to_remove); new_name = old_name(pos+length(pattern_to_remove):end); end
github
SwanLab/Swan-master
RunningOneMicrostructureVademecum.m
.m
Swan-master/Topology Optimization/Homogenization/Sources/VadamecumCalculator/RunningOneMicrostructureVademecum.m
752
utf_8
76b1d3aa121b8db9aafec4290bb1be2d
function RunningOneMicrostructureVademecum %dSmooth = obtainSettings('SquareMesh4b','Rectangle'); dSmooth = obtainSettings('SmallCircleQ2','SmoothRectangle'); vc = VademecumCellVariablesCalculator(dSmooth); vc.computeVademecumData() end function d = obtainSettings(prefix,freeFemFile) d = SettingsVademecumCellVariablesCalculator(); d.freeFemFileName = freeFemFile; d.fileName = prefix; d.mxMin = 0.1; d.mxMax = 0.1; d.myMin = 0.1; d.myMax = 0.1; d.nMx = 1; d.nMy = 1; d.outPutPath = []; d.print = true; %i = 4; %d.freeFemSettings.hMax = 10^(-1)/(2^(i - 1));%0.0025; d.freeFemSettings.hMax = 0.02;%0.0025; %d.smoothingExponentSettings.type = 'Optimal'; d.smoothingExponentSettings.type = 'Given'; d.smoothingExponentSettings.q = 2; end
github
SwanLab/Swan-master
ComparingSymmetry.m
.m
Swan-master/Topology Optimization/Homogenization/Sources/VadamecumCalculator/ComparingSymmetry.m
770
utf_8
6bce34d7d895f1eb38c40ab27a731a88
function ComparingSymmetry incPhi = pi/180; fileName = 'StressSymmetryTraction'; sPnormT = computeExperiment(incPhi,fileName); fileName = 'StressSymmetryCompression'; sPnormC = computeExperiment(-incPhi,fileName); end function sPnorm = computeExperiment(incPhi,fileName) txi = pi/2 - 0.2;%1083; rho = 0.9; q = 4; phi = 0+incPhi; pNorm = 'max'; print = false; hMesh = 0.01; hasToCaptureImage = true; mx = SuperEllipseParamsRelator.mx(txi,rho,q); my = SuperEllipseParamsRelator.my(txi,rho,q); s.mx = mx; s.my = my; s.q = q; s.phi = phi; s.pNorm = pNorm; s.print = print; s.hMesh = hMesh; s.fileName = fileName; s.hasToCaptureImage = false; sN = StressNormSuperEllipseComputer(s); sPnorm = sN.compute(); sN.printStress(); end
github
SwanLab/Swan-master
StressMeshVariation.m
.m
Swan-master/Topology Optimization/Homogenization/Sources/VadamecumCalculator/StressMeshVariation.m
732
utf_8
a969aa16faf878fb7fb8cab9ad3ff016
function StressMeshVariation hMesh = [0.1, 0.05, 0.0025, 0.00125]; for imesh = 1:length(hMesh) dSmooth = obtainSettings(['RectangleStressMeshDependency',num2str((imesh))],'Rectangle',hMesh(imesh)); computeVademecum(dSmooth); end end function computeVademecum(d) vc = VademecumCellVariablesCalculator(d); vc.computeVademecumData() end function d = obtainSettings(prefix,freeFemFile,h) d = SettingsVademecumCellVariablesCalculator(); d.freeFemFileName = freeFemFile; d.fileName = prefix; d.mxMin = 0.8; d.mxMax = 0.8; d.myMin = 0.8; d.myMax = 0.8; d.nMx = 1; d.nMy = 1; d.outPutPath = []; d.print = true; d.freeFemSettings.hMax = h;%0.0025; d.smoothingExponentSettings.type = 'Given'; d.smoothingExponentSettings.q = 2; end
github
SwanLab/Swan-master
RunningVademecum.m
.m
Swan-master/Topology Optimization/Homogenization/Sources/VadamecumCalculator/RunningVademecum.m
1,060
utf_8
c087a7f4123f17683e191c603552a2c8
function RunningVademecum % % dSmooth = obtainSettings('SuperEllipseQMax'); % dSmooth.smoothingExponentSettings.type = 'Given'; % dSmooth.smoothingExponentSettings.q = 32; % computeVademecum(dSmooth); % % dSmooth = obtainSettings('SuperEllipseQ2'); % dSmooth.smoothingExponentSettings.type = 'Given'; % dSmooth.smoothingExponentSettings.q = 2; % computeVademecum(dSmooth); % % dSmooth = obtainSettings('RectangleVademecum','Rectangle'); % dSmooth.smoothingExponentSettings.type = 'Given'; % computeVademecum(dSmooth); dSmooth = obtainSettings('SuperEllipseQOptAnalytic'); dSmooth.smoothingExponentSettings.type = 'Optimal'; computeVademecum(dSmooth); end function computeVademecum(d) vc = VademecumCellVariablesCalculator(d); vc.computeVademecumData() vc.saveVademecumData(); end function d = obtainSettings(prefix) d = SettingsVademecumCellVariablesCalculator(); d.fileName = prefix; d.mxMin = 0.01; d.mxMax = 0.99; d.myMin = 0.01; d.myMax = 0.99; d.nMx = 20; d.nMy = 20; d.outPutPath = 'Topology Optimization/Vademecums/'; d.print = false; end
github
SwanLab/Swan-master
findingVolumeMatch.m
.m
Swan-master/Topology Optimization/Homogenization/Sources/VadamecumCalculator/findingVolumeMatch.m
422
utf_8
228e5717e73d0b12bb85e910b6d51067
function findingVolumeMatch vS = findVolume('SmoothRectangle'); vR = findVolume('Rectangle'); end function volV = findVolume(micro) d = load(['/home/alex/git-repos/SwanLab/Swan/Output/',micro,'/',micro,'.mat']); var = d.d.variables; mxV = d.d.domVariables.mxV; myV = d.d.domVariables.myV; for imx = 1:length(mxV) for imy = 1:length(myV) volV(imx,imy) = var{imx,imy}.volume; end end end
github
SwanLab/Swan-master
runningOptimalSuperEllipseExponent.m
.m
Swan-master/Topology Optimization/Homogenization/Sources/VadamecumCalculator/runningOptimalSuperEllipseExponent.m
475
utf_8
31302449ab211ee6c0af81872433cc84
function runningOptimalSuperEllipseExponent s.samplePoints = createSamplePoints(); s.fileName = 'OptimalSuperEllipseExponentDataFromFixedRho'; exponentComputer = OptimalExponentComputer(s); exponentComputer.compute(); end function sample = createSamplePoints() s.type = 'FromMxMy'; sample = SamplePointsCreatorForOptimalExponentComputer.create(s); s.type = 'FromFixedRho'; s.rho0 = 0.8; s.psi = pi/4; sample = SamplePointsCreatorForOptimalExponentComputer.create(s); end
github
SwanLab/Swan-master
AnalyticalVsNumerical.m
.m
Swan-master/Topology Optimization/Homogenization/Sources/VadamecumCalculator/SmoothingExponentComputer/AnalyticalVsNumerical.m
1,394
utf_8
b57cbc83d117e1270badaadba4371921
function AnalyticalVsNumerical v = VademecumReader(); s.vademecum = v; sE = PonderatedOptimalSuperEllipseComputer(s); sE.compute(); %t = abs(v.mxV(:,1) - v.myV(:,1)) < 1e-6; m1 = v.mxV(:,1); m2 = v.myV(:,1); q = sE.qMean; thet = 45; theta = thet*pi/180; m1L = @(x) sqrt(x^2*(1+tan(theta)^2)); m2L = @(y) sqrt(y^2*(1+1/(tan(theta)^2))); tmin = min(m1L(max(m1)),m2L(max(m2))); tmax = min(m1L(max(m1)),m2L(max(m2))); t = linspace(0,1,100); m1t = min(m1) + t/tmax*cos(theta); m2t = min(m2) + t/tmax*sin(theta); F = scatteredInterpolant(m1,m2,q); qI = F(m1t,m2t); qA(:,1) = computeQanalytic(m1t,m2t); f = figure(); hold on h{1} = plot(t,qA,'-+'); h{2} = plot(t,qI,'-+'); xlabel(['$\rho \quad (\xi = ',num2str(thet),') $'],'Interpreter','Latex') ylabel('$q$','Interpreter','Latex') legA = '$\textrm{Analytical smoothing exponent} \, q_A$'; legN = '$\textrm{Numerical smoothing exponent} \, q_N$'; legObj = legend({legA,legN},'Interpreter','Latex','Location','Best'); outPutPath = '/home/alex/git-repos/MicroStructurePaper/'; outputName = [outPutPath,'qMaxM1M2AnalyticalNumerical']; printer = plotPrinter(f,h); %printer.print(outputName); end function qA = computeQanalytic(mx,my) for ipoint = 1:length(mx) s.m1 = mx(ipoint); s.m2 = my(ipoint); s.type = 'Optimal'; qExp = SmoothingExponentComputer.create(s); qA(ipoint) = qExp.compute(); end end
github
SwanLab/Swan-master
runningSimpleTopOpt.m
.m
Swan-master/SimpleTopOpt/runningSimpleTopOpt.m
498
utf_8
dd5f5b99ad2c9facf9a1b431261ba41a
%% Simple topology optimization example % Note that the beta term function runningSimpleTopOpt s.maxIter = 100; s.TOL = 1e-12; s.topOptProblem = createFullTopOptProblem(); solver = SimpleShapeOptimizationSolver(s); solver.solve(); end function t = createFullTopOptProblem() settings = Settings('Example1'); translator = SettingsTranslator(); translator.translate(settings); fileName = translator.fileName; settingsTopOpt = SettingsTopOptProblem(fileName); t = TopOpt_Problem(settingsTopOpt); end
github
SwanLab/Swan-master
subsolv.m
.m
Swan-master/TopOptEig/OptimalBucklingColumn/subsolv.m
5,887
utf_8
4d6cc3eb2f01df75cb6feae665525c62
% This is the file subsolv.m % function [xmma,ymma,zmma,lamma,xsimma,etamma,mumma,zetmma,smma] = ... subsolv(m,n,epsimin,low,upp,alfa,beta,p0,q0,P,Q,a0,a,b,c,d); % % Written in May 1999 by % Krister Svanberg <[email protected]> % Department of Mathematics % SE-10044 Stockholm, Sweden. % % This function subsolv solves the MMA subproblem: % % minimize SUM[ p0j/(uppj-xj) + q0j/(xj-lowj) ] + a0*z + % + SUM[ ci*yi + 0.5*di*(yi)^2 ], % % subject to SUM[ pij/(uppj-xj) + qij/(xj-lowj) ] - ai*z - yi <= bi, % alfaj <= xj <= betaj, yi >= 0, z >= 0. % % Input: m, n, low, upp, alfa, beta, p0, q0, P, Q, a0, a, b, c, d. % Output: xmma,ymma,zmma, slack variables and Lagrange multiplers. % een = ones(n,1); eem = ones(m,1); epsi = 1; epsvecn = epsi*een; epsvecm = epsi*eem; x = 0.5*(alfa+beta); y = eem; z = 1; lam = eem; xsi = een./(x-alfa); xsi = max(xsi,een); eta = een./(beta-x); eta = max(eta,een); mu = max(eem,0.5*c); zet = 1; s = eem; itera = 0; while epsi > epsimin epsvecn = epsi*een; epsvecm = epsi*eem; ux1 = upp-x; xl1 = x-low; ux2 = ux1.*ux1; xl2 = xl1.*xl1; uxinv1 = een./ux1; xlinv1 = een./xl1; plam = p0 + P'*lam ; qlam = q0 + Q'*lam ; gvec = P*uxinv1 + Q*xlinv1; dpsidx = plam./ux2 - qlam./xl2 ; rex = dpsidx - xsi + eta; rey = c + d.*y - mu - lam; rez = a0 - zet - a'*lam; relam = gvec - a*z - y + s - b; rexsi = xsi.*(x-alfa) - epsvecn; reeta = eta.*(beta-x) - epsvecn; remu = mu.*y - epsvecm; rezet = zet*z - epsi; res = lam.*s - epsvecm; residu1 = [rex' rey' rez]'; residu2 = [relam' rexsi' reeta' remu' rezet res']'; residu = [residu1' residu2']'; residunorm = sqrt(residu'*residu); residumax = max(abs(residu)); ittt = 0; while residumax > 0.9*epsi & ittt < 100 ittt=ittt + 1; itera=itera + 1; ux1 = upp-x; xl1 = x-low; ux2 = ux1.*ux1; xl2 = xl1.*xl1; ux3 = ux1.*ux2; xl3 = xl1.*xl2; uxinv1 = een./ux1; xlinv1 = een./xl1; uxinv2 = een./ux2; xlinv2 = een./xl2; plam = p0 + P'*lam ; qlam = q0 + Q'*lam ; gvec = P*uxinv1 + Q*xlinv1; GG = P*spdiags(uxinv2,0,n,n) - Q*spdiags(xlinv2,0,n,n); dpsidx = plam./ux2 - qlam./xl2 ; delx = dpsidx - epsvecn./(x-alfa) + epsvecn./(beta-x); dely = c + d.*y - lam - epsvecm./y; delz = a0 - a'*lam - epsi/z; dellam = gvec - a*z - y - b + epsvecm./lam; diagx = plam./ux3 + qlam./xl3; diagx = 2*diagx + xsi./(x-alfa) + eta./(beta-x); diagxinv = een./diagx; diagy = d + mu./y; diagyinv = eem./diagy; diaglam = s./lam; diaglamyi = diaglam+diagyinv; if m < n blam = dellam + dely./diagy - GG*(delx./diagx); bb = [blam' delz]'; Alam = spdiags(diaglamyi,0,m,m) + GG*spdiags(diagxinv,0,n,n)*GG'; AA = [Alam a a' -zet/z ]; solut = AA\bb; dlam = solut(1:m); dz = solut(m+1); dx = -delx./diagx - (GG'*dlam)./diagx; else diaglamyiinv = eem./diaglamyi; dellamyi = dellam + dely./diagy; Axx = spdiags(diagx,0,n,n) + GG'*spdiags(diaglamyiinv,0,m,m)*GG; azz = zet/z + a'*(a./diaglamyi); axz = -GG'*(a./diaglamyi); bx = delx + GG'*(dellamyi./diaglamyi); bz = delz - a'*(dellamyi./diaglamyi); AA = [Axx axz axz' azz ]; bb = [-bx' -bz]'; solut = AA\bb; dx = solut(1:n); dz = solut(n+1); dlam = (GG*dx)./diaglamyi - dz*(a./diaglamyi) + dellamyi./diaglamyi; end dy = -dely./diagy + dlam./diagy; dxsi = -xsi + epsvecn./(x-alfa) - (xsi.*dx)./(x-alfa); deta = -eta + epsvecn./(beta-x) + (eta.*dx)./(beta-x); dmu = -mu + epsvecm./y - (mu.*dy)./y; dzet = -zet + epsi/z - zet*dz/z; ds = -s + epsvecm./lam - (s.*dlam)./lam; xx = [ y' z lam' xsi' eta' mu' zet s']'; dxx = [dy' dz dlam' dxsi' deta' dmu' dzet ds']'; stepxx = -1.01*dxx./xx; stmxx = max(stepxx); stepalfa = -1.01*dx./(x-alfa); stmalfa = max(stepalfa); stepbeta = 1.01*dx./(beta-x); stmbeta = max(stepbeta); stmalbe = max(stmalfa,stmbeta); stmalbexx = max(stmalbe,stmxx); stminv = max(stmalbexx,1); steg = 1/stminv; xold = x; yold = y; zold = z; lamold = lam; xsiold = xsi; etaold = eta; muold = mu; zetold = zet; sold = s; itto = 0; resinew = 2*residunorm; while resinew > residunorm & itto < 50 itto = itto+1; x = xold + steg*dx; y = yold + steg*dy; z = zold + steg*dz; lam = lamold + steg*dlam; xsi = xsiold + steg*dxsi; eta = etaold + steg*deta; mu = muold + steg*dmu; zet = zetold + steg*dzet; s = sold + steg*ds; ux1 = upp-x; xl1 = x-low; ux2 = ux1.*ux1; xl2 = xl1.*xl1; uxinv1 = een./ux1; xlinv1 = een./xl1; plam = p0 + P'*lam ; qlam = q0 + Q'*lam ; gvec = P*uxinv1 + Q*xlinv1; dpsidx = plam./ux2 - qlam./xl2 ; rex = dpsidx - xsi + eta; rey = c + d.*y - mu - lam; rez = a0 - zet - a'*lam; relam = gvec - a*z - y + s - b; rexsi = xsi.*(x-alfa) - epsvecn; reeta = eta.*(beta-x) - epsvecn; remu = mu.*y - epsvecm; rezet = zet*z - epsi; res = lam.*s - epsvecm; residu1 = [rex' rey' rez]'; residu2 = [relam' rexsi' reeta' remu' rezet res']'; residu = [residu1' residu2']'; resinew = sqrt(residu'*residu); steg = steg/2; end residunorm=resinew; residumax = max(abs(residu)); steg = 2*steg; end epsi = 0.1*epsi; end xmma = x; ymma = y; zmma = z; lamma = lam; xsimma = xsi; etamma = eta; mumma = mu; zetmma = zet; smma = s;
github
SwanLab/Swan-master
mmasub.m
.m
Swan-master/TopOptEig/OptimalBucklingColumn/mmasub.m
5,946
utf_8
58dc1410125aaae8d671b426a85f3608
% This is the file mmasub.m % function [xmma,ymma,zmma,lam,xsi,eta,mu,zet,s,low,upp] = ... mmasub(m,n,iter,xval,xmin,xmax,xold1,xold2, ... f0val,df0dx,df0dx2,fval,dfdx,dfdx2,low,upp,a0,a,c,d); % % Written in May 1999 by % Krister Svanberg <[email protected]> % Department of Mathematics % SE-10044 Stockholm, Sweden. % % This function mmasub performs one MMA-iteration, aimed at % solving the nonlinear programming problem: % % Minimize f_0(x) + a_0*z + sum( c_i*y_i + 0.5*d_i*(y_i)^2 ) % subject to f_i(x) - a_i*z - y_i <= 0, i = 1,...,m % xmin_j <= x_j <= xmax_j, j = 1,...,n % z >= 0, y_i >= 0, i = 1,...,m %*** INPUT: % % m = The number of general constraints. % n = The number of variables x_j. % iter = Current iteration number ( =1 the first time mmasub is called). % xval = Column vector with the current values of the variables x_j. % xmin = Column vector with the lower bounds for the variables x_j. % xmax = Column vector with the upper bounds for the variables x_j. % xold1 = xval, one iteration ago (provided that iter>1). % xold2 = xval, two iterations ago (provided that iter>2). % f0val = The value of the objective function f_0 at xval. % df0dx = Column vector with the derivatives of the objective function % f_0 with respect to the variables x_j, calculated at xval. % df0dx2 = Column vector with the non-mixed second derivatives of the % objective function f_0 with respect to the variables x_j, % calculated at xval. df0dx2(j) = the second derivative % of f_0 with respect to x_j (twice). % Important note: If second derivatives are not available, % simply let df0dx2 = 0*df0dx. % fval = Column vector with the values of the constraint functions f_i, % calculated at xval. % dfdx = (m x n)-matrix with the derivatives of the constraint functions % f_i with respect to the variables x_j, calculated at xval. % dfdx(i,j) = the derivative of f_i with respect to x_j. % dfdx2 = (m x n)-matrix with the non-mixed second derivatives of the % constraint functions f_i with respect to the variables x_j, % calculated at xval. dfdx2(i,j) = the second derivative % of f_i with respect to x_j (twice). % Important note: If second derivatives are not available, % simply let dfdx2 = 0*dfdx. % low = Column vector with the lower asymptotes from the previous % iteration (provided that iter>1). % upp = Column vector with the upper asymptotes from the previous % iteration (provided that iter>1). % a0 = The constants a_0 in the term a_0*z. % a = Column vector with the constants a_i in the terms a_i*z. % c = Column vector with the constants c_i in the terms c_i*y_i. % d = Column vector with the constants d_i in the terms 0.5*d_i*(y_i)^2. % %*** OUTPUT: % % xmma = Column vector with the optimal values of the variables x_j % in the current MMA subproblem. % ymma = Column vector with the optimal values of the variables y_i % in the current MMA subproblem. % zmma = Scalar with the optimal value of the variable z % in the current MMA subproblem. % lam = Lagrange multipliers for the m general MMA constraints. % xsi = Lagrange multipliers for the n constraints alfa_j - x_j <= 0. % eta = Lagrange multipliers for the n constraints x_j - beta_j <= 0. % mu = Lagrange multipliers for the m constraints -y_i <= 0. % zet = Lagrange multiplier for the single constraint -z <= 0. % s = Slack variables for the m general MMA constraints. % low = Column vector with the lower asymptotes, calculated and used % in the current MMA subproblem. % upp = Column vector with the upper asymptotes, calculated and used % in the current MMA subproblem. % epsimin = sqrt(m+n)*10^(-9); feps = 0.000001; asyinit = 0.2; asyincr = 1.1; asydecr = 0.65; albefa = 0.1; een = ones(n,1); zeron = zeros(n,1); % Calculation of the asymptotes low and upp : if iter < 2.5 low = xval - asyinit*(xmax-xmin); upp = xval + asyinit*(xmax-xmin); else zzz = (xval-xold1).*(xold1-xold2); factor = een; factor(find(zzz > 0)) = asyincr; factor(find(zzz < 0)) = asydecr; low = xval - factor.*(xold1 - low); upp = xval + factor.*(upp - xold1); end % Calculation of the bounds alfa and beta : zzz = low + albefa*(xval-low); alfa = max(zzz,xmin); zzz = upp - albefa*(upp-xval); beta = min(zzz,xmax); % Calculations of p0, q0, P, Q and b. ux1 = upp-xval; ux2 = ux1.*ux1; ux3 = ux2.*ux1; xl1 = xval-low; xl2 = xl1.*xl1; xl3 = xl2.*xl1; ul1 = upp-low; ulinv1 = een./ul1; uxinv1 = een./ux1; xlinv1 = een./xl1; uxinv3 = een./ux3; xlinv3 = een./xl3; diap = (ux3.*xl1)./(2*ul1); diaq = (ux1.*xl3)./(2*ul1); p0 = zeron; p0(find(df0dx > 0)) = df0dx(find(df0dx > 0)); p0 = p0 + 0.001*abs(df0dx) + feps*ulinv1; p0 = p0.*ux2; q0 = zeron; q0(find(df0dx < 0)) = -df0dx(find(df0dx < 0)); q0 = q0 + 0.001*abs(df0dx) + feps*ulinv1; q0 = q0.*xl2; dg0dx2 = 2*(p0./ux3 + q0./xl3); del0 = df0dx2 - dg0dx2; delpos0 = zeron; delpos0(find(del0 > 0)) = del0(find(del0 > 0)); p0 = p0 + delpos0.*diap; q0 = q0 + delpos0.*diaq; P = zeros(m,n); P(find(dfdx > 0)) = dfdx(find(dfdx > 0)); P = P * diag(ux2); Q = zeros(m,n); Q(find(dfdx < 0)) = -dfdx(find(dfdx < 0)); Q = Q * diag(xl2); dgdx2 = 2*(P*diag(uxinv3) + Q*diag(xlinv3)); del = dfdx2 - dgdx2; delpos = zeros(m,n); delpos(find(del > 0)) = del(find(del > 0)); P = P + delpos*diag(diap); Q = Q + delpos*diag(diaq); b = P*uxinv1 + Q*xlinv1 - fval ; %%% Solving the subproblem by a primal-dual Newton method [xmma,ymma,zmma,lam,xsi,eta,mu,zet,s] = ... subsolv(m,n,epsimin,low,upp,alfa,beta,p0,q0,P,Q,a0,a,b,c,d);
github
SwanLab/Swan-master
bound.m
.m
Swan-master/TopOptEig/OptimalBucklingColumn/bound.m
6,682
utf_8
813de3962b18bd8c013d954ff9690fc3
function [x] = bound(N) % This algorithm maximizes the least eigenvalue of a clamped-clamped % column, accounting for the presence of simple or multiple eigenvalues. % It also illustrates the best strongest profile of that column against % buckling as well as it gives its buckling modes. Its input variable is N, % which refers to the number of elements of column with the Finite Element % Analysis. % CONSTANTS DEFINITION E=1; %Young's Modulus L=1/N; %Element's length I=1; %Moment of inertia of the column's cross section % VARIABLES DEFINITION n_val=N+1; m=3; % PUNCTUAL LIMITATIONS OF THE DESIGN %(Pre-defined in MMA file) alpha=0.25; beta=10; x=ones(N+1,1); xmin=alpha*ones(N,1); xmin=[xmin; 0]; xmax=beta*ones(N,1); xmax=[xmax; 1000]; xold1=x; xold2=x; loop=0; low = zeros(n_val,1); upp = ones(n_val,1); a0 = 1; a_mma = zeros(m,1); d = zeros(m,1); c = 1000*ones(m,1); % AUXILIAR VECTORS DEFINITION FOR EIGENVALUES COMPARATIVE e=zeros(loop); E1=zeros(loop); E2=zeros(loop); % ELEMENTARY BENDING MATRIX Be =(E*I/(L^3))*[12 6*L -12 6*L; 6*L 4*L^2 -6*L 2*L^2; -12 -6*L 12 -6*L; 6*L 2*L^2 -6*L 4*L^2]; % ELEMENTARY STIFFNESS MATRIX Ke = 1/(30*L)*[36 3*L -36 3*L; 3*L 4*L^2 -3*L -L^2; -36 -3*L 36 -3*L; 3*L -L^2 -3*L 4*L^2]; % ITERATIVE PROCESS change = 1; while (change > 0.0005) && (loop < 1000) loop = loop + 1; % BENDING AND STIFFNESS MATRICES DEFINTION B=sparse(2*N+2, 2*N+2); K=sparse(2*N+2, 2*N+2); % BENDING AND STIFFNESS MATRICES ASSEMBLY for elx=1:N edof=[2*elx-1; 2*elx; 2*(elx+1)-1; 2*(elx+1)]; B(edof,edof)=B(edof,edof)+(x(elx)^2)*Be; K(edof,edof)=K(edof,edof)+ Ke; end % BOUNDARY CONDITIONS fixnodes = union([1,2], [2*N+1,2*N+2]); nodes = 1:2*N+2; freenodes = setdiff(nodes,fixnodes); % EIGENVALUES AND EIGENVECTOR'S CALCULATION [V,D]=eigs(B(freenodes,freenodes),K(freenodes,freenodes),2,'SM'); lambda=sort(diag(D)); if lambda(1)==D(1,1) v1=V(:,1); v2=V(:,2); else v1=V(:,2); v2=V(:,1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %__________________MMA____________________ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % UPDATING OF THE SOLUTION xval = x; % OBJECTIVE FUNCTION f0val=-x(N+1); % OBJECTIVE FUNCTION'S FIRST DERIVATIVE df0dx=zeros(N+1,1); df0dx(N+1)=-1; % OBJECTIVE FUNCTION'S SECOND DERIVATIVE df0dx2 = 0*df0dx; % CONSTRAINTS VECTOR fval=[x(N+1)-lambda(1),x(N+1)-lambda(2),(1/N)*sum(x(1:N))-1]'; % CONSTRAINTS VECTOR'S FIRST DERIVATIVE dfdx=zeros(m,N+1); dfdx(3,1:N)=(1/N)*ones(1,N); % CONSTRAINTS VECTOR'S SECOND DERIVATIVE dfdx2 = 0*dfdx; % MULTIPLE EIGENVALUE'S IDENTIFICATION if abs(D(2,2)-D(1,1))> 1 % OBJECTIVE FUNCTION'S FIRST DERIVATIVE CALCULATION FOR SIMPLE EIGENVALUES W=zeros(2*N+2,2); for i=3:2*N W(i,1)=v1(i-2); end for i=1:N dfdx(1,i)= -(2*x(i,1))*(W(2*(i-1)+1: 2*(i-1)+4,1)'*Be*W(2*(i-1)+1: 2*(i-1)+4,1)); end for i=3:2*N W(i,2)=v2(i-2); end for i=1:N dfdx(2,i)= -(2*x(i,1))*(W(2*(i-1)+1: 2*(i-1)+4,2)'*Be*W(2*(i-1)+1: 2*(i-1)+4,2)); end else D disp('dobles') % OBJECTIVE FUNCTION'S FIRST DERIVATIVE CALCULATION FOR DOUBLE EIGENVALUES % AUXILIAR VECTORS FOR DERIVATIVE'S CALCULATION Q1=zeros(2*N+2,1); Q2=zeros(2*N+2,1); dQ1=zeros(N,1); dQ2=zeros(N,1); dQ1Q2=zeros(N,1); for i=3:2*N Q1(i,1)=V(i-2,1); end for i=3:2*N Q2(i,1)=V(i-2,2); end % DERIVATIVES MATRIX DEFINITION A=zeros(2,2); for i=1:N %Derivadas. dQ1(i,1)= (2*x(i,1))*(Q1(2*(i-1)+1: 2*(i-1)+4,1)'*Be*Q1(2*(i-1)+1: 2*(i-1)+4,1)); dQ2(i,1)= (2*x(i,1))*(Q2(2*(i-1)+1: 2*(i-1)+4,1)'*Be*Q2(2*(i-1)+1: 2*(i-1)+4,1)); dQ1Q2(i,1)= (2*x(i,1))*(Q1(2*(i-1)+1: 2*(i-1)+4,1)'*Be*Q2(2*(i-1)+1: 2*(i-1)+4,1)); A=[dQ1(i,1) dQ1Q2(i,1); dQ1Q2(i,1) dQ2(i,1)]; [U,R]=eigs(A,2,'SM'); S=sort(diag(R)); dfdx(1,i)=-S(1); dfdx(2,i)=-S(2); end end dfdx(1,N+1)=1; dfdx(2,N+1)=1; % INVOKING MMA [xmma,ymma,zmma,lam,xsi,eta,mu,zet,s,low,upp] = ... mmasub(m,n_val,loop,xval,xmin,xmax,xold1,xold2, ... f0val,df0dx,df0dx2,fval,dfdx,dfdx2,low,upp,a0,a_mma,c,d); %CALCULATION THE OF BUCKLING MODES Mode1=zeros(2*N+2); Mode2=zeros(2*N+2); for i=3:2*N Mode1(i)=v1(i-2); Mode2(i)=v2(i-2); end % COLUMN'S PROFILE z=sqrt(x(1:N)); % AXES DEFINION FOR FIGURES ch= 0:L:1-L; h= 0:L:1; % PLOT OF THE BEST STRONGEST PROFILE OF THE COLUMN AGAINST BUCKLING % Clamped-clamped configuration figure(1) subplot(2,2,[1 3]);plot(ch,z) title('Clamped-Clamped Column Profile','Interpreter', 'latex','FontSize',20, 'fontweight','b'); xlabel('x','Interpreter', 'latex','fontsize',14,'fontweight','b'); ylabel('A(x)','Interpreter', 'latex','fontsize',14,'fontweight','b'); %Buckling modes subplot(2,2,2); plot(h,-Mode1(1:2:2*N+2)); title('First Buckling Mode','Interpreter', 'latex','FontSize',14, 'fontweight','b') subplot(2,2,4); plot(h,-Mode2(1:2:2*N+2)); title('Second Buckling Mode','Interpreter', 'latex','FontSize',14, 'fontweight','b') % CONVERGENCE OF DOUBLE EIGENVALUES e(loop)=loop; E1(loop)= D(1,1); E2(loop)=D(2,2); figure(2) plot(e,E1); hold all plot(e,E2); hold off xlabel('Number of Iteration','Interpreter', 'latex','fontsize',18,'fontweight','b'); ylabel('Eigenvalues','Interpreter', 'latex','fontsize',18,'fontweight','b'); axis([0 65 0 100]); %OUTPUT VARIABLES UPDATING xold2 = xold1; xold1 = xval; x = xmma; change = max(abs(x-xold1)); cost(loop) = -xmma(N+1); vol(loop) = (1/N)*sum(x(1:N)); % x=xmma, esta bien? figure(3) plot(cost) figure(4) plot(vol) % PRINTING OF THE RESULTS disp([' It.: ' sprintf('%4i',loop) ' Obj.: ' sprintf('%10.4f',f0val) ... ' Vol.: ' sprintf('%6.3f', (1/N)*(sum(x)-x(N+1)) ) ... ' ch.: ' sprintf('%6.3f',abs(D(2,2)-D(1,1)) )]) end
github
SwanLab/Swan-master
vert2lcon.m
.m
Swan-master/polytopes_2017_10_04_v1.9/vert2lcon.m
5,773
utf_8
3c50975c970cc4f5961715a166e01407
function [A,b,Aeq,beq]=vert2lcon(V,tol) %An extension of Michael Kleder's vert2con function, used for finding the %linear constraints defining a polyhedron in R^n given its vertices. This %wrapper extends the capabilities of vert2con to also handle cases where the %polyhedron is not solid in R^n, i.e., where the polyhedron is defined by %both equality and inequality constraints. % %SYNTAX: % % [A,b,Aeq,beq]=vert2lcon(V,TOL) % %The rows of the N x n matrix V are a series of N vertices of a polyhedron %in R^n. TOL is a rank-estimation tolerance (Default = 1e-10). % %Any point x inside the polyhedron will/must satisfy % % A*x <= b % Aeq*x = beq % %up to machine precision issues. % % %EXAMPLE: % %Consider V=eye(3) corresponding to the 3D region defined %by x+y+z=1, x>=0, y>=0, z>=0. % % % >>[A,b,Aeq,beq]=vert2lcon(eye(3)) % % % A = % % 0.4082 -0.8165 0.4082 % 0.4082 0.4082 -0.8165 % -0.8165 0.4082 0.4082 % % % b = % % 0.4082 % 0.4082 % 0.4082 % % % Aeq = % % 0.5774 0.5774 0.5774 % % % beq = % % 0.5774 %%initial stuff if nargin<2, tol=1e-10; end [M,N]=size(V); if M==1 A=[];b=[]; Aeq=eye(N); beq=V(:); return end p=V(1,:).'; X=bsxfun(@minus,V.',p); %In the following, we need Q to be full column rank %and we prefer E compact. if M>N %X is wide [Q, R, E] = qr(X,0); %economy-QR ensures that E is compact. %Q automatically full column rank since X wide else%X is tall, hence non-solid polytope [Q, R, P]=qr(X); %non-economy-QR so that Q is full-column rank. [~,E]=max(P); %No way to get E compact. This is the alternative. clear P end diagr = abs(diag(R)); if nnz(diagr) %Rank estimation r = find(diagr >= tol*diagr(1), 1, 'last'); %rank estimation iE=1:length(E); iE(E)=iE; Rsub=R(1:r,iE).'; if r>1 [A,b]=vert2con(Rsub,tol); elseif r==1 A=[1;-1]; b=[max(Rsub);-min(Rsub)]; end A=A*Q(:,1:r).'; b=bsxfun(@plus,b,A*p); if r<N Aeq=Q(:,r+1:end).'; beq=Aeq*p; else Aeq=[]; beq=[]; end else %Rank=0. All points are identical A=[]; b=[]; Aeq=eye(N); beq=p; end % ibeq=abs(beq); % ibeq(~beq)=1; % % Aeq=bsxfun(@rdivide,Aeq,ibeq); % beq=beq./ibeq; function [A,b] = vert2con(V,tol) % VERT2CON - convert a set of points to the set of inequality constraints % which most tightly contain the points; i.e., create % constraints to bound the convex hull of the given points % % [A,b] = vert2con(V) % % V = a set of points, each ROW of which is one point % A,b = a set of constraints such that A*x <= b defines % the region of space enclosing the convex hull of % the given points % % For n dimensions: % V = p x n matrix (p vertices, n dimensions) % A = m x n matrix (m constraints, n dimensions) % b = m x 1 vector (m constraints) % % NOTES: (1) In higher dimensions, duplicate constraints can % appear. This program detects duplicates at up to 6 % digits of precision, then returns the unique constraints. % (2) See companion function CON2VERT. % (3) ver 1.0: initial version, June 2005. % (4) ver 1.1: enhanced redundancy checks, July 2005 % (5) Written by Michael Kleder, % %Modified by Matt Jacobson - March 29,2011 % k = convhulln(V); c = mean(V(unique(k),:)); V = bsxfun(@minus,V,c); A = nan(size(k,1),size(V,2)); dim=size(V,2); ee=ones(size(k,2),1); rc=0; for ix = 1:size(k,1) F = V(k(ix,:),:); if lindep(F,tol) == dim rc=rc+1; A(rc,:)=F\ee; end end A=A(1:rc,:); b=ones(size(A,1),1); b=b+A*c'; % eliminate duplicate constraints: [A,b]=rownormalize(A,b); [discard,I]=unique( round([A,b]*1e6),'rows'); A=A(I,:); % NOTE: rounding is NOT done for actual returned results b=b(I); return function [A,b]=rownormalize(A,b) %Modifies A,b data pair so that norm of rows of A is either 0 or 1 if isempty(A), return; end normsA=sqrt(sum(A.^2,2)); idx=normsA>0; A(idx,:)=bsxfun(@rdivide,A(idx,:),normsA(idx)); b(idx)=b(idx)./normsA(idx); function [r,idx,Xsub]=lindep(X,tol) %Extract a linearly independent set of columns of a given matrix X % % [r,idx,Xsub]=lindep(X) % %in: % % X: The given input matrix % tol: A rank estimation tolerance. Default=1e-10 % %out: % % r: rank estimate % idx: Indices (into X) of linearly independent columns % Xsub: Extracted linearly independent columns of X if ~nnz(X) %X has no non-zeros and hence no independent columns Xsub=[]; idx=[]; return end if nargin<2, tol=1e-10; end [Q, R, E] = qr(X,0); diagr = abs(diag(R)); %Rank estimation r = find(diagr >= tol*diagr(1), 1, 'last'); %rank estimation if nargout>1 idx=sort(E(1:r)); idx=idx(:); end if nargout>2 Xsub=X(:,idx); end
github
SwanLab/Swan-master
lcon2vert.m
.m
Swan-master/polytopes_2017_10_04_v1.9/lcon2vert.m
15,372
utf_8
adab98b0f5c2f025ba76f9c88f0c8c64
function [V,nr,nre]=lcon2vert(A,b,Aeq,beq,TOL,checkbounds) %An extension of Michael Kleder's con2vert function, used for finding the %vertices of a bounded polyhedron in R^n, given its representation as a set %of linear constraints. This wrapper extends the capabilities of con2vert to %also handle cases where the polyhedron has zero volume in R^n, i.e., where the %polyhedron is defined by both equality and inequality constraints. % %SYNTAX: % % [V,nr,nre]=lcon2vert(A,b,Aeq,beq,TOL) % %The rows of the N x n matrix V are a series of N vertices of the polyhedron %in R^n, defined by the linear constraints % % A*x <= b % Aeq*x = beq % %By default, Aeq=beq=[], implying no equality constraints. The output "nr" %lists non-redundant inequality constraints, and "nre" lists non-redundant %equality constraints. % %The optional TOL argument is a tolerance used for both rank-estimation and %for testing feasibility of the equality constraints. Default=1e-10. %The default can also be obtained by passing TOL=[]; % %NOTE: It is important that the region specified by the inequality system A*x<=b %have non-zero volume in R^n. For example, A=b=[1;-1] is not legal input data, %because the only solution to A*x<=b is x=1, which has zero volume in R^1. The %proper way to express a zero-volume region is with the addition of %equality constraint data, as for example Aeq=1, beq=1, A=1,b=100. % %EXAMPLE: % %The 3D region defined by x+y+z=1, x>=0, y>=0, z>=0 %is described by the following constraint data. % % % A = % % 0.4082 -0.8165 0.4082 % 0.4082 0.4082 -0.8165 % -0.8165 0.4082 0.4082 % % % b = % % 0.4082 % 0.4082 % 0.4082 % % % Aeq = % % 0.5774 0.5774 0.5774 % % % beq = % % 0.5774 % % % >> V=lcon2vert(A,b,Aeq,beq) % % V = % % 1.0000 0.0000 0.0000 % 0.0000 0.0000 1.0000 % -0.0000 1.0000 0.0000 % % %%initial argument parsing nre=[]; nr=[]; if nargin<5 || isempty(TOL), TOL=1e-10; end if nargin<6, checkbounds=true; end switch nargin case 0 error 'At least 1 input argument required' case 1 b=[]; Aeq=[]; beq=[]; case 2 Aeq=[]; beq=[]; case 3 beq=[]; error 'Since argument Aeq specified, beq must also be specified' end b=b(:); beq=beq(:); if xor(isempty(A), isempty(b)) error 'Since argument A specified, b must also be specified' end if xor(isempty(Aeq), isempty(beq)) error 'Since argument Aeq specified, beq must also be specified' end nn=max(size(A,2)*~isempty(A),size(Aeq,2)*~isempty(Aeq)); if ~isempty(A) && ~isempty(Aeq) && ( size(A,2)~=nn || size(Aeq,2)~=nn) error 'A and Aeq must have the same number of columns if both non-empty' end inequalityConstrained=~isempty(A); equalityConstrained=~isempty(Aeq); [A,b]=rownormalize(A,b); [Aeq,beq]=rownormalize(Aeq,beq); if equalityConstrained && nargout>2 [discard,nre]=lindep([Aeq,beq].',TOL); %#ok<ASGLU> if ~isempty(nre) %reduce the equality constraints Aeq=Aeq(nre,:); beq=beq(nre); else equalityConstrained=false; end end %%Find 1 solution to equality constraints within tolerance if equalityConstrained Neq=null(Aeq); x0=pinv(Aeq)*beq; if norm(Aeq*x0-beq)>TOL*norm(beq) %infeasible nre=[]; nr=[]; %All constraints redundant for empty polytopes V=[]; return; elseif isempty(Neq) if inequalityConstrained && ~all(A*x0<=b) nre=[]; nr=[]; %All constraints redundant for empty polytopes V=[]; return; else %inequality constraints all satisfied, including vacuously V=x0(:).'; nre=(1:nn).'; %Equality constraints determine everything. nr=[];%All inequality constraints are therefore redundant. return end end %rkAeq= nn - size(Neq,2); end %% if inequalityConstrained && equalityConstrained AAA=A*Neq; bbb=b-A*x0; elseif inequalityConstrained AAA=A; bbb=b; elseif equalityConstrained && ~inequalityConstrained error('Non-bounding constraints detected. (Consider box constraints on variables.)') end nnn=size(AAA,2); if nnn==1 %Special case idxu=sign(AAA)==1; idxl=sign(AAA)==-1; idx0=sign(AAA)==0; Q=bbb./AAA; U=Q; U(~idxu)=inf; L=Q; L(~idxl)=-inf; [ub,uloc]=min(U); [lb,lloc]=max(L); if ~all(bbb(idx0)>=0) || ub<lb %infeasible V=[]; nr=[]; nre=[]; return elseif ~isfinite(ub) || ~isfinite(lb) error('Non-bounding constraints detected. (Consider box constraints on variables.)') end Zt=[lb;ub]; if nargout>1 nr=unique([lloc,uloc]); nr=nr(:); end else if nargout>1 [Zt,nr]=con2vert(AAA,bbb,TOL,checkbounds); else Zt=con2vert(AAA,bbb,TOL,checkbounds); end end if equalityConstrained && ~isempty(Zt) V=bsxfun(@plus,Zt*Neq.',x0(:).'); else V=Zt; end if isempty(V) nr=[]; nre=[]; end function [V,nr] = con2vert(A,b,TOL,checkbounds) % CON2VERT - convert a convex set of constraint inequalities into the set % of vertices at the intersections of those inequalities;i.e., % solve the "vertex enumeration" problem. Additionally, % identify redundant entries in the list of inequalities. % % V = con2vert(A,b) % [V,nr] = con2vert(A,b) % % Converts the polytope (convex polygon, polyhedron, etc.) defined by the % system of inequalities A*x <= b into a list of vertices V. Each ROW % of V is a vertex. For n variables: % A = m x n matrix, where m >= n (m constraints, n variables) % b = m x 1 vector (m constraints) % V = p x n matrix (p vertices, n variables) % nr = list of the rows in A which are NOT redundant constraints % % NOTES: (1) This program employs a primal-dual polytope method. % (2) In dimensions higher than 2, redundant vertices can % appear using this method. This program detects redundancies % at up to 6 digits of precision, then returns the % unique vertices. % (3) Non-bounding constraints give erroneous results; therefore, % the program detects non-bounding constraints and returns % an error. You may wish to implement large "box" constraints % on your variables if you need to induce bounding. For example, % if x is a person's height in feet, the box constraint % -1 <= x <= 1000 would be a reasonable choice to induce % boundedness, since no possible solution for x would be % prohibited by the bounding box. % (4) This program requires that the feasible region have some % finite extent in all dimensions. For example, the feasible % region cannot be a line segment in 2-D space, or a plane % in 3-D space. % (5) At least two dimensions are required. % (6) See companion function VERT2CON. % (7) ver 1.0: initial version, June 2005 % (8) ver 1.1: enhanced redundancy checks, July 2005 % (9) Written by Michael Kleder % %Modified by Matt Jacobson - March 30, 2011 % %%%3/4/2012 Improved boundedness test - unfortunately slower than Michael Kleder's if checkbounds [aa,bb,aaeq,bbeq]=vert2lcon(A,TOL); if any(bb<=0) || ~isempty(bbeq) error('Non-bounding constraints detected. (Consider box constraints on variables.)') end clear aa bb aaeq bbeq end dim=size(A,2); %%%Matt J initialization if strictinpoly(b,TOL) c=zeros(dim,1); else slackfun=@(c)b-A*c; %Initializer0 c = pinv(A)*b; %02/17/2012 -replaced with pinv() s=slackfun(c); if ~approxinpoly(s,TOL) %Initializer1 c=Initializer1(TOL,A,b,c); s=slackfun(c); end if ~approxinpoly(s,TOL) %Attempt refinement %disp 'It is unusually difficult to find an interior point of your polytope. This may take some time... ' %disp ' ' c=Initializer2(TOL,A,b,c); %[c,fval]=Initializer1(TOL,A,b,c,10000); s=slackfun(c); end if ~approxinpoly(s,TOL) %error('Unable to locate a point near the interior of the feasible region.') V=[]; nr=[]; return end if ~strictinpoly(s,TOL) %Added 02/17/2012 to handle initializers too close to polytope surface %disp 'Recursing...' idx=( abs(s)<=max(s)*TOL ); Amod=A; bmod=b; Amod(idx,:)=[]; bmod(idx)=[]; Aeq=A(idx,:); %pick the nearest face to c beq=b(idx); faceVertices=lcon2vert(Amod,bmod,Aeq,beq,TOL,1); if isempty(faceVertices) disp 'Something''s wrong. Couldn''t find face vertices. Possibly polyhedron is unbounded.' keyboard end c=faceVertices(1,:).'; %Take any vertex - find local recession cone vector s=slackfun(c); idx=( abs(s)<=max(s)*TOL ); Asub=A(idx,:); bsub=b(idx,:); [aa,bb,aaeq,bbeq]=vert2lcon(Asub); aa=[aa;aaeq;-aaeq]; bb=[bb;bbeq;-bbeq]; clear aaeq bbeq [bmin,idx]=min(bb); if bmin>=-TOL disp 'Something''s wrong. We should have found a recession vector (bb<0).' keyboard end Aeq2=null(aa(idx,:)).'; beq2=Aeq2*c; %find intersection of polytope with line through facet centroid. linetips = lcon2vert(A,b,Aeq2,beq2,TOL,1); if size(linetips,1)<2 disp 'Failed to identify line segment through interior.' disp 'Possibly {x: Aeq*x=beq} has weak intersection with interior({x: Ax<=b}).' keyboard end lineCentroid=mean(linetips);%Relies on boundedness clear aa bb c=lineCentroid(:); s=slackfun(c); end b = s; end %%%end Matt J initialization D=bsxfun(@rdivide,A,b); k = convhulln(D); nr = unique(k(:)); G = zeros(size(k,1),dim); ee=ones(size(k,2),1); discard=false( 1, size(k,1) ); for ix = 1:size(k,1) %02/17/2012 - modified F = D(k(ix,:),:); if lindep(F,TOL)<dim; discard(ix)=1; continue; end G(ix,:)=F\ee; end G(discard,:)=[]; V = bsxfun(@plus, G, c.'); [discard,I]=unique( round(V*1e6),'rows'); V=V(I,:); return function [c,fval]=Initializer1(TOL, A,b,c,maxIter) thresh=-10*max(eps(b)); if nargin>4 [c,fval]=fminsearch(@(x) max([thresh;A*x-b]), c,optimset('MaxIter',maxIter)); else [c,fval]=fminsearch(@(x) max([thresh;A*x-b]), c); end return function c=Initializer2(TOL,A,b,c) %norm( (I-A*pinv(A))*(s-b) ) subj. to s>=0 maxIter=100000; [mm,nn]=size(A); Ap=pinv(A); Aaug=speye(mm)-A*Ap; Aaugt=Aaug.'; M=Aaugt*Aaug; C=sum(abs(M),2); C(C<=0)=min(C(C>0)); slack=b-A*c; slack(slack<0)=0; % relto=norm(b); % relto =relto + (relto==0); % % relres=norm(A*c-b)/relto; IterThresh=maxIter; s=slack; ii=0; %for ii=1:maxIter while ii<=2*maxIter %HARDCODE ii=ii+1; if ii>IterThresh, %warning 'This is taking a lot of iterations' IterThresh=IterThresh+maxIter; end s=s-Aaugt*(Aaug*(s-b))./C; s(s<0)=0; c=Ap*(b-s); %slack=b-A*c; %relres=norm(slack)/relto; %if all(0<slack,1)||relres<1e-6||ii==maxIter, break; end end return function [r,idx,Xsub]=lindep(X,tol) %Extract a linearly independent set of columns of a given matrix X % % [r,idx,Xsub]=lindep(X) % %in: % % X: The given input matrix % tol: A rank estimation tolerance. Default=1e-10 % %out: % % r: rank estimate % idx: Indices (into X) of linearly independent columns % Xsub: Extracted linearly independent columns of X if ~nnz(X) %X has no non-zeros and hence no independent columns Xsub=[]; idx=[]; return end if nargin<2, tol=1e-10; end [Q, R, E] = qr(X,0); diagr = abs(diag(R)); %Rank estimation r = find(diagr >= tol*diagr(1), 1, 'last'); %rank estimation if nargout>1 idx=sort(E(1:r)); idx=idx(:); end if nargout>2 Xsub=X(:,idx); end function [A,b]=rownormalize(A,b) %Modifies A,b data pair so that norm of rows of A is either 0 or 1 if isempty(A), return; end normsA=sqrt(sum(A.^2,2)); idx=normsA>0; A(idx,:)=bsxfun(@rdivide,A(idx,:),normsA(idx)); b(idx)=b(idx)./normsA(idx); function tf=approxinpoly(s,TOL) smax=max(s); if smax<=0 tf=false; return end tf=all(s>=-smax*TOL); function tf=strictinpoly(s,TOL) smax=max(s); if smax<=0 tf=false; return end tf=all(s>=smax*TOL);
github
SwanLab/Swan-master
rayTracer.m
.m
Swan-master/gypsilabModified/openRay/rayTracer.m
3,683
utf_8
1770ad508b72889ee203feed1ff679a2
function ray = rayTracer(ray,ord,rMax) %+========================================================================+ %| | %| OPENRAY - LIBRARY FOR TRI-DIMENSIONAL RAY TRACING | %| openRay is part of the GYPSILAB toolbox for Matlab | %| | %| COPYRIGHT : Matthieu Aussal (c) 2017-2018. | %| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, | %| route de Saclay, 91128 Palaiseau, France. All rights reserved. | %| LICENCE : This program is free software, distributed in the hope that| %| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, | %| redistribute and/or modify it under the terms of the GNU General Public| %| License, as published by the Free Software Foundation (version 3 or | %| later, http://www.gnu.org/licenses). For private use, dual licencing | %| is available, please contact us to activate a "pay for remove" option. | %| CONTACT : [email protected] | %| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      | %| | %| Please acknowledge the gypsilab toolbox in programs or publications in | %| which you use it. | %|________________________________________________________________________| %| '&` | | %| # | FILE : rayTracer.m | %| # | VERSION : 0.41 | %| _#_ | AUTHOR(S) : Matthieu Aussal | %| ( # ) | CREATION : 14.03.2017 | %| / 0 \ | LAST MODIF : 01.04.2018 | %| ( === ) | SYNOPSIS : Ray tracer with octree speedup | %| `---' | | %+========================================================================+ % Infos disp('====> RAY TRACING <====') tps = time(); % Mesh dimension Nelt = length(ray.msh); % Prepare sphere tree = rayTreeInit(ray); % Available ray ind = find( (ray.dst<rMax) & (sum(ray.dir.^2,2)~=0) ); % Current order n = length(ray.pos)-1; % Infos disp([' ~~> Tree with ',num2str(length(tree)),' stage(s) - Elapsed time is ', ... num2str(time()-tps),' seconds.']) % Iterative loop while ~isempty(ind) && (n < ord) % Infos tps = time(); % Full repartition for smallest meshes if (Nelt < 50) Iray = cell(Nelt,1); for el = 1:Nelt Iray{el} = ind; end % Hierarchical repartition else Iray = rayTree(ray,tree,ind); end % Intersection between mesh and ray ray = rayCollision(ray,Iray); % Update available ray ind = find( (ray.dst<rMax) & (sum(ray.dir.^2,2)~=0) ); % Order incrementation n = n + 1; % Infos disp([' + Step ',num2str(n), ' - Elapsed time is ', ... num2str(time()-tps),' seconds.']) end end function tps = time() tps = clock; tps = tps(4)*3600 + tps(5)*60 + tps(6); end % % Representation graphique % figure % hold on % for el = 1:Nelt % subElt = ray.msh.sub(el); % subRay = ray.sub(Iray{el}); % plot(subElt,1) % plot(subRay) % pause % end % hold off
github
SwanLab/Swan-master
integralEbd.m
.m
Swan-master/gypsilabModified/openEbd/integralEbd.m
4,100
utf_8
fde80394e93a08ea414a874b5f3cdc4a
function [I,loc] = integralEbd(Xdom,Ydom,u,green,k,v,tol) %+========================================================================+ %| | %| OPENDOM - LIBRARY FOR NUMERICAL INTEGRATION | %| openDom is part of the GYPSILAB toolbox for Matlab | %| | %| COPYRIGHT : Matthieu Aussal & Francois Alouges (c) 2017-2018. | %| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, | %| route de Saclay, 91128 Palaiseau, France. All rights reserved. | %| LICENCE : This program is free software, distributed in the hope that| %| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, | %| redistribute and/or modify it under the terms of the GNU General Public| %| License, as published by the Free Software Foundation (version 3 or | %| later, http://www.gnu.org/licenses). For private use, dual licencing | %| is available, please contact us to activate a "pay for remove" option. | %| CONTACT : [email protected] | %| [email protected] | %| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      | %| | %| Please acknowledge the gypsilab toolbox in programs or publications in | %| which you use it. | %|________________________________________________________________________| %| '&` | | %| # | FILE : integralEbd.m | %| # | VERSION : 0.50 | %| _#_ | AUTHOR(S) : Matthieu Aussal & Martin Averseng | %| ( # ) | CREATION : 14.03.2017 | %| / 0 \ | LAST MODIF : 25.11.2018 | %| ( === ) | SYNOPSIS : Numerical integation with 8 input arguments | %| `---' | | %+========================================================================+ %%% EFFCIENT BESSEL DECOMPOSITION WITH BOUNDARY ELEMENT OPERATOR --> \int_{mesh(x)} \int_{mesh(y)} psi(x)' f(x,y) psi(y) dxdy % Domain with quadrature [X,Wx] = Xdom.qud; Nx = size(X,1); Wx = spdiags(Wx,0,Nx,Nx); % Domain with quadrature [Y,Wy] = Ydom.qud; Ny = size(Y,1); Wy = spdiags(Wy,0,Ny,Ny); % Finite element matrix with integration Mu = u.uqm(Xdom); if iscell(Mu) Mu{1} = Mu{1}' * Wx; Mu{2} = Mu{2}' * Wx; Mu{3} = Mu{3}' * Wx; else Mu = Mu' * Wx; end % Finite element matrix with integration Mv = v.uqm(Ydom); if iscell(Mv) Mv{1} = Wy * Mv{1}; Mv{2} = Wy * Mv{2}; Mv{3} = Wy * Mv{3}; else Mv = Wy * Mv; end % EBD matrix-vector product if ~iscell(Mu) && ~iscell(green) && ~iscell(Mv) [Gxy,loc] = MVproduct(green,X(:,1:2),Y(:,1:2),tol,k); I = @(V) Mu*Gxy(Mv*V); loc = Mu*loc*Mv; % elseif iscell(Mu) && ~iscell(green) && iscell(Mv) % I = 0; % for i = 1:3 % I = I + Mu{i} * ffmProduct(X,Y,Mv{i}*V,green,k,tol); % end % % elseif iscell(Mu) && iscell(green) && ~iscell(Mv) % I = 0; % for i = 1:3 % I = I + Mu{i} * ffmProduct(X,Y,Mv*V,green{i},k,tol); % end % % elseif ~iscell(Mu) && iscell(green) && iscell(Mv) % I = 0; % for i = 1:3 % I = I + Mu * ffmProduct(X,Y,Mv{i}*V,green{i},k,tol); % end % % elseif iscell(Mu) && iscell(green) && iscell(Mv) % I = 0; % ind = [1 2 3 ; 1 3 2 ; 2 3 1 ; 2 1 3 ; 3 1 2 ; 3 2 1]; % sgn = [+1 -1 +1 -1 +1 -1]; % for i = 1:6 % I = I + sgn(i) .* (Mu{ind(i,1)} * ... % ffmProduct(X,Y,Mv{ind(i,3)}*V,green{ind(i,2)},k,tol)); % end else error('integralEbd.m : unavailable case') end end function MV = test() end
github
SwanLab/Swan-master
besselJRobinzeros.m
.m
Swan-master/gypsilabModified/openEbd/utils/besselJRobinzeros.m
1,431
utf_8
2743c8f9d8c380a9fa5622efd4db0470
function [zs] = besselJRobinzeros(c,k,N,freqCenter) if ~exist('freqCenter','var') freqCenter = 0; end xmin = max(freqCenter - pi*N,0); xmax = freqCenter + 2*pi*N; % Using zn ~ pi*n if c == Inf % Returns the N first zeros of the function % Jk(x) zs = AllZeros(@(x)(besselj(k,x)),xmin,xmax,5*(N+freqCenter)); else % Returns the N first zeros of the function % c Jk(x) + xJk'(x) switch N case 0 derBess = @(x)(-besselj(1,x)); otherwise derBess = @(x)(0.5*(besselj(k-1,x)-besselj(k+1,x))); end zs = AllZeros(@(x)(c*besselj(k,x)+x*derBess(x)),xmin,xmax,5*(N+freqCenter)); end [~,I] = sort(abs(zs-freqCenter)); zs = zs(I); if zs(1)==0 zs = zs(2:(N+1)); else zs = zs(1:N); end zs = zs(:); end function z=AllZeros(f,xmin,xmax,N) % Inputs : % f : function of one variable % [xmin - xmax] : range where f is continuous containing zeros % N : control of the minimum distance (xmax-xmin)/N between two zeros if (nargin<4) N=100; end options=optimset('Display','off'); dx=(xmax-xmin)/N; x2=xmin; y2=f(x2); z=[]; for i=1:N x1=x2; y1=y2; x2=xmin+i*dx; y2=f(x2); if (y1*y2<=0) % Rolle's theorem : one zeros (or more) present z=[z,fsolve(f,(x2*y1-x1*y2)/(y1-y2),options)]; % Linear approximation to guess the initial value in the [x1,x2] range. end end end
github
SwanLab/Swan-master
RadialQuadrature.m
.m
Swan-master/gypsilabModified/openEbd/radialQuad/RadialQuadrature.m
12,212
utf_8
4d0c3e0a8e95bc4506e6e8bf419e7105
classdef RadialQuadrature % Approximation of a function as a series of the functions (e_i) % where e_i is the i-th normalized (in H10 norm) eigenfunction of the % Laplace operator with Dirichlet boundary conditions. % The approximation takes place on the set a(1) < |x| < a(2) of R^2 % and writes % func \approx \sum_{i \in I} alpha0(i) e_i(x) % The coefficients $\alpha$ are chosen as the minimizers of the H10 % norm of this approximation. properties (GetAccess = public, SetAccess = protected) a, b, kernel, tol, Pmax, alpha0, alpha, rho, resH10, errLinfStored, reachedTol, times, scal01, nIter; end methods %% constructor and displays function[rq] = RadialQuadrature(aa,kernel,ttol,varargin) if nargin > 0 %% Input description % REQUIRED INPUTS : % - aa : as described in object description % - func : the radial function to be approximated % - der : the derivative of func % OPTIONAL INPUTS (Name-Value pairs) % - Pmax / type : integer or Inf / Default : Inf % Descr : maximal number of elements in quadrature % - verbose / type : logical / default : false % Descr : Set to true to enable text displays during computation % - batch_size : sets the constant K such that fix(K/a)+1 is the % number of frequencies added at each iteration. %% Creation of quadrature out = radialQuad(aa,kernel,ttol,varargin{:}); %% Export rq.a = out.a; rq.b = out.b; rq.kernel = kernel; rq.tol = out.tol; rq.Pmax = out.Pmax; rq.alpha0 = out.alpha0; rq.alpha = out.alpha; rq.rho = out.rho; rq.resH10 = out.resH10; rq.errLinfStored = out.errLinf; rq.reachedTol = out.reachedTol; rq.times = out.times; rq.scal01 = out.scal01; rq.nIter = out.nIter; rrho = rq.rho; assert(rrho(1) == 0); % This convention must always be satisfied !! The constant. else % Represents the null function rq.a = 0; rq.b = Inf; rq.kernel = Kernel; rq.tol = 0; rq.Pmax = NaN; rq.alpha0 = 0; rq.alpha = 0; rq.rho = 0; rq.errLinfStored = []; rq.reachedTol = true; times = struct; times.freq = 0; times.storeValsError = 0; times.chol = 0; times.cholInv = 0; times.projections = 0; times.testErr = 0; times.total = 0; rq.times = times; rq.nIter = 0; end end function[] = show(this,n) noDer = false; if nargin==1 showAux(this,'all',noDer); else showAux(this,n,noDer); end end function[] = showDer(this,n) optDer = true; if nargin==1 showAux(this,'all',optDer); else showAux(this,n,optDer); end end function[] = disp(this) dispAux(this); end function[] = showTimes(this) t = this.times; fprintf('Time history (s) :\n\n') rowNames = {'J0 roots';'J0 values';'Cholesky';'Cholesky^{-1}';'Projection';'Linf';'TOTAL'}; Times = struct2array(t)'; T = table(Times,'RowNames',rowNames,'VariableNames',{'t'}); disp(T); if sum(Times(1:end-1))>0 explode = Times(1:end-1)*0+1; figure('Name','Computation time','NumberTitle','off') pie(Times(1:end-1)/sum(Times(1:end-1)),explode,rowNames(1:end-1)) end end %% Other methods function[err] = errLinf(this) if isempty(this.errLinfStored) t = RadialQuadrature.tTestLinf(this.a,this.b,this.rho); [~,errs] = this.eval(t); err = max(abs(errs)); else err = this.errLinfStored; end end function[s] = getQuadErrString(this) if this.errLinf < 0.1*this.tol s = sprintf('Quadrature error : < %s \n',num2str(this.errLinf)); elseif this.errLinf <= this.tol s= sprintf('Quadrature error : <= %s \n',num2str(this.tol)); else s = sprintf('Quadrature error : %s \n',num2str(this.errLinf)); s = [s,sprintf('The tolerance defined by user was not reached. Increase Pmax \n')]; end end function[rq] = plus(rq1,rq2) rq = RadialQuadrature; rq.a = max(rq1.a,rq2.a); rq.b = min(rq1.b,rq2.b); rq.kernel = rq1.kernel + rq2.kernel; rq.tol = rq1.tol + rq2.tol; rq.Pmax = max(rq1.Pmax,rq2.Pmax); [rq.rho,rq.alpha] = mergeQuads(rq1.rho,rq1.alpha,rq2.rho,rq2.alpha); [~,rq.alpha0] = mergeQuads(rq1.rho,rq1.alpha0,rq2.rho,rq2.alpha0); [~,rq.scal01] = mergeQuads(rq1.rho(2:end),rq1.scal01,rq2.rho(2:end),rq2.scal01); rq.resH10 = rq1.resH10 + rq2.resH10; rq.errLinfStored = rq.errLinf; rq.reachedTol = and(rq1.reachedTol,rq2.reachedTol); rq.times = sumStruct(rq1.times,rq2.times); rq.nIter = max(rq1.nIter,rq2.nIter); end function[rq] = mtimes(rq1,lambda) if isa(rq1,'RadialQuadrature') assert(and(isa(lambda,'double'),isscalar(lambda))); rq = rq1; rq.alpha = lambda*rq.alpha; rq.alpha0 = lambda*rq.alpha0; rq.kernel = lambda*rq.kernel; rq.tol = abs(lambda)*rq.tol; rq.resH10 = abs(lambda)*rq.resH10; rq.errLinfStored = abs(lambda)*rq1.errLinf; rq.scal01 = lambda*rq.scal01; else rq = mtimes(lambda,rq1); end end function[res] = getTheoreticalBoundH10(this) res = sqrt(-log(this.a)/(2*pi))*this.resH10; end function[s] = getFunc(this) s = func2str(this.kernel.func); end function[this] = dilatation(this,lambda) assert(lambda > this.a); % Otherwise new value of a would be > 1 this.a = this.a/lambda; this.b = min(this.b/lambda,1); oldRho = this.rho; this.rho = this.rho*lambda; newKernel = this.kernel.dilatation(lambda); this.kernel = newKernel; this.alpha0 = this.alpha0.*Cp(oldRho)./Cp(this.rho); end function[quad,err] = eval(this,r) quad = coeff2func(this.alpha0,this.rho,r).'; trueVal = this.kernel.func(r); err = quad - trueVal; end function[quad,err] = evalDer(this,r) quad = coeff2der(this.alpha0,this.rho,r); quad = quad(:); if nargout >=2 trueVal = this.kernel.der(r); trueVal = trueVal(:); err = quad - trueVal; end end end methods (Static) function[t] = tTestLinf(a,b,rho) if a==0 t = [linspace(0,0.1,fix(max(rho))+1),linspace(0.9,1,fix(max(rho))+1)]; else t = [linspace(a,min(2*a,b),fix(10*max(rho)*min(a,b-a))+1)... linspace(min(b,1-a),1,fix(10*max(rho)*min(1-b,a))+1)]; % 10 points per freq end end end end %% Auxiliary functions function[] = dispAux(in) func = in.kernel.func; rho = in.rho; a = in.a; b = in.b; P = length(rho); if isa(in,'RadialQuadratureY0') s = 'Y0(Rx)'; fprintf('Radial Quadrature of function %s \n',s); fprintf('With R = %s \n',num2str(in.getR)); elseif isa(in,'RadialQuadratureLog') s = 'log(Rx)'; fprintf('Radial Quadrature of function %s \n',s); fprintf('With R = %s \n',num2str(in.getR)); else fprintf('Radial Quadrature of function %s \n',func2str(func)); end fprintf('Domain of approximation : [%s, %s]\n',num2str(a),num2str(b)) fprintf('Number of components (not including constant) : %d \n',P-1) disp(in.getQuadErrString); end function [] = showAux(in,n,optDer) if nargin < 2 n = 'all'; optDer = false; elseif nargin==2 optDer = false; end a = in.a; b = in.b; der = in.kernel.der; func = in.kernel.func; rho = in.rho; alpha0 = in.alpha0; tol = in.tol; scal01 = in.scal01; startFreq = in.kernel.startFreq; crop = 0.999; % Needed to avoid having a 10^-16 value in the error at the outer edge % Since function and approx are always equal at b if isequal(n,'all') if optDer figure('Name','Derivative of Radial quadrature','NumberTitle','off') else figure('Name','Radial quadrature','NumberTitle','off') end subplot(1,3,1) showAux(in,1,optDer); subplot(1,3,2) showAux(in,2,optDer); subplot(1,3,3) showAux(in,3,optDer) else switch n case 1 t2 = linspace(0,1,fix(min(max(rho)*5,20000))); t1 = t2(and(t2>a/3,t2<b*crop)); if optDer quad = in.evalDer(t2); plot(t1,real(der(t1)),'b'); hold on plot(t1,imag(der(t1)),'r'); else quad = in.eval(t2); plot(t1,real(func(t1)),'b'); hold on plot(t1,imag(func(t1)),'r'); end plot(t2,real(quad),'b--'); plot(t2,imag(quad),'r--'); plot([a a],ylim,'k--'); if b<1 plot([a a],ylim,'k--'); end axis tight if optDer title('Derivative and its radial quadrature','Interpreter','LaTex'); else title('Function and its radial quadrature','Interpreter','LaTex'); end xlabel('r'); case 2 t2 = linspace(0,1,fix(min(max(rho)*5,20000))); t1 = t2(and(t2>a/3,t2<b*crop)); if optDer [~,err] = in.evalDer(t1); else [~,err] = in.eval(t1); end colors = get(gca,'ColorOrder'); index = get(gca,'ColorOrderIndex'); loglog(t1,abs(err),'color',colors(index,:)); hold on loglog(t1,t1*0+tol,'k--','HandleVisibility','off'); loglog(ones(36,1)*a,10.^(linspace(-18,18,36)),'color',colors(index,:),'LineStyle',... '--','HandleVisibility','off'); grid on axis tight ylim([1e-14 1]); title('Quadrature error','Interpreter','LaTex'); xlabel('r','Interpreter','LaTex'); set(gca,'ColorOrderIndex',mod(index,7)+1) case 3 scatter(rho(2:end),abs(alpha0(2:end)).^2); hold on scatter(rho(2:end),abs(scal01).^2); set(gca,'yscale','log'); grid on; axis tight if startFreq >0 hold on plot([startFreq startFreq],ylim,'k--','LineWidth',2,'HandleVisibility','off'); end title('Spectral power','Interpreter','LaTex'); if isempty(scal01(isnan(scal01))) legend({'Optimal approximation','Truncature of Bessel-Fourier expansion'}) end xlabel('$\rho$','Interpreter','LaTex'); otherwise error('invalid argument n (value 1, 2, 3, or ''all'' accepted)') end end end
github
SwanLab/Swan-master
sphereMaxwell.m
.m
Swan-master/gypsilabModified/miscellaneous/sphereMaxwell.m
5,141
utf_8
c2edb73ded59a527e93e4ed4ea6309c0
function [esTheta, esPhi] = sphereMaxwell(radius, frequency, theta, phi, nMax) % Compute the complex-value scattered electric far field of a perfectly % conducting sphere using the mie series. Follows the treatment in % Chapter 3 of % % Ruck, et. al. "Radar Cross Section Handbook", Plenum Press, 1970. % % The incident electric field is in the -z direction (theta = 0) and is % theta-polarized. The time-harmonic convention exp(jwt) is assumed, and % the Green's function is of the form exp(-jkr)/r. % % Inputs: % radius: Radius of the sphere (meters) % frequency: Operating frequency (Hz) % theta: Scattered field theta angle (radians) % phi: Scattered field phi angle (radians) % nMax: Maximum mode for computing Bessel functions % Outputs: % esTheta: Theta-polarized electric field at the given scattering angles % esPhi: Phi-polarized electric field at the given scattering angles % % Output electric field values are normalized such that the square of the % magnitude is the radar cross section (RCS) in square meters. % % Author: Walton C. Gibson, email: [email protected] % speed of light c = 299792458.0; % radian frequency w = 2.0*pi*frequency; % wavenumber k = w/c; % conversion factor between cartesian and spherical Bessel/Hankel function s = sqrt(0.5*pi/(k*radius)); % mode numbers mode = 1:nMax; % compute spherical bessel, hankel functions [J(mode)] = besselj(mode + 1/2, k*radius); J = J*s; [H(mode)] = besselh(mode + 1/2, 2, k*radius); H = H*s; [J2(mode)] = besselj(mode + 1/2 - 1, k*radius); J2 = J2*s; [H2(mode)] = besselh(mode + 1/2 - 1, 2, k*radius); H2 = H2*s; % derivatives of spherical bessel and hankel functions % Recurrence relationship, Abramowitz and Stegun Page 361 kaJ1P(mode) = (k*radius*J2 - mode .* J ); kaH1P(mode) = (k*radius*H2 - mode .* H ); % Ruck, et. al. (3.2-1) An = -((i).^mode) .* ( J ./ H ) .* (2*mode + 1) ./ (mode.*(mode + 1)); % Ruck, et. al. (3.2-2), using derivatives of bessel functions Bn = ((i).^(mode+1)) .* (kaJ1P ./ kaH1P) .* (2*mode + 1) ./ (mode.*(mode + 1)); [esTheta esPhi] = mieScatteredField(An, Bn, theta, phi, frequency); end function [esTheta, esPhi] = mieScatteredField(An, Bn, theta, phi, frequency) % Compute the complex-value scattered electric far field of a sphere % using pre-computed coefficients An and Bn. Based on the treatment in: % % Ruck, et. al. "Radar Cross Section Handbook", Plenum Press, 1970. % % The incident electric field is in the -z direction (theta = 0) and is % theta-polarized. The time-harmonic convention exp(jwt) is assumed, and % the Green's function is of the form exp(-jkr)/r. % % Inputs: % An: Array of Mie solution constants % Bn: Array of Mie solution constants % (An and Bn should have the same length) % theta: Scattered field theta angle (radians) % phi: Scattered field phi angle (radians) % Outputs: % esTheta: Theta-polarized electric field at the given scattering angles % esPhi: Phi-polarized electric field at the given scattering angles % % Output electric field values are normalized such that the square of the % magnitude is the radar cross section (RCS) in square meters. % % Author: Walton C. Gibson, email: [email protected] % speed of light c = 299792458.0; % wavenumber k = 2.0*pi*frequency/c; sinTheta = abs(sin(theta)); % note: theta only defined from from 0 to pi cosTheta = cos(theta); % ok for theta > pi % first two values of the Associated Legendre Polynomial plm(1) = -sinTheta; plm(2) = -3.0*sinTheta*cosTheta; S1 = 0.0; S2 = 0.0; p = plm(1); % compute coefficients for scattered electric far field for iMode = 1:length(An) % derivative of associated Legendre Polynomial if abs(cosTheta) < 0.999999 if iMode == 1 dp = cosTheta*plm(1)/sqrt(1.0 - cosTheta*cosTheta); else dp = (iMode*cosTheta*plm(iMode) - (iMode + 1)*plm(iMode - 1))/sqrt(1.0 - cosTheta*cosTheta); end end if abs(sinTheta) > 1.0e-6 term1 = An(iMode)*p/sinTheta; term2 = Bn(iMode)*p/sinTheta; end if cosTheta > 0.999999 % Ruck, et. al. (3.1-12) val = ((i)^(iMode-1))*(iMode*(iMode+1)/2)*(An(iMode) - i*Bn(iMode)); S1 = S1 + val; S2 = S2 + val; elseif cosTheta < -0.999999 % Ruck, et. al. (3.1-14) val = ((-i)^(iMode-1))*(iMode*(iMode+1)/2)*(An(iMode) + i*Bn(iMode)); S1 = S1 + val; S2 = S2 - val; else % Ruck, et. al. (3.1-6) S1 = S1 + ((i)^(iMode+1))*(term1 - i*Bn(iMode)*dp); % Ruck, et. al. (3.1-7) S2 = S2 + ((i)^(iMode+1))*(An(iMode)*dp - i*term2); end % recurrence relationship for next Associated Legendre Polynomial if iMode > 1 plm(iMode + 1) = (2.0*iMode + 1)*cosTheta*plm(iMode)/iMode - (iMode + 1)*plm(iMode - 1)/iMode; end p = plm(iMode + 1); end % complex-value scattered electric far field, Ruck, et. al. (3.1-5) esTheta = S1*cos(phi); esPhi = -S2*sin(phi); % normalize electric field so square of magnitude is RCS in square meters esTheta = esTheta*sqrt(4.0*pi)/k; esPhi = esPhi*sqrt(4.0*pi)/k; end
github
SwanLab/Swan-master
mshClean.m
.m
Swan-master/gypsilabModified/openMsh/mshClean.m
5,217
utf_8
ad930c538762f562dbac6b0dabb0bc02
function mesh = mshClean(mesh,dst) %+========================================================================+ %| | %| OPENMSH - LIBRARY FOR MESH MANAGEMENT | %| openMsh is part of the GYPSILAB toolbox for Matlab | %| | %| COPYRIGHT : Matthieu Aussal (c) 2017-2018. | %| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, | %| route de Saclay, 91128 Palaiseau, France. All rights reserved. | %| LICENCE : This program is free software, distributed in the hope that| %| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, | %| redistribute and/or modify it under the terms of the GNU General Public| %| License, as published by the Free Software Foundation (version 3 or | %| later, http://www.gnu.org/licenses). For private use, dual licencing | %| is available, please contact us to activate a "pay for remove" option. | %| CONTACT : [email protected] | %| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      | %| | %| Please acknowledge the gypsilab toolbox in programs or publications in | %| which you use it. | %|________________________________________________________________________| %| '&` | | %| # | FILE : mshClean.m | %| # | VERSION : 0.53 | %| _#_ | AUTHOR(S) : Matthieu Aussal | %| ( # ) | CREATION : 14.03.2017 | %| / 0 \ | LAST MODIF : 14.03.2019 | %| ( === ) | SYNOPSIS : Clean mesh | %| `---' | | %+========================================================================+ % Unify duplicate vertex if isempty(dst) [~,I,J] = unique(single(mesh.vtx),'rows','stable'); else % Range search for specified close distance [J,D] = rangeSearch(mesh.vtx,mesh.vtx,dst); M = rangeMatrix(J,D); M = (M>0); % Security if ~issymmetric(M) error('mshClean.m : unavailable case'); end % Select pairs for descent sort M = triu(M); for i = 1:size(M,1) % Initialization J = []; Jnew = 1; % Iterate on new neighbours while (length(Jnew) > length(J)) % Column indices J = find(M(i,:)); J = J(J>i); % Row indices [I,~] = find(M(:,J)); I = unique(I); I = I(I>i); % Add new values M(i,:) = M(i,:) + sum(M(I,:),1); M(I,:) = 0; % Verify if new entries Jnew = find(M(i,:)); Jnew = Jnew(Jnew>i); end end % Security if (nnz(M) ~= size(M,1)) error('mshClean.m : unavailable case'); end % Find interactions [idx,jdx] = find(M); % Unicity ind = (1:size(mesh.vtx,1))'; ind(jdx) = idx ; [~,I,J] = unique(ind,'stable'); end % Update mesh mesh.vtx = mesh.vtx(I,:); if (size(mesh.elt,1) == 1) J = J'; end mesh.elt = J(mesh.elt); % Extract vertex table from element Ivtx = zeros(size(mesh.vtx,1),1); Ivtx(mesh.elt(:)) = 1; mesh.vtx = mesh.vtx(logical(Ivtx),:); % Reorder elements Ivtx(Ivtx==1) = 1:sum(Ivtx,1); if size(mesh.elt,1) == 1 mesh.elt = Ivtx(mesh.elt)'; else mesh.elt = Ivtx(mesh.elt); end % Empty mesh if (size(mesh.elt,2) == 0) I = 0; % Particles mesh elseif (size(mesh.elt,2) == 1) [~,ind] = unique(mesh.elt); I = ones(size(mesh.elt,1),1); I(ind) = 0; % Edge mesh elseif (size(mesh.elt,2) == 2) I = (mesh.elt(:,1)==mesh.elt(:,2)); % Triangular mesh elseif (size(mesh.elt,2) == 3) I = (mesh.elt(:,1)==mesh.elt(:,2)) + ... (mesh.elt(:,1)==mesh.elt(:,3)) + ... (mesh.elt(:,2)==mesh.elt(:,3)) ; % Tetrahedral mesh elseif (size(mesh.elt,2) == 4) I = (mesh.elt(:,1)==mesh.elt(:,2)) + ... (mesh.elt(:,1)==mesh.elt(:,3)) + ... (mesh.elt(:,1)==mesh.elt(:,4)) + ... (mesh.elt(:,2)==mesh.elt(:,3)) + ... (mesh.elt(:,2)==mesh.elt(:,4)) + ... (mesh.elt(:,3)==mesh.elt(:,4)) ; % Unknown type else error('mshClean.m : unavailable case') end % Extract non degenerated elements if sum(I) mesh = mesh.sub(~I); end end function M = rangeMatrix(J,D) % Row indices and distances idx = cell2mat(J')'; val = cell2mat(D')'+eps; % Column indices jdx = zeros(length(idx)+1,1); n = 1; for i = 1:length(J) jdx(n) = jdx(n) + 1; n = n + length(J{i}); end jdx = cumsum(jdx(1:end-1)); % Sparse Matrix M = sparse(idx,jdx,val); end
github
SwanLab/Swan-master
mshReadPly.m
.m
Swan-master/gypsilabModified/openMsh/mshReadPly.m
17,258
utf_8
d02bba04d191d09e5e18680d30103adf
function [vertex,face] = mshReadPly(filename) % read_ply - read data from PLY file. % % [vertex,face] = read_ply(filename); % % 'vertex' is a 'nb.vert x 3' array specifying the position of the vertices. % 'face' is a 'nb.face x 3' array specifying the connectivity of the mesh. % % IMPORTANT: works only for triangular meshes. % % Copyright (c) 2003 Gabriel Peyr [d,c] = plyread(filename); vi = d.face.vertex_indices; nf = length(vi); face = zeros(nf,3); for i=1:nf face(i,:) = vi{i}+1; end vertex = [d.vertex.x, d.vertex.y, d.vertex.z]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Elements,varargout] = plyread(Path,Str) %PLYREAD Read a PLY 3D data file. % [DATA,COMMENTS] = PLYREAD(FILENAME) reads a version 1.0 PLY file % FILENAME and returns a structure DATA. The fields in this structure % are defined by the PLY header; each element type is a field and each % element property is a subfield. If the file contains any comments, % they are returned in a cell string array COMMENTS. % % [TRI,PTS] = PLYREAD(FILENAME,'tri') or % [TRI,PTS,DATA,COMMENTS] = PLYREAD(FILENAME,'tri') converts vertex % and face data into triangular connectivity and vertex arrays. The % mesh can then be displayed using the TRISURF command. % % Note: This function is slow for large mesh files (+50K faces), % especially when reading data with list type properties. % % Example: % [Tri,Pts] = PLYREAD('cow.ply','tri'); % trisurf(Tri,Pts(:,1),Pts(:,2),Pts(:,3)); % colormap(gray); axis equal; % % See also: PLYWRITE % Pascal Getreuer 2004 [fid,Msg] = fopen(Path,'rt'); % open file in read text mode if fid == -1, error(Msg); end Buf = fscanf(fid,'%s',1); if ~strcmp(Buf,'ply') fclose(fid); error('Not a PLY file.'); end %%% read header %%% Position = ftell(fid); Format = ''; NumComments = 0; Comments = {}; % for storing any file comments NumElements = 0; NumProperties = 0; Elements = []; % structure for holding the element data ElementCount = []; % number of each type of element in file PropertyTypes = []; % corresponding structure recording property types ElementNames = {}; % list of element names in the order they are stored in the file PropertyNames = []; % structure of lists of property names while 1 Buf = fgetl(fid); % read one line from file BufRem = Buf; Token = {}; Count = 0; while ~isempty(BufRem) % split line into tokens [tmp,BufRem] = strtok(BufRem); if ~isempty(tmp) Count = Count + 1; % count tokens Token{Count} = tmp; end end if Count % parse line switch lower(Token{1}) case 'format' % read data format if Count >= 2 Format = lower(Token{2}); if Count == 3 & ~strcmp(Token{3},'1.0') fclose(fid); error('Only PLY format version 1.0 supported.'); end end case 'comment' % read file comment NumComments = NumComments + 1; Comments{NumComments} = ''; for i = 2:Count Comments{NumComments} = [Comments{NumComments},Token{i},' ']; end case 'element' % element name if Count >= 3 if isfield(Elements,Token{2}) fclose(fid); error(['Duplicate element name, ''',Token{2},'''.']); end NumElements = NumElements + 1; NumProperties = 0; Elements = setfield(Elements,Token{2},[]); PropertyTypes = setfield(PropertyTypes,Token{2},[]); ElementNames{NumElements} = Token{2}; PropertyNames = setfield(PropertyNames,Token{2},{}); CurElement = Token{2}; ElementCount(NumElements) = str2double(Token{3}); if isnan(ElementCount(NumElements)) fclose(fid); error(['Bad element definition: ',Buf]); end else error(['Bad element definition: ',Buf]); end case 'property' % element property if ~isempty(CurElement) & Count >= 3 NumProperties = NumProperties + 1; eval(['tmp=isfield(Elements.',CurElement,',Token{Count});'],... 'fclose(fid);error([''Error reading property: '',Buf])'); if tmp error(['Duplicate property name, ''',CurElement,'.',Token{2},'''.']); end % add property subfield to Elements eval(['Elements.',CurElement,'.',Token{Count},'=[];'], ... 'fclose(fid);error([''Error reading property: '',Buf])'); % add property subfield to PropertyTypes and save type eval(['PropertyTypes.',CurElement,'.',Token{Count},'={Token{2:Count-1}};'], ... 'fclose(fid);error([''Error reading property: '',Buf])'); % record property name order eval(['PropertyNames.',CurElement,'{NumProperties}=Token{Count};'], ... 'fclose(fid);error([''Error reading property: '',Buf])'); else fclose(fid); if isempty(CurElement) error(['Property definition without element definition: ',Buf]); else error(['Bad property definition: ',Buf]); end end case 'end_header' % end of header, break from while loop break; end end end %%% set reading for specified data format %%% if isempty(Format) warning('Data format unspecified, assuming ASCII.'); Format = 'ascii'; end switch Format case 'ascii' Format = 0; case 'binary_little_endian' Format = 1; case 'binary_big_endian' Format = 2; otherwise fclose(fid); error(['Data format ''',Format,''' not supported.']); end if ~Format Buf = fscanf(fid,'%f'); % read the rest of the file as ASCII data BufOff = 1; else % reopen the file in read binary mode fclose(fid); if Format == 1 fid = fopen(Path,'r','ieee-le.l64'); % little endian else fid = fopen(Path,'r','ieee-be.l64'); % big endian end % find the end of the header again (using ftell on the old handle doesn't give the correct position) BufSize = 8192; Buf = [blanks(10),char(fread(fid,BufSize,'uchar')')]; i = []; tmp = -11; while isempty(i) i = findstr(Buf,['end_header',13,10]); % look for end_header + CR/LF i = [i,findstr(Buf,['end_header',10])]; % look for end_header + LF if isempty(i) tmp = tmp + BufSize; Buf = [Buf(BufSize+1:BufSize+10),char(fread(fid,BufSize,'uchar')')]; end end % seek to just after the line feed fseek(fid,i + tmp + 11 + (Buf(i + 10) == 13),-1); end %%% read element data %%% % PLY and MATLAB data types (for fread) PlyTypeNames = {'char','uchar','short','ushort','int','uint','float','double', ... 'char8','uchar8','short16','ushort16','int32','uint32','float32','double64'}; MatlabTypeNames = {'schar','uchar','int16','uint16','int32','uint32','single','double'}; SizeOf = [1,1,2,2,4,4,4,8]; % size in bytes of each type for i = 1:NumElements % get current element property information eval(['CurPropertyNames=PropertyNames.',ElementNames{i},';']); eval(['CurPropertyTypes=PropertyTypes.',ElementNames{i},';']); NumProperties = size(CurPropertyNames,2); % fprintf('Reading %s...\n',ElementNames{i}); if ~Format %%% read ASCII data %%% for j = 1:NumProperties Token = getfield(CurPropertyTypes,CurPropertyNames{j}); if strcmpi(Token{1},'list') Type(j) = 1; else Type(j) = 0; end end % parse buffer if ~any(Type) % no list types Data = reshape(Buf(BufOff:BufOff+ElementCount(i)*NumProperties-1),NumProperties,ElementCount(i))'; BufOff = BufOff + ElementCount(i)*NumProperties; else ListData = cell(NumProperties,1); for k = 1:NumProperties ListData{k} = cell(ElementCount(i),1); end % list type for j = 1:ElementCount(i) for k = 1:NumProperties if ~Type(k) Data(j,k) = Buf(BufOff); BufOff = BufOff + 1; else tmp = Buf(BufOff); ListData{k}{j} = Buf(BufOff+(1:tmp))'; BufOff = BufOff + tmp + 1; end end end end else %%% read binary data %%% % translate PLY data type names to MATLAB data type names ListFlag = 0; % = 1 if there is a list type SameFlag = 1; % = 1 if all types are the same for j = 1:NumProperties Token = getfield(CurPropertyTypes,CurPropertyNames{j}); if ~strcmp(Token{1},'list') % non-list type tmp = rem(strmatch(Token{1},PlyTypeNames,'exact')-1,8)+1; if ~isempty(tmp) TypeSize(j) = SizeOf(tmp); Type{j} = MatlabTypeNames{tmp}; TypeSize2(j) = 0; Type2{j} = ''; SameFlag = SameFlag & strcmp(Type{1},Type{j}); else fclose(fid); error(['Unknown property data type, ''',Token{1},''', in ', ... ElementNames{i},'.',CurPropertyNames{j},'.']); end else % list type if length(Token) == 3 ListFlag = 1; SameFlag = 0; tmp = rem(strmatch(Token{2},PlyTypeNames,'exact')-1,8)+1; tmp2 = rem(strmatch(Token{3},PlyTypeNames,'exact')-1,8)+1; if ~isempty(tmp) & ~isempty(tmp2) TypeSize(j) = SizeOf(tmp); Type{j} = MatlabTypeNames{tmp}; TypeSize2(j) = SizeOf(tmp2); Type2{j} = MatlabTypeNames{tmp2}; else fclose(fid); error(['Unknown property data type, ''list ',Token{2},' ',Token{3},''', in ', ... ElementNames{i},'.',CurPropertyNames{j},'.']); end else fclose(fid); error(['Invalid list syntax in ',ElementNames{i},'.',CurPropertyNames{j},'.']); end end end % read file if ~ListFlag if SameFlag % no list types, all the same type (fast) Data = fread(fid,[NumProperties,ElementCount(i)],Type{1})'; else % no list types, mixed type Data = zeros(ElementCount(i),NumProperties); for j = 1:ElementCount(i) for k = 1:NumProperties Data(j,k) = fread(fid,1,Type{k}); end end end else ListData = cell(NumProperties,1); for k = 1:NumProperties ListData{k} = cell(ElementCount(i),1); end if NumProperties == 1 BufSize = 512; SkipNum = 4; j = 0; % list type, one property (fast if lists are usually the same length) while j < ElementCount(i) Position = ftell(fid); % read in BufSize count values, assuming all counts = SkipNum [Buf,BufSize] = fread(fid,BufSize,Type{1},SkipNum*TypeSize2(1)); Miss = find(Buf ~= SkipNum); % find first count that is not SkipNum fseek(fid,Position + TypeSize(1),-1); % seek back to after first count if isempty(Miss) % all counts are SkipNum Buf = fread(fid,[SkipNum,BufSize],[int2str(SkipNum),'*',Type2{1}],TypeSize(1))'; fseek(fid,-TypeSize(1),0); % undo last skip for k = 1:BufSize ListData{1}{j+k} = Buf(k,:); end j = j + BufSize; BufSize = floor(1.5*BufSize); else if Miss(1) > 1 % some counts are SkipNum Buf2 = fread(fid,[SkipNum,Miss(1)-1],[int2str(SkipNum),'*',Type2{1}],TypeSize(1))'; for k = 1:Miss(1)-1 ListData{1}{j+k} = Buf2(k,:); end j = j + k; end % read in the list with the missed count SkipNum = Buf(Miss(1)); j = j + 1; ListData{1}{j} = fread(fid,[1,SkipNum],Type2{1}); BufSize = ceil(0.6*BufSize); end end else % list type(s), multiple properties (slow) Data = zeros(ElementCount(i),NumProperties); for j = 1:ElementCount(i) for k = 1:NumProperties if isempty(Type2{k}) Data(j,k) = fread(fid,1,Type{k}); else tmp = fread(fid,1,Type{k}); ListData{k}{j} = fread(fid,[1,tmp],Type2{k}); end end end end end end % put data into Elements structure for k = 1:NumProperties if (~Format & ~Type(k)) | (Format & isempty(Type2{k})) eval(['Elements.',ElementNames{i},'.',CurPropertyNames{k},'=Data(:,k);']); else eval(['Elements.',ElementNames{i},'.',CurPropertyNames{k},'=ListData{k};']); end end end clear Data ListData; fclose(fid); if (nargin > 1 & strcmpi(Str,'Tri')) | nargout > 2 % find vertex element field Name = {'vertex','Vertex','point','Point','pts','Pts'}; Names = []; for i = 1:length(Name) if any(strcmp(ElementNames,Name{i})) Names = getfield(PropertyNames,Name{i}); Name = Name{i}; break; end end if any(strcmp(Names,'x')) & any(strcmp(Names,'y')) & any(strcmp(Names,'z')) eval(['varargout{1}=[Elements.',Name,'.x,Elements.',Name,'.y,Elements.',Name,'.z];']); else varargout{1} = zeros(1,3); end varargout{2} = Elements; varargout{3} = Comments; Elements = []; % find face element field Name = {'face','Face','poly','Poly','tri','Tri'}; Names = []; for i = 1:length(Name) if any(strcmp(ElementNames,Name{i})) Names = getfield(PropertyNames,Name{i}); Name = Name{i}; break; end end if ~isempty(Names) % find vertex indices property subfield PropertyName = {'vertex_indices','vertex_indexes','vertex_index','indices','indexes'}; for i = 1:length(PropertyName) if any(strcmp(Names,PropertyName{i})) PropertyName = PropertyName{i}; break; end end if ~iscell(PropertyName) % convert face index lists to triangular connectivity eval(['FaceIndices=varargout{2}.',Name,'.',PropertyName,';']); N = length(FaceIndices); Elements = zeros(N*2,3); Extra = 0; for k = 1:N Elements(k,:) = FaceIndices{k}(1:3); for j = 4:length(FaceIndices{k}) Extra = Extra + 1; Elements(N + Extra,:) = [Elements(k,[1,j-1]),FaceIndices{k}(j)]; end end Elements = Elements(1:N+Extra,:) + 1; end end else varargout{1} = Comments; end end
github
SwanLab/Swan-master
mshReadStl.m
.m
Swan-master/gypsilabModified/openMsh/mshReadStl.m
3,520
utf_8
68055d9984fbde771248884d606df172
function [vtx,elt] = mshReadStl(file) % STLREAD imports geometry from an STL file into MATLAB. % FV = STLREAD(FILENAME) imports triangular faces from the ASCII or binary % STL file idicated by FILENAME, and returns the patch struct FV, with fields % 'faces' and 'vertices'. % % [F,V] = STLREAD(FILENAME) returns the faces F and vertices V separately. % % [F,V,N] = STLREAD(FILENAME) also returns the face normal vectors. % % The faces and vertices are arranged in the format used by the PATCH plot % object. % Copyright 2011 The MathWorks, Inc. if ~exist(file,'file') error(['File ''%s'' not found. If the file is not on MATLAB''s path' ... ', be sure to specify the full path to the file.'], file); end fid = fopen(file,'r'); if ~isempty(ferror(fid)) error(lasterror); %#ok end M = fread(fid,inf,'uint8=>uint8'); fclose(fid); [elt,vtx] = stlbinary(M); %if( isbinary(M) ) % This may not be a reliable test % [f,v,n] = stlbinary(M); %else % [f,v,n] = stlascii(M); %end end function [F,V,N] = stlbinary(M) F = []; V = []; N = []; if length(M) < 84 error('MATLAB:stlread:incorrectFormat', ... 'Incomplete header information in binary STL file.'); end % Bytes 81-84 are an unsigned 32-bit integer specifying the number of faces % that follow. numFaces = typecast(M(81:84),'uint32'); %numFaces = double(numFaces); if numFaces == 0 warning('MATLAB:stlread:nodata','No data in STL file.'); return end T = M(85:end); F = NaN(numFaces,3); V = NaN(3*numFaces,3); N = NaN(numFaces,3); numRead = 0; while numRead < numFaces % Each facet is 50 bytes % - Three single precision values specifying the face normal vector % - Three single precision values specifying the first vertex (XYZ) % - Three single precision values specifying the second vertex (XYZ) % - Three single precision values specifying the third vertex (XYZ) % - Two unused bytes i1 = 50 * numRead + 1; i2 = i1 + 50 - 1; facet = T(i1:i2)'; n = typecast(facet(1:12),'single'); v1 = typecast(facet(13:24),'single'); v2 = typecast(facet(25:36),'single'); v3 = typecast(facet(37:48),'single'); n = double(n); v = double([v1; v2; v3]); % Figure out where to fit these new vertices, and the face, in the % larger F and V collections. fInd = numRead + 1; vInd1 = 3 * (fInd - 1) + 1; vInd2 = vInd1 + 3 - 1; V(vInd1:vInd2,:) = v; F(fInd,:) = vInd1:vInd2; N(fInd,:) = n; numRead = numRead + 1; end end function [F,V,N] = stlascii(M) warning('MATLAB:stlread:ascii','ASCII STL files currently not supported.'); F = []; V = []; N = []; end % TODO: Change the testing criteria! Some binary STL files still begin with % 'solid'. function tf = isbinary(A) % ISBINARY uses the first line of an STL file to identify its format. if isempty(A) || length(A) < 5 error('MATLAB:stlread:incorrectFormat', ... 'File does not appear to be an ASCII or binary STL file.'); end if strcmpi('solid',char(A(1:5)')) tf = false; % ASCII else tf = true; % Binary end end
github
SwanLab/Swan-master
mshTree.m
.m
Swan-master/gypsilabModified/openMsh/mshTree.m
7,421
utf_8
4adb5dc5a797e4fae6a0167bb58ed1d3
function tree = mshTree(mesh,typ,Nlf,fig) %+========================================================================+ %| | %| OPENMSH - LIBRARY FOR MESH MANAGEMENT | %| openMsh is part of the GYPSILAB toolbox for Matlab | %| | %| COPYRIGHT : Matthieu Aussal (c) 2017-2018. | %| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, | %| route de Saclay, 91128 Palaiseau, France. All rights reserved. | %| LICENCE : This program is free software, distributed in the hope that| %| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, | %| redistribute and/or modify it under the terms of the GNU General Public| %| License, as published by the Free Software Foundation (version 3 or | %| later, http://www.gnu.org/licenses). For private use, dual licencing | %| is available, please contact us to activate a "pay for remove" option. | %| CONTACT : [email protected] | %| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      | %| | %| Please acknowledge the gypsilab toolbox in programs or publications in | %| which you use it. | %|________________________________________________________________________| %| '&` | | %| # | FILE : mshtree.m | %| # | VERSION : 0.41 | %| _#_ | AUTHOR(S) : Matthieu Aussal | %| ( # ) | CREATION : 14.03.2017 | %| / 0 \ | LAST MODIF : 01.04.2018 | %| ( === ) | SYNOPSIS : Hierarchical tree subdivision | %| `---' | | %+========================================================================+ % Security if isempty(Nlf) Nlf = 1; end % Particles are element centers X = mesh.ctr; Nx = length(mesh); % Box initialization Xmin = min(X,[],1); Xmax = max(X,[],1); edg = max(Xmax-Xmin); % Initialize octree tree = cell(1,1); tree{1}.chd = []; tree{1}.ctr = Xmin + 0.5*edg; tree{1}.edg = edg; tree{1}.ind{1} = (1:Nx)'; tree{1}.nbr = Nx; tree{1}.prt = 0; % Recursive hierarchical clustering n = 1; while (max(tree{n}.nbr) > Nlf) % Tree subdivision if strcmp(typ,'octree') [tree{n+1,1},Ichd] = mshSubDivide8(X,tree{n}); elseif strcmp(typ,'binary') [tree{n+1,1},Ichd] = mshSubDivide2(X,tree{n}); else error('mshTree.m : unavailable case') end % Add children indices to parents tree{n}.chd = Ichd; % Verify children if (norm( cell2mat(tree{n}.chd) - (1:length(tree{n+1}.nbr))' , 'inf') > 1e-12) error('mshTree.m : unavailable case') end % Verify indices if (norm( sort(cell2mat(tree{n+1}.ind)) - sort(cell2mat(tree{n+1}.ind)) , 'inf') > 1e-12) error('mshTree.m : unavailable case') end % Verify number if (abs( sum(tree{n+1}.nbr) - sum(tree{n}.nbr) ) > 1e-12) error('mshTree.m : unavailable case') end % Verify parents if (norm( unique(tree{n+1}.prt) - (1:length(tree{n}.nbr))' , 'inf') > 1e-12) error('mshTree.m - unavailable case') end % Incrementation n = n+1; % Graphical representation if fig % Numbering boxes V = zeros(Nx,1); for i = 1:length(tree{n}.ind) V(tree{n}.ind{i}) = i; end % Graphical representation figure(fig); clf plot3(tree{n}.ctr(:,1),tree{n}.ctr(:,2),tree{n}.ctr(:,3),'ok','MarkerSize',8) hold on plot(mesh,V) title(['Tree at step ',num2str(n-1)]) grid on ; axis equal xlabel('X'); zlabel('Y'); zlabel('Z'); alpha(0.9) colorbar drawnow end end end function [chd,Ichd] = mshSubDivide8(X,prt) % Initialize children tree Nprt = length(prt.ind); chd.chd = []; chd.ctr = zeros(8*Nprt,3); chd.edg = 0.5 * prt.edg; chd.ind = cell(8*Nprt,1); chd.nbr = zeros(8*Nprt,1); chd.prt = zeros(8*Nprt,1); % Initialize children indices Ichd = cell(Nprt,1); % Loop for parents l = 0; for i = 1:Nprt % Central subdivision ind = prt.ind{i}; cutx = X(ind,1)<=prt.ctr(i,1); cuty = X(ind,2)<=prt.ctr(i,2); cutz = X(ind,3)<=prt.ctr(i,3); % Indices repartition for children cut = [ ... cutx & cuty & cutz , ... ~cutx & cuty & cutz , ... cutx & ~cuty & cutz , ... ~cutx & ~cuty & cutz , ... cutx & cuty & ~cutz , ... ~cutx & cuty & ~cutz , ... cutx & ~cuty & ~cutz , ... ~cutx & ~cuty & ~cutz ]; Ncut = sum(cut,1); % Indices for parents Ichd{i} = l + (1:sum(Ncut>0))'; % Children centers ctr = ones(8,1)*prt.ctr(i,:) + 0.25*prt.edg .* [... -1 -1 -1 ; 1 -1 -1; -1 1 -1 ; 1 1 -1 ;... -1 -1 1 ; 1 -1 1; -1 1 1 ; 1 1 1 ]; % Add box only for non empty children for j = find(Ncut) % Children data chd.ctr(l+1,:) = ctr(j,:); chd.ind{l+1} = ind(cut(:,j)); chd.nbr(l+1) = Ncut(j); chd.prt(l+1) = i; % Incrementation l = l + 1; end end % Extract non empty box chd.ctr = chd.ctr(1:l,:); chd.ind = chd.ind(1:l); chd.nbr = chd.nbr(1:l); chd.prt = chd.prt(1:l); end function [chd,Ichd] = mshSubDivide2(X,prt) % Initialize children tree Nprt = length(prt.ind); chd.chd = []; chd.ctr = zeros(2*Nprt,3); chd.edg = zeros(2*Nprt,1); chd.ind = cell(2*Nprt,1); chd.nbr = zeros(2*Nprt,1); chd.prt = zeros(2*Nprt,1); % Initialize children indices Ichd = cell(Nprt,1); % Loop for parents l = 0; for i = 1:Nprt % Local points ind = prt.ind{i}; % Local box xmin = min(X(ind,:),[],1); xmax = max(X(ind,:),[],1); xdgl = xmax - xmin; % Median subdivision over largest dimension [~,d] = max(xdgl); m = median(X(ind,d)); cutd = (X(ind,d) <= m); cut = [ cutd , ~cutd ]; Ncut = sum(cut,1); % Security for planar repartition if (abs(Ncut(1)-Ncut(2)) > 1) [~,I] = sort(X(ind,d)); cutd(:) = 0; cutd(I(1:floor(end/2))) = 1; cut = [ cutd , ~cutd ]; Ncut = sum(cut,1); end % Indices for parents Ichd{i} = l + (1:sum(Ncut>0))'; % Add box only for non empty children for j = find(Ncut) % Local box Ij = ind(cut(:,j)); xmin = min(X(Ij,:),[],1); xmax = max(X(Ij,:),[],1); % Children data chd.ctr(l+1,:) = 0.5*(xmin+xmax); chd.edg(l+1) = max(xmax-xmin); chd.ind{l+1} = Ij; chd.nbr(l+1) = Ncut(j); chd.prt(l+1) = i; % Incrementation l = l + 1; end end % Extract non empty box chd.ctr = chd.ctr(1:l,:); chd.edg = chd.edg(1:l); chd.ind = chd.ind(1:l); chd.nbr = chd.nbr(1:l); chd.prt = chd.prt(1:l); end
github
SwanLab/Swan-master
mshMidpoint.m
.m
Swan-master/gypsilabModified/openMsh/mshMidpoint.m
6,741
utf_8
dddacc98db280b2469202b171e440e64
function [meshr,Ir] = mshMidpoint(mesh,I) %+========================================================================+ %| | %| OPENMSH - LIBRARY FOR MESH MANAGEMENT | %| openMsh is part of the GYPSILAB toolbox for Matlab | %| | %| COPYRIGHT : Matthieu Aussal (c) 2017-2018. | %| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, | %| route de Saclay, 91128 Palaiseau, France. All rights reserved. | %| LICENCE : This program is free software, distributed in the hope that| %| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, | %| redistribute and/or modify it under the terms of the GNU General Public| %| License, as published by the Free Software Foundation (version 3 or | %| later, http://www.gnu.org/licenses). For private use, dual licencing | %| is available, please contact us to activate a "pay for remove" option. | %| CONTACT : [email protected] | %| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      | %| | %| Please acknowledge the gypsilab toolbox in programs or publications in | %| which you use it. | %|________________________________________________________________________| %| '&` | | %| # | FILE : mshMidpoint.m | %| # | VERSION : 0.50 | %| _#_ | AUTHOR(S) : Matthieu Aussal | %| ( # ) | CREATION : 14.03.2017 | %| / 0 \ | LAST MODIF : 25.11.2018 | %| ( === ) | SYNOPSIS : Refine triangular mesh with midpoint algorithm| %| `---' | | %+========================================================================+ % Check dimenion if (size(mesh,2) ~= 3) error('mshMidpoint : unavailable case 1') end % Save color and replace by hierarchy col = mesh.col; mesh.col = (1:length(mesh))'; % Submeshing (triangle) meshs = mesh.sub(I); % Edge meshes edgs = meshs.edg; [edg,Itri] = mesh.edg; % Interface with edge multiplicity for triangle [int,Iedg] = intersect(edg,edgs); ind = ismember(Itri,Iedg); mlt = sum(ind,2); % Security tmp = setdiff(int,edgs); if (size(tmp.elt,1) ~= 0) error('mshMidpoint.m : unavailable case 2'); end % Initialize refined mesh for element without refinement meshr = mesh.sub(mlt==0); % Subdivision with 1 common edge tmp = mesh.sub(mlt==1); tmp = mshMidpoint1(tmp,int); meshr = union(meshr,tmp); % Subdivision with 2 common edges tmp = mesh.sub(mlt==2); tmp = mshMidpoint2(tmp,int); meshr = union(meshr,tmp); % Subdivision with 3 common edges tmp = mesh.sub(mlt==3); tmp = mshMidpoint3(tmp); meshr = union(meshr,tmp); % Parent indices and replace colours Ir = meshr.col; meshr.col = col(Ir); % Security if (sum(mesh.ndv)-sum(meshr.ndv))/sum(mesh.ndv) > 1e-15*length(meshr) error('mshMidpoint.m : unavailable case 3'); end end function mesh = mshMidpoint1(mesh,int) % Mesh nodes and edges center [nds,ctr] = data(mesh); % Interface center Xctr = int.ctr; % Refined mesh initialization Nvtx = size(mesh.vtx,1); Nelt = length(mesh); col = mesh.col; mesh = mesh.sub([]); % Loop over nodes for i = 1:3 % Neighbours ip1 = mod(i,3)+1; ip2 = mod(ip1,3)+1; % Selected center are inside subdivided mesh I = find(ismember(single(ctr{i}),single(Xctr),'rows')); % First elements vtx = [nds{i}(I,:) ; nds{ip1}(I,:) ; ctr{i}(I,:)]; elt = reshape((1:3*length(I))',length(I),3); tmp = msh(vtx,elt,col(I)); mesh = union(mesh,tmp); % Second elements vtx = [nds{i}(I,:) ; ctr{i}(I,:) ; nds{ip2}(I,:)]; elt = reshape((1:3*length(I))',length(I),3); tmp = msh(vtx,elt,col(I)); mesh = union(mesh,tmp); % Mesh fusion with previous submeshes mesh = union(mesh,tmp); end % Security if size(mesh.elt,1) ~= 2*Nelt error('mshMidpoint1.m : unavailable case 1') end if size(mesh.vtx,1) ~= Nvtx+Nelt error('mshMidpoint1.m : unavailable case 2') end end function mesh = mshMidpoint2(mesh,int) % Mesh nodes and edges center [nds,ctr] = data(mesh); % Interface center Xctr = int.ctr; % Refined mesh initialization Nvtx = size(mesh.vtx,1); Nelt = length(mesh); col = mesh.col; mesh = mesh.sub([]); % Loop over nodes for i = 1:3 % Neighbours ip1 = mod(i,3)+1; ip2 = mod(ip1,3)+1; % Selected nodes center not inside subdivided mesh I = find(~ismember(single(ctr{i}),single(Xctr),'rows')); % First elements vtx = [nds{i}(I,:) ; ctr{ip2}(I,:) ; ctr{ip1}(I,:)]; elt = reshape((1:3*length(I))',length(I),3); tmp = msh(vtx,elt,col(I)); mesh = union(mesh,tmp); % Second elements vtx = [nds{ip1}(I,:) ; nds{ip2}(I,:) ; ctr{ip1}(I,:)]; elt = reshape((1:3*length(I))',length(I),3); tmp = msh(vtx,elt,col(I)); mesh = union(mesh,tmp); % Third elements vtx = [nds{ip1}(I,:) ; ctr{ip1}(I,:) ; ctr{ip2}(I,:) ; ]; elt = reshape((1:3*length(I))',length(I),3); tmp = msh(vtx,elt,col(I)); mesh = union(mesh,tmp); end % Security if size(mesh.elt,1) ~= 3*Nelt error('mshMidpoint2.m : unavailable case 1') end if size(mesh.vtx,1) ~= Nvtx+2*Nelt error('mshMidpoint2.m : unavailable case 2') end end function mesh = mshMidpoint3(mesh) % Mesh nodes and edges center [nds,ctr] = data(mesh); % Refined mesh initialization with centered triangle Nelt = length(mesh); vtx = [ctr{1} ; ctr{2} ; ctr{3}]; elt = reshape((1:3*Nelt)',Nelt,3); col = mesh.col; mesh = msh(vtx,elt,col); % For each node for i = 1:3 % Neighbours ip1 = mod(i,3)+1; ip2 = mod(ip1,3)+1; % New submesh with nodes triangles vtx = [nds{i} ; ctr{ip2} ; ctr{ip1}]; tmp = msh(vtx,elt,col); % Mesh fusion with previous submeshes mesh = union(mesh,tmp); end % Security if size(mesh.elt,1) ~= 4*Nelt error('mshMidpoint3.m : unavailable case 1') end end function [nds,ctr] = data(mesh) % Triangle nodes nds{1} = mesh.vtx(mesh.elt(:,1),:); nds{2} = mesh.vtx(mesh.elt(:,2),:); nds{3} = mesh.vtx(mesh.elt(:,3),:); % Edges center ctr{1} = 0.5 * (nds{2} + nds{3}); ctr{2} = 0.5 * (nds{3} + nds{1}); ctr{3} = 0.5 * (nds{1} + nds{2}); end
github
SwanLab/Swan-master
mshReadMsh.m
.m
Swan-master/gypsilabModified/openMsh/mshReadMsh.m
4,296
utf_8
bb060ec4ccb725d2837eac69deaaa6b8
function [vtx,elt,col,data] = mshReadMsh(filename) %+========================================================================+ %| | %| OPENMSH - LIBRARY FOR MESH MANAGEMENT | %| openMsh is part of the GYPSILAB toolbox for Matlab | %| | %| COPYRIGHT : Matthieu Aussal (c) 2017-2018. | %| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, | %| route de Saclay, 91128 Palaiseau, France. All rights reserved. | %| LICENCE : This program is free software, distributed in the hope that| %| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, | %| redistribute and/or modify it under the terms of the GNU General Public| %| License, as published by the Free Software Foundation (version 3 or | %| later, http://www.gnu.org/licenses). For private use, dual licencing | %| is available, please contact us to activate a "pay for remove" option. | %| CONTACT : [email protected] | %| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      | %| | %| Please acknowledge the gypsilab toolbox in programs or publications in | %| which you use it. | %|________________________________________________________________________| %| '&` | | %| # | FILE : mshReadMsh.m | %| # | VERSION : 0.42 | %| _#_ | AUTHOR(S) : Matthieu Aussal | %| ( # ) | CREATION : 14.03.2017 | %| / 0 \ | LAST MODIF : 31.12.2018 | %| ( === ) | SYNOPSIS : Read .msh files (particle, edge, triangular | %| `---' | and tetrahedral | %+========================================================================+ % Open fid = fopen(filename,'r'); if (fid==-1) error('mshReadMsh.m : cant open the file'); end % Read file using keywords str = fgets(fid); while ~(str==-1) if contains(str,'$Nodes') vtx = readNodes(fid); elseif contains(str,'$Elements') [elt,col] = readElements(fid); elseif contains(str,'$NodeData') data = readNodesData(fid,size(vtx,1)); end str = fgets(fid); end % Close file fclose(fid); % Only keep higher elements (tetra > triangle > edge > particles) ord = sum(elt>0,2); dim = max(ord); elt = elt(ord==dim,1:dim); col = col(ord==dim); end function vtx = readNodes(fid) % Nodes Nvtx = str2double(fgets(fid)); vtx = zeros(Nvtx,3); for i = 1:Nvtx tmp = str2num(fgets(fid)); vtx(i,:) = tmp(2:4); end % Verify nodes ending str = fgets(fid); if ~contains(str,'$EndNodes') error('mshReadMsh.m : unavailable case'); end end function [elt,col] = readElements(fid) % Initialize Nelt = str2double(fgets(fid)); elt = zeros(Nelt,4); col = zeros(Nelt,1); % Elements (up to tetra) for i = 1:Nelt tmp = str2num(fgets(fid)); col(i) = tmp(4); if (tmp(2) == 15) % particles elt(i,1) = tmp(6); elseif (tmp(2) == 1) % segment elt(i,1:2) = tmp(6:7); elseif (tmp(2) == 2) % triangles elt(i,1:3) = tmp(6:8); elseif (tmp(2) == 4) % tetrahedra elt(i,1:4) = tmp(6:9); end end % Verify elements ending str = fgets(fid); if ~contains(str,'$EndElements') error('mshReadMsh.m : unavailable case'); end end function data = readNodesData(fid,Nvtx) % Go to Node Data str = fgets(fid); while ~contains(str,num2str(Nvtx)) str = fgets(fid); end % Initialization with first row tmp = str2num(fgets(fid)); data = zeros(Nvtx,length(tmp)-1); data(1,:) = tmp(2:end); % Nodes data for i = 2:Nvtx tmp = str2num(fgets(fid)); data(i,:) = tmp(2:end); end % Verify node data ending str = fgets(fid); if ~contains(str,'$EndNodeData') error('mshReadMsh.m : unavailable case'); end end
github
SwanLab/Swan-master
ffmInteractionsSparse.m
.m
Swan-master/gypsilabModified/openFfm/ffmInteractionsSparse.m
6,847
utf_8
24a505db7ba4f09c90852a9030e47f92
function MV = ffmInteractionsSparse(X,Xbox,Y,Ybox,V,Ibox,green,k,edg,tol) %+========================================================================+ %| | %| OPENFFM - LIBRARY FOR FAST AND FREE MEMORY CONVOLUTION | %| openFfm is part of the GYPSILAB toolbox for Matlab | %| | %| COPYRIGHT : Matthieu Aussal (c) 2017-2019. | %| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, | %| route de Saclay, 91128 Palaiseau, France. All rights reserved. | %| LICENCE : This program is free software, distributed in the hope that| %| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, | %| redistribute and/or modify it under the terms of the GNU General Public| %| License, as published by the Free Software Foundation (version 3 or | %| later, http://www.gnu.org/licenses). For private use, dual licencing | %| is available, please contact us to activate a "pay for remove" option. | %| CONTACT : [email protected] | %| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      | %| | %| Please acknowledge the gypsilab toolbox in programs or publications in | %| which you use it. | %|________________________________________________________________________| %| '&` | | %| # | FILE : ffmInteractionsSparse.m | %| # | VERSION : 0.61 | %| _#_ | AUTHOR(S) : Matthieu Aussal | %| ( # ) | CREATION : 14.03.2017 | %| / 0 \ | LAST MODIF : 05.09.2019 | %| ( === ) | SYNOPSIS : Sparse product for low-frequency compressible | %| `---' | leaves | %+========================================================================+ % Initialisation du produit Matrice-Vecteur MV = zeros(size(X,1),1,class(V)); % Quadrature des interpolations lagrangiennes [Xq,ii,jj,kk,xq] = ffmQuadrature(green,k,edg,tol); % Unicite des vecteurs de translation XY = Ybox.ctr(Ibox(:,2),:) - Xbox.ctr(Ibox(:,1),:); [~,Il,It] = unique(floor(XY*1e6),'rows','stable'); Nt = length(Il); % Fonctions de transfert Tx = cell(Nt,1); Ty = cell(Nt,1); for i = 1:Nt [Tx{i},Ty{i}] = ffmTransfert(Xq,XY(Il(i),:),green,k,edg,tol); end % Interpolations en Y Vy = cell(size(Ybox.ind)); for i = unique(Ibox(:,2)') % Boite centree en Y dans le cube unitaire d'interpolation iy = Ybox.ind{i}; ny = length(iy); Ym = (2/edg) .* (Y(iy,:) - ones(ny,1)*Ybox.ctr(i,:)); % Interpolation de Lagrange (Ym->Xq) Vy{i} = ffmInterp(ii,jj,kk,xq,Ym,V(iy),-1); end % Translations TVy = cell(size(Xbox.ind)); for i = 1:length(TVy) TVy{i} = 0; end for i = 1:size(Ibox,1) TVy{Ibox(i,1)} = TVy{Ibox(i,1)} + Tx{It(i)} * (Ty{It(i)} * Vy{Ibox(i,2)}); end % Interpolations en X for i = unique(Ibox(:,1)') % Boite centree en X dans le cube unitaire d'interpolation ix = Xbox.ind{i}; nx = length(ix); Xm = (2/edg) .* (X(ix,:) - ones(nx,1)*Xbox.ctr(i,:)); % Interpolation de Lagrange (Xq->Xm) MV(ix) = ffmInterp(ii,jj,kk,xq,Xm,TVy{i},+1); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Xq,ii,jj,kk,xq] = ffmQuadrature(green,k,edg,tol) % Nuages de reference emetteurs X x = (-0.5*edg:edg/(10-1):0.5*edg)'; [x,y,z] = ndgrid(x,x,x); Xref = [x(:) y(:) z(:)]; Nref = size(Xref,1); % Nuage de reference transmetteur avec translation minimale r0 = [2*edg 0 0]; Yref = [Xref(:,1)+r0(1) , Xref(:,2:3)]; % Xref dans le cube unitaire d'interpolation a = [-0.5 -0.5 -0.5]*edg; b = [0.5 0.5 0.5]*edg; Xuni = ones(Nref,1)*(2./(b-a)) .* (Xref-ones(Nref,1)*(b+a)./2); % Solution de reference V = ones(Nref,1) + 1i; [I,J] = ndgrid(1:Nref,1:1:Nref); ref = reshape(ffmGreenKernel(Xref(I,:),Yref(J,:),green,k),Nref,Nref) * V; % Initialisation sol = 1e6; nq = 1; % Boucle sur l'ordre de quadrature while norm(ref-sol)/norm(ref) > tol % Incrementation nq = nq + 1; % Indices de construction de l'interpolateur de Lagrange [ii,jj,kk] = ndgrid(1:nq,1:nq,1:nq); % Points de quadratures Tchebitchev (1D et 3D) xq = cos( (2*(nq:-1:1)-1)*pi/(2*nq))'; Xq = [xq(ii(:)) xq(jj(:)) xq(kk(:))]; % Vecteur de la translation [TA,TB] = ffmTransfert(Xq,r0,green,k,edg,tol); % Interpolation de Lagrange (Ym->Yq) Vy = ffmInterp(ii,jj,kk,xq,Xuni,V,-1); % Transfert (Yq->Xq) TVy = TA * (TB * Vy); % Interpolation de Lagrange (Xq->Xm) sol = ffmInterp(ii,jj,kk,xq,Xuni,TVy,+1); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [TA,TB] = ffmTransfert(Xq,xy,green,k,edg,tol) % Dimensions Nq = size(Xq,1); % Interpolants en X a = [0 0 0]; b = [1 1 1]*edg; Txq = (ones(Nq,1)*(b-a)/2).*Xq + ones(Nq,1)*(b+a)/2; % Interpolants en Y a = xy + a; b = xy + b; Tyq = (ones(Nq,1)*(b-a)/2).*Xq + ones(Nq,1)*(b+a)/2; % Noyaux de green avec compression aux interpolants [TA,TB,flag] = hmxACA(Txq,Tyq,green,k,tol/10); % Calcul direct si necessaire if ~flag [I,J] = ndgrid(1:Nq,1:1:Nq); TA = reshape(ffmGreenKernel(Txq(I,:),Tyq(J,:),green,k),Nq,Nq); TB = 1; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function MV = ffmInterp(ii,jj,kk,xq,X,V,iflag) % Dimensions Nx = size(X,1); nq = length(xq); % Interpolateur de Lagrange par dimension d'espace Aq = cell(1,nq); for l = 1:nq^2 if isempty(Aq{ii(l)}) Aq{ii(l)} = ones(Nx,3,class(V)); end if ii(l) ~= jj(l) Aq{ii(l)} = Aq{ii(l)} .* (X-xq(jj(l)))./(xq(ii(l))-xq(jj(l))); end end % Interpolation (X->Xq) if (iflag == -1) MV = zeros(nq^3,1,class(V)); for l = 1:nq^3 MV(l) = (Aq{ii(l)}(:,1) .* Aq{jj(l)}(:,2) .* Aq{kk(l)}(:,3)).' * V; end % Interpolation (Xq->X) elseif (iflag == +1) MV = zeros(Nx,1,class(V)); for l = 1:nq^3 MV = MV + Aq{ii(l)}(:,1) .* Aq{jj(l)}(:,2) .* Aq{kk(l)}(:,3) .* V(l); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
SwanLab/Swan-master
ffmInteractionsSparseHF.m
.m
Swan-master/gypsilabModified/openFfm/ffmInteractionsSparseHF.m
7,864
utf_8
6e507eb2dc266efb27bf9fd99d6e0304
function MV = ffmInteractionsSparseHF(X,Xbox,Y,Ybox,V,Ibox,green,k,edg,tol) %+========================================================================+ %| | %| OPENFFM - LIBRARY FOR FAST AND FREE MEMORY CONVOLUTION | %| openFfm is part of the GYPSILAB toolbox for Matlab | %| | %| COPYRIGHT : Matthieu Aussal (c) 2017-2019. | %| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, | %| route de Saclay, 91128 Palaiseau, France. All rights reserved. | %| LICENCE : This program is free software, distributed in the hope that| %| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, | %| redistribute and/or modify it under the terms of the GNU General Public| %| License, as published by the Free Software Foundation (version 3 or | %| later, http://www.gnu.org/licenses). For private use, dual licencing | %| is available, please contact us to activate a "pay for remove" option. | %| CONTACT : [email protected] | %| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      | %| | %| Please acknowledge the gypsilab toolbox in programs or publications in | %| which you use it. | %|________________________________________________________________________| %| '&` | | %| # | FILE : ffmInteractionsSparseHF.m | %| # | VERSION : 0.6 | %| _#_ | AUTHOR(S) : Matthieu Aussal | %| ( # ) | CREATION : 14.03.2017 | %| / 0 \ | LAST MODIF : 05.09.2019 | %| ( === ) | SYNOPSIS : Sparse product for high-frequency compressible| %| `---' | leaves | %+========================================================================+ % Initialisation du produit Matrice-Vecteur MV = zeros(size(X,1),1,class(V)); % Quadrature spherique de Geggenbauer [Xq,Wq,l] = ffmQuadratureHF(k,edg,tol); % Unicite des vecteurs de translation XY = Ybox.ctr(Ibox(:,2),:) - Xbox.ctr(Ibox(:,1),:); [~,Il,It] = unique(floor(XY*1e6),'rows','stable'); Nt = length(Il); % Fonctions de transfert Txy = cell(Nt,1); for i = 1:Nt Txy{i} = ffmTransfertHF(Xq,Wq,XY(Il(i),:),k,l); end % Convolution en Y Vy = cell(size(Ybox.ind)); for i = unique(Ibox(:,2)') % Boite centree en Y iy = Ybox.ind{i}; ny = length(iy); Ym = Y(iy,:) - ones(ny,1)*Ybox.ctr(i,:); % Transformee de Fourier inverse (Ym->Xq) Vy{i} = ffmInterpHF(Xq,Ym,V(iy),-1,tol); % Derivation du noyau en Y if strcmp(green(1:end-1),'grady[exp(ikr)/r]') j = str2double(green(end)); Vy{i} = -1i*Xq(:,j) .* Vy{i}; end end % Translations TVy = cell(size(Xbox.ind)); for i = 1:length(TVy) TVy{i} = 0; end for i = 1:size(Ibox,1) TVy{Ibox(i,1)} = TVy{Ibox(i,1)} + Txy{It(i)}.*Vy{Ibox(i,2)}; end % Convolutions en X for i = unique(Ibox(:,1)') % Boite centree en X ix = Xbox.ind{i}; nx = length(ix); Xm = X(ix,:) - ones(nx,1)*Xbox.ctr(i,:); % Derivation du noyau en X if strcmp(green(1:end-1),'gradx[exp(ikr)/r]') j = str2double(green(end)); TVy{i} = 1i*Xq(:,j) .* TVy{i}; end % Transformee de Fourier (Xq->X) MV(ix) = ffmInterpHF(Xm,Xq,TVy{i},+1,tol); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Xq,Wq,l] = ffmQuadratureHF(k,edg,tol) % Ordre harmonique (E. Darve) l = floor( abs(k)*sqrt(3)*edg - log(tol) ); % Quadrature de Gauss sur [-1,1] u = 1:l; u = u ./ sqrt(4*u.^2 - 1); [V,x] = eig( diag(u,-1) + diag(u,+1) ); [x,I] = sort(diag(x)); w = 2*V(1,I)'.^2; % Quadrature de Gauss sur [0,1] par transformation lineaire a = 0; b = 1; x = 0.5*(b-a)*x + 0.5*(a+b); w = 0.5*(b-a)*w; % Quadrature de Gauss en elevation (phi) phi = acos(2*x(end:-1:1)-1) - pi/2; Wp = 2*w(end:-1:1)'; % Quadrature reguliere en azimut (theta) Ntheta = 2*(l+1); theta = 2*pi/Ntheta*(0:Ntheta-1)'; Wt = 2*pi/Ntheta*ones(Ntheta,1); % Quadrature spherique par produit tensoriel [theta,phi] = ndgrid(theta,phi); theta = theta(:); phi = phi(:); Wq = Wt * Wp; Wq = Wq(:); % Coordonnees carthesienne et produit par le nombre d'onde [x,y,z] = sph2cart(theta,phi,1); Xq = k*[x,y,z]; % Securite if (l>3) % Harmoniques spheriques jusqu'a l'ordre 3 n = 1; Ylm = zeros(length(theta),16); for ll = 0:3 Plm = sqrt((2*ll+1)/(4*pi)) * legendre(ll,cos(pi/2-phi),'sch').'; for m = -ll:ll if m<0 Ylm(:,n) = Plm(:,abs(m)+1) .* sin(abs(m).*theta); else Ylm(:,n) = Plm(:,abs(m)+1) .* cos(abs(m).*theta); end n = n+1; end end % Test de l'integration spherique des harmoniques (produit scalaire) [m,n] = size(Ylm); if norm( (Ylm' * spdiags(Wq,0,m,m) * Ylm) - eye(n) , 'inf') > 1e-5 error('ffmQuadratureHF.m - error 1'); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function T = ffmTransfertHF(Xq,ws,xy,k,l) % Fonctions de hankel spherique 1ere espece besselhs = @(n,z) sqrt(pi./(2.*z)) .* besselh(n+0.5,1,z); % Distance kr = k*norm(xy); % cosinus(angle incidence) x = Xq*(-xy/kr)'; % Initialisation de la recursion sur (besselhs(kr) * Pl(cos(phi)) P0 = ones(size(x)); P1 = x; T = besselhs(0,kr).*P0 + 3i*besselhs(1,kr).*P1; % Construction recursive des polynomes de Legendre for ll = 2:l P2 = 1/ll .* ( (2*(ll-1)+1).*x.*P1 - (ll-1).*P0 ); T = T + (2*ll+1) * 1i^ll * besselhs(ll,kr) .* P2; P0 = P1; P1 = P2; end % Operateur de Translation T = 1i*abs(k)/(4*pi) .* ws .* T; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function MV = ffmInterpHF(X,Y,V,iflag,tol) % Dimensions Nx = size(X,1); Ny = size(Y,1); Nmax = max(Nx,Ny); Nmin = min(Nx,Ny); % DFT non uniforme if (Nmin<100) || (Nmin<log(Nmax)) MV = exp(1i*iflag*X*Y') * V; % FFT non uniforme else % Conversion de type if isa(X,'single') || isa(Y,'single') || isa(V,'single') sgl = 1; X = double(X); Y = double(Y); V = double(V); else sgl = 0; end % Initialisation produit Matrice-Vecteur MV = zeros(Nx,1) + 1i*zeros(Nx,1); % Prevention de coplanarite en X Nx = Nx + 1; X(end+1,:) = X(end,:) + tol; MV(end+1) = 0; % Prevention de coplanarite en X Ny = Ny + 1; Y(end+1,:) = Y(end,:) + tol; V(end+1) = 0; % Transformee de Fourier ier = 0; mex_id = 'nufft3d3f90(i int[x], i double[], i double[], i double[], i dcomplex[], i int[x], i double[x], i int[x], i double[], i double[], i double[], io dcomplex[], io int[x])'; MV = nufft3d(mex_id,Ny,Y(:,1),Y(:,2),Y(:,3),V, iflag, tol, ... Nx,X(:,1),X(:,2),X(:,3),MV, ier, 1, 1, 1, 1, 1); % Supression dernier point MV = MV(1:end-1); % Conversion de type if sgl MV = single(MV); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
SwanLab/Swan-master
domSemiAnalyticInt2D.m
.m
Swan-master/gypsilabModified/openDom/domSemiAnalyticInt2D.m
3,515
utf_8
2da8f9735e072de96405ed6bcae8e470
function [logR,rlogR,gradlogR] = domSemiAnalyticInt2D(X,S,n,tau) %+========================================================================+ %| | %| OPENDOM - LIBRARY FOR NUMERICAL INTEGRATION | %| openDom is part of the GYPSILAB toolbox for Matlab | %| | %| COPYRIGHT : Matthieu Aussal & Francois Alouges (c) 2017-2018. | %| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, | %| route de Saclay, 91128 Palaiseau, France. All rights reserved. | %| LICENCE : This program is free software, distributed in the hope that| %| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, | %| redistribute and/or modify it under the terms of the GNU General Public| %| License, as published by the Free Software Foundation (version 3 or | %| later, http://www.gnu.org/licenses). For private use, dual licencing | %| is available, please contact us to activate a "pay for remove" option. | %| CONTACT : [email protected] | %| [email protected] | %| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      | %| | %| Please acknowledge the gypsilab toolbox in programs or publications in | %| which you use it. | %|________________________________________________________________________| %| '&` | | %| # | FILE : domSemiAnalyticInt2D.m | %| # | VERSION : 0.53 | %| _#_ | AUTHOR(S) : Matthieu Aussal & Martin Averseng | %| ( # ) | CREATION : 25.11.2018 | %| / 0 \ | LAST MODIF : 14.03.2019 | %| ( === ) | SYNOPSIS : Semi-analytic integration on segment for a set| %| `---' | of particles | %+========================================================================+ % Dimensions Nx = size(X,1); unx = ones(Nx,1); un2 = [1 1]; % Parametric coordinates on (AB) XA = unx*S(1,:)-X; XB = unx*S(2,:)-X; d = -XA*n'; a = XA*tau'; b = XB*tau'; % Check distance to (AB) bool = (abs(d)>1e-8); % Initialization logR = zeros(Nx,1); % General primitive : \int_a^b ln(x^2+d^2) dx I = find(bool); logR(I) = F1(b,d,I) - F1(a,d,I); % Assymptotic primitive (d=0) : \int_a^b ln(x^2) dx I = find(~bool); logR(I) = F2(b,I) - F2(a,I); % \int rlogr rlogRtau = F3(b,d) - F3(a,d); rlogRn = -(d.*logR); rlogR = rlogRtau*tau + rlogRn*n; % \int grad(logr) gradlogRtau = 1/2*log((b.^2 + d.^2)./(a.^2 + d.^2)); gradlogRtau(I) = log(abs(b(I)./a(I))); gradlogRtau(a<=0 & b>=0 & ~bool) = 0; gradlogRn = -atan(b./d) + atan(a./d); gradlogRn(I) = 0; gradlogR = gradlogRtau*tau + gradlogRn*n; end function y = F1(x,d,I) x = x(I); d = d(I); y = 1/2*x.*log(x.^2+d.^2) - x + d.*atan(x./d); end function y = F2(x,I) x = x(I); y = xlog(x) - x; end function y = F3(x,d) y = 1/4 * (xlog(x.^2+d.^2) - x.^2); end function y = xlog(x) y = x.*log(abs(x)); I = (abs(x)<1e-15); y(I) = 0; end
github
SwanLab/Swan-master
createSTL.m
.m
Swan-master/PostProcess/STL/createSTL.m
1,760
utf_8
52f2112d13e434c8770602ea429328c4
function createSTL pathTcl = '/home/alex/Desktop/tclFiles/'; gidPath = '/home/alex/GiDx64/15.0.1/'; resultsFile = '/home/alex/git-repos/FEM-MAT-OO/Output/GrippingTriangleFine_Case_1_1_1/GrippingTriangleFine_Case_1_1_1_12.flavia.res'; writeTclFile(pathTcl,gidPath,resultsFile) writeExportTclFile(pathTcl,gidPath) command = [gidPath,'gid -t "source ',pathTcl,'callGiD.tcl"']; unix(command); delete('oe.msh') delete('oe.png') delete('oe.res') delete('oe.vv') delete('oe') command = [gidPath,'gid -t "source callGiD2.tcl"']; unix(command); end function writeExportTclFile(pathTcl,gidpath) tclFile = 'callGiD2.tcl'; stlFileTocall = 'ExportSTL.tcl'; fid = fopen(tclFile,'w+'); gidBasPath = [gidpath,'templates/STL.bas']; fprintf(fid,['set path "',pathTcl,'"\n']); fprintf(fid,['set tclFile "',stlFileTocall,'"\n']); fprintf(fid,['source $path$tclFile \n']); fprintf(fid,['set input "$path/oe.gid" \n']); fprintf(fid,['set output "$path/oeFile.stl" \n']); fprintf(fid,['set gidBasPath "',gidBasPath,'" \n']); fprintf(fid,['ExportSTL $input $output $gidBasPath \n']); fclose(fid); end function writeTclFile(pathTcl,gidpath,resultsFile) tclFile = 'callGiD.tcl'; stlFileTocall = 'CreateSurfaceSTL.tcl'; gidBasPath = [gidpath,'templates/DXF.bas']; fid = fopen(tclFile,'w+'); fprintf(fid,['set path "',pathTcl,'"\n']); fprintf(fid,['set tclFile "',stlFileTocall,'"\n']); fprintf(fid,['source $path$tclFile \n']); fprintf(fid,['set output "$path/oe" \n']); fprintf(fid,['set inputFile "',resultsFile,'"\n']); fprintf(fid,['set meshFile "$path/oe" \n']); fprintf(fid,['set gidProjectName "$path/oe" \n']); fprintf(fid,['set gidBasPath "',gidBasPath,'" \n']); fprintf(fid,['CreateSurfaceSTL $inputFile $output $meshFile $gidProjectName $gidBasPath \n']); fclose(fid); end
github
SwanLab/Swan-master
getSubclasses.m
.m
Swan-master/Other/getSubclasses.m
7,309
utf_8
47de174f369d7029c2615f02e92929fd
function tb = getSubclasses(rootclass,rootpath) % GETSUBCLASSES Display all subclasses % % GETSUBCLASSES(ROOTCLASS, [ROOTPATH]) % Lists all subclasses of ROOTCLASS and their node dependency. % ROOTCLASS can be a string with the name of the class, an % object or a meta.class(). % % It looks for subclasses in the ROOTPATH folder and in all % its subfolders (at any depth). If ROOTPATH is not specified, % it is set to the folder where ROOTCLASS is located. % ROOTCLASS can also be a negative integer indicating how many % folders above that of ROOTCLASS to begin the search. % % TB = GETSUBCLASSES... % TB is a table with % .names - name of the subclass % .from - current node % .to - node of the direct subclass % % If the function is called with no output, it will plot % a graph() with the dependencies. % % % Example: % % which sde % C:\Program Files\MATLAB\R2016a\toolbox\finance\finsupport\@sde\sde.m % sde constructor % % getSubclasses('sde','C:\Program Files\MATLAB\R2016a\toolbox\finance\finsupport\'); % % See also: META.CLASS, GRAPH rootclass = validateRootclass(rootclass); if isempty(rootclass) || ~isa(rootclass, 'meta.class') error('getSubclasses:unrecognizedClass','Unrecognized class.') end if nargin < 2 rootpath = 0; end rootpath = validateRootpath(rootpath, rootclass); garray = addNewTree([],rootclass,{rootclass.Name}); garray = recurseFolder(rootpath, garray); tb = getFromToNodes(garray{1}); if nargout == 0 G = graph(tb.from, tb.to, [], unique(tb.names,'stable')); G.plot() end end % retrieve files and subfolders recursively function garray = recurseFolder(folder, garray) [files, subfld] = getEligible(folder); garray = checkFiles(files,garray); for ii = 1:numel(subfld) garray = recurseFolder(subfld{ii}, garray); % cell2table(garray{1}.values,'VariableNames',garray{1}.keys) end end % List files and folders to search down for subclasses function [files,subfolders] = getEligible(folder) list = dir(folder); idir = [list.isdir]; files = {list(~idir).name}; files = regexp(files,'.+(?=\.m|\.p)','match','once'); subfolders = {list(idir).name}; % Drop . and .. (setdiff is slow) nfld = nnz(idir); idir = false(nfld,1); for ii = 1:nfld idir(ii) = subfolders{ii}(1) == '.'; end subfolders(idir) = []; subfolders = fullfile(folder, subfolders); end % check if files are classes and build up parent relationship function garray = checkFiles(files,garray) for ii = 1:numel(files) mcls = meta.class.fromName(files{ii}); if isempty(mcls) || isempty(mcls.SuperclassList) || isInTreeArray(garray, mcls.Name) % Do something with classes with no parents? continue end garray = addNewTree(garray, mcls); [garray,trash,hasMerged] = getSuperclassTree(mcls, garray, numel(garray), 1); if hasMerged garray(end) = []; end end end % recursively travel up through all parents assigning node values function [garray, current_node, doMerge] = getSuperclassTree(mcls,garray,index, current_node) disp(mcls.Name) % Add direct parents [garray{index}, parent_list, current_node] = addParents(mcls, garray{index}, current_node); % Check if any parent is mergeable doMerge = false; nparen = numel(parent_list); iexclude = false(nparen,1); for ii = 1:nparen p = parent_list(ii); [doMerge, into] = isInTreeArray(garray(1:end-1), p.Name); if doMerge garray{into} = mergeTrees(garray{into}, garray{index}, p.Name); iexclude(ii) = true; end end % Exclude merged parents from recursion parent_list(iexclude) = []; % Recurse each parent up for p = parent_list(:)' [garray, current_node, doMerge] = getSuperclassTree(p, garray, index, current_node); end end function [tree, list, nodenum] = addParents(mcls, tree, nodenum) [list, parent_names] = getParentList(mcls); for ii = 1:numel(list) nodenum = nodenum + 1; [trash,grandparent_names] = getParentList(list(ii)); tree(parent_names{ii}) = makeVal(grandparent_names,nodenum); end end % get meta classes and names of parents function [list,names] = getParentList(mcls) list = mcls.SuperclassList; if isempty(list) list = []; names = mcls.Name; return end if nargout == 2 names = arrayfun(@(x) x.Name,list,'un',0); end end % merge tree into parent containing the root class of interest function main = mergeTrees(main, subtree, mergeat) num_children = subtree.Count - 1; shift = getNode(main, mergeat); for k = main.keys val = main(k{1}); if val.Node > shift val.Node = val.Node + num_children; main(k{1}) = val; end end nodenum = getNode(subtree, mergeat); for k = subtree.keys val = subtree(k{1}); if val.Node < nodenum val.Node = val.Node + shift; main(k{1}) = val; end end end function node = getNode(g, classname) val = g(classname); node = val.Node; end % checks if class is already part of any tree function [bool,into] = isInTreeArray(array,classname) numtrees = numel(array); bool = false; into = 0; for t = 1:numtrees bool = bool | array{t}.isKey(classname); if bool into = t; return end end end % initialize data structure that builds parent relationships function array = addNewTree(array, class, parents) if nargin < 3 [trash, parents] = getParentList(class); array = addNewTree(array, class, parents); else array = [array, {containers.Map(class.Name, makeVal(parents,1))}]; end end function val = makeVal(parents, nodenum) if ischar(parents) parents = {parents}; end val = struct('Parent',{parents},'Node',nodenum); end % create list with from-to nodes for graph() input function tb = getFromToNodes(g) keys = g.keys; n = numel(keys); c = 0; [from,to] = deal(zeros(n,1)); names = cell(n,1); for k = keys value = g(k{1}); for p = value.Parent(:)' c = c+1; try to(c) = getNode(g,p{1}); catch to(c) = value.Node; end from(c) = value.Node; names{c} = k{1}; end end tb = table(names, from, to); tb = unique(tb,'rows'); tb = sortrows(tb,'from'); % remove duplicates [un,trash,subs] = unique(tb.names); irepeated = accumarray(subs,1) > 1; irepeated = ismember(tb.names,un(irepeated)); icircular = tb.from == tb.to; tb(irepeated & icircular,:) = []; % TODO: avoid re-mapping node [un,trash,from_new] = unique(tb.from); [trash,pos] = ismember(tb.to, tb.from); to_new = from_new(pos); tb.from = from_new; tb.to = to_new; end function rclass = validateRootclass(rclass) if ischar(rclass) rclass = meta.class.fromName(rclass); elseif isobject(rclass) && ~isa(rclass, 'meta.class') rclass = meta.class.fromName(class(rclass)); end end function rpath = validateRootpath(rpath, rclass) if isnumeric(rpath) && rpath <= 0 && mod(rpath,1) == 0 s = what(rclass.Name); for ii = 1:abs(rpath) s.path = fileparts(s.path); end rpath = s.path; elseif ~ischar(rpath) error('getSubclasses:unrecognizedPath','Unrecognized path.') end end
github
SwanLab/Swan-master
genop.m
.m
Swan-master/Other/Utilities/Multiprod_2009/Testing/genop.m
3,837
utf_8
2c087f1f1c6d8843c6f5198716d04526
function z = genop(op,x,y) %GENOP Generalized array operations. % GENOP(OP, X, Y) applies the function OP to the arguments X and Y where % singleton dimensions of X and Y have been expanded so that X and Y are % the same size, but this is done without actually copying any data. % % OP must be a function handle to a function that computes an % element-by-element function of its two arguments. % % X and Y can be any numeric arrays where non-singleton dimensions in one % must correspond to the same or unity size in the other. In other % words, singleton dimensions in one can be expanded to the size of % the other, otherwise the size of the dimensions must match. % % For example, to subtract the mean from each column, you could use % % X2 = X - repmat(mean(X),size(X,1),1); % % or, using GENOP, % % X2 = genop(@minus,X,mean(X)); % % where the single row of mean(x) has been logically expanded to match % the number of rows in X, but without actually copying any data. % % GENOP(OP) returns a function handle that can be used like above: % % f = genop(@minus); % X2 = f(X,mean(X)); % written by Douglas M. Schwarz % email: dmschwarz (at) urgrad (dot) rochester (dot) edu % 13 March 2006 % This function was inspired by an idea by Urs Schwarz (no relation) and % the idea for returning a function handle was shamelessly stolen from % Duane Hanselman. % Check inputs. if ~(nargin == 1 || nargin == 3) error('genop:zeroInputs','1 or 3 arguments required.') end if ~isa(op,'function_handle') error('genop:incorrectOperator','Operator must be a function handle.') end if nargin == 1 z = @(x,y) genop(op,x,y); return end % Compute sizes of x and y, possibly extended with ones so they match % in length. nd = max(ndims(x),ndims(y)); sx = size(x); sx(end+1:nd) = 1; sy = size(y); sy(end+1:nd) = 1; dz = sx ~= sy; dims = find(dz); num_dims = length(dims); % Eliminate some simple cases. if num_dims == 0 || numel(x) == 1 || numel(y) == 1 z = op(x,y); return end % Check for dimensional compatibility of inputs, compute size and class of % output array and allocate it. if ~(all(sx(dz) == 1 | sy(dz) == 1)) error('genop:argSizeError','Argument dimensions are not compatible.') end sz = max([sx;sy]); z1 = op(x(1),y(1)); if islogical(z1) z = repmat(logical(0),sz); else z = zeros(sz,class(z1)); end % The most efficient way to compute the result seems to require that we % loop through the unmatching dimensions (those where dz = 1), performing % the operation and assigning to the appropriately indexed output. Since % we don't know in advance which or how many dimensions don't match we have % to create the code as a string and then eval it. To see how this works, % uncomment the disp statement below to display the code before it is % evaluated. This could all be done with fixed code using subsref and % subsasgn, but that way seems to be much slower. % Compute code strings representing the subscripts of x, y and z. xsub = subgen(sy ~= sz); ysub = subgen(sx ~= sz); zsub = subgen(dz); % Generate the code. indent = 2; % spaces per indent level code_cells = cell(1,2*num_dims + 1); for i = 1:num_dims code_cells{i} = sprintf('%*sfor i%d = 1:sz(%d)\n',indent*(i-1),'',... dims([i i])); code_cells{end-i+1} = sprintf('%*send\n',indent*(i-1),''); end code_cells{num_dims+1} = sprintf('%*sz(%s) = op(x(%s),y(%s));\n',... indent*num_dims,'',zsub,xsub,ysub); code = [code_cells{:}]; % Evaluate the code. % disp(code) eval(code) function sub = subgen(select_flag) elements = {':,','i%d,'}; selected_elements = elements(select_flag + 1); format_str = [selected_elements{:}]; sub = sprintf(format_str(1:end-1),find(select_flag));
github
SwanLab/Swan-master
arraylab133.m
.m
Swan-master/Other/Utilities/Multiprod_2009/Testing/arraylab133.m
2,056
utf_8
46c91102f1666d2e8a3f0accd7d809ed
function c = arraylab133(a,b,d1,d2) % Several adjustments to ARRAYLAB13: % 1) Adjustment used in ARRAYLAB131 was not used here. % 2) Nested statement used in ARRAYLAB132 was used here. % 3) PERMUTE in subfunction MBYV was substituted with RESHAPE % (faster by one order of magnitude!). ndimsA = ndims(a); % NOTE - Since trailing singletons are removed, ndimsB = ndims(b); % not always NDIMSB = NDIMSA NsA = d2 - ndimsA; % Number of added trailing singletons NsB = d2 - ndimsB; sizA = [size(a) ones(1,NsA)]; sizB = [size(b) ones(1,NsB)]; p = sizA(d1); r = sizB(d1); s = sizB(d2); % Initializing C sizC = sizA; sizC(d2) = s; c = zeros(sizC); % Vectorized indices for B and C Nd = length(sizB); Bindices = cell(1,Nd); % preallocating (cell array) for d = 1 : Nd Bindices{d} = 1:sizB(d); end B2size = sizB; B2size([d1 d2]) = [1 r]; B2indices = Bindices; % B2 will be cloned P times along its singleton dimension D1 (see MBYV). B2indices([d1 d2]) = [{ones(1, p)} Bindices(d1)]; % "Cloned" index if sizB(d2) == 1 % PxQ IN A - Rx1 IN B % A * B c = mbyv(a, b, B2indices,B2size,d1,d2,p); else % PxQ IN A - RxS IN B Cindices = Bindices; Cindices{d1} = 1:p; % Building C for Ncol = 1:s Bindices{d2} = Ncol; Cindices{d2} = Ncol; c(Cindices{:}) = mbyv(a, b(Bindices{:}), B2indices,B2size,d1,d2,p); end end function c = mbyv(a, b2, indices, newsize, d1, d2, p) % This is an adjustment to a subfunction used within MULTIPROD 1.3 % 1 - Transposing: Qx1 matrices in B become 1xQ matrices b2 = reshape(b2, newsize); % 3 - Performing dot products along dimension DIM+1 % % NOTE: b(indices{:}) has same size as A % % NOTE: This nested statement is much faster than two separate ones. c = sum(a .* b2(indices{:}), d2);
github
SwanLab/Swan-master
timing_MX.m
.m
Swan-master/Other/Utilities/Multiprod_2009/Testing/timing_MX.m
1,472
utf_8
7db26cc2c4954f1026e93f2d0c44139a
function timing_MX % TIMING_MX Speed of MX as performed by MULTIPROD and by a nested loop. % TIMING_MX compares the speed of matrix expansion as performed by % MULTIPROD and an equivalent nested loop. The results are shown in the % manual (fig. 2). % Notice that MULTIPROD enables array expansion which generalizes matrix % expansion to arrays of any size, while the loop tested in this % function works only for this specific case, and would be much slower % if it were generalized to N-D arrays. % Checking whether needed software exists message = sysrequirements_for_testing('timeit'); if message disp ' ', error('testing_memory_usage:Missing_subfuncs', message) end % Matrix expansion example (fig. 2) disp ' ' disp 'Timing matrix expansion (see MULTIPROD manual, figure 2)' disp ' ' a = rand(2, 5); b = rand(5, 3, 1000, 10); fprintf ('Size of A: %0.0fx%0.0f\n', size(a)) fprintf ('Size of B: (%0.0fx%0.0f)x%0.0fx%0.0f\n', size(b)) disp ' ', disp 'Please wait...' disp ' ' f1 = @() loop(a,b); f2 = @() multiprod(a,b); t1 = timeit(f1)*1000; fprintf('LOOP(A, B): %10.4f milliseconds\n', t1) t2 = timeit(f2)*1000; fprintf('MULTIPROD(A, B): %10.4f milliseconds\n', t2) disp ' ' fprintf('MULTIPROD performed matrix expansion %6.0f times faster than a plain loop\n', t1/t2) disp ' ' function C = loop(A,B) for i = 1:1000 for j = 1:10 C(:,:,i,j) = A * B(:,:,i,j); end end
github
SwanLab/Swan-master
timing_matlab_commands.m
.m
Swan-master/Other/Utilities/Multiprod_2009/Testing/timing_matlab_commands.m
7,975
utf_8
5384e23295d7b37d3318825a1d5c3dfe
function timing_matlab_commands % TIMING_MATLAB_COMMANDS Testing for speed different MATLAB commands. % % Main conclusion: RESHAPE and * (i.e. MTIMES) are very quick! % Paolo de Leva % University of Rome, Foro Italico, Rome, Italy % 2008 Dec 24 clear all % Checking whether needed software exists if ~exist('bsxfun', 'builtin') message = sysrequirements_for_testing('bsxmex', 'timeit'); else message = sysrequirements_for_testing('timeit'); end if message disp ' ', error('timing_matlab_commands:Missing_subfuncs', message) end disp ' ' disp '---------------------------------- Experiment 1 ----------------------------------' N = 10000; P = 3; Q = 3; R = 1; timing(N,P,Q,R); disp '---------------------------------- Experiment 2 ----------------------------------' N = 1000; P = 3; Q = 30; R = 1; timing(N,P,Q,R); disp '---------------------------------- Experiment 3 ----------------------------------' N = 1000; P = 9; Q = 10; R = 3; timing(N,P,Q,R); disp '---------------------------------- Experiment 4 ----------------------------------' N = 100; P = 9; Q = 100; R = 3; timing(N,P,Q,R); disp '---------------------------------- Experiment 5 ----------------------------------' disp ' ' timing2(4, 10000); timing2(200, 200); timing2(10000, 4); disp '---------------------------- Experiment 6 ----------------------------' disp ' ' a = rand(4096, 4096); fprintf ('Size of A: %0.0f x %0.0f\n', size(a)) disp ' ' disp ' SUM(A,1) SUM(A,2)' f1 = @() sum(a, 1); f2 = @() sum(a, 2); disp ([timeit(f1), timeit(f2)]) clear all b = rand(256, 256, 256); fprintf ('Size of B: %0.0f x %0.0f x %0.0f\n', size(b)) disp ' ' disp ' SUM(B,1) SUM(B,2) SUM(B,3)' f1 = @() sum(b, 1); f2 = @() sum(b, 2); f3 = @() sum(b, 3); disp ([timeit(f1), timeit(f2), timeit(f3)]) disp '---------------------------- Experiment 7 ----------------------------' disp ' ' a = rand(101,102,103); fprintf ('Size of A: %0.0f x %0.0f x %0.0f\n', size(a)) disp ' ' disp 'Moving last dimension to first dimension:' disp 'PERMUTE(A,[3 2 1]) PERMUTE(A,[3 1 2]) SHIFTDIM(A,2)' disp '(SWAPPING) (SHIFTING) (SHIFTING)' f1 = @() permute(a, [3 2 1]); f2 = @() permute(a, [3 1 2]); f3 = @() shiftdim(a, 2); fprintf(1, '%8.2g ', [timeit(f1), timeit(f2), timeit(f3)]) disp ' ', disp ' ' a2 = f1(); s = size(a2); a2 = f2(); s(2,:) = size(a2); a2 = f3(); s(3,:) = size(a2); disp (s) disp 'Moving first dimension to last dimension:' disp 'PERMUTE(A,[3 2 1]) PERMUTE(A,[2 3 1]) SHIFTDIM(A,1)' disp '(SWAPPING) (SHIFTING) (SHIFTING)' f1 = @() permute(a, [3 2 1]); f2 = @() permute(a, [2 3 1]); f3 = @() shiftdim(a, 1); fprintf(1, '%8.2g ', [timeit(f1), timeit(f2), timeit(f3)]) disp ' ', disp ' ' a2 = f1(); s = size(a2); a2 = f2(); s(2,:) = size(a2); a2 = f3(); s(3,:) = size(a2); disp (s) disp ' ' a = rand(21,22,23,24,25); fprintf ('Size of A: %0.0f x %0.0f x %0.0f x %0.0f x %0.0f\n', size(a)) disp ' ' disp 'Moving 4th dimension to 1st dimension:' disp 'PERMUTE(A,[4 2 3 1 5]) PERMUTE(A,[4 1 2 3 5]) PERMUTE(A,[4 5 1 2 3])' disp '(SWAPPING) (PARTIAL SHIFTING) (SHIFTING)' f1 = @() permute(a, [4 2 3 1 5]); f2 = @() permute(a, [4 1 2 3 5]); f3 = @() permute(a, [4 5 1 2 3]); fprintf(1, '%8.2g ', [timeit(f1), timeit(f2), timeit(f3)]) disp ' ', disp ' ' a2 = f1(); s = size(a2); a2 = f2(); s(2,:) = size(a2); a2 = f3(); s(3,:) = size(a2); disp (s) disp 'Moving 2nd dimension to 5th dimension:' disp 'PERMUTE(A,[1 5 3 4 2]) PERMUTE(A,[1 3 4 5 2]) PERMUTE(A,[3 4 5 1 2])' disp '(SWAPPING) (PARTIAL SHIFTING) (SHIFTING)' f1 = @() permute(a, [1 5 3 4 2]); f2 = @() permute(a, [1 3 4 5 2]); f3 = @() permute(a, [3 4 5 1 2]); fprintf(1, '%8.2g ', [timeit(f1), timeit(f2), timeit(f3)]) disp ' ', disp ' ' a2 = f1(); s = size(a2); a2 = f2(); s(2,:) = size(a2); a2 = f3(); s(3,:) = size(a2); disp (s) disp '---------------------------- Experiment 8 ----------------------------' disp ' ' a =rand(101,102,103); order = [1 2 3]; shape = [101,102,103]; f1 = @() perm(a,order); f2 = @() ifpermute(a,order); f3 = @() ifpermute2(a,order); f4 = @() resh(a,shape); f5 = @() ifreshape(a,shape); f6 = @() ifreshape2(a,shape); disp 'COMPARING STATEMENTS THAT DO NOTHING!' disp ' ' fprintf ('Size of A: %0.0f x %0.0f x %0.0f\n', size(a)) disp ' ' disp 'ORDER = [1 2 3] % (keeping same order)' disp 'SHAPE = [101,102,103] % (keeping same shape)' disp ' ' fprintf (1,'PERMUTE(A,ORDER) .......................................... %0.4g\n', timeit(f1)) fprintf (1,'IF ~ISEQUAL(ORDER,1:LENGTH(ORDER)), A=PERMUTE(A,ORDER); END %0.4g\n', timeit(f2)) fprintf (1,'IF ~ISEQUAL(ORDER,1:3), A=PERMUTE(A,ORDER); END %0.4g\n', timeit(f3)) disp ' ' fprintf (1,'RESHAPE(A,SHAPE) .......................................... %0.4g\n', timeit(f4)) fprintf (1,'IF ~ISEQUAL(SHAPE,SIZE(A)), A=RESHAPE(A,SHAPE); END ....... %0.4g\n', timeit(f5)) fprintf (1,'IF ~ISEQUAL(SHAPE,SHAPE), A=RESHAPE(A,SHAPE); END ....... %0.4g\n', timeit(f5)) disp ' ' function a=perm(a, order) a=permute(a, order); function a=resh(a,shape) a=reshape(a,shape); function a=ifpermute(a, order) if ~isequal(order, 1:length(order)), a=permute(a,order); end function a=ifreshape(a, shape) if ~isequal(shape, size(a)), a=reshape(a,shape); end function a=ifpermute2(a, order) if ~isequal(order, 1:3), a=permute(a,order); end function a=ifreshape2(a, shape) if ~isequal(shape, shape), a=reshape(a,shape); end function timing(N,P,Q,R) a0 = rand(1, P, Q); b0 = rand(1, Q, R); a = a0(ones(1,N),:,:); % Cloning along first dimension b = b0(ones(1,N),:,:); % Cloning along first dimension [n1 p q1] = size(a); % reads third dim even if it is 1. [n2 q2 r] = size(b); % reads third dim even if it is 1. disp ' ' disp 'Array Size Size Number of elements' fprintf (1, 'A Nx(PxQ) %0.0f x (%0.0f x %0.0f) %8.0f\n', [n1 p q1 numel(a)]) fprintf (1, 'B Nx(QxR) %0.0f x (%0.0f x %0.0f) %8.0f\n', [n2 q2 r numel(b)]) f1 = @() permute(a, [2 3 1]); f2 = @() permute(a, [1 3 2]); f3 = @() permute(a, [2 1 3]); f4 = @() permute(a, [1 2 3]); f5 = @() permute(b, [2 3 1]); f6 = @() permute(b, [1 3 2]); f7 = @() permute(b, [2 1 3]); f8 = @() permute(b, [1 2 3]); disp ' ' disp ' PERMUTE(A,[2 3 1]) PERMUTE(A,[1 3 2]) PERMUTE(A,[2 1 3]) PERMUTE(A,[1 2 3])' fprintf(1, '%20.5f', [timeit(f1), timeit(f2), timeit(f3), timeit(f4)]) disp ' ' disp ' PERMUTE(B,[2 3 1]) PERMUTE(B,[1 3 2]) PERMUTE(B,[2 1 3]) PERMUTE(B,[1 2 3])' fprintf(1, '%20.5f', [timeit(f5), timeit(f6), timeit(f7), timeit(f8)]) disp ' ' disp ' ' disp ' RESHAPE(A,[N*P Q]) RESHAPE(B,[N R Q]) RESHAPE(B,[N 1 R Q])' f1 = @() reshape(a, [N*P Q]); f2 = @() reshape(b, [N R Q]); f3 = @() reshape(b, [N 1 R Q]); fprintf(1, '%20.5f', [timeit(f1), timeit(f2), timeit(f3)]) disp ' ' f1 = @() a .* a; f2 = @() bsxfun(@times, a, a); f3 = @() b .* b; f4 = @() bsxfun(@times, b, b); disp ' ' disp ' A .* A BSXFUN(@TIMES,A,A)' fprintf(1, '%20.5f%20.5f\n', [timeit(f1), timeit(f2)]) disp ' B .* B BSXFUN(@TIMES,B,B)' fprintf(1, '%20.5f%20.5f\n', [timeit(f3), timeit(f4)]) if R==1 disp ' ' disp ' NOTE: If R=1 then RESHAPE(B,[N R Q]) is equivalent to' disp ' PERMUTE(B,[1 3 2]) but much faster!' disp ' (at least on my system)' end disp ' ' function timing2(P,Q) a = rand(P, Q); b = rand(Q, 1); fprintf ('Size of A: %0.0f x %0.0f\n', size(a)) fprintf ('Size of B: %0.0f x %0.0f\n', size(b)) disp ' ' disp ' A * B TONY''S TRICK BSXFUN' f1 = @() a * b; f2 = @() clone_multiply_sum(a, b', P); f3 = @() sum(bsxfun(@times, a, b'), 2); fprintf(1, '%13.5f', [timeit(f1), timeit(f2), timeit(f3)]) disp ' ' disp ' ' c = f1() - f2(); d = max(c(:)); if d > eps*20 disp 'There is an unexpected output difference:'; disp (d); end function c = clone_multiply_sum(a,b,P) c = sum(a .* b(ones(1,P),:), 2);
github
SwanLab/Swan-master
arraylab13.m
.m
Swan-master/Other/Utilities/Multiprod_2009/Testing/arraylab13.m
1,913
utf_8
942e4a25270936f264b83f4367d9b7fa
function c = arraylab13(a,b,d1,d2) % This is the engine used in MULTIPROD 1.3 for these cases: % PxQ IN A - Rx1 IN B % PxQ IN A - RxS IN B (slowest) ndimsA = ndims(a); % NOTE - Since trailing singletons are removed, ndimsB = ndims(b); % not always NDIMSB = NDIMSA NsA = d2 - ndimsA; % Number of added trailing singletons NsB = d2 - ndimsB; sizA = [size(a) ones(1,NsA)]; sizB = [size(b) ones(1,NsB)]; % Performing products if sizB(d2) == 1 % PxQ IN A - Rx1 IN B % A * B c = mbyv(a, b, d1); else % PxQ IN A - RxS IN B (least efficient) p = sizA(d1); s = sizB(d2); % Initializing C sizC = sizA; sizC(d2) = s; c = zeros(sizC); % Vectorized indices for B and C Nd = length(sizB); Bindices = cell(1,Nd); % preallocating (cell array) for d = 1 : Nd Bindices{d} = 1:sizB(d); end Cindices = Bindices; Cindices{d1} = 1:p; % Building C for Ncol = 1:s Bindices{d2} = Ncol; Cindices{d2} = Ncol; c(Cindices{:}) = mbyv(a, b(Bindices{:}), d1); end end function c = mbyv(a, b, dim) % NOTE: This function is part of MULTIPROD 1.3 % 1 - Transposing: Qx1 matrices in B become 1xQ matrices order = [1:dim-1, dim+1, dim, dim+2:ndims(b)]; b = permute(b, order); % 2 - Cloning B P times along its singleton dimension DIM. % Optimized code for B2 = REPMAT(B, [ONES(1,DIM-1), P]). % INDICES is a cell array containing vectorized indices. P = size(a, dim); siz = size(b); siz = [siz ones(1,dim-length(siz))]; % Ones are added if DIM > NDIMS(B) Nd = length(siz); indices = cell(1,Nd); % preallocating for d = 1 : Nd indices{d} = 1:siz(d); end indices{dim} = ones(1, P); % "Cloned" index for dimension DIM b2 = b(indices{:}); % B2 has same size as A % 3 - Performing dot products along dimension DIM+1 c = sum(a .* b2, dim+1);
github
SwanLab/Swan-master
ExperimentingAcceleratedShapeOpt.m
.m
Swan-master/ImageProcessing/ExperimentingAccelerationForShapeOptimization/ExperimentingAcceleratedShapeOpt.m
1,304
utf_8
c32b58cf71f0c4f321fc2d30bec70b69
function ExperimentingAcceleratedShapeOpt() exp1 = computeStandardCase(); exp2 = computeMomentumCase(); exp3 = computeConstantOne(); nFigures = 5; fh = figure('units', 'pixels'); hold on fh.set('Position',[4000 1500 3000 500]) plotSubFigure(nFigures,1,'Cost',exp1.JV,exp2.JV,exp3.JV) plotSubFigure(nFigures,2,'LineSearch',exp1.tV,exp2.tV,exp3.tV) plotSubFigure(nFigures,3,'Beta',exp1.betaV,exp2.betaV,exp3.betaV) plotSubFigure(nFigures,4,'IncX',exp1.incXvalues,exp2.incXvalues,exp3.incXvalues) end function plotSubFigure(nFigures,nF,name,y1,y2,y3) subplot(1,nFigures,nF) plot(y1,'-+','LineWidth',3); hold on plot(y2,'-+','LineWidth',3); hold on plot(y3,'-+','LineWidth',3); legend('Standard','Momentum','Constant One') title(name) end function solver = computeMomentumCase() s.momentumParams.type = 'CONVEX'; s.maxIter = 100; s.TOL = 1e-12; solver = ShapeOptimizationSolver(s); solver.solve(); end function solver = computeStandardCase() s.momentumParams.type = 'CONSTANT'; s.momentumParams.value = 0; s.maxIter = 100; s.TOL = 1e-12; solver = SimpleShapeOptimizationSolver(s); solver.solve(); end function solver = computeConstantOne() s.momentumParams.type = 'CONSTANT'; s.momentumParams.value = 1; s.maxIter = 100; s.TOL = 1e-12; solver = ShapeOptimizationSolver(s); solver.solve(); end
github
SwanLab/Swan-master
learningConvergence.m
.m
Swan-master/ImageProcessing/Old/learningConvergence.m
2,079
utf_8
eda54498760dd18ec103fc1b2b0bf942
function learningConvergence k = 10; iter = 1:200; lblRate = LowerBoundLipshitzFirstOrder(iter); lbscRate = lowerBoundStronglyConvexFirstOrder(iter,k); sRate = subgradientConvergence(iter); nRate = stronglyConvexNesterovConvergence(iter,k); qRate = quadraticConvergence(iter,1/k); lgRate = LipschitzGradientConvergence(iter); scRate = stronglyConvexGradientConvergence(iter,k); colors = { [0.9290, 0.6940, 0.1250]; [0, 0.4470, 0.7410]; [0.8500, 0.3250, 0.0980]; [0, 0.4470, 0.7410]; [0.8500, 0.3250, 0.0980]; [0.4940, 0.1840, 0.5560]; [0.4660, 0.6740, 0.1880]; [0.3010, 0.7450, 0.9330]}; style = {'-';'--';'--';'-';'-';'-';'-';}; rates = [sRate;lblRate;lbscRate;lgRate;scRate;nRate;qRate]; figure(1) subplot(1,2,1); hold on for i = 1:size(rates,1) plot(iter,rates(i,:),'Color',colors{i},'LineStyle',style{i}); end legend('Subgradient','LowerBound Lipshitz','LowerBound Strongly Convex', 'Lipschitz Diff Gradient','StronglyConvex Diff Gradient','Strongly Convex Diff Nesterov','Quadratic Diff') figure(1) subplot(1,2,2); hold on for i = 1:size(rates,1) h = plot(iter,rates(i,:),'Color',colors{i},'LineStyle',style{i}); set(gca,'yscale','log'); end legend('Subgradient','LowerBound Lipshitz','LowerBound Strongly Convex', 'Lipschitz Diff Gradient','StronglyConvex Diff Gradient','Strongly Convex Diff Nesterov','Quadratic Diff') end function rate = subgradientConvergence(x) rate = 1./sqrt(x); end function rate = LowerBoundLipshitzFirstOrder(x) rate = 1./(x + 1).^2; end function rate = LipschitzGradientConvergence(x) rate = 1./(x + 1); end function rate = stronglyConvexGradientConvergence(x,k) rate = (((k) - 1)/((k)+1)).^(x); end function rate = quadraticConvergence(x,k) rate = k.^(2.^x); end function rate = lowerBoundStronglyConvexFirstOrder(x,k) rate = ((sqrt(k) - 1)/(sqrt(k) + 1)).^(2*x); end function rate = stronglyConvexNesterovConvergence(x,k) rate = ((sqrt(k) - 1)/(sqrt(k)+1)).^(x); end
github
ha-ha-ha-han/NeuromicsCellDetection-master
registerSixPoints.m
.m
NeuromicsCellDetection-master/+neuroReg/registerSixPoints.m
4,847
utf_8
84d89f2c880829628c40d20530726a1d
function M_1 = registerSixPoints(pts_1,pts_2) % This function calculate the M that let the equation % point_set_2 = M^(-1) * point_set_1 best holds. % x and y should be 3-by-6 arrays. % in the neuroReg case, x(2,:) is assumed as zero. % Because it is 1am and this is the 4th day that I work until 1am during the % week :( % % Han M=[]; M_1 = []; %% Match center of the mass pts_2_center = mean(pts_2,2); pts_1_center = mean(pts_1,2); pts_1c = pts_1 - pts_1_center; pts_2c = pts_2 - pts_2_center; % figure(10099);hold off; % scatter3(pts_1c(1,:),pts_1c(2,:),pts_1c(3,:)); % hold on; % scatter3(pts_2c(1,:),pts_2c(2,:),pts_2c(3,:)); % hold off; % xlabel x; % ylabel y; % zlabel z; % axis equal;axis vis3d; %% Get the average surface normal for pts_1 % pts_2 surface normal is [0,1,0] % It is actually a linear regression dist_plane = @(angles)dist2plane(angles,pts_1c); angles = fminsearch(dist_plane,[0;0]); d2 = dist2plane(angles,pts_1c); sn(3,1) = cosd(angles(1)); sn(1,1) = sind(angles(1))*cosd(angles(2)); sn(2,1) = sind(angles(1))*sind(angles(2)); axis1 = cross(sn,[0;1;0]); axis1 = axis1./norm(axis1); axis3 = cross(axis1,sn); RotMat_1 = [axis1';sn';axis3']; pts_1r_step1 = RotMat_1*pts_1c; %% Visualization for testing % scatter3(pts_1r_step1(1,:),pts_1r_step1(2,:),pts_1r_step1(3,:)); % hold on; % plot3([pts_1r_step1(1,1:3),pts_1r_step1(1,1)],[pts_1r_step1(2,1:3),pts_1r_step1(2,1)],[pts_1r_step1(3,1:3),pts_1r_step1(3,1)]); % plot3([pts_1r_step1(1,4:6),pts_1r_step1(1,4)],[pts_1r_step1(2,4:6),pts_1r_step1(2,4)],[pts_1r_step1(3,4:6),pts_1r_step1(3,4)]); % scatter3(pts_2c(1,:),pts_2c(2,:),pts_2c(3,:)); % % hold off; % axis equal;axis vis3d; % xlabel x; % ylabel y; % zlabel z; %% Final rotation dist_rotation = @(angle)distRotation(angle,pts_1r_step1,pts_2c); rotation_angle = fminsearch(dist_rotation,0); RotMat_2 = [cosd(rotation_angle),0,sind(rotation_angle);0,1,0;-sind(rotation_angle),0,cosd(rotation_angle)]; pts_1r_step2 = RotMat_2*pts_1r_step1; pts_1r_step2_center = mean(RotMat_2*RotMat_1*pts_1,2); pts_1r_step2_translate = pts_1r_step2 + pts_2_center; % Note: for a Four-Element Number, the translation is after rotation. M = RotMat_2*RotMat_1; M_1 = M'; pts_2r = M'*pts_2; pts_2r_center = mean(pts_2r,2); M_1 = cat(2,M_1,-pts_2r_center+pts_1_center); pts_2_translate = M_1*cat(1,pts_2,ones(size(pts_2(1,:)))); dist10 = norm(pts_1(:,1:3)-pts_1(:,4:6)); dist20 = norm(pts_2(:,1:3)-pts_2(:,4:6)); dist21 = norm(pts_2_translate(:,1:3)-pts_2_translate(:,4:6)); % fprintf('dist10 = %6.1f, dist20 = %6.1f, dist21 = %6.1f\n',dist10,dist20,dist21); %% Visualization for testing % figure(10099);hold off; % scatter3(pts_1(1,:),pts_1(2,:),pts_1(3,:),'b'); % hold on; % plot3([pts_1(1,1:3),pts_1(1,1)],[pts_1(2,1:3),pts_1(2,1)],[pts_1(3,1:3),pts_1(3,1)],'b'); % plot3([pts_1(1,4:6),pts_1(1,4)],[pts_1(2,4:6),pts_1(2,4)],[pts_1(3,4:6),pts_1(3,4)],'b'); % % Test M % scatter3(pts_2_translate(1,:),pts_2_translate(2,:),pts_2_translate(3,:),'d'); % hold on; % scatter3(pts_2(1,:),pts_2(2,:),pts_2(3,:),'r'); % plot3([pts_2_translate(1,1:3),pts_2_translate(1,1)],[pts_2_translate(2,1:3),pts_2_translate(2,1)],[pts_2_translate(3,1:3),pts_2_translate(3,1)],'r'); % plot3([pts_2_translate(1,4:6),pts_2_translate(1,4)],[pts_2_translate(2,4:6),pts_2_translate(2,4)],[pts_2_translate(3,4:6),pts_2_translate(3,4)],'r'); % % original distance dist0 % dist0 = norm(pts_1(:,1:3)-pts_1(:,4:6)); % % After re-center % distC = norm(pts_1c(:,1:3)-pts_1c(:,4:6)); % %dist1 step1 % dist1_step1 = norm(pts_1r_step1(:,1:3)-pts_1r_step1(:,4:6)); % %dist1 step2 % dist1_step2 = norm(pts_1r_step2_translate(:,1:3)-pts_1r_step2_translate(:,4:6)); % %dist2 % dist2 = norm(pts_2(:,1:3)-pts_2(:,4:6)); % %Title dist1 dist2 difference % diff_dist = dist2 - dist1_step1; % % title(['dist1=',num2str(dist1_step1),' dist2=',num2str(dist2),' diff=',num2str(diff_dist)]); % fprintf([... % 'dist0=%6.1f, distC=%6.1f, dist1_step1=%6.1f,\n',... % 'dist1_step2=%6.1f, dist2=%6.1f\n',... % 'diff_12=%6.1f\n'], ... % dist0,distC,dist1_step1,dist1_step2,dist2,diff_dist); % hold off; % axis equal;axis vis3d; % xlabel x; % ylabel y; % zlabel z; % End of test %% Do the point cloud registration % ............... %% Use this matrix to test all the data set. record the best 20 matches %% Visualize the match %% Fix coplanar and distance test!!!! end function dist = dist2plane(angles,pts) % pts should be 3-by-n % sn is 3-by-1 sn(3) = cosd(angles(1)); sn(1) = sind(angles(1))*cosd(angles(2)); sn(2) = sind(angles(1))*sind(angles(2)); x = pts(1,:); y = pts(2,:); z = pts(3,:); t = x*sn(1)+y*sn(2)+z*sn(3); dist = (sum(t.^2)).^0.5/6; end function dist = distRotation(angle,pts_1,pts_2) RotMat = [cosd(angle),0,sind(angle);0,1,0;-sind(angle),0,cosd(angle)]; pts_1r = RotMat*pts_1; diff_pts = pts_1r - pts_2; dist = sum(diff_pts(:).^2)^0.5/6; end
github
ha-ha-ha-han/NeuromicsCellDetection-master
cutVolume.m
.m
NeuromicsCellDetection-master/+neuroReg/cutVolume.m
4,191
utf_8
c21ab95b4df9ef6cce89c058b2ca584b
function [data_out,b_plane,b_list_volume] = cutVolume(data,cut_grid,M,d) % cutVolume cut a slice from the data. % data_out.x, data_out.y, data_out.value is the output slice. % b_list is the boundary polygon (5-by-2) in the plane coordination % b_list1 is the boundary polygon (5-by-3) in the volume coordination % The slice is specified by the initial grid (cut_grid.x,cut_grid.y) which % is transformed by M. % M is the tranform from slice coordination to volume coordination. % The initial plane is assumed to be perpendicular to y axis. if nargin==3 % Integration disenable %% Rotate slice % Get the size of the targeting image (it will be cropped afterwards) nx = length(cut_grid.x); ny = length(cut_grid.y); % Create the grid [xx0,zz0] = ndgrid(cut_grid.x,cut_grid.y); yy0 = zeros(size(xx0)); pts0 = [xx0(:),yy0(:),zz0(:),ones(size(yy0(:)))]'; % Transformation pts1 = M*pts0; xx1 = pts1(1,:); yy1 = pts1(2,:); zz1 = pts1(3,:); % Interp and get the data data_out = cut_grid; v = interp3(data.y,data.x,data.z,data.value,yy1,xx1,zz1); data_out.value = reshape(v,[nx,ny]); % Crop the image [data_out,xb,zb] = cropNaN(data_out); xb_list = [xb(1),xb(1),xb(2),xb(2),xb(1)]; yb_list = [0,0,0,0,0]; zb_list = [zb(1),zb(2),zb(2),zb(1),zb(1)]; b_plane = [xb_list;zb_list]; b_list_volume = M * [xb_list;yb_list;zb_list;ones(size(xb_list))]; elseif nargin>=4 % Integration enable %% Gather information stepX = mean(diff(data.x)); stepSlice = stepX; num_slice = 2*round(d/2/stepSlice)+1; offset = (1:num_slice)-round(d/2/stepSlice)-1; offset = offset*stepSlice; % plus and minus d/2 nx = length(cut_grid.x); ny = length(cut_grid.y); %% Rotate slice % Get the size of the targeting image (it will be cropped afterwards) % Create the grid [xx0,zz0] = ndgrid(cut_grid.x,cut_grid.y); yy0 = zeros(size(xx0)); pts0 = [xx0(:),yy0(:),zz0(:),ones(size(yy0(:)))]'; % Transformation pts1 = M*pts0; n = M*[0;1;0;0]; data_out = cut_grid; % Interp and get the data v_sum = zeros(nx,ny); pts1_rep = repmat(pts1,[1,1,num_slice]); offset = reshape(offset,[1,1,num_slice]); n1 = reshape(n,[3,1,1]); pt_offset = offset.*n1; pts2 = pts1_rep + pt_offset; pts2 = reshape(pts2,[3,nx*ny*num_slice]); v = interp3(data.y,data.x,data.z,data.value,pts2(2,:),pts2(1,:),pts2(3,:)); % I like vectorization... v_mat = reshape(v,[nx,ny,num_slice]); % nf = squeeze(isnan(v_mat(:,:,round(d/2/stepSlice)+1))); % not an NaN % nf = repmat(nf,[1,1,num_slice]); for i = 1:num_slice v_mat_this = v_mat(:,:,i); nf = isnan(v_mat_this); % nf: is NaN v_mat_this = v_mat_this - mean(v_mat_this(~nf)); if i~=round(d/2/stepSlice)+1 % Middle slice is the mask with nan v_mat_this(nf)=0; end v_mat(:,:,i) = v_mat_this; end % for i = 1:num_slice % pt_offset = offset(i)*n; % pts2 = pts1 + pt_offset; % v = interp3(data.y,data.x,data.z,data.value,pts2(2,:),pts2(1,:),pts2(3,:)); % v_mat = reshape(v,[nx,ny]); % nf = isnan(v_mat); % nf: is NaN % v_mat = v_mat - mean(v_mat(~nf)); % if i~=round(d/2/stepSlice)+1 % % Middle slice is the mask with nan % v_mat(~nf)=0; % end % v_sum = v_sum+v_mat; % end % v_sum = v_sum/num_slice; v_sum = sum(v_mat,3); data_out.value = v_sum; % Crop the image [data_out,xb,zb] = cropNaN(data_out); xb_list = [xb(1),xb(1),xb(2),xb(2),xb(1)]; yb_list = [0,0,0,0,0]; zb_list = [zb(1),zb(2),zb(2),zb(1),zb(1)]; b_plane = [xb_list;zb_list]; b_list_volume = M * [xb_list;yb_list;zb_list;ones(size(xb_list))]; end end function [data_out,xb,zb] = cropNaN(data) v = ~isnan(data.value); vx = sum(v,2); vy = sum(v,1); ix1 = find(vx,1,'first'); ix2 = find(vx,1,'last'); iy1 = find(vy,1,'first'); iy2 = find(vy,1,'last'); data_out.x = data.x(ix1:ix2); data_out.y = data.y(iy1:iy2); data_out.value = data.value(ix1:ix2,iy1:iy2); xb = data.x([ix1,ix2]); zb = data.y([iy1,iy2]); end
github
ha-ha-ha-han/NeuromicsCellDetection-master
rotationCorr3.m
.m
NeuromicsCellDetection-master/+neuroReg/rotationCorr3.m
12,671
utf_8
ae693186f8640431e3d90302a603c363
function TransTable = rotationCorr3(pt_list_slice,pt_list_vol,data_slice,AngleRange,Option,ex_list) % rotationCorr3 returns the transformation parameters and the corresponding % correlation functions. % TransTable = ... % rotationCorr3(pt_list_slice,pt_list_vol,data_slice,AngleRange,Option,ex_list) % The transfermation matrix is from volume to slice. % % ---- OUTPUT ---- % TransTable record the possible transformation parameters and the % coorelation intensity. % n-by-(1+6) table with column names: % Intensity, Angle, Translation % [{intensity},{alpha,beta,gamma},{tx,ty,yz}] % The transformation is from volume to cut. % Corr record the corresponding correlation functions. % 1-by-n % % --- INPUT ---- % pt_list is 3xN array. Coordinations of the cells in 3D volume % data_slice is the *2D* slice (with dataS.x, dataS.y and dataS.value) % AngleRange should be a 3x3 matrix with the form % [Alpha_Start, Alpha_End, Number; Beta_Start, Beta_End, Beta_Number; Gamma...] % alpha: rotation around y-axis % beta: rotation around z-axis % gamma: rotation around x-axis % Convention: % R = Rx*Rz*Ry % Y = R*X % ********** % * OPTION * % ********** % Option is a structure specifying the options used in calculating % correlation function. % Fields not specified will be set as default. % Below is the description of each field: % (I write it with enormous patience because tomorrow morning I will forget % them all) % --------- % For peak record % 'TransTol' >> Translation tolerance to divide two peaks in XCC % 'AngleTol' >> Angle tolerance to divide two peaks in XCC % 'MaxPeakNum' >> Number of peaks in the output table % --------- % For image reconstruction from cell list % 'Integ' >> Integration range of the reconstructed plane. Default: 10 (um) % 'StepD' >> Off-plane translational resolution. Default: 5 (um) % 'StepX' >> In-plane translational resolution. Smaller resolution leads to % better result but also with more computation time. Default: 7 (um) % 'CellRadius' >> The radius for each neuron, used in the render process. % Default: 3 (um) % --------- % For cell detection in the slice data % 'Sigma' >> [sx,sy],Size of the gaussian filter. Default: [8,8] (um) % 'Res0' >> Intensity threshold for the cell. Change with the resolution % of the input dataS. Trial with neuroReg.bwCell2 is recommended. % Default: 0.03 % 'SizeLimit' >> Size limit of the cell. Default: [100,2000] (um2) % --------- % For correlation function calculation % MagicNumber >> I = I - MageicNumber * Mean(I(:)) is calculated before % going to correlation function Default:2 % PeakThreshold >> from 0 to 1. The peaks larger than % PeakThreshold * PeakIntensity will be regarded as a possible match. % Defualt: 0.8 % --------- % By Han Peng, [email protected] % 2017.07.18 % % % ********** % * TEST * % ********** % pt_list = evalin('base','pt_list2'); % data = evalin('base','dataS_resam_gen'); % N = 21; % N: Number of angles % alpha = linspace(-5,5,N); % alpha: rotation around y-axis % beta = linspace(-5,5,N); % beta: rotation around z-axis % gamma = linspace(-5,5,N); % gamma: rotation around x-axis % Integ = 10; % Integ: slice thickness % stepD = 5; % stepD: slice step (recommend: Integ/2) % stepX = 7; % stepX: resolution of the slice % CellRadius = 3; % MagicNumber = 2; % Intensity ratio for cell and background %% Rotation Angles fprintf('neuroReg.rotationCorr3 running...\n') alpha1 = AngleRange(1,1); alpha2 = AngleRange(1,2); n_alpha = AngleRange(1,3); beta1 = AngleRange(2,1); beta2 = AngleRange(2,2); n_beta = AngleRange(2,3); gamma1 = AngleRange(3,1); gamma2 = AngleRange(3,2); n_gamma = AngleRange(3,3); alpha = linspace(alpha1,alpha2,n_alpha); % alpha: rotation around y-axis beta = linspace(beta1,beta2,n_beta); % beta: rotation around z-axis gamma = linspace(gamma1,gamma2,n_gamma); % gamma: rotation around x-axis %% Option % Peak Records Option = neuroReg.setOption(Option); % Check input, set default value. TRANSLATION_TOLERANCE2 = Option.TransTol^2; ANGLE_TOLERANCE2 = Option.AngleTol^2; MAX_PEAK_RECORD_NUM = Option.MaxPeakNum; % For image reconstruction from cell list stepD = Option.StepD; % stepD: slice step (recommend: Integ/2) stepX = Option.StepX; % stepX: resolution of the slice % For cell detection in the slice data option2.Sigma = Option.Sigma; % For cell detection in the slice data option2.SigmaRender = Option.SigmaRender; % For cell detection in the slice data option2.Res0 = Option.Res0; % For cell detection. option2.SizeLimit = Option.SizeLimit; % For cell detection. Cell Size Limit option2.Threshold = Option.Threshold; % For cell detection. Cell Size Limit option2.MedianFilterSize = Option.MedianFilterSize; % For cell detection. Cell Size Limit % For correlation function calculation MagicNumber = Option.MagicNumber; % Intensity ratio for cell and background %% Binarize the slice image data_slice_bw = neuroReg.bwCell2(data_slice,option2,ex_list); data_slice_bw_low = neuroReg.downSample(data_slice_bw, stepX, [], stepX); data_slice_bw_low.value = data_slice_bw_low.value - mean(data_slice_bw_low.value(:))*MagicNumber; figure(100860); cla; subplot(2,1,1) neuroReg.plotData2(data_slice); subplot(2,1,2) neuroReg.plotData2(data_slice_bw_low); title('Binarization and render result from the input slice'); %% Rotation and Calculation of Correlation Function h1 = waitbar(0,'Calculating correlation function... Have a coffee...',... 'Name','Calculating XCC... '); data_corr.x = data_slice_bw_low.x; data_corr.y = data_slice_bw_low.y; % [nx,nz] = size(data_slice_bw_low.value); % corr_max = 0; % para_max = [nan;nan;nan;nan;nan;nan]; N = n_gamma * n_beta * n_alpha; % Record the peak positions % I love tables TransTable = table; TransTable.Intensity = zeros(0); TransTable.Angles = zeros(0,3); TransTable.Translation = zeros(0,3); tic; for i = 1:n_gamma for j = 1:n_beta for k = 1:n_alpha %% Rotate the cells from the volume to slice coordination % x_lim, y_lim and d_lim are the size of the rotated cube %v1 = pt_list_rotated(1,:); % x-direction of the slice %v2 = pt_list_rotated(3,:); % up-down-direction of the slice %v3 = pt_list_rotated(2,:); % normal direction of the slice [pt_list_rotated,~,x_lim,y_lim,d_lim] = neuroReg.rotateCells(pt_list_vol,alpha(k),beta(j),gamma(i)); % x_lim: dim1, y_lim: dim3, d_lim: dim2 pt_list_rotated_now = [pt_list_rotated(1,:);pt_list_rotated(3,:);pt_list_rotated(2,:)]; data_now = neuroReg.renderCell3(x_lim,y_lim,d_lim,stepX,stepD,pt_list_rotated_now,Option); % Get the planes to calculate correlation function x_c(1,1) = mean(x_lim); % center position (x) of the 2d plane x_c(3,1) = mean(y_lim); % center position (z) of the 2d plane %% Calculate Cross correlation by FFT % x-z: in-plane directions. y: normal direction of the plane. Im1 = data_slice_bw_low.value; ImZ = data_now.value; % 3D value_temp = neuroReg.xcorrFFT(Im1,ImZ); %% After the distance loop, record the maxima position % y_c: coordination after transformation (Slice coordination) % x_c: coordiniation before transformation (Volume coordination) % M: the transform from Volume coordinate system to Slice % coordinate sytem. value_temp_bw = value_temp; value_temp_bw(value_temp<0.8*max(value_temp(:))) = 0; CC = bwconncomp(value_temp_bw); PeakNum = CC.NumObjects; Angles = [alpha(k),beta(j),gamma(i)]; for i_pk = 1:PeakNum % Get the Maximum intensity from each object [Intensity,i_pos] = max(value_temp_bw(CC.PixelIdxList{i_pk})); % Get the Maximum position from each object [y_c_temp_x,y_c_temp_z,y_c_temp_d] = ind2sub(CC.ImageSize,CC.PixelIdxList{i_pk}(i_pos)); x_c(2,1) = data_now.z(y_c_temp_d); y_c = [y_c_temp_x;0;y_c_temp_z]; y_c(1) = y_c(1)*stepX+data_slice_bw_low.x(1)-stepX; y_c(3) = y_c(3)*stepX+data_slice_bw_low.y(1)-stepX; % Get the translation vector (after rotation. from volune % to slice) Translation = (-x_c+y_c)'; Angles_diff = TransTable.Angles - Angles; af = (sum(Angles_diff.^2,2)<ANGLE_TOLERANCE2); Translation_diff = TransTable.Translation(af,:) - Translation; tf = (sum(Translation_diff.^2,2) < TRANSLATION_TOLERANCE2); TransTableLength = size(TransTable,1); % Modify the TransTable if sum(tf)==0 % If this peak does not exist, then add it to the table TransTable(TransTableLength+1,:) = {Intensity,Angles,Translation}; else % If this peak already exists, then compare the intensities index_list = 1:TransTableLength; index_tf = index_list(af); index_tf = index_tf(tf); Intensity_diff = Intensity-TransTable.Intensity(index_tf); intensf = (Intensity_diff>0); index_change = index_tf(intensf); % If the intensity is larger, then change it if ~isempty(index_change) TransTable(index_change(1),:) = {Intensity,Angles,Translation}; if length(index_change)>1 % delete duplicated peaks TransTable(index_change(2:end),:) = []; end end end % Peaks.Corr, Peaks.M end % Rank the Peaks with intensity TransTable = sortrows(TransTable,'Intensity','descend'); TransTableLength = size(TransTable,1); if TransTableLength>MAX_PEAK_RECORD_NUM % Only keep the peaks with large intensities. TransTable((MAX_PEAK_RECORD_NUM+1):end,:)=[]; end %% Visualization after each cube-XCC [corr_now_max,ind_max] = max(value_temp(:)); [~,~,y_c_temp_d] = ind2sub(size(value_temp),ind_max); x_c(2,1) = data_now.z(y_c_temp_d); % x_c: center position for the volume for XCC maxima % y_c = [y_c_temp_x;0;y_c_temp_z]; % y_c: center position of the cut for XCC maxima % y_c(1) = y_c(1)*stepX+data_slice_bw_low.x(1)-stepX; % y_c(3) = y_c(3)*stepX+data_slice_bw_low.y(1)-stepX; % t = -x_c+y_c; % if corr_now_max > corr_max % corr_max = corr_now_max; % para_max = [alpha(k);beta(j);gamma(i);t]; % end % M = cat(2,R,t); % Transformation from Volume Coodination to Slice Coodination % Visualization for test data_corr.value(:,:) = value_temp(:,:,y_c_temp_d); data_this_cut = neuroReg.renderCell3(x_lim,y_lim,[x_c(2,1),x_c(2,1)],stepX,stepD,pt_list_rotated_now,Option); % Visualize current result figure(100861); subplot(1,2,1); neuroReg.plotData2(data_this_cut); subplot(1,2,2); neuroReg.plotData2(data_corr); title(['d=',num2str(data_now.z(y_c_temp_d)),' Max\_XCC=',num2str(corr_now_max)]); %% Waitbar i_tot = sub2ind([n_alpha,n_beta,n_gamma],k,j,i); a = toc; waitbar(i_tot/N,h1,[... 'Current angle: ',num2str([alpha(k),beta(j),gamma(i)]),... ' Time remaining: ',datestr(a/i_tot*(N-i_tot)/24/3600,'DD HH:MM:SS')]); end % end of alpha cycle end % end of beta cycle end % end of gamma cycle close(h1); end function vts = getCube ( origin, size ) x=([0 1 1 0 0 0;1 1 0 0 1 1;1 1 0 0 1 1;0 1 1 0 0 0]-0.5)*size(1)+origin(1)+size(1)/2; y=([0 0 1 1 0 0;0 1 1 0 0 0;0 1 1 0 1 1;0 0 1 1 1 1]-0.5)*size(2)+origin(2)+size(2)/2; z=([0 0 0 0 0 1;0 0 0 0 0 1;1 1 1 1 0 1;1 1 1 1 0 1]-0.5)*size(3)+origin(3)+size(3)/2; vts(1,:,:) = x; vts(2,:,:) = y; vts(3,:,:) = z; end function drawCube(vts,c) for i=1:6 hold on plot3(vts(1,:,i),vts(2,:,i),vts(3,:,i),c); hold off end h=patch(vts(1,:,6),vts(2,:,6),vts(3,:,6),'y'); alpha(h,0.3); end
github
ha-ha-ha-han/NeuromicsCellDetection-master
plotTransform.m
.m
NeuromicsCellDetection-master/+neuroReg/plotTransform.m
7,273
utf_8
346f38d7e1f14d32aee85c590a274023
function plotTransform(h,TransTable,DataSets,pt_list_vol,pt_list_slice,Option,ex_list,M_icp_s2v,M_icp_v2s,UseMe) % plotTransform visualize the registration from dataZ to data_slice. % h specifies the Figure handle to plot in. % TransTable is a 1-by-7 table. It can be one row from the output of % rotationCorr3. It records: % Intensity, Angle, Translation % [{intensity},{alpha,beta,gamma},{tx,ty,yz}] % dataZ is the volume data. % data_slice is the particular slice. TransTable = table2array(TransTable); Corr = TransTable(1,1); TransParameters = TransTable(1,2:end); StepX = Option.StepX; MagicNumber = Option.MagicNumber; CellRadius = Option.CellRadius; Integ = Option.Integ; dataZ = DataSets.dataZ; data_slice = DataSets.data_slice; data_slice_bw_low = DataSets.data_slice_bw_low; icp_flag = 0; if nargin == 10 icp_flag = 1; end %% Visualization for transformation if icp_flag==1 % Plot icp result M = M_icp_s2v; % M: slice to volume. Default. M1 = M_icp_v2s; % Volume to Slice else [~,R,x_lim,y_lim,d_lim] = ... neuroReg.rotateCells(pt_list_vol,... TransParameters(1),TransParameters(2),TransParameters(3)); t = TransParameters(4:6)'; M = [R',-R'*t]; % M: slice to volume. Default. M1 = [R,t]; % Volume to Slice end figure(h); clf(h); %% Plot the slice from volume subplot(2,4,3); [data_cut1,b_plane,b_list_volume] = neuroReg.cutVolume(dataZ,data_slice,M,Integ); neuroReg.plotData2(data_cut1); title(['Cut from Volume, Thickness =',num2str(Integ),'um']); %% Plot detected cells figure(h); subplot(2,4,8); xs_full = pt_list_slice(1,:); ys_full = pt_list_slice(2,:); xb = b_plane(1,:); yb = b_plane(2,:); x_lim = [xb(1),xb(3)]; y_lim = [yb(1),yb(2)]; pt_list_slice_now = pt_list_slice(:,inpolygon(xs_full,ys_full,xb,yb)); pt_list_vol_rotated = M1*[pt_list_vol;ones(size(pt_list_vol(1,:)))]; pf = abs(pt_list_vol_rotated(2,:))<Integ; pt_list_vol_now = pt_list_vol_rotated(:,pf); xs = pt_list_slice_now(1,:); ys = pt_list_slice_now(2,:); xv = pt_list_vol_now(1,:); yv = pt_list_vol_now(3,:); dv = pt_list_vol_now(2,:); pt_now_area = ones(1,sum(pf==1)).*exp(-(dv/CellRadius).^2/2); hold on; scatter(xs,ys,72,'k+'); scatter(xv,yv,72*pt_now_area,'ro'); axis equal; xlim([b_plane(1,1),b_plane(1,3)]); ylim([b_plane(2,1),b_plane(2,2)]); hold off; title('Detected Cells. + = Sclice, o = Volume'); %% Plot cut from reconstruction figure(h); subplot(2,4,7); data_cut_r = neuroReg.renderCell2(x_lim,y_lim,Option.StepX,[xv;yv],pt_now_area,Option); nf = isnan(data_cut_r.value); data_cut_r.value = data_cut_r.value - mean(data_cut_r.value(~nf))*Option.MagicNumber; data_cut_r.value(nf) = 0; neuroReg.plotData2(data_cut_r); title('Reconstruction') %% Plot the geometry figure(h); subplot(2,4,1); [xx0,zz0] = ndgrid(data_slice.x,data_slice.y); yy0 = zeros(size(xx0)); surf(xx0,yy0,zz0,double(data_slice.value)); shading interp; axis equal; axis vis3d; hold on; vts = getCube([dataZ.x(1),dataZ.y(1),dataZ.z(1)],... [dataZ.x(end)-dataZ.x(1),dataZ.y(end)-dataZ.y(1),dataZ.z(end)-dataZ.z(1)]); vts1 = M1*[reshape(vts,[3,24]);ones(1,24)]; vts1 = reshape(vts1,[3 4 6]); plot3(b_plane(1,:),zeros(size(b_plane(1,:))),b_plane(2,:),'r'); drawCube(vts1,'r'); hold off; title('Geometry'); %% Plot the slice from the ex-vivo slice figure(h); subplot(2,4,2); x1 = min(b_plane(1,:)); x2 = max(b_plane(1,:)); y1 = min(b_plane(2,:)); y2 = max(b_plane(2,:)); [~,ix1] = min(abs(data_slice.x - x1)); [~,ix2] = min(abs(data_slice.x - x2)); [~,iy1] = min(abs(data_slice.y - y1)); [~,iy2] = min(abs(data_slice.y - y2)); data_slice_now.x = data_slice.x(ix1:ix2); data_slice_now.y = data_slice.y(iy1:iy2); data_slice_now.value = data_slice.value(ix1:ix2,iy1:iy2); neuroReg.plotData2(data_slice_now); title('Slice'); %% Plot the correlation function XCC figure(h); subplot(2,4,5); Option2 = Option; Option2.Res0 = 0.003; % data_1_bw = neuroReg.bwCell2(data_cut,Option2); % data_1_bw.value = data_1_bw.value - MagicNumber * mean(data_1_bw.value(:)); % data_1_bw = neuroReg.downSample(data_1_bw,StepX,[],StepX); data_cut_now = data_cut1; nf = isnan(data_cut_now.value); data_cut_now.value = data_cut_now.value - mean(data_cut_now.value(~nf)); data_cut_now.value(nf) = 0; data_cut_now = neuroReg.downSample(data_cut_now,StepX,[],StepX); % data_slice_bw = neuroReg.bwCell2(data_slice,Option,ex_list); % data_slice_bw_low = neuroReg.downSample(data_2_bw,StepX,[],StepX); data_slice_bw_low.value = data_slice_bw_low.value - MagicNumber * mean(data_slice_bw_low.value(:)); data_corr_now = data_slice_bw_low; data_corr_now.value = filter2(data_cut_now.value,data_slice_bw_low.value); neuroReg.plotData2(data_corr_now); hold on; plot(b_plane(1,:),b_plane(2,:),'r'); hold off; title(['XCC, max: ',num2str(Corr)]); %% Plot XCC from reconstruction figure(h); subplot(2,4,6); data_corr_now_r = data_corr_now; data_corr_now_r.value = filter2(data_cut_r.value,data_slice_bw_low.value); neuroReg.plotData2(data_corr_now_r); hold on; plot(b_plane(1,:),b_plane(2,:),'r'); hold off; title('XCC from reconstruction') %% Overlap plot figure(h); h_temp=subplot(2,4,4); % sigma = StepX/mean(diff(data_cut1.x)); % v_temp1 = data_cut1.value; % v_temp1 = intensity_normalize(v_temp1); % v_temp1 = imgaussfilt(v_temp1,sigma); % v_temp1 = intensity_normalize(v_temp1); % I = zeros([size(v_temp1),3]); % I(:,:,1) = v_temp1; % v_temp2 = data_slice_now.value; % v_temp2 = intensity_normalize(v_temp2); % v_temp2 = imgaussfilt(v_temp2,sigma); % v_temp2 = intensity_normalize(v_temp2); % I(:,:,3) = v_temp2; % I(:,:,2) = intensity_normalize(v_temp1.*v_temp2); % I = flip(I,2); % I = permute(I,[2,1,3]); % imshow(I); % title('Overlap'); sigma = StepX/mean(diff(data_cut1.x)); v_temp1 = data_cut1.value; v_temp1 = intensity_normalize(v_temp1); v_temp1 = imgaussfilt(v_temp1,sigma); v_temp1 = intensity_normalize(v_temp1); v_temp1 = flipud(v_temp1'); v_temp2 = data_slice_now.value; v_temp2 = intensity_normalize(v_temp2); v_temp2 = imgaussfilt(v_temp2,sigma); v_temp2 = intensity_normalize(v_temp2); v_temp2 = flipud(v_temp2'); imshowpair(v_temp1,v_temp2,'falsecolor','Parent',h_temp); title('Overlap'); end function v_out = intensity_normalize(v_in) v_in(isnan(v_in))=0; v_out = v_in - mean(v_in(:)); v_out(v_out<0)=0; v_out = v_out/max(v_out(:)); end function vts = getCube ( origin, size ) x=([0 1 1 0 0 0;1 1 0 0 1 1;1 1 0 0 1 1;0 1 1 0 0 0]-0.5)*size(1)+origin(1)+size(1)/2; y=([0 0 1 1 0 0;0 1 1 0 0 0;0 1 1 0 1 1;0 0 1 1 1 1]-0.5)*size(2)+origin(2)+size(2)/2; z=([0 0 0 0 0 1;0 0 0 0 0 1;1 1 1 1 0 1;1 1 1 1 0 1]-0.5)*size(3)+origin(3)+size(3)/2; vts(1,:,:) = x; vts(2,:,:) = y; vts(3,:,:) = z; end function drawCube(vts,c) for i=1:6 hold on plot3(vts(1,:,i),vts(2,:,i),vts(3,:,i),c); hold off end h=patch(vts(1,:,6),vts(2,:,6),vts(3,:,6),'y'); alpha(h,0.3); end % function [pt_list_rotated,R] = rotateCells(pt_list,alpha,beta,gamma) % % pt_list should be 3-by-n % % alpha: rotation around y-axis % % beta: rotation around z-axis % % gamma: rotation around x-axis % % %% Make rotation matrix % Ry = [cosd(alpha),0,sind(alpha);0,1,0;-sind(alpha),0,cosd(alpha)]; % Rz = [cosd(beta),-sind(beta),0;sind(beta),cosd(beta),0;0,0,1]; % Rx = [1,0,0;0,cosd(gamma),-sind(gamma);0,sind(gamma),cosd(gamma)]; % R = Rx*Rz*Ry; % %% Rotate % pt_list_rotated = R*pt_list; % % end
github
ha-ha-ha-han/NeuromicsCellDetection-master
detectCells2.m
.m
NeuromicsCellDetection-master/+neuroReg/detectCells2.m
4,844
utf_8
11a89cd603ebc1b64185caae30a5f639
function [pt_list,pt_area] = detectCells2(data,Option,ex_list) % detectCells2 detects cells from a slice data. % [data_out,pt_list] = detectCells2(data,Option,ex_list) % INPUT: % data: a slice data with data.x, data.y, data.value (2D only). % For 3D data, use bwCell3. % Option: see neuroReg.setOption % ex_list: points to exclude. Generated in the preprocess stage. 2-by-M % OUTPUT: % pt_list: detected cells. It should be the same with the result from % bwCells2 with the same input. 2-by-N % pt_area: detected cells' area if nargin==2 exclude_flag=0; elseif nargin==3&&isempty(ex_list) exclude_flag=0; elseif nargin==3&&~isempty(ex_list) exclude_flag=1; else error(['Check input.','neuroReg.detectCells2(data,Option)',... ' or neuroReg.detectCells2(data,Option, ex_list)']); end %% Preset options if ~isfield(Option,'Sigma') Option.Sigma = [1 1]*5; end if ~isfield(Option,'Res0') Option.Res0 = 0.03; end if ~isfield(Option,'SizeLimit') Option.SizeLimit = [100,2000]; end if ~isfield(Option,'MedianFilterSize') Option.MedianFilterSize = [15,15]; end if ~isfield(Option,'Threshold') Option.Threshold = 0.5; end %% Get slice stepX = mean(diff(data.x)); stepY = mean(diff(data.y)); Threshold = Option.Threshold; v_thres = max(data.value(:))*Threshold; SizeLimit = Option.SizeLimit/(stepX*stepY); Res0 = Option.Res0; %% Thresholding Median filter data.value(data.value<v_thres)=0; MedianFilterSize = Option.MedianFilterSize; MedianFilterSizePx = ceil(MedianFilterSize./[stepX,stepY]); MedianFilterSizePx = floor(MedianFilterSizePx/2)*2+1; v = data.value / max(data.value(:)); v = medfilt2(v,MedianFilterSizePx); %% Use difference of Gaussian detector sigmaInd = [1 1]; sigmaInd(1) = Option.Sigma(1)/stepY; % in imgaussfilt, sigma(1) is for 2nd dimension sigmaInd(2) = Option.Sigma(1)/stepX; % sigma(2) is for 1st dimension tic; fprintf('Applying difference of gaussian detector...\n'); Ic = imgaussfilt(v,sigmaInd); Is = imgaussfilt(v,sigmaInd*5); res = Ic - Is; im_bw = imbinarize(res,Res0)*1.0; fprintf('Difference of gaussian detector done...\n'); toc tic %% Connectivity detection fprintf('Finalizing result...\n'); CC = bwconncomp(im_bw); stats = regionprops(CC,'Area','Centroid'); pt_list = [nan nan]'; pt_area = []; k=1; if exclude_flag==1 % exclude some false positive ex_list(1,:) = (ex_list(1,:) - data.x(1))/stepX; ex_list(2,:) = (ex_list(2,:) - data.y(1))/stepY; ex_range2 = 25/stepX/stepY; for i = 1:length(stats) if stats(i).Area>SizeLimit(1)&&stats(i).Area<SizeLimit(2) pt_this = stats(i).Centroid'; d_this = ex_list-[pt_this(2);pt_this(1)]; d_this = d_this(1,:).^2 + d_this(2,:).^2; if sum(d_this < ex_range2)==0 % Not near to any exclude list. pt_list(:,k) = pt_this; pt_area(k) = stats(i).Area; k=k+1; end end end else for i = 1:length(stats) if stats(i).Area>SizeLimit(1)&&stats(i).Area<SizeLimit(2) pt_list(:,k) = stats(i).Centroid'; pt_area(k) = stats(i).Area; k=k+1; end end end %% Output pt_area = pt_area*(stepX*stepY); v = pt_list(1,:); pt_list(1,:) = pt_list(2,:); pt_list(2,:) = v; pt_list(1,:) = pt_list(1,:)*stepX + min(data.x) - stepX; pt_list(2,:) = pt_list(2,:)*stepY + min(data.y) - stepY; fprintf('Result done.\n Number of Cells = %d\n',length(pt_area)); toc %% Visualization for testing figure(1065);cla; plotSlice(data); hold on; scatter(pt_list(1,:),pt_list(2,:),64*pt_area(:)./max(pt_area(:)),'r'); title(['detected cells, number = ',num2str(length(pt_list(1,:)))]); hold off; end function plotSlice(data) % plotSlice(data) visualize a 2-D data set pcolor(data.x,data.y,data.value'); axis equal; axis tight; shading flat; end function data_out = downSample(data,stepX,stepY,stepZ) % downSample put data into a new grid if ndims(data.value) == 2 %#ok<ISMAT> % Get range x1 = min(data.x); x2 = max(data.x); y1 = min(data.y); y2 = max(data.y); data_out.x = x1:stepX:x2; data_out.y = y1:stepZ:y2; [yy,xx] = meshgrid(data.y,data.x); [yyq,xxq] = meshgrid(data_out.y,data_out.x); data_out.value = interp2(yy,xx,data.value,yyq,xxq); elseif ndims(data.value) == 3 x1 = min(data.x); x2 = max(data.x); y1 = min(data.y); y2 = max(data.y); z1 = min(data.z); z2 = max(data.z); data_out.x = x1:stepX:x2; data_out.y = y1:stepY:y2; data_out.z = z1:stepZ:z2; [yyy,xxx,zzz] = meshgrid(data.y,data.x,data.z); [yyyq,xxxq,zzzq] = meshgrid(data_out.y,data_out.x,data_out.z); data_out.value = interp3(yyy,xxx,zzz,data.value,yyyq,xxxq,zzzq); end end
github
ha-ha-ha-han/NeuromicsCellDetection-master
detectCells3.m
.m
NeuromicsCellDetection-master/+neuroReg/detectCells3.m
7,994
utf_8
7eba0e222e182ece0386402da4122839
function [pt_list,pt_area] = detectCells3(data,Option) % detectCells3 detects cell positions from a ZStack data. % [pt_list,pt_area] = detectCells3(data,Option) % --------- % OUTPUT: % pt_list: positions of the detected cells (3-by-N array) % pt_area: volume of each detected cells (1-by-N array) % --------- % INPUT % data: data.x, data.y, data.z, data.value (see doc neuroReg) % Option: % Note: pass [] to the function to use default settings. % ----------------------------- % Options and default settings: % Option.Detect3Mode = 'Red'; % >> Specify the detection mode. Can be 'Red' or 'Green' % Option.Sigma = [1 1 1]*4; % >> Size for difference of Gaussian filter. Unit: um % Option.Res0 = 0.0035; % >> Threshold for difference of Gaussian filter % Option.SizeLimit = [100,4500]; % >> Estimization of the cell volume. Unite: um^3 % Option.Sensitivity = 1.3; % >> Used in Green Mode. The larger this number is, the less cells % will be detected. % Option.MedianFilterSize = [7,7,7]; % >> Size for median filter % Option.NeighborSize = [30 30 50]; % >> Neighbor size in adaptive thresholding. Green Mode only. Unit: % um. %% Preset options if ~isfield(Option,'Detect3Mode') % Specify the detection mode Option.Detect3Mode = 'Red'; end if ~isfield(Option,'Sigma') % Size for difference of Gaussian filter. Unit: um Option.Sigma = [1 1 1]*4; end if ~isfield(Option,'Res0') % Threshold for difference of Gaussian filter Option.Res0 = 0.0035; end if ~isfield(Option,'SizeLimit') % Estimization of the cell volume. Unite: um^3 Option.SizeLimit = [100,4500]; end if ~isfield(Option,'Sensitivity') % Used in Green Mode. The larger this number is, the less cells will be % detected. Option.Sensitivity = 1.3; end if ~isfield(Option,'MedianFilterSize') % Size for median filter Option.MedianFilterSize = [7,7,7]; end if ~isfield(Option,'NeighborSize') % Used in Green Mode. Neighbor size in adaptive thresholding. Option.NeighborSize = [50 50 50]; end disp(Option); %% Load data & get slice % data = evalin('base','dataZ'); %% Preprocessing % Use difference of Gaussian detector Res0 = Option.Res0; Sensitivity = Option.Sensitivity; SizeLimit = Option.SizeLimit; Sigma = Option.Sigma; stepX = mean(diff(data.x)); stepY = mean(diff(data.y)); stepZ = mean(diff(data.z)); SizeLimitPx = SizeLimit/stepX/stepY/stepZ; MedianFilterSizePx = round(Option.MedianFilterSize./[stepX,stepY,stepZ]/2)*2+1; v = data.value / max(data.value(:)); %% Green Channel Mode if strcmp(Option.Detect3Mode,'Green') NbSize = round(Option.NeighborSize./[stepX,stepY,stepZ]); % Normalization v = (data.value - min(data.value(:))) / (max(data.value(:))-min(data.value(:))); tic % Local thresholding. Time consuming (around 200s). disp('Local thresholding... May take about 200 seconds.'); v_local_thres = Sensitivity * convn(v,1/(NbSize(1)*NbSize(2)*NbSize(3))*ones(NbSize),'same'); v = v - v_local_thres; % v = medfilt3(v,MedianFilterSizePx); % data1 = data; % data1.value = v; vf = v>0; v(~vf) = 0; data1 = data; data1.value = v; % data3 = data; % data3.value = v_local_thres; v = v./v_local_thres; v = (v - min(v(:)))/(max(v(:))-min(v(:))); % data4 = data; % data4.value = v; assignin('base','data1',data1) % assignin('base','data2',data2) % assignin('base','data3',data3) % assignin('base','data4',data4) disp('Local threshold calculated.'); toc end %% Gaussian % um2vx sigmaInd = [1 1 1]; sigmaInd(2) = Sigma(1)/stepX; % in imgaussfilt, sigmaInd(2) is for 1st dimension sigmaInd(1) = Sigma(2)/stepY; % sigmaInd(1) is for 2nd dimension sigmaInd(3) = Sigma(3)/stepZ; tic fprintf('Applying difference of gaussian detector...\n'); Ic = imgaussfilt3(v,sigmaInd); Is = imgaussfilt3(v,sigmaInd*5); res = Ic - Is; fprintf('Difference of gaussian detector done...\n'); toc % illumination correction % Res = adaptthresh3(res,Sensitivity); % im_bw = single((res-Res)>0); tic fprintf('Finalizing result...\n'); im_bw = single(res>Res0); im_bw = imclearborder(im_bw); CC = bwconncomp(im_bw,26); stats = regionprops(CC,'Area','Centroid','FilledImage','BoundingBox'); pt_list = [nan nan nan]'; pt_area = []; k=1; for i = 1:length(stats) if stats(i).Area>SizeLimitPx(1) if stats(i).Area<SizeLimitPx(2) pt_list(:,k) = stats(i).Centroid'; pt_area(k) = stats(i).Area; k=k+1; else bw = stats(i).FilledImage; [pt_this,pt_area_this] = splitCells(bw,stepX); n = length(pt_area_this); if n>=1 for j = 1:n pt_list(:,k) = pt_this(:,j) + stats(i).BoundingBox(1:3)'; pt_area(k) = pt_area_this(j); k = k+1; end end end end end pt_area = pt_area*(stepX*stepY*stepZ); if strcmp(Option.Detect3Mode,'Green') % If it Green mode, the area will not be accurate. % To fix this, a unified cell volume is assigned. pt_area = ones(size(pt_area))*mean(Option.SizeLimit); end temp = pt_list(1,:); pt_list(1,:) = pt_list(2,:); pt_list(2,:) = temp; pt_list(1,:) = pt_list(1,:)*stepX + min(data.x) - stepX; pt_list(2,:) = pt_list(2,:) * stepY + min(data.y) - stepY; pt_list(3,:) = pt_list(3,:) * stepZ + min(data.z) - stepZ; fprintf('Result done.\n Number of Cells = %d\n',length(pt_area)); toc %% Visualized feedback % ^^^^^^^^^^^^^^^^ TO CONTINUE % Sub plot detected cells. Label axis. Set proper vis angle % Sub plot origin data. % Enable Adjustment. % figure(10086); % subplot(1,3,1); % scatter3(pt_list(1,:),pt_list(2,:),pt_list(3,:)); % title(['detected cells, number = ',num2str(length(pt_list(1,:)))]); % xlabel x; % ylabel y; % zlabel z; % axis equal % axis vis3d % view([0,90]) % subplot(1,3,2); % data_res = data; % data_res.value = squeeze(sum(im_bw,3)); % plotSlice(data_res); % title('binarized data'); % xlabel x; % ylabel y; % subplot(1,3,3); % data_z = data; % data_z.value = squeeze(sum(data.value,3)); % plotSlice(data_z); % title('Original data'); % xlabel x; % ylabel y; assignin('base','data_temp_749',data); neuroReg.PlotSlices('data_temp_749','y',pt_list,pt_area,25); end function [pt,pt_area] = splitCells(bw,step) min_dist = 15/step; D = bwdist(~bw); D = -D; D(~bw) = Inf; L = watershed(D); L(~bw) = 0; stats = regionprops(L,'Area','Centroid'); n = length(stats); SizeLimitPx = 0.8*sum(bw(:))/n; pt_area = []; pt = [nan,nan,nan]'; k=1; for i = 1:length(stats) if stats(i).Area>SizeLimitPx % Leave out small parts pt(:,k) = stats(i).Centroid'; pt_area(k) = stats(i).Area; k = k+1; end end if k==3 % Check the case when one cell is falsely identified as two. d = norm(pt(:,1)-pt(:,2)); if d < min_dist clear pt; clear pt_area; CC = bwconncomp(bw); stats = regionprops(CC,'Area','Centroid'); pt(:,1) = stats(1).Centroid'; pt_area(1) = stats(1).Area; k=2; % Visualization for testing figure(10099),cla, isosurface(bw,0.5), axis equal, title('BW') xlabel x, ylabel y, zlabel z view(3), camlight, lighting gouraud figure(10100),cla isosurface(L==1,0.5) isosurface(L==2,0.5) axis equal title(['Segmented objects, ',num2str(k-1)]) xlabel x, ylabel y, zlabel z view(3), camlight, lighting gouraud % test ended end end % Visualization for testing % figure(10099),cla, isosurface(bw,0.5), axis equal, title('BW') % xlabel x, ylabel y, zlabel z % view(3), camlight, lighting gouraud % figure(10100),cla % isosurface(L==1,0.5) % isosurface(L==2,0.5) % axis equal % title(['Segmented objects, ',num2str(k-1)]) % xlabel x, ylabel y, zlabel z % view(3), camlight, lighting gouraud % test ended end
github
ha-ha-ha-han/NeuromicsCellDetection-master
rotationCorr3_20170727.m
.m
NeuromicsCellDetection-master/+neuroReg/rotationCorr3_20170727.m
14,541
utf_8
f20cc8f00c80e34760d981c40f935455
function PeakTable = rotationCorr3(pt_list,data_slice,AngleRange,Option,ex_list) % rotationCorr3 returns the transformation parameters and the corresponding % correlation functions. % The transfermation matrix is from volume to slice. % OUTPUT: % PeakTable record the possible transformation parameters and the % coorelation intensity. % n-by-(1+6) table with column names: % Intensity, Angle, Translation % [{intensity},{alpha,beta,gamma},{tx,ty,yz}] % The transformation is from volume to cut. % Corr record the corresponding correlation functions. % 1-by-n % INPUT: % pt_list is 3xN array. Coordinations of the cells in 3D volume % data_slice is the *2D* slice (with dataS.x, dataS.y and dataS.value) % AngleRange should be a 3x3 matrix with the form % [Alpha_Start, Alpha_End, Number; Beta_Start, Beta_End, Beta_Number; Gamma...] % alpha: rotation around y-axis % beta: rotation around z-axis % gamma: rotation around x-axis % Convention: % R = Rx*Rz*Ry % Y = R*X % ********** % * OPTION * % ********** % Option is a structure specifying the options used in calculating % correlation function. % Fields not specified will be set as default. % Below is the description of each field: % (I write it with enormous patience because tomorrow morning I will forget % them all) % --------- % For peak record % 'TransTol' >> Translation tolerance to divide two peaks in XCC % 'AngleTol' >> Angle tolerance to divide two peaks in XCC % 'MaxPeakNum' >> Number of peaks in the output table % --------- % For image reconstruction from cell list % 'Integ' >> Integration range of the reconstructed plane. Default: 10 (um) % 'StepD' >> Off-plane translational resolution. Default: 5 (um) % 'StepX' >> In-plane translational resolution. Smaller resolution leads to % better result but also with more computation time. Default: 7 (um) % 'CellRadius' >> The radius for each neuron, used in the render process. % Default: 3 (um) % --------- % For cell detection in the slice data % 'Sigma' >> [sx,sy],Size of the gaussian filter. Default: [8,8] (um) % 'Res0' >> Intensity threshold for the cell. Change with the resolution % of the input dataS. Trial with neuroReg.bwCell2 is recommended. % Default: 0.03 % 'SizeLimit' >> Size limit of the cell. Default: [100,2000] (um2) % --------- % For correlation function calculation % MagicNumber >> I = I - MageicNumber * Mean(I(:)) is calculated before % going to correlation function Default:2 % PeakThreshold >> from 0 to 1. The peaks larger than % PeakThreshold * PeakIntensity will be regarded as a possible match. % Defualt: 0.8 % --------- % By Han Peng, [email protected] % 2017.07.18 % % % ********** % * TEST * % ********** % pt_list = evalin('base','pt_list2'); % data = evalin('base','dataS_resam_gen'); % N = 21; % N: Number of angles % alpha = linspace(-5,5,N); % alpha: rotation around y-axis % beta = linspace(-5,5,N); % beta: rotation around z-axis % gamma = linspace(-5,5,N); % gamma: rotation around x-axis % Integ = 10; % Integ: slice thickness % stepD = 5; % stepD: slice step (recommend: Integ/2) % stepX = 7; % stepX: resolution of the slice % CellRadius = 3; % MagicNumber = 2; % Intensity ratio for cell and background %% Rotation Angles alpha1 = AngleRange(1,1); alpha2 = AngleRange(1,2); n_alpha = AngleRange(1,3); beta1 = AngleRange(2,1); beta2 = AngleRange(2,2); n_beta = AngleRange(2,3); gamma1 = AngleRange(3,1); gamma2 = AngleRange(3,2); n_gamma = AngleRange(3,3); alpha = linspace(alpha1,alpha2,n_alpha); % alpha: rotation around y-axis beta = linspace(beta1,beta2,n_beta); % beta: rotation around z-axis gamma = linspace(gamma1,gamma2,n_gamma); % gamma: rotation around x-axis %% Option % Peak Records Option = neuroReg.setOption(Option); % Check input, set default value. TRANSLATION_TOLERANCE2 = Option.TransTol^2; ANGLE_TOLERANCE2 = Option.AngleTol^2; MAX_PEAK_RECORD_NUM = Option.MaxPeakNum; % For image reconstruction from cell list Integ = Option.Integ; % Integ: slice thickness stepD = Option.StepD; % stepD: slice step (recommend: Integ/2) stepX = Option.StepX; % stepX: resolution of the slice CellRadius = Option.CellRadius; % CellRadius: radius of a typical neuron % For cell detection in the slice data option2.Sigma = Option.Sigma; % For cell detection in the slice data option2.SigmaRender = Option.SigmaRender; % For cell detection in the slice data option2.Res0 = Option.Res0; % For cell detection. option2.SizeLimit = Option.SizeLimit; % For cell detection. Cell Size Limit option2.Threshold = Option.Threshold; % For cell detection. Cell Size Limit option2.MedianFilterSize = Option.MedianFilterSize; % For cell detection. Cell Size Limit % For correlation function calculation MagicNumber = Option.MagicNumber; % Intensity ratio for cell and background %% Binarize the slice image data_slice_bw = neuroReg.bwCell2(data_slice,option2,ex_list); data_slice_bw_low = neuroReg.downSample(data_slice_bw, stepX, [], stepX); data_slice_bw_low.value = data_slice_bw_low.value - mean(data_slice_bw_low.value(:))*MagicNumber; figure(100860); cla; subplot(2,1,1) neuroReg.plotData2(data_slice); subplot(2,1,2) neuroReg.plotData2(data_slice_bw_low); title('Binarization and render result from the input slice'); %% Rotation and Calculation of Correlation Function h1 = waitbar(0,'Calculating correlation function... Have a coffee...',... 'Name','Calculating XCC... '); data_corr.x = data_slice_bw_low.x; data_corr.z = data_slice_bw_low.y; [nx,nz] = size(data_slice_bw_low.value); corr_max = 0; para_max = [nan;nan;nan;nan;nan;nan]; N = n_gamma * n_beta * n_alpha; % Record the peak positions % I love tables PeakTable = table; PeakTable.Intensity = zeros(0); PeakTable.Angles = zeros(0,3); PeakTable.Translation = zeros(0,3); tic; for i = 1:n_gamma for j = 1:n_beta for k = 1:n_alpha %% Rotate the cells from the volume to slice coordination [pt_list_rotated,R] = neuroReg.rotateCells(pt_list,alpha(k),beta(j),gamma(i)); v1 = pt_list_rotated(1,:); % x-direction of the slice v2 = pt_list_rotated(3,:); % up-down-direction of the slice v3 = pt_list_rotated(2,:); % normal direction of the slice % Get the size of the rotated cube x_lim(1) = min(v1); x_lim(2) = max(v1); y_lim(1) = min(v2); y_lim(2) = max(v2); d_lim(1) = min(v3); d_lim(2) = max(v3); % Get the planes to calculate correlation function d_list = d_lim(1):stepD:d_lim(2); x_c(1,1) = mean(x_lim); % center position (x) of the 2d plane x_c(3,1) = mean(y_lim); % center position (z) of the 2d plane value_temp = zeros(nx,nz,length(d_list)); % Preparation for FFT Im1 = data_slice_bw_low.value; Im2 = zeros(size(Im1)); [Lx1,Ly1]=size(Im1); Lx2 = length(x_lim(1):stepX:x_lim(2)); Ly2 = length(y_lim(1):stepX:y_lim(2)); Mx1 = round(Lx1/2); My1 = round(Ly1/2); Mx2 = round(Lx2/2); My2 = round(Ly2/2); x_start = Mx1-Mx2+1; x_end = Mx1-Mx2+Lx2; y_start = My1-My2+1; y_end = My1-My2+Ly2; f1 = fft2(Im1); for m = 1:length(d_list) %% Calculate correlation function in 3D % x-z: in-plane directions. y: normal direction of the plane. % Reconstruct the cell image vd = v3 - d_list(m); selected = (abs(vd)<Integ); px = v1(selected==1); py = v2(selected==1); pt_now_dist = vd(selected==1); pt_now_area = ones(1,sum(selected==1)).*exp(-(pt_now_dist./CellRadius).^2/2); data_now = neuroReg.renderCell2(x_lim,y_lim,stepX,[px;py],pt_now_area,Option); data_now.value = data_now.value - mean(data_now.value(~isnan(data_now.value(:))))*MagicNumber; data_now.value(isnan(data_now.value))=0; % Calculate the correlation function for the m-th plane % value_temp_slice = filter2(data_now.value,data_slice_bw_low.value); Im2_temp = data_now.value; Im2(x_start:x_end,y_start:y_end)=Im2_temp; f2 = fft2(Im2); value_temp_slice = fftshift(ifft2(f1 .* conj(f2))); value_temp(:,:,m) = value_temp_slice; end %% After the distance loop, record the maxima position % THIS PART WILL CHANGE TO RECORD ALL POSSIBLE PEAKS % y_c: coordination after transformation (Slice coordination) % x_c: coordiniation before transformation (Volume coordination) % M: the transform from Volume coordinate system to Slice % coordinate sytem. value_temp_bw = value_temp; % value_temp_bw = imgaussfilt3(value_temp,[10,10,10]); value_temp_bw(value_temp<0.8*max(value_temp(:))) = 0; CC = bwconncomp(value_temp_bw); PeakNum = CC.NumObjects; Angles = [alpha(k),beta(j),gamma(i)]; for i_pk = 1:PeakNum % Get the Maximum intensity from each object [Intensity,i_pos] = max(value_temp_bw(CC.PixelIdxList{i_pk})); % Get the Maximum position from each object [y_c_temp_x,y_c_temp_z,y_c_temp_d] = ind2sub(CC.ImageSize,CC.PixelIdxList{i_pk}(i_pos)); x_c(2,1) = d_list(y_c_temp_d); y_c = [y_c_temp_x;0;y_c_temp_z]; y_c(1) = y_c(1)*stepX+data_slice_bw_low.x(1)-stepX; y_c(3) = y_c(3)*stepX+data_slice_bw_low.y(1)-stepX; % Get the translation vector (after rotation. from volune % to slice) Translation = (-x_c+y_c)'; Angles_diff = PeakTable.Angles - Angles; af = (sum(Angles_diff.^2,2)<ANGLE_TOLERANCE2); Translation_diff = PeakTable.Translation(af,:) - Translation; tf = (sum(Translation_diff.^2,2) < TRANSLATION_TOLERANCE2); PeakTableLength = size(PeakTable,1); % Modify the PeakTable if sum(tf)==0 % If this peak does not exist, then add it to the table PeakTable(PeakTableLength+1,:) = {Intensity,Angles,Translation}; else % If this peak already exists, then compare the intensities index_list = 1:PeakTableLength; index_tf = index_list(af); index_tf = index_tf(tf); Intensity_diff = Intensity-PeakTable.Intensity(index_tf); intensf = (Intensity_diff>0); index_change = index_tf(intensf); % If the intensity is larger, then change it if ~isempty(index_change) PeakTable(index_change(1),:) = {Intensity,Angles,Translation}; if length(index_change)>1 % delete duplicated peaks PeakTable(index_change(2:end),:) = []; end end end % Peaks.Corr, Peaks.M end % Rank the Peaks with intensity PeakTable = sortrows(PeakTable,'Intensity','descend'); PeakTableLength = size(PeakTable,1); if PeakTableLength>MAX_PEAK_RECORD_NUM % Only keep the peaks with large intensities. PeakTable((MAX_PEAK_RECORD_NUM+1):end,:)=[]; end %% [corr_now_max,ind_max] = max(value_temp(:)); [y_c_temp_x,y_c_temp_z,y_c_temp_d] = ind2sub(size(value_temp),ind_max); % y_c_temp(x_dim,z_dim,y_dim) x_c(2,1) = d_list(y_c_temp_d); y_c = [y_c_temp_x;0;y_c_temp_z]; y_c(1) = y_c(1)*stepX+data_slice_bw_low.x(1)-stepX; y_c(3) = y_c(3)*stepX+data_slice_bw_low.y(1)-stepX; t = -x_c+y_c; if corr_now_max > corr_max corr_max = corr_now_max; para_max = [alpha(k);beta(j);gamma(i);t]; end M = cat(2,R,t); % Transformation from Volume Coodination to Slice Coodination % Visualization for test data_corr.value(:,:,i) = value_temp(:,:,y_c_temp_d); vd = v3 - d_list(y_c_temp_d); selected = (abs(vd)<Integ); px = v1(selected==1); py = v2(selected==1); pt_now_dist = vd(selected==1); pt_now_area = ones(1,sum(selected==1)).*exp(-(pt_now_dist./10).^2/2); data_now = neuroReg.renderCell2(x_lim,y_lim,stepX,[px;py],pt_now_area,Option); data_now.value = data_now.value - mean(data_now.value(~isnan(data_now.value(:))))*MagicNumber; data_now.value(isnan(data_now.value))=0; data_now_corr = data_slice_bw_low; data_now_corr.value = filter2(data_now.value,data_slice_bw_low.value); % Visualize current result figure(100861); subplot(1,2,1); neuroReg.plotData2(data_now); subplot(1,2,2); neuroReg.plotData2(data_now_corr); title(['d=',num2str(d_list(y_c_temp_d)),' Max\_XCC=',num2str(corr_now_max)]); %% i_tot = sub2ind([n_alpha,n_beta,n_gamma],k,j,i); a = toc; waitbar(i_tot/N,h1,[... 'Current angle: ',num2str([alpha(k),beta(j),gamma(i)]),... ' Time remaining: ',datestr(a/i_tot*(N-i_tot)/24/3600,'DD HH:MM:SS')]); end end end TransParameters = para_max; Corr = corr_max; close(h1); end function vts = getCube ( origin, size ) x=([0 1 1 0 0 0;1 1 0 0 1 1;1 1 0 0 1 1;0 1 1 0 0 0]-0.5)*size(1)+origin(1)+size(1)/2; y=([0 0 1 1 0 0;0 1 1 0 0 0;0 1 1 0 1 1;0 0 1 1 1 1]-0.5)*size(2)+origin(2)+size(2)/2; z=([0 0 0 0 0 1;0 0 0 0 0 1;1 1 1 1 0 1;1 1 1 1 0 1]-0.5)*size(3)+origin(3)+size(3)/2; vts(1,:,:) = x; vts(2,:,:) = y; vts(3,:,:) = z; end function drawCube(vts,c) for i=1:6 hold on plot3(vts(1,:,i),vts(2,:,i),vts(3,:,i),c); hold off end h=patch(vts(1,:,6),vts(2,:,6),vts(3,:,6),'y'); alpha(h,0.3); end
github
ha-ha-ha-han/NeuromicsCellDetection-master
rotationHist3.m
.m
NeuromicsCellDetection-master/+neuroReg/rotationHist3.m
13,151
utf_8
aadff69f7a896a683b1b400a671d2cda
function PeakTable = rotationHist3(pt_list_slice,pt_list_vol,data_slice,AngleRange,Option,ex_list) % rotationHist3 returns the transformation parameters and the corresponding % correlation functions using histogram method.. % The transfermation matrix is from volume to slice. % OUTPUT: % PeakTable record the possible transformation parameters and the % coorelation intensity. % n-by-(1+6) table with column names: % Intensity, Angle, Translation % [{intensity},{alpha,beta,gamma},{tx,ty,yz}] % The transformation is from volume to cut. % Corr record the corresponding correlation functions. % 1-by-n % INPUT: % pt_list is 3xN array. Coordinations of the cells in 3D volume % data_slice is the *2D* slice (with dataS.x, dataS.y and dataS.value) % AngleRange should be a 3x3 matrix with the form % [Alpha_Start, Alpha_End, Number; Beta_Start, Beta_End, Beta_Number; Gamma...] % alpha: rotation around y-axis % beta: rotation around z-axis % gamma: rotation around x-axis % Convention: % R = Rx*Rz*Ry % Y = R*X % ********** % * OPTION * % ********** % (Option = neuroReg.setOption. See more for Option in setOption.) % Option is a structure specifying the options used in calculating % correlation function. % Fields not specified will be set as default. % Below is the description of each field: % (I write it with enormous patience because tomorrow morning I will forget % them all) % --------- % For peak record % 'TransTol' >> Translation tolerance to divide two peaks in XCC % 'AngleTol' >> Angle tolerance to divide two peaks in XCC % 'MaxPeakNum' >> Number of peaks in the output table % --------- % For image reconstruction from cell list % 'Integ' >> Integration range of the reconstructed plane. Default: 10 (um) % 'StepD' >> Off-plane translational resolution. Default: 5 (um) % 'StepX' >> In-plane translational resolution. Smaller resolution leads to % better result but also with more computation time. Default: 7 (um) % 'CellRadius' >> The radius for each neuron, used in the render process. % Default: 3 (um) % --------- % For cell detection in the slice data % 'Sigma' >> [sx,sy],Size of the gaussian filter. Default: [8,8] (um) % 'Res0' >> Intensity threshold for the cell. Change with the resolution % of the input dataS. Trial with neuroReg.bwCell2 is recommended. % Default: 0.03 % 'SizeLimit' >> Size limit of the cell. Default: [100,2000] (um2) % --------- % For correlation function calculation % MagicNumber >> I = I - MageicNumber * Mean(I(:)) is calculated before % going to correlation function Default:2 % PeakThreshold >> from 0 to 1. The peaks larger than % PeakThreshold * PeakIntensity will be regarded as a possible match. % Defualt: 0.8 % --------- % By Han Peng, [email protected] % 2017.07.18 % % % ********** % * TEST * % ********** % pt_list = evalin('base','pt_list2'); % data = evalin('base','dataS_resam_gen'); % N = 21; % N: Number of angles % alpha = linspace(-5,5,N); % alpha: rotation around y-axis % beta = linspace(-5,5,N); % beta: rotation around z-axis % gamma = linspace(-5,5,N); % gamma: rotation around x-axis % Integ = 10; % Integ: slice thickness % stepD = 5; % stepD: slice step (recommend: Integ/2) % stepX = 7; % stepX: resolution of the slice % CellRadius = 3; % MagicNumber = 2; % Intensity ratio for cell and background fprintf('neuroReg.rotationHist3 running...\n') %% Rotation Angles alpha1 = AngleRange(1,1); alpha2 = AngleRange(1,2); n_alpha = AngleRange(1,3); beta1 = AngleRange(2,1); beta2 = AngleRange(2,2); n_beta = AngleRange(2,3); gamma1 = AngleRange(3,1); gamma2 = AngleRange(3,2); n_gamma = AngleRange(3,3); alpha = linspace(alpha1,alpha2,n_alpha); % alpha: rotation around y-axis beta = linspace(beta1,beta2,n_beta); % beta: rotation around z-axis gamma = linspace(gamma1,gamma2,n_gamma); % gamma: rotation around x-axis %% Option % Peak Records Option = neuroReg.setOption(Option); % Check input, set default value. TRANSLATION_TOLERANCE2 = Option.TransTol^2; ANGLE_TOLERANCE2 = Option.AngleTol^2; MAX_PEAK_RECORD_NUM = Option.MaxPeakNum; % For image reconstruction from cell list stepD = Option.StepD; % stepD: slice step (recommend: Integ/2) stepX = Option.StepX; % stepX: resolution of the slice % For cell detection in the slice data option2.Sigma = Option.Sigma; % For cell detection in the slice data option2.SigmaRender = Option.SigmaRender; % For cell detection in the slice data option2.Res0 = Option.Res0; % For cell detection. option2.SizeLimit = Option.SizeLimit; % For cell detection. Cell Size Limit option2.Threshold = Option.Threshold; % For cell detection. Cell Size Limit option2.MedianFilterSize = Option.MedianFilterSize; % For cell detection. Cell Size Limit % For correlation function calculation MagicNumber = Option.MagicNumber; % Intensity ratio for cell and background %% Binarize the slice image data_slice_bw = neuroReg.bwCell2(data_slice,option2,ex_list); data_slice_bw_low = neuroReg.downSample(data_slice_bw, stepX, [], stepX); data_slice_bw_low.value = data_slice_bw_low.value - mean(data_slice_bw_low.value(:))*MagicNumber; figure(100860); cla; subplot(2,1,1) neuroReg.plotData2(data_slice); subplot(2,1,2) neuroReg.plotData2(data_slice_bw_low); title('Binarization and render result from the input slice'); %% Rotation and Calculation of Correlation Function h1 = waitbar(0,'Calculating correlation function... Have a coffee...',... 'Name','Calculating Hist... '); % [nx,nz] = size(data_slice_bw_low.value); % corr_max = 0; % para_max = [nan;nan;nan;nan;nan;nan]; N = n_gamma * n_beta * n_alpha; % Record the peak positions % I love tables PeakTable = table; PeakTable.Intensity = zeros(0); PeakTable.Angles = zeros(0,3); PeakTable.Translation = zeros(0,3); tic; pt_list_slice3(1,:) = pt_list_slice(1,:); pt_list_slice3(2,:) = pt_list_slice(2,:); pt_list_slice3(3,:) = zeros(size(pt_list_slice(1,:))); for i = 1:n_gamma for j = 1:n_beta for k = 1:n_alpha %% Rotate the cells from the volume to slice coordination % x_lim, y_lim and d_lim are the size of the rotated cube %v1 = pt_list_rotated(1,:); % x-direction of the slice %v2 = pt_list_rotated(3,:); % up-down-direction of the slice %v3 = pt_list_rotated(2,:); % normal direction of the slice [pt_list_rotated,~,x_lim,y_lim,d_lim] = neuroReg.rotateCells(pt_list_vol,alpha(k),beta(j),gamma(i)); x1 = data_slice_bw_low.x(1) - x_lim(2); x2 = data_slice_bw_low.x(end) - x_lim(1); y1 = data_slice_bw_low.y(1) - y_lim(2); y2 = data_slice_bw_low.y(end) - y_lim(1); Grid.x = x1:stepX:x2; Grid.y = y1:stepX:y2; Grid.z = (-d_lim(2)):stepD:(-d_lim(1)); % x_lim: dim1, y_lim: dim3, d_lim: dim2 pt_list_rotated_now = [pt_list_rotated(1,:);pt_list_rotated(3,:);pt_list_rotated(2,:)]; % data_now = neuroReg.renderCell3(x_lim,y_lim,d_lim,stepX,stepD,pt_list_rotated_now,Option); % Get the planes to calculate correlation function x_c(1,1) = mean(x_lim); % center position (x) of the 2d plane x_c(3,1) = mean(y_lim); % center position (z) of the 2d plane %% Calculate Cross correlation by FFT % x-z: in-plane directions. y: normal direction of the plane. %Im1 = data_slice_bw_low.value; %ImZ = data_now.value; % 3D value_temp = neuroReg.posHist3(pt_list_slice3,pt_list_rotated_now,Grid,Option); %% After the distance loop, record the maxima position % y_c: coordination after transformation (Slice coordination) % x_c: coordiniation before transformation (Volume coordination) % M: the transform from Volume coordinate system to Slice % coordinate sytem. value_temp_bw = value_temp; value_temp_bw(value_temp<0.8*max(value_temp(:))) = 0; CC = bwconncomp(value_temp_bw); PeakNum = CC.NumObjects; Angles = [alpha(k),beta(j),gamma(i)]; for i_pk = 1:PeakNum % Get the Maximum intensity from each object [Intensity,i_pos] = max(value_temp_bw(CC.PixelIdxList{i_pk})); % Get the Maximum position from each object [y_c_temp_x,y_c_temp_z,y_c_temp_d] = ind2sub(CC.ImageSize,CC.PixelIdxList{i_pk}(i_pos)); x_c(2,1) = -Grid.z(y_c_temp_d); y_c = [y_c_temp_x;0;y_c_temp_z]; y_c(1) = y_c(1)*stepX+Grid.x(1)-stepX; y_c(2) = Grid.z(y_c_temp_d); y_c(3) = y_c(3)*stepX+Grid.y(1)-stepX; % Get the translation vector (after rotation. from volune % to slice) Translation = y_c'; Angles_diff = PeakTable.Angles - Angles; af = (sum(Angles_diff.^2,2)<ANGLE_TOLERANCE2); Translation_diff = PeakTable.Translation(af,:) - Translation; tf = (sum(Translation_diff.^2,2) < TRANSLATION_TOLERANCE2); PeakTableLength = size(PeakTable,1); % Modify the PeakTable if sum(tf)==0 % If this peak does not exist, then add it to the table PeakTable(PeakTableLength+1,:) = {Intensity,Angles,Translation}; else % If this peak already exists, then compare the intensities index_list = 1:PeakTableLength; index_tf = index_list(af); index_tf = index_tf(tf); Intensity_diff = Intensity-PeakTable.Intensity(index_tf); intensf = (Intensity_diff>0); index_change = index_tf(intensf); % If the intensity is larger, then change it if ~isempty(index_change) PeakTable(index_change(1),:) = {Intensity,Angles,Translation}; if length(index_change)>1 % delete duplicated peaks PeakTable(index_change(2:end),:) = []; end end end % Peaks.Corr, Peaks.M end % Rank the Peaks with intensity PeakTable = sortrows(PeakTable,'Intensity','descend'); PeakTableLength = size(PeakTable,1); if PeakTableLength>MAX_PEAK_RECORD_NUM % Only keep the peaks with large intensities. PeakTable((MAX_PEAK_RECORD_NUM+1):end,:)=[]; end %% Visualization after each cube-XCC [corr_now_max,ind_max] = max(value_temp(:)); [~,~,y_c_temp_d] = ind2sub(size(value_temp),ind_max); x_c(2,1) = -Grid.z(y_c_temp_d); % x_c: center position for the volume for XCC maxima % y_c = [y_c_temp_x;0;y_c_temp_z]; % y_c: center position of the cut for XCC maxima % y_c(1) = y_c(1)*stepX+data_slice_bw_low.x(1)-stepX; % y_c(3) = y_c(3)*stepX+data_slice_bw_low.y(1)-stepX; % t = -x_c+y_c; % if corr_now_max > corr_max % corr_max = corr_now_max; % para_max = [alpha(k);beta(j);gamma(i);t]; % end % M = cat(2,R,t); % Transformation from Volume Coodination to Slice Coodination % Visualization for test % data_corr.x = Grid.x; % data_corr.y = Grid.y; % data_corr.value = value_temp(:,:,y_c_temp_d); % data_this_cut = neuroReg.renderCell3(x_lim,y_lim,[x_c(2,1),x_c(2,1)],stepX,stepD,pt_list_rotated_now,Option); % Visualize current result % figure(100861); % subplot(1,2,1); % neuroReg.plotData2(data_this_cut); % subplot(1,2,2); % neuroReg.plotData2(data_corr); % title(['d=',num2str(x_c(2,1)),' Max\_XCC=',num2str(corr_now_max)]); %% Waitbar i_tot = sub2ind([n_alpha,n_beta,n_gamma],k,j,i); a = toc; waitbar(i_tot/N,h1,[... 'Current angle: ',num2str([alpha(k),beta(j),gamma(i)]),... ' Time remaining: ',datestr(a/i_tot*(N-i_tot)/24/3600,'DD HH:MM:SS')]); end % end of alpha cycle end % end of beta cycle end % end of gamma cycle close(h1); end function vts = getCube ( origin, size ) x=([0 1 1 0 0 0;1 1 0 0 1 1;1 1 0 0 1 1;0 1 1 0 0 0]-0.5)*size(1)+origin(1)+size(1)/2; y=([0 0 1 1 0 0;0 1 1 0 0 0;0 1 1 0 1 1;0 0 1 1 1 1]-0.5)*size(2)+origin(2)+size(2)/2; z=([0 0 0 0 0 1;0 0 0 0 0 1;1 1 1 1 0 1;1 1 1 1 0 1]-0.5)*size(3)+origin(3)+size(3)/2; vts(1,:,:) = x; vts(2,:,:) = y; vts(3,:,:) = z; end function drawCube(vts,c) for i=1:6 hold on plot3(vts(1,:,i),vts(2,:,i),vts(3,:,i),c); hold off end h=patch(vts(1,:,6),vts(2,:,6),vts(3,:,6),'y'); alpha(h,0.3); end
github
ha-ha-ha-han/NeuromicsCellDetection-master
correction.m
.m
NeuromicsCellDetection-master/+neuroReg/@PlotSlices/correction.m
7,284
utf_8
692c480b324e30dab5e20d08685a7fbb
function correction(obj,varargin) % Set the Upper and Lower limit. It is changeable, but now % disabled. % tll=1; %Tolerance lower limit. %Max of tolerance is 1 and zero tolerance is forbidden. %Choose this value in between. % tul=1; %Tolerance upper limit. %Max of tolerance is 1 and zero tolerance is forbidden. %Choose this value in between. %modified by sandy for photon dep data %% Gather information disp(['Please process Square correction first if needed.'... 'Along x or y is permitted.'... 'Please select at least three points.',... 'Data selection end with Enter.']); switch obj.Direction case 'x' d=1; xData=obj.Data.y; yData=obj.Data.z; %sandy modified if isfield(obj.Data,'ztot') ytotData=obj.Data.ztot; end %sandy end modified case 'y' d=2; xData=obj.Data.x; yData=obj.Data.z; %sandy modified if isfield(obj.Data,'ztot') ytotData=obj.Data.ztot; end %sandy end modified otherwise d=3; xData=obj.Data.x; yData=obj.Data.y; end pos=get(obj.Slider,'Value'); [~,posInd]=min(abs(obj.AxisData-pos)); index=arraySliceIndex(3,posInd,d); sliceData=squeeze(obj.Data.value(index{:})); [~,sizeOfxData]=size(xData); [~,sizeOfyData]=size(yData); [m,n]=getpts; hold on; correctionPointHandle=plot(m,n,'k+'); % can give bigger order or not? A=polyfit(m,n,2); z=polyval(A,xData); correctionLineHandle=plot(xData,z,'r--'); hold off; rangeOfyData=max(yData)-min(yData);%range of yData %% positive quadratic term coefficient if (A(1,1)>0) %positive quadratic term coefficient xd=xData; pv=polyval(A,xd); fitmin1=min(pv); fitmax1=max(pv); newyDataDimension=ceil((fitmax1-fitmin1)*sizeOfyData/rangeOfyData)+sizeOfyData;%new yData dimension nsliceData=NaN.*ones(sizeOfxData,newyDataDimension); for i=1:sizeOfxData dif=fix((polyval(A,xd(1,i))-fitmin1)*sizeOfyData/rangeOfyData);%difference nsliceData(i,newyDataDimension-dif-sizeOfyData+(1:sizeOfyData))=sliceData(i,1:sizeOfyData); end if (d==1) [~,columnsize]=size(obj.Data.x); newDataValue=NaN.*ones(columnsize,sizeOfxData,newyDataDimension); for i=1:sizeOfxData dif=fix((polyval(A,xd(1,i))-fitmin1)*sizeOfyData/rangeOfyData);%difference newDataValue(1:columnsize,i,newyDataDimension-dif-sizeOfyData+(1:sizeOfyData))=obj.Data.value(1:columnsize,i,1:sizeOfyData); end end if (d==2) [~,columnsize]=size(obj.Data.y); newDataValue=NaN.*ones(sizeOfxData,columnsize,newyDataDimension); for i=1:sizeOfxData dif=fix((polyval(A,xd(1,i))-fitmin1)*sizeOfyData/rangeOfyData);%difference newDataValue(i,1:columnsize,newyDataDimension-dif-sizeOfyData+(1:sizeOfyData))=obj.Data.value(i,1:columnsize,1:sizeOfyData); end end end %end of positive quadratic term coefficient case %% negative quadratic term coefficient if (A(1,1)<0)%negative quadratic term coefficient xd=xData; pv=polyval(A,xd); fitmin2=min(pv); fitmax2=max(pv); newyDataDimension=ceil((fitmax2-fitmin2)*sizeOfyData/rangeOfyData)+sizeOfyData; nsliceData=NaN.*ones(sizeOfxData,newyDataDimension); for i=1:sizeOfxData dif=fix((fitmax2-polyval(A,xd(1,i)))*sizeOfyData/rangeOfyData);%difference nsliceData(i,dif+(1:sizeOfyData))=sliceData(i,1:sizeOfyData); end if (d==1) [~,columnsize]=size(obj.Data.x); newDataValue=NaN.*ones(columnsize,sizeOfxData,newyDataDimension); for i=1:sizeOfxData dif=fix((fitmax2-polyval(A,xd(1,i)))*sizeOfyData/rangeOfyData);%difference newDataValue(1:columnsize,i,dif+(1:sizeOfyData))=obj.Data.value(1:columnsize,i,1:sizeOfyData); end end if (d==2) [~,columnsize]=size(obj.Data.y); newDataValue=NaN.*ones(sizeOfxData,columnsize,newyDataDimension); for i=1:sizeOfxData dif=fix((fitmax2-polyval(A,xd(1,i)))*sizeOfyData/rangeOfyData);%difference newDataValue(i,1:columnsize,dif+(1:sizeOfyData))=obj.Data.value(i,1:columnsize,1:sizeOfyData); end end end %end of negative quadratic term coefficient case boolNewDataValue=~isnan(newDataValue); flagU=1; Testu=NaN.*ones(1,newyDataDimension); for ciru=newyDataDimension:-1:1 Testu(1,ciru)=sum(sum(boolNewDataValue(:,:,ciru))); if sum(sum(boolNewDataValue(:,:,ciru)))~=0 newUpperLimit=ciru; flagU=0; break; end end % disp(Testu(1,:)) flagL=1; for cirl=1:newyDataDimension % disp(sum(sum(boolNewDataValue(:,:,cirl)))) if sum(sum(boolNewDataValue(:,:,cirl)))~=0 newLowerLimit=cirl; flagL=0; break; end end obj.CorrData.x=obj.Data.x; obj.CorrData.y=obj.Data.y; if (flagL+flagU~=0) obj.CorrData.value=newDataValue; nyData=NaN.*ones(1,newyDataDimension); for i=1:newyDataDimension nyData(1,i)=min(yData)+(i-1)*rangeOfyData/sizeOfyData;%new yData %sandy modified if isfield(obj.Data,'ztot') nytotData(i,:) = min(ytotData)+(i-1)*rangeOfyData/sizeOfyData;%#ok<AGROW> %new ytotData end %sandy end modified end obj.CorrData.z=nyData; %sandy modified if isfield(obj.Data,'ztot') obj.CorrData.ztot=nytotData; end %sandy end modified end if (flagL+flagU==0) if(d==1) [~,columnsize]=size(obj.Data.x); obj.CorrData.value(1:columnsize,1:sizeOfxData,1:(newUpperLimit-newLowerLimit+1))=newDataValue(1:columnsize,1:sizeOfxData,newLowerLimit:newUpperLimit); end if(d==2) [~,columnsize]=size(obj.Data.y); obj.CorrData.value(1:sizeOfxData,1:columnsize,1:(newUpperLimit-newLowerLimit+1))=newDataValue(1:sizeOfxData,1:columnsize,newLowerLimit:newUpperLimit); end nyData=NaN.*ones(1,(newUpperLimit-newLowerLimit+1)); for i=1:(newUpperLimit-newLowerLimit+1) nyData(1,i)=min(yData)+(i-1)*rangeOfyData/sizeOfyData;%new yData %sandy modified if isfield(obj.Data,'ztot') nytotData(i,:) = min(ytotData)+(i-1)*rangeOfyData/sizeOfyData;%new ytotData end %sandy end modified end obj.CorrData.z=nyData; %sandy modified if isfield(obj.Data,'ztot') obj.CorrData.ztot=nytotData; end %sandy end modified end [flag,DataName] = saveCorrection(obj); if flag if(d==1) PlotSlices(DataName,'x'); end if(d==2) PlotSlices(DataName,'y'); end end delete(correctionLineHandle); delete(correctionPointHandle); end function [flag,DataName]=saveCorrection(obj,varargin) flag=0; newData=obj.Data; newData.x=obj.CorrData.x; newData.y=obj.CorrData.y; newData.z=obj.CorrData.z; newData.value=obj.CorrData.value; %sandy modified if isfield(obj.Data,'ztot') newData.ztot=obj.CorrData.ztot; end %sandy end modified if length(newData.x)==1 newData.x=newData.y; newData.y=newData.z; newData=rmfield(newData,'z'); newData.value=squeeze(newData.value); end DataName=inputdlg({'Data Name'},... 'Save correction',... 1,... {[obj.DataName,'_corr']}); if isempty(DataName) return; end assignin('base',DataName{1},newData); flag=1; end
github
ha-ha-ha-han/NeuromicsCellDetection-master
area_secant_ph.m
.m
NeuromicsCellDetection-master/+neuroReg/@PlotSlices/private/area_secant_ph.m
1,303
utf_8
6481a9d3042db7acdb53481253370c1d
function [x,y,r] = area_secant_ph( x_grid , y_grid, x0, y0, x1, y1 ) % Area_secant_ph returns the coodinates of points of a secant of a %rectangular area defined by x_grid and y_grid. %% determine the line k=(y1-y0)/(x1-x0); reverse_flag=0; if k>10e4 % in case the line is vertical to x-axis [x_grid,y_grid]=exchange_p(x_grid,y_grid); [x0,y0]=exchange_p(x0,y0); [x1,y1]=exchange_p(x1,y1); k=(y1-y0)/(x1-x0); reverse_flag=1; end b=y1-x1*k; %% determine the range of output x array y_max=max(y_grid); y_min=min(y_grid); x_max=max(x_grid); x_min=min(x_grid); x1=(y_max-b)/k; x2=(y_min-b)/k; if x1>x2 [x1,x2]=exchange_p(x1,x2); end if x2<x_min||x1>x_max errordlg('hehe, the line is out of the area'); return; end if x1<x_min x1=x_min; y1=k*x1+b; else y1=y_min; end if x2>x_max x2=x_max; y2=k*x2+b; else y2=y_max; end % determine the number of sampling points r=sqrt((x1-x2)^2+(y1-y2)^2); n=floor(abs(r/(min(x_grid(1)-x_grid(2),y_grid(1)-y_grid(2)))))+1; %% determine the output array x and array y x=linspace(x1,x2,n); y=k*x+b; sgn=(x-x0)./abs(x-x0); sgn(isnan(sgn))=0; r=sgn.*sqrt((x-x0).^2+(y-y0).^2); if reverse_flag==1 [x,y]=exchange_p(x,y); end function [a,b] = exchange_p(c,d) % just exchange a=d; b=c;
github
thk2dth/LocalSmoothing-master
Proposed.m
.m
LocalSmoothing-master/Proposed.m
3,481
utf_8
579e28d64f4fd10c4032d2e3c3027495
function [ nrbsPos, nrbsOri] = Proposed( wcs, pe, oe, c ) % Proposed method smooths the tool position and tool % orientation both in WCS. % Input: % wcs, cutter data in WCS. % pe, position error, in mm. % oe, orientation error, in rad. % c, d1/d2. c=0.25, by default. % Output: % nrbsPos, inserted B-splines during position transition. % nrbsOri, inserted B-splines during orientation transition. % Note that this spline is not on the unit sphere. num = size(wcs, 2) - 2; % number of transition curves. nrbsPos = cell(1, num); nrbsOri = cell(1, num); d2p = zeros(1, num); d2o = zeros(1, num); for i = 1:num [nrbsPos{i}, d2p(i)] = localPositionSmoothing(wcs(1:3, i),... wcs(1:3, i+1), wcs(1:3, i+2), pe, c); [nrbsOri{i}, d2o(i)] = localOrientationSmoothing(wcs(4:6, i),... wcs(4:6, i+1), wcs(4:6, i+2), oe, c); end % Parameter synchronization. % The inserted two intermediate points are calculated only % for computation comparison. for i = 1:num+1 if (i > 1) d21p = d2p(i-1); d21o = d2p(i-1); V0p = nrbsPos{i-1}.coefs(1:3, 5); V0o = nrbsOri{i-1}.coefs(1:3, 5); else d21p = 0; % transition length of the first B-spline. d21o = 0; V0p = wcs(1:3, i); V0o = wcs(4:6, i); end if (i < num+1) d22p = d2p(i); d22o = d2o(i); V3p = nrbsPos{i}.coefs(1:3, 1); V3o = nrbsOri{i}.coefs(1:3, 1); else d22p = 0; % transitiong length of the last B-spline. d22o = 0; V3p = wcs(1:3, i); V3o = wcs(4:6, i); end vp = V3p - V0p; lp = sqrt( vp' * vp); vo = V3o - V0o; lo = sqrt(vo' * vo); tp = 2*c*d21p / (lp-(1+c)*(d21p+d22p) ); V1p = V0p + vp * tp; V2p = V3p - vp * tp; to = 2*c*d21o / (lo-(1+c)*(d21o+d22o) ); V1o = V0o + vo * to; V2o = V3o - vo * to; end end %% Local position smoothing for three points. function [nrb, d2] = localPositionSmoothing(p1, p2, p3, pe, c) v1 = p2 - p1; v2 = p3 - p2; l1 = sqrt(v1' * v1); l2 = sqrt(v2' * v2); m1 = v1 / l1; m2 = v2 / l2; beta = 0.5 * acos( m1' * m2 ); % Eq. (9) n1 = 2 * pe / (sin(beta) ); n2 = min(l1, l2) / (3*(1+c) ); % lm = min(l1, l2)/3. d2 = min(n1, n2); % inserted B-spline has five control points. ctrls = zeros(3, 5); knots = [0, 0, 0, 0, 0.5, 1, 1, 1, 1]; ctrls(:, 1) = p2 - m1 * (d2*(1+c) ); ctrls(:, 2) = p2 - m1 * d2; ctrls(:, 3) = p2; ctrls(:, 4) = p2 + m2 * d2; ctrls(:, 5) = p2 + m2 * (d2*(1+c) ); nrb = nrbmak(ctrls, knots); end %% Local orientation smoothing for three points. function [nrb, d2] = localOrientationSmoothing(o1, o2, o3, oe, c) v1 = o2 - o1; v2 = o3 - o2; s1 = sqrt(v1' * v1); s2 = sqrt(v2' * v2); m1 = v1 / s1; % unit vector of v1. m2 = v2 / s2; % unit vector of v2. dv = m2 - m1; k1 = 0.25 * dv' * o2; k2 = dv' * dv / 16.0; te = cos(oe)^2; % temp variable. a = k1 * k1 - k2*te; r0 = min(s1, s2) / (3*(1+c) ); % Eq. (16) % Algorithm to determine d2. if (a==0) && (k1<0) d2 = min(-0.5/k1, r0); elseif (a<0) % Eq. (15) discri = (1-te) * (k2-k1*k1)*te; % 1/4 of the discriminant. r1 = ( (te-1)*k1 - sqrt(discri) ) / a; % Eq. (16) d2 = min(r1, r0); else d2 = r0; end % inserted B-spline has five control points. ctrls = zeros(3, 5); knots = [0, 0, 0, 0, 0.5, 1, 1, 1, 1]; ctrls(:, 1) = o2 - m1 * (d2*(1+c) ); ctrls(:, 2) = o2 - m1 * d2; ctrls(:, 3) = o2; ctrls(:, 4) = o2 + m2 * d2; ctrls(:, 5) = o2 + m2 * (d2*(1+c) ); nrb = nrbmak(ctrls, knots); end
github
thk2dth/LocalSmoothing-master
Yang.m
.m
LocalSmoothing-master/Yang.m
2,907
utf_8
e6d6d8da4fbb32ac58939ba066de274e
function [ nrbsPos, nrbsRot] = Yang( mcs, pe, oe, mp ) % Yang's method smooths the tool position in WCS and tool % orientation in MCS. % Input: % mcs, cutter data in MCS. % pe, position error in WCS. % oe, orientation error in WCS. % mp, geometric property of machine tool. % Output: % nrbsPos, inserted B-spline (Bezier) curve for % tool position in WCS. % nrbsRot, inserted B-spline (Bezier) curve for % rotary axes in MCS. num = size(mcs, 2) - 2; % number of transition curves. nrbsPos = cell(1, num); nrbsRot = cell(1, num); lp = zeros(1, num); for i = 1:num [nrbsPos{i}, nrbsRot{i}, lp(i)] = localSmoothing(mcs(1:3, i),... mcs(1:3, i+1), mcs(1:3, i+2), mcs(4:5, i), mcs(4:5, i+1), mcs(4:5, i+2),... pe, oe, mp); end end %% Local position smoothing for three cutter data. % In Yang's method, the tool position and rotary axes cannot % be smoothed seperately. function [nrbPos, nrbRot, lp] = localSmoothing(T1, T2, T3, R1, R2, R3, pe, oe, mp) % The algorithm should do FKT, since either the machine coordinate % or the workpiece coordinate is known in pratical applications. wc1 = FKT([T1; R1], mp); wc2 = FKT([T2; R2], mp); wc3 = FKT([T3; R3], mp); p1 = wc1(1:3); p2 = wc2(1:3); p3 = wc3(1:3); v1 = p1 - p2; % The reverse direction is adopted. v2 = p3 - p2; l1 = sqrt(v1' * v1); l2 = sqrt(v2' * v2); m1 = v1 / l1; % unit vector of v1. m2 = v2 / l2; alpha = acos( m1' * m2 ); % Eq. (5) without consideration of synchronization. lp = min(4*pe/(3*cos(0.5*alpha) ), 0.2*min(l1, l2) ); u1 = R1 - R2; u2 = R3 - R2; s1 = sqrt(u1' * u1); s2 = sqrt( u2' * u2); n1 = u1 / s1; n2 = u2 / s2; beta = acos(n1' * n2); k = s2*l1 / (s1*l2); % Eq. (20) O = wc2(4:6); % tool orientation. % skew-symmetric matrix of O. Eq. (28) Ohat = [0, -O(3), O(2);... O(3), 0, -O(1);... -O(2), O(1), 0]; Jo = JRR(R2(1), R2(2) ); % Eq. (33) T1 = Ohat * Jo; T2 = T1' * T1; % maximum eigen values of T2. m_eig = max( eig(T2) ); % Eq. (28) lop = 8*sin(oe)*l1 / (3*m_eig*s1 * sqrt(1+k*k+2*k*cos(beta)) ); % Eq. (29) lp = min(lp, lop); % Eq. (19) loa = s1*lp / l1; % Eq. (20) lob = k * loa; % inserted B-spline has seven control points. ctrls = zeros(3, 7); knots = [zeros(1, 6), 0.5, ones(1, 6)]; % inserted B-spline for tool position. % Eq. (4) ctrls(:, 4) = p2; ctrls(:, 3) = p2 + m1 * lp; ctrls(:, 5) = p2 + m2 * lp; ctrls(:, 2) = ctrls(:, 3)*2 - p2; ctrls(:, 1) = 0.5 * (ctrls(:, 3)*5 - p2*3); ctrls(:, 6) = ctrls(:, 5)*2 - p2; ctrls(:, 7) = 0.5 * (ctrls(:, 5)*5 - p2*3); nrbPos = nrbmak(ctrls, knots); % inserted B-spline for rotary axes. % Eq. (30) ctrls = zeros(2, 7); % Two dimension data ctrls(:, 4) = R2; ctrls(:, 3) = R2 + n1 * loa; ctrls(:, 5) = R2 + n2 * lob; ctrls(:, 2) = ctrls(:, 3)*2 - R2; ctrls(:, 1) = 0.5 * (ctrls(:, 3)*5 - R2*3); ctrls(:, 6) = ctrls(:, 5)*2 - R2; ctrls(:, 7) = 0.5 * (ctrls(:, 5)*5 - R2*3); nrbRot = nrbmak(ctrls, knots); end
github
thk2dth/LocalSmoothing-master
Bi.m
.m
LocalSmoothing-master/Bi.m
2,686
utf_8
dfb6f6b7f590a9f043fb61ef5bd1b555
function [ nrbsTrans, nrbsRot] = Bi( mcs, pe, oe, mp ) % Bi's method smooths the tool position and tool % orientation both in MCS. % Input: % mcs, cutter data in MCS. % pe, position error in WCS. % oe, orientation error in WCS. % mp, geometric property of machine tool. % Output: % nrbsTrans, inserted B-spline (Bezier) curve for % translational axes in MCS. % nrbsRot, inserted B-spline (Bezier) curve for % rotary axes in MCS. num = size(mcs, 2) - 2; % number of transition curves. nrbsTrans = cell(1, num); nrbsRot = cell(1, num); tl = zeros(1, num); tr = zeros(1, num); for i = 1:num [nrbsTrans{i}, nrbsRot{i}, tl(i), tr(i)] = localSmoothing(mcs(1:3, i),... mcs(1:3, i+1), mcs(1:3, i+2), mcs(4:5, i), mcs(4:5, i+1), mcs(4:5, i+2),... pe, oe, mp); end end %% Local smoothing for three cutter data. % In Bi's method, the translational axes and rotary axes cannot % be smoothed seperately. function [nrbTrans, nrbRot, tl, tr] = localSmoothing(T1, T2, T3, R1, R2, R3, pe, oe, mp) % The algorithm should do FKT, since either the machine coordinate % or the workpiece coordinate is known in pratical applications. wc1 = FKT([T1; R1], mp); wc2 = FKT([T2; R2], mp); % wc3 = FKT([T3; R3], mp); p1 = wc1(1:3); % tool position. p2 = wc2(1:3); % p3 = wc3(1:3); n = wc2(4:6); % tool orientation. vp1 =p2 - p1; t = vp1 - n * (vp1'*n); t = t / sqrt(t'*t); % normalize t. b = cross(t, n); % b Jrr = JRR(R2(1), R2(2) ); % Eq. (11) T = [t'; b'] * Jrr; % Matrix of dimension 2*2. Tn = T' * T; % Eq. (12) e1 = max(eig(Tn) ); dOmr = sin(oe) / e1; % Eq. (13) % Eq. (5) Jtr = JTR([T2; R2], mp); e2 = max(eig(Jtr' * Jtr) ); Jtt = JTT(R2(1), R2(2) ); e3 = max(eig(Jtt' * Jtt) ); dQmr = (pe - e2*dOmr) / e3; v1 = T2 - T1; v2 = T3 - T2; u1 = R2 - R1; u2 = R3 - R2; l1 = sqrt(v1' * v1); l2 = sqrt(v2' * v2); s1 = sqrt(u1' * u1); s2 = sqrt(u2' * u2); m1 = v1 / l1; m2 = v2 / l2; n1 = u1 / s1; n2 = u2 / s2; theta = acos(m1' * m2); alpha = acos(n1' * n2); % Eq. (29) dP = 4*dQmr / sin(0.5 * theta); dO = 4*dOmr / sin(0.5 * alpha); % Eq. (31) tl = min(min(dO/s1, dP/l1), 0.5); tr = min(min(dO/s2, dP/l2), 0.5); % inserted B-splines in MCS. % In Bi's paper, Bezier curve is inserted. We convert the % Bezier curve to B-spline curve for expression consistence. knots = [0, 0, 0, 0, 1, 1, 1, 1]; ctrls = zeros(3, 4); % Eq. (28) ctrls(:, 2) = T2; ctrls(:, 3) = T3; ctrls(:, 1) = T1 * tl + T2 * (1-tl); ctrls(:, 4) = T2 * tr + T3 * (1 - tr); nrbTrans = nrbmak(ctrls, knots); ctrls = zeros(2, 3); ctrls(:, 2) = R2; ctrls(:, 3) = R2; ctrls(:, 1) = R1 * tl + R2 * (1-tl); ctrls(:, 4) = R2 * tr + R3 * (1 - tr); nrbRot = nrbmak(ctrls, knots); end
github
thk2dth/LocalSmoothing-master
SuccessRate.m
.m
LocalSmoothing-master/SuccessRate.m
2,362
utf_8
3f9c393aa7956fc7ec048dbccd6c7b4f
function [ra, rm, ea, em] = SuccessRate( nrbs, oe, isWCS, cornerIndex ) % Evaluate the success rate of the transition method. % If the orientation error is under the specified value, i.e., oe, % the method succeedes. % Input: % nrbs, inserted B-splines during orientation smoothing. % oe, specified orientation error. % isWCS, whether the nrbs is in WCS. % cornerIndex, the index of the corner point in the B-spline % Output: % ra, success rate for all points. % rm, success rate for middle points. % ea, minimum error of all points. % em, error of middle point. if nargin == 2 isWCS =1; cornerIndex = 3; end % num points are sampled on each B-spline. numSpline = length(nrbs); numPts = 5001; u = linspace(0, 1, numPts); ea = zeros(1, numSpline); em = ea; numFailAll = 0; numFailMid = 0; coe = cos(oe); % This value is used to avoid numeric issues when % testing the success of the algorithm. num_eps = 1e-12; numberOfCores = 4; % quad-core CPU pool_obj = parpool(numberOfCores); parfor i = 1:numSpline if isWCS O = nrbs{i}.coefs(1:3, cornerIndex); % Corner point. else % Corner point. O = Ori(nrbs{i}.coefs(1, cornerIndex), nrbs{i}.coefs(2, cornerIndex)); end ce = 0.0; for j = 1:numPts p = nrbeval(nrbs{i}, u(j) ); if isWCS lp = sqrt( p' * p); cet = O' * p / lp; else o = Ori(p(1), p(2)); cet = O' * o; end % Minimum angle between the sampled points and % O. if (cet > ce) ce = cet; end end % Numeric issues should be considered. if coe - ce >= num_eps numFailAll = numFailAll + 1; end if (ce > 1) ce = 1; end if (ce < -1) ce = -1; end ea(i) = acos(ce); % in rad. % Smoothing error at middle point. m = nrbeval(nrbs{i}, 0.5 ); if isWCS ml = sqrt(m' * m); me = O' * m / ml; else o = Ori(m(1), m(2)); me = O' * o; end % Numeric issues should be considered. if coe - me >= num_eps numFailMid = numFailMid + 1; end em(i) = acos(me); end delete(pool_obj); ra = numFailAll / numSpline; rm = numFailMid / numSpline; end %% Mapping A and C to an orientation. function O = Ori(A, C) O = [sin(A)*sin(C); -sin(A)*cos(C); cos(A)]; end
github
thk2dth/LocalSmoothing-master
bspdegelev.m
.m
LocalSmoothing-master/nurbs_toolbox/bspdegelev.m
20,232
utf_8
f3f726254444c07038e088dfbb120a32
function [ic,ik] = bspdegelev(d,c,k,t) % % Function Name: % % bspdegevel - Degree elevate a univariate B-Spline. % % Calling Sequence: % % [ic,ik] = bspdegelev(d,c,k,t) % % Parameters: % % d : Degree of the B-Spline. % % c : Control points, matrix of size (dim,nc). % % k : Knot sequence, row vector of size nk. % % t : Raise the B-Spline degree t times. % % ic : Control points of the new B-Spline. % % ik : Knot vector of the new B-Spline. % % Description: % % Degree elevate a univariate B-Spline. This function provides an % interface to a toolbox 'C' routine. [mc,nc] = size(c); % % int bspdegelev(int d, double *c, int mc, int nc, double *k, int nk, % int t, int *nh, double *ic, double *ik) % { % int row,col; % % int ierr = 0; % int i, j, q, s, m, ph, ph2, mpi, mh, r, a, b, cind, oldr, mul; % int n, lbz, rbz, save, tr, kj, first, kind, last, bet, ii; % double inv, ua, ub, numer, den, alf, gam; % double **bezalfs, **bpts, **ebpts, **Nextbpts, *alfs; % % double **ctrl = vec2mat(c, mc, nc); % ic = zeros(mc,nc*(t)); % double **ictrl = vec2mat(ic, mc, nc*(t+1)); % n = nc - 1; % n = nc - 1; % bezalfs = zeros(d+1,d+t+1); % bezalfs = matrix(d+1,d+t+1); bpts = zeros(mc,d+1); % bpts = matrix(mc,d+1); ebpts = zeros(mc,d+t+1); % ebpts = matrix(mc,d+t+1); Nextbpts = zeros(mc,d+1); % Nextbpts = matrix(mc,d+1); alfs = zeros(d,1); % alfs = (double *) mxMalloc(d*sizeof(double)); % m = n + d + 1; % m = n + d + 1; ph = d + t; % ph = d + t; ph2 = floor(ph / 2); % ph2 = ph / 2; % % // compute bezier degree elevation coefficeients bezalfs(1,1) = 1; % bezalfs[0][0] = bezalfs[ph][d] = 1.0; bezalfs(d+1,ph+1) = 1; % for i=1:ph2 % for (i = 1; i <= ph2; i++) { inv = 1/bincoeff(ph,i); % inv = 1.0 / bincoeff(ph,i); mpi = min(d,i); % mpi = min(d,i); % for j=max(0,i-t):mpi % for (j = max(0,i-t); j <= mpi; j++) bezalfs(j+1,i+1) = inv*bincoeff(d,j)*bincoeff(t,i-j); % bezalfs[i][j] = inv * bincoeff(d,j) * bincoeff(t,i-j); end end % } % for i=ph2+1:ph-1 % for (i = ph2+1; i <= ph-1; i++) { mpi = min(d,i); % mpi = min(d, i); for j=max(0,i-t):mpi % for (j = max(0,i-t); j <= mpi; j++) bezalfs(j+1,i+1) = bezalfs(d-j+1,ph-i+1); % bezalfs[i][j] = bezalfs[ph-i][d-j]; end end % } % mh = ph; % mh = ph; kind = ph+1; % kind = ph+1; r = -1; % r = -1; a = d; % a = d; b = d+1; % b = d+1; cind = 1; % cind = 1; ua = k(1); % ua = k[0]; % for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) ic(ii+1,1) = c(ii+1,1); % ictrl[0][ii] = ctrl[0][ii]; end % for i=0:ph % for (i = 0; i <= ph; i++) ik(i+1) = ua; % ik[i] = ua; end % % // initialise first bezier seg for i=0:d % for (i = 0; i <= d; i++) for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) bpts(ii+1,i+1) = c(ii+1,i+1); % bpts[i][ii] = ctrl[i][ii]; end end % % // big loop thru knot vector while b < m % while (b < m) { i = b; % i = b; while b < m && k(b+1) == k(b+2) % while (b < m && k[b] == k[b+1]) b = b + 1; % b++; end % mul = b - i + 1; % mul = b - i + 1; mh = mh + mul + t; % mh += mul + t; ub = k(b+1); % ub = k[b]; oldr = r; % oldr = r; r = d - mul; % r = d - mul; % % // insert knot u(b) r times if oldr > 0 % if (oldr > 0) lbz = floor((oldr+2)/2); % lbz = (oldr+2) / 2; else % else lbz = 1; % lbz = 1; end % if r > 0 % if (r > 0) rbz = ph - floor((r+1)/2); % rbz = ph - (r+1)/2; else % else rbz = ph; % rbz = ph; end % if r > 0 % if (r > 0) { % // insert knot to get bezier segment numer = ub - ua; % numer = ub - ua; for q=d:-1:mul+1 % for (q = d; q > mul; q--) alfs(q-mul) = numer / (k(a+q+1)-ua); % alfs[q-mul-1] = numer / (k[a+q]-ua); end for j=1:r % for (j = 1; j <= r; j++) { save = r - j; % save = r - j; s = mul + j; % s = mul + j; % for q=d:-1:s % for (q = d; q >= s; q--) for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) tmp1 = alfs(q-s+1)*bpts(ii+1,q+1); tmp2 = (1-alfs(q-s+1))*bpts(ii+1,q); bpts(ii+1,q+1) = tmp1 + tmp2; % bpts[q][ii] = alfs[q-s]*bpts[q][ii]+(1.0-alfs[q-s])*bpts[q-1][ii]; end end % for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) Nextbpts(ii+1,save+1) = bpts(ii+1,d+1); % Nextbpts[save][ii] = bpts[d][ii]; end end % } end % } % // end of insert knot % % // degree elevate bezier for i=lbz:ph % for (i = lbz; i <= ph; i++) { for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) ebpts(ii+1,i+1) = 0; % ebpts[i][ii] = 0.0; end mpi = min(d, i); % mpi = min(d, i); for j=max(0,i-t):mpi % for (j = max(0,i-t); j <= mpi; j++) for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) tmp1 = ebpts(ii+1,i+1); tmp2 = bezalfs(j+1,i+1)*bpts(ii+1,j+1); ebpts(ii+1,i+1) = tmp1 + tmp2; % ebpts[i][ii] = ebpts[i][ii] + bezalfs[i][j]*bpts[j][ii]; end end end % } % // end of degree elevating bezier % if oldr > 1 % if (oldr > 1) { % // must remove knot u=k[a] oldr times first = kind - 2; % first = kind - 2; last = kind; % last = kind; den = ub - ua; % den = ub - ua; bet = floor((ub-ik(kind)) / den); % bet = (ub-ik[kind-1]) / den; % % // knot removal loop for tr=1:oldr-1 % for (tr = 1; tr < oldr; tr++) { i = first; % i = first; j = last; % j = last; kj = j - kind + 1; % kj = j - kind + 1; while j-i > tr % while (j - i > tr) { % // loop and compute the new control points % // for one removal step if i < cind % if (i < cind) { alf = (ub-ik(i+1))/(ua-ik(i+1)); % alf = (ub-ik[i])/(ua-ik[i]); for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) tmp1 = alf*ic(ii+1,i+1); tmp2 = (1-alf)*ic(ii+1,i); ic(ii+1,i+1) = tmp1 + tmp2; % ictrl[i][ii] = alf * ictrl[i][ii] + (1.0-alf) * ictrl[i-1][ii]; end end % } if j >= lbz % if (j >= lbz) { if j-tr <= kind-ph+oldr % if (j-tr <= kind-ph+oldr) { gam = (ub-ik(j-tr+1)) / den; % gam = (ub-ik[j-tr]) / den; for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) tmp1 = gam*ebpts(ii+1,kj+1); tmp2 = (1-gam)*ebpts(ii+1,kj+2); ebpts(ii+1,kj+1) = tmp1 + tmp2; % ebpts[kj][ii] = gam*ebpts[kj][ii] + (1.0-gam)*ebpts[kj+1][ii]; end % } else % else { for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) tmp1 = bet*ebpts(ii+1,kj+1); tmp2 = (1-bet)*ebpts(ii+1,kj+2); ebpts(ii+1,kj+1) = tmp1 + tmp2; % ebpts[kj][ii] = bet*ebpts[kj][ii] + (1.0-bet)*ebpts[kj+1][ii]; end end % } end % } i = i + 1; % i++; j = j - 1; % j--; kj = kj - 1; % kj--; end % } % first = first - 1; % first--; last = last + 1; % last++; end % } end % } % // end of removing knot n=k[a] % % // load the knot ua if a ~= d % if (a != d) for i=0:ph-oldr-1 % for (i = 0; i < ph-oldr; i++) { ik(kind+1) = ua; % ik[kind] = ua; kind = kind + 1; % kind++; end end % } % % // load ctrl pts into ic for j=lbz:rbz % for (j = lbz; j <= rbz; j++) { for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) ic(ii+1,cind+1) = ebpts(ii+1,j+1); % ictrl[cind][ii] = ebpts[j][ii]; end cind = cind + 1; % cind++; end % } % if b < m % if (b < m) { % // setup for next pass thru loop for j=0:r-1 % for (j = 0; j < r; j++) for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) bpts(ii+1,j+1) = Nextbpts(ii+1,j+1); % bpts[j][ii] = Nextbpts[j][ii]; end end for j=r:d % for (j = r; j <= d; j++) for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) bpts(ii+1,j+1) = c(ii+1,b-d+j+1); % bpts[j][ii] = ctrl[b-d+j][ii]; end end a = b; % a = b; b = b+1; % b++; ua = ub; % ua = ub; % } else % else % // end knot for i=0:ph % for (i = 0; i <= ph; i++) ik(kind+i+1) = ub; % ik[kind+i] = ub; end end end % } % End big while loop % // end while loop % % *nh = mh - ph - 1; % % freevec2mat(ctrl); % freevec2mat(ictrl); % freematrix(bezalfs); % freematrix(bpts); % freematrix(ebpts); % freematrix(Nextbpts); % mxFree(alfs); % % return(ierr); % } function b = bincoeff(n,k) % Computes the binomial coefficient. % % ( n ) n! % ( ) = -------- % ( k ) k!(n-k)! % % b = bincoeff(n,k) % % Algorithm from 'Numerical Recipes in C, 2nd Edition' pg215. % double bincoeff(int n, int k) % { b = floor(0.5+exp(factln(n)-factln(k)-factln(n-k))); % return floor(0.5+exp(factln(n)-factln(k)-factln(n-k))); % } function f = factln(n) % computes ln(n!) if n <= 1, f = 0; return, end f = gammaln(n+1); %log(factorial(n));</pre>
github
evanrussek/Predictive-Representations-PLOS-CB-2017-master
model_SRDYNA.m
.m
Predictive-Representations-PLOS-CB-2017-master/agents/model_SRDYNA.m
4,145
utf_8
b9bde41bec4a7e50ff64602bbf08bed6
function model = model_SRDYNA() model.init = @modelinit; model.update = @modelupdate; model.eval = @modeleval; model.choose = @modelchoose; model.dyna_update = @dyna_update; model.qlearn_update = @qlearn_update; function model = modelinit(model,game,params_in) n_sa = length(game.sa_to_nextstate); H = eye(n_sa); H(n_sa,:) = 0; w = zeros(n_sa,1); if nargin < 3 model.param.epsilon = .1; model.param.sr_alpha = .3; model.param.w_alpha = .3; model.param.discount = .95; model.param.nsamples = 10000; model.param.bsamples = 10; else model.param = params_in; end model.H = H; model.w = w; model.dn_tot = 1; % store samples seperately for each state for i = 1:n_sa model.sa(i).samples = zeros(10000,5); model.sa(i).dn = 1; end model.sa_list = zeros(10000,1); model.s = game.current_state; model.s_prime = 0; model.a = 0; model.a_prime = 0; model.r = 0; function model = modelupdate(model,game) % update H model.H = sarsa_update(model.s,model.a,model.s_prime,model.a_prime,model,game); % update w model.w = w_update(model.s,model.a,model.r,model.s_prime,model.a_prime,model,game); sa_num = game.available_sa(model.s,model.a); model.sa(sa_num).samples(model.sa(sa_num).dn,:) = [model.s, model.a, model.r, model.s_prime, model.a_prime]; model.sa(sa_num).dn = model.sa(sa_num).dn + 1; model.sa_list(model.dn_tot) = sa_num; model.dn_tot = model.dn_tot + 1; model = model.dyna_update(model,game,model.param.b_samples); function [Q,model] = modeleval(model,game) model.Q = model.H*model.w; asa = game.available_sa(game.current_state,:); asa(asa==0) = []; Q = model.Q(asa); function a = modelchoose(Qvals,game, epsilon) %epsilon = .1; action_prob = zeros(length(Qvals),1); [maxval, max_a] = max(Qvals); [bestA] = find(Qvals==maxval); action_prob(bestA) = (1 - epsilon)/length(bestA); action_prob = action_prob + epsilon/length(Qvals); a = find(rand < cumsum(action_prob),1); function H = sarsa_update(s,a,s_prime,a_prime,model,game) sa = game.available_sa(s,a); sa_prime = game.available_sa(s_prime,a_prime); newH = model.H; t = zeros(length(model.H),1); t(sa) = 1; newH(sa,:) = (1-model.param.sr_alpha)*model.H(sa,:) + model.param.sr_alpha*(t' + model.param.discount*model.H(sa_prime,:)); H = newH; function [H] = qlearn_update(s,a,r,s_prime,a_prime,model,game) sa = game.available_sa(s,a); available_sa_prime = game.available_sa(s_prime,:); available_sa_prime(available_sa_prime==0) = []; Qvals = model.Q(available_sa_prime); [maxval, max_a] = max(Qvals); [bestA] = find(Qvals==maxval); if length(bestA) > 1 a_prime_star = a_prime; else a_prime_star = bestA; end sa_prime_star = game.available_sa(s_prime,a_prime_star); oldH = model.H; H = oldH; t = zeros(length(oldH),1); t(sa) = 1; H(sa,:) = (1-model.param.sr_alpha)*oldH(sa,:) + model.param.sr_alpha*(t' + model.param.discount*oldH(sa_prime_star,:)); function model = dyna_update(model,game,nsamples) %keyboard u_sa = unique(model.sa_list(1:model.dn_tot-1)); % should have no zeros for k = 1:nsamples ind = ceil(rand*length(u_sa)); % pick an index from unique elements in sa_list sa_num = u_sa(ind); % choose a sample from the list for this sa pdf = exponential(1:100, 1/5); pdf = pdf/sum(pdf); n = find(rand < cumsum(pdf),1); if n > model.sa(sa_num).dn - 1 n = model.sa(sa_num).dn - 1; end %sample = model.sa(sa_num).samples(n,:); sample = model.sa(sa_num).samples(model.sa(sa_num).dn-n,:); s = sample(1); a = sample(2); r = sample(3); s_prime = sample(4); a_prime = sample(5); [H] = qlearn_update(s,a,r,s_prime,a_prime,model,game); model.H = H; model.Q = model.H*model.w; end function w = w_update(s,a,r,s_prime,a_prime,model,game) w = model.w; sa = game.available_sa(s,a); sa_prime = game.available_sa(s_prime,a_prime); feature_rep_s = model.H(sa,:); norm_feature_rep_s = feature_rep_s./(feature_rep_s*feature_rep_s'); w_error = r + model.param.discount*(model.H(sa_prime,:)*model.w) - (model.H(sa,:)*model.w); w = w + model.param.w_alpha*w_error*norm_feature_rep_s'; function y = exponential(x,mu) y = (1/mu).*exp(-x./mu);
github
evanrussek/Predictive-Representations-PLOS-CB-2017-master
model_SRMB.m
.m
Predictive-Representations-PLOS-CB-2017-master/agents/model_SRMB.m
4,385
utf_8
ca063c120e201d37da8b2964a3a6eaba
function model = model_SRMB() model.init = @modelinit; model.update = @modelupdate; model.eval = @modeleval; model.choose = @modelchoose; model.dyna_update = @dyna_update; model.qlearn_update = @qlearn_update; function model = modelinit(model,game, params_in) if nargin < 3 % parameters model.param.epsilon = .1; model.param.p_alpha = .1; model.param.w_alpha = .25; model.param.discount = .9; else model.param = params_in; end model.param.build = 0; % structures n_s = length(game.Rs)+1; M = eye(n_s); M(101:end,:) = 0; w = zeros(n_s,1); model.M = M; model.w = w; n_s = length(game.Rs)+1; [next_state, available_actions] = initialize_next_state(game); policy = .25*available_actions; w = zeros(n_s,1); model.next_state = next_state; model.available_actions = available_actions; model.policy = policy; model.w = w; model.s = game.current_state; model.s_prime = 0; model.a = 0; model.a_prime = 0; model.r = 0; function [Q,model] = modeleval(model,game) if model.param.build == 1 model.T = buildT(model.next_state, model.available_actions, model.policy); model.M = buildM(model.T,model.param.discount); end model.V = model.M*model.w; next_state = game.nextState(game.current_state,:); next_state(next_state == 0) = []; Q = model.V(next_state); function a = modelchoose(Qvals,game,epsilon) action_prob = zeros(length(Qvals),1); [maxval, max_a] = max(Qvals); [bestA] = find(Qvals==maxval); action_prob(bestA) = (1 - epsilon)/length(bestA); action_prob = action_prob + epsilon/length(Qvals); a = find(rand < cumsum(action_prob),1); % epsilon = .1; % % which of these actions are actually availalbe % next_state = game.nextState(game.current_state,:); % next_state(next_state == 0) = []; % available_choices = find(~(next_state == game.current_state)); % action_prob = zeros(length(Qvals),1); % [maxval, max_aa] = max(Qvals(available_choices)); % all_best_aa = find(Qvals(available_choices)==maxval); % all_best_c = available_choices(all_best_aa); % action_prob(all_best_c) = (1 - epsilon)/length(all_best_c); % action_prob(available_choices) = action_prob(available_choices) + epsilon/length(available_choices); % a = find(rand < cumsum(action_prob),1); function model = modelupdate(model,game) % update available_actions oldM = model.M; model.available_actions = aa_update(model.s_prime,model,game); % update w model.w = w_update(model.s,model.r,model.s_prime,model,oldM); % update policy model.policy = policy_update(model.s_prime,model.a_prime,model); function [w, w_error, w_change] = w_update(s,r,s_prime,model,oldM); feature_rep_s = oldM(s,:); norm_feature_rep_s = feature_rep_s./(feature_rep_s*feature_rep_s'); w_error = r + model.param.discount*model.V(s_prime) - model.V(s); w_change = w_error*oldM(s,:)'; w = model.w + model.param.w_alpha*(r + model.param.discount*model.V(s_prime) - model.V(s))*norm_feature_rep_s'; function aa = aa_update(s_prime,model,game) aa = model.available_actions; this_state_aa = aa(s_prime,:); this_state_aa(game.nextState(s_prime,:) == s_prime) = 0; aa(s_prime,:) = this_state_aa; function policy = policy_update(s_prime,a_prime,model) policy = model.policy; this_state_p = policy(s_prime,:); outcome = zeros(1,4); outcome(a_prime) = 1; policy(s_prime,:) = model.param.p_alpha*outcome + (1 - model.param.p_alpha)*this_state_p; function [next_state, available_actions] = initialize_next_state(game) % the sr gets to start with accurate knowledge of next state (e.g. basic physics of gridworld), but does not know about any walls modelgame = makegame2(game.locations,zeros(size(game.locations,1),1), []); next_state = modelgame.nextState; next_state(next_state>100) = 0; available_actions = ones(size(next_state)); % deal w/ actions in terminal states (in fact the model represents nothing about terminal states) available_actions(next_state == 0) = 0; function T = buildT(next_state, available_actions, policy) T = zeros(length(next_state), length(next_state)); % next_state for s = 1:length(next_state) % get policy in s sp = policy(s,:); sp(~available_actions(s,:)) = 0; sp = sp/sum(sp); ns = next_state(s,:); ns = ns(logical(available_actions(s,:))); if ~isempty(ns) T(s,ns) = sp(sp~=0); end end function M = buildM(T,discount) M = inv(eye(length(T)) - discount*T);
github
evanrussek/Predictive-Representations-PLOS-CB-2017-master
model_dynaQ3.m
.m
Predictive-Representations-PLOS-CB-2017-master/agents/model_dynaQ3.m
3,212
utf_8
65c8ca122cbbf62b77b3917514daccc9
function model = model_dynaQ() model.init = @modelinit; model.update = @modelupdate; model.eval = @modeleval; model.choose = @modelchoose; model.dyna_update = @dyna_update; model.q_update = @q_update; % store samples, but function model = modelinit(model,game,params_in) n_sa = length(game.sa_to_nextstate); Q = zeros(n_sa,1); if nargin < 3 model.param.epsilon = .1; model.param.alpha = .3; model.param.discount = .9; model.param.b_samples = 20; else model.param = params_in; end model.Q = Q; model.dn_tot = 1; % store samples seperately for each state for i = 1:n_sa model.sa(i).samples = zeros(10000,5); model.sa(i).dn = 1; end model.sa_list = zeros(10000,1); model.s = game.current_state; model.s_prime = 0; model.a = 0; model.a_prime = 0; model.r = 0; function model = modelupdate(model,game) model.Q = q_update(model.s,model.a,model.r,model.s_prime,model.a_prime,model,game); sa_num = game.available_sa(model.s,model.a); model.sa(sa_num).samples(model.sa(sa_num).dn,:) = [model.s, model.a, model.r, model.s_prime, model.a_prime]; model.sa(sa_num).dn = model.sa(sa_num).dn + 1; model.sa_list(model.dn_tot) = sa_num; model.dn_tot = model.dn_tot + 1; % if dyna mode model = model.dyna_update(model,game,model.param.b_samples); % run 40 samples function [Q,model] = modeleval(model,game) asa = game.available_sa(game.current_state,:); asa(asa==0) = []; Q = model.Q(asa); function a = modelchoose(Qvals,game,epsilon) action_prob = zeros(length(Qvals),1); [maxval, max_a] = max(Qvals); [bestA] = find(Qvals==maxval); action_prob(bestA) = (1 - epsilon)/length(bestA); action_prob = action_prob + epsilon/length(Qvals); a = find(rand < cumsum(action_prob),1); function Q = q_update(s,a,r,s_prime,a_prime,model,game) sa = game.available_sa(s,a); available_sa_prime = game.available_sa(s_prime,:); available_sa_prime(available_sa_prime==0) = []; Qvals = model.Q(available_sa_prime); [maxval, max_a] = max(Qvals); [bestA] = find(Qvals==maxval); if length(bestA) > 1 a_prime_star = a_prime; else a_prime_star = bestA; end sa_prime_star = game.available_sa(s_prime,a_prime_star); oldQ = model.Q; Q = oldQ; Q(sa) = (1 - model.param.alpha)*oldQ(sa) + model.param.alpha*(r + model.param.discount*oldQ(sa_prime_star)); function model = dyna_update(model,game,nsamples) u_sa = unique(model.sa_list(1:model.dn_tot-1)); % should have no zeors for k = 1:nsamples ind = ceil(rand*length(u_sa)); % pick an index from unique elements in sa_list sa_num = u_sa(ind); % choose a sample from the list for this sa %pdf = exponential(model.sa(sa_num).dn-1:-1:1,5); pdf = exponential(1:100, 1/5); pdf = pdf/sum(pdf); n = find(rand < cumsum(pdf),1); if n > model.sa(sa_num).dn - 1 n = model.sa(sa_num).dn - 1; end %sample = model.sa(sa_num).samples(n,:); sample = model.sa(sa_num).samples(model.sa(sa_num).dn-n,:); s = sample(1); a = sample(2); r = sample(3); s_prime = sample(4); a_prime = sample(5); old401 = model.Q(401); model.Q = q_update(s,a,r,s_prime,a_prime,model,game); new401 = model.Q(401); %if new401 < old401 % keyboard %end end function y = exponential(x,mu) y = (1/mu).*exp(-x./mu);
github
evanrussek/Predictive-Representations-PLOS-CB-2017-master
model_Qsr_r.m
.m
Predictive-Representations-PLOS-CB-2017-master/agents/model_Qsr_r.m
4,016
utf_8
fb07da7010d4fd773602b1dc76111181
function model = model_QSR() model.init = @modelinit; model.update = @modelupdate; model.eval = @modeleval; model.choose = @modelchoose; model.dyna_update = @dyna_update; model.qlearn_update = @qlearn_update; function model = modelinit(model,game) n_sa = length(game.sa_to_nextstate); H = eye(n_sa); H(n_sa,:) = 0; w = zeros(n_sa,1); model.param.epsilon = .1; model.param.sr_alpha = .4; model.param.w_alpha = .1; model.param.discount = .95; model.param.nsamples = 10000; model.H = H; model.w = w; model.samples = zeros(10000,5); % may need more than this model.dn = 1; model.s = game.current_state; model.s_prime = 0; model.a = 0; model.a_prime = 0; model.r = 0; function model = modelupdate(model,game) % update w %model.w = w_update(model,game); model.w = w_update(model.s,model.a,model.r,model.s_prime,model.a_prime,model,game); % update H model.H = sarsa_update(model.s,model.a,model.s_prime,model.a_prime,model,game); % update samples? -- add later if model.dn > size(model.samples,1) model.samples = [model.samples; zeros(10000,5)]; end model.samples(model.dn,:) = [model.s, model.a, model.r, model.s_prime, model.a_prime]; model.dn = model.dn + 1; model = model.dyna_update(model,game,40); function [Q,model] = modeleval(model,game) model.Q = model.H*model.w; asa = game.available_sa(game.current_state,:); asa(asa==0) = []; Q = model.Q(asa); function a = modelchoose(Qvals,game) epsilon = .1; action_prob = zeros(length(Qvals),1); [maxval, max_a] = max(Qvals); [bestA] = find(Qvals==maxval); action_prob(bestA) = (1 - epsilon)/length(bestA); action_prob = action_prob + epsilon/length(Qvals); a = find(rand < cumsum(action_prob),1); % epsilon = .1; % % which of these actions are actually availalbe % next_state = game.nextState(game.current_state,:); % next_state(next_state == 0) = []; % available_choices = find(~(next_state == game.current_state)); % action_prob = zeros(length(Qvals),1); % [maxval, max_aa] = max(Qvals(available_choices)); % all_best_aa = find(Qvals(available_choices)==maxval); % all_best_c = available_choices(all_best_aa); % action_prob(all_best_c) = (1 - epsilon)/length(all_best_c); % action_prob(available_choices) = action_prob(available_choices) + epsilon/length(available_choices); % a = find(rand < cumsum(action_prob),1); function H = sarsa_update(s,a,s_prime,a_prime,model,game) sa = game.available_sa(s,a); sa_prime = game.available_sa(s_prime,a_prime); newH = model.H; t = zeros(length(model.H),1); t(sa) = 1; newH(sa,:) = (1-model.param.sr_alpha)*model.H(sa,:) + model.param.sr_alpha*(t' + model.param.discount*model.H(sa_prime,:)); H = newH; function [H] = qlearn_update(s,a,r,s_prime,a_prime,model,game) sa = game.available_sa(s,a); available_sa_prime = game.available_sa(s_prime,:); available_sa_prime(available_sa_prime==0) = []; Qvals = model.Q(available_sa_prime); [maxval, max_a] = max(Qvals); [bestA] = find(Qvals==maxval); if length(bestA) > 1 a_prime_star = a_prime; else a_prime_star = bestA; end sa_prime_star = game.available_sa(s_prime,a_prime_star); oldH = model.H; H = oldH; t = zeros(length(oldH),1); t(sa) = 1; H(sa,:) = (1-model.param.sr_alpha)*oldH(sa,:) + model.param.sr_alpha*(t' + model.param.discount*oldH(sa_prime_star,:)); function model = dyna_update(model,game,nsamples) pdf = exponential(model.dn-1:-1:1,model.dn/5); pdf = pdf/sum(pdf); for k = 1:nsamples n = find(rand < cumsum(pdf),1); %n = ceil(model.dn*rand); sample = model.samples(n,:); s = sample(1); a = sample(2); r = sample(3); s_prime = sample(4); a_prime = sample(5); [H] = qlearn_update(s,a,r,s_prime,a_prime,model,game); model.H = H; %model.w = w; model.Q = model.H*model.w; end function w = w_update(s,a,r,s_prime,a_prime,model,game) w = model.w; sa = game.available_sa(s,a); sa_prime = game.available_sa(s_prime,a_prime); w(sa) = w(sa) + model.param.w_alpha*(r - w(sa)); function y = exponential(x,mu) y = (1/mu).*exp(-x./mu);
github
evanrussek/Predictive-Representations-PLOS-CB-2017-master
model_SRTD.m
.m
Predictive-Representations-PLOS-CB-2017-master/agents/model_SRTD.m
2,428
utf_8
5621145bdb915387e3db6b3a711936dc
function model = model_SRTD() model.init = @modelinit; model.update = @modelupdate; model.eval = @modeleval; model.choose = @modelchoose; function model = modelinit(model,game, params_in) if nargin < 3 % parameters model.param.epsilon = .1; model.param.sr_alpha = .25; model.param.w_alpha = .25; model.param.discount = .9; else model.param = params_in; end % structures n_s = length(game.Rs)+1; M = eye(n_s); M(101:end,:) = 0; w = zeros(n_s,1); model.M = M; model.w = w; % state/action index model.s = game.current_state; model.s_prime = 0; model.a = 0; model.a_prime = 0; model.r = 0; % store other things model.w_error = 0; model.w_change = zeros(size(M,1),1); model.m_error = zeros(size(M,1),1); function model = modelupdate(model,game) % update M oldM = model.M; [model.M, model.m_error] = m_update(model.s,model.s_prime,model,game); % update w [model.w, model.w_error, model.w_change] = w_update(model.s,model.r,model.s_prime,model,oldM); function a = modelchoose(Qvals,game,epsilon) %epsilon = .1; action_prob = zeros(length(Qvals),1); [maxval, max_a] = max(Qvals); [bestA] = find(Qvals==maxval); action_prob(bestA) = (1 - epsilon)/length(bestA); action_prob = action_prob + epsilon/length(Qvals); a = find(rand < cumsum(action_prob),1); if isempty(a) keyboard end function [Q,model] = modeleval(model,game) model.V = model.M*model.w; next_state = game.nextState(game.current_state,:); next_state(next_state == 0) = []; Q = model.V(next_state); if any(isnan(Q)) keyboard end function [M, m_error] = m_update(s,s_prime, model,game) oldM = model.M; M = oldM; t = zeros(length(oldM),1); t(s) = 1; m_error = model.param.discount*oldM(s_prime,:) + t' - oldM(s,:); M(s,:) = (1-model.param.sr_alpha)*oldM(s,:) + model.param.sr_alpha*(t' + model.param.discount*oldM(s_prime,:)); function [w, w_error, w_change] = w_update(s,r,s_prime,model,oldM); feature_rep_s = model.M(s,:); norm_feature_rep_s = feature_rep_s./(feature_rep_s*feature_rep_s'); w_error = r + model.param.discount*(model.M(s_prime,:)*model.w) - (model.M(s,:)*model.w); w_change = w_error*model.M(s,:)'; w = model.w + model.param.w_alpha*w_error*norm_feature_rep_s'; %w = model.w + model.param.w_alpha*(r + model.param.discount*model.V(s_prime) - model.V(s))*norm_feature_rep_s'; if any(isnan(w)) keyboard end % if any(model.w < -5) % keyboard % end
github
evanrussek/Predictive-Representations-PLOS-CB-2017-master
model_Vsr_r.m
.m
Predictive-Representations-PLOS-CB-2017-master/agents/model_Vsr_r.m
2,142
utf_8
cd3291fd57ade21cafd7ca1516478814
function model = model_Vsr() model.init = @modelinit; model.update = @modelupdate; model.eval = @modeleval; model.choose = @modelchoose; function model = modelinit(model,game,params_in) if nargin < 3 % parameters model.param.epsilon = .1; model.param.sr_alpha = .25; model.param.w_alpha = .25; model.param.discount = .9; else model.param = params_in; end % structures n_s = length(game.Rs)+1; M = eye(n_s); M(101:end,:) = 0; w = zeros(n_s,1); model.M = M; model.w = w; % state/action index model.s = game.current_state; model.s_prime = 0; model.a = 0; model.a_prime = 0; model.r = 0; % store other things model.w_error = 0; model.w_change = zeros(size(M,1),1); model.m_error = zeros(size(M,1),1); function model = modelupdate(model,game) % update M oldM = model.M; [model.M, model.m_error] = m_update(model.s,model.s_prime,model,game); % update w [model.w, model.w_error, model.w_change] = w_update(model.s,model.r,model.s_prime,model,oldM); function a = modelchoose(Qvals,game,epsilon) %epsilon = .1; action_prob = zeros(length(Qvals),1); [maxval, max_a] = max(Qvals); [bestA] = find(Qvals==maxval); action_prob(bestA) = (1 - epsilon)/length(bestA); action_prob = action_prob + epsilon/length(Qvals); a = find(rand < cumsum(action_prob),1); if isempty(a) keyboard end function [Q,model] = modeleval(model,game) model.V = model.M*model.w; next_state = game.nextState(game.current_state,:); next_state(next_state == 0) = []; Q = model.V(next_state); if any(isnan(Q)) keyboard end function [M, m_error] = m_update(s,s_prime, model,game) oldM = model.M; M = oldM; t = zeros(length(oldM),1); t(s) = 1; m_error = model.param.discount*oldM(s_prime,:) + t' - oldM(s,:); M(s,:) = (1-model.param.sr_alpha)*oldM(s,:) + model.param.sr_alpha*(t' + model.param.discount*oldM(s_prime,:)); function [w, w_error, w_change] = w_update(s,r,s_prime,model,oldM); w = model.w; w_error = r - w(s); w_change = model.param.w_alpha*(r-w(s)); w(s) = w(s) + model.param.w_alpha*(r - w(s)); if any(isnan(w)) keyboard end % if any(model.w < -5) % keyboard % end